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 mutex = Mutex()92 93 94 95 96 97 98 99 private val stateLock = ReentrantLock()100 private val rng = SecureRandom()101102 103104105106107 private var sessionEpoch: Long = 0L108109 private fun nextSessionEpoch(epoch: Long): Long =110 if (epoch == Long.MAX_VALUE) 0L else epoch + 1L111112 113 @VisibleForTesting114 internal var beforeDurableCommit: () -> Unit = {}115116 117 @VisibleForTesting118 internal var afterCodexRollback: () -> Unit = {}119120 121122123124125 private inline fun <T> mutateState(block: () -> T): T {126 stateLock.lock()127 return try { block() } finally { stateLock.unlock() }128 }129130 131 private inline fun <T> withEpochCommit(epoch: Long, block: () -> T): T? {132 stateLock.lock()133 return try {134 if (sessionEpoch != epoch) null else block()135 } finally {136 stateLock.unlock()137 }138 }139140 141 @VisibleForTesting142 internal var beforeSessionEpochCommit: () -> Unit = {}143144 145146147148149 @VisibleForTesting150 internal var beforeSessionStateMutation: () -> Unit = {}151152 153154155156157158 internal fun <T> withSessionEpochCommit(epoch: Long, block: () -> T): T? {159 beforeSessionEpochCommit()160 return withEpochCommit(epoch, block)161 }162163 private fun currentEpoch(): Long = mutateState { sessionEpoch }164165 private inline fun <T> mutateIfCurrentEpoch(epoch: Long, block: () -> T): T? =166 mutateState { if (sessionEpoch == epoch) block() else null }167168 169 private inline fun <T> mutateCurrentSession(epoch: Long, block: () -> T): T? {170 beforeSessionStateMutation()171 return mutateIfCurrentEpoch(epoch, block)172 }173174 private data class PersistSnapshot(175 val epoch: Long,176 val key: ByteArray,177 val payload: VaultPayload,178 val decoy: Boolean,179 )180181 182 private fun snapshotForPersist(expectedEpoch: Long? = null): PersistSnapshot? = mutateState {183 if (expectedEpoch != null && sessionEpoch != expectedEpoch) return@mutateState null184 val liveKey = derivedKey ?: return@mutateState null185 PersistSnapshot(186 epoch = sessionEpoch,187 key = liveKey.copyOf(),188 payload = currentPayloadLocked(),189 decoy = decoyMode,190 )191 }192193 private var derivedKey: ByteArray? = null194 private var rootKey: ByteArray? = null195 private var entryList: MutableList<VaultEntry> = mutableListOf()196 private var authenticatedDuressConfigured: Boolean = false197 private var recoveryWordHash: String? = null198 private var recoveryWordsSet: Boolean = false199 200 private var sessionDataAvailable: Boolean = false201 202 private var decoyMode: Boolean = false203204 private val _isUnlocked = MutableStateFlow(false)205 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()206207 private val _duressConfigured = MutableStateFlow(false)208 209 val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()210211212 213214215216217218 private val _uiGateLocked = MutableStateFlow(false)219 val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()220221 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())222 223 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()224225 226 227 228 229 private val _settings = MutableStateFlow(store.loadSettings())230 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()231232 233 private fun clearSessionStateLocked() {234 derivedKey?.let(VaultCrypto::zero)235 rootKey?.let(VaultCrypto::zero)236 derivedKey = null237 rootKey = null238 entryList = mutableListOf()239 authenticatedDuressConfigured = false240 _duressConfigured.value = false241 recoveryWordHash = null242 recoveryWordsSet = false243 sessionDataAvailable = false244 decoyMode = false245 _settings.value = store.loadSettings()246 _entries.value = emptyList()247 _isUnlocked.value = false248 }249250 fun hasVault(): Boolean = store.hasVault()251252 253254 255256257258259260261 fun codexVaultBlobBase64(): String? {262 val slotA = store.loadSlotA() ?: return null263 264 265 val slotD = store.loadDecoySlot() ?: return null266 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""267 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))268 }269270 271272273274275 276 private fun JsonElement?.asSlotJson(): String? = when {277 this == null || this is JsonNull -> null278 this is JsonPrimitive && isString -> content279 else -> toString()280 }281282 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {283 val expectedEpoch = currentEpoch()284 var candidateKey: ByteArray? = null285 var plaintext: ByteArray? = null286 return try {287 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)288 289 290 291 292 293 294 295 val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject296 ?: return UnlockResult.Error("invalid_codex_blob")297 val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")298 299 300 301 302 303 val slotA = VaultCodec.decodeSlot(slotJson)304 ?: BrowserSlot.parse(slotJson)?.let {305 BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword306 }307 ?: return UnlockResult.Error("invalid_codex_blob")308 309 310 311 312 313 candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))314 plaintext = decryptSlotABlob(slotA, candidateKey)315 316 317 318 319 if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {320 VaultCrypto.zero(candidateKey)321 candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))322 plaintext = decryptSlotABlob(slotA, candidateKey)323 }324 if (plaintext == null) return UnlockResult.WrongPassword325 val payload = try {326 VaultCodec.decode(plaintext)327 } catch (_: Exception) {328 return UnlockResult.Error("invalid_codex_blob")329 }330331 val priorA = store.loadSlotA()332 val priorB = store.loadSlotB()333 val priorD = store.loadDecoySlot()334 335 336 337 338 339 val codexDuressJson = wrapper["b"].asSlotJson()340 val codexDuress: StoredVault? = codexDuressJson?.let {341 VaultCodec.decodeSlot(it)?.let { slot ->342 if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) null else slot343 } ?: BrowserSlot.parse(it)?.let { b ->344 browserDuressPassthrough(b)345 }346 }347348 beforeDurableCommit()349 val committed = runCatching {350 withEpochCommit(expectedEpoch) {351 try {352 353 354 355 356 if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")357 358 359 if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")360 361 362 val duressOk = if (codexDuress != null) {363 store.writeDecoySlot(codexDuress)364 } else {365 writeFakeDuressSlot(slotA)366 }367 if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")368 store.stampLocalMutation()369 true370 } catch (_: Exception) {371 reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))372 373 374 375 afterCodexRollback()376 false377 }378 } ?: false379 }.getOrDefault(false)380 if (!committed) {381 return UnlockResult.Error("storage_write_failed")382 }383384 val ownedKey = candidateKey!!385 candidateKey = null 386 VaultKeyRotationHooks.onRotated()387 adoptSlotA(ownedKey, payload, expectedEpoch)388 } catch (e: Exception) {389 390 391 392 393 394 395 if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))396 UnlockResult.Error(e.message ?: "restore_failed")397 } finally {398 plaintext?.let(VaultCrypto::zero)399 candidateKey?.let(VaultCrypto::zero)400 }401 }402403 404 private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =405 runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()406407 408409410411412413414415416 private fun rollbackRestoreLocked(417 priorA: StoredVault?,418 priorB: String?,419 priorD: StoredVault? = null,420 ): List<String> {421 val failures = mutableListOf<String>()422 if (priorA == null) {423 runCatching { store.clearVault() }.onFailure { failures += "clearVault: $it" }424 } else {425 runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }426 .onFailure { failures += "writeSlotA: $it" }427 if (priorB != null) {428 runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }429 .onFailure { failures += "writeSlotB: $it" }430 }431 432 433 434 if (priorD != null) {435 runCatching { if (!store.writeDecoySlot(priorD)) failures += "writeDecoySlot returned false" }436 .onFailure { failures += "writeDecoySlot: $it" }437 } else {438 runCatching { store.clearDecoySlot() }.onFailure { failures += "clearDecoySlot: $it" }439 }440 }441 return failures442 }443444 private fun reportRollbackFailures(failures: List<String>) {445 446 447 if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }448 }449450 451 private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {452 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)453 val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()454 val window = offset?.let {455 val from = (it - 40).coerceAtLeast(0)456 val to = (it + 40).coerceAtMost(wrapperJson.length)457 wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")458 }459 val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()460 val slot = wrapper?.get("a")461 buildString {462 append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)463 append(" | blobBase64=").append(vaultBlobBase64.length)464 append(" wrapperChars=").append(wrapperJson.length)465 append(" wrapperParses=").append(wrapper != null)466 append(" keys=").append(wrapper?.keys)467 append(" slotAKind=").append(468 when {469 slot == null -> "absent"470 slot is JsonPrimitive && slot.isString -> "string"471 slot is JsonObject -> "object:" + slot.keys472 else -> slot::class.simpleName473 },474 )475 if (window != null) append(" masked@").append(offset).append("=").append(window)476 }477 }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }478479 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {480 val expectedEpoch = currentEpoch()481 var key: ByteArray? = null482 return try {483 val salt = VaultCrypto.generateSalt()484 key = VaultCrypto.deriveKey(password, salt)485 if (mutateIfCurrentEpoch(expectedEpoch) {486 entryList = mutableListOf()487 authenticatedDuressConfigured = false488 _duressConfigured.value = false489 recoveryWordHash = null490 recoveryWordsSet = false491 decoyMode = false492 sessionDataAvailable = false493 rootKey = generateRecoverableRootKey()494 } == null) return CreateVaultResult.Error("stale_create")495 496 497 498 499 val slotA = sealSlotA(key!!, salt)500 501 502 beforeDurableCommit()503 val created = withEpochCommit(expectedEpoch) {504 if (!store.writeSlotA(slotA)) return@withEpochCommit false505 try {506 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")507 508 509 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")510 store.stampLocalMutation()511 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")512 true513 } catch (_: Exception) {514 515 516 store.clearVault()517 false518 }519 } ?: false520 if (!created) {521 lock()522 return CreateVaultResult.Error("storage_write_failed")523 }524 val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")525 if (mutateIfCurrentEpoch(expectedEpoch) {526 derivedKey = sessionKey527 key = null528 publish()529 _isUnlocked.value = true530 sessionDataAvailable = true531 sessionEpoch = nextSessionEpoch(sessionEpoch)532 } == null) return CreateVaultResult.Error("stale_create")533 CreateVaultResult.Success534 } catch (e: Exception) {535 lock()536 CreateVaultResult.Error(e.message ?: "create_failed")537 } finally {538 key?.let(VaultCrypto::zero)539 }540 }541542 suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {543 val expectedEpoch = currentEpoch()544 if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")545 if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")546 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {547 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")548 }549 var adoptedRootKey: ByteArray? = null550 var nextDerivedKey: ByteArray? = null551 var sessionRootKey: ByteArray? = null552 return try {553 adoptedRootKey = hexToRootKey(rootKeyHex)554 if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {555 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")556 }557 val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)558 val salt = VaultCrypto.generateSalt()559 nextDerivedKey = VaultCrypto.deriveKey(password, salt)560 sessionRootKey = adoptedRootKey.copyOf()561 val payload = VaultPayload(562 entries = emptyList(),563 duressConfigured = false,564 rootKeyB64 = b64(sessionRootKey),565 recoveryWordHash = null,566 recoveryWordsSet = false,567 )568 val plaintext = VaultCodec.encode(payload)569 val blob = try {570 b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))571 } finally {572 VaultCrypto.zero(plaintext)573 }574 val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)575 576 577 beforeDurableCommit()578 val created = withEpochCommit(expectedEpoch) {579 if (!store.writeSlotA(slotA)) return@withEpochCommit false580 try {581 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")582 583 584 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")585 store.stampLocalMutation()586 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")587 true588 } catch (_: Exception) {589 store.clearVault()590 false591 }592 } ?: false593 if (!created) return AdoptVaultResult.Error("storage_write_failed")594595 val adopted = mutateIfCurrentEpoch(expectedEpoch) {596 val previousDerivedKey = derivedKey597 val previousRootKey = rootKey598 derivedKey = nextDerivedKey599 rootKey = sessionRootKey600 nextDerivedKey = null601 sessionRootKey = null602 entryList = mutableListOf()603 authenticatedDuressConfigured = false604 _duressConfigured.value = false605 recoveryWordHash = null606 recoveryWordsSet = false607 decoyMode = false608 sessionDataAvailable = true609 publish()610 _isUnlocked.value = true611 sessionEpoch = nextSessionEpoch(sessionEpoch)612 previousDerivedKey to previousRootKey613 }614 if (adopted == null) return AdoptVaultResult.Error("stale_adoption")615 val (previousDerivedKey, previousRootKey) = adopted616 previousDerivedKey?.let(VaultCrypto::zero)617 previousRootKey?.let(VaultCrypto::zero)618 619 620 621 runCatching {622 val words = rootKeyToWords(rootKey!!)623 val escrow = buildRecoveryEscrow(words)624 val rkEscrow = buildRootKeyEscrow(words)625 if (escrow != null || rkEscrow != null) {626 val prior = store.loadSlotA()627 if (prior != null) {628 store.writeSlotA(prior.copy(629 recoveryEscrow = escrow ?: prior.recoveryEscrow,630 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,631 ))632 }633 mutateState {634 recoveryWordHash = recoveryWordsHash(words)635 recoveryWordsSet = true636 }637 }638 }639 AdoptVaultResult.Success(vaultId)640 } catch (e: Exception) {641 AdoptVaultResult.Error(e.message ?: "adoption_create_failed")642 } finally {643 adoptedRootKey?.let(VaultCrypto::zero)644 nextDerivedKey?.let(VaultCrypto::zero)645 sessionRootKey?.let(VaultCrypto::zero)646 }647 }648649 suspend fun unlock(password: String): UnlockResult = mutex.withLock {650 val result = unlockLocked(password, currentEpoch())651 if (result is UnlockResult.Success) ensureRecoveryEscrow()652 result653 }654655 656 private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {657 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")658 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))659 val payload = try {660 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)661 try {662 VaultCodec.decode(plaintext)663 } finally {664 VaultCrypto.zero(plaintext)665 }666 } catch (_: Exception) {667 VaultCrypto.zero(key)668 669 670 671 if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {672 val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)673 if (legacy != null) return legacy674 }675 return UnlockResult.WrongPassword676 }677 return adoptSlotA(key, payload, expectedEpoch)678 }679680 681682683684685686687688 private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {689 var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))690 var newKey: ByteArray? = null691 return try {692 val payload = try {693 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)694 try {695 VaultCodec.decode(plaintext)696 } finally {697 VaultCrypto.zero(plaintext)698 }699 } catch (_: Exception) {700 return null701 }702 703 704 val newSalt = VaultCrypto.generateSalt()705 newKey = VaultCrypto.deriveKey(password, newSalt)706 val plaintext = VaultCodec.encode(payload)707 val blob = try {708 b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))709 } finally {710 VaultCrypto.zero(plaintext)711 }712 val next = StoredVault(713 version = slotA.version,714 salt = b64(newSalt),715 blob = blob,716 recoveryEscrow = slotA.recoveryEscrow,717 rootKeyEscrow = slotA.rootKeyEscrow,718 )719 720 721 722 val priorB = store.loadSlotB()723 beforeDurableCommit()724 val healed = withEpochCommit(expectedEpoch) {725 if (!store.writeSlotA(next)) {726 false727 } else try {728 if (!writeMatchingNoiseSlotB(next)) {729 runCatching { store.writeSlotA(slotA) }730 if (priorB != null) runCatching { store.writeSlotB(priorB) }731 false732 } else if (!writeCompanionDuressSlot(next)) {733 runCatching { store.writeSlotA(slotA) }734 if (priorB != null) runCatching { store.writeSlotB(priorB) }735 false736 } else {737 store.stampLocalMutation()738 true739 }740 } catch (_: Exception) {741 runCatching { store.writeSlotA(slotA) }742 if (priorB != null) runCatching { store.writeSlotB(priorB) }743 false744 }745 } ?: false746 if (healed) {747 VaultCrypto.zero(rawKey!!)748 rawKey = null749 val result = adoptSlotA(newKey!!, payload, expectedEpoch) 750 newKey = null751 result752 } else {753 VaultCrypto.zero(newKey!!)754 newKey = null755 val result = adoptSlotA(rawKey!!, payload, expectedEpoch) 756 rawKey = null757 result758 }759 } finally {760 761 762 rawKey?.let(VaultCrypto::zero)763 newKey?.let(VaultCrypto::zero)764 }765 }766767 768 private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {769 return try {770 771 772 773 774 775 val adopted = mutateIfCurrentEpoch(expectedEpoch) {776 derivedKey = key777 decoyMode = false778 entryList = payload.entries.toMutableList()779 authenticatedDuressConfigured = payload.duressConfigured780 _duressConfigured.value = payload.duressConfigured781 recoveryWordHash = payload.recoveryWordHash782 recoveryWordsSet = payload.recoveryWordsSet783 sessionDataAvailable = true784 _settings.value = store.loadSettings()785 ensureRootKey(payload)786 autoPurgeExpiredTrash()787 consolidatePasskeyEntries()788 publish()789 _isUnlocked.value = true790 791 792 793 sessionEpoch = nextSessionEpoch(sessionEpoch)794 }795 if (adopted == null) {796 VaultCrypto.zero(key)797 UnlockResult.Error("stale_unlock")798 } else {799 UnlockResult.Success800 }801 } catch (e: Exception) {802 803 804 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }805 VaultCrypto.zero(key)806 UnlockResult.Error(e.message ?: "unlock_failed")807 }808 }809810 811812 813814815816817818 class SlotAUnlock internal constructor(819 key: ByteArray,820 internal val payload: VaultPayload,821 internal val epoch: Long,822 ) {823 private var ownedKey: ByteArray? = key824 private var consumed = false825826 827 internal fun takeKey(): ByteArray? = synchronized(this) {828 if (consumed) return@synchronized null829 consumed = true830 ownedKey.also { ownedKey = null }831 }832833 834 internal fun discard() = synchronized(this) {835 if (consumed) return@synchronized836 consumed = true837 ownedKey?.let(VaultCrypto::zero)838 ownedKey = null839 }840 }841842 843844845846847848 fun tryUnlockSlotA(password: String): SlotAUnlock? {849 val epoch = currentEpoch()850 val slotA = store.loadSlotA() ?: return null851 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))852 try {853 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)854 val payload = try {855 VaultCodec.decode(plaintext)856 } finally {857 VaultCrypto.zero(plaintext)858 }859 return SlotAUnlock(key, payload, epoch)860 } catch (_: Exception) {861 VaultCrypto.zero(key)862 }863864 if (password == Normalizer.normalize(password, Normalizer.Form.NFC)) return null865 return tryLegacyRawCandidate(password, slotA, epoch)866 }867868 869 private fun tryLegacyRawCandidate(password: String, slotA: StoredVault, epoch: Long): SlotAUnlock? {870 var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))871 var newKey: ByteArray? = null872 return try {873 val plaintext = try {874 VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)875 } catch (_: Exception) {876 return null877 }878 val payload = try {879 VaultCodec.decode(plaintext)880 } finally {881 VaultCrypto.zero(plaintext)882 }883 val newSalt = VaultCrypto.generateSalt()884 newKey = VaultCrypto.deriveKey(password, newSalt)885 val encoded = VaultCodec.encode(payload)886 val blob = try {887 b64(VaultCrypto.encrypt(encoded, newKey!!, VaultCrypto.AAD_SLOT_A))888 } finally {889 VaultCrypto.zero(encoded)890 }891 val next = slotA.copy(salt = b64(newSalt), blob = blob)892 val priorB = store.loadSlotB()893 beforeDurableCommit()894 val healed = withEpochCommit(epoch) {895 if (!store.writeSlotA(next)) false else try {896 if (!writeMatchingNoiseSlotB(next) || !writeCompanionDuressSlot(next)) {897 runCatching { store.writeSlotA(slotA) }898 if (priorB != null) runCatching { store.writeSlotB(priorB) }899 false900 } else {901 store.stampLocalMutation()902 true903 }904 } catch (_: Exception) {905 runCatching { store.writeSlotA(slotA) }906 if (priorB != null) runCatching { store.writeSlotB(priorB) }907 false908 }909 } ?: false910 if (healed) {911 VaultCrypto.zero(rawKey!!)912 rawKey = null913 SlotAUnlock(newKey!!, payload, epoch).also { newKey = null }914 } else {915 VaultCrypto.zero(newKey!!)916 newKey = null917 SlotAUnlock(rawKey!!, payload, epoch).also { rawKey = null }918 }919 } finally {920 rawKey?.let(VaultCrypto::zero)921 newKey?.let(VaultCrypto::zero)922 }923 }924925 926 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {927 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")928 adoptSlotA(key, unlock.payload, unlock.epoch)929 }930931 932 fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()933934 935936 937938939940941 class DuressUnlock internal constructor(942 key: ByteArray,943 internal val payload: VaultPayload,944 internal val epoch: Long,945 ) {946 private var ownedKey: ByteArray? = key947 private var consumed = false948949 internal fun takeKey(): ByteArray? = synchronized(this) {950 if (consumed) return@synchronized null951 consumed = true952 ownedKey.also { ownedKey = null }953 }954955 internal fun discard() = synchronized(this) {956 if (consumed) return@synchronized957 consumed = true958 ownedKey?.let(VaultCrypto::zero)959 ownedKey = null960 }961 }962963 964965966967968969970 fun tryUnlockDuress(password: String): DuressUnlock? {971 val epoch = currentEpoch()972 val slot = store.loadDecoySlot() ?: return null973 if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) return null974 var key: ByteArray? = VaultCrypto.deriveKey(password, unb64(slot.salt))975 return try {976 val plaintext = try {977 if (slot.version == CURRENT_ANDROID_SLOT_VERSION) {978 VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)979 } else {980 runCatching {981 VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_A)982 }.getOrElse {983 VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)984 }985 }986 } catch (_: Exception) {987 VaultCrypto.zero(key!!)988 key = null989 return null990 }991 val payload = try {992 VaultCodec.decode(plaintext)993 } finally {994 VaultCrypto.zero(plaintext)995 }996 if (slot.version == LEGACY_ANDROID_SLOT_VERSION) {997 val migratedKey = migrateLegacyDuressSlot(slot, password, payload, key!!, epoch)998 ?: run {999 VaultCrypto.zero(key!!)1000 key = null1001 return null1002 }1003 if (migratedKey !== key) {1004 VaultCrypto.zero(key!!)1005 key = migratedKey1006 }1007 }1008 DuressUnlock(key!!, payload, epoch).also { key = null }1009 } catch (_: Exception) {1010 key?.let(VaultCrypto::zero)1011 null1012 }1013 }10141015 10161017101810191020 private fun migrateLegacyDuressSlot(1021 legacy: StoredVault,1022 password: String,1023 payload: VaultPayload,1024 legacyKey: ByteArray,1025 epoch: Long,1026 ): ByteArray? {1027 var salt: ByteArray? = null1028 var migratedKey: ByteArray? = null1029 var plaintext: ByteArray? = null1030 var restoredLegacy = false1031 var migrated = false1032 try {1033 salt = VaultCrypto.generateSalt()1034 migratedKey = VaultCrypto.deriveKey(password, salt)1035 plaintext = VaultCodec.encode(payload)1036 val next = StoredVault(1037 version = CURRENT_ANDROID_SLOT_VERSION,1038 salt = b64(salt),1039 blob = b64(VaultCrypto.encrypt(plaintext, migratedKey, VaultCrypto.AAD_SLOT_B)),1040 )1041 var priorA: StoredVault? = null1042 var priorB: String? = null1043 withSessionEpochCommit(epoch) {1044 priorA = store.loadSlotA()1045 priorB = store.loadSlotB()1046 if (store.loadDecoySlot() != legacy) return@withSessionEpochCommit false1047 if (!store.writeDecoySlot(next)) {1048 restoredLegacy = store.loadDecoySlot() == legacy1049 return@withSessionEpochCommit restoredLegacy1050 }1051 val reopened = store.loadDecoySlot()1052 val verified = reopened?.version == CURRENT_ANDROID_SLOT_VERSION && runCatching {1053 val reopenedPlaintext = VaultCrypto.decrypt(unb64(reopened.blob), migratedKey!!, VaultCrypto.AAD_SLOT_B)1054 try { VaultCodec.decode(reopenedPlaintext) == payload } finally { VaultCrypto.zero(reopenedPlaintext) }1055 }.getOrDefault(false)1056 if (verified) {1057 migrated = true1058 return@withSessionEpochCommit true1059 }1060 val restored = priorA != null && store.restoreVaultTriad(priorA!!, priorB, legacy)1061 restoredLegacy = restored && store.loadSlotA() == priorA && store.loadSlotB() == priorB && store.loadDecoySlot() == legacy1062 restoredLegacy1063 }1064 if (migrated) {1065 VaultCrypto.zero(legacyKey)1066 return migratedKey.also { migratedKey = null }1067 }1068 if (restoredLegacy) return legacyKey1069 } catch (_: Exception) {1070 1071 1072 }1073 if (!restoredLegacy) runCatching { store.loadDecoySlot() == legacy }1074 migratedKey?.let(VaultCrypto::zero)1075 return if (restoredLegacy) legacyKey else null1076 }10771078 1079 suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {1080 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")1081 if (currentEpoch() != unlock.epoch) {1082 VaultCrypto.zero(key)1083 return@withLock UnlockResult.Error("stale_unlock")1084 }1085 return try {1086 val adopted = mutateIfCurrentEpoch(unlock.epoch) {1087 derivedKey = key1088 decoyMode = true1089 entryList = unlock.payload.entries.toMutableList()1090 authenticatedDuressConfigured = false1091 _duressConfigured.value = false1092 recoveryWordHash = unlock.payload.recoveryWordHash1093 recoveryWordsSet = unlock.payload.recoveryWordsSet1094 sessionDataAvailable = true1095 rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)1096 else VaultCrypto.generateRootKey()1097 1098 1099 1100 1101 1102 _settings.value = VaultSettings()1103 publish()1104 _isUnlocked.value = true1105 sessionEpoch = nextSessionEpoch(sessionEpoch)1106 }1107 if (adopted == null) {1108 VaultCrypto.zero(key)1109 UnlockResult.Error("stale_unlock")1110 } else {1111 UnlockResult.Success1112 }1113 } catch (e: Exception) {1114 1115 1116 1117 1118 mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }1119 VaultCrypto.zero(key)1120 UnlockResult.Error(e.message ?: "decoy_unlock_failed")1121 }1122 }11231124 1125 fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()11261127 112811291130113111321133 suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {1134 1135 val expectedEpoch = mutateState {1136 if (derivedKey != null && !decoyMode) sessionEpoch else null1137 } ?: return false1138 1139 1140 tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }1141 var key: ByteArray? = null1142 var basePlaintext: ByteArray? = null1143 return try {1144 val salt = VaultCrypto.generateSalt()1145 key = VaultCrypto.deriveKey(duressPassphrase, salt)1146 1147 val decoyRoot = VaultCrypto.generateRootKey()1148 val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }1149 val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)1150 basePlaintext = VaultCodec.encode(decoyPayload)1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 val slotA = store.loadSlotA()1161 val targetSize = slotA?.let(::matchingCiphertextLength) ?: 01162 val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!1163 val blob = try {1164 b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_B))1165 } finally {1166 VaultCrypto.zero(plaintext)1167 1168 1169 if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)1170 basePlaintext = null1171 key?.let(VaultCrypto::zero)1172 key = null1173 }1174 beforeDurableCommit()1175 val ok = withEpochCommit(expectedEpoch) {1176 store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob))1177 } ?: false1178 if (!ok) return false1179 val marked = mutateIfCurrentEpoch(expectedEpoch) {1180 authenticatedDuressConfigured = true1181 _duressConfigured.value = true1182 true1183 } ?: false1184 if (!marked) return false1185 if (!runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1186 mutateIfCurrentEpoch(expectedEpoch) {1187 authenticatedDuressConfigured = false1188 _duressConfigured.value = false1189 }1190 runCatching { writeFakeDuressSlot(store.loadSlotA()!!) }1191 return false1192 }1193 true1194 } catch (_: Exception) {1195 false1196 } finally {1197 1198 1199 key?.let(VaultCrypto::zero)1200 basePlaintext?.let(VaultCrypto::zero)1201 }1202 }120312041205 120612071208120912101211121212131214 suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1215 if (!authenticatedDuressConfigured) return null1216 val slot = store.loadDecoySlot() ?: return null1217 return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1218 }12191220 1221122212231224122512261227 private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1228 1229 1230 1231 1232 1233 var salt: ByteArray? = null1234 var blob: ByteArray? = null1235 var nonce: ByteArray? = null1236 var ctAndTag: ByteArray? = null1237 var ct: ByteArray? = null1238 var tag: ByteArray? = null1239 try {1240 salt = unb64(slot.salt)1241 blob = unb64(slot.blob)1242 nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1243 ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1244 ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1245 tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1246 val obj = JsonObject(mapOf(1247 "version" to JsonPrimitive(1),1248 "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1249 "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1250 "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1251 "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1252 ))1253 return obj.toString()1254 } finally {1255 salt?.let(VaultCrypto::zero)1256 blob?.let(VaultCrypto::zero)1257 nonce?.let(VaultCrypto::zero)1258 ctAndTag?.let(VaultCrypto::zero)1259 ct?.let(VaultCrypto::zero)1260 tag?.let(VaultCrypto::zero)1261 }1262 }12631264 126512661267 suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1268 val b = BrowserSlot.parse(json) ?: return false1269 if (b.version != 1) return false1270 val expectedEpoch = currentEpoch()1271 var salt: ByteArray? = null1272 var nonce: ByteArray? = null1273 var ct: ByteArray? = null1274 var tag: ByteArray? = null1275 var blob: ByteArray? = null1276 try {1277 salt = unhex(b.salt)1278 nonce = unhex(b.nonce)1279 ct = unhex(b.ciphertext)1280 tag = unhex(b.tag)1281 blob = ByteArray(nonce.size + ct.size + tag.size).also {1282 System.arraycopy(nonce, 0, it, 0, nonce.size)1283 System.arraycopy(ct, 0, it, nonce.size, ct.size)1284 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1285 }1286 val stored = StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))1287 val priorA = store.loadSlotA() ?: return false1288 val priorB = store.loadSlotB()1289 val priorD = store.loadDecoySlot() ?: return false1290 beforeDurableCommit()1291 val committed = withEpochCommit(expectedEpoch) {1292 if (!store.writeDecoySlot(stored)) return@withEpochCommit false1293 authenticatedDuressConfigured = true1294 _duressConfigured.value = true1295 true1296 } ?: false1297 if (!committed) return false1298 if (runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1299 true1300 } else {1301 mutateIfCurrentEpoch(expectedEpoch) {1302 authenticatedDuressConfigured = false1303 _duressConfigured.value = false1304 }1305 withEpochCommit(expectedEpoch) { store.restoreVaultTriad(priorA, priorB, priorD) }1306 false1307 }1308 } catch (_: Exception) {1309 false1310 } finally {1311 salt?.let(VaultCrypto::zero)1312 nonce?.let(VaultCrypto::zero)1313 ct?.let(VaultCrypto::zero)1314 tag?.let(VaultCrypto::zero)1315 blob?.let(VaultCrypto::zero)1316 }1317 }13181319 1320 suspend fun clearDuress(): Boolean = mutex.withLock {1321 1322 1323 1324 1325 val expectedEpoch = currentEpoch()1326 val replaced = withEpochCommit(expectedEpoch) {1327 store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1328 ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1329 } ?: false1330 if (!replaced) return@withLock false1331 1332 1333 if (!isSessionEpochCurrent(expectedEpoch)) return false1334 val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1335 if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) {1336 authenticatedDuressConfigured = false1337 _duressConfigured.value = false1338 } != null) {1339 runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1340 }1341 true1342 }13431344 1345 private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1346 var current: Throwable? = error1347 while (current != null) {1348 if (current is javax.crypto.AEADBadTagException) return true1349 1350 1351 1352 1353 if (current is javax.crypto.BadPaddingException) return true1354 current = current.cause1355 }1356 return false1357 }13581359 1360 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1361 val expectedEpoch = currentEpoch()1362 val slotA = try {1363 store.loadSlotA()1364 } catch (_: Exception) {1365 return@withLock UnlockResult.Error("unlock_key_storage_failed")1366 } ?: return@withLock UnlockResult.Error("no_vault")1367 1368 1369 1370 1371 var stagedKey: ByteArray? = key.copyOf()1372 return try {1373 val encrypted = try {1374 unb64(slotA.blob)1375 } catch (_: Exception) {1376 return@withLock UnlockResult.Error("invalid_vault_blob")1377 }1378 1379 1380 1381 1382 if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1383 return@withLock UnlockResult.Error("invalid_vault_blob")1384 }1385 val plaintext = try {1386 VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1387 } catch (e: Exception) {1388 if (isGcmAuthenticationFailure(e)) {1389 return@withLock UnlockResult.WrongPassword1390 }1391 return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1392 }1393 val payload = try {1394 VaultCodec.decode(plaintext)1395 } catch (_: Exception) {1396 return@withLock UnlockResult.Error("invalid_vault_payload")1397 } finally {1398 VaultCrypto.zero(plaintext)1399 }1400 val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1401 val result = adoptSlotA(candidate, payload, expectedEpoch)1402 if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1403 result1404 } finally {1405 stagedKey?.let(VaultCrypto::zero)1406 }1407 }14081409 fun lock() {1410 1411 1412 1413 1414 if (mutex.tryLock()) {1415 try {1416 runCatching { LockedSyncSpoolHooks.refresh(this) }1417 } finally {1418 mutex.unlock()1419 }1420 }1421 1422 1423 1424 1425 1426 1427 stateLock.lock()1428 try {1429 sessionEpoch = nextSessionEpoch(sessionEpoch)1430 clearSessionStateLocked()1431 _uiGateLocked.value = false1432 } finally {1433 stateLock.unlock()1434 }1435 }14361437 1438143914401441144214431444 fun lockUiGate() {1445 if (_isUnlocked.value) _uiGateLocked.value = true1446 }14471448 1449 fun clearUiGate() {1450 _uiGateLocked.value = false1451 }14521453 @Volatile private var suppressNextBackgroundLockUntil: Long = 0L14541455 1456 1457 @VisibleForTesting1458 internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }14591460 146114621463146414651466146714681469147014711472 fun expectTransientBackground() {1473 suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1474 }14751476 14771478147914801481 fun consumeTransientBackgroundSuppression(): Boolean {1482 val until = suppressNextBackgroundLockUntil1483 val active = until != 0L && nowMs() < until1484 suppressNextBackgroundLockUntil = 0L1485 return active1486 }14871488 14891490 14911492149314941495 14961497149814991500150115021503150415051506 1507 1508 1509 1510 1511 internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)15121513 internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1514 if (decoyMode || !_isUnlocked.value) null1515 else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1516 }15171518 internal fun isSessionEpochCurrent(epoch: Long): Boolean =1519 mutateState { sessionEpoch == epoch }15201521 internal fun unlockedSessionEpoch(): Long? = mutateState {1522 if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1523 }15241525 fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key15261527 152815291530153115321533153415351536 fun sessionRootKey(): ByteArray? = mutateState {1537 if (!sessionDataAvailable) null else rootKey?.copyOf()1538 }15391540 15411542 fun syncVaultId(): String? = mutateState {1543 if (decoyMode || !_isUnlocked.value) null1544 else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1545 }15461547 15481549155015511552 suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1553 val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1554 ?: return false1555 installRootKey(generateRecoverableRootKey(), expectedEpoch)1556 }15571558 15591560156115621563156415651566156715681569157015711572157315741575 suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1576 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1577 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1578 }1579 val expectedEpoch = mutateState {1580 when {1581 derivedKey == null -> null1582 decoyMode -> Long.MIN_VALUE1583 else -> sessionEpoch1584 }1585 }1586 if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1587 if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1588 if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")15891590 val incoming = hexToRootKey(rootKeyHex)1591 if (incoming.size != VaultCrypto.KEY_SIZE) {1592 VaultCrypto.zero(incoming)1593 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1594 }1595 1596 1597 1598 val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1599 if (!roundTrips) {1600 VaultCrypto.zero(incoming)1601 return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1602 }16031604 val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1605 return if (installRootKey(incoming, expectedEpoch)) {1606 AdoptVaultResult.Success(vaultId)1607 } else {1608 AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1609 }1610 }16111612 16131614161516161617 fun previewRecoveryWords(rootKeyHex: String): List<String>? {1618 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1619 val bytes = hexToRootKey(rootKeyHex)1620 return try {1621 val words = rootKeyToWords(bytes)1622 if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1623 } catch (_: Exception) {1624 null1625 } finally {1626 VaultCrypto.zero(bytes)1627 }1628 }16291630 16311632163316341635 private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1636 1637 1638 1639 1640 1641 1642 data class Snapshot(1643 val key: ByteArray,1644 val priorRootKey: ByteArray,1645 val priorRecoveryHash: String?,1646 val priorRecoverySet: Boolean,1647 )1648 val snap = mutateIfCurrentEpoch(expectedEpoch) {1649 val k = derivedKey ?: return@mutateIfCurrentEpoch null1650 if (decoyMode) return@mutateIfCurrentEpoch null1651 val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1652 Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1653 } ?: run {1654 VaultCrypto.zero(nextRootKey)1655 return false1656 }1657 val priorSlot = store.loadSlotA() ?: run {1658 VaultCrypto.zero(snap.key)1659 VaultCrypto.zero(snap.priorRootKey)1660 VaultCrypto.zero(nextRootKey)1661 return false1662 }1663 val nextWords = rootKeyToWords(nextRootKey)16641665 return try {1666 beforeDurableCommit()1667 if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1668 if (mutateIfCurrentEpoch(expectedEpoch) {1669 rootKey = nextRootKey1670 recoveryWordHash = recoveryWordsHash(nextWords)1671 recoveryWordsSet = false1672 } == null) throw IllegalStateException("stale_root_rotation")16731674 val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1675 ?: throw IllegalStateException("recovery_escrow_failed")1676 val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1677 ?: throw IllegalStateException("root_escrow_failed")1678 val plaintext = VaultCodec.encode(currentPayload())1679 val blob = try {1680 b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1681 } finally {1682 VaultCrypto.zero(plaintext)1683 }1684 val nextSlot = priorSlot.copy(1685 blob = blob,1686 recoveryEscrow = nextRecoveryEscrow,1687 rootKeyEscrow = nextRootKeyEscrow,1688 )1689 val committed = withEpochCommit(expectedEpoch) {1690 if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1691 try {1692 if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1693 1694 1695 if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1696 store.stampLocalMutation()1697 } catch (_: Exception) {1698 store.writeSlotA(priorSlot)1699 return@withEpochCommit false1700 }1701 true1702 } ?: false1703 if (!committed) throw IllegalStateException("storage_write_failed")1704 mutateIfCurrentEpoch(expectedEpoch) { publish() }1705 true1706 } catch (_: Exception) {1707 val restored = mutateIfCurrentEpoch(expectedEpoch) {1708 rootKey?.let(VaultCrypto::zero)1709 rootKey = snap.priorRootKey.copyOf()1710 recoveryWordHash = snap.priorRecoveryHash1711 recoveryWordsSet = snap.priorRecoverySet1712 }1713 if (restored != null) {1714 withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1715 }1716 false1717 } finally {1718 VaultCrypto.zero(snap.key)1719 VaultCrypto.zero(snap.priorRootKey)1720 1721 1722 1723 val stillOwnedBySession = mutateState {1724 sessionEpoch == expectedEpoch && rootKey === nextRootKey1725 }1726 if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1727 }1728 }17291730 17311732173317341735 fun currentVaultKey(): ByteArray? = mutateState {1736 if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1737 }17381739 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1740 val expectedEpoch = currentEpoch()1741 val slotA = store.loadSlotA() ?: return false1742 var oldKey: ByteArray? = null1743 var newKey: ByteArray? = null1744 var plaintext: ByteArray? = null1745 return try {1746 oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1747 1748 1749 1750 1751 val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1752 val payload = try {1753 VaultCodec.decode(decrypted)1754 } finally {1755 VaultCrypto.zero(decrypted)1756 }1757 val newSalt = VaultCrypto.generateSalt()1758 newKey = VaultCrypto.deriveKey(newPassword, newSalt)1759 1760 plaintext = VaultCodec.encode(payload)1761 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1762 1763 1764 1765 1766 1767 1768 1769 val next = StoredVault(1770 version = slotA.version,1771 salt = b64(newSalt),1772 blob = blob,1773 recoveryEscrow = slotA.recoveryEscrow,1774 rootKeyEscrow = slotA.rootKeyEscrow,1775 )1776 1777 1778 1779 1780 val priorB = store.loadSlotB()1781 if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1782 1783 1784 1785 if (mutateIfCurrentEpoch(expectedEpoch) {1786 oldKey?.let(VaultCrypto::zero); oldKey = null1787 derivedKey?.let(VaultCrypto::zero)1788 derivedKey = newKey; newKey = null1789 } == null) return false1790 VaultKeyRotationHooks.onRotated()1791 true1792 } catch (_: Exception) {1793 false1794 } finally {1795 oldKey?.let(VaultCrypto::zero)1796 newKey?.let(VaultCrypto::zero)1797 plaintext?.let(VaultCrypto::zero)1798 }1799 }18001801 1802180318041805 suspend fun destroyVault() = mutex.withLock {1806 lock()1807 store.clearVault()1808 store.clearDecoySlot()1809 }18101811 18121813 1814181518161817181818191820182118221823182418251826 private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")18271828 private fun String?.normalizedEntryId(): String =1829 if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()18301831 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1832 val epoch = requireUnlocked()1833 val stamp = VaultCrypto.monotonicEntryTimestamp()1834 val now = System.currentTimeMillis()1835 val entry = withDerivedLast4(draft.copy(1836 id = draft.id.normalizedEntryId(),1837 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1838 modifiedAt = stamp,1839 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1840 ))1841 1842 1843 val rollback = mutateCurrentSession(epoch) {1844 val r = entryList.toMutableList()1845 entryList.add(entry)1846 r1847 } ?: throw IllegalStateException("vault_locked")1848 persistOrRollback(rollback, epoch)1849 entry1850 }18511852 185318541855185618571858185918601861 suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1862 val epoch = requireUnlocked()1863 if (drafts.isEmpty()) return 01864 val now = System.currentTimeMillis()1865 val ready = drafts.map { draft ->1866 val stamp = VaultCrypto.monotonicEntryTimestamp()1867 withDerivedLast4(1868 draft.copy(1869 id = draft.id.normalizedEntryId(),1870 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1871 modifiedAt = stamp,1872 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1873 ),1874 )1875 }1876 1877 val rollback = mutateCurrentSession(epoch) {1878 val r = entryList.toMutableList()1879 entryList.addAll(ready)1880 r1881 } ?: throw IllegalStateException("vault_locked")1882 persistOrRollback(rollback, epoch)1883 return drafts.size1884 }18851886 1887188818891890189118921893189418951896189718981899 suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1900 val epoch = requireUnlocked()1901 val now = System.currentTimeMillis()1902 val ready = newEntries.map { draft ->1903 val stamp = VaultCrypto.monotonicEntryTimestamp()1904 withDerivedLast4(1905 draft.copy(1906 id = draft.id.normalizedEntryId(),1907 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1908 modifiedAt = stamp,1909 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1910 ),1911 )1912 }1913 1914 1915 1916 1917 1918 1919 val incomingIds = ready.map { it.id }.toHashSet()1920 val rollback = mutateCurrentSession(epoch) {1921 val r = entryList.toMutableList()1922 val replaced = entryList.map { entry ->1923 if (entry.deletedAt != null) return@map entry1924 if (entry.id in incomingIds) return@map null1925 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1926 entry.copy(deletedAt = stamp, modifiedAt = stamp)1927 }.filterNotNull()1928 entryList = (replaced + ready).toMutableList()1929 r1930 } ?: throw IllegalStateException("vault_locked")1931 persistOrRollback(rollback, epoch)1932 return ready.size1933 }19341935 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1936 val epoch = requireUnlocked()1937 1938 1939 1940 1941 val prepared = mutateCurrentSession(epoch) {1942 val idx = entryList.indexOfFirst { it.id == patch.id }1943 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1944 val current = entryList[idx]1945 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1946 1947 val passwordChanged = patch.password != null && patch.password != current.password1948 1949 1950 1951 1952 1953 1954 val priorPassword = current.password1955 val shouldCapture = passwordChanged &&1956 !priorPassword.isNullOrEmpty() &&1957 current.passwordHistory?.firstOrNull()?.password != priorPassword1958 val nextHistory = if (shouldCapture) {1959 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1960 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1961 } else {1962 current.passwordHistory1963 }1964 val updated = withDerivedLast4(patch.copy(1965 createdAt = current.createdAt,1966 modifiedAt = stamp,1967 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1968 passwordHistory = nextHistory,1969 ))1970 val rollback = entryList.toMutableList()1971 entryList[idx] = updated1972 updated to rollback1973 } ?: throw IllegalStateException("vault_locked")1974 val (updated, rollback) = prepared1975 persistOrRollback(rollback, epoch)1976 updated1977 }19781979 1980 suspend fun deleteEntry(id: String) = mutex.withLock {1981 val epoch = requireUnlocked()1982 1983 1984 val rollback = mutateCurrentSession(epoch) {1985 val idx = entryList.indexOfFirst { it.id == id }1986 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1987 val current = entryList[idx]1988 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1989 val prior = entryList.toMutableList()1990 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1991 prior1992 } ?: throw IllegalStateException("vault_locked")1993 persistOrRollback(rollback, epoch)1994 }19951996 suspend fun restoreEntry(id: String) = mutex.withLock {1997 val epoch = requireUnlocked()1998 val rollback = mutateCurrentSession(epoch) {1999 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }2000 if (idx == -1) throw IllegalStateException("deleted entry not found")2001 val current = entryList[idx]2002 val prior = entryList.toMutableList()2003 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))2004 prior2005 } ?: throw IllegalStateException("vault_locked")2006 persistOrRollback(rollback, epoch)2007 }20082009 2010 suspend fun purgeEntry(id: String) = mutex.withLock {2011 val epoch = requireUnlocked()2012 val rollback = mutateCurrentSession(epoch) {2013 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }2014 if (idx == -1) throw IllegalStateException("deleted entry not found")2015 val prior = entryList.toMutableList()2016 entryList.removeAt(idx)2017 prior2018 } ?: throw IllegalStateException("vault_locked")2019 persistOrRollback(rollback, epoch)2020 }20212022 2023 suspend fun purgeDeletedEntries(): Int = mutex.withLock {2024 val epoch = requireUnlocked()2025 2026 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2027 val r = mutateCurrentSession(epoch) {2028 val rollback = entryList.toMutableList()2029 val before = entryList.size2030 entryList.removeAll { it.deletedAt != null }2031 R(rollback, before - entryList.size)2032 } ?: throw IllegalStateException("vault_locked")2033 if (r.removed > 0) persistOrRollback(r.rollback, epoch)2034 r.removed2035 }20362037 2038 suspend fun countDuplicateEntries(): Int = mutex.withLock {2039 val epoch = requireUnlocked()2040 2041 2042 mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }2043 ?: throw IllegalStateException("vault_locked")2044 }20452046 20472048204920502051 suspend fun deduplicateEntries(): Int = mutex.withLock {2052 val epoch = requireUnlocked()2053 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2054 val ready = mutateCurrentSession(epoch) {2055 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")2056 val active = entryList.filter { it.deletedAt == null }2057 val keepIds = mutableSetOf<String>()2058 active.groupBy { it.duplicateKey() }.values.forEach { group ->2059 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id2060 }2061 val rollback = entryList.toMutableList()2062 var removed = 02063 entryList = entryList.map { entry ->2064 if (entry.deletedAt == null && entry.id !in keepIds) {2065 removed++2066 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)2067 entry.copy(deletedAt = stamp, modifiedAt = stamp)2068 } else {2069 entry2070 }2071 }.toMutableList()2072 R(rollback, removed)2073 } ?: throw IllegalStateException("vault_locked")2074 if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)2075 ready.removed2076 }20772078 fun getEntries(): List<VaultEntry> = mutateState {2079 if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }2080 }2081 fun getEntry(id: String): VaultEntry? = mutateState {2082 if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }2083 }2084 fun getDeletedEntries(): List<VaultEntry> = mutateState {2085 if (!sessionDataAvailable) emptyList()2086 else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }2087 }20882089 2090 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {2091 return mutateState {2092 if (!sessionDataAvailable) return@mutateState emptyList()2093 val active = entryList.filter { it.deletedAt == null }2094 if (tagFilter == null) return@mutateState active2095 val needle = tagFilter.trim().lowercase()2096 active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }2097 }2098 }20992100 2101 fun getDistinctTags(): List<String> = mutateState {2102 if (!sessionDataAvailable) return@mutateState emptyList()2103 entryList.asSequence()2104 .filter { it.deletedAt == null }2105 .flatMap { it.tags?.asSequence() ?: emptySequence() }2106 .map { it.trim().lowercase() }2107 .filter { it.isNotEmpty() }2108 .distinct()2109 .sorted()2110 .toList()2111 }21122113 211421152116211721182119 fun getDistinctFieldValues(field: String): List<String> {2120 val select: (VaultEntry) -> String? = when (field) {2121 "username" -> { e -> e.username }2122 "email" -> { e -> e.email }2123 else -> return emptyList()2124 }2125 return mutateState {2126 if (!sessionDataAvailable) return@mutateState emptyList()2127 entryList.asSequence()2128 .filter { it.deletedAt == null }2129 .mapNotNull { select(it)?.trim() }2130 .filter { it.isNotEmpty() }2131 .groupingBy { it.lowercase() }2132 .aggregate { _, acc: Pair<String, Int>?, value, _ ->2133 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)2134 }2135 .values2136 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })2137 .map { it.first }2138 }2139 }21402141 fun getTombstones(): List<Tombstone> = mutateState {2142 if (!sessionDataAvailable) emptyList()2143 else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }2144 }2145 fun getVaultVersion(): Long = store.version()2146 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots21472148 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {2149 val expectedEpoch = currentEpoch()2150 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false2151 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false2152 2153 2154 val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)2155 val priorA = store.loadSlotA()2156 val priorB = store.loadSlotB()2157 val priorD = store.loadDecoySlot()2158 2159 2160 2161 2162 2163 val priorHistory = store.loadVaultHistory()2164 2165 2166 2167 2168 beforeDurableCommit()2169 if (!takeVaultSnapshot("restore", expectedEpoch)) {2170 return false2171 }2172 2173 2174 2175 val nextD: StoredVault = restoredD ?: run {2176 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 162177 val fakeBlob = ByteArray(target).also(rng::nextBytes)2178 val fakeSalt = VaultCrypto.generateSalt()2179 StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob))2180 }2181 if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2182 withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2183 return false2184 }2185 lock()2186 true2187 }21882189 21902191219221932194219521962197219821992200 private fun commitRestoreAtomic(2201 nextA: StoredVault,2202 nextB: String,2203 nextD: StoredVault,2204 priorA: StoredVault?,2205 priorB: String?,2206 priorD: StoredVault?,2207 expectedEpoch: Long,2208 ): Boolean {2209 return withEpochCommit(expectedEpoch) {2210 if (!store.writeSlotA(nextA)) return@withEpochCommit false2211 2212 2213 2214 try {2215 if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2216 2217 2218 if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2219 store.stampLocalMutation()2220 } catch (_: Exception) {2221 reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2222 return@withEpochCommit false2223 }2224 true2225 } ?: false2226 }22272228 22292230 22312232223322342235 suspend fun applyMergedRemoteEntries(2236 remoteEntries: List<VaultEntry>,2237 remoteTombstones: List<Tombstone>,2238 expectedEpoch: Long? = null,2239 ): Int = mutex.withLock {2240 val epoch = expectedEpoch ?: requireUnlocked()2241 if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02242 2243 2244 2245 2246 2247 val mergeNow = System.currentTimeMillis()2248 val clamped = remoteEntries.mapNotNull { entry ->2249 2250 2251 2252 SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2253 modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2254 deletedAt = entry.deletedAt?.let {2255 SyncLimits.clampSyncTimestamp(it, mergeNow)2256 },2257 )2258 }2259 val tombMap = remoteTombstones.associate {2260 it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2261 }2262 2263 2264 val applied = mutateCurrentSession(epoch) {2265 var n = 02266 val byId = entryList.associateBy { it.id }.toMutableMap()22672268 for (remote in clamped) {2269 val tomb = tombMap[remote.id]2270 if (tomb != null && tomb >= remote.modifiedAt) continue2271 val local = byId[remote.id]2272 if (local == null) {2273 entryList.add(remote); byId[remote.id] = remote; n++2274 } else if (remote.modifiedAt > local.modifiedAt) {2275 val i = entryList.indexOfFirst { it.id == local.id }2276 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2277 }2278 }22792280 for ((id, deletedAt) in tombMap) {2281 val local = byId[id] ?: continue2282 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2283 if (deletedAt < local.modifiedAt) continue2284 val i = entryList.indexOfFirst { it.id == id }2285 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2286 }2287 n2288 } ?: return@withLock 022892290 if (applied > 0) {2291 persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2292 mutateIfCurrentEpoch(epoch) { publish() }2293 runCatching { LockedSyncSpoolHooks.refresh(this) }2294 }2295 applied2296 }22972298 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2299 2300 2301 2302 2303 if (mutateState { decoyMode }) {2304 val decoyEpoch = requireUnlocked()2305 mutateCurrentSession(decoyEpoch) { _settings.value = settings }2306 ?: throw IllegalStateException("vault_locked")2307 return@withLock2308 }2309 2310 2311 2312 val epoch = requireUnlocked()2313 val prior = mutateCurrentSession(epoch) {2314 val old = _settings.value2315 _settings.value = settings2316 old2317 } ?: throw IllegalStateException("vault_locked")23182319 val committed = try {2320 beforeDurableCommit()2321 2322 2323 2324 withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2325 } catch (_: Exception) {2326 false2327 }2328 if (!committed) {2329 2330 2331 2332 mutateIfCurrentEpoch(epoch) { _settings.value = prior }2333 throw IllegalStateException("settings_write_failed")2334 }2335 }23362337 23382339 2340 fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }23412342 23432344234523462347 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2348 val epoch = requireUnlocked()2349 2350 2351 2352 2353 2354 2355 val prior = mutateCurrentSession(epoch) {2356 val priorPair = recoveryWordHash to recoveryWordsSet2357 recoveryWordHash = recoveryWordsHash(words)2358 recoveryWordsSet = true2359 priorPair2360 } ?: return@withLock false2361 2362 2363 2364 2365 val persisted = runCatching {2366 persistSlotAWithEscrows(2367 buildRecoveryEscrow(words),2368 buildRootKeyEscrow(words),2369 expectedEpoch = epoch,2370 )2371 }.getOrDefault(false)2372 if (!persisted) {2373 mutateIfCurrentEpoch(epoch) {2374 recoveryWordHash = prior.first2375 recoveryWordsSet = prior.second2376 }2377 }2378 persisted2379 }23802381 2382 fun verifyRecoveryWords(words: List<String>): Boolean {2383 return mutateState {2384 val stored = recoveryWordHash ?: return@mutateState false2385 MessageDigest.isEqual(2386 stored.toByteArray(Charsets.UTF_8),2387 recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2388 )2389 }2390 }23912392 23932394 2395 fun hasRecoveryEscrow(): Boolean =2396 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false23972398 23992400240124022403 private fun ensureRecoveryEscrow() {2404 if (hasRecoveryEscrow()) return2405 val rk = mutateState { rootKey?.copyOf() } ?: return2406 runCatching {2407 val words = rootKeyToWords(rk)2408 val escrow = buildRecoveryEscrow(words)2409 val rkEscrow = buildRootKeyEscrow(words)2410 if (escrow != null || rkEscrow != null) {2411 val prior = store.loadSlotA() ?: return@runCatching2412 store.writeSlotA(prior.copy(2413 recoveryEscrow = escrow ?: prior.recoveryEscrow,2414 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2415 ))2416 mutateState {2417 recoveryWordHash = recoveryWordsHash(words)2418 recoveryWordsSet = true2419 }2420 }2421 }.also { VaultCrypto.zero(rk) }2422 }24232424 242524262427242824292430243124322433243424352436 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2437 val expectedEpoch = currentEpoch()2438 val slotA = store.loadSlotA() ?: return false2439 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false24402441 2442 2443 val fullEscrow = slotA.recoveryEscrow2444 if (fullEscrow != null) {2445 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2446 if (material != null) {2447 var keyBytes: ByteArray? = null2448 var plaintext: ByteArray? = null2449 var candidateRoot: ByteArray? = null2450 var stateCommitStarted = false2451 try {2452 keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2453 plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2454 val payload = VaultCodec.decode(plaintext)2455 2456 2457 2458 2459 val candidateSettings = store.loadSettings()2460 candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2461 val decodedRoot = unb64(payload.rootKeyB64)2462 if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2463 2464 2465 2466 VaultCrypto.zero(decodedRoot)2467 throw IllegalArgumentException("invalid recovery root key")2468 }2469 decodedRoot2470 } else {2471 generateRecoverableRootKey()2472 }2473 stateCommitStarted = true2474 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2475 clearSessionStateLocked()2476 entryList = payload.entries.toMutableList()2477 authenticatedDuressConfigured = payload.duressConfigured2478 _duressConfigured.value = payload.duressConfigured2479 recoveryWordHash = payload.recoveryWordHash2480 recoveryWordsSet = payload.recoveryWordsSet2481 rootKey = candidateRoot2482 candidateRoot = null2483 _settings.value = candidateSettings2484 publish()2485 2486 2487 sessionDataAvailable = true2488 _isUnlocked.value = false2489 true2490 }2491 if (adopted == true) return@withLock true2492 } catch (_: Exception) {2493 2494 2495 2496 2497 if (stateCommitStarted) {2498 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2499 }2500 } finally {2501 plaintext?.let(VaultCrypto::zero)2502 VaultCrypto.zero(material)2503 keyBytes?.let(VaultCrypto::zero)2504 candidateRoot?.let(VaultCrypto::zero)2505 }2506 }2507 }25082509 2510 2511 2512 val rootEscrow = slotA.rootKeyEscrow2513 if (rootEscrow != null) {2514 var candidateRoot: ByteArray? = null2515 var stateCommitStarted = false2516 try {2517 candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2518 require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2519 val candidateSettings = store.loadSettings()2520 stateCommitStarted = true2521 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2522 clearSessionStateLocked()2523 entryList = mutableListOf()2524 authenticatedDuressConfigured = false2525 _duressConfigured.value = false2526 recoveryWordHash = recoveryWordsHash(words)2527 recoveryWordsSet = true2528 rootKey = candidateRoot2529 candidateRoot = null2530 _settings.value = candidateSettings2531 publish()2532 sessionDataAvailable = true2533 _isUnlocked.value = false2534 true2535 }2536 if (adopted == true) return@withLock true2537 } catch (_: Exception) {2538 if (stateCommitStarted) {2539 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2540 }2541 } finally {2542 candidateRoot?.let(VaultCrypto::zero)2543 }2544 }2545 return false2546 }25472548 254925502551255225532554255525562557 suspend fun resetPasswordWithRecoveryWords(2558 words: List<String>,2559 newPassword: String,2560 ): Boolean = mutex.withLock {2561 val expectedEpoch = currentEpoch()2562 2563 2564 2565 if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2566 val priorA = store.loadSlotA() ?: return false2567 var newKey: ByteArray? = null2568 var plaintext: ByteArray? = null2569 return try {2570 val newSalt = VaultCrypto.generateSalt()2571 newKey = VaultCrypto.deriveKey(newPassword, newSalt)2572 plaintext = VaultCodec.encode(currentPayload())2573 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2574 2575 2576 2577 val valid = words.size == 12 && findInvalidWords(words).isEmpty()2578 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2579 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2580 val next = StoredVault(2581 version = priorA.version,2582 salt = b64(newSalt),2583 blob = blob,2584 recoveryEscrow = freshRecovery,2585 rootKeyEscrow = freshRootKey,2586 )2587 2588 2589 2590 val priorB = store.loadSlotB()2591 if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2592 2593 2594 2595 if (mutateIfCurrentEpoch(expectedEpoch) {2596 derivedKey?.let(VaultCrypto::zero)2597 derivedKey = newKey; newKey = null2598 publish()2599 _isUnlocked.value = true2600 } == null) return false2601 VaultKeyRotationHooks.onRotated()2602 true2603 } catch (_: Exception) {2604 false2605 } finally {2606 newKey?.let(VaultCrypto::zero)2607 plaintext?.let(VaultCrypto::zero)2608 }2609 }26102611 261226132614261526162617 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2618 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2619 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2620 var keyBytes: ByteArray? = null2621 var plaintext: ByteArray? = null2622 return try {2623 val salt = VaultCrypto.generateSalt()2624 val recoveryKey = deriveRecoveryKey(material, salt)2625 keyBytes = recoveryKey.encoded2626 plaintext = VaultCodec.encode(currentPayload())2627 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2628 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2629 } finally {2630 VaultCrypto.zero(material)2631 keyBytes?.let(VaultCrypto::zero)2632 plaintext?.let(VaultCrypto::zero)2633 }2634 }26352636 26372638263926402641264226432644 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2645 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2646 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2647 val rk = mutateState { rootKey?.copyOf() } ?: run {2648 VaultCrypto.zero(material)2649 return null2650 }2651 var keyBytes: ByteArray? = null2652 var plaintext: ByteArray? = null2653 return try {2654 val salt = VaultCrypto.generateSalt()2655 val recoveryKey = deriveRecoveryKey(material, salt)2656 keyBytes = recoveryKey.encoded2657 plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2658 2659 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2660 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2661 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2662 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2663 val ct = ctTag.copyOfRange(0, ctTag.size - 16)2664 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2665 } finally {2666 VaultCrypto.zero(rk)2667 VaultCrypto.zero(material)2668 keyBytes?.let(VaultCrypto::zero)2669 plaintext?.let(VaultCrypto::zero)2670 }2671 }26722673 2674 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2675 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2676 var keyBytes: ByteArray? = null2677 var pt: ByteArray? = null2678 return try {2679 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2680 keyBytes = recoveryKey.encoded2681 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2682 pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2683 hexToRootKey(String(pt, Charsets.US_ASCII))2684 } catch (_: Exception) {2685 null2686 } finally {2687 2688 2689 2690 VaultCrypto.zero(material)2691 keyBytes?.let(VaultCrypto::zero)2692 pt?.let(VaultCrypto::zero)2693 }2694 }26952696 269726982699270027012702 private fun persistSlotAWithEscrows(2703 recoveryEscrow: RecoveryEscrow?,2704 rootKeyEscrow: RootKeyEscrow?,2705 expectedEpoch: Long? = null,2706 ): Boolean {2707 val snapshot = snapshotForPersist(expectedEpoch)2708 ?: throw IllegalStateException("vault_locked_or_stale")2709 if (snapshot.decoy) {2710 VaultCrypto.zero(snapshot.key)2711 return false2712 }2713 try {2714 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2715 val plaintext = VaultCodec.encode(snapshot.payload)2716 val blob = try {2717 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2718 } finally {2719 2720 2721 VaultCrypto.zero(plaintext)2722 }2723 val next = prior.copy(2724 blob = blob,2725 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2726 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2727 )2728 beforeDurableCommit()2729 return withEpochCommit(snapshot.epoch) {2730 if (!store.writeSlotA(next)) return@withEpochCommit false2731 try {2732 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2733 2734 2735 2736 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2737 } catch (e: Exception) {2738 store.writeSlotA(prior)2739 throw e2740 }2741 true2742 } ?: false2743 } finally {2744 VaultCrypto.zero(snapshot.key)2745 }2746 }27472748 27492750 private fun requireUnlocked(): Long {2751 2752 2753 2754 stateLock.lock()2755 try {2756 if (derivedKey == null) throw IllegalStateException("vault_locked")2757 return sessionEpoch2758 } finally {2759 stateLock.unlock()2760 }2761 }27622763 2764 private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null27652766 private fun countDuplicateEntriesLocked(): Int {2767 val seen = mutableMapOf<String, VaultEntry>()2768 var duplicates = 02769 for (entry in entryList.filter { it.deletedAt == null }) {2770 val key = entry.duplicateKey()2771 val existing = seen[key]2772 if (existing == null) {2773 seen[key] = entry2774 } else {2775 duplicates++2776 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2777 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2778 if (entryStamp > existingStamp) seen[key] = entry2779 }2780 }2781 return duplicates2782 }27832784 private fun VaultEntry.duplicateKey(): String {2785 if (type == "note") return "note|${title.lowercase()}"2786 val passkeyData = passkey2787 if (passkeyData != null) {2788 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2789 }2790 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2791 }27922793 279427952796279727982799 private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2800 val epoch = expectedEpoch ?: currentEpoch()2801 if (mutateIfCurrentEpoch(epoch) { true } != true) return false2802 val slotA = store.loadSlotA() ?: return false2803 val vaultA = VaultCodec.encodeSlot(slotA)2804 val vaultB = store.loadSlotB() ?: slotA.blob2805 2806 2807 2808 2809 2810 val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2811 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162812 val fakeBlob = ByteArray(target).also(rng::nextBytes)2813 val fakeSalt = VaultCrypto.generateSalt()2814 VaultCodec.encodeSlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2815 }2816 val history = store.loadVaultHistory()2817 val latest = history.snapshots.firstOrNull()2818 if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2819 val entryCount = mutateIfCurrentEpoch(epoch) {2820 if (derivedKey != null && !decoyMode) {2821 bucketEntryCount(entryList.count { it.deletedAt == null })2822 } else {2823 null2824 }2825 } ?: return false2826 return try {2827 val snapshot = VaultSnapshot(2828 id = UUID.randomUUID().toString(),2829 savedAt = System.currentTimeMillis(),2830 reason = reason,2831 vault_a = vaultA,2832 vault_b = vaultB,2833 vault_d = vaultD,2834 entryCount = entryCount,2835 )2836 2837 2838 2839 withEpochCommit(epoch) {2840 store.writeVaultHistory(2841 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2842 )2843 } ?: false2844 } catch (_: Exception) {2845 false2846 }2847 }28482849 private fun bucketEntryCount(n: Int): Int = when {2850 n <= 0 -> 02851 n <= 10 -> 102852 n <= 25 -> 252853 n <= 50 -> 502854 n <= 100 -> 1002855 n <= 250 -> 2502856 n <= 500 -> 5002857 else -> ((n + 499) / 500) * 5002858 }28592860 286128622863286428652866286728682869 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2870 if (!entry.isCard()) return entry2871 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2872 val derived = if (digits.length >= 4) digits.takeLast(4) else null2873 return entry.copy(last4 = derived ?: entry.last4)2874 }28752876 287728782879288028812882 private fun autoPurgeExpiredTrash() {2883 val days = _settings.value.trashRetentionDays ?: return2884 if (days <= 0) return2885 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2886 val before = entryList.size2887 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2888 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2889 }28902891 289228932894289528962897 private fun consolidatePasskeyEntries() {2898 val passkeyOnly = entryList.filter { entry ->2899 entry.deletedAt == null &&2900 entry.isLogin() &&2901 entry.password.isNullOrBlank() &&2902 !entry.rpId.isNullOrBlank() &&2903 !entry.credentialId.isNullOrBlank()2904 }2905 if (passkeyOnly.isEmpty()) return2906 var changed = false2907 val now = System.currentTimeMillis()2908 for (pkEntry in passkeyOnly) {2909 val rpId = pkEntry.rpId ?: continue2910 val target = entryList.firstOrNull { candidate ->2911 candidate.deletedAt == null &&2912 candidate.id != pkEntry.id &&2913 candidate.isLogin() &&2914 candidate.passkey == null &&2915 candidate.credentialId.isNullOrBlank() &&2916 !candidate.password.isNullOrBlank() &&2917 listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2918 .any { com.peachpasswords.shared.extractDomain(it) == rpId }2919 } ?: continue2920 val idx = entryList.indexOfFirst { it.id == target.id }2921 if (idx < 0) continue2922 entryList[idx] = target.copy(2923 rpId = pkEntry.rpId,2924 rpName = pkEntry.rpName ?: target.rpName,2925 credentialId = pkEntry.credentialId,2926 publicKeyCose = pkEntry.publicKeyCose,2927 privateKeyJwk = pkEntry.privateKeyJwk,2928 userHandle = pkEntry.userHandle,2929 userName = pkEntry.userName,2930 userDisplayName = pkEntry.userDisplayName,2931 algorithm = pkEntry.algorithm,2932 signCount = pkEntry.signCount,2933 lastUsedAt = pkEntry.lastUsedAt,2934 modifiedAt = now,2935 )2936 2937 val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2938 if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2939 changed = true2940 }2941 if (changed) runCatching { persistSlotA(bumpVersion = false) }2942 }29432944 2945 private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }29462947 private fun currentPayloadLocked(): VaultPayload =2948 VaultPayload(2949 entries = entryList.toList(),2950 duressConfigured = authenticatedDuressConfigured,2951 rootKeyB64 = rootKey?.let(::b64) ?: "",2952 recoveryWordHash = recoveryWordHash,2953 recoveryWordsSet = recoveryWordsSet,2954 )29552956 29572958295929602961 private fun ensureRootKey(payload: VaultPayload) {2962 if (payload.rootKeyB64.isNotBlank()) {2963 rootKey = unb64(payload.rootKeyB64)2964 return2965 }2966 rootKey = generateRecoverableRootKey()2967 runCatching { persistSlotA(bumpVersion = false) }2968 }29692970 private fun publish() {2971 _entries.value = entryList.filter { it.deletedAt == null }2972 }29732974 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2975 var plaintext = VaultCodec.encode(currentPayload())2976 return try {2977 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2978 StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob)2979 } finally {2980 2981 2982 2983 VaultCrypto.zero(plaintext)2984 }2985 }29862987 private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2988 2989 2990 2991 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2992 val noise = ByteArray(approxBytes).also(rng::nextBytes)2993 return store.writeSlotB(b64(noise))2994 }29952996 299729982999 private fun matchingCiphertextLength(slotA: StoredVault): Int =3000 (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)30013002 30033004300530063007 private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {3008 val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 163009 val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)3010 val fakeSalt = VaultCrypto.generateSalt()3011 return store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))3012 }30133014 301530163017301830193020 private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {3021 val isConfigured = mutateState { authenticatedDuressConfigured }3022 return if (isConfigured) true else writeFakeDuressSlot(slotA)3023 }30243025 3026302730283029303030313032 private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {3033 val salt = unhex(b.salt)3034 val nonce = unhex(b.nonce)3035 val ct = unhex(b.ciphertext)3036 val tag = unhex(b.tag)3037 val blob = ByteArray(nonce.size + ct.size + tag.size).also {3038 System.arraycopy(nonce, 0, it, 0, nonce.size)3039 System.arraycopy(ct, 0, it, nonce.size, ct.size)3040 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)3041 }3042 return StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))3043 }3044 3045 private fun persistSlotA(3046 bumpVersion: Boolean,3047 snapshotReason: String? = "local_save",3048 expectedEpoch: Long? = null,3049 ): Boolean {3050 val snapshot = snapshotForPersist(expectedEpoch)3051 ?: throw IllegalStateException("vault_locked_or_stale")3052 return try {3053 3054 if (snapshot.decoy) {3055 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")3056 val plaintext = VaultCodec.encode(snapshot.payload)3057 val blob = try {3058 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_B))3059 } finally {3060 3061 3062 VaultCrypto.zero(plaintext)3063 }3064 beforeDurableCommit()3065 return withEpochCommit(snapshot.epoch) {3066 store.writeDecoySlot(prior.copy(version = CURRENT_ANDROID_SLOT_VERSION, blob = blob))3067 } ?: false3068 }3069 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")3070 3071 3072 3073 3074 val priorB = store.loadSlotB()3075 beforeDurableCommit()3076 if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false3077 val plaintext = VaultCodec.encode(snapshot.payload)3078 val blob = try {3079 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))3080 } finally {3081 3082 3083 VaultCrypto.zero(plaintext)3084 }3085 val next = prior.copy(blob = blob)3086 3087 3088 3089 3090 withEpochCommit(snapshot.epoch) {3091 if (!store.writeSlotA(next)) return@withEpochCommit false3092 try {3093 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")3094 3095 3096 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")3097 if (bumpVersion) store.stampLocalMutation()3098 } catch (e: Exception) {3099 store.writeSlotA(prior)3100 if (priorB != null) runCatching { store.writeSlotB(priorB) }3101 throw e3102 }3103 true3104 } ?: false3105 } finally {3106 3107 3108 VaultCrypto.zero(snapshot.key)3109 }3110 }31113112 3113311431153116311731183119 private fun commitVaultRotation(3120 priorA: StoredVault,3121 priorB: String?,3122 nextA: StoredVault,3123 expectedEpoch: Long,3124 ): Boolean {3125 beforeDurableCommit()3126 return withEpochCommit(expectedEpoch) {3127 if (!store.writeSlotA(nextA)) return@withEpochCommit false3128 3129 3130 3131 try {3132 if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")3133 3134 3135 3136 3137 if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")3138 store.stampLocalMutation()3139 } catch (_: Exception) {3140 rollbackRotation(priorA, priorB)3141 return@withEpochCommit false3142 }3143 true3144 } ?: false3145 }31463147 31483149315031513152 private fun rollbackRotation(priorA: StoredVault, priorB: String?) {3153 val failures = mutableListOf<String>()3154 runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }3155 .onFailure { failures += "writeSlotA: $it" }3156 if (priorB != null) {3157 runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }3158 .onFailure { failures += "writeSlotB: $it" }3159 }3160 if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }3161 }31623163 3164 private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {3165 try {3166 if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {3167 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3168 throw IllegalStateException("storage_write_failed")3169 }3170 } catch (e: Exception) {3171 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3172 throw e3173 }3174 3175 3176 3177 mutateIfCurrentEpoch(expectedEpoch) { publish() }3178 runCatching { LockedSyncSpoolHooks.refresh(this) }3179 }3180}