VaultRepository.kt

151.6 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(): Boolean = mutex.withLock {1806        lock()1807        val cleared = store.clearVault()1808        store.clearDecoySlot()1809        cleared1810    }18111812    // ---- Entry CRUD -------------------------------------------------------18131814    /**1815     * A Peach entry id is a UUID. Import and restore carry ids from foreign1816     * files (another Peach install, a vendor export, a hand-written backup) and1817     * no reader bounds them, so an id that is not a well-formed Peach id is1818     * replaced here rather than trusted.1819     *1820     * This is the naturalisation seam, and it is deliberately the only place it1821     * happens. Minting costs at most one duplicate if the same vault is later1822     * restored on a device that still holds the old id — visible and fixable.1823     * The sync path must NOT do this: adopting a peer's id verbatim is the only1824     * thing that keeps two devices agreeing on which entry they are discussing,1825     * so reminting there would fork identity on every device, on every round.1826     */1827    private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")18281829    private fun String?.normalizedEntryId(): String =1830        if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()18311832    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1833        val epoch = requireUnlocked()1834        val stamp = VaultCrypto.monotonicEntryTimestamp()1835        val now = System.currentTimeMillis()1836        val entry = withDerivedLast4(draft.copy(1837            id = draft.id.normalizedEntryId(),1838            createdAt = if (draft.createdAt > 0) draft.createdAt else now,1839            modifiedAt = stamp,1840            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1841        ))1842        // H-03: capture rollback AND write entryList under stateLock so a1843        // concurrent lock() cannot zero the session between the read and the write.1844        val rollback = mutateCurrentSession(epoch) {1845            val r = entryList.toMutableList()1846            entryList.add(entry)1847            r1848        } ?: throw IllegalStateException("vault_locked")1849        persistOrRollback(rollback, epoch)1850        entry1851    }18521853    /**1854     * Insert many entries with a single encrypt-and-write at the end.1855     *1856     * Importing a real vault through [addEntry] was quadratic: every entry took1857     * the lock and re-encrypted and rewrote the whole vault, so an 806-entry1858     * restore did 806 full-vault writes and hung the app long enough to ANR.1859     * Rolls back to the pre-import list if the one write fails, matching1860     * [addEntry]'s all-or-nothing behaviour.1861     */1862    suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1863        val epoch = requireUnlocked()1864        if (drafts.isEmpty()) return 01865        val now = System.currentTimeMillis()1866        val ready = drafts.map { draft ->1867            val stamp = VaultCrypto.monotonicEntryTimestamp()1868            withDerivedLast4(1869                draft.copy(1870                    id = draft.id.normalizedEntryId(),1871                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1872                    modifiedAt = stamp,1873                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1874                ),1875            )1876        }1877        // H-03: capture rollback AND append every entry under stateLock.1878        val rollback = mutateCurrentSession(epoch) {1879            val r = entryList.toMutableList()1880            entryList.addAll(ready)1881            r1882        } ?: throw IllegalStateException("vault_locked")1883        persistOrRollback(rollback, epoch)1884        return drafts.size1885    }18861887    /**1888     * M-01: replace the whole active set with [newEntries] in one write.1889     *1890     * Import's REPLACE mode used to soft-delete every current entry one durable1891     * write at a time (swallowing each failure) and then batch-add, so a failed1892     * add left the old entries stranded in Trash with nothing restored. Staging1893     * the entire next list in memory and committing it through1894     * [persistOrRollback] makes the swap all-or-nothing: on any failure the1895     * pre-import list — active entries included — is restored.1896     *1897     * Existing tombstones are preserved so paired devices still see the1898     * deletions they already know about.1899     */1900    suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1901        val epoch = requireUnlocked()1902        val now = System.currentTimeMillis()1903        val ready = newEntries.map { draft ->1904            val stamp = VaultCrypto.monotonicEntryTimestamp()1905            withDerivedLast4(1906                draft.copy(1907                    id = draft.id.normalizedEntryId(),1908                    createdAt = if (draft.createdAt > 0) draft.createdAt else now,1909                    modifiedAt = stamp,1910                    passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1911                ),1912            )1913        }1914        // M-03: an incoming entry that shares an id with an existing live entry1915        // is meant to *replace* it (PEACHSCRIPT REPLACE restore). Tombstoning1916        // the old one and then appending the new one would leave the list with1917        // two entries of the same id — the tombstoned one would be returned by1918        // updateEntry's indexOfFirst and trip entry_not_found. Drop the to-be-1919        // superseded entries from the tombstone set instead.1920        val incomingIds = ready.map { it.id }.toHashSet()1921        val rollback = mutateCurrentSession(epoch) {1922            val r = entryList.toMutableList()1923            val replaced = entryList.map { entry ->1924                if (entry.deletedAt != null) return@map entry1925                if (entry.id in incomingIds) return@map null1926                val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1927                entry.copy(deletedAt = stamp, modifiedAt = stamp)1928            }.filterNotNull()1929            entryList = (replaced + ready).toMutableList()1930            r1931        } ?: throw IllegalStateException("vault_locked")1932        persistOrRollback(rollback, epoch)1933        return ready.size1934    }19351936    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1937        val epoch = requireUnlocked()1938        // H-03: read entryList, compute the patched entry, and write it under a1939        // single stateLock so a concurrent lock() cannot interleave between the1940        // lookup and the assignment (would IndexOutOfBoundsException on a shrunk1941        // list, or clobber the entry onto the wrong id after a relock).1942        val prepared = mutateCurrentSession(epoch) {1943            val idx = entryList.indexOfFirst { it.id == patch.id }1944            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1945            val current = entryList[idx]1946            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1947            // Only refresh passwordChangedAt when the password value actually changes.1948            val passwordChanged = patch.password != null && patch.password != current.password1949            // Capture the outgoing password (newest first) so the user can reveal/copy/1950            // restore it later. History is computed authoritatively from `current`, not1951            // the patch — updateEntry is a full-entry replace, so trusting patch's value1952            // would let a stale form clobber the real history. Record the age the old1953            // password carried, skip an empty prior, and skip an immediate exact dupe1954            // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.1955            val priorPassword = current.password1956            val shouldCapture = passwordChanged &&1957                !priorPassword.isNullOrEmpty() &&1958                current.passwordHistory?.firstOrNull()?.password != priorPassword1959            val nextHistory = if (shouldCapture) {1960                (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1961                    (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1962            } else {1963                current.passwordHistory1964            }1965            val updated = withDerivedLast4(patch.copy(1966                createdAt = current.createdAt,1967                modifiedAt = stamp,1968                passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1969                passwordHistory = nextHistory,1970            ))1971            val rollback = entryList.toMutableList()1972            entryList[idx] = updated1973            updated to rollback1974        } ?: throw IllegalStateException("vault_locked")1975        val (updated, rollback) = prepared1976        persistOrRollback(rollback, epoch)1977        updated1978    }19791980    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */1981    suspend fun deleteEntry(id: String) = mutex.withLock {1982        val epoch = requireUnlocked()1983        // H-03: lookup + tombstone write under stateLock so lock() cannot shrink1984        // the list out from under the indexOfFirst.1985        val rollback = mutateCurrentSession(epoch) {1986            val idx = entryList.indexOfFirst { it.id == id }1987            if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1988            val current = entryList[idx]1989            val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1990            val prior = entryList.toMutableList()1991            entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1992            prior1993        } ?: throw IllegalStateException("vault_locked")1994        persistOrRollback(rollback, epoch)1995    }19961997    suspend fun restoreEntry(id: String) = mutex.withLock {1998        val epoch = requireUnlocked()1999        val rollback = mutateCurrentSession(epoch) {2000            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }2001            if (idx == -1) throw IllegalStateException("deleted entry not found")2002            val current = entryList[idx]2003            val prior = entryList.toMutableList()2004            entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))2005            prior2006        } ?: throw IllegalStateException("vault_locked")2007        persistOrRollback(rollback, epoch)2008    }20092010    /** Permanent delete — no tombstone, no recovery. */2011    suspend fun purgeEntry(id: String) = mutex.withLock {2012        val epoch = requireUnlocked()2013        val rollback = mutateCurrentSession(epoch) {2014            val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }2015            if (idx == -1) throw IllegalStateException("deleted entry not found")2016            val prior = entryList.toMutableList()2017            entryList.removeAt(idx)2018            prior2019        } ?: throw IllegalStateException("vault_locked")2020        persistOrRollback(rollback, epoch)2021    }20222023    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */2024    suspend fun purgeDeletedEntries(): Int = mutex.withLock {2025        val epoch = requireUnlocked()2026        // H-03: read+remove under stateLock so lock() can't reorder the remove.2027        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2028        val r = mutateCurrentSession(epoch) {2029            val rollback = entryList.toMutableList()2030            val before = entryList.size2031            entryList.removeAll { it.deletedAt != null }2032            R(rollback, before - entryList.size)2033        } ?: throw IllegalStateException("vault_locked")2034        if (r.removed > 0) persistOrRollback(r.rollback, epoch)2035        r.removed2036    }20372038    /** Browser parity: number of active entries that dedupe would move to trash. */2039    suspend fun countDuplicateEntries(): Int = mutex.withLock {2040        val epoch = requireUnlocked()2041        // countDuplicateEntriesLocked reads entryList; H-03 fences the read so2042        // lock() can't race the read with state writes.2043        mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }2044            ?: throw IllegalStateException("vault_locked")2045    }20462047    /**2048     * Browser parity: soft-delete duplicate entries, keeping the most recently2049     * modified member of each group. Refuse in decoy mode so the duress vault is2050     * not reshaped into a forensically distinct state.2051     */2052    suspend fun deduplicateEntries(): Int = mutex.withLock {2053        val epoch = requireUnlocked()2054        data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2055        val ready = mutateCurrentSession(epoch) {2056            if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")2057            val active = entryList.filter { it.deletedAt == null }2058            val keepIds = mutableSetOf<String>()2059            active.groupBy { it.duplicateKey() }.values.forEach { group ->2060                keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id2061            }2062            val rollback = entryList.toMutableList()2063            var removed = 02064            entryList = entryList.map { entry ->2065                if (entry.deletedAt == null && entry.id !in keepIds) {2066                    removed++2067                    val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)2068                    entry.copy(deletedAt = stamp, modifiedAt = stamp)2069                } else {2070                    entry2071                }2072            }.toMutableList()2073            R(rollback, removed)2074        } ?: throw IllegalStateException("vault_locked")2075        if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)2076        ready.removed2077    }20782079    fun getEntries(): List<VaultEntry> = mutateState {2080        if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }2081    }2082    fun getEntry(id: String): VaultEntry? = mutateState {2083        if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }2084    }2085    fun getDeletedEntries(): List<VaultEntry> = mutateState {2086        if (!sessionDataAvailable) emptyList()2087        else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }2088    }20892090    /** Active entries, optionally narrowed to those carrying [tagFilter]. */2091    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {2092        return mutateState {2093            if (!sessionDataAvailable) return@mutateState emptyList()2094            val active = entryList.filter { it.deletedAt == null }2095            if (tagFilter == null) return@mutateState active2096            val needle = tagFilter.trim().lowercase()2097            active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }2098        }2099    }21002101    /** Sorted, de-duplicated tags across all active entries. */2102    fun getDistinctTags(): List<String> = mutateState {2103        if (!sessionDataAvailable) return@mutateState emptyList()2104        entryList.asSequence()2105            .filter { it.deletedAt == null }2106            .flatMap { it.tags?.asSequence() ?: emptySequence() }2107            .map { it.trim().lowercase() }2108            .filter { it.isNotEmpty() }2109            .distinct()2110            .sorted()2111            .toList()2112    }21132114    /**2115     * Distinct non-blank values for an identity field across active entries,2116     * most-frequently-used first. Supports "username" and "email"; unknown field2117     * names return an empty list. Values keep original casing (deduped2118     * case-insensitively) so a suggestion matches what the user typed.2119     */2120    fun getDistinctFieldValues(field: String): List<String> {2121        val select: (VaultEntry) -> String? = when (field) {2122            "username" -> { e -> e.username }2123            "email" -> { e -> e.email }2124            else -> return emptyList()2125        }2126        return mutateState {2127            if (!sessionDataAvailable) return@mutateState emptyList()2128            entryList.asSequence()2129                .filter { it.deletedAt == null }2130                .mapNotNull { select(it)?.trim() }2131                .filter { it.isNotEmpty() }2132                .groupingBy { it.lowercase() }2133                .aggregate { _, acc: Pair<String, Int>?, value, _ ->2134                    Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)2135                }2136                .values2137                .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })2138                .map { it.first }2139        }2140    }21412142    fun getTombstones(): List<Tombstone> = mutateState {2143        if (!sessionDataAvailable) emptyList()2144        else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }2145    }2146    fun getVaultVersion(): Long = store.version()2147    fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots21482149    suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {2150        val expectedEpoch = currentEpoch()2151        val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false2152        val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false2153        // H-04: snapshots now carry the duress slot too — restore preserves2154        // the at-rest triad (A/B/D), not just the A/B pair.2155        val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)2156        val priorA = store.loadSlotA()2157        val priorB = store.loadSlotB()2158        val priorD = store.loadDecoySlot()2159        // H-02: capture pre-restore state as the recovery snapshot BEFORE any2160        // slot write — the old code took this snapshot, then stranded it on2161        // every failure, polluting history with a "restore" entry that never2162        // restored anything. The history below is rolled back together with2163        // the slots if the commit fails.2164        val priorHistory = store.loadVaultHistory()2165        // P1-4 (codex): the recovery snapshot must land before we commit the2166        // slot pair, otherwise a failed restore cannot be rolled back to the2167        // pre-restore history. If the history write itself fails, refuse to2168        // proceed — the alternative is a successful restore with no undo path.2169        beforeDurableCommit()2170        if (!takeVaultSnapshot("restore", expectedEpoch)) {2171            return false2172        }2173        // H-04: legacy snapshots without vault_d, or vault_d that fails to2174        // decode, fall back to a fake duress of slot A's size — presence-2175        // indistinguishable from any other freshly-restored vault.2176        val nextD: StoredVault = restoredD ?: run {2177            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 162178            val fakeBlob = ByteArray(target).also(rng::nextBytes)2179            val fakeSalt = VaultCrypto.generateSalt()2180            StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob))2181        }2182        if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2183            withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2184            return false2185        }2186        lock()2187        true2188    }21892190    /**2191     * H-02: atomic slot-A + slot-B + version stamp for a snapshot restore.2192     * Mirrors [commitVaultRotation] but writes the snapshot's EXACT slot B2193     * (a restore preserves the duress-shaped blob from history), not a fresh2194     * noise record. Any failure rolls back so the at-rest pair never holds a2195     * restored slot A against a pre-restore slot B. Caller is responsible for2196     * restoring the pre-snapshot history on a false return.2197     *2198     * H-04: duress slot is now part of the atomic triad — restored last so2199     * a duress-write failure rolls the A/B pair back too.2200     */2201    private fun commitRestoreAtomic(2202        nextA: StoredVault,2203        nextB: String,2204        nextD: StoredVault,2205        priorA: StoredVault?,2206        priorB: String?,2207        priorD: StoredVault?,2208        expectedEpoch: Long,2209    ): Boolean {2210        return withEpochCommit(expectedEpoch) {2211            if (!store.writeSlotA(nextA)) return@withEpochCommit false2212            // P1-2 (codex): writeSlotB's boolean AND any thrown exception from it2213            // must trigger rollback; previously a throw escaped without restoring2214            // the prior slot A and history.2215            try {2216                if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2217                // H-04: duress slot is part of the restore triad. Failures here2218                // roll A+B back so the at-rest state stays consistent.2219                if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2220                store.stampLocalMutation()2221            } catch (_: Exception) {2222                reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2223                return@withEpochCommit false2224            }2225            true2226        } ?: false2227    }22282229    // ---- Sync apply (does NOT advance the version) ------------------------22302231    /**2232     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists2233     * WITHOUT bumping the version counter, so a sync round cannot cascade into2234     * another outbound sync. Returns the number of locally-applied changes.2235     */2236    suspend fun applyMergedRemoteEntries(2237        remoteEntries: List<VaultEntry>,2238        remoteTombstones: List<Tombstone>,2239        expectedEpoch: Long? = null,2240    ): Int = mutex.withLock {2241        val epoch = expectedEpoch ?: requireUnlocked()2242        if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02243        // HV-1: clamp every peer-supplied timestamp to now + MAX_CLOCK_SKEW_MS2244        // BEFORE any comparison against a local one. Without this a peer can2245        // send a far-future modifiedAt and permanently pin its version of an2246        // entry against every honest local edit. The browser clamps in the2247        // matching place (vault.ts applyMergedRemoteEntries).2248        val mergeNow = System.currentTimeMillis()2249        val clamped = remoteEntries.mapNotNull { entry ->2250            // MN-3: drop peer entries that decode cleanly but are semantically2251            // hollow (blank title, credential-less login, husk passkey) and2252            // re-cap passwordHistory before anything merges into the vault.2253            SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2254                modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2255                deletedAt = entry.deletedAt?.let {2256                    SyncLimits.clampSyncTimestamp(it, mergeNow)2257                },2258            )2259        }2260        val tombMap = remoteTombstones.associate {2261            it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2262        }2263        // H-03: build the new entryList under stateLock so a concurrent lock()2264        // cannot zero derivedKey/entryList between the byId read and the merge.2265        val applied = mutateCurrentSession(epoch) {2266            var n = 02267            val byId = entryList.associateBy { it.id }.toMutableMap()22682269            for (remote in clamped) {2270                val tomb = tombMap[remote.id]2271                if (tomb != null && tomb >= remote.modifiedAt) continue2272                val local = byId[remote.id]2273                if (local == null) {2274                    entryList.add(remote); byId[remote.id] = remote; n++2275                } else if (remote.modifiedAt > local.modifiedAt) {2276                    val i = entryList.indexOfFirst { it.id == local.id }2277                    if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2278                }2279            }22802281            for ((id, deletedAt) in tombMap) {2282                val local = byId[id] ?: continue2283                if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2284                if (deletedAt < local.modifiedAt) continue2285                val i = entryList.indexOfFirst { it.id == id }2286                if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2287            }2288            n2289        } ?: return@withLock 022902291        if (applied > 0) {2292            persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2293            mutateIfCurrentEpoch(epoch) { publish() }2294            runCatching { LockedSyncSpoolHooks.refresh(this) }2295        }2296        applied2297    }22982299    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2300        // A decoy session edits an in-memory copy only — discarded at lock.2301        // The real vault's settings record is not the duress session's to2302        // change, and letting it through weakened capture protection on a plain2303        // in-app surface (PB-26-120).2304        if (mutateState { decoyMode }) {2305            val decoyEpoch = requireUnlocked()2306            mutateCurrentSession(decoyEpoch) { _settings.value = settings }2307                ?: throw IllegalStateException("vault_locked")2308            return@withLock2309        }2310        // Require a fully live session before exposing a settings mutation.  The2311        // epoch is captured with the read so a lock/new-session boundary cannot2312        // let stale work publish into the replacement session.2313        val epoch = requireUnlocked()2314        val prior = mutateCurrentSession(epoch) {2315            val old = _settings.value2316            _settings.value = settings2317            old2318        } ?: throw IllegalStateException("vault_locked")23192320        val committed = try {2321            beforeDurableCommit()2322            // The durable write is inside the same epoch fence as the in-memory2323            // publication.  If lock() won first, this returns null and no stale2324            // settings reach storage or the public StateFlow.2325            withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2326        } catch (_: Exception) {2327            false2328        }2329        if (!committed) {2330            // A live-session storage failure rolls back the public value.  A2331            // stale epoch is already reset by lock()/the new session and must2332            // not be allowed to overwrite that safe state.2333            mutateIfCurrentEpoch(epoch) { _settings.value = prior }2334            throw IllegalStateException("settings_write_failed")2335        }2336    }23372338    // ---- Recovery words (vault metadata) ----------------------------------23392340    /** True once the user has confirmed their recovery words for this vault. */2341    fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }23422343    /**2344     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.2345     * Persisted without bumping the version — recovery metadata is local-only and2346     * is not an entry mutation paired devices should sync against.2347     */2348    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2349        val epoch = requireUnlocked()2350        // H-03: hash + escrow-related state fields set under stateLock so a2351        // concurrent lock() cannot zero them in the middle of buildRecoveryEscrow.2352        // M-04: the flags have to be live before the escrows are built — both seal2353        // currentPayload() — so capture the prior pair and put it back if the write2354        // never lands. Otherwise the session reports words set against a slot A2355        // that still holds no escrow, and the recovery screen never offers a retry.2356        val prior = mutateCurrentSession(epoch) {2357            val priorPair = recoveryWordHash to recoveryWordsSet2358            recoveryWordHash = recoveryWordsHash(words)2359            recoveryWordsSet = true2360            priorPair2361        } ?: return@withLock false2362        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow2363        // (cross-platform recovery of the sync root key) and Android's whole-payload2364        // escrow (offline forgot-password restore of entries). Both derive their key2365        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.2366        val persisted = runCatching {2367            persistSlotAWithEscrows(2368                buildRecoveryEscrow(words),2369                buildRootKeyEscrow(words),2370                expectedEpoch = epoch,2371            )2372        }.getOrDefault(false)2373        if (!persisted) {2374            mutateIfCurrentEpoch(epoch) {2375                recoveryWordHash = prior.first2376                recoveryWordsSet = prior.second2377            }2378        }2379        persisted2380    }23812382    /** Verify entered words against the stored recovery hash. */2383    fun verifyRecoveryWords(words: List<String>): Boolean {2384        return mutateState {2385            val stored = recoveryWordHash ?: return@mutateState false2386            MessageDigest.isEqual(2387                stored.toByteArray(Charsets.UTF_8),2388                recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2389            )2390        }2391    }23922393    // ---- Recovery escrow (forgot-password) --------------------------------23942395    /** True at rest if this vault has any recovery escrow the recovery flow can use. */2396    fun hasRecoveryEscrow(): Boolean =2397        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false23982399    /**2400     * One-time self-heal: if this vault has a root key but no recovery escrow2401     * on disk (adopted vaults created before the escrow fix), build and persist2402     * it now. Called on every successful unlock; no-ops once the escrow exists.2403     */2404    private fun ensureRecoveryEscrow() {2405        if (hasRecoveryEscrow()) return2406        val rk = mutateState { rootKey?.copyOf() } ?: return2407        runCatching {2408            val words = rootKeyToWords(rk)2409            val escrow = buildRecoveryEscrow(words)2410            val rkEscrow = buildRootKeyEscrow(words)2411            if (escrow != null || rkEscrow != null) {2412                val prior = store.loadSlotA() ?: return@runCatching2413                store.writeSlotA(prior.copy(2414                    recoveryEscrow = escrow ?: prior.recoveryEscrow,2415                    rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2416                ))2417                mutateState {2418                    recoveryWordHash = recoveryWordsHash(words)2419                    recoveryWordsSet = true2420                }2421            }2422        }.also { VaultCrypto.zero(rk) }2423    }24242425    /**2426     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of2427     * the master password. On success the slot-A plaintext sealed in the escrow is2428     * adopted as the live session (entries, rootKey, settings), but no Argon2id2429     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a2430     * new password and finish unlocking. Returns false when there is no escrow, the2431     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).2432     *2433     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no2434     * detached vault key to return here — slot A is wrapped under the rotating2435     * Argon2id key — so this opens the escrowed payload directly.2436     */2437    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2438        val expectedEpoch = currentEpoch()2439        val slotA = store.loadSlotA() ?: return false2440        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false24412442        // Prefer Android's whole-payload escrow: a full offline restore of entries,2443        // root key, and settings. Present for Android-created vaults.2444        val fullEscrow = slotA.recoveryEscrow2445        if (fullEscrow != null) {2446            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2447            if (material != null) {2448                var keyBytes: ByteArray? = null2449                var plaintext: ByteArray? = null2450                var candidateRoot: ByteArray? = null2451                var stateCommitStarted = false2452                try {2453                    keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2454                    plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2455                    val payload = VaultCodec.decode(plaintext)2456                    // Stage every fallible operation before touching live session2457                    // fields.  In particular, a settings/provider/decode failure2458                    // cannot leave entries, flags, or a root key resident while the2459                    // public session remains locked.2460                    val candidateSettings = store.loadSettings()2461                    candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2462                        val decodedRoot = unb64(payload.rootKeyB64)2463                        if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2464                            // Do not let a malformed authenticated payload abandon2465                            // this decoded root-key candidate before the outer2466                            // finally block owns it.2467                            VaultCrypto.zero(decodedRoot)2468                            throw IllegalArgumentException("invalid recovery root key")2469                        }2470                        decodedRoot2471                    } else {2472                        generateRecoverableRootKey()2473                    }2474                    stateCommitStarted = true2475                    val adopted = mutateIfCurrentEpoch(expectedEpoch) {2476                        clearSessionStateLocked()2477                        entryList = payload.entries.toMutableList()2478                        authenticatedDuressConfigured = payload.duressConfigured2479                        _duressConfigured.value = payload.duressConfigured2480                        recoveryWordHash = payload.recoveryWordHash2481                        recoveryWordsSet = payload.recoveryWordsSet2482                        rootKey = candidateRoot2483                        candidateRoot = null2484                        _settings.value = candidateSettings2485                        publish()2486                        // This is the authenticated recovery half-unlock boundary:2487                        // only set it after every candidate field is installed.2488                        sessionDataAvailable = true2489                        _isUnlocked.value = false2490                        true2491                    }2492                    if (adopted == true) return@withLock true2493                } catch (_: Exception) {2494                    // Wrong words, malformed payloads, provider failures, and2495                    // settings failures all fall through to the browser-compatible2496                    // root-key escrow.  If the state commit had started, invalidate2497                    // that epoch so no partial candidate survives.2498                    if (stateCommitStarted) {2499                        mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2500                    }2501                } finally {2502                    plaintext?.let(VaultCrypto::zero)2503                    VaultCrypto.zero(material)2504                    keyBytes?.let(VaultCrypto::zero)2505                    candidateRoot?.let(VaultCrypto::zero)2506                }2507            }2508        }25092510        // Browser-format vault (only the root-key escrow): recover the 32-byte root2511        // key (sync identity) and reset the password; entries return via sync. This2512        // is exactly the browser's recovery semantics (`messages.ts:312-347`).2513        val rootEscrow = slotA.rootKeyEscrow2514        if (rootEscrow != null) {2515            var candidateRoot: ByteArray? = null2516            var stateCommitStarted = false2517            try {2518                candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2519                require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2520                val candidateSettings = store.loadSettings()2521                stateCommitStarted = true2522                val adopted = mutateIfCurrentEpoch(expectedEpoch) {2523                    clearSessionStateLocked()2524                    entryList = mutableListOf()2525                    authenticatedDuressConfigured = false2526                    _duressConfigured.value = false2527                    recoveryWordHash = recoveryWordsHash(words)2528                    recoveryWordsSet = true2529                    rootKey = candidateRoot2530                    candidateRoot = null2531                    _settings.value = candidateSettings2532                    publish()2533                    sessionDataAvailable = true2534                    _isUnlocked.value = false2535                    true2536                }2537                if (adopted == true) return@withLock true2538            } catch (_: Exception) {2539                if (stateCommitStarted) {2540                    mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2541                }2542            } finally {2543                candidateRoot?.let(VaultCrypto::zero)2544            }2545        }2546        return false2547    }25482549    /**2550     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:2551     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same2552     * words, mark the session fully unlocked, and publish. Returns false if called2553     * without a prior successful recovery unlock (no in-memory root key).2554     *2555     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`2556     * into one step, since there is no detached vault key here.2557     */2558    suspend fun resetPasswordWithRecoveryWords(2559        words: List<String>,2560        newPassword: String,2561    ): Boolean = mutex.withLock {2562        val expectedEpoch = currentEpoch()2563        // H-03: read rootKey + entryList under stateLock before computing the new2564        // plaintext, then re-publish + swap the derived key under stateLock so a2565        // concurrent lock() cannot straddle the two fences.2566        if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2567        val priorA = store.loadSlotA() ?: return false2568        var newKey: ByteArray? = null2569        var plaintext: ByteArray? = null2570        return try {2571            val newSalt = VaultCrypto.generateSalt()2572            newKey = VaultCrypto.deriveKey(newPassword, newSalt)2573            plaintext = VaultCodec.encode(currentPayload())2574            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2575            // Rebuild both escrows against the recovered session so their salts rotate2576            // with the password reset; fall back to the prior escrows if rebuild fails2577            // (e.g. a checksum-invalid phrase). The same 12 words keep working.2578            val valid = words.size == 12 && findInvalidWords(words).isEmpty()2579            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2580            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2581            val next = StoredVault(2582                version = priorA.version,2583                salt = b64(newSalt),2584                blob = blob,2585                recoveryEscrow = freshRecovery,2586                rootKeyEscrow = freshRootKey,2587            )2588            // H-01: see changePassword — both rotations share the same2589            // commit-or-keep-old-key contract so a partial write can't strand2590            // the session on a key that no longer matches disk.2591            val priorB = store.loadSlotB()2592            if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2593            // H-03 (P1-2 codex): zero the old live key and install the new one2594            // inside the same stateLock critical section so a concurrent lock()2595            // can't observe the in-between.2596            if (mutateIfCurrentEpoch(expectedEpoch) {2597                derivedKey?.let(VaultCrypto::zero)2598                derivedKey = newKey; newKey = null2599                publish()2600                _isUnlocked.value = true2601            } == null) return false2602            VaultKeyRotationHooks.onRotated()2603            true2604        } catch (_: Exception) {2605            false2606        } finally {2607            newKey?.let(VaultCrypto::zero)2608            plaintext?.let(VaultCrypto::zero)2609        }2610    }26112612    /**2613     * Seal the current slot-A plaintext under a key derived from the 12 BIP392614     * recovery [words] (Android offline-restore escrow). IKM is the browser's2615     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].2616     * Returns null for a checksum-invalid phrase.2617     */2618    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2619        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2620        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2621        var keyBytes: ByteArray? = null2622        var plaintext: ByteArray? = null2623        return try {2624            val salt = VaultCrypto.generateSalt()2625            val recoveryKey = deriveRecoveryKey(material, salt)2626            keyBytes = recoveryKey.encoded2627            plaintext = VaultCodec.encode(currentPayload())2628            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2629            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2630        } finally {2631            VaultCrypto.zero(material)2632            keyBytes?.let(VaultCrypto::zero)2633            plaintext?.let(VaultCrypto::zero)2634        }2635    }26362637    /**2638     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,2639     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex2640     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,2641     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap2642     * the same root key on the browser. Returns null with no in-memory root key or2643     * a checksum-invalid phrase.2644     */2645    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2646        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2647        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2648        val rk = mutateState { rootKey?.copyOf() } ?: run {2649            VaultCrypto.zero(material)2650            return null2651        }2652        var keyBytes: ByteArray? = null2653        var plaintext: ByteArray? = null2654        return try {2655            val salt = VaultCrypto.generateSalt()2656            val recoveryKey = deriveRecoveryKey(material, salt)2657            keyBytes = recoveryKey.encoded2658            plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2659            // combined = nonce(12) || ciphertext || tag(16)2660            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2661            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2662            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2663            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2664            val ct = ctTag.copyOfRange(0, ctTag.size - 16)2665            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2666        } finally {2667            VaultCrypto.zero(rk)2668            VaultCrypto.zero(material)2669            keyBytes?.let(VaultCrypto::zero)2670            plaintext?.let(VaultCrypto::zero)2671        }2672    }26732674    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */2675    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2676        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2677        var keyBytes: ByteArray? = null2678        var pt: ByteArray? = null2679        return try {2680            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2681            keyBytes = recoveryKey.encoded2682            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2683            pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2684            hexToRootKey(String(pt, Charsets.US_ASCII))2685        } catch (_: Exception) {2686            null2687        } finally {2688            // M-05: pt is the lowercase hex of the 32-byte root key — i.e. the2689            // IKM-equivalent of the vault identity. material+keyBytes were2690            // already zeroed; pt was leaking.2691            VaultCrypto.zero(material)2692            keyBytes?.let(VaultCrypto::zero)2693            pt?.let(VaultCrypto::zero)2694        }2695    }26962697    /**2698     * Re-seal slot A from the current in-memory state under the live key, carrying2699     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs2700     * in decoy mode (recovery is never offered for the decoy) and persists without2701     * a version bump, like the recovery-words metadata write it replaces.2702     */2703    private fun persistSlotAWithEscrows(2704        recoveryEscrow: RecoveryEscrow?,2705        rootKeyEscrow: RootKeyEscrow?,2706        expectedEpoch: Long? = null,2707    ): Boolean {2708        val snapshot = snapshotForPersist(expectedEpoch)2709            ?: throw IllegalStateException("vault_locked_or_stale")2710        if (snapshot.decoy) {2711            VaultCrypto.zero(snapshot.key)2712            return false2713        }2714        try {2715            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2716            val plaintext = VaultCodec.encode(snapshot.payload)2717            val blob = try {2718                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2719            } finally {2720                // The escrow path used to drop this reference before zeroing it;2721                // keep it live through the fill on both success and failure.2722                VaultCrypto.zero(plaintext)2723            }2724            val next = prior.copy(2725                blob = blob,2726                recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2727                rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2728            )2729            beforeDurableCommit()2730            return withEpochCommit(snapshot.epoch) {2731                if (!store.writeSlotA(next)) return@withEpochCommit false2732                try {2733                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2734                    // H-04: escrow rebuild changes slot A's plaintext size, so re-pad2735                    // the duress slot too. A real decoy is left alone; a fake is2736                    // re-sized to slot A's new ciphertext length.2737                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2738                } catch (e: Exception) {2739                    store.writeSlotA(prior)2740                    throw e2741                }2742                true2743            } ?: false2744        } finally {2745            VaultCrypto.zero(snapshot.key)2746        }2747    }27482749    // ---- Internals --------------------------------------------------------27502751    private fun requireUnlocked(): Long {2752        // H-03: read derivedKey atomically with [lock]'s reset; without it,2753        // [lock] from a background lifecycle event can run between this read2754        // and the caller's first state touch.2755        stateLock.lock()2756        try {2757            if (derivedKey == null) throw IllegalStateException("vault_locked")2758            return sessionEpoch2759        } finally {2760            stateLock.unlock()2761        }2762    }27632764    /** A locked or half-adopted session must not expose secret-bearing fields. */2765    private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null27662767    private fun countDuplicateEntriesLocked(): Int {2768        val seen = mutableMapOf<String, VaultEntry>()2769        var duplicates = 02770        for (entry in entryList.filter { it.deletedAt == null }) {2771            val key = entry.duplicateKey()2772            val existing = seen[key]2773            if (existing == null) {2774                seen[key] = entry2775            } else {2776                duplicates++2777                val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2778                val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2779                if (entryStamp > existingStamp) seen[key] = entry2780            }2781        }2782        return duplicates2783    }27842785    private fun VaultEntry.duplicateKey(): String {2786        if (type == "note") return "note|${title.lowercase()}"2787        val passkeyData = passkey2788        if (passkeyData != null) {2789            return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2790        }2791        return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2792    }27932794    /**2795     * Capture the current slot pair (and metadata) into the history list.2796     * Returns true when the history write landed, false when it didn't — callers2797     * that depend on the snapshot existing (notably [restoreVaultSnapshot])2798     * must check the result and roll back if it does not.2799     */2800    private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2801        val epoch = expectedEpoch ?: currentEpoch()2802        if (mutateIfCurrentEpoch(epoch) { true } != true) return false2803        val slotA = store.loadSlotA() ?: return false2804        val vaultA = VaultCodec.encodeSlot(slotA)2805        val vaultB = store.loadSlotB() ?: slotA.blob2806        // H-04: capture the duress slot so a restore preserves the at-rest2807        // triad, not just the A/B pair. The duress slot is always present2808        // (real or fake), so loadDecoySlot() returning null is a logic error2809        // — fall through to a fake duress in that case rather than silently2810        // losing the record from the snapshot.2811        val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2812            val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162813            val fakeBlob = ByteArray(target).also(rng::nextBytes)2814            val fakeSalt = VaultCrypto.generateSalt()2815            VaultCodec.encodeSlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2816        }2817        val history = store.loadVaultHistory()2818        val latest = history.snapshots.firstOrNull()2819        if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2820        val entryCount = mutateIfCurrentEpoch(epoch) {2821            if (derivedKey != null && !decoyMode) {2822                bucketEntryCount(entryList.count { it.deletedAt == null })2823            } else {2824                null2825            }2826        } ?: return false2827        return try {2828            val snapshot = VaultSnapshot(2829                id = UUID.randomUUID().toString(),2830                savedAt = System.currentTimeMillis(),2831                reason = reason,2832                vault_a = vaultA,2833                vault_b = vaultB,2834                vault_d = vaultD,2835                entryCount = entryCount,2836            )2837            // P1-4 (codex): return the history-write boolean to callers so a2838            // false return no longer leaves the snapshot out of history while2839            // callers (notably restoreVaultSnapshot) proceed as if it succeeded.2840            withEpochCommit(epoch) {2841                store.writeVaultHistory(2842                    history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2843                )2844            } ?: false2845        } catch (_: Exception) {2846            false2847        }2848    }28492850    private fun bucketEntryCount(n: Int): Int = when {2851        n <= 0 -> 02852        n <= 10 -> 102853        n <= 25 -> 252854        n <= 50 -> 502855        n <= 100 -> 1002856        n <= 250 -> 2502857        n <= 500 -> 5002858        else -> ((n + 499) / 500) * 5002859    }28602861    /**2862     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),2863     * so it is stored explicitly and survives the sync wire format rather than being2864     * re-derived at render time. Non-card entries pass through unchanged.2865     *2866     * M-03: never overwrite a stored last4 with null. A card kept only as last42867     * (e.g. after a PeachScript import that had no PAN) must keep that value;2868     * re-deriving from an absent cardNumber would silently zero the field.2869     */2870    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2871        if (!entry.isCard()) return entry2872        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2873        val derived = if (digits.length >= 4) digits.takeLast(4) else null2874        return entry.copy(last4 = derived ?: entry.last4)2875    }28762877    /**2878     * On unlock, hard-delete trashed entries older than the retention window.2879     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"2880     * (the app's "Never" option), so nothing is purged. Persists without a2881     * version bump and without touching the publish state (caller publishes).2882     */2883    private fun autoPurgeExpiredTrash() {2884        val days = _settings.value.trashRetentionDays ?: return2885        if (days <= 0) return2886        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2887        val before = entryList.size2888        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2889        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2890    }28912892    /**2893     * Browser parity (P1): merge orphaned passkey-only entries into matching2894     * login entries that share the same registrable domain. A passkey-only2895     * entry has passkey fields (rpId + credentialId) but no password. Runs on2896     * unlock so consolidation is idempotent and cheap.2897     */2898    private fun consolidatePasskeyEntries() {2899        val passkeyOnly = entryList.filter { entry ->2900            entry.deletedAt == null &&2901                entry.isLogin() &&2902                entry.password.isNullOrBlank() &&2903                !entry.rpId.isNullOrBlank() &&2904                !entry.credentialId.isNullOrBlank()2905        }2906        if (passkeyOnly.isEmpty()) return2907        var changed = false2908        val now = System.currentTimeMillis()2909        for (pkEntry in passkeyOnly) {2910            val rpId = pkEntry.rpId ?: continue2911            val target = entryList.firstOrNull { candidate ->2912                candidate.deletedAt == null &&2913                    candidate.id != pkEntry.id &&2914                    candidate.isLogin() &&2915                    candidate.passkey == null &&2916                    candidate.credentialId.isNullOrBlank() &&2917                    !candidate.password.isNullOrBlank() &&2918                    listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2919                        .any { com.peachpasswords.shared.extractDomain(it) == rpId }2920            } ?: continue2921            val idx = entryList.indexOfFirst { it.id == target.id }2922            if (idx < 0) continue2923            entryList[idx] = target.copy(2924                rpId = pkEntry.rpId,2925                rpName = pkEntry.rpName ?: target.rpName,2926                credentialId = pkEntry.credentialId,2927                publicKeyCose = pkEntry.publicKeyCose,2928                privateKeyJwk = pkEntry.privateKeyJwk,2929                userHandle = pkEntry.userHandle,2930                userName = pkEntry.userName,2931                userDisplayName = pkEntry.userDisplayName,2932                algorithm = pkEntry.algorithm,2933                signCount = pkEntry.signCount,2934                lastUsedAt = pkEntry.lastUsedAt,2935                modifiedAt = now,2936            )2937            // Soft-delete the orphan so it lands in trash (recoverable).2938            val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2939            if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2940            changed = true2941        }2942        if (changed) runCatching { persistSlotA(bumpVersion = false) }2943    }29442945    /** The slot-A plaintext envelope for the current in-memory session. */2946    private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }29472948    private fun currentPayloadLocked(): VaultPayload =2949        VaultPayload(2950            entries = entryList.toList(),2951            duressConfigured = authenticatedDuressConfigured,2952            rootKeyB64 = rootKey?.let(::b64) ?: "",2953            recoveryWordHash = recoveryWordHash,2954            recoveryWordsSet = recoveryWordsSet,2955        )29562957    /**2958     * Adopt the payload's root key, lazily minting one for legacy payloads.2959     * A freshly-minted key is persisted WITHOUT bumping the version — adopting2960     * a root key is not a mutation paired devices should sync against.2961     */2962    private fun ensureRootKey(payload: VaultPayload) {2963        if (payload.rootKeyB64.isNotBlank()) {2964            rootKey = unb64(payload.rootKeyB64)2965            return2966        }2967        rootKey = generateRecoverableRootKey()2968        runCatching { persistSlotA(bumpVersion = false) }2969    }29702971    private fun publish() {2972        _entries.value = entryList.filter { it.deletedAt == null }2973    }29742975    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2976        var plaintext = VaultCodec.encode(currentPayload())2977        return try {2978            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2979            StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob)2980        } finally {2981            // M-05: full vault plaintext is allocated here once per createVault.2982            // Zeroing in finally keeps the transient copy off the heap after the2983            // caller either succeeds or rolls back via lock().2984            VaultCrypto.zero(plaintext)2985        }2986    }29872988    private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2989        // Size the noise so its base64 length matches slot A's blob (MN-1): with the2990        // plaintext now bucket-padded, an at-rest observer sees two equal-length slots2991        // and cannot pick the real one by size. b64(N bytes) ≈ N*4/3 chars.2992        val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2993        val noise = ByteArray(approxBytes).also(rng::nextBytes)2994        return store.writeSlotB(b64(noise))2995    }29962997    /** H-04: the ciphertext length slot A is using right now, so the duress2998     *  slot's blob can match it on disk. AES-GCM is a stream cipher — plaintext2999     *  length equals ciphertext length, so this also matches slot A's plaintext. */3000    private fun matchingCiphertextLength(slotA: StoredVault): Int =3001        (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)30023003    /** H-04: a decoy-shaped StoredVault with a random blob of [matchingCiphertextLength]3004     *  bytes. Replaces a real decoy when the user clears duress, and is the3005     *  initial duress slot when no decoy is configured — so the record's3006     *  PRESENCE on disk is independent of authenticatedDuressConfigured, and its SIZE3007     *  matches slot A's blob length. */3008    private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {3009        val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 163010        val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)3011        val fakeSalt = VaultCrypto.generateSalt()3012        return store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))3013    }30143015    /** H-04: keep the duress record present on every persist. A real decoy is3016     *  left alone (it was padded at setDuressPassphrase time, and we don't have3017     *  the duress key here to re-seal it) — VaultStore re-pads both slot3018     *  records to the longer of the two on every write, which is what keeps the3019     *  pair the same length after slot A crosses a padding bucket3020     *  (PAI-2026-004). No real decoy → a fresh fake of slot A's size. */3021    private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {3022        val isConfigured = mutateState { authenticatedDuressConfigured }3023        return if (isConfigured) true else writeFakeDuressSlot(slotA)3024    }30253026    /**3027     * H-04: convert a browser-shaped duress slot to Android StoredVault3028     * without decrypting. The browser seals slot "b" under the duress3029     * passphrase; decrypting with the main password silently drops it.3030     * Concatenates nonce‖ciphertext‖tag into Android's blob and re-encodes3031     * the salt from hex to base64.3032     */3033    private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {3034        val salt = unhex(b.salt)3035        val nonce = unhex(b.nonce)3036        val ct = unhex(b.ciphertext)3037        val tag = unhex(b.tag)3038        val blob = ByteArray(nonce.size + ct.size + tag.size).also {3039            System.arraycopy(nonce, 0, it, 0, nonce.size)3040            System.arraycopy(ct, 0, it, nonce.size, ct.size)3041            System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)3042        }3043        return StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))3044    }3045    /** Re-seal slot A from the current in-memory state under the live key. */3046    private fun persistSlotA(3047        bumpVersion: Boolean,3048        snapshotReason: String? = "local_save",3049        expectedEpoch: Long? = null,3050    ): Boolean {3051        val snapshot = snapshotForPersist(expectedEpoch)3052            ?: throw IllegalStateException("vault_locked_or_stale")3053        return try {3054            // Decoy sessions persist to the decoy slot only — never touch the real slot A.3055            if (snapshot.decoy) {3056                val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")3057                val plaintext = VaultCodec.encode(snapshot.payload)3058                val blob = try {3059                    b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_B))3060                } finally {3061                    // Keep the last reference alive until the zero, including the3062                    // successful encrypt path (M-05).3063                    VaultCrypto.zero(plaintext)3064                }3065                beforeDurableCommit()3066                return withEpochCommit(snapshot.epoch) {3067                    store.writeDecoySlot(prior.copy(version = CURRENT_ANDROID_SLOT_VERSION, blob = blob))3068                } ?: false3069            }3070            val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")3071            // H-01: captured BEFORE the noise write so a stamp failure can restore3072            // the prior slot B alongside the prior slot A. Slot B is always3073            // overwritten by writeMatchingNoiseSlotB below, so a stamp failure3074            // leaves (new A, new B, old version) on disk — partial commit.3075            val priorB = store.loadSlotB()3076            beforeDurableCommit()3077            if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false3078            val plaintext = VaultCodec.encode(snapshot.payload)3079            val blob = try {3080                b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))3081            } finally {3082                // Do not drop [plaintext] before fill(0): the serialized vault3083                // contains every entry password and is the primary M-05 target.3084                VaultCrypto.zero(plaintext)3085            }3086            val next = prior.copy(blob = blob)3087            // The epoch check and the entire A/B/D/version commit share one brief3088            // stateLock critical section. lock() either wins before this block or3089            // waits until the already-committed write is complete; it can never3090            // clear the session between the check and the durable write.3091            withEpochCommit(snapshot.epoch) {3092                if (!store.writeSlotA(next)) return@withEpochCommit false3093                try {3094                    if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")3095                    // H-04: duress slot stays present (real one untouched, fake one3096                    // re-padded to slot A's current size on every persist).3097                    if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")3098                    if (bumpVersion) store.stampLocalMutation()3099                } catch (e: Exception) {3100                    store.writeSlotA(prior)3101                    if (priorB != null) runCatching { store.writeSlotB(priorB) }3102                    throw e3103                }3104                true3105            } ?: false3106        } finally {3107            // Snapshot keys are copies, so lock() may zero the live key while this3108            // operation is still deriving/encrypting; always scrub our copy too.3109            VaultCrypto.zero(snapshot.key)3110        }3111    }31123113    /**3114     * H-01: durably commit a slot-A rotation by writing slot A, its3115     * size-matched noise slot B, and the local-mutation stamp in order. Any3116     * failure rolls the previously-committed steps back so the at-rest pair3117     * matches what was there before the call. Returns true only when every3118     * step succeeded — callers must NOT swap their session key on false.3119     */3120    private fun commitVaultRotation(3121        priorA: StoredVault,3122        priorB: String?,3123        nextA: StoredVault,3124        expectedEpoch: Long,3125    ): Boolean {3126        beforeDurableCommit()3127        return withEpochCommit(expectedEpoch) {3128            if (!store.writeSlotA(nextA)) return@withEpochCommit false3129            // P1-1 (codex): the noise write's boolean AND any thrown exception from3130            // it must trigger rollback; previously a throw from writeMatchingNoiseSlotB3131            // escaped the helper and left slot A committed.3132            try {3133                if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")3134                // H-04: a password rotation changes slot A's plaintext size (new3135                // salt → re-encrypted blob), so the duress slot must be re-padded3136                // alongside. writeCompanionDuressSlot leaves a real decoy alone3137                // and re-emits a fake of slot A's size otherwise.3138                if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")3139                store.stampLocalMutation()3140            } catch (_: Exception) {3141                rollbackRotation(priorA, priorB)3142                return@withEpochCommit false3143            }3144            true3145        } ?: false3146    }31473148    /**3149     * Best-effort undo of the writes [commitVaultRotation] may have committed.3150     * Each step runs independently — a failed rollback must not mask the3151     * original commit failure. Log is a throwing stub off-device.3152     */3153    private fun rollbackRotation(priorA: StoredVault, priorB: String?) {3154        val failures = mutableListOf<String>()3155        runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }3156            .onFailure { failures += "writeSlotA: $it" }3157        if (priorB != null) {3158            runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }3159                .onFailure { failures += "writeSlotB: $it" }3160        }3161        if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }3162    }31633164    /** Persist a local mutation, rolling the in-memory list back on failure. */3165    private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {3166        try {3167            if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {3168                mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3169                throw IllegalStateException("storage_write_failed")3170            }3171        } catch (e: Exception) {3172            mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3173            throw e3174        }3175        // A lock can win in the small interval after the durable commit and3176        // before publication. The epoch check prevents pre-lock entries from3177        // being republished into a newly locked (or newly unlocked) session.3178        mutateIfCurrentEpoch(expectedEpoch) { publish() }3179        runCatching { LockedSyncSpoolHooks.refresh(this) }3180    }3181}