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}6061626364656667686970internal object VaultKeyRotationHooks {71 @Volatile var onRotated: () -> Unit = {}72}737475767778798081828384858687@Singleton88class VaultRepository @Inject constructor(89 private val store: VaultStorage,90) {91 private val slotRollback = VaultSlotRollback(store)92 private val mutex = Mutex()93 94 95 96 97 98 99 100 private val stateLock = ReentrantLock()101 private val rng = SecureRandom()102103 104105106107108 private var sessionEpoch: Long = 0L109110 private fun nextSessionEpoch(epoch: Long): Long =111 if (epoch == Long.MAX_VALUE) 0L else epoch + 1L112113 114 @VisibleForTesting115 internal var beforeDurableCommit: () -> Unit = {}116117 118 @VisibleForTesting119 internal var afterCodexRollback: () -> Unit = {}120121 122123124125126 private inline fun <T> mutateState(block: () -> T): T {127 stateLock.lock()128 return try { block() } finally { stateLock.unlock() }129 }130131 132 private inline fun <T> withEpochCommit(epoch: Long, block: () -> T): T? {133 stateLock.lock()134 return try {135 if (sessionEpoch != epoch) null else block()136 } finally {137 stateLock.unlock()138 }139 }140141 142 @VisibleForTesting143 internal var beforeSessionEpochCommit: () -> Unit = {}144145 146147148149150 @VisibleForTesting151 internal var beforeSessionStateMutation: () -> Unit = {}152153 154155156157158159 internal fun <T> withSessionEpochCommit(epoch: Long, block: () -> T): T? {160 beforeSessionEpochCommit()161 return withEpochCommit(epoch, block)162 }163164 private fun currentEpoch(): Long = mutateState { sessionEpoch }165166 private inline fun <T> mutateIfCurrentEpoch(epoch: Long, block: () -> T): T? =167 mutateState { if (sessionEpoch == epoch) block() else null }168169 170 private inline fun <T> mutateCurrentSession(epoch: Long, block: () -> T): T? {171 beforeSessionStateMutation()172 return mutateIfCurrentEpoch(epoch, block)173 }174175 private data class PersistSnapshot(176 val epoch: Long,177 val key: ByteArray,178 val payload: VaultPayload,179 val decoy: Boolean,180 )181182 183 private fun snapshotForPersist(expectedEpoch: Long? = null): PersistSnapshot? = mutateState {184 if (expectedEpoch != null && sessionEpoch != expectedEpoch) return@mutateState null185 val liveKey = derivedKey ?: return@mutateState null186 PersistSnapshot(187 epoch = sessionEpoch,188 key = liveKey.copyOf(),189 payload = currentPayloadLocked(),190 decoy = decoyMode,191 )192 }193194 private var derivedKey: ByteArray? = null195 private var rootKey: ByteArray? = null196 private var entryList: MutableList<VaultEntry> = mutableListOf()197 private var authenticatedDuressConfigured: Boolean = false198 private var recoveryWordHash: String? = null199 private var recoveryWordsSet: Boolean = false200 201 private var sessionDataAvailable: Boolean = false202 203 private var decoyMode: Boolean = false204205 private val _isUnlocked = MutableStateFlow(false)206 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()207208 private val _duressConfigured = MutableStateFlow(false)209 210 val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()211212213 214215216217218219 private val _uiGateLocked = MutableStateFlow(false)220 val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()221222 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())223 224 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()225226 227 228 229 230 private val _settings = MutableStateFlow(store.loadSettings())231 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()232233 234 private fun clearSessionStateLocked() {235 derivedKey?.let(VaultCrypto::zero)236 rootKey?.let(VaultCrypto::zero)237 derivedKey = null238 rootKey = null239 entryList = mutableListOf()240 authenticatedDuressConfigured = false241 _duressConfigured.value = false242 recoveryWordHash = null243 recoveryWordsSet = false244 sessionDataAvailable = false245 decoyMode = false246 _settings.value = store.loadSettings()247 _entries.value = emptyList()248 _isUnlocked.value = false249 }250251 fun hasVault(): Boolean = store.hasVault()252253 254255 256257258259260261262 fun codexVaultBlobBase64(): String? {263 val slotA = store.loadSlotA() ?: return null264 265 266 val slotD = store.loadDecoySlot() ?: return null267 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""268 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))269 }270271 272273274275276 277 private fun JsonElement?.asSlotJson(): String? = when {278 this == null || this is JsonNull -> null279 this is JsonPrimitive && isString -> content280 else -> toString()281 }282283 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {284 val expectedEpoch = currentEpoch()285 var candidateKey: ByteArray? = null286 var plaintext: ByteArray? = null287 return try {288 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)289 290 291 292 293 294 295 296 val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject297 ?: return UnlockResult.Error("invalid_codex_blob")298 val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")299 300 301 302 303 304 val slotA = VaultCodec.decodeSlot(slotJson)305 ?: BrowserSlot.parse(slotJson)?.let {306 BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword307 }308 ?: return UnlockResult.Error("invalid_codex_blob")309 310 311 312 313 314 candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))315 plaintext = decryptSlotABlob(slotA, candidateKey)316 317 318 319 320 if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {321 VaultCrypto.zero(candidateKey)322 candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))323 plaintext = decryptSlotABlob(slotA, candidateKey)324 }325 if (plaintext == null) return UnlockResult.WrongPassword326 val payload = try {327 VaultCodec.decode(plaintext)328 } catch (_: Exception) {329 return UnlockResult.Error("invalid_codex_blob")330 }331332 val priorA = store.loadSlotA()333 val priorB = store.loadSlotB()334 val priorD = store.loadDecoySlot()335 336 337 338 339 340 val codexDuressJson = wrapper["b"].asSlotJson()341 val codexDuress: StoredVault? = codexDuressJson?.let {342 VaultCodec.decodeSlot(it)?.let { slot ->343 if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) null else slot344 } ?: BrowserSlot.parse(it)?.let { b ->345 browserDuressPassthrough(b)346 }347 }348349 beforeDurableCommit()350 val committed = runCatching {351 withEpochCommit(expectedEpoch) {352 try {353 354 355 356 357 if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")358 359 360 if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")361 362 363 val duressOk = if (codexDuress != null) {364 store.writeDecoySlot(codexDuress)365 } else {366 writeFakeDuressSlot(slotA)367 }368 if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")369 store.stampLocalMutation()370 true371 } catch (_: Exception) {372 reportRollbackFailures(slotRollback.restoreTriad(priorA, priorB, priorD))373 374 375 376 afterCodexRollback()377 false378 }379 } ?: false380 }.getOrDefault(false)381 if (!committed) {382 return UnlockResult.Error("storage_write_failed")383 }384385 val ownedKey = candidateKey!!386 candidateKey = null 387 VaultKeyRotationHooks.onRotated()388 adoptSlotA(ownedKey, payload, expectedEpoch)389 } catch (e: Exception) {390 391 392 393 394 395 396 if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))397 UnlockResult.Error(e.message ?: "restore_failed")398 } finally {399 plaintext?.let(VaultCrypto::zero)400 candidateKey?.let(VaultCrypto::zero)401 }402 }403404 405 private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =406 runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()407408 private fun reportRollbackFailures(failures: List<String>) {409 410 411 if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }412 }413414 415 private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {416 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)417 val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()418 val window = offset?.let {419 val from = (it - 40).coerceAtLeast(0)420 val to = (it + 40).coerceAtMost(wrapperJson.length)421 wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")422 }423 val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()424 val slot = wrapper?.get("a")425 buildString {426 append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)427 append(" | blobBase64=").append(vaultBlobBase64.length)428 append(" wrapperChars=").append(wrapperJson.length)429 append(" wrapperParses=").append(wrapper != null)430 append(" keys=").append(wrapper?.keys)431 append(" slotAKind=").append(432 when {433 slot == null -> "absent"434 slot is JsonPrimitive && slot.isString -> "string"435 slot is JsonObject -> "object:" + slot.keys436 else -> slot::class.simpleName437 },438 )439 if (window != null) append(" masked@").append(offset).append("=").append(window)440 }441 }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }442443 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {444 val expectedEpoch = currentEpoch()445 var key: ByteArray? = null446 return try {447 val salt = VaultCrypto.generateSalt()448 key = VaultCrypto.deriveKey(password, salt)449 if (mutateIfCurrentEpoch(expectedEpoch) {450 entryList = mutableListOf()451 authenticatedDuressConfigured = false452 _duressConfigured.value = false453 recoveryWordHash = null454 recoveryWordsSet = false455 decoyMode = false456 sessionDataAvailable = false457 rootKey = generateRecoverableRootKey()458 } == null) return CreateVaultResult.Error("stale_create")459 460 461 462 463 val slotA = sealSlotA(key!!, salt)464 465 466 beforeDurableCommit()467 val created = withEpochCommit(expectedEpoch) {468 if (!store.writeSlotA(slotA)) return@withEpochCommit false469 try {470 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")471 472 473 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")474 store.stampLocalMutation()475 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")476 true477 } catch (_: Exception) {478 479 480 store.clearVault()481 false482 }483 } ?: false484 if (!created) {485 lock()486 return CreateVaultResult.Error("storage_write_failed")487 }488 val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")489 if (mutateIfCurrentEpoch(expectedEpoch) {490 derivedKey = sessionKey491 key = null492 publish()493 _isUnlocked.value = true494 sessionDataAvailable = true495 sessionEpoch = nextSessionEpoch(sessionEpoch)496 } == null) return CreateVaultResult.Error("stale_create")497 CreateVaultResult.Success498 } catch (e: Exception) {499 lock()500 CreateVaultResult.Error(e.message ?: "create_failed")501 } finally {502 key?.let(VaultCrypto::zero)503 }504 }505506 suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {507 val expectedEpoch = currentEpoch()508 if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")509 if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")510 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {511 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")512 }513 var adoptedRootKey: ByteArray? = null514 var nextDerivedKey: ByteArray? = null515 var sessionRootKey: ByteArray? = null516 return try {517 adoptedRootKey = hexToRootKey(rootKeyHex)518 if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {519 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")520 }521 val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)522 val salt = VaultCrypto.generateSalt()523 nextDerivedKey = VaultCrypto.deriveKey(password, salt)524 sessionRootKey = adoptedRootKey.copyOf()525 val payload = VaultPayload(526 entries = emptyList(),527 duressConfigured = false,528 rootKeyB64 = b64(sessionRootKey),529 recoveryWordHash = null,530 recoveryWordsSet = false,531 )532 val plaintext = VaultCodec.encode(payload)533 val blob = try {534 b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))535 } finally {536 VaultCrypto.zero(plaintext)537 }538 val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)539 540 541 beforeDurableCommit()542 val created = withEpochCommit(expectedEpoch) {543 if (!store.writeSlotA(slotA)) return@withEpochCommit false544 try {545 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")546 547 548 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")549 store.stampLocalMutation()550 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")551 true552 } catch (_: Exception) {553 store.clearVault()554 false555 }556 } ?: false557 if (!created) return AdoptVaultResult.Error("storage_write_failed")558559 val adopted = mutateIfCurrentEpoch(expectedEpoch) {560 val previousDerivedKey = derivedKey561 val previousRootKey = rootKey562 derivedKey = nextDerivedKey563 rootKey = sessionRootKey564 nextDerivedKey = null565 sessionRootKey = null566 entryList = mutableListOf()567 authenticatedDuressConfigured = false568 _duressConfigured.value = false569 recoveryWordHash = null570 recoveryWordsSet = false571 decoyMode = false572 sessionDataAvailable = true573 publish()574 _isUnlocked.value = true575 sessionEpoch = nextSessionEpoch(sessionEpoch)576 previousDerivedKey to previousRootKey577 }578 if (adopted == null) return AdoptVaultResult.Error("stale_adoption")579 val (previousDerivedKey, previousRootKey) = adopted580 previousDerivedKey?.let(VaultCrypto::zero)581 previousRootKey?.let(VaultCrypto::zero)582 583 584 585 runCatching {586 val words = rootKeyToWords(rootKey!!)587 val escrow = buildRecoveryEscrow(words)588 val rkEscrow = buildRootKeyEscrow(words)589 if (escrow != null || rkEscrow != null) {590 val prior = store.loadSlotA()591 if (prior != null) {592 store.writeSlotA(prior.copy(593 recoveryEscrow = escrow ?: prior.recoveryEscrow,594 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,595 ))596 }597 mutateState {598 recoveryWordHash = recoveryWordsHash(words)599 recoveryWordsSet = true600 }601 }602 }603 AdoptVaultResult.Success(vaultId)604 } catch (e: Exception) {605 AdoptVaultResult.Error(e.message ?: "adoption_create_failed")606 } finally {607 adoptedRootKey?.let(VaultCrypto::zero)608 nextDerivedKey?.let(VaultCrypto::zero)609 sessionRootKey?.let(VaultCrypto::zero)610 }611 }612613 suspend fun unlock(password: String): UnlockResult = mutex.withLock {614 val result = unlockLocked(password, currentEpoch())615 if (result is UnlockResult.Success) ensureRecoveryEscrow()616 result617 }618619 620 private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {621 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")622 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))623 val payload = try {624 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)625 try {626 VaultCodec.decode(plaintext)627 } finally {628 VaultCrypto.zero(plaintext)629 }630 } catch (_: Exception) {631 VaultCrypto.zero(key)632 633 634 635 if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {636 val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)637 if (legacy != null) return legacy638 }639 return UnlockResult.WrongPassword640 }641 return adoptSlotA(key, payload, expectedEpoch)642 }643644 645646647648649650651652 private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {653 var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))654 var newKey: ByteArray? = null655 return try {656 val payload = try {657 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)658 try {659 VaultCodec.decode(plaintext)660 } finally {661 VaultCrypto.zero(plaintext)662 }663 } catch (_: Exception) {664 return null665 }666 667 668 val newSalt = VaultCrypto.generateSalt()669 newKey = VaultCrypto.deriveKey(password, newSalt)670 val plaintext = VaultCodec.encode(payload)671 val blob = try {672 b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))673 } finally {674 VaultCrypto.zero(plaintext)675 }676 val next = StoredVault(677 version = slotA.version,678 salt = b64(newSalt),679 blob = blob,680 recoveryEscrow = slotA.recoveryEscrow,681 rootKeyEscrow = slotA.rootKeyEscrow,682 )683 684 685 686 val priorB = store.loadSlotB()687 beforeDurableCommit()688 val healed = withEpochCommit(expectedEpoch) {689 if (!store.writeSlotA(next)) {690 false691 } else try {692 if (!writeMatchingNoiseSlotB(next)) {693 runCatching { store.writeSlotA(slotA) }694 if (priorB != null) runCatching { store.writeSlotB(priorB) }695 false696 } else if (!writeCompanionDuressSlot(next)) {697 runCatching { store.writeSlotA(slotA) }698 if (priorB != null) runCatching { store.writeSlotB(priorB) }699 false700 } else {701 store.stampLocalMutation()702 true703 }704 } catch (_: Exception) {705 runCatching { store.writeSlotA(slotA) }706 if (priorB != null) runCatching { store.writeSlotB(priorB) }707 false708 }709 } ?: false710 if (healed) {711 VaultCrypto.zero(rawKey!!)712 rawKey = null713 val result = adoptSlotA(newKey!!, payload, expectedEpoch) 714 newKey = null715 result716 } else {717 VaultCrypto.zero(newKey!!)718 newKey = null719 val result = adoptSlotA(rawKey!!, payload, expectedEpoch) 720 rawKey = null721 result722 }723 } finally {724 725 726 rawKey?.let(VaultCrypto::zero)727 newKey?.let(VaultCrypto::zero)728 }729 }730731 732 private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {733 return try {734 735 736 737 738 739 val adopted = mutateIfCurrentEpoch(expectedEpoch) {740 derivedKey = key741 decoyMode = false742 entryList = payload.entries.toMutableList()743 authenticatedDuressConfigured = payload.duressConfigured744 _duressConfigured.value = payload.duressConfigured745 recoveryWordHash = payload.recoveryWordHash746 recoveryWordsSet = payload.recoveryWordsSet747 sessionDataAvailable = true748 _settings.value = store.loadSettings()749 ensureRootKey(payload)750 autoPurgeExpiredTrash()751 consolidatePasskeyEntries()752 publish()753 _isUnlocked.value = true754 755 756 757 sessionEpoch = nextSessionEpoch(sessionEpoch)758 }759 if (adopted == null) {760 VaultCrypto.zero(key)761 UnlockResult.Error("stale_unlock")762 } else {763 UnlockResult.Success764 }765 } catch (e: Exception) {766 767 768 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }769 VaultCrypto.zero(key)770 UnlockResult.Error(e.message ?: "unlock_failed")771 }772 }773774 775776 777778779780781782 class SlotAUnlock internal constructor(783 key: ByteArray,784 internal val payload: VaultPayload,785 internal val epoch: Long,786 ) {787 private var ownedKey: ByteArray? = key788 private var consumed = false789790 791 internal fun takeKey(): ByteArray? = synchronized(this) {792 if (consumed) return@synchronized null793 consumed = true794 ownedKey.also { ownedKey = null }795 }796797 798 internal fun discard() = synchronized(this) {799 if (consumed) return@synchronized800 consumed = true801 ownedKey?.let(VaultCrypto::zero)802 ownedKey = null803 }804 }805806 807808809810811812 fun tryUnlockSlotA(password: String): SlotAUnlock? {813 val epoch = currentEpoch()814 val slotA = store.loadSlotA() ?: return null815 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))816 try {817 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)818 val payload = try {819 VaultCodec.decode(plaintext)820 } finally {821 VaultCrypto.zero(plaintext)822 }823 return SlotAUnlock(key, payload, epoch)824 } catch (_: Exception) {825 VaultCrypto.zero(key)826 }827828 if (password == Normalizer.normalize(password, Normalizer.Form.NFC)) return null829 return tryLegacyRawCandidate(password, slotA, epoch)830 }831832 833 private fun tryLegacyRawCandidate(password: String, slotA: StoredVault, epoch: Long): SlotAUnlock? {834 var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))835 var newKey: ByteArray? = null836 return try {837 val plaintext = try {838 VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)839 } catch (_: Exception) {840 return null841 }842 val payload = try {843 VaultCodec.decode(plaintext)844 } finally {845 VaultCrypto.zero(plaintext)846 }847 val newSalt = VaultCrypto.generateSalt()848 newKey = VaultCrypto.deriveKey(password, newSalt)849 val encoded = VaultCodec.encode(payload)850 val blob = try {851 b64(VaultCrypto.encrypt(encoded, newKey!!, VaultCrypto.AAD_SLOT_A))852 } finally {853 VaultCrypto.zero(encoded)854 }855 val next = slotA.copy(salt = b64(newSalt), blob = blob)856 val priorB = store.loadSlotB()857 beforeDurableCommit()858 val healed = withEpochCommit(epoch) {859 if (!store.writeSlotA(next)) false else try {860 if (!writeMatchingNoiseSlotB(next) || !writeCompanionDuressSlot(next)) {861 runCatching { store.writeSlotA(slotA) }862 if (priorB != null) runCatching { store.writeSlotB(priorB) }863 false864 } else {865 store.stampLocalMutation()866 true867 }868 } catch (_: Exception) {869 runCatching { store.writeSlotA(slotA) }870 if (priorB != null) runCatching { store.writeSlotB(priorB) }871 false872 }873 } ?: false874 if (healed) {875 VaultCrypto.zero(rawKey!!)876 rawKey = null877 SlotAUnlock(newKey!!, payload, epoch).also { newKey = null }878 } else {879 VaultCrypto.zero(newKey!!)880 newKey = null881 SlotAUnlock(rawKey!!, payload, epoch).also { rawKey = null }882 }883 } finally {884 rawKey?.let(VaultCrypto::zero)885 newKey?.let(VaultCrypto::zero)886 }887 }888889 890 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {891 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")892 adoptSlotA(key, unlock.payload, unlock.epoch)893 }894895 896 fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()897898 899900 901902903904905 class DuressUnlock internal constructor(906 key: ByteArray,907 internal val payload: VaultPayload,908 internal val epoch: Long,909 ) {910 private var ownedKey: ByteArray? = key911 private var consumed = false912913 internal fun takeKey(): ByteArray? = synchronized(this) {914 if (consumed) return@synchronized null915 consumed = true916 ownedKey.also { ownedKey = null }917 }918919 internal fun discard() = synchronized(this) {920 if (consumed) return@synchronized921 consumed = true922 ownedKey?.let(VaultCrypto::zero)923 ownedKey = null924 }925 }926927 928929930931932933934 fun tryUnlockDuress(password: String): DuressUnlock? {935 val epoch = currentEpoch()936 val slot = store.loadDecoySlot() ?: return null937 if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) return null938 var key: ByteArray? = VaultCrypto.deriveKey(password, unb64(slot.salt))939 return try {940 val plaintext = try {941 if (slot.version == CURRENT_ANDROID_SLOT_VERSION) {942 VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)943 } else {944 runCatching {945 VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_A)946 }.getOrElse {947 VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)948 }949 }950 } catch (_: Exception) {951 VaultCrypto.zero(key!!)952 key = null953 return null954 }955 val payload = try {956 VaultCodec.decode(plaintext)957 } finally {958 VaultCrypto.zero(plaintext)959 }960 if (slot.version == LEGACY_ANDROID_SLOT_VERSION) {961 val migratedKey = migrateLegacyDuressSlot(slot, password, payload, key!!, epoch)962 ?: run {963 VaultCrypto.zero(key!!)964 key = null965 return null966 }967 if (migratedKey !== key) {968 VaultCrypto.zero(key!!)969 key = migratedKey970 }971 }972 DuressUnlock(key!!, payload, epoch).also { key = null }973 } catch (_: Exception) {974 key?.let(VaultCrypto::zero)975 null976 }977 }978979 980981982983984 private fun migrateLegacyDuressSlot(985 legacy: StoredVault,986 password: String,987 payload: VaultPayload,988 legacyKey: ByteArray,989 epoch: Long,990 ): ByteArray? {991 var salt: ByteArray? = null992 var migratedKey: ByteArray? = null993 var plaintext: ByteArray? = null994 var restoredLegacy = false995 var migrated = false996 try {997 salt = VaultCrypto.generateSalt()998 migratedKey = VaultCrypto.deriveKey(password, salt)999 plaintext = VaultCodec.encode(payload)1000 val next = StoredVault(1001 version = CURRENT_ANDROID_SLOT_VERSION,1002 salt = b64(salt),1003 blob = b64(VaultCrypto.encrypt(plaintext, migratedKey, VaultCrypto.AAD_SLOT_B)),1004 )1005 var priorA: StoredVault? = null1006 var priorB: String? = null1007 withSessionEpochCommit(epoch) {1008 priorA = store.loadSlotA()1009 priorB = store.loadSlotB()1010 if (store.loadDecoySlot() != legacy) return@withSessionEpochCommit false1011 if (!store.writeDecoySlot(next)) {1012 restoredLegacy = store.loadDecoySlot() == legacy1013 return@withSessionEpochCommit restoredLegacy1014 }1015 val reopened = store.loadDecoySlot()1016 val verified = reopened?.version == CURRENT_ANDROID_SLOT_VERSION && runCatching {1017 val reopenedPlaintext = VaultCrypto.decrypt(unb64(reopened.blob), migratedKey!!, VaultCrypto.AAD_SLOT_B)1018 try { VaultCodec.decode(reopenedPlaintext) == payload } finally { VaultCrypto.zero(reopenedPlaintext) }1019 }.getOrDefault(false)1020 if (verified) {1021 migrated = true1022 return@withSessionEpochCommit true1023 }1024 val restored = priorA != null && store.restoreVaultTriad(priorA!!, priorB, legacy)1025 restoredLegacy = restored && store.loadSlotA() == priorA && store.loadSlotB() == priorB && store.loadDecoySlot() == legacy1026 restoredLegacy1027 }1028 if (migrated) {1029 VaultCrypto.zero(legacyKey)1030 return migratedKey.also { migratedKey = null }1031 }1032 if (restoredLegacy) return legacyKey1033 } catch (_: Exception) {1034 1035 1036 }1037 if (!restoredLegacy) runCatching { store.loadDecoySlot() == legacy }1038 migratedKey?.let(VaultCrypto::zero)1039 return if (restoredLegacy) legacyKey else null1040 }10411042 1043 suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {1044 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")1045 if (currentEpoch() != unlock.epoch) {1046 VaultCrypto.zero(key)1047 return@withLock UnlockResult.Error("stale_unlock")1048 }1049 return try {1050 val adopted = mutateIfCurrentEpoch(unlock.epoch) {1051 derivedKey = key1052 decoyMode = true1053 entryList = unlock.payload.entries.toMutableList()1054 authenticatedDuressConfigured = false1055 _duressConfigured.value = false1056 recoveryWordHash = unlock.payload.recoveryWordHash1057 recoveryWordsSet = unlock.payload.recoveryWordsSet1058 sessionDataAvailable = true1059 rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)1060 else VaultCrypto.generateRootKey()1061 1062 1063 1064 1065 1066 _settings.value = VaultSettings()1067 publish()1068 _isUnlocked.value = true1069 sessionEpoch = nextSessionEpoch(sessionEpoch)1070 }1071 if (adopted == null) {1072 VaultCrypto.zero(key)1073 UnlockResult.Error("stale_unlock")1074 } else {1075 UnlockResult.Success1076 }1077 } catch (e: Exception) {1078 1079 1080 1081 1082 mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }1083 VaultCrypto.zero(key)1084 UnlockResult.Error(e.message ?: "decoy_unlock_failed")1085 }1086 }10871088 1089 fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()10901091 109210931094109510961097 suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {1098 1099 val expectedEpoch = mutateState {1100 if (derivedKey != null && !decoyMode) sessionEpoch else null1101 } ?: return false1102 1103 1104 tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }1105 var key: ByteArray? = null1106 var basePlaintext: ByteArray? = null1107 return try {1108 val salt = VaultCrypto.generateSalt()1109 key = VaultCrypto.deriveKey(duressPassphrase, salt)1110 1111 val decoyRoot = VaultCrypto.generateRootKey()1112 val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }1113 val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)1114 basePlaintext = VaultCodec.encode(decoyPayload)1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 val slotA = store.loadSlotA()1125 val targetSize = slotA?.let(::matchingCiphertextLength) ?: 01126 val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!1127 val blob = try {1128 b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_B))1129 } finally {1130 VaultCrypto.zero(plaintext)1131 1132 1133 if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)1134 basePlaintext = null1135 key?.let(VaultCrypto::zero)1136 key = null1137 }1138 beforeDurableCommit()1139 val ok = withEpochCommit(expectedEpoch) {1140 store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob))1141 } ?: false1142 if (!ok) return false1143 val marked = mutateIfCurrentEpoch(expectedEpoch) {1144 authenticatedDuressConfigured = true1145 _duressConfigured.value = true1146 true1147 } ?: false1148 if (!marked) return false1149 if (!runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1150 mutateIfCurrentEpoch(expectedEpoch) {1151 authenticatedDuressConfigured = false1152 _duressConfigured.value = false1153 }1154 runCatching { writeFakeDuressSlot(store.loadSlotA()!!) }1155 return false1156 }1157 true1158 } catch (_: Exception) {1159 false1160 } finally {1161 1162 1163 key?.let(VaultCrypto::zero)1164 basePlaintext?.let(VaultCrypto::zero)1165 }1166 }116711681169 117011711172117311741175117611771178 suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1179 if (!authenticatedDuressConfigured) return null1180 val slot = store.loadDecoySlot() ?: return null1181 return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1182 }11831184 1185118611871188118911901191 private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1192 1193 1194 1195 1196 1197 var salt: ByteArray? = null1198 var blob: ByteArray? = null1199 var nonce: ByteArray? = null1200 var ctAndTag: ByteArray? = null1201 var ct: ByteArray? = null1202 var tag: ByteArray? = null1203 try {1204 salt = unb64(slot.salt)1205 blob = unb64(slot.blob)1206 nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1207 ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1208 ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1209 tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1210 val obj = JsonObject(mapOf(1211 "version" to JsonPrimitive(1),1212 "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1213 "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1214 "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1215 "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1216 ))1217 return obj.toString()1218 } finally {1219 salt?.let(VaultCrypto::zero)1220 blob?.let(VaultCrypto::zero)1221 nonce?.let(VaultCrypto::zero)1222 ctAndTag?.let(VaultCrypto::zero)1223 ct?.let(VaultCrypto::zero)1224 tag?.let(VaultCrypto::zero)1225 }1226 }12271228 122912301231 suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1232 val b = BrowserSlot.parse(json) ?: return false1233 if (b.version != 1) return false1234 val expectedEpoch = currentEpoch()1235 var salt: ByteArray? = null1236 var nonce: ByteArray? = null1237 var ct: ByteArray? = null1238 var tag: ByteArray? = null1239 var blob: ByteArray? = null1240 try {1241 salt = unhex(b.salt)1242 nonce = unhex(b.nonce)1243 ct = unhex(b.ciphertext)1244 tag = unhex(b.tag)1245 blob = ByteArray(nonce.size + ct.size + tag.size).also {1246 System.arraycopy(nonce, 0, it, 0, nonce.size)1247 System.arraycopy(ct, 0, it, nonce.size, ct.size)1248 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1249 }1250 val stored = StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))1251 val priorA = store.loadSlotA() ?: return false1252 val priorB = store.loadSlotB()1253 val priorD = store.loadDecoySlot() ?: return false1254 beforeDurableCommit()1255 val committed = withEpochCommit(expectedEpoch) {1256 if (!store.writeDecoySlot(stored)) return@withEpochCommit false1257 authenticatedDuressConfigured = true1258 _duressConfigured.value = true1259 true1260 } ?: false1261 if (!committed) return false1262 if (runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1263 true1264 } else {1265 mutateIfCurrentEpoch(expectedEpoch) {1266 authenticatedDuressConfigured = false1267 _duressConfigured.value = false1268 }1269 withEpochCommit(expectedEpoch) { store.restoreVaultTriad(priorA, priorB, priorD) }1270 false1271 }1272 } catch (_: Exception) {1273 false1274 } finally {1275 salt?.let(VaultCrypto::zero)1276 nonce?.let(VaultCrypto::zero)1277 ct?.let(VaultCrypto::zero)1278 tag?.let(VaultCrypto::zero)1279 blob?.let(VaultCrypto::zero)1280 }1281 }12821283 1284 suspend fun clearDuress(): Boolean = mutex.withLock {1285 1286 1287 1288 1289 val expectedEpoch = currentEpoch()1290 val replaced = withEpochCommit(expectedEpoch) {1291 store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1292 ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1293 } ?: false1294 if (!replaced) return@withLock false1295 1296 1297 if (!isSessionEpochCurrent(expectedEpoch)) return false1298 val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1299 if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) {1300 authenticatedDuressConfigured = false1301 _duressConfigured.value = false1302 } != null) {1303 runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1304 }1305 true1306 }13071308 1309 private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1310 var current: Throwable? = error1311 while (current != null) {1312 if (current is javax.crypto.AEADBadTagException) return true1313 1314 1315 1316 1317 if (current is javax.crypto.BadPaddingException) return true1318 current = current.cause1319 }1320 return false1321 }13221323 1324 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1325 val expectedEpoch = currentEpoch()1326 val slotA = try {1327 store.loadSlotA()1328 } catch (_: Exception) {1329 return@withLock UnlockResult.Error("unlock_key_storage_failed")1330 } ?: return@withLock UnlockResult.Error("no_vault")1331 1332 1333 1334 1335 var stagedKey: ByteArray? = key.copyOf()1336 return try {1337 val encrypted = try {1338 unb64(slotA.blob)1339 } catch (_: Exception) {1340 return@withLock UnlockResult.Error("invalid_vault_blob")1341 }1342 1343 1344 1345 1346 if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1347 return@withLock UnlockResult.Error("invalid_vault_blob")1348 }1349 val plaintext = try {1350 VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1351 } catch (e: Exception) {1352 if (isGcmAuthenticationFailure(e)) {1353 return@withLock UnlockResult.WrongPassword1354 }1355 return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1356 }1357 val payload = try {1358 VaultCodec.decode(plaintext)1359 } catch (_: Exception) {1360 return@withLock UnlockResult.Error("invalid_vault_payload")1361 } finally {1362 VaultCrypto.zero(plaintext)1363 }1364 val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1365 val result = adoptSlotA(candidate, payload, expectedEpoch)1366 if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1367 result1368 } finally {1369 stagedKey?.let(VaultCrypto::zero)1370 }1371 }13721373 fun lock() {1374 1375 1376 1377 1378 if (mutex.tryLock()) {1379 try {1380 runCatching { LockedSyncSpoolHooks.refresh(this) }1381 } finally {1382 mutex.unlock()1383 }1384 }1385 1386 1387 1388 1389 1390 1391 stateLock.lock()1392 try {1393 sessionEpoch = nextSessionEpoch(sessionEpoch)1394 clearSessionStateLocked()1395 _uiGateLocked.value = false1396 } finally {1397 stateLock.unlock()1398 }1399 }14001401 1402140314041405140614071408 fun lockUiGate() {1409 if (_isUnlocked.value) _uiGateLocked.value = true1410 }14111412 1413 fun clearUiGate() {1414 _uiGateLocked.value = false1415 }14161417 @Volatile private var suppressNextBackgroundLockUntil: Long = 0L14181419 1420 1421 @VisibleForTesting1422 internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }14231424 142514261427142814291430143114321433143414351436 fun expectTransientBackground() {1437 suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1438 }14391440 14411442144314441445 fun consumeTransientBackgroundSuppression(): Boolean {1446 val until = suppressNextBackgroundLockUntil1447 val active = until != 0L && nowMs() < until1448 suppressNextBackgroundLockUntil = 0L1449 return active1450 }14511452 14531454 14551456145714581459 14601461146214631464146514661467146814691470 1471 1472 1473 1474 1475 internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)14761477 internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1478 if (decoyMode || !_isUnlocked.value) null1479 else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1480 }14811482 internal fun isSessionEpochCurrent(epoch: Long): Boolean =1483 mutateState { sessionEpoch == epoch }14841485 internal fun unlockedSessionEpoch(): Long? = mutateState {1486 if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1487 }14881489 fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key14901491 149214931494149514961497149814991500 fun sessionRootKey(): ByteArray? = mutateState {1501 if (!sessionDataAvailable) null else rootKey?.copyOf()1502 }15031504 15051506 fun syncVaultId(): String? = mutateState {1507 if (decoyMode || !_isUnlocked.value) null1508 else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1509 }15101511 15121513151415151516 suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1517 val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1518 ?: return false1519 installRootKey(generateRecoverableRootKey(), expectedEpoch)1520 }15211522 15231524152515261527152815291530153115321533153415351536153715381539 suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1540 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1541 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1542 }1543 val expectedEpoch = mutateState {1544 when {1545 derivedKey == null -> null1546 decoyMode -> Long.MIN_VALUE1547 else -> sessionEpoch1548 }1549 }1550 if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1551 if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1552 if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")15531554 val incoming = hexToRootKey(rootKeyHex)1555 if (incoming.size != VaultCrypto.KEY_SIZE) {1556 VaultCrypto.zero(incoming)1557 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1558 }1559 1560 1561 1562 val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1563 if (!roundTrips) {1564 VaultCrypto.zero(incoming)1565 return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1566 }15671568 val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1569 return if (installRootKey(incoming, expectedEpoch)) {1570 AdoptVaultResult.Success(vaultId)1571 } else {1572 AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1573 }1574 }15751576 15771578157915801581 fun previewRecoveryWords(rootKeyHex: String): List<String>? {1582 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1583 val bytes = hexToRootKey(rootKeyHex)1584 return try {1585 val words = rootKeyToWords(bytes)1586 if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1587 } catch (_: Exception) {1588 null1589 } finally {1590 VaultCrypto.zero(bytes)1591 }1592 }15931594 15951596159715981599 private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1600 1601 1602 1603 1604 1605 1606 data class Snapshot(1607 val key: ByteArray,1608 val priorRootKey: ByteArray,1609 val priorRecoveryHash: String?,1610 val priorRecoverySet: Boolean,1611 )1612 val snap = mutateIfCurrentEpoch(expectedEpoch) {1613 val k = derivedKey ?: return@mutateIfCurrentEpoch null1614 if (decoyMode) return@mutateIfCurrentEpoch null1615 val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1616 Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1617 } ?: run {1618 VaultCrypto.zero(nextRootKey)1619 return false1620 }1621 val priorSlot = store.loadSlotA() ?: run {1622 VaultCrypto.zero(snap.key)1623 VaultCrypto.zero(snap.priorRootKey)1624 VaultCrypto.zero(nextRootKey)1625 return false1626 }1627 val nextWords = rootKeyToWords(nextRootKey)16281629 return try {1630 beforeDurableCommit()1631 if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1632 if (mutateIfCurrentEpoch(expectedEpoch) {1633 rootKey = nextRootKey1634 recoveryWordHash = recoveryWordsHash(nextWords)1635 recoveryWordsSet = false1636 } == null) throw IllegalStateException("stale_root_rotation")16371638 val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1639 ?: throw IllegalStateException("recovery_escrow_failed")1640 val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1641 ?: throw IllegalStateException("root_escrow_failed")1642 val plaintext = VaultCodec.encode(currentPayload())1643 val blob = try {1644 b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1645 } finally {1646 VaultCrypto.zero(plaintext)1647 }1648 val nextSlot = priorSlot.copy(1649 blob = blob,1650 recoveryEscrow = nextRecoveryEscrow,1651 rootKeyEscrow = nextRootKeyEscrow,1652 )1653 val committed = withEpochCommit(expectedEpoch) {1654 if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1655 try {1656 if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1657 1658 1659 if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1660 store.stampLocalMutation()1661 } catch (_: Exception) {1662 store.writeSlotA(priorSlot)1663 return@withEpochCommit false1664 }1665 true1666 } ?: false1667 if (!committed) throw IllegalStateException("storage_write_failed")1668 mutateIfCurrentEpoch(expectedEpoch) { publish() }1669 true1670 } catch (_: Exception) {1671 val restored = mutateIfCurrentEpoch(expectedEpoch) {1672 rootKey?.let(VaultCrypto::zero)1673 rootKey = snap.priorRootKey.copyOf()1674 recoveryWordHash = snap.priorRecoveryHash1675 recoveryWordsSet = snap.priorRecoverySet1676 }1677 if (restored != null) {1678 withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1679 }1680 false1681 } finally {1682 VaultCrypto.zero(snap.key)1683 VaultCrypto.zero(snap.priorRootKey)1684 1685 1686 1687 val stillOwnedBySession = mutateState {1688 sessionEpoch == expectedEpoch && rootKey === nextRootKey1689 }1690 if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1691 }1692 }16931694 16951696169716981699 fun currentVaultKey(): ByteArray? = mutateState {1700 if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1701 }17021703 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1704 val expectedEpoch = currentEpoch()1705 val slotA = store.loadSlotA() ?: return false1706 var oldKey: ByteArray? = null1707 var newKey: ByteArray? = null1708 var plaintext: ByteArray? = null1709 return try {1710 oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1711 1712 1713 1714 1715 val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1716 val payload = try {1717 VaultCodec.decode(decrypted)1718 } finally {1719 VaultCrypto.zero(decrypted)1720 }1721 val newSalt = VaultCrypto.generateSalt()1722 newKey = VaultCrypto.deriveKey(newPassword, newSalt)1723 1724 plaintext = VaultCodec.encode(payload)1725 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1726 1727 1728 1729 1730 1731 1732 1733 val next = StoredVault(1734 version = slotA.version,1735 salt = b64(newSalt),1736 blob = blob,1737 recoveryEscrow = slotA.recoveryEscrow,1738 rootKeyEscrow = slotA.rootKeyEscrow,1739 )1740 1741 1742 1743 1744 val priorB = store.loadSlotB()1745 if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1746 1747 1748 1749 if (mutateIfCurrentEpoch(expectedEpoch) {1750 oldKey?.let(VaultCrypto::zero); oldKey = null1751 derivedKey?.let(VaultCrypto::zero)1752 derivedKey = newKey; newKey = null1753 } == null) return false1754 VaultKeyRotationHooks.onRotated()1755 true1756 } catch (_: Exception) {1757 false1758 } finally {1759 oldKey?.let(VaultCrypto::zero)1760 newKey?.let(VaultCrypto::zero)1761 plaintext?.let(VaultCrypto::zero)1762 }1763 }17641765 1766176717681769 suspend fun destroyVault(): Boolean = mutex.withLock {1770 lock()1771 val cleared = store.clearVault()1772 store.clearDecoySlot()1773 cleared1774 }17751776 17771778 1779178017811782178317841785178617871788178917901791 private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")17921793 private fun String?.normalizedEntryId(): String =1794 if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()17951796 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1797 val epoch = requireUnlocked()1798 val stamp = VaultCrypto.monotonicEntryTimestamp()1799 val now = System.currentTimeMillis()1800 val entry = withDerivedLast4(draft.copy(1801 id = draft.id.normalizedEntryId(),1802 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1803 modifiedAt = stamp,1804 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1805 ))1806 1807 1808 val rollback = mutateCurrentSession(epoch) {1809 val r = entryList.toMutableList()1810 entryList.add(entry)1811 r1812 } ?: throw IllegalStateException("vault_locked")1813 persistOrRollback(rollback, epoch)1814 entry1815 }18161817 181818191820182118221823182418251826 suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1827 val epoch = requireUnlocked()1828 if (drafts.isEmpty()) return 01829 val now = System.currentTimeMillis()1830 val ready = drafts.map { draft ->1831 val stamp = VaultCrypto.monotonicEntryTimestamp()1832 withDerivedLast4(1833 draft.copy(1834 id = draft.id.normalizedEntryId(),1835 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1836 modifiedAt = stamp,1837 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1838 ),1839 )1840 }1841 1842 val rollback = mutateCurrentSession(epoch) {1843 val r = entryList.toMutableList()1844 entryList.addAll(ready)1845 r1846 } ?: throw IllegalStateException("vault_locked")1847 persistOrRollback(rollback, epoch)1848 return drafts.size1849 }18501851 1852185318541855185618571858185918601861186218631864 suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1865 val epoch = requireUnlocked()1866 val now = System.currentTimeMillis()1867 val ready = newEntries.map { draft ->1868 val stamp = VaultCrypto.monotonicEntryTimestamp()1869 withDerivedLast4(1870 draft.copy(1871 id = draft.id.normalizedEntryId(),1872 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1873 modifiedAt = stamp,1874 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1875 ),1876 )1877 }1878 1879 1880 1881 1882 1883 1884 val incomingIds = ready.map { it.id }.toHashSet()1885 val rollback = mutateCurrentSession(epoch) {1886 val r = entryList.toMutableList()1887 val replaced = entryList.map { entry ->1888 if (entry.deletedAt != null) return@map entry1889 if (entry.id in incomingIds) return@map null1890 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1891 entry.copy(deletedAt = stamp, modifiedAt = stamp)1892 }.filterNotNull()1893 entryList = (replaced + ready).toMutableList()1894 r1895 } ?: throw IllegalStateException("vault_locked")1896 persistOrRollback(rollback, epoch)1897 return ready.size1898 }18991900 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1901 val epoch = requireUnlocked()1902 1903 1904 1905 1906 val prepared = mutateCurrentSession(epoch) {1907 val idx = entryList.indexOfFirst { it.id == patch.id }1908 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1909 val current = entryList[idx]1910 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1911 1912 val passwordChanged = patch.password != null && patch.password != current.password1913 1914 1915 1916 1917 1918 1919 val priorPassword = current.password1920 val shouldCapture = passwordChanged &&1921 !priorPassword.isNullOrEmpty() &&1922 current.passwordHistory?.firstOrNull()?.password != priorPassword1923 val nextHistory = if (shouldCapture) {1924 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1925 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1926 } else {1927 current.passwordHistory1928 }1929 val updated = withDerivedLast4(patch.copy(1930 createdAt = current.createdAt,1931 modifiedAt = stamp,1932 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1933 passwordHistory = nextHistory,1934 ))1935 val rollback = entryList.toMutableList()1936 entryList[idx] = updated1937 updated to rollback1938 } ?: throw IllegalStateException("vault_locked")1939 val (updated, rollback) = prepared1940 persistOrRollback(rollback, epoch)1941 updated1942 }19431944 1945 suspend fun deleteEntry(id: String) = mutex.withLock {1946 val epoch = requireUnlocked()1947 1948 1949 val rollback = mutateCurrentSession(epoch) {1950 val idx = entryList.indexOfFirst { it.id == id }1951 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1952 val current = entryList[idx]1953 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1954 val prior = entryList.toMutableList()1955 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1956 prior1957 } ?: throw IllegalStateException("vault_locked")1958 persistOrRollback(rollback, epoch)1959 }19601961 suspend fun restoreEntry(id: String) = mutex.withLock {1962 val epoch = requireUnlocked()1963 val rollback = mutateCurrentSession(epoch) {1964 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1965 if (idx == -1) throw IllegalStateException("deleted entry not found")1966 val current = entryList[idx]1967 val prior = entryList.toMutableList()1968 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))1969 prior1970 } ?: throw IllegalStateException("vault_locked")1971 persistOrRollback(rollback, epoch)1972 }19731974 1975 suspend fun purgeEntry(id: String) = mutex.withLock {1976 val epoch = requireUnlocked()1977 val rollback = mutateCurrentSession(epoch) {1978 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1979 if (idx == -1) throw IllegalStateException("deleted entry not found")1980 val prior = entryList.toMutableList()1981 entryList.removeAt(idx)1982 prior1983 } ?: throw IllegalStateException("vault_locked")1984 persistOrRollback(rollback, epoch)1985 }19861987 1988 suspend fun purgeDeletedEntries(): Int = mutex.withLock {1989 val epoch = requireUnlocked()1990 1991 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1992 val r = mutateCurrentSession(epoch) {1993 val rollback = entryList.toMutableList()1994 val before = entryList.size1995 entryList.removeAll { it.deletedAt != null }1996 R(rollback, before - entryList.size)1997 } ?: throw IllegalStateException("vault_locked")1998 if (r.removed > 0) persistOrRollback(r.rollback, epoch)1999 r.removed2000 }20012002 2003 suspend fun countDuplicateEntries(): Int = mutex.withLock {2004 val epoch = requireUnlocked()2005 2006 2007 mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }2008 ?: throw IllegalStateException("vault_locked")2009 }20102011 20122013201420152016 suspend fun deduplicateEntries(): Int = mutex.withLock {2017 val epoch = requireUnlocked()2018 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2019 val ready = mutateCurrentSession(epoch) {2020 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")2021 val active = entryList.filter { it.deletedAt == null }2022 val keepIds = mutableSetOf<String>()2023 active.groupBy { it.duplicateKey() }.values.forEach { group ->2024 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id2025 }2026 val rollback = entryList.toMutableList()2027 var removed = 02028 entryList = entryList.map { entry ->2029 if (entry.deletedAt == null && entry.id !in keepIds) {2030 removed++2031 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)2032 entry.copy(deletedAt = stamp, modifiedAt = stamp)2033 } else {2034 entry2035 }2036 }.toMutableList()2037 R(rollback, removed)2038 } ?: throw IllegalStateException("vault_locked")2039 if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)2040 ready.removed2041 }20422043 fun getEntries(): List<VaultEntry> = mutateState {2044 if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }2045 }2046 fun getEntry(id: String): VaultEntry? = mutateState {2047 if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }2048 }2049 fun getDeletedEntries(): List<VaultEntry> = mutateState {2050 if (!sessionDataAvailable) emptyList()2051 else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }2052 }20532054 2055 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {2056 return mutateState {2057 if (!sessionDataAvailable) return@mutateState emptyList()2058 val active = entryList.filter { it.deletedAt == null }2059 if (tagFilter == null) return@mutateState active2060 val needle = tagFilter.trim().lowercase()2061 active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }2062 }2063 }20642065 2066 fun getDistinctTags(): List<String> = mutateState {2067 if (!sessionDataAvailable) return@mutateState emptyList()2068 entryList.asSequence()2069 .filter { it.deletedAt == null }2070 .flatMap { it.tags?.asSequence() ?: emptySequence() }2071 .map { it.trim().lowercase() }2072 .filter { it.isNotEmpty() }2073 .distinct()2074 .sorted()2075 .toList()2076 }20772078 207920802081208220832084 fun getDistinctFieldValues(field: String): List<String> {2085 val select: (VaultEntry) -> String? = when (field) {2086 "username" -> { e -> e.username }2087 "email" -> { e -> e.email }2088 else -> return emptyList()2089 }2090 return mutateState {2091 if (!sessionDataAvailable) return@mutateState emptyList()2092 entryList.asSequence()2093 .filter { it.deletedAt == null }2094 .mapNotNull { select(it)?.trim() }2095 .filter { it.isNotEmpty() }2096 .groupingBy { it.lowercase() }2097 .aggregate { _, acc: Pair<String, Int>?, value, _ ->2098 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)2099 }2100 .values2101 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })2102 .map { it.first }2103 }2104 }21052106 fun getTombstones(): List<Tombstone> = mutateState {2107 if (!sessionDataAvailable) emptyList()2108 else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }2109 }2110 fun getVaultVersion(): Long = store.version()2111 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots21122113 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {2114 val expectedEpoch = currentEpoch()2115 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false2116 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false2117 2118 2119 val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)2120 val priorA = store.loadSlotA()2121 val priorB = store.loadSlotB()2122 val priorD = store.loadDecoySlot()2123 2124 2125 2126 2127 2128 val priorHistory = store.loadVaultHistory()2129 2130 2131 2132 2133 beforeDurableCommit()2134 if (!takeVaultSnapshot("restore", expectedEpoch)) {2135 return false2136 }2137 2138 2139 2140 val nextD: StoredVault = restoredD ?: run {2141 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 162142 val fakeBlob = ByteArray(target).also(rng::nextBytes)2143 val fakeSalt = VaultCrypto.generateSalt()2144 StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob))2145 }2146 if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2147 withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2148 return false2149 }2150 lock()2151 true2152 }21532154 21552156215721582159216021612162216321642165 private fun commitRestoreAtomic(2166 nextA: StoredVault,2167 nextB: String,2168 nextD: StoredVault,2169 priorA: StoredVault?,2170 priorB: String?,2171 priorD: StoredVault?,2172 expectedEpoch: Long,2173 ): Boolean {2174 return withEpochCommit(expectedEpoch) {2175 if (!store.writeSlotA(nextA)) return@withEpochCommit false2176 2177 2178 2179 try {2180 if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2181 2182 2183 if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2184 store.stampLocalMutation()2185 } catch (_: Exception) {2186 reportRollbackFailures(slotRollback.restoreTriad(priorA, priorB, priorD))2187 return@withEpochCommit false2188 }2189 true2190 } ?: false2191 }21922193 21942195 21962197219821992200 suspend fun applyMergedRemoteEntries(2201 remoteEntries: List<VaultEntry>,2202 remoteTombstones: List<Tombstone>,2203 expectedEpoch: Long? = null,2204 ): Int = mutex.withLock {2205 val epoch = expectedEpoch ?: requireUnlocked()2206 if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02207 2208 2209 2210 2211 2212 val mergeNow = System.currentTimeMillis()2213 val clamped = remoteEntries.mapNotNull { entry ->2214 2215 2216 2217 SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2218 modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2219 deletedAt = entry.deletedAt?.let {2220 SyncLimits.clampSyncTimestamp(it, mergeNow)2221 },2222 )2223 }2224 val tombMap = remoteTombstones.associate {2225 it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2226 }2227 2228 2229 val applied = mutateCurrentSession(epoch) {2230 var n = 02231 val byId = entryList.associateBy { it.id }.toMutableMap()22322233 for (remote in clamped) {2234 val tomb = tombMap[remote.id]2235 if (tomb != null && tomb >= remote.modifiedAt) continue2236 val local = byId[remote.id]2237 if (local == null) {2238 entryList.add(remote); byId[remote.id] = remote; n++2239 } else if (remote.modifiedAt > local.modifiedAt) {2240 val i = entryList.indexOfFirst { it.id == local.id }2241 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2242 }2243 }22442245 for ((id, deletedAt) in tombMap) {2246 val local = byId[id] ?: continue2247 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2248 if (deletedAt < local.modifiedAt) continue2249 val i = entryList.indexOfFirst { it.id == id }2250 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2251 }2252 n2253 } ?: return@withLock 022542255 if (applied > 0) {2256 persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2257 mutateIfCurrentEpoch(epoch) { publish() }2258 runCatching { LockedSyncSpoolHooks.refresh(this) }2259 }2260 applied2261 }22622263 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2264 2265 2266 2267 2268 if (mutateState { decoyMode }) {2269 val decoyEpoch = requireUnlocked()2270 mutateCurrentSession(decoyEpoch) { _settings.value = settings }2271 ?: throw IllegalStateException("vault_locked")2272 return@withLock2273 }2274 2275 2276 2277 val epoch = requireUnlocked()2278 val prior = mutateCurrentSession(epoch) {2279 val old = _settings.value2280 _settings.value = settings2281 old2282 } ?: throw IllegalStateException("vault_locked")22832284 val committed = try {2285 beforeDurableCommit()2286 2287 2288 2289 withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2290 } catch (_: Exception) {2291 false2292 }2293 if (!committed) {2294 2295 2296 2297 mutateIfCurrentEpoch(epoch) { _settings.value = prior }2298 throw IllegalStateException("settings_write_failed")2299 }2300 }23012302 23032304 2305 fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }23062307 23082309231023112312 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2313 val epoch = requireUnlocked()2314 2315 2316 2317 2318 2319 2320 val prior = mutateCurrentSession(epoch) {2321 val priorPair = recoveryWordHash to recoveryWordsSet2322 recoveryWordHash = recoveryWordsHash(words)2323 recoveryWordsSet = true2324 priorPair2325 } ?: return@withLock false2326 2327 2328 2329 2330 val persisted = runCatching {2331 persistSlotAWithEscrows(2332 buildRecoveryEscrow(words),2333 buildRootKeyEscrow(words),2334 expectedEpoch = epoch,2335 )2336 }.getOrDefault(false)2337 if (!persisted) {2338 mutateIfCurrentEpoch(epoch) {2339 recoveryWordHash = prior.first2340 recoveryWordsSet = prior.second2341 }2342 }2343 persisted2344 }23452346 2347 fun verifyRecoveryWords(words: List<String>): Boolean {2348 return mutateState {2349 val stored = recoveryWordHash ?: return@mutateState false2350 MessageDigest.isEqual(2351 stored.toByteArray(Charsets.UTF_8),2352 recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2353 )2354 }2355 }23562357 23582359 2360 fun hasRecoveryEscrow(): Boolean =2361 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false23622363 23642365236623672368 private fun ensureRecoveryEscrow() {2369 if (hasRecoveryEscrow()) return2370 val rk = mutateState { rootKey?.copyOf() } ?: return2371 runCatching {2372 val words = rootKeyToWords(rk)2373 val escrow = buildRecoveryEscrow(words)2374 val rkEscrow = buildRootKeyEscrow(words)2375 if (escrow != null || rkEscrow != null) {2376 val prior = store.loadSlotA() ?: return@runCatching2377 store.writeSlotA(prior.copy(2378 recoveryEscrow = escrow ?: prior.recoveryEscrow,2379 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2380 ))2381 mutateState {2382 recoveryWordHash = recoveryWordsHash(words)2383 recoveryWordsSet = true2384 }2385 }2386 }.also { VaultCrypto.zero(rk) }2387 }23882389 239023912392239323942395239623972398239924002401 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2402 val expectedEpoch = currentEpoch()2403 val slotA = store.loadSlotA() ?: return false2404 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false24052406 2407 2408 val fullEscrow = slotA.recoveryEscrow2409 if (fullEscrow != null) {2410 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2411 if (material != null) {2412 var keyBytes: ByteArray? = null2413 var plaintext: ByteArray? = null2414 var candidateRoot: ByteArray? = null2415 var stateCommitStarted = false2416 try {2417 keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2418 plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2419 val payload = VaultCodec.decode(plaintext)2420 2421 2422 2423 2424 val candidateSettings = store.loadSettings()2425 candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2426 val decodedRoot = unb64(payload.rootKeyB64)2427 if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2428 2429 2430 2431 VaultCrypto.zero(decodedRoot)2432 throw IllegalArgumentException("invalid recovery root key")2433 }2434 decodedRoot2435 } else {2436 generateRecoverableRootKey()2437 }2438 stateCommitStarted = true2439 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2440 clearSessionStateLocked()2441 entryList = payload.entries.toMutableList()2442 authenticatedDuressConfigured = payload.duressConfigured2443 _duressConfigured.value = payload.duressConfigured2444 recoveryWordHash = payload.recoveryWordHash2445 recoveryWordsSet = payload.recoveryWordsSet2446 rootKey = candidateRoot2447 candidateRoot = null2448 _settings.value = candidateSettings2449 publish()2450 2451 2452 sessionDataAvailable = true2453 _isUnlocked.value = false2454 true2455 }2456 if (adopted == true) return@withLock true2457 } catch (_: Exception) {2458 2459 2460 2461 2462 if (stateCommitStarted) {2463 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2464 }2465 } finally {2466 plaintext?.let(VaultCrypto::zero)2467 VaultCrypto.zero(material)2468 keyBytes?.let(VaultCrypto::zero)2469 candidateRoot?.let(VaultCrypto::zero)2470 }2471 }2472 }24732474 2475 2476 2477 val rootEscrow = slotA.rootKeyEscrow2478 if (rootEscrow != null) {2479 var candidateRoot: ByteArray? = null2480 var stateCommitStarted = false2481 try {2482 candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2483 require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2484 val candidateSettings = store.loadSettings()2485 stateCommitStarted = true2486 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2487 clearSessionStateLocked()2488 entryList = mutableListOf()2489 authenticatedDuressConfigured = false2490 _duressConfigured.value = false2491 recoveryWordHash = recoveryWordsHash(words)2492 recoveryWordsSet = true2493 rootKey = candidateRoot2494 candidateRoot = null2495 _settings.value = candidateSettings2496 publish()2497 sessionDataAvailable = true2498 _isUnlocked.value = false2499 true2500 }2501 if (adopted == true) return@withLock true2502 } catch (_: Exception) {2503 if (stateCommitStarted) {2504 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2505 }2506 } finally {2507 candidateRoot?.let(VaultCrypto::zero)2508 }2509 }2510 return false2511 }25122513 251425152516251725182519252025212522 suspend fun resetPasswordWithRecoveryWords(2523 words: List<String>,2524 newPassword: String,2525 ): Boolean = mutex.withLock {2526 val expectedEpoch = currentEpoch()2527 2528 2529 2530 if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2531 val priorA = store.loadSlotA() ?: return false2532 var newKey: ByteArray? = null2533 var plaintext: ByteArray? = null2534 return try {2535 val newSalt = VaultCrypto.generateSalt()2536 newKey = VaultCrypto.deriveKey(newPassword, newSalt)2537 plaintext = VaultCodec.encode(currentPayload())2538 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2539 2540 2541 2542 val valid = words.size == 12 && findInvalidWords(words).isEmpty()2543 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2544 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2545 val next = StoredVault(2546 version = priorA.version,2547 salt = b64(newSalt),2548 blob = blob,2549 recoveryEscrow = freshRecovery,2550 rootKeyEscrow = freshRootKey,2551 )2552 2553 2554 2555 val priorB = store.loadSlotB()2556 if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2557 2558 2559 2560 if (mutateIfCurrentEpoch(expectedEpoch) {2561 derivedKey?.let(VaultCrypto::zero)2562 derivedKey = newKey; newKey = null2563 publish()2564 _isUnlocked.value = true2565 } == null) return false2566 VaultKeyRotationHooks.onRotated()2567 true2568 } catch (_: Exception) {2569 false2570 } finally {2571 newKey?.let(VaultCrypto::zero)2572 plaintext?.let(VaultCrypto::zero)2573 }2574 }25752576 257725782579258025812582 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2583 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2584 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2585 var keyBytes: ByteArray? = null2586 var plaintext: ByteArray? = null2587 return try {2588 val salt = VaultCrypto.generateSalt()2589 val recoveryKey = deriveRecoveryKey(material, salt)2590 keyBytes = recoveryKey.encoded2591 plaintext = VaultCodec.encode(currentPayload())2592 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2593 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2594 } finally {2595 VaultCrypto.zero(material)2596 keyBytes?.let(VaultCrypto::zero)2597 plaintext?.let(VaultCrypto::zero)2598 }2599 }26002601 26022603260426052606260726082609 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2610 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2611 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2612 val rk = mutateState { rootKey?.copyOf() } ?: run {2613 VaultCrypto.zero(material)2614 return null2615 }2616 var keyBytes: ByteArray? = null2617 var plaintext: ByteArray? = null2618 return try {2619 val salt = VaultCrypto.generateSalt()2620 val recoveryKey = deriveRecoveryKey(material, salt)2621 keyBytes = recoveryKey.encoded2622 plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2623 2624 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2625 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2626 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2627 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2628 val ct = ctTag.copyOfRange(0, ctTag.size - 16)2629 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2630 } finally {2631 VaultCrypto.zero(rk)2632 VaultCrypto.zero(material)2633 keyBytes?.let(VaultCrypto::zero)2634 plaintext?.let(VaultCrypto::zero)2635 }2636 }26372638 2639 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2640 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2641 var keyBytes: ByteArray? = null2642 var pt: ByteArray? = null2643 return try {2644 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2645 keyBytes = recoveryKey.encoded2646 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2647 pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2648 hexToRootKey(String(pt, Charsets.US_ASCII))2649 } catch (_: Exception) {2650 null2651 } finally {2652 2653 2654 2655 VaultCrypto.zero(material)2656 keyBytes?.let(VaultCrypto::zero)2657 pt?.let(VaultCrypto::zero)2658 }2659 }26602661 266226632664266526662667 private fun persistSlotAWithEscrows(2668 recoveryEscrow: RecoveryEscrow?,2669 rootKeyEscrow: RootKeyEscrow?,2670 expectedEpoch: Long? = null,2671 ): Boolean {2672 val snapshot = snapshotForPersist(expectedEpoch)2673 ?: throw IllegalStateException("vault_locked_or_stale")2674 if (snapshot.decoy) {2675 VaultCrypto.zero(snapshot.key)2676 return false2677 }2678 try {2679 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2680 val plaintext = VaultCodec.encode(snapshot.payload)2681 val blob = try {2682 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2683 } finally {2684 2685 2686 VaultCrypto.zero(plaintext)2687 }2688 val next = prior.copy(2689 blob = blob,2690 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2691 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2692 )2693 beforeDurableCommit()2694 return withEpochCommit(snapshot.epoch) {2695 if (!store.writeSlotA(next)) return@withEpochCommit false2696 try {2697 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2698 2699 2700 2701 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2702 } catch (e: Exception) {2703 store.writeSlotA(prior)2704 throw e2705 }2706 true2707 } ?: false2708 } finally {2709 VaultCrypto.zero(snapshot.key)2710 }2711 }27122713 27142715 private fun requireUnlocked(): Long {2716 2717 2718 2719 stateLock.lock()2720 try {2721 if (derivedKey == null) throw IllegalStateException("vault_locked")2722 return sessionEpoch2723 } finally {2724 stateLock.unlock()2725 }2726 }27272728 2729 private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null27302731 private fun countDuplicateEntriesLocked(): Int {2732 val seen = mutableMapOf<String, VaultEntry>()2733 var duplicates = 02734 for (entry in entryList.filter { it.deletedAt == null }) {2735 val key = entry.duplicateKey()2736 val existing = seen[key]2737 if (existing == null) {2738 seen[key] = entry2739 } else {2740 duplicates++2741 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2742 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2743 if (entryStamp > existingStamp) seen[key] = entry2744 }2745 }2746 return duplicates2747 }27482749 private fun VaultEntry.duplicateKey(): String {2750 if (type == "note") return "note|${title.lowercase()}"2751 val passkeyData = passkey2752 if (passkeyData != null) {2753 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2754 }2755 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2756 }27572758 275927602761276227632764 private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2765 val epoch = expectedEpoch ?: currentEpoch()2766 if (mutateIfCurrentEpoch(epoch) { true } != true) return false2767 val slotA = store.loadSlotA() ?: return false2768 val vaultA = VaultCodec.encodeSlot(slotA)2769 val vaultB = store.loadSlotB() ?: slotA.blob2770 2771 2772 2773 2774 2775 val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2776 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162777 val fakeBlob = ByteArray(target).also(rng::nextBytes)2778 val fakeSalt = VaultCrypto.generateSalt()2779 VaultCodec.encodeSlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2780 }2781 val history = store.loadVaultHistory()2782 val latest = history.snapshots.firstOrNull()2783 if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2784 val entryCount = mutateIfCurrentEpoch(epoch) {2785 if (derivedKey != null && !decoyMode) {2786 bucketEntryCount(entryList.count { it.deletedAt == null })2787 } else {2788 null2789 }2790 } ?: return false2791 return try {2792 val snapshot = VaultSnapshot(2793 id = UUID.randomUUID().toString(),2794 savedAt = System.currentTimeMillis(),2795 reason = reason,2796 vault_a = vaultA,2797 vault_b = vaultB,2798 vault_d = vaultD,2799 entryCount = entryCount,2800 )2801 2802 2803 2804 withEpochCommit(epoch) {2805 store.writeVaultHistory(2806 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2807 )2808 } ?: false2809 } catch (_: Exception) {2810 false2811 }2812 }28132814 private fun bucketEntryCount(n: Int): Int = when {2815 n <= 0 -> 02816 n <= 10 -> 102817 n <= 25 -> 252818 n <= 50 -> 502819 n <= 100 -> 1002820 n <= 250 -> 2502821 n <= 500 -> 5002822 else -> ((n + 499) / 500) * 5002823 }28242825 282628272828282928302831283228332834 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2835 if (!entry.isCard()) return entry2836 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2837 val derived = if (digits.length >= 4) digits.takeLast(4) else null2838 return entry.copy(last4 = derived ?: entry.last4)2839 }28402841 284228432844284528462847 private fun autoPurgeExpiredTrash() {2848 val days = _settings.value.trashRetentionDays ?: return2849 if (days <= 0) return2850 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2851 val before = entryList.size2852 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2853 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2854 }28552856 285728582859286028612862 private fun consolidatePasskeyEntries() {2863 val passkeyOnly = entryList.filter { entry ->2864 entry.deletedAt == null &&2865 entry.isLogin() &&2866 entry.password.isNullOrBlank() &&2867 !entry.rpId.isNullOrBlank() &&2868 !entry.credentialId.isNullOrBlank()2869 }2870 if (passkeyOnly.isEmpty()) return2871 var changed = false2872 val now = System.currentTimeMillis()2873 for (pkEntry in passkeyOnly) {2874 val rpId = pkEntry.rpId ?: continue2875 val target = entryList.firstOrNull { candidate ->2876 candidate.deletedAt == null &&2877 candidate.id != pkEntry.id &&2878 candidate.isLogin() &&2879 candidate.passkey == null &&2880 candidate.credentialId.isNullOrBlank() &&2881 !candidate.password.isNullOrBlank() &&2882 listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2883 .any { com.peachpasswords.shared.extractDomain(it) == rpId }2884 } ?: continue2885 val idx = entryList.indexOfFirst { it.id == target.id }2886 if (idx < 0) continue2887 entryList[idx] = target.copy(2888 rpId = pkEntry.rpId,2889 rpName = pkEntry.rpName ?: target.rpName,2890 credentialId = pkEntry.credentialId,2891 publicKeyCose = pkEntry.publicKeyCose,2892 privateKeyJwk = pkEntry.privateKeyJwk,2893 userHandle = pkEntry.userHandle,2894 userName = pkEntry.userName,2895 userDisplayName = pkEntry.userDisplayName,2896 algorithm = pkEntry.algorithm,2897 signCount = pkEntry.signCount,2898 lastUsedAt = pkEntry.lastUsedAt,2899 modifiedAt = now,2900 )2901 2902 val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2903 if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2904 changed = true2905 }2906 if (changed) runCatching { persistSlotA(bumpVersion = false) }2907 }29082909 2910 private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }29112912 private fun currentPayloadLocked(): VaultPayload =2913 VaultPayload(2914 entries = entryList.toList(),2915 duressConfigured = authenticatedDuressConfigured,2916 rootKeyB64 = rootKey?.let(::b64) ?: "",2917 recoveryWordHash = recoveryWordHash,2918 recoveryWordsSet = recoveryWordsSet,2919 )29202921 29222923292429252926 private fun ensureRootKey(payload: VaultPayload) {2927 if (payload.rootKeyB64.isNotBlank()) {2928 rootKey = unb64(payload.rootKeyB64)2929 return2930 }2931 rootKey = generateRecoverableRootKey()2932 runCatching { persistSlotA(bumpVersion = false) }2933 }29342935 private fun publish() {2936 _entries.value = entryList.filter { it.deletedAt == null }2937 }29382939 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2940 var plaintext = VaultCodec.encode(currentPayload())2941 return try {2942 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2943 StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob)2944 } finally {2945 2946 2947 2948 VaultCrypto.zero(plaintext)2949 }2950 }29512952 private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2953 2954 2955 2956 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2957 val noise = ByteArray(approxBytes).also(rng::nextBytes)2958 return store.writeSlotB(b64(noise))2959 }29602961 296229632964 private fun matchingCiphertextLength(slotA: StoredVault): Int =2965 (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)29662967 29682969297029712972 private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {2973 val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162974 val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)2975 val fakeSalt = VaultCrypto.generateSalt()2976 return store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2977 }29782979 298029812982298329842985 private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {2986 val isConfigured = mutateState { authenticatedDuressConfigured }2987 return if (isConfigured) true else writeFakeDuressSlot(slotA)2988 }29892990 2991299229932994299529962997 private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {2998 val salt = unhex(b.salt)2999 val nonce = unhex(b.nonce)3000 val ct = unhex(b.ciphertext)3001 val tag = unhex(b.tag)3002 val blob = ByteArray(nonce.size + ct.size + tag.size).also {3003 System.arraycopy(nonce, 0, it, 0, nonce.size)3004 System.arraycopy(ct, 0, it, nonce.size, ct.size)3005 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)3006 }3007 return StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))3008 }3009 3010 private fun persistSlotA(3011 bumpVersion: Boolean,3012 snapshotReason: String? = "local_save",3013 expectedEpoch: Long? = null,3014 ): Boolean {3015 val snapshot = snapshotForPersist(expectedEpoch)3016 ?: throw IllegalStateException("vault_locked_or_stale")3017 return try {3018 3019 if (snapshot.decoy) {3020 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")3021 val plaintext = VaultCodec.encode(snapshot.payload)3022 val blob = try {3023 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_B))3024 } finally {3025 3026 3027 VaultCrypto.zero(plaintext)3028 }3029 beforeDurableCommit()3030 return withEpochCommit(snapshot.epoch) {3031 store.writeDecoySlot(prior.copy(version = CURRENT_ANDROID_SLOT_VERSION, blob = blob))3032 } ?: false3033 }3034 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")3035 3036 3037 3038 3039 val priorB = store.loadSlotB()3040 beforeDurableCommit()3041 if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false3042 val plaintext = VaultCodec.encode(snapshot.payload)3043 val blob = try {3044 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))3045 } finally {3046 3047 3048 VaultCrypto.zero(plaintext)3049 }3050 val next = prior.copy(blob = blob)3051 3052 3053 3054 3055 withEpochCommit(snapshot.epoch) {3056 if (!store.writeSlotA(next)) return@withEpochCommit false3057 try {3058 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")3059 3060 3061 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")3062 if (bumpVersion) store.stampLocalMutation()3063 } catch (e: Exception) {3064 store.writeSlotA(prior)3065 if (priorB != null) runCatching { store.writeSlotB(priorB) }3066 throw e3067 }3068 true3069 } ?: false3070 } finally {3071 3072 3073 VaultCrypto.zero(snapshot.key)3074 }3075 }30763077 3078307930803081308230833084 private fun commitVaultRotation(3085 priorA: StoredVault,3086 priorB: String?,3087 nextA: StoredVault,3088 expectedEpoch: Long,3089 ): Boolean {3090 beforeDurableCommit()3091 return withEpochCommit(expectedEpoch) {3092 if (!store.writeSlotA(nextA)) return@withEpochCommit false3093 3094 3095 3096 try {3097 if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")3098 3099 3100 3101 3102 if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")3103 store.stampLocalMutation()3104 } catch (_: Exception) {3105 reportRotationRollback(slotRollback.restorePair(priorA, priorB))3106 return@withEpochCommit false3107 }3108 true3109 } ?: false3110 }31113112 31133114311531163117 private fun reportRotationRollback(failures: List<String>) {3118 if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }3119 }31203121 3122 private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {3123 try {3124 if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {3125 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3126 throw IllegalStateException("storage_write_failed")3127 }3128 } catch (e: Exception) {3129 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3130 throw e3131 }3132 3133 3134 3135 mutateIfCurrentEpoch(expectedEpoch) { publish() }3136 runCatching { LockedSyncSpoolHooks.refresh(this) }3137 }3138}