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)161718private const val PASSWORD_HISTORY_MAX = 50192021private 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}333435363738394041424344454647@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 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 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 7677 7879808182 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 8990919293 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 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 163164165166167168 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 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 247248 249250251252253 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()254255 256 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }257258 259260261262263 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 275 val plaintext = VaultCodec.encode(payload)276 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))277 278 279 280 val next = StoredVault(281 version = slotA.version,282 salt = b64(newSalt),283 blob = blob,284 recoveryEscrow = slotA.recoveryEscrow,285 )286 if (!store.writeSlotA(next)) return false287 writeMatchingNoiseSlotB(next)288 store.stampLocalMutation()289 VaultCrypto.zero(oldKey)290 derivedKey?.let(VaultCrypto::zero)291 derivedKey = newKey292 true293 } catch (_: Exception) {294 false295 }296 }297298 299300301302 suspend fun destroyVault() = mutex.withLock {303 lock()304 store.clearVault()305 store.clearDecoySlot()306 }307308 309310 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {311 requireUnlocked()312 val stamp = VaultCrypto.monotonicEntryTimestamp()313 val now = System.currentTimeMillis()314 val entry = draft.copy(315 id = draft.id.ifBlank { UUID.randomUUID().toString() },316 createdAt = if (draft.createdAt > 0) draft.createdAt else now,317 modifiedAt = stamp,318 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,319 )320 val rollback = entryList.toMutableList()321 entryList.add(entry)322 persistOrRollback(rollback)323 entry324 }325326 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {327 requireUnlocked()328 val idx = entryList.indexOfFirst { it.id == patch.id }329 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")330 val current = entryList[idx]331 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)332 333 val passwordChanged = patch.password != null && patch.password != current.password334 335 336 337 338 339 340 val priorPassword = current.password341 val shouldCapture = passwordChanged &&342 !priorPassword.isNullOrEmpty() &&343 current.passwordHistory?.firstOrNull()?.password != priorPassword344 val nextHistory = if (shouldCapture) {345 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +346 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)347 } else {348 current.passwordHistory349 }350 val updated = patch.copy(351 createdAt = current.createdAt,352 modifiedAt = stamp,353 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,354 passwordHistory = nextHistory,355 )356 val rollback = entryList.toMutableList()357 entryList[idx] = updated358 persistOrRollback(rollback)359 updated360 }361362 363 suspend fun deleteEntry(id: String) = mutex.withLock {364 requireUnlocked()365 val idx = entryList.indexOfFirst { it.id == id }366 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")367 val current = entryList[idx]368 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)369 val rollback = entryList.toMutableList()370 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)371 persistOrRollback(rollback)372 }373374 suspend fun restoreEntry(id: String) = mutex.withLock {375 requireUnlocked()376 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }377 if (idx == -1) throw IllegalStateException("deleted entry not found")378 val current = entryList[idx]379 val rollback = entryList.toMutableList()380 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))381 persistOrRollback(rollback)382 }383384 385 suspend fun purgeEntry(id: String) = mutex.withLock {386 requireUnlocked()387 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }388 if (idx == -1) throw IllegalStateException("deleted entry not found")389 val rollback = entryList.toMutableList()390 entryList.removeAt(idx)391 persistOrRollback(rollback)392 }393394 395 suspend fun purgeDeletedEntries(): Int = mutex.withLock {396 requireUnlocked()397 val rollback = entryList.toMutableList()398 val before = entryList.size399 entryList.removeAll { it.deletedAt != null }400 val removed = before - entryList.size401 if (removed > 0) persistOrRollback(rollback)402 removed403 }404405 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }406 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }407 fun getDeletedEntries(): List<VaultEntry> =408 entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }409410 411 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {412 val active = entryList.filter { it.deletedAt == null }413 if (tagFilter == null) return active414 val needle = tagFilter.trim().lowercase()415 return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }416 }417418 419 fun getDistinctTags(): List<String> =420 entryList.asSequence()421 .filter { it.deletedAt == null }422 .flatMap { it.tags?.asSequence() ?: emptySequence() }423 .map { it.trim().lowercase() }424 .filter { it.isNotEmpty() }425 .distinct()426 .sorted()427 .toList()428429 430431432433434435 fun getDistinctFieldValues(field: String): List<String> {436 val select: (VaultEntry) -> String? = when (field) {437 "username" -> { e -> e.username }438 "email" -> { e -> e.email }439 else -> return emptyList()440 }441 return entryList.asSequence()442 .filter { it.deletedAt == null }443 .mapNotNull { select(it)?.trim() }444 .filter { it.isNotEmpty() }445 .groupingBy { it.lowercase() }446 .aggregate { _, acc: Pair<String, Int>?, value, _ ->447 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)448 }449 .values450 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })451 .map { it.first }452 }453454 fun getTombstones(): List<Tombstone> =455 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }456 fun getVaultVersion(): Long = store.version()457458 459460 461462463464465 suspend fun applyMergedRemoteEntries(466 remoteEntries: List<VaultEntry>,467 remoteTombstones: List<Tombstone>,468 ): Int = mutex.withLock {469 requireUnlocked()470 val tombMap = remoteTombstones.associate { it.id to it.deletedAt }471 var applied = 0472 val byId = entryList.associateBy { it.id }.toMutableMap()473474 for (remote in remoteEntries) {475 val tomb = tombMap[remote.id]476 if (tomb != null && tomb >= remote.modifiedAt) continue477 val local = byId[remote.id]478 if (local == null) {479 entryList.add(remote); byId[remote.id] = remote; applied++480 } else if (remote.modifiedAt > local.modifiedAt) {481 val i = entryList.indexOfFirst { it.id == local.id }482 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }483 }484 }485486 for ((id, deletedAt) in tombMap) {487 val local = byId[id] ?: continue488 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue489 if (deletedAt < local.modifiedAt) continue490 val i = entryList.indexOfFirst { it.id == id }491 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }492 }493494 if (applied > 0) {495 persistSlotA(bumpVersion = false)496 publish()497 }498 applied499 }500501 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {502 _settings.value = settings503 store.writeSettings(settings)504 }505506 507508 509 fun isRecoveryWordsSet(): Boolean = recoveryWordsSet510511 512513514515516 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {517 requireUnlocked()518 recoveryWordHash = recoveryWordsHash(words)519 recoveryWordsSet = true520 521 522 runCatching { persistSlotAWithEscrow(buildRecoveryEscrow(words)) }.getOrDefault(false)523 }524525 526 fun verifyRecoveryWords(words: List<String>): Boolean {527 val stored = recoveryWordHash ?: return false528 return stored == recoveryWordsHash(words)529 }530531 532533 534 fun hasRecoveryEscrow(): Boolean = store.loadSlotA()?.recoveryEscrow != null535536 537538539540541542543544545546547548 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {549 val slotA = store.loadSlotA() ?: return false550 val escrow = slotA.recoveryEscrow ?: return false551 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false552 val material = wordKeyMaterial(words)553 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))554 val keyBytes = recoveryKey.encoded555 return try {556 val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)557 val payload = VaultCodec.decode(plaintext)558 decoyMode = false559 entryList = payload.entries.toMutableList()560 duressConfigured = payload.duressConfigured561 recoveryWordHash = payload.recoveryWordHash562 recoveryWordsSet = payload.recoveryWordsSet563 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)564 else VaultCrypto.generateRootKey()565 _settings.value = store.loadSettings()566 VaultCrypto.zero(plaintext)567 true568 } catch (_: Exception) {569 false 570 } finally {571 VaultCrypto.zero(material)572 VaultCrypto.zero(keyBytes)573 }574 }575576 577578579580581582583584585 suspend fun resetPasswordWithRecoveryWords(586 words: List<String>,587 newPassword: String,588 ): Boolean = mutex.withLock {589 if (rootKey == null) return false 590 return try {591 val newSalt = VaultCrypto.generateSalt()592 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)593 val plaintext = VaultCodec.encode(currentPayload())594 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))595 val prior = store.loadSlotA()596 597 598 val freshEscrow = if (words.size != 12 || findInvalidWords(words).isNotEmpty()) {599 prior?.recoveryEscrow600 } else {601 val material = wordKeyMaterial(words)602 val salt = VaultCrypto.generateSalt()603 val rk = deriveRecoveryKey(material, salt)604 val kb = rk.encoded605 try {606 RecoveryEscrow(607 salt = b64(salt),608 blob = b64(VaultCrypto.encrypt(plaintext, kb, VaultCrypto.AAD_RECOVERY)),609 )610 } finally {611 VaultCrypto.zero(material); VaultCrypto.zero(kb)612 }613 }614 val next = StoredVault(615 version = prior?.version ?: 1,616 salt = b64(newSalt),617 blob = blob,618 recoveryEscrow = freshEscrow,619 )620 if (!store.writeSlotA(next)) return false621 writeMatchingNoiseSlotB(next)622 store.stampLocalMutation()623 derivedKey?.let(VaultCrypto::zero)624 derivedKey = newKey625 VaultCrypto.zero(plaintext)626 publish()627 _isUnlocked.value = true628 true629 } catch (_: Exception) {630 false631 }632 }633634 635636637638639 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {640 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null641 val material = wordKeyMaterial(words)642 val salt = VaultCrypto.generateSalt()643 val recoveryKey = deriveRecoveryKey(material, salt)644 val keyBytes = recoveryKey.encoded645 val plaintext = VaultCodec.encode(currentPayload())646 return try {647 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)648 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))649 } finally {650 VaultCrypto.zero(material)651 VaultCrypto.zero(keyBytes)652 VaultCrypto.zero(plaintext)653 }654 }655656 657658659660661662663 private fun persistSlotAWithEscrow(escrow: RecoveryEscrow?): Boolean {664 val key = derivedKey ?: throw IllegalStateException("vault_locked")665 if (decoyMode) return false666 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")667 val plaintext = VaultCodec.encode(currentPayload())668 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))669 val next = prior.copy(blob = blob, recoveryEscrow = escrow ?: prior.recoveryEscrow)670 if (!store.writeSlotA(next)) return false671 try {672 writeMatchingNoiseSlotB(next)673 } catch (e: Exception) {674 store.writeSlotA(prior)675 throw e676 }677 return true678 }679680 681682 private fun requireUnlocked() {683 if (derivedKey == null) throw IllegalStateException("vault_locked")684 }685686 687688689690691692 private fun autoPurgeExpiredTrash() {693 val days = _settings.value.trashRetentionDays ?: return694 if (days <= 0) return695 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L696 val before = entryList.size697 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }698 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }699 }700701 702 private fun currentPayload(): VaultPayload =703 VaultPayload(704 entries = entryList.toList(),705 duressConfigured = duressConfigured,706 rootKeyB64 = rootKey?.let(::b64) ?: "",707 recoveryWordHash = recoveryWordHash,708 recoveryWordsSet = recoveryWordsSet,709 )710711 712713714715716 private fun ensureRootKey(payload: VaultPayload) {717 if (payload.rootKeyB64.isNotBlank()) {718 rootKey = unb64(payload.rootKeyB64)719 return720 }721 rootKey = VaultCrypto.generateRootKey()722 runCatching { persistSlotA(bumpVersion = false) }723 }724725 private fun publish() {726 _entries.value = entryList.filter { it.deletedAt == null }727 }728729 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {730 val plaintext = VaultCodec.encode(currentPayload())731 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))732 return StoredVault(version = 1, salt = b64(salt), blob = blob)733 }734735 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {736 val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)737 val noise = ByteArray(approxBytes).also(rng::nextBytes)738 store.writeSlotB(b64(noise))739 }740741 742 private fun persistSlotA(bumpVersion: Boolean): Boolean {743 val key = derivedKey ?: throw IllegalStateException("vault_locked")744 745 if (decoyMode) {746 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")747 val plaintext = VaultCodec.encode(currentPayload())748 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))749 return store.writeDecoySlot(prior.copy(blob = blob))750 }751 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")752 val plaintext = VaultCodec.encode(currentPayload())753 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))754 val next = prior.copy(blob = blob)755 if (!store.writeSlotA(next)) return false756 757 758 try {759 writeMatchingNoiseSlotB(next)760 if (bumpVersion) store.stampLocalMutation()761 } catch (e: Exception) {762 store.writeSlotA(prior)763 throw e764 }765 return true766 }767768 769 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {770 try {771 if (!persistSlotA(bumpVersion = true)) {772 entryList = rollback773 throw IllegalStateException("storage_write_failed")774 }775 } catch (e: Exception) {776 entryList = rollback777 throw e778 }779 publish()780 }781}