VaultRepository.kt

26.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.SecureRandom9import java.util.Base6410import java.util.UUID11import javax.inject.Inject12import javax.inject.Singleton1314private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)15private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)1617/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */18private const val PASSWORD_HISTORY_MAX = 501920/** Fixed in-app key material for the decoy vault — holds nothing secret by design. */21private const val DECOY_SENTINEL = "peach_decoy_v1"2223sealed interface UnlockResult {24    data object Success : UnlockResult25    data object WrongPassword : UnlockResult26    data class Error(val reason: String) : UnlockResult27}2829sealed interface CreateVaultResult {30    data object Success : CreateVaultResult31    data class Error(val reason: String) : CreateVaultResult32}3334/**35 * In-memory vault session backed by [VaultStore]. Faithful port of the browser36 * `vault.ts` semantics that matter for correctness:37 *38 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched39 *    noise blob so a fresh install shows two similarly-shaped records.40 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a41 *    deletion always wins last-write-wins against an in-flight edit.42 *  - Local writes bump the version counter; sync-applied writes do NOT (so a43 *    sync round never cascades into another outbound sync).44 *  - add/update/delete roll back in-memory state if the disk write fails.45 *  - destroyVault never touches the Pro license (separate store).46 */47@Singleton48class VaultRepository @Inject constructor(49    private val store: VaultStorage,50) {51    private val mutex = Mutex()52    private val rng = SecureRandom()5354    private var derivedKey: ByteArray? = null55    private var rootKey: ByteArray? = null56    private var entryList: MutableList<VaultEntry> = mutableListOf()57    private var duressConfigured: Boolean = false58    private var recoveryWordHash: String? = null59    private var recoveryWordsSet: Boolean = false60    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */61    private var decoyMode: Boolean = false6263    private val _isUnlocked = MutableStateFlow(false)64    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6566    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())67    /** Active (non-deleted) entryList. */68    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()6970    private val _settings = MutableStateFlow(VaultSettings())71    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()7273    fun hasVault(): Boolean = store.hasVault()7475    // ---- Codex (printed paper backup) -------------------------------------7677    /**78     * The at-rest slot-A envelope as base64 JSON `{"a": <StoredVault>}` — the79     * Codex payload's vaultBlob. Slot B is noise, so it is omitted. Restorable80     * on any device that has the master password. Null when no vault exists.81     */82    fun codexVaultBlobBase64(): String? {83        val slotA = store.loadSlotA() ?: return null84        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""85        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))86    }8788    /**89     * Replace the local vault from a Codex blob, then unlock with [password].90     * Writes slot A (and a size-matched noise slot B) before unlocking so the91     * restored vault is at rest exactly as a freshly-created one would be.92     */93    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {94        return try {95            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)96            val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)97                ?: return UnlockResult.Error("invalid_codex_blob")98            val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")99            if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")100            writeMatchingNoiseSlotB(slotA)101            store.stampLocalMutation()102            unlockLocked(password)103        } catch (e: Exception) {104            UnlockResult.Error(e.message ?: "restore_failed")105        }106    }107108    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {109        return try {110            val salt = VaultCrypto.generateSalt()111            val key = VaultCrypto.deriveKey(password, salt)112            entryList = mutableListOf()113            duressConfigured = false114            recoveryWordHash = null115            recoveryWordsSet = false116            decoyMode = false117            rootKey = VaultCrypto.generateRootKey()118            val slotA = sealSlotA(key, salt)119            if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")120            writeMatchingNoiseSlotB(slotA)121            store.stampLocalMutation()122            store.writeSettings(_settings.value)123            derivedKey = key124            publish()125            _isUnlocked.value = true126            CreateVaultResult.Success127        } catch (e: Exception) {128            CreateVaultResult.Error(e.message ?: "create_failed")129        }130    }131132    suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }133134    /** Unlock body without acquiring the mutex — callers must already hold it. */135    private fun unlockLocked(password: String): UnlockResult {136        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")137        return try {138            val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))139            val payload = try {140                VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))141            } catch (_: Exception) {142                VaultCrypto.zero(key)143                return UnlockResult.WrongPassword144            }145            derivedKey = key146            decoyMode = false147            entryList = payload.entries.toMutableList()148            duressConfigured = payload.duressConfigured149            recoveryWordHash = payload.recoveryWordHash150            recoveryWordsSet = payload.recoveryWordsSet151            _settings.value = store.loadSettings()152            ensureRootKey(payload)153            autoPurgeExpiredTrash()154            publish()155            _isUnlocked.value = true156            UnlockResult.Success157        } catch (e: Exception) {158            UnlockResult.Error(e.message ?: "unlock_failed")159        }160    }161162    /**163     * Unlock into the decoy (duress) vault. Creates an empty decoy on first use,164     * sealed under a fixed in-app sentinel key with its own salt. The real slot A165     * is never read, so the real vault stays hidden. Edits during a decoy session166     * persist to the decoy slot only (see [persistSlotA]).167     */168    suspend fun unlockDecoy(): UnlockResult = mutex.withLock {169        return try {170            val existing = store.loadDecoySlot()171            if (existing == null) {172                val salt = VaultCrypto.generateSalt()173                val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)174                entryList = mutableListOf()175                duressConfigured = false176                recoveryWordHash = null177                recoveryWordsSet = false178                rootKey = VaultCrypto.generateRootKey()179                derivedKey = key180                decoyMode = true181                val plaintext = VaultCodec.encode(currentPayload())182                val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))183                if (!store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob)))184                    return UnlockResult.Error("storage_write_failed")185            } else {186                val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))187                val payload = VaultCodec.decode(188                    VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),189                )190                derivedKey = key191                decoyMode = true192                entryList = payload.entries.toMutableList()193                duressConfigured = false194                recoveryWordHash = payload.recoveryWordHash195                recoveryWordsSet = payload.recoveryWordsSet196                rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)197                          else VaultCrypto.generateRootKey()198            }199            _settings.value = store.loadSettings()200            publish()201            _isUnlocked.value = true202            UnlockResult.Success203        } catch (e: Exception) {204            UnlockResult.Error(e.message ?: "decoy_unlock_failed")205        }206    }207208    /** Unlock with an already-derived AES-256 key (biometric path). */209    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {210        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")211        return try {212            val payload = VaultCodec.decode(213                VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),214            )215            derivedKey = key.copyOf()216            decoyMode = false217            entryList = payload.entries.toMutableList()218            duressConfigured = payload.duressConfigured219            recoveryWordHash = payload.recoveryWordHash220            recoveryWordsSet = payload.recoveryWordsSet221            _settings.value = store.loadSettings()222            ensureRootKey(payload)223            autoPurgeExpiredTrash()224            publish()225            _isUnlocked.value = true226            UnlockResult.Success227        } catch (_: Exception) {228            UnlockResult.WrongPassword229        }230    }231232    fun lock() {233        derivedKey?.let(VaultCrypto::zero)234        rootKey?.let(VaultCrypto::zero)235        derivedKey = null236        rootKey = null237        entryList = mutableListOf()238        duressConfigured = false239        recoveryWordHash = null240        recoveryWordsSet = false241        decoyMode = false242        _entries.value = emptyList()243        _isUnlocked.value = false244    }245246    // ---- Sync identity ----------------------------------------------------247248    /**249     * The vault's stable sync master key (a copy). Caller must zero it. Backs250     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry251     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].252     */253    fun syncMasterKey(): ByteArray? = rootKey?.copyOf()254255    /** Stable per-vault id two paired devices must share to sync. Null when locked. */256    fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }257258    /**259     * A copy of the live Argon2id-derived vault key, for biometric escrow only260     * (wrapped under a hardware KeyStore key on biometric enable). Null when261     * locked. Caller must [VaultCrypto.zero] it after use.262     */263    fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()264265    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {266        val slotA = store.loadSlotA() ?: return false267        return try {268            val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))269            val payload = VaultCodec.decode(270                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),271            )272            val newSalt = VaultCrypto.generateSalt()273            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)274            // Re-seal the existing payload under the new key/salt.275            val plaintext = VaultCodec.encode(payload)276            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))277            val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)278            if (!store.writeSlotA(next)) return false279            writeMatchingNoiseSlotB(next)280            store.stampLocalMutation()281            VaultCrypto.zero(oldKey)282            derivedKey?.let(VaultCrypto::zero)283            derivedKey = newKey284            true285        } catch (_: Exception) {286            false287        }288    }289290    /**291     * Irreversible wipe. Locks the session and clears every vault key. The Pro292     * license is in a separate store and is preserved by construction.293     */294    suspend fun destroyVault() = mutex.withLock {295        lock()296        store.clearVault()297        store.clearDecoySlot()298    }299300    // ---- Entry CRUD -------------------------------------------------------301302    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {303        requireUnlocked()304        val stamp = VaultCrypto.monotonicEntryTimestamp()305        val now = System.currentTimeMillis()306        val entry = draft.copy(307            id = draft.id.ifBlank { UUID.randomUUID().toString() },308            createdAt = if (draft.createdAt > 0) draft.createdAt else now,309            modifiedAt = stamp,310            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,311        )312        val rollback = entryList.toMutableList()313        entryList.add(entry)314        persistOrRollback(rollback)315        entry316    }317318    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {319        requireUnlocked()320        val idx = entryList.indexOfFirst { it.id == patch.id }321        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")322        val current = entryList[idx]323        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)324        // Only refresh passwordChangedAt when the password value actually changes.325        val passwordChanged = patch.password != null && patch.password != current.password326        // Capture the outgoing password (newest first) so the user can reveal/copy/327        // restore it later. History is computed authoritatively from `current`, not328        // the patch — updateEntry is a full-entry replace, so trusting patch's value329        // would let a stale form clobber the real history. Record the age the old330        // password carried, skip an empty prior, and skip an immediate exact dupe331        // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.332        val priorPassword = current.password333        val shouldCapture = passwordChanged &&334            !priorPassword.isNullOrEmpty() &&335            current.passwordHistory?.firstOrNull()?.password != priorPassword336        val nextHistory = if (shouldCapture) {337            (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +338                (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)339        } else {340            current.passwordHistory341        }342        val updated = patch.copy(343            createdAt = current.createdAt,344            modifiedAt = stamp,345            passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,346            passwordHistory = nextHistory,347        )348        val rollback = entryList.toMutableList()349        entryList[idx] = updated350        persistOrRollback(rollback)351        updated352    }353354    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */355    suspend fun deleteEntry(id: String) = mutex.withLock {356        requireUnlocked()357        val idx = entryList.indexOfFirst { it.id == id }358        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")359        val current = entryList[idx]360        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)361        val rollback = entryList.toMutableList()362        entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)363        persistOrRollback(rollback)364    }365366    suspend fun restoreEntry(id: String) = mutex.withLock {367        requireUnlocked()368        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }369        if (idx == -1) throw IllegalStateException("deleted entry not found")370        val current = entryList[idx]371        val rollback = entryList.toMutableList()372        entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))373        persistOrRollback(rollback)374    }375376    /** Permanent delete — no tombstone, no recovery. */377    suspend fun purgeEntry(id: String) = mutex.withLock {378        requireUnlocked()379        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }380        if (idx == -1) throw IllegalStateException("deleted entry not found")381        val rollback = entryList.toMutableList()382        entryList.removeAt(idx)383        persistOrRollback(rollback)384    }385386    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */387    suspend fun purgeDeletedEntries(): Int = mutex.withLock {388        requireUnlocked()389        val rollback = entryList.toMutableList()390        val before = entryList.size391        entryList.removeAll { it.deletedAt != null }392        val removed = before - entryList.size393        if (removed > 0) persistOrRollback(rollback)394        removed395    }396397    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }398    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }399    fun getDeletedEntries(): List<VaultEntry> =400        entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }401402    /** Active entries, optionally narrowed to those carrying [tagFilter]. */403    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {404        val active = entryList.filter { it.deletedAt == null }405        if (tagFilter == null) return active406        val needle = tagFilter.trim().lowercase()407        return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }408    }409410    /** Sorted, de-duplicated tags across all active entries. */411    fun getDistinctTags(): List<String> =412        entryList.asSequence()413            .filter { it.deletedAt == null }414            .flatMap { it.tags?.asSequence() ?: emptySequence() }415            .map { it.trim().lowercase() }416            .filter { it.isNotEmpty() }417            .distinct()418            .sorted()419            .toList()420421    /**422     * Distinct non-blank values for an identity field across active entries,423     * most-frequently-used first. Supports "username" and "email"; unknown field424     * names return an empty list. Values keep original casing (deduped425     * case-insensitively) so a suggestion matches what the user typed.426     */427    fun getDistinctFieldValues(field: String): List<String> {428        val select: (VaultEntry) -> String? = when (field) {429            "username" -> { e -> e.username }430            "email" -> { e -> e.email }431            else -> return emptyList()432        }433        return entryList.asSequence()434            .filter { it.deletedAt == null }435            .mapNotNull { select(it)?.trim() }436            .filter { it.isNotEmpty() }437            .groupingBy { it.lowercase() }438            .aggregate { _, acc: Pair<String, Int>?, value, _ ->439                Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)440            }441            .values442            .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })443            .map { it.first }444    }445446    fun getTombstones(): List<Tombstone> =447        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }448    fun getVaultVersion(): Long = store.version()449450    // ---- Sync apply (does NOT advance the version) ------------------------451452    /**453     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists454     * WITHOUT bumping the version counter, so a sync round cannot cascade into455     * another outbound sync. Returns the number of locally-applied changes.456     */457    suspend fun applyMergedRemoteEntries(458        remoteEntries: List<VaultEntry>,459        remoteTombstones: List<Tombstone>,460    ): Int = mutex.withLock {461        requireUnlocked()462        val tombMap = remoteTombstones.associate { it.id to it.deletedAt }463        var applied = 0464        val byId = entryList.associateBy { it.id }.toMutableMap()465466        for (remote in remoteEntries) {467            val tomb = tombMap[remote.id]468            if (tomb != null && tomb >= remote.modifiedAt) continue469            val local = byId[remote.id]470            if (local == null) {471                entryList.add(remote); byId[remote.id] = remote; applied++472            } else if (remote.modifiedAt > local.modifiedAt) {473                val i = entryList.indexOfFirst { it.id == local.id }474                if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }475            }476        }477478        for ((id, deletedAt) in tombMap) {479            val local = byId[id] ?: continue480            if (local.deletedAt != null && local.deletedAt >= deletedAt) continue481            if (deletedAt < local.modifiedAt) continue482            val i = entryList.indexOfFirst { it.id == id }483            if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }484        }485486        if (applied > 0) {487            persistSlotA(bumpVersion = false)488            publish()489        }490        applied491    }492493    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {494        _settings.value = settings495        store.writeSettings(settings)496    }497498    // ---- Recovery words (vault metadata) ----------------------------------499500    /** True once the user has confirmed their recovery words for this vault. */501    fun isRecoveryWordsSet(): Boolean = recoveryWordsSet502503    /**504     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.505     * Persisted without bumping the version — recovery metadata is local-only and506     * is not an entry mutation paired devices should sync against.507     */508    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {509        requireUnlocked()510        recoveryWordHash = recoveryWordsHash(words)511        recoveryWordsSet = true512        runCatching { persistSlotA(bumpVersion = false) }.getOrDefault(false)513    }514515    /** Verify entered words against the stored recovery hash. */516    fun verifyRecoveryWords(words: List<String>): Boolean {517        val stored = recoveryWordHash ?: return false518        return stored == recoveryWordsHash(words)519    }520521    // ---- Internals --------------------------------------------------------522523    private fun requireUnlocked() {524        if (derivedKey == null) throw IllegalStateException("vault_locked")525    }526527    /**528     * On unlock, hard-delete trashed entries older than the retention window.529     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"530     * (the app's "Never" option), so nothing is purged. Persists without a531     * version bump and without touching the publish state (caller publishes).532     */533    private fun autoPurgeExpiredTrash() {534        val days = _settings.value.trashRetentionDays ?: return535        if (days <= 0) return536        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L537        val before = entryList.size538        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }539        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }540    }541542    /** The slot-A plaintext envelope for the current in-memory session. */543    private fun currentPayload(): VaultPayload =544        VaultPayload(545            entries = entryList.toList(),546            duressConfigured = duressConfigured,547            rootKeyB64 = rootKey?.let(::b64) ?: "",548            recoveryWordHash = recoveryWordHash,549            recoveryWordsSet = recoveryWordsSet,550        )551552    /**553     * Adopt the payload's root key, lazily minting one for legacy payloads.554     * A freshly-minted key is persisted WITHOUT bumping the version — adopting555     * a root key is not a mutation paired devices should sync against.556     */557    private fun ensureRootKey(payload: VaultPayload) {558        if (payload.rootKeyB64.isNotBlank()) {559            rootKey = unb64(payload.rootKeyB64)560            return561        }562        rootKey = VaultCrypto.generateRootKey()563        runCatching { persistSlotA(bumpVersion = false) }564    }565566    private fun publish() {567        _entries.value = entryList.filter { it.deletedAt == null }568    }569570    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {571        val plaintext = VaultCodec.encode(currentPayload())572        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))573        return StoredVault(version = 1, salt = b64(salt), blob = blob)574    }575576    private fun writeMatchingNoiseSlotB(slotA: StoredVault) {577        val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)578        val noise = ByteArray(approxBytes).also(rng::nextBytes)579        store.writeSlotB(b64(noise))580    }581582    /** Re-seal slot A from the current in-memory state under the live key. */583    private fun persistSlotA(bumpVersion: Boolean): Boolean {584        val key = derivedKey ?: throw IllegalStateException("vault_locked")585        // Decoy sessions persist to the decoy slot only — never touch the real slot A.586        if (decoyMode) {587            val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")588            val plaintext = VaultCodec.encode(currentPayload())589            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))590            return store.writeDecoySlot(prior.copy(blob = blob))591        }592        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")593        val plaintext = VaultCodec.encode(currentPayload())594        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))595        val next = prior.copy(blob = blob)596        if (!store.writeSlotA(next)) return false597        // Slot A committed — keep slot B size-matched, then advance the version598        // for local writes only. Restore slot A if a later step fails.599        try {600            writeMatchingNoiseSlotB(next)601            if (bumpVersion) store.stampLocalMutation()602        } catch (e: Exception) {603            store.writeSlotA(prior)604            throw e605        }606        return true607    }608609    /** Persist a local mutation, rolling the in-memory list back on failure. */610    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {611        try {612            if (!persistSlotA(bumpVersion = true)) {613                entryList = rollback614                throw IllegalStateException("storage_write_failed")615            }616        } catch (e: Exception) {617            entryList = rollback618            throw e619        }620        publish()621    }622}