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.Singleton272829private 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)333435private const val PASSWORD_HISTORY_MAX = 5036private const val VAULT_HISTORY_MAX = 537383940414243private 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}606162636465666768697071727374@Singleton75class VaultRepository @Inject constructor(76 private val store: VaultStorage,77) {78 private val mutex = Mutex()79 80 81 82 83 84 85 86 private val stateLock = ReentrantLock()87 private val rng = SecureRandom()8889 9091929394 private var sessionEpoch: Long = 0L9596 private fun nextSessionEpoch(epoch: Long): Long =97 if (epoch == Long.MAX_VALUE) 0L else epoch + 1L9899 100 @VisibleForTesting101 internal var beforeDurableCommit: () -> Unit = {}102103 104 @VisibleForTesting105 internal var afterCodexRollback: () -> Unit = {}106107 108109110111112 private inline fun <T> mutateState(block: () -> T): T {113 stateLock.lock()114 return try { block() } finally { stateLock.unlock() }115 }116117 118 private inline fun <T> withEpochCommit(epoch: Long, block: () -> T): T? {119 stateLock.lock()120 return try {121 if (sessionEpoch != epoch) null else block()122 } finally {123 stateLock.unlock()124 }125 }126127 128 @VisibleForTesting129 internal var beforeSessionEpochCommit: () -> Unit = {}130131 132133134135136 @VisibleForTesting137 internal var beforeSessionStateMutation: () -> Unit = {}138139 140141142143144145 internal fun <T> withSessionEpochCommit(epoch: Long, block: () -> T): T? {146 beforeSessionEpochCommit()147 return withEpochCommit(epoch, block)148 }149150 private fun currentEpoch(): Long = mutateState { sessionEpoch }151152 private inline fun <T> mutateIfCurrentEpoch(epoch: Long, block: () -> T): T? =153 mutateState { if (sessionEpoch == epoch) block() else null }154155 156 private inline fun <T> mutateCurrentSession(epoch: Long, block: () -> T): T? {157 beforeSessionStateMutation()158 return mutateIfCurrentEpoch(epoch, block)159 }160161 private data class PersistSnapshot(162 val epoch: Long,163 val key: ByteArray,164 val payload: VaultPayload,165 val decoy: Boolean,166 )167168 169 private fun snapshotForPersist(expectedEpoch: Long? = null): PersistSnapshot? = mutateState {170 if (expectedEpoch != null && sessionEpoch != expectedEpoch) return@mutateState null171 val liveKey = derivedKey ?: return@mutateState null172 PersistSnapshot(173 epoch = sessionEpoch,174 key = liveKey.copyOf(),175 payload = currentPayloadLocked(),176 decoy = decoyMode,177 )178 }179180 private var derivedKey: ByteArray? = null181 private var rootKey: ByteArray? = null182 private var entryList: MutableList<VaultEntry> = mutableListOf()183 private var authenticatedDuressConfigured: Boolean = false184 private var recoveryWordHash: String? = null185 private var recoveryWordsSet: Boolean = false186 187 private var sessionDataAvailable: Boolean = false188 189 private var decoyMode: Boolean = false190191 private val _isUnlocked = MutableStateFlow(false)192 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()193194 private val _duressConfigured = MutableStateFlow(false)195 196 val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()197198199 200201202203204205 private val _uiGateLocked = MutableStateFlow(false)206 val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()207208 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())209 210 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()211212 213 214 215 216 private val _settings = MutableStateFlow(store.loadSettings())217 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()218219 220 private fun clearSessionStateLocked() {221 derivedKey?.let(VaultCrypto::zero)222 rootKey?.let(VaultCrypto::zero)223 derivedKey = null224 rootKey = null225 entryList = mutableListOf()226 authenticatedDuressConfigured = false227 _duressConfigured.value = false228 recoveryWordHash = null229 recoveryWordsSet = false230 sessionDataAvailable = false231 decoyMode = false232 _settings.value = store.loadSettings()233 _entries.value = emptyList()234 _isUnlocked.value = false235 }236237 fun hasVault(): Boolean = store.hasVault()238239 240241 242243244245246247248 fun codexVaultBlobBase64(): String? {249 val slotA = store.loadSlotA() ?: return null250 251 252 val slotD = store.loadDecoySlot() ?: return null253 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""254 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))255 }256257 258259260261262 263 private fun JsonElement?.asSlotJson(): String? = when {264 this == null || this is JsonNull -> null265 this is JsonPrimitive && isString -> content266 else -> toString()267 }268269 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {270 val expectedEpoch = currentEpoch()271 var candidateKey: ByteArray? = null272 var plaintext: ByteArray? = null273 return try {274 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)275 276 277 278 279 280 281 282 val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject283 ?: return UnlockResult.Error("invalid_codex_blob")284 val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")285 286 287 288 289 290 val slotA = VaultCodec.decodeSlot(slotJson)291 ?: BrowserSlot.parse(slotJson)?.let {292 BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword293 }294 ?: return UnlockResult.Error("invalid_codex_blob")295 296 297 298 299 300 candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))301 plaintext = decryptSlotABlob(slotA, candidateKey)302 303 304 305 306 if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {307 VaultCrypto.zero(candidateKey)308 candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))309 plaintext = decryptSlotABlob(slotA, candidateKey)310 }311 if (plaintext == null) return UnlockResult.WrongPassword312 val payload = try {313 VaultCodec.decode(plaintext)314 } catch (_: Exception) {315 return UnlockResult.Error("invalid_codex_blob")316 }317318 val priorA = store.loadSlotA()319 val priorB = store.loadSlotB()320 val priorD = store.loadDecoySlot()321 322 323 324 325 326 val codexDuressJson = wrapper["b"].asSlotJson()327 val codexDuress: StoredVault? = codexDuressJson?.let {328 VaultCodec.decodeSlot(it)?.let { slot ->329 if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) null else slot330 } ?: BrowserSlot.parse(it)?.let { b ->331 browserDuressPassthrough(b)332 }333 }334335 beforeDurableCommit()336 val committed = runCatching {337 withEpochCommit(expectedEpoch) {338 try {339 340 341 342 343 if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")344 345 346 if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")347 348 349 val duressOk = if (codexDuress != null) {350 store.writeDecoySlot(codexDuress)351 } else {352 writeFakeDuressSlot(slotA)353 }354 if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")355 store.stampLocalMutation()356 true357 } catch (_: Exception) {358 reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))359 360 361 362 afterCodexRollback()363 false364 }365 } ?: false366 }.getOrDefault(false)367 if (!committed) {368 return UnlockResult.Error("storage_write_failed")369 }370371 val ownedKey = candidateKey!!372 candidateKey = null 373 adoptSlotA(ownedKey, payload, expectedEpoch)374 } catch (e: Exception) {375 376 377 378 379 380 381 if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))382 UnlockResult.Error(e.message ?: "restore_failed")383 } finally {384 plaintext?.let(VaultCrypto::zero)385 candidateKey?.let(VaultCrypto::zero)386 }387 }388389 390 private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =391 runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()392393 394395396397398399400401402 private fun rollbackRestoreLocked(403 priorA: StoredVault?,404 priorB: String?,405 priorD: StoredVault? = null,406 ): List<String> {407 val failures = mutableListOf<String>()408 if (priorA == null) {409 runCatching { store.clearVault() }.onFailure { failures += "clearVault: $it" }410 } else {411 runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }412 .onFailure { failures += "writeSlotA: $it" }413 if (priorB != null) {414 runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }415 .onFailure { failures += "writeSlotB: $it" }416 }417 418 419 420 if (priorD != null) {421 runCatching { if (!store.writeDecoySlot(priorD)) failures += "writeDecoySlot returned false" }422 .onFailure { failures += "writeDecoySlot: $it" }423 } else {424 runCatching { store.clearDecoySlot() }.onFailure { failures += "clearDecoySlot: $it" }425 }426 }427 return failures428 }429430 private fun reportRollbackFailures(failures: List<String>) {431 432 433 if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }434 }435436 437 private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {438 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)439 val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()440 val window = offset?.let {441 val from = (it - 40).coerceAtLeast(0)442 val to = (it + 40).coerceAtMost(wrapperJson.length)443 wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")444 }445 val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()446 val slot = wrapper?.get("a")447 buildString {448 append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)449 append(" | blobBase64=").append(vaultBlobBase64.length)450 append(" wrapperChars=").append(wrapperJson.length)451 append(" wrapperParses=").append(wrapper != null)452 append(" keys=").append(wrapper?.keys)453 append(" slotAKind=").append(454 when {455 slot == null -> "absent"456 slot is JsonPrimitive && slot.isString -> "string"457 slot is JsonObject -> "object:" + slot.keys458 else -> slot::class.simpleName459 },460 )461 if (window != null) append(" masked@").append(offset).append("=").append(window)462 }463 }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }464465 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {466 val expectedEpoch = currentEpoch()467 var key: ByteArray? = null468 return try {469 val salt = VaultCrypto.generateSalt()470 key = VaultCrypto.deriveKey(password, salt)471 if (mutateIfCurrentEpoch(expectedEpoch) {472 entryList = mutableListOf()473 authenticatedDuressConfigured = false474 _duressConfigured.value = false475 recoveryWordHash = null476 recoveryWordsSet = false477 decoyMode = false478 sessionDataAvailable = false479 rootKey = generateRecoverableRootKey()480 } == null) return CreateVaultResult.Error("stale_create")481 482 483 484 485 val slotA = sealSlotA(key!!, salt)486 487 488 beforeDurableCommit()489 val created = withEpochCommit(expectedEpoch) {490 if (!store.writeSlotA(slotA)) return@withEpochCommit false491 try {492 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")493 494 495 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")496 store.stampLocalMutation()497 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")498 true499 } catch (_: Exception) {500 501 502 store.clearVault()503 false504 }505 } ?: false506 if (!created) {507 lock()508 return CreateVaultResult.Error("storage_write_failed")509 }510 val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")511 if (mutateIfCurrentEpoch(expectedEpoch) {512 derivedKey = sessionKey513 key = null514 publish()515 _isUnlocked.value = true516 sessionDataAvailable = true517 sessionEpoch = nextSessionEpoch(sessionEpoch)518 } == null) return CreateVaultResult.Error("stale_create")519 CreateVaultResult.Success520 } catch (e: Exception) {521 lock()522 CreateVaultResult.Error(e.message ?: "create_failed")523 } finally {524 key?.let(VaultCrypto::zero)525 }526 }527528 suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {529 val expectedEpoch = currentEpoch()530 if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")531 if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")532 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {533 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")534 }535 var adoptedRootKey: ByteArray? = null536 var nextDerivedKey: ByteArray? = null537 var sessionRootKey: ByteArray? = null538 return try {539 adoptedRootKey = hexToRootKey(rootKeyHex)540 if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {541 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")542 }543 val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)544 val salt = VaultCrypto.generateSalt()545 nextDerivedKey = VaultCrypto.deriveKey(password, salt)546 sessionRootKey = adoptedRootKey.copyOf()547 val payload = VaultPayload(548 entries = emptyList(),549 duressConfigured = false,550 rootKeyB64 = b64(sessionRootKey),551 recoveryWordHash = null,552 recoveryWordsSet = false,553 )554 val plaintext = VaultCodec.encode(payload)555 val blob = try {556 b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))557 } finally {558 VaultCrypto.zero(plaintext)559 }560 val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)561 562 563 beforeDurableCommit()564 val created = withEpochCommit(expectedEpoch) {565 if (!store.writeSlotA(slotA)) return@withEpochCommit false566 try {567 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")568 569 570 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")571 store.stampLocalMutation()572 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")573 true574 } catch (_: Exception) {575 store.clearVault()576 false577 }578 } ?: false579 if (!created) return AdoptVaultResult.Error("storage_write_failed")580581 val adopted = mutateIfCurrentEpoch(expectedEpoch) {582 val previousDerivedKey = derivedKey583 val previousRootKey = rootKey584 derivedKey = nextDerivedKey585 rootKey = sessionRootKey586 nextDerivedKey = null587 sessionRootKey = null588 entryList = mutableListOf()589 authenticatedDuressConfigured = false590 _duressConfigured.value = false591 recoveryWordHash = null592 recoveryWordsSet = false593 decoyMode = false594 sessionDataAvailable = true595 publish()596 _isUnlocked.value = true597 sessionEpoch = nextSessionEpoch(sessionEpoch)598 previousDerivedKey to previousRootKey599 }600 if (adopted == null) return AdoptVaultResult.Error("stale_adoption")601 val (previousDerivedKey, previousRootKey) = adopted602 previousDerivedKey?.let(VaultCrypto::zero)603 previousRootKey?.let(VaultCrypto::zero)604 605 606 607 runCatching {608 val words = rootKeyToWords(rootKey!!)609 val escrow = buildRecoveryEscrow(words)610 val rkEscrow = buildRootKeyEscrow(words)611 if (escrow != null || rkEscrow != null) {612 val prior = store.loadSlotA()613 if (prior != null) {614 store.writeSlotA(prior.copy(615 recoveryEscrow = escrow ?: prior.recoveryEscrow,616 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,617 ))618 }619 mutateState {620 recoveryWordHash = recoveryWordsHash(words)621 recoveryWordsSet = true622 }623 }624 }625 AdoptVaultResult.Success(vaultId)626 } catch (e: Exception) {627 AdoptVaultResult.Error(e.message ?: "adoption_create_failed")628 } finally {629 adoptedRootKey?.let(VaultCrypto::zero)630 nextDerivedKey?.let(VaultCrypto::zero)631 sessionRootKey?.let(VaultCrypto::zero)632 }633 }634635 suspend fun unlock(password: String): UnlockResult = mutex.withLock {636 val result = unlockLocked(password, currentEpoch())637 if (result is UnlockResult.Success) ensureRecoveryEscrow()638 result639 }640641 642 private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {643 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")644 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))645 val payload = try {646 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)647 try {648 VaultCodec.decode(plaintext)649 } finally {650 VaultCrypto.zero(plaintext)651 }652 } catch (_: Exception) {653 VaultCrypto.zero(key)654 655 656 657 if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {658 val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)659 if (legacy != null) return legacy660 }661 return UnlockResult.WrongPassword662 }663 return adoptSlotA(key, payload, expectedEpoch)664 }665666 667668669670671672673674 private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {675 var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))676 var newKey: ByteArray? = null677 return try {678 val payload = try {679 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)680 try {681 VaultCodec.decode(plaintext)682 } finally {683 VaultCrypto.zero(plaintext)684 }685 } catch (_: Exception) {686 return null687 }688 689 690 val newSalt = VaultCrypto.generateSalt()691 newKey = VaultCrypto.deriveKey(password, newSalt)692 val plaintext = VaultCodec.encode(payload)693 val blob = try {694 b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))695 } finally {696 VaultCrypto.zero(plaintext)697 }698 val next = StoredVault(699 version = slotA.version,700 salt = b64(newSalt),701 blob = blob,702 recoveryEscrow = slotA.recoveryEscrow,703 rootKeyEscrow = slotA.rootKeyEscrow,704 )705 706 707 708 val priorB = store.loadSlotB()709 beforeDurableCommit()710 val healed = withEpochCommit(expectedEpoch) {711 if (!store.writeSlotA(next)) {712 false713 } else try {714 if (!writeMatchingNoiseSlotB(next)) {715 runCatching { store.writeSlotA(slotA) }716 if (priorB != null) runCatching { store.writeSlotB(priorB) }717 false718 } else if (!writeCompanionDuressSlot(next)) {719 runCatching { store.writeSlotA(slotA) }720 if (priorB != null) runCatching { store.writeSlotB(priorB) }721 false722 } else {723 store.stampLocalMutation()724 true725 }726 } catch (_: Exception) {727 runCatching { store.writeSlotA(slotA) }728 if (priorB != null) runCatching { store.writeSlotB(priorB) }729 false730 }731 } ?: false732 if (healed) {733 VaultCrypto.zero(rawKey!!)734 rawKey = null735 val result = adoptSlotA(newKey!!, payload, expectedEpoch) 736 newKey = null737 result738 } else {739 VaultCrypto.zero(newKey!!)740 newKey = null741 val result = adoptSlotA(rawKey!!, payload, expectedEpoch) 742 rawKey = null743 result744 }745 } finally {746 747 748 rawKey?.let(VaultCrypto::zero)749 newKey?.let(VaultCrypto::zero)750 }751 }752753 754 private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {755 return try {756 757 758 759 760 761 val adopted = mutateIfCurrentEpoch(expectedEpoch) {762 derivedKey = key763 decoyMode = false764 entryList = payload.entries.toMutableList()765 authenticatedDuressConfigured = payload.duressConfigured766 _duressConfigured.value = payload.duressConfigured767 recoveryWordHash = payload.recoveryWordHash768 recoveryWordsSet = payload.recoveryWordsSet769 sessionDataAvailable = true770 _settings.value = store.loadSettings()771 ensureRootKey(payload)772 autoPurgeExpiredTrash()773 consolidatePasskeyEntries()774 publish()775 _isUnlocked.value = true776 777 778 779 sessionEpoch = nextSessionEpoch(sessionEpoch)780 }781 if (adopted == null) {782 VaultCrypto.zero(key)783 UnlockResult.Error("stale_unlock")784 } else {785 UnlockResult.Success786 }787 } catch (e: Exception) {788 789 790 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }791 VaultCrypto.zero(key)792 UnlockResult.Error(e.message ?: "unlock_failed")793 }794 }795796 797798 799800801802803804 class SlotAUnlock internal constructor(805 key: ByteArray,806 internal val payload: VaultPayload,807 internal val epoch: Long,808 ) {809 private var ownedKey: ByteArray? = key810 private var consumed = false811812 813 internal fun takeKey(): ByteArray? = synchronized(this) {814 if (consumed) return@synchronized null815 consumed = true816 ownedKey.also { ownedKey = null }817 }818819 820 internal fun discard() = synchronized(this) {821 if (consumed) return@synchronized822 consumed = true823 ownedKey?.let(VaultCrypto::zero)824 ownedKey = null825 }826 }827828 829830831832833834 fun tryUnlockSlotA(password: String): SlotAUnlock? {835 val epoch = currentEpoch()836 val slotA = store.loadSlotA() ?: return null837 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))838 return try {839 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)840 val payload = try {841 VaultCodec.decode(plaintext)842 } finally {843 VaultCrypto.zero(plaintext)844 }845 SlotAUnlock(key, payload, epoch)846 } catch (_: Exception) {847 VaultCrypto.zero(key)848 null849 }850 }851852 853 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {854 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")855 adoptSlotA(key, unlock.payload, unlock.epoch)856 }857858 859 fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()860861 862863 864865866867868 class DuressUnlock internal constructor(869 key: ByteArray,870 internal val payload: VaultPayload,871 internal val epoch: Long,872 ) {873 private var ownedKey: ByteArray? = key874 private var consumed = false875876 internal fun takeKey(): ByteArray? = synchronized(this) {877 if (consumed) return@synchronized null878 consumed = true879 ownedKey.also { ownedKey = null }880 }881882 internal fun discard() = synchronized(this) {883 if (consumed) return@synchronized884 consumed = true885 ownedKey?.let(VaultCrypto::zero)886 ownedKey = null887 }888 }889890 891892893894895896897 fun tryUnlockDuress(password: String): DuressUnlock? {898 val epoch = currentEpoch()899 val slot = store.loadDecoySlot() ?: return null900 if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) return null901 var key: ByteArray? = VaultCrypto.deriveKey(password, unb64(slot.salt))902 return try {903 val plaintext = try {904 if (slot.version == CURRENT_ANDROID_SLOT_VERSION) {905 VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)906 } else {907 runCatching {908 VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_A)909 }.getOrElse {910 VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)911 }912 }913 } catch (_: Exception) {914 VaultCrypto.zero(key!!)915 key = null916 return null917 }918 val payload = try {919 VaultCodec.decode(plaintext)920 } finally {921 VaultCrypto.zero(plaintext)922 }923 if (slot.version == LEGACY_ANDROID_SLOT_VERSION) {924 val migratedKey = migrateLegacyDuressSlot(slot, password, payload, key!!, epoch)925 ?: run {926 VaultCrypto.zero(key!!)927 key = null928 return null929 }930 if (migratedKey !== key) {931 VaultCrypto.zero(key!!)932 key = migratedKey933 }934 }935 DuressUnlock(key!!, payload, epoch).also { key = null }936 } catch (_: Exception) {937 key?.let(VaultCrypto::zero)938 null939 }940 }941942 943944945946947 private fun migrateLegacyDuressSlot(948 legacy: StoredVault,949 password: String,950 payload: VaultPayload,951 legacyKey: ByteArray,952 epoch: Long,953 ): ByteArray? {954 var salt: ByteArray? = null955 var migratedKey: ByteArray? = null956 var plaintext: ByteArray? = null957 var restoredLegacy = false958 var migrated = false959 try {960 salt = VaultCrypto.generateSalt()961 migratedKey = VaultCrypto.deriveKey(password, salt)962 plaintext = VaultCodec.encode(payload)963 val next = StoredVault(964 version = CURRENT_ANDROID_SLOT_VERSION,965 salt = b64(salt),966 blob = b64(VaultCrypto.encrypt(plaintext, migratedKey, VaultCrypto.AAD_SLOT_B)),967 )968 var priorA: StoredVault? = null969 var priorB: String? = null970 withSessionEpochCommit(epoch) {971 priorA = store.loadSlotA()972 priorB = store.loadSlotB()973 if (store.loadDecoySlot() != legacy) return@withSessionEpochCommit false974 if (!store.writeDecoySlot(next)) {975 restoredLegacy = store.loadDecoySlot() == legacy976 return@withSessionEpochCommit restoredLegacy977 }978 val reopened = store.loadDecoySlot()979 val verified = reopened?.version == CURRENT_ANDROID_SLOT_VERSION && runCatching {980 val reopenedPlaintext = VaultCrypto.decrypt(unb64(reopened.blob), migratedKey!!, VaultCrypto.AAD_SLOT_B)981 try { VaultCodec.decode(reopenedPlaintext) == payload } finally { VaultCrypto.zero(reopenedPlaintext) }982 }.getOrDefault(false)983 if (verified) {984 migrated = true985 return@withSessionEpochCommit true986 }987 val restored = priorA != null && store.restoreVaultTriad(priorA!!, priorB, legacy)988 restoredLegacy = restored && store.loadSlotA() == priorA && store.loadSlotB() == priorB && store.loadDecoySlot() == legacy989 restoredLegacy990 }991 if (migrated) {992 VaultCrypto.zero(legacyKey)993 return migratedKey.also { migratedKey = null }994 }995 if (restoredLegacy) return legacyKey996 } catch (_: Exception) {997 998 999 }1000 if (!restoredLegacy) runCatching { store.loadDecoySlot() == legacy }1001 migratedKey?.let(VaultCrypto::zero)1002 return if (restoredLegacy) legacyKey else null1003 }10041005 1006 suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {1007 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")1008 if (currentEpoch() != unlock.epoch) {1009 VaultCrypto.zero(key)1010 return@withLock UnlockResult.Error("stale_unlock")1011 }1012 return try {1013 val adopted = mutateIfCurrentEpoch(unlock.epoch) {1014 derivedKey = key1015 decoyMode = true1016 entryList = unlock.payload.entries.toMutableList()1017 authenticatedDuressConfigured = false1018 _duressConfigured.value = false1019 recoveryWordHash = unlock.payload.recoveryWordHash1020 recoveryWordsSet = unlock.payload.recoveryWordsSet1021 sessionDataAvailable = true1022 rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)1023 else VaultCrypto.generateRootKey()1024 _settings.value = store.loadSettings()1025 publish()1026 _isUnlocked.value = true1027 sessionEpoch = nextSessionEpoch(sessionEpoch)1028 }1029 if (adopted == null) {1030 VaultCrypto.zero(key)1031 UnlockResult.Error("stale_unlock")1032 } else {1033 UnlockResult.Success1034 }1035 } catch (e: Exception) {1036 1037 1038 1039 1040 mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }1041 VaultCrypto.zero(key)1042 UnlockResult.Error(e.message ?: "decoy_unlock_failed")1043 }1044 }10451046 1047 fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()10481049 105010511052105310541055 suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {1056 1057 val expectedEpoch = mutateState {1058 if (derivedKey != null && !decoyMode) sessionEpoch else null1059 } ?: return false1060 1061 1062 tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }1063 var key: ByteArray? = null1064 var basePlaintext: ByteArray? = null1065 return try {1066 val salt = VaultCrypto.generateSalt()1067 key = VaultCrypto.deriveKey(duressPassphrase, salt)1068 1069 val decoyRoot = VaultCrypto.generateRootKey()1070 val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }1071 val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)1072 basePlaintext = VaultCodec.encode(decoyPayload)1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 val slotA = store.loadSlotA()1083 val targetSize = slotA?.let(::matchingCiphertextLength) ?: 01084 val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!1085 val blob = try {1086 b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_B))1087 } finally {1088 VaultCrypto.zero(plaintext)1089 1090 1091 if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)1092 basePlaintext = null1093 key?.let(VaultCrypto::zero)1094 key = null1095 }1096 beforeDurableCommit()1097 val ok = withEpochCommit(expectedEpoch) {1098 store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob))1099 } ?: false1100 if (!ok) return false1101 val marked = mutateIfCurrentEpoch(expectedEpoch) {1102 authenticatedDuressConfigured = true1103 _duressConfigured.value = true1104 true1105 } ?: false1106 if (!marked) return false1107 if (!runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1108 mutateIfCurrentEpoch(expectedEpoch) {1109 authenticatedDuressConfigured = false1110 _duressConfigured.value = false1111 }1112 runCatching { writeFakeDuressSlot(store.loadSlotA()!!) }1113 return false1114 }1115 true1116 } catch (_: Exception) {1117 false1118 } finally {1119 1120 1121 key?.let(VaultCrypto::zero)1122 basePlaintext?.let(VaultCrypto::zero)1123 }1124 }112511261127 112811291130113111321133113411351136 suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1137 if (!authenticatedDuressConfigured) return null1138 val slot = store.loadDecoySlot() ?: return null1139 return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1140 }11411142 1143114411451146114711481149 private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1150 1151 1152 1153 1154 1155 var salt: ByteArray? = null1156 var blob: ByteArray? = null1157 var nonce: ByteArray? = null1158 var ctAndTag: ByteArray? = null1159 var ct: ByteArray? = null1160 var tag: ByteArray? = null1161 try {1162 salt = unb64(slot.salt)1163 blob = unb64(slot.blob)1164 nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1165 ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1166 ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1167 tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1168 val obj = JsonObject(mapOf(1169 "version" to JsonPrimitive(1),1170 "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1171 "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1172 "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1173 "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1174 ))1175 return obj.toString()1176 } finally {1177 salt?.let(VaultCrypto::zero)1178 blob?.let(VaultCrypto::zero)1179 nonce?.let(VaultCrypto::zero)1180 ctAndTag?.let(VaultCrypto::zero)1181 ct?.let(VaultCrypto::zero)1182 tag?.let(VaultCrypto::zero)1183 }1184 }11851186 118711881189 suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1190 val b = BrowserSlot.parse(json) ?: return false1191 if (b.version != 1) return false1192 val expectedEpoch = currentEpoch()1193 var salt: ByteArray? = null1194 var nonce: ByteArray? = null1195 var ct: ByteArray? = null1196 var tag: ByteArray? = null1197 var blob: ByteArray? = null1198 try {1199 salt = unhex(b.salt)1200 nonce = unhex(b.nonce)1201 ct = unhex(b.ciphertext)1202 tag = unhex(b.tag)1203 blob = ByteArray(nonce.size + ct.size + tag.size).also {1204 System.arraycopy(nonce, 0, it, 0, nonce.size)1205 System.arraycopy(ct, 0, it, nonce.size, ct.size)1206 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1207 }1208 val stored = StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))1209 val priorA = store.loadSlotA() ?: return false1210 val priorB = store.loadSlotB()1211 val priorD = store.loadDecoySlot() ?: return false1212 beforeDurableCommit()1213 val committed = withEpochCommit(expectedEpoch) {1214 if (!store.writeDecoySlot(stored)) return@withEpochCommit false1215 authenticatedDuressConfigured = true1216 _duressConfigured.value = true1217 true1218 } ?: false1219 if (!committed) return false1220 if (runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1221 true1222 } else {1223 mutateIfCurrentEpoch(expectedEpoch) {1224 authenticatedDuressConfigured = false1225 _duressConfigured.value = false1226 }1227 withEpochCommit(expectedEpoch) { store.restoreVaultTriad(priorA, priorB, priorD) }1228 false1229 }1230 } catch (_: Exception) {1231 false1232 } finally {1233 salt?.let(VaultCrypto::zero)1234 nonce?.let(VaultCrypto::zero)1235 ct?.let(VaultCrypto::zero)1236 tag?.let(VaultCrypto::zero)1237 blob?.let(VaultCrypto::zero)1238 }1239 }12401241 1242 suspend fun clearDuress(): Boolean = mutex.withLock {1243 1244 1245 1246 1247 val expectedEpoch = currentEpoch()1248 val replaced = withEpochCommit(expectedEpoch) {1249 store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1250 ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1251 } ?: false1252 if (!replaced) return@withLock false1253 1254 1255 if (!isSessionEpochCurrent(expectedEpoch)) return false1256 val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1257 if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) {1258 authenticatedDuressConfigured = false1259 _duressConfigured.value = false1260 } != null) {1261 runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1262 }1263 true1264 }12651266 1267 private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1268 var current: Throwable? = error1269 while (current != null) {1270 if (current is javax.crypto.AEADBadTagException) return true1271 1272 1273 1274 1275 if (current is javax.crypto.BadPaddingException) return true1276 current = current.cause1277 }1278 return false1279 }12801281 1282 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1283 val expectedEpoch = currentEpoch()1284 val slotA = try {1285 store.loadSlotA()1286 } catch (_: Exception) {1287 return@withLock UnlockResult.Error("unlock_key_storage_failed")1288 } ?: return@withLock UnlockResult.Error("no_vault")1289 1290 1291 1292 1293 var stagedKey: ByteArray? = key.copyOf()1294 return try {1295 val encrypted = try {1296 unb64(slotA.blob)1297 } catch (_: Exception) {1298 return@withLock UnlockResult.Error("invalid_vault_blob")1299 }1300 1301 1302 1303 1304 if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1305 return@withLock UnlockResult.Error("invalid_vault_blob")1306 }1307 val plaintext = try {1308 VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1309 } catch (e: Exception) {1310 if (isGcmAuthenticationFailure(e)) {1311 return@withLock UnlockResult.WrongPassword1312 }1313 return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1314 }1315 val payload = try {1316 VaultCodec.decode(plaintext)1317 } catch (_: Exception) {1318 return@withLock UnlockResult.Error("invalid_vault_payload")1319 } finally {1320 VaultCrypto.zero(plaintext)1321 }1322 val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1323 val result = adoptSlotA(candidate, payload, expectedEpoch)1324 if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1325 result1326 } finally {1327 stagedKey?.let(VaultCrypto::zero)1328 }1329 }13301331 fun lock() {1332 1333 1334 1335 1336 if (mutex.tryLock()) {1337 try {1338 runCatching { LockedSyncSpoolHooks.refresh(this) }1339 } finally {1340 mutex.unlock()1341 }1342 }1343 1344 1345 1346 1347 1348 1349 stateLock.lock()1350 try {1351 sessionEpoch = nextSessionEpoch(sessionEpoch)1352 clearSessionStateLocked()1353 _uiGateLocked.value = false1354 } finally {1355 stateLock.unlock()1356 }1357 }13581359 1360136113621363136413651366 fun lockUiGate() {1367 if (_isUnlocked.value) _uiGateLocked.value = true1368 }13691370 1371 fun clearUiGate() {1372 _uiGateLocked.value = false1373 }13741375 @Volatile private var suppressNextBackgroundLockUntil: Long = 0L13761377 1378 1379 @VisibleForTesting1380 internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }13811382 138313841385138613871388138913901391139213931394 fun expectTransientBackground() {1395 suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1396 }13971398 13991400140114021403 fun consumeTransientBackgroundSuppression(): Boolean {1404 val until = suppressNextBackgroundLockUntil1405 val active = until != 0L && nowMs() < until1406 suppressNextBackgroundLockUntil = 0L1407 return active1408 }14091410 14111412 14131414141514161417 14181419142014211422142314241425142614271428 1429 1430 1431 1432 1433 internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)14341435 internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1436 if (decoyMode || !_isUnlocked.value) null1437 else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1438 }14391440 internal fun isSessionEpochCurrent(epoch: Long): Boolean =1441 mutateState { sessionEpoch == epoch }14421443 internal fun unlockedSessionEpoch(): Long? = mutateState {1444 if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1445 }14461447 fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key14481449 145014511452145314541455145614571458 fun sessionRootKey(): ByteArray? = mutateState {1459 if (!sessionDataAvailable) null else rootKey?.copyOf()1460 }14611462 14631464 fun syncVaultId(): String? = mutateState {1465 if (decoyMode || !_isUnlocked.value) null1466 else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1467 }14681469 14701471147214731474 suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1475 val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1476 ?: return false1477 installRootKey(generateRecoverableRootKey(), expectedEpoch)1478 }14791480 14811482148314841485148614871488148914901491149214931494149514961497 suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1498 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1499 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1500 }1501 val expectedEpoch = mutateState {1502 when {1503 derivedKey == null -> null1504 decoyMode -> Long.MIN_VALUE1505 else -> sessionEpoch1506 }1507 }1508 if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1509 if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1510 if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")15111512 val incoming = hexToRootKey(rootKeyHex)1513 if (incoming.size != VaultCrypto.KEY_SIZE) {1514 VaultCrypto.zero(incoming)1515 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1516 }1517 1518 1519 1520 val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1521 if (!roundTrips) {1522 VaultCrypto.zero(incoming)1523 return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1524 }15251526 val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1527 return if (installRootKey(incoming, expectedEpoch)) {1528 AdoptVaultResult.Success(vaultId)1529 } else {1530 AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1531 }1532 }15331534 15351536153715381539 fun previewRecoveryWords(rootKeyHex: String): List<String>? {1540 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1541 val bytes = hexToRootKey(rootKeyHex)1542 return try {1543 val words = rootKeyToWords(bytes)1544 if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1545 } catch (_: Exception) {1546 null1547 } finally {1548 VaultCrypto.zero(bytes)1549 }1550 }15511552 15531554155515561557 private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1558 1559 1560 1561 1562 1563 1564 data class Snapshot(1565 val key: ByteArray,1566 val priorRootKey: ByteArray,1567 val priorRecoveryHash: String?,1568 val priorRecoverySet: Boolean,1569 )1570 val snap = mutateIfCurrentEpoch(expectedEpoch) {1571 val k = derivedKey ?: return@mutateIfCurrentEpoch null1572 if (decoyMode) return@mutateIfCurrentEpoch null1573 val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1574 Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1575 } ?: run {1576 VaultCrypto.zero(nextRootKey)1577 return false1578 }1579 val priorSlot = store.loadSlotA() ?: run {1580 VaultCrypto.zero(snap.key)1581 VaultCrypto.zero(snap.priorRootKey)1582 VaultCrypto.zero(nextRootKey)1583 return false1584 }1585 val nextWords = rootKeyToWords(nextRootKey)15861587 return try {1588 beforeDurableCommit()1589 if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1590 if (mutateIfCurrentEpoch(expectedEpoch) {1591 rootKey = nextRootKey1592 recoveryWordHash = recoveryWordsHash(nextWords)1593 recoveryWordsSet = false1594 } == null) throw IllegalStateException("stale_root_rotation")15951596 val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1597 ?: throw IllegalStateException("recovery_escrow_failed")1598 val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1599 ?: throw IllegalStateException("root_escrow_failed")1600 val plaintext = VaultCodec.encode(currentPayload())1601 val blob = try {1602 b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1603 } finally {1604 VaultCrypto.zero(plaintext)1605 }1606 val nextSlot = priorSlot.copy(1607 blob = blob,1608 recoveryEscrow = nextRecoveryEscrow,1609 rootKeyEscrow = nextRootKeyEscrow,1610 )1611 val committed = withEpochCommit(expectedEpoch) {1612 if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1613 try {1614 if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1615 1616 1617 if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1618 store.stampLocalMutation()1619 } catch (_: Exception) {1620 store.writeSlotA(priorSlot)1621 return@withEpochCommit false1622 }1623 true1624 } ?: false1625 if (!committed) throw IllegalStateException("storage_write_failed")1626 mutateIfCurrentEpoch(expectedEpoch) { publish() }1627 true1628 } catch (_: Exception) {1629 val restored = mutateIfCurrentEpoch(expectedEpoch) {1630 rootKey?.let(VaultCrypto::zero)1631 rootKey = snap.priorRootKey.copyOf()1632 recoveryWordHash = snap.priorRecoveryHash1633 recoveryWordsSet = snap.priorRecoverySet1634 }1635 if (restored != null) {1636 withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1637 }1638 false1639 } finally {1640 VaultCrypto.zero(snap.key)1641 VaultCrypto.zero(snap.priorRootKey)1642 1643 1644 1645 val stillOwnedBySession = mutateState {1646 sessionEpoch == expectedEpoch && rootKey === nextRootKey1647 }1648 if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1649 }1650 }16511652 16531654165516561657 fun currentVaultKey(): ByteArray? = mutateState {1658 if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1659 }16601661 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1662 val expectedEpoch = currentEpoch()1663 val slotA = store.loadSlotA() ?: return false1664 var oldKey: ByteArray? = null1665 var newKey: ByteArray? = null1666 var plaintext: ByteArray? = null1667 return try {1668 oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1669 1670 1671 1672 1673 val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1674 val payload = try {1675 VaultCodec.decode(decrypted)1676 } finally {1677 VaultCrypto.zero(decrypted)1678 }1679 val newSalt = VaultCrypto.generateSalt()1680 newKey = VaultCrypto.deriveKey(newPassword, newSalt)1681 1682 plaintext = VaultCodec.encode(payload)1683 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1684 1685 1686 1687 1688 1689 1690 1691 val next = StoredVault(1692 version = slotA.version,1693 salt = b64(newSalt),1694 blob = blob,1695 recoveryEscrow = slotA.recoveryEscrow,1696 rootKeyEscrow = slotA.rootKeyEscrow,1697 )1698 1699 1700 1701 1702 val priorB = store.loadSlotB()1703 if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1704 1705 1706 1707 if (mutateIfCurrentEpoch(expectedEpoch) {1708 oldKey?.let(VaultCrypto::zero); oldKey = null1709 derivedKey?.let(VaultCrypto::zero)1710 derivedKey = newKey; newKey = null1711 } == null) return false1712 true1713 } catch (_: Exception) {1714 false1715 } finally {1716 oldKey?.let(VaultCrypto::zero)1717 newKey?.let(VaultCrypto::zero)1718 plaintext?.let(VaultCrypto::zero)1719 }1720 }17211722 1723172417251726 suspend fun destroyVault() = mutex.withLock {1727 lock()1728 store.clearVault()1729 store.clearDecoySlot()1730 }17311732 17331734 1735173617371738173917401741174217431744174517461747 private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")17481749 private fun String?.normalizedEntryId(): String =1750 if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()17511752 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1753 val epoch = requireUnlocked()1754 val stamp = VaultCrypto.monotonicEntryTimestamp()1755 val now = System.currentTimeMillis()1756 val entry = withDerivedLast4(draft.copy(1757 id = draft.id.normalizedEntryId(),1758 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1759 modifiedAt = stamp,1760 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1761 ))1762 1763 1764 val rollback = mutateCurrentSession(epoch) {1765 val r = entryList.toMutableList()1766 entryList.add(entry)1767 r1768 } ?: throw IllegalStateException("vault_locked")1769 persistOrRollback(rollback, epoch)1770 entry1771 }17721773 177417751776177717781779178017811782 suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1783 val epoch = requireUnlocked()1784 if (drafts.isEmpty()) return 01785 val now = System.currentTimeMillis()1786 val ready = drafts.map { draft ->1787 val stamp = VaultCrypto.monotonicEntryTimestamp()1788 withDerivedLast4(1789 draft.copy(1790 id = draft.id.normalizedEntryId(),1791 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1792 modifiedAt = stamp,1793 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1794 ),1795 )1796 }1797 1798 val rollback = mutateCurrentSession(epoch) {1799 val r = entryList.toMutableList()1800 entryList.addAll(ready)1801 r1802 } ?: throw IllegalStateException("vault_locked")1803 persistOrRollback(rollback, epoch)1804 return drafts.size1805 }18061807 1808180918101811181218131814181518161817181818191820 suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1821 val epoch = requireUnlocked()1822 val now = System.currentTimeMillis()1823 val ready = newEntries.map { draft ->1824 val stamp = VaultCrypto.monotonicEntryTimestamp()1825 withDerivedLast4(1826 draft.copy(1827 id = draft.id.normalizedEntryId(),1828 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1829 modifiedAt = stamp,1830 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1831 ),1832 )1833 }1834 1835 1836 1837 1838 1839 1840 val incomingIds = ready.map { it.id }.toHashSet()1841 val rollback = mutateCurrentSession(epoch) {1842 val r = entryList.toMutableList()1843 val replaced = entryList.map { entry ->1844 if (entry.deletedAt != null) return@map entry1845 if (entry.id in incomingIds) return@map null1846 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1847 entry.copy(deletedAt = stamp, modifiedAt = stamp)1848 }.filterNotNull()1849 entryList = (replaced + ready).toMutableList()1850 r1851 } ?: throw IllegalStateException("vault_locked")1852 persistOrRollback(rollback, epoch)1853 return ready.size1854 }18551856 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1857 val epoch = requireUnlocked()1858 1859 1860 1861 1862 val prepared = mutateCurrentSession(epoch) {1863 val idx = entryList.indexOfFirst { it.id == patch.id }1864 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1865 val current = entryList[idx]1866 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1867 1868 val passwordChanged = patch.password != null && patch.password != current.password1869 1870 1871 1872 1873 1874 1875 val priorPassword = current.password1876 val shouldCapture = passwordChanged &&1877 !priorPassword.isNullOrEmpty() &&1878 current.passwordHistory?.firstOrNull()?.password != priorPassword1879 val nextHistory = if (shouldCapture) {1880 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1881 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1882 } else {1883 current.passwordHistory1884 }1885 val updated = withDerivedLast4(patch.copy(1886 createdAt = current.createdAt,1887 modifiedAt = stamp,1888 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1889 passwordHistory = nextHistory,1890 ))1891 val rollback = entryList.toMutableList()1892 entryList[idx] = updated1893 updated to rollback1894 } ?: throw IllegalStateException("vault_locked")1895 val (updated, rollback) = prepared1896 persistOrRollback(rollback, epoch)1897 updated1898 }18991900 1901 suspend fun deleteEntry(id: String) = mutex.withLock {1902 val epoch = requireUnlocked()1903 1904 1905 val rollback = mutateCurrentSession(epoch) {1906 val idx = entryList.indexOfFirst { it.id == id }1907 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1908 val current = entryList[idx]1909 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1910 val prior = entryList.toMutableList()1911 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1912 prior1913 } ?: throw IllegalStateException("vault_locked")1914 persistOrRollback(rollback, epoch)1915 }19161917 suspend fun restoreEntry(id: String) = mutex.withLock {1918 val epoch = requireUnlocked()1919 val rollback = mutateCurrentSession(epoch) {1920 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1921 if (idx == -1) throw IllegalStateException("deleted entry not found")1922 val current = entryList[idx]1923 val prior = entryList.toMutableList()1924 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))1925 prior1926 } ?: throw IllegalStateException("vault_locked")1927 persistOrRollback(rollback, epoch)1928 }19291930 1931 suspend fun purgeEntry(id: String) = mutex.withLock {1932 val epoch = requireUnlocked()1933 val rollback = mutateCurrentSession(epoch) {1934 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1935 if (idx == -1) throw IllegalStateException("deleted entry not found")1936 val prior = entryList.toMutableList()1937 entryList.removeAt(idx)1938 prior1939 } ?: throw IllegalStateException("vault_locked")1940 persistOrRollback(rollback, epoch)1941 }19421943 1944 suspend fun purgeDeletedEntries(): Int = mutex.withLock {1945 val epoch = requireUnlocked()1946 1947 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1948 val r = mutateCurrentSession(epoch) {1949 val rollback = entryList.toMutableList()1950 val before = entryList.size1951 entryList.removeAll { it.deletedAt != null }1952 R(rollback, before - entryList.size)1953 } ?: throw IllegalStateException("vault_locked")1954 if (r.removed > 0) persistOrRollback(r.rollback, epoch)1955 r.removed1956 }19571958 1959 suspend fun countDuplicateEntries(): Int = mutex.withLock {1960 val epoch = requireUnlocked()1961 1962 1963 mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }1964 ?: throw IllegalStateException("vault_locked")1965 }19661967 19681969197019711972 suspend fun deduplicateEntries(): Int = mutex.withLock {1973 val epoch = requireUnlocked()1974 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1975 val ready = mutateCurrentSession(epoch) {1976 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")1977 val active = entryList.filter { it.deletedAt == null }1978 val keepIds = mutableSetOf<String>()1979 active.groupBy { it.duplicateKey() }.values.forEach { group ->1980 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id1981 }1982 val rollback = entryList.toMutableList()1983 var removed = 01984 entryList = entryList.map { entry ->1985 if (entry.deletedAt == null && entry.id !in keepIds) {1986 removed++1987 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1988 entry.copy(deletedAt = stamp, modifiedAt = stamp)1989 } else {1990 entry1991 }1992 }.toMutableList()1993 R(rollback, removed)1994 } ?: throw IllegalStateException("vault_locked")1995 if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)1996 ready.removed1997 }19981999 fun getEntries(): List<VaultEntry> = mutateState {2000 if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }2001 }2002 fun getEntry(id: String): VaultEntry? = mutateState {2003 if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }2004 }2005 fun getDeletedEntries(): List<VaultEntry> = mutateState {2006 if (!sessionDataAvailable) emptyList()2007 else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }2008 }20092010 2011 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {2012 return mutateState {2013 if (!sessionDataAvailable) return@mutateState emptyList()2014 val active = entryList.filter { it.deletedAt == null }2015 if (tagFilter == null) return@mutateState active2016 val needle = tagFilter.trim().lowercase()2017 active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }2018 }2019 }20202021 2022 fun getDistinctTags(): List<String> = mutateState {2023 if (!sessionDataAvailable) return@mutateState emptyList()2024 entryList.asSequence()2025 .filter { it.deletedAt == null }2026 .flatMap { it.tags?.asSequence() ?: emptySequence() }2027 .map { it.trim().lowercase() }2028 .filter { it.isNotEmpty() }2029 .distinct()2030 .sorted()2031 .toList()2032 }20332034 203520362037203820392040 fun getDistinctFieldValues(field: String): List<String> {2041 val select: (VaultEntry) -> String? = when (field) {2042 "username" -> { e -> e.username }2043 "email" -> { e -> e.email }2044 else -> return emptyList()2045 }2046 return mutateState {2047 if (!sessionDataAvailable) return@mutateState emptyList()2048 entryList.asSequence()2049 .filter { it.deletedAt == null }2050 .mapNotNull { select(it)?.trim() }2051 .filter { it.isNotEmpty() }2052 .groupingBy { it.lowercase() }2053 .aggregate { _, acc: Pair<String, Int>?, value, _ ->2054 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)2055 }2056 .values2057 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })2058 .map { it.first }2059 }2060 }20612062 fun getTombstones(): List<Tombstone> = mutateState {2063 if (!sessionDataAvailable) emptyList()2064 else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }2065 }2066 fun getVaultVersion(): Long = store.version()2067 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots20682069 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {2070 val expectedEpoch = currentEpoch()2071 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false2072 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false2073 2074 2075 val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)2076 val priorA = store.loadSlotA()2077 val priorB = store.loadSlotB()2078 val priorD = store.loadDecoySlot()2079 2080 2081 2082 2083 2084 val priorHistory = store.loadVaultHistory()2085 2086 2087 2088 2089 beforeDurableCommit()2090 if (!takeVaultSnapshot("restore", expectedEpoch)) {2091 return false2092 }2093 2094 2095 2096 val nextD: StoredVault = restoredD ?: run {2097 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 162098 val fakeBlob = ByteArray(target).also(rng::nextBytes)2099 val fakeSalt = VaultCrypto.generateSalt()2100 StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob))2101 }2102 if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2103 withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2104 return false2105 }2106 lock()2107 true2108 }21092110 21112112211321142115211621172118211921202121 private fun commitRestoreAtomic(2122 nextA: StoredVault,2123 nextB: String,2124 nextD: StoredVault,2125 priorA: StoredVault?,2126 priorB: String?,2127 priorD: StoredVault?,2128 expectedEpoch: Long,2129 ): Boolean {2130 return withEpochCommit(expectedEpoch) {2131 if (!store.writeSlotA(nextA)) return@withEpochCommit false2132 2133 2134 2135 try {2136 if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2137 2138 2139 if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2140 store.stampLocalMutation()2141 } catch (_: Exception) {2142 reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2143 return@withEpochCommit false2144 }2145 true2146 } ?: false2147 }21482149 21502151 21522153215421552156 suspend fun applyMergedRemoteEntries(2157 remoteEntries: List<VaultEntry>,2158 remoteTombstones: List<Tombstone>,2159 expectedEpoch: Long? = null,2160 ): Int = mutex.withLock {2161 val epoch = expectedEpoch ?: requireUnlocked()2162 if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02163 2164 2165 2166 2167 2168 val mergeNow = System.currentTimeMillis()2169 val clamped = remoteEntries.mapNotNull { entry ->2170 2171 2172 2173 SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2174 modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2175 deletedAt = entry.deletedAt?.let {2176 SyncLimits.clampSyncTimestamp(it, mergeNow)2177 },2178 )2179 }2180 val tombMap = remoteTombstones.associate {2181 it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2182 }2183 2184 2185 val applied = mutateCurrentSession(epoch) {2186 var n = 02187 val byId = entryList.associateBy { it.id }.toMutableMap()21882189 for (remote in clamped) {2190 val tomb = tombMap[remote.id]2191 if (tomb != null && tomb >= remote.modifiedAt) continue2192 val local = byId[remote.id]2193 if (local == null) {2194 entryList.add(remote); byId[remote.id] = remote; n++2195 } else if (remote.modifiedAt > local.modifiedAt) {2196 val i = entryList.indexOfFirst { it.id == local.id }2197 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2198 }2199 }22002201 for ((id, deletedAt) in tombMap) {2202 val local = byId[id] ?: continue2203 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2204 if (deletedAt < local.modifiedAt) continue2205 val i = entryList.indexOfFirst { it.id == id }2206 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2207 }2208 n2209 } ?: return@withLock 022102211 if (applied > 0) {2212 persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2213 mutateIfCurrentEpoch(epoch) { publish() }2214 runCatching { LockedSyncSpoolHooks.refresh(this) }2215 }2216 applied2217 }22182219 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2220 2221 2222 2223 val epoch = requireUnlocked()2224 val prior = mutateCurrentSession(epoch) {2225 val old = _settings.value2226 _settings.value = settings2227 old2228 } ?: throw IllegalStateException("vault_locked")22292230 val committed = try {2231 beforeDurableCommit()2232 2233 2234 2235 withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2236 } catch (_: Exception) {2237 false2238 }2239 if (!committed) {2240 2241 2242 2243 mutateIfCurrentEpoch(epoch) { _settings.value = prior }2244 throw IllegalStateException("settings_write_failed")2245 }2246 }22472248 22492250 2251 fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }22522253 22542255225622572258 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2259 val epoch = requireUnlocked()2260 2261 2262 2263 2264 2265 2266 val prior = mutateCurrentSession(epoch) {2267 val priorPair = recoveryWordHash to recoveryWordsSet2268 recoveryWordHash = recoveryWordsHash(words)2269 recoveryWordsSet = true2270 priorPair2271 } ?: return@withLock false2272 2273 2274 2275 2276 val persisted = runCatching {2277 persistSlotAWithEscrows(2278 buildRecoveryEscrow(words),2279 buildRootKeyEscrow(words),2280 expectedEpoch = epoch,2281 )2282 }.getOrDefault(false)2283 if (!persisted) {2284 mutateIfCurrentEpoch(epoch) {2285 recoveryWordHash = prior.first2286 recoveryWordsSet = prior.second2287 }2288 }2289 persisted2290 }22912292 2293 fun verifyRecoveryWords(words: List<String>): Boolean {2294 return mutateState {2295 val stored = recoveryWordHash ?: return@mutateState false2296 MessageDigest.isEqual(2297 stored.toByteArray(Charsets.UTF_8),2298 recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2299 )2300 }2301 }23022303 23042305 2306 fun hasRecoveryEscrow(): Boolean =2307 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false23082309 23102311231223132314 private fun ensureRecoveryEscrow() {2315 if (hasRecoveryEscrow()) return2316 val rk = mutateState { rootKey?.copyOf() } ?: return2317 runCatching {2318 val words = rootKeyToWords(rk)2319 val escrow = buildRecoveryEscrow(words)2320 val rkEscrow = buildRootKeyEscrow(words)2321 if (escrow != null || rkEscrow != null) {2322 val prior = store.loadSlotA() ?: return@runCatching2323 store.writeSlotA(prior.copy(2324 recoveryEscrow = escrow ?: prior.recoveryEscrow,2325 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2326 ))2327 mutateState {2328 recoveryWordHash = recoveryWordsHash(words)2329 recoveryWordsSet = true2330 }2331 }2332 }.also { VaultCrypto.zero(rk) }2333 }23342335 233623372338233923402341234223432344234523462347 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2348 val expectedEpoch = currentEpoch()2349 val slotA = store.loadSlotA() ?: return false2350 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false23512352 2353 2354 val fullEscrow = slotA.recoveryEscrow2355 if (fullEscrow != null) {2356 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2357 if (material != null) {2358 var keyBytes: ByteArray? = null2359 var plaintext: ByteArray? = null2360 var candidateRoot: ByteArray? = null2361 var stateCommitStarted = false2362 try {2363 keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2364 plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2365 val payload = VaultCodec.decode(plaintext)2366 2367 2368 2369 2370 val candidateSettings = store.loadSettings()2371 candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2372 val decodedRoot = unb64(payload.rootKeyB64)2373 if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2374 2375 2376 2377 VaultCrypto.zero(decodedRoot)2378 throw IllegalArgumentException("invalid recovery root key")2379 }2380 decodedRoot2381 } else {2382 generateRecoverableRootKey()2383 }2384 stateCommitStarted = true2385 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2386 clearSessionStateLocked()2387 entryList = payload.entries.toMutableList()2388 authenticatedDuressConfigured = payload.duressConfigured2389 _duressConfigured.value = payload.duressConfigured2390 recoveryWordHash = payload.recoveryWordHash2391 recoveryWordsSet = payload.recoveryWordsSet2392 rootKey = candidateRoot2393 candidateRoot = null2394 _settings.value = candidateSettings2395 publish()2396 2397 2398 sessionDataAvailable = true2399 _isUnlocked.value = false2400 true2401 }2402 if (adopted == true) return@withLock true2403 } catch (_: Exception) {2404 2405 2406 2407 2408 if (stateCommitStarted) {2409 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2410 }2411 } finally {2412 plaintext?.let(VaultCrypto::zero)2413 VaultCrypto.zero(material)2414 keyBytes?.let(VaultCrypto::zero)2415 candidateRoot?.let(VaultCrypto::zero)2416 }2417 }2418 }24192420 2421 2422 2423 val rootEscrow = slotA.rootKeyEscrow2424 if (rootEscrow != null) {2425 var candidateRoot: ByteArray? = null2426 var stateCommitStarted = false2427 try {2428 candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2429 require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2430 val candidateSettings = store.loadSettings()2431 stateCommitStarted = true2432 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2433 clearSessionStateLocked()2434 entryList = mutableListOf()2435 authenticatedDuressConfigured = false2436 _duressConfigured.value = false2437 recoveryWordHash = recoveryWordsHash(words)2438 recoveryWordsSet = true2439 rootKey = candidateRoot2440 candidateRoot = null2441 _settings.value = candidateSettings2442 publish()2443 sessionDataAvailable = true2444 _isUnlocked.value = false2445 true2446 }2447 if (adopted == true) return@withLock true2448 } catch (_: Exception) {2449 if (stateCommitStarted) {2450 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2451 }2452 } finally {2453 candidateRoot?.let(VaultCrypto::zero)2454 }2455 }2456 return false2457 }24582459 246024612462246324642465246624672468 suspend fun resetPasswordWithRecoveryWords(2469 words: List<String>,2470 newPassword: String,2471 ): Boolean = mutex.withLock {2472 val expectedEpoch = currentEpoch()2473 2474 2475 2476 if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2477 val priorA = store.loadSlotA() ?: return false2478 var newKey: ByteArray? = null2479 var plaintext: ByteArray? = null2480 return try {2481 val newSalt = VaultCrypto.generateSalt()2482 newKey = VaultCrypto.deriveKey(newPassword, newSalt)2483 plaintext = VaultCodec.encode(currentPayload())2484 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2485 2486 2487 2488 val valid = words.size == 12 && findInvalidWords(words).isEmpty()2489 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2490 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2491 val next = StoredVault(2492 version = priorA.version,2493 salt = b64(newSalt),2494 blob = blob,2495 recoveryEscrow = freshRecovery,2496 rootKeyEscrow = freshRootKey,2497 )2498 2499 2500 2501 val priorB = store.loadSlotB()2502 if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2503 2504 2505 2506 if (mutateIfCurrentEpoch(expectedEpoch) {2507 derivedKey?.let(VaultCrypto::zero)2508 derivedKey = newKey; newKey = null2509 publish()2510 _isUnlocked.value = true2511 } == null) return false2512 true2513 } catch (_: Exception) {2514 false2515 } finally {2516 newKey?.let(VaultCrypto::zero)2517 plaintext?.let(VaultCrypto::zero)2518 }2519 }25202521 252225232524252525262527 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2528 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2529 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2530 var keyBytes: ByteArray? = null2531 var plaintext: ByteArray? = null2532 return try {2533 val salt = VaultCrypto.generateSalt()2534 val recoveryKey = deriveRecoveryKey(material, salt)2535 keyBytes = recoveryKey.encoded2536 plaintext = VaultCodec.encode(currentPayload())2537 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2538 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2539 } finally {2540 VaultCrypto.zero(material)2541 keyBytes?.let(VaultCrypto::zero)2542 plaintext?.let(VaultCrypto::zero)2543 }2544 }25452546 25472548254925502551255225532554 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2555 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2556 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2557 val rk = mutateState { rootKey?.copyOf() } ?: run {2558 VaultCrypto.zero(material)2559 return null2560 }2561 var keyBytes: ByteArray? = null2562 var plaintext: ByteArray? = null2563 return try {2564 val salt = VaultCrypto.generateSalt()2565 val recoveryKey = deriveRecoveryKey(material, salt)2566 keyBytes = recoveryKey.encoded2567 plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2568 2569 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2570 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2571 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2572 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2573 val ct = ctTag.copyOfRange(0, ctTag.size - 16)2574 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2575 } finally {2576 VaultCrypto.zero(rk)2577 VaultCrypto.zero(material)2578 keyBytes?.let(VaultCrypto::zero)2579 plaintext?.let(VaultCrypto::zero)2580 }2581 }25822583 2584 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2585 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2586 var keyBytes: ByteArray? = null2587 var pt: ByteArray? = null2588 return try {2589 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2590 keyBytes = recoveryKey.encoded2591 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2592 pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2593 hexToRootKey(String(pt, Charsets.US_ASCII))2594 } catch (_: Exception) {2595 null2596 } finally {2597 2598 2599 2600 VaultCrypto.zero(material)2601 keyBytes?.let(VaultCrypto::zero)2602 pt?.let(VaultCrypto::zero)2603 }2604 }26052606 260726082609261026112612 private fun persistSlotAWithEscrows(2613 recoveryEscrow: RecoveryEscrow?,2614 rootKeyEscrow: RootKeyEscrow?,2615 expectedEpoch: Long? = null,2616 ): Boolean {2617 val snapshot = snapshotForPersist(expectedEpoch)2618 ?: throw IllegalStateException("vault_locked_or_stale")2619 if (snapshot.decoy) {2620 VaultCrypto.zero(snapshot.key)2621 return false2622 }2623 try {2624 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2625 val plaintext = VaultCodec.encode(snapshot.payload)2626 val blob = try {2627 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2628 } finally {2629 2630 2631 VaultCrypto.zero(plaintext)2632 }2633 val next = prior.copy(2634 blob = blob,2635 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2636 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2637 )2638 beforeDurableCommit()2639 return withEpochCommit(snapshot.epoch) {2640 if (!store.writeSlotA(next)) return@withEpochCommit false2641 try {2642 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2643 2644 2645 2646 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2647 } catch (e: Exception) {2648 store.writeSlotA(prior)2649 throw e2650 }2651 true2652 } ?: false2653 } finally {2654 VaultCrypto.zero(snapshot.key)2655 }2656 }26572658 26592660 private fun requireUnlocked(): Long {2661 2662 2663 2664 stateLock.lock()2665 try {2666 if (derivedKey == null) throw IllegalStateException("vault_locked")2667 return sessionEpoch2668 } finally {2669 stateLock.unlock()2670 }2671 }26722673 2674 private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null26752676 private fun countDuplicateEntriesLocked(): Int {2677 val seen = mutableMapOf<String, VaultEntry>()2678 var duplicates = 02679 for (entry in entryList.filter { it.deletedAt == null }) {2680 val key = entry.duplicateKey()2681 val existing = seen[key]2682 if (existing == null) {2683 seen[key] = entry2684 } else {2685 duplicates++2686 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2687 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2688 if (entryStamp > existingStamp) seen[key] = entry2689 }2690 }2691 return duplicates2692 }26932694 private fun VaultEntry.duplicateKey(): String {2695 if (type == "note") return "note|${title.lowercase()}"2696 val passkeyData = passkey2697 if (passkeyData != null) {2698 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2699 }2700 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2701 }27022703 270427052706270727082709 private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2710 val epoch = expectedEpoch ?: currentEpoch()2711 if (mutateIfCurrentEpoch(epoch) { true } != true) return false2712 val slotA = store.loadSlotA() ?: return false2713 val vaultA = VaultCodec.encodeSlot(slotA)2714 val vaultB = store.loadSlotB() ?: slotA.blob2715 2716 2717 2718 2719 2720 val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2721 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162722 val fakeBlob = ByteArray(target).also(rng::nextBytes)2723 val fakeSalt = VaultCrypto.generateSalt()2724 VaultCodec.encodeSlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2725 }2726 val history = store.loadVaultHistory()2727 val latest = history.snapshots.firstOrNull()2728 if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2729 val entryCount = mutateIfCurrentEpoch(epoch) {2730 if (derivedKey != null && !decoyMode) {2731 bucketEntryCount(entryList.count { it.deletedAt == null })2732 } else {2733 null2734 }2735 } ?: return false2736 return try {2737 val snapshot = VaultSnapshot(2738 id = UUID.randomUUID().toString(),2739 savedAt = System.currentTimeMillis(),2740 reason = reason,2741 vault_a = vaultA,2742 vault_b = vaultB,2743 vault_d = vaultD,2744 entryCount = entryCount,2745 )2746 2747 2748 2749 withEpochCommit(epoch) {2750 store.writeVaultHistory(2751 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2752 )2753 } ?: false2754 } catch (_: Exception) {2755 false2756 }2757 }27582759 private fun bucketEntryCount(n: Int): Int = when {2760 n <= 0 -> 02761 n <= 10 -> 102762 n <= 25 -> 252763 n <= 50 -> 502764 n <= 100 -> 1002765 n <= 250 -> 2502766 n <= 500 -> 5002767 else -> ((n + 499) / 500) * 5002768 }27692770 277127722773277427752776277727782779 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2780 if (!entry.isCard()) return entry2781 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2782 val derived = if (digits.length >= 4) digits.takeLast(4) else null2783 return entry.copy(last4 = derived ?: entry.last4)2784 }27852786 278727882789279027912792 private fun autoPurgeExpiredTrash() {2793 val days = _settings.value.trashRetentionDays ?: return2794 if (days <= 0) return2795 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2796 val before = entryList.size2797 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2798 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2799 }28002801 280228032804280528062807 private fun consolidatePasskeyEntries() {2808 val passkeyOnly = entryList.filter { entry ->2809 entry.deletedAt == null &&2810 entry.isLogin() &&2811 entry.password.isNullOrBlank() &&2812 !entry.rpId.isNullOrBlank() &&2813 !entry.credentialId.isNullOrBlank()2814 }2815 if (passkeyOnly.isEmpty()) return2816 var changed = false2817 val now = System.currentTimeMillis()2818 for (pkEntry in passkeyOnly) {2819 val rpId = pkEntry.rpId ?: continue2820 val target = entryList.firstOrNull { candidate ->2821 candidate.deletedAt == null &&2822 candidate.id != pkEntry.id &&2823 candidate.isLogin() &&2824 candidate.passkey == null &&2825 candidate.credentialId.isNullOrBlank() &&2826 !candidate.password.isNullOrBlank() &&2827 listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2828 .any { com.peachpasswords.shared.extractDomain(it) == rpId }2829 } ?: continue2830 val idx = entryList.indexOfFirst { it.id == target.id }2831 if (idx < 0) continue2832 entryList[idx] = target.copy(2833 rpId = pkEntry.rpId,2834 rpName = pkEntry.rpName ?: target.rpName,2835 credentialId = pkEntry.credentialId,2836 publicKeyCose = pkEntry.publicKeyCose,2837 privateKeyJwk = pkEntry.privateKeyJwk,2838 userHandle = pkEntry.userHandle,2839 userName = pkEntry.userName,2840 userDisplayName = pkEntry.userDisplayName,2841 algorithm = pkEntry.algorithm,2842 signCount = pkEntry.signCount,2843 lastUsedAt = pkEntry.lastUsedAt,2844 modifiedAt = now,2845 )2846 2847 val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2848 if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2849 changed = true2850 }2851 if (changed) runCatching { persistSlotA(bumpVersion = false) }2852 }28532854 2855 private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }28562857 private fun currentPayloadLocked(): VaultPayload =2858 VaultPayload(2859 entries = entryList.toList(),2860 duressConfigured = authenticatedDuressConfigured,2861 rootKeyB64 = rootKey?.let(::b64) ?: "",2862 recoveryWordHash = recoveryWordHash,2863 recoveryWordsSet = recoveryWordsSet,2864 )28652866 28672868286928702871 private fun ensureRootKey(payload: VaultPayload) {2872 if (payload.rootKeyB64.isNotBlank()) {2873 rootKey = unb64(payload.rootKeyB64)2874 return2875 }2876 rootKey = generateRecoverableRootKey()2877 runCatching { persistSlotA(bumpVersion = false) }2878 }28792880 private fun publish() {2881 _entries.value = entryList.filter { it.deletedAt == null }2882 }28832884 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2885 var plaintext = VaultCodec.encode(currentPayload())2886 return try {2887 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2888 StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob)2889 } finally {2890 2891 2892 2893 VaultCrypto.zero(plaintext)2894 }2895 }28962897 private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2898 2899 2900 2901 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2902 val noise = ByteArray(approxBytes).also(rng::nextBytes)2903 return store.writeSlotB(b64(noise))2904 }29052906 290729082909 private fun matchingCiphertextLength(slotA: StoredVault): Int =2910 (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)29112912 29132914291529162917 private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {2918 val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162919 val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)2920 val fakeSalt = VaultCrypto.generateSalt()2921 return store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2922 }29232924 292529262927292829292930 private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {2931 val isConfigured = mutateState { authenticatedDuressConfigured }2932 return if (isConfigured) true else writeFakeDuressSlot(slotA)2933 }29342935 2936293729382939294029412942 private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {2943 val salt = unhex(b.salt)2944 val nonce = unhex(b.nonce)2945 val ct = unhex(b.ciphertext)2946 val tag = unhex(b.tag)2947 val blob = ByteArray(nonce.size + ct.size + tag.size).also {2948 System.arraycopy(nonce, 0, it, 0, nonce.size)2949 System.arraycopy(ct, 0, it, nonce.size, ct.size)2950 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)2951 }2952 return StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))2953 }2954 2955 private fun persistSlotA(2956 bumpVersion: Boolean,2957 snapshotReason: String? = "local_save",2958 expectedEpoch: Long? = null,2959 ): Boolean {2960 val snapshot = snapshotForPersist(expectedEpoch)2961 ?: throw IllegalStateException("vault_locked_or_stale")2962 return try {2963 2964 if (snapshot.decoy) {2965 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")2966 val plaintext = VaultCodec.encode(snapshot.payload)2967 val blob = try {2968 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_B))2969 } finally {2970 2971 2972 VaultCrypto.zero(plaintext)2973 }2974 beforeDurableCommit()2975 return withEpochCommit(snapshot.epoch) {2976 store.writeDecoySlot(prior.copy(version = CURRENT_ANDROID_SLOT_VERSION, blob = blob))2977 } ?: false2978 }2979 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2980 2981 2982 2983 2984 val priorB = store.loadSlotB()2985 beforeDurableCommit()2986 if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false2987 val plaintext = VaultCodec.encode(snapshot.payload)2988 val blob = try {2989 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2990 } finally {2991 2992 2993 VaultCrypto.zero(plaintext)2994 }2995 val next = prior.copy(blob = blob)2996 2997 2998 2999 3000 withEpochCommit(snapshot.epoch) {3001 if (!store.writeSlotA(next)) return@withEpochCommit false3002 try {3003 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")3004 3005 3006 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")3007 if (bumpVersion) store.stampLocalMutation()3008 } catch (e: Exception) {3009 store.writeSlotA(prior)3010 if (priorB != null) runCatching { store.writeSlotB(priorB) }3011 throw e3012 }3013 true3014 } ?: false3015 } finally {3016 3017 3018 VaultCrypto.zero(snapshot.key)3019 }3020 }30213022 3023302430253026302730283029 private fun commitVaultRotation(3030 priorA: StoredVault,3031 priorB: String?,3032 nextA: StoredVault,3033 expectedEpoch: Long,3034 ): Boolean {3035 beforeDurableCommit()3036 return withEpochCommit(expectedEpoch) {3037 if (!store.writeSlotA(nextA)) return@withEpochCommit false3038 3039 3040 3041 try {3042 if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")3043 3044 3045 3046 3047 if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")3048 store.stampLocalMutation()3049 } catch (_: Exception) {3050 rollbackRotation(priorA, priorB)3051 return@withEpochCommit false3052 }3053 true3054 } ?: false3055 }30563057 30583059306030613062 private fun rollbackRotation(priorA: StoredVault, priorB: String?) {3063 val failures = mutableListOf<String>()3064 runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }3065 .onFailure { failures += "writeSlotA: $it" }3066 if (priorB != null) {3067 runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }3068 .onFailure { failures += "writeSlotB: $it" }3069 }3070 if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }3071 }30723073 3074 private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {3075 try {3076 if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {3077 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3078 throw IllegalStateException("storage_write_failed")3079 }3080 } catch (e: Exception) {3081 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3082 throw e3083 }3084 3085 3086 3087 mutateIfCurrentEpoch(expectedEpoch) { publish() }3088 runCatching { LockedSyncSpoolHooks.refresh(this) }3089 }3090}