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(): Boolean = mutex.withLock {1806 lock()1807 val cleared = store.clearVault()1808 store.clearDecoySlot()1809 cleared1810 }18111812 18131814 1815181618171818181918201821182218231824182518261827 private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")18281829 private fun String?.normalizedEntryId(): String =1830 if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()18311832 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1833 val epoch = requireUnlocked()1834 val stamp = VaultCrypto.monotonicEntryTimestamp()1835 val now = System.currentTimeMillis()1836 val entry = withDerivedLast4(draft.copy(1837 id = draft.id.normalizedEntryId(),1838 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1839 modifiedAt = stamp,1840 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1841 ))1842 1843 1844 val rollback = mutateCurrentSession(epoch) {1845 val r = entryList.toMutableList()1846 entryList.add(entry)1847 r1848 } ?: throw IllegalStateException("vault_locked")1849 persistOrRollback(rollback, epoch)1850 entry1851 }18521853 185418551856185718581859186018611862 suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1863 val epoch = requireUnlocked()1864 if (drafts.isEmpty()) return 01865 val now = System.currentTimeMillis()1866 val ready = drafts.map { draft ->1867 val stamp = VaultCrypto.monotonicEntryTimestamp()1868 withDerivedLast4(1869 draft.copy(1870 id = draft.id.normalizedEntryId(),1871 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1872 modifiedAt = stamp,1873 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1874 ),1875 )1876 }1877 1878 val rollback = mutateCurrentSession(epoch) {1879 val r = entryList.toMutableList()1880 entryList.addAll(ready)1881 r1882 } ?: throw IllegalStateException("vault_locked")1883 persistOrRollback(rollback, epoch)1884 return drafts.size1885 }18861887 1888188918901891189218931894189518961897189818991900 suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1901 val epoch = requireUnlocked()1902 val now = System.currentTimeMillis()1903 val ready = newEntries.map { draft ->1904 val stamp = VaultCrypto.monotonicEntryTimestamp()1905 withDerivedLast4(1906 draft.copy(1907 id = draft.id.normalizedEntryId(),1908 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1909 modifiedAt = stamp,1910 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1911 ),1912 )1913 }1914 1915 1916 1917 1918 1919 1920 val incomingIds = ready.map { it.id }.toHashSet()1921 val rollback = mutateCurrentSession(epoch) {1922 val r = entryList.toMutableList()1923 val replaced = entryList.map { entry ->1924 if (entry.deletedAt != null) return@map entry1925 if (entry.id in incomingIds) return@map null1926 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1927 entry.copy(deletedAt = stamp, modifiedAt = stamp)1928 }.filterNotNull()1929 entryList = (replaced + ready).toMutableList()1930 r1931 } ?: throw IllegalStateException("vault_locked")1932 persistOrRollback(rollback, epoch)1933 return ready.size1934 }19351936 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1937 val epoch = requireUnlocked()1938 1939 1940 1941 1942 val prepared = mutateCurrentSession(epoch) {1943 val idx = entryList.indexOfFirst { it.id == patch.id }1944 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1945 val current = entryList[idx]1946 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1947 1948 val passwordChanged = patch.password != null && patch.password != current.password1949 1950 1951 1952 1953 1954 1955 val priorPassword = current.password1956 val shouldCapture = passwordChanged &&1957 !priorPassword.isNullOrEmpty() &&1958 current.passwordHistory?.firstOrNull()?.password != priorPassword1959 val nextHistory = if (shouldCapture) {1960 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1961 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1962 } else {1963 current.passwordHistory1964 }1965 val updated = withDerivedLast4(patch.copy(1966 createdAt = current.createdAt,1967 modifiedAt = stamp,1968 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1969 passwordHistory = nextHistory,1970 ))1971 val rollback = entryList.toMutableList()1972 entryList[idx] = updated1973 updated to rollback1974 } ?: throw IllegalStateException("vault_locked")1975 val (updated, rollback) = prepared1976 persistOrRollback(rollback, epoch)1977 updated1978 }19791980 1981 suspend fun deleteEntry(id: String) = mutex.withLock {1982 val epoch = requireUnlocked()1983 1984 1985 val rollback = mutateCurrentSession(epoch) {1986 val idx = entryList.indexOfFirst { it.id == id }1987 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1988 val current = entryList[idx]1989 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1990 val prior = entryList.toMutableList()1991 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1992 prior1993 } ?: throw IllegalStateException("vault_locked")1994 persistOrRollback(rollback, epoch)1995 }19961997 suspend fun restoreEntry(id: String) = mutex.withLock {1998 val epoch = requireUnlocked()1999 val rollback = mutateCurrentSession(epoch) {2000 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }2001 if (idx == -1) throw IllegalStateException("deleted entry not found")2002 val current = entryList[idx]2003 val prior = entryList.toMutableList()2004 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))2005 prior2006 } ?: throw IllegalStateException("vault_locked")2007 persistOrRollback(rollback, epoch)2008 }20092010 2011 suspend fun purgeEntry(id: String) = mutex.withLock {2012 val epoch = requireUnlocked()2013 val rollback = mutateCurrentSession(epoch) {2014 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }2015 if (idx == -1) throw IllegalStateException("deleted entry not found")2016 val prior = entryList.toMutableList()2017 entryList.removeAt(idx)2018 prior2019 } ?: throw IllegalStateException("vault_locked")2020 persistOrRollback(rollback, epoch)2021 }20222023 2024 suspend fun purgeDeletedEntries(): Int = mutex.withLock {2025 val epoch = requireUnlocked()2026 2027 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2028 val r = mutateCurrentSession(epoch) {2029 val rollback = entryList.toMutableList()2030 val before = entryList.size2031 entryList.removeAll { it.deletedAt != null }2032 R(rollback, before - entryList.size)2033 } ?: throw IllegalStateException("vault_locked")2034 if (r.removed > 0) persistOrRollback(r.rollback, epoch)2035 r.removed2036 }20372038 2039 suspend fun countDuplicateEntries(): Int = mutex.withLock {2040 val epoch = requireUnlocked()2041 2042 2043 mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }2044 ?: throw IllegalStateException("vault_locked")2045 }20462047 20482049205020512052 suspend fun deduplicateEntries(): Int = mutex.withLock {2053 val epoch = requireUnlocked()2054 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)2055 val ready = mutateCurrentSession(epoch) {2056 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")2057 val active = entryList.filter { it.deletedAt == null }2058 val keepIds = mutableSetOf<String>()2059 active.groupBy { it.duplicateKey() }.values.forEach { group ->2060 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id2061 }2062 val rollback = entryList.toMutableList()2063 var removed = 02064 entryList = entryList.map { entry ->2065 if (entry.deletedAt == null && entry.id !in keepIds) {2066 removed++2067 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)2068 entry.copy(deletedAt = stamp, modifiedAt = stamp)2069 } else {2070 entry2071 }2072 }.toMutableList()2073 R(rollback, removed)2074 } ?: throw IllegalStateException("vault_locked")2075 if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)2076 ready.removed2077 }20782079 fun getEntries(): List<VaultEntry> = mutateState {2080 if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }2081 }2082 fun getEntry(id: String): VaultEntry? = mutateState {2083 if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }2084 }2085 fun getDeletedEntries(): List<VaultEntry> = mutateState {2086 if (!sessionDataAvailable) emptyList()2087 else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }2088 }20892090 2091 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {2092 return mutateState {2093 if (!sessionDataAvailable) return@mutateState emptyList()2094 val active = entryList.filter { it.deletedAt == null }2095 if (tagFilter == null) return@mutateState active2096 val needle = tagFilter.trim().lowercase()2097 active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }2098 }2099 }21002101 2102 fun getDistinctTags(): List<String> = mutateState {2103 if (!sessionDataAvailable) return@mutateState emptyList()2104 entryList.asSequence()2105 .filter { it.deletedAt == null }2106 .flatMap { it.tags?.asSequence() ?: emptySequence() }2107 .map { it.trim().lowercase() }2108 .filter { it.isNotEmpty() }2109 .distinct()2110 .sorted()2111 .toList()2112 }21132114 211521162117211821192120 fun getDistinctFieldValues(field: String): List<String> {2121 val select: (VaultEntry) -> String? = when (field) {2122 "username" -> { e -> e.username }2123 "email" -> { e -> e.email }2124 else -> return emptyList()2125 }2126 return mutateState {2127 if (!sessionDataAvailable) return@mutateState emptyList()2128 entryList.asSequence()2129 .filter { it.deletedAt == null }2130 .mapNotNull { select(it)?.trim() }2131 .filter { it.isNotEmpty() }2132 .groupingBy { it.lowercase() }2133 .aggregate { _, acc: Pair<String, Int>?, value, _ ->2134 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)2135 }2136 .values2137 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })2138 .map { it.first }2139 }2140 }21412142 fun getTombstones(): List<Tombstone> = mutateState {2143 if (!sessionDataAvailable) emptyList()2144 else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }2145 }2146 fun getVaultVersion(): Long = store.version()2147 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots21482149 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {2150 val expectedEpoch = currentEpoch()2151 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false2152 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false2153 2154 2155 val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)2156 val priorA = store.loadSlotA()2157 val priorB = store.loadSlotB()2158 val priorD = store.loadDecoySlot()2159 2160 2161 2162 2163 2164 val priorHistory = store.loadVaultHistory()2165 2166 2167 2168 2169 beforeDurableCommit()2170 if (!takeVaultSnapshot("restore", expectedEpoch)) {2171 return false2172 }2173 2174 2175 2176 val nextD: StoredVault = restoredD ?: run {2177 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 162178 val fakeBlob = ByteArray(target).also(rng::nextBytes)2179 val fakeSalt = VaultCrypto.generateSalt()2180 StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob))2181 }2182 if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2183 withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2184 return false2185 }2186 lock()2187 true2188 }21892190 21912192219321942195219621972198219922002201 private fun commitRestoreAtomic(2202 nextA: StoredVault,2203 nextB: String,2204 nextD: StoredVault,2205 priorA: StoredVault?,2206 priorB: String?,2207 priorD: StoredVault?,2208 expectedEpoch: Long,2209 ): Boolean {2210 return withEpochCommit(expectedEpoch) {2211 if (!store.writeSlotA(nextA)) return@withEpochCommit false2212 2213 2214 2215 try {2216 if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2217 2218 2219 if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2220 store.stampLocalMutation()2221 } catch (_: Exception) {2222 reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2223 return@withEpochCommit false2224 }2225 true2226 } ?: false2227 }22282229 22302231 22322233223422352236 suspend fun applyMergedRemoteEntries(2237 remoteEntries: List<VaultEntry>,2238 remoteTombstones: List<Tombstone>,2239 expectedEpoch: Long? = null,2240 ): Int = mutex.withLock {2241 val epoch = expectedEpoch ?: requireUnlocked()2242 if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02243 2244 2245 2246 2247 2248 val mergeNow = System.currentTimeMillis()2249 val clamped = remoteEntries.mapNotNull { entry ->2250 2251 2252 2253 SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2254 modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2255 deletedAt = entry.deletedAt?.let {2256 SyncLimits.clampSyncTimestamp(it, mergeNow)2257 },2258 )2259 }2260 val tombMap = remoteTombstones.associate {2261 it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2262 }2263 2264 2265 val applied = mutateCurrentSession(epoch) {2266 var n = 02267 val byId = entryList.associateBy { it.id }.toMutableMap()22682269 for (remote in clamped) {2270 val tomb = tombMap[remote.id]2271 if (tomb != null && tomb >= remote.modifiedAt) continue2272 val local = byId[remote.id]2273 if (local == null) {2274 entryList.add(remote); byId[remote.id] = remote; n++2275 } else if (remote.modifiedAt > local.modifiedAt) {2276 val i = entryList.indexOfFirst { it.id == local.id }2277 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2278 }2279 }22802281 for ((id, deletedAt) in tombMap) {2282 val local = byId[id] ?: continue2283 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2284 if (deletedAt < local.modifiedAt) continue2285 val i = entryList.indexOfFirst { it.id == id }2286 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2287 }2288 n2289 } ?: return@withLock 022902291 if (applied > 0) {2292 persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2293 mutateIfCurrentEpoch(epoch) { publish() }2294 runCatching { LockedSyncSpoolHooks.refresh(this) }2295 }2296 applied2297 }22982299 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2300 2301 2302 2303 2304 if (mutateState { decoyMode }) {2305 val decoyEpoch = requireUnlocked()2306 mutateCurrentSession(decoyEpoch) { _settings.value = settings }2307 ?: throw IllegalStateException("vault_locked")2308 return@withLock2309 }2310 2311 2312 2313 val epoch = requireUnlocked()2314 val prior = mutateCurrentSession(epoch) {2315 val old = _settings.value2316 _settings.value = settings2317 old2318 } ?: throw IllegalStateException("vault_locked")23192320 val committed = try {2321 beforeDurableCommit()2322 2323 2324 2325 withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2326 } catch (_: Exception) {2327 false2328 }2329 if (!committed) {2330 2331 2332 2333 mutateIfCurrentEpoch(epoch) { _settings.value = prior }2334 throw IllegalStateException("settings_write_failed")2335 }2336 }23372338 23392340 2341 fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }23422343 23442345234623472348 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2349 val epoch = requireUnlocked()2350 2351 2352 2353 2354 2355 2356 val prior = mutateCurrentSession(epoch) {2357 val priorPair = recoveryWordHash to recoveryWordsSet2358 recoveryWordHash = recoveryWordsHash(words)2359 recoveryWordsSet = true2360 priorPair2361 } ?: return@withLock false2362 2363 2364 2365 2366 val persisted = runCatching {2367 persistSlotAWithEscrows(2368 buildRecoveryEscrow(words),2369 buildRootKeyEscrow(words),2370 expectedEpoch = epoch,2371 )2372 }.getOrDefault(false)2373 if (!persisted) {2374 mutateIfCurrentEpoch(epoch) {2375 recoveryWordHash = prior.first2376 recoveryWordsSet = prior.second2377 }2378 }2379 persisted2380 }23812382 2383 fun verifyRecoveryWords(words: List<String>): Boolean {2384 return mutateState {2385 val stored = recoveryWordHash ?: return@mutateState false2386 MessageDigest.isEqual(2387 stored.toByteArray(Charsets.UTF_8),2388 recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2389 )2390 }2391 }23922393 23942395 2396 fun hasRecoveryEscrow(): Boolean =2397 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false23982399 24002401240224032404 private fun ensureRecoveryEscrow() {2405 if (hasRecoveryEscrow()) return2406 val rk = mutateState { rootKey?.copyOf() } ?: return2407 runCatching {2408 val words = rootKeyToWords(rk)2409 val escrow = buildRecoveryEscrow(words)2410 val rkEscrow = buildRootKeyEscrow(words)2411 if (escrow != null || rkEscrow != null) {2412 val prior = store.loadSlotA() ?: return@runCatching2413 store.writeSlotA(prior.copy(2414 recoveryEscrow = escrow ?: prior.recoveryEscrow,2415 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2416 ))2417 mutateState {2418 recoveryWordHash = recoveryWordsHash(words)2419 recoveryWordsSet = true2420 }2421 }2422 }.also { VaultCrypto.zero(rk) }2423 }24242425 242624272428242924302431243224332434243524362437 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2438 val expectedEpoch = currentEpoch()2439 val slotA = store.loadSlotA() ?: return false2440 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false24412442 2443 2444 val fullEscrow = slotA.recoveryEscrow2445 if (fullEscrow != null) {2446 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2447 if (material != null) {2448 var keyBytes: ByteArray? = null2449 var plaintext: ByteArray? = null2450 var candidateRoot: ByteArray? = null2451 var stateCommitStarted = false2452 try {2453 keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2454 plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2455 val payload = VaultCodec.decode(plaintext)2456 2457 2458 2459 2460 val candidateSettings = store.loadSettings()2461 candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2462 val decodedRoot = unb64(payload.rootKeyB64)2463 if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2464 2465 2466 2467 VaultCrypto.zero(decodedRoot)2468 throw IllegalArgumentException("invalid recovery root key")2469 }2470 decodedRoot2471 } else {2472 generateRecoverableRootKey()2473 }2474 stateCommitStarted = true2475 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2476 clearSessionStateLocked()2477 entryList = payload.entries.toMutableList()2478 authenticatedDuressConfigured = payload.duressConfigured2479 _duressConfigured.value = payload.duressConfigured2480 recoveryWordHash = payload.recoveryWordHash2481 recoveryWordsSet = payload.recoveryWordsSet2482 rootKey = candidateRoot2483 candidateRoot = null2484 _settings.value = candidateSettings2485 publish()2486 2487 2488 sessionDataAvailable = true2489 _isUnlocked.value = false2490 true2491 }2492 if (adopted == true) return@withLock true2493 } catch (_: Exception) {2494 2495 2496 2497 2498 if (stateCommitStarted) {2499 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2500 }2501 } finally {2502 plaintext?.let(VaultCrypto::zero)2503 VaultCrypto.zero(material)2504 keyBytes?.let(VaultCrypto::zero)2505 candidateRoot?.let(VaultCrypto::zero)2506 }2507 }2508 }25092510 2511 2512 2513 val rootEscrow = slotA.rootKeyEscrow2514 if (rootEscrow != null) {2515 var candidateRoot: ByteArray? = null2516 var stateCommitStarted = false2517 try {2518 candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2519 require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2520 val candidateSettings = store.loadSettings()2521 stateCommitStarted = true2522 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2523 clearSessionStateLocked()2524 entryList = mutableListOf()2525 authenticatedDuressConfigured = false2526 _duressConfigured.value = false2527 recoveryWordHash = recoveryWordsHash(words)2528 recoveryWordsSet = true2529 rootKey = candidateRoot2530 candidateRoot = null2531 _settings.value = candidateSettings2532 publish()2533 sessionDataAvailable = true2534 _isUnlocked.value = false2535 true2536 }2537 if (adopted == true) return@withLock true2538 } catch (_: Exception) {2539 if (stateCommitStarted) {2540 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2541 }2542 } finally {2543 candidateRoot?.let(VaultCrypto::zero)2544 }2545 }2546 return false2547 }25482549 255025512552255325542555255625572558 suspend fun resetPasswordWithRecoveryWords(2559 words: List<String>,2560 newPassword: String,2561 ): Boolean = mutex.withLock {2562 val expectedEpoch = currentEpoch()2563 2564 2565 2566 if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2567 val priorA = store.loadSlotA() ?: return false2568 var newKey: ByteArray? = null2569 var plaintext: ByteArray? = null2570 return try {2571 val newSalt = VaultCrypto.generateSalt()2572 newKey = VaultCrypto.deriveKey(newPassword, newSalt)2573 plaintext = VaultCodec.encode(currentPayload())2574 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2575 2576 2577 2578 val valid = words.size == 12 && findInvalidWords(words).isEmpty()2579 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2580 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2581 val next = StoredVault(2582 version = priorA.version,2583 salt = b64(newSalt),2584 blob = blob,2585 recoveryEscrow = freshRecovery,2586 rootKeyEscrow = freshRootKey,2587 )2588 2589 2590 2591 val priorB = store.loadSlotB()2592 if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2593 2594 2595 2596 if (mutateIfCurrentEpoch(expectedEpoch) {2597 derivedKey?.let(VaultCrypto::zero)2598 derivedKey = newKey; newKey = null2599 publish()2600 _isUnlocked.value = true2601 } == null) return false2602 VaultKeyRotationHooks.onRotated()2603 true2604 } catch (_: Exception) {2605 false2606 } finally {2607 newKey?.let(VaultCrypto::zero)2608 plaintext?.let(VaultCrypto::zero)2609 }2610 }26112612 261326142615261626172618 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2619 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2620 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2621 var keyBytes: ByteArray? = null2622 var plaintext: ByteArray? = null2623 return try {2624 val salt = VaultCrypto.generateSalt()2625 val recoveryKey = deriveRecoveryKey(material, salt)2626 keyBytes = recoveryKey.encoded2627 plaintext = VaultCodec.encode(currentPayload())2628 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2629 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2630 } finally {2631 VaultCrypto.zero(material)2632 keyBytes?.let(VaultCrypto::zero)2633 plaintext?.let(VaultCrypto::zero)2634 }2635 }26362637 26382639264026412642264326442645 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2646 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2647 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2648 val rk = mutateState { rootKey?.copyOf() } ?: run {2649 VaultCrypto.zero(material)2650 return null2651 }2652 var keyBytes: ByteArray? = null2653 var plaintext: ByteArray? = null2654 return try {2655 val salt = VaultCrypto.generateSalt()2656 val recoveryKey = deriveRecoveryKey(material, salt)2657 keyBytes = recoveryKey.encoded2658 plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2659 2660 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2661 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2662 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2663 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2664 val ct = ctTag.copyOfRange(0, ctTag.size - 16)2665 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2666 } finally {2667 VaultCrypto.zero(rk)2668 VaultCrypto.zero(material)2669 keyBytes?.let(VaultCrypto::zero)2670 plaintext?.let(VaultCrypto::zero)2671 }2672 }26732674 2675 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2676 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2677 var keyBytes: ByteArray? = null2678 var pt: ByteArray? = null2679 return try {2680 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2681 keyBytes = recoveryKey.encoded2682 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2683 pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2684 hexToRootKey(String(pt, Charsets.US_ASCII))2685 } catch (_: Exception) {2686 null2687 } finally {2688 2689 2690 2691 VaultCrypto.zero(material)2692 keyBytes?.let(VaultCrypto::zero)2693 pt?.let(VaultCrypto::zero)2694 }2695 }26962697 269826992700270127022703 private fun persistSlotAWithEscrows(2704 recoveryEscrow: RecoveryEscrow?,2705 rootKeyEscrow: RootKeyEscrow?,2706 expectedEpoch: Long? = null,2707 ): Boolean {2708 val snapshot = snapshotForPersist(expectedEpoch)2709 ?: throw IllegalStateException("vault_locked_or_stale")2710 if (snapshot.decoy) {2711 VaultCrypto.zero(snapshot.key)2712 return false2713 }2714 try {2715 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2716 val plaintext = VaultCodec.encode(snapshot.payload)2717 val blob = try {2718 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2719 } finally {2720 2721 2722 VaultCrypto.zero(plaintext)2723 }2724 val next = prior.copy(2725 blob = blob,2726 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2727 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2728 )2729 beforeDurableCommit()2730 return withEpochCommit(snapshot.epoch) {2731 if (!store.writeSlotA(next)) return@withEpochCommit false2732 try {2733 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2734 2735 2736 2737 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2738 } catch (e: Exception) {2739 store.writeSlotA(prior)2740 throw e2741 }2742 true2743 } ?: false2744 } finally {2745 VaultCrypto.zero(snapshot.key)2746 }2747 }27482749 27502751 private fun requireUnlocked(): Long {2752 2753 2754 2755 stateLock.lock()2756 try {2757 if (derivedKey == null) throw IllegalStateException("vault_locked")2758 return sessionEpoch2759 } finally {2760 stateLock.unlock()2761 }2762 }27632764 2765 private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null27662767 private fun countDuplicateEntriesLocked(): Int {2768 val seen = mutableMapOf<String, VaultEntry>()2769 var duplicates = 02770 for (entry in entryList.filter { it.deletedAt == null }) {2771 val key = entry.duplicateKey()2772 val existing = seen[key]2773 if (existing == null) {2774 seen[key] = entry2775 } else {2776 duplicates++2777 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2778 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2779 if (entryStamp > existingStamp) seen[key] = entry2780 }2781 }2782 return duplicates2783 }27842785 private fun VaultEntry.duplicateKey(): String {2786 if (type == "note") return "note|${title.lowercase()}"2787 val passkeyData = passkey2788 if (passkeyData != null) {2789 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2790 }2791 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2792 }27932794 279527962797279827992800 private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2801 val epoch = expectedEpoch ?: currentEpoch()2802 if (mutateIfCurrentEpoch(epoch) { true } != true) return false2803 val slotA = store.loadSlotA() ?: return false2804 val vaultA = VaultCodec.encodeSlot(slotA)2805 val vaultB = store.loadSlotB() ?: slotA.blob2806 2807 2808 2809 2810 2811 val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2812 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162813 val fakeBlob = ByteArray(target).also(rng::nextBytes)2814 val fakeSalt = VaultCrypto.generateSalt()2815 VaultCodec.encodeSlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))2816 }2817 val history = store.loadVaultHistory()2818 val latest = history.snapshots.firstOrNull()2819 if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2820 val entryCount = mutateIfCurrentEpoch(epoch) {2821 if (derivedKey != null && !decoyMode) {2822 bucketEntryCount(entryList.count { it.deletedAt == null })2823 } else {2824 null2825 }2826 } ?: return false2827 return try {2828 val snapshot = VaultSnapshot(2829 id = UUID.randomUUID().toString(),2830 savedAt = System.currentTimeMillis(),2831 reason = reason,2832 vault_a = vaultA,2833 vault_b = vaultB,2834 vault_d = vaultD,2835 entryCount = entryCount,2836 )2837 2838 2839 2840 withEpochCommit(epoch) {2841 store.writeVaultHistory(2842 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2843 )2844 } ?: false2845 } catch (_: Exception) {2846 false2847 }2848 }28492850 private fun bucketEntryCount(n: Int): Int = when {2851 n <= 0 -> 02852 n <= 10 -> 102853 n <= 25 -> 252854 n <= 50 -> 502855 n <= 100 -> 1002856 n <= 250 -> 2502857 n <= 500 -> 5002858 else -> ((n + 499) / 500) * 5002859 }28602861 286228632864286528662867286828692870 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2871 if (!entry.isCard()) return entry2872 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2873 val derived = if (digits.length >= 4) digits.takeLast(4) else null2874 return entry.copy(last4 = derived ?: entry.last4)2875 }28762877 287828792880288128822883 private fun autoPurgeExpiredTrash() {2884 val days = _settings.value.trashRetentionDays ?: return2885 if (days <= 0) return2886 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2887 val before = entryList.size2888 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2889 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2890 }28912892 289328942895289628972898 private fun consolidatePasskeyEntries() {2899 val passkeyOnly = entryList.filter { entry ->2900 entry.deletedAt == null &&2901 entry.isLogin() &&2902 entry.password.isNullOrBlank() &&2903 !entry.rpId.isNullOrBlank() &&2904 !entry.credentialId.isNullOrBlank()2905 }2906 if (passkeyOnly.isEmpty()) return2907 var changed = false2908 val now = System.currentTimeMillis()2909 for (pkEntry in passkeyOnly) {2910 val rpId = pkEntry.rpId ?: continue2911 val target = entryList.firstOrNull { candidate ->2912 candidate.deletedAt == null &&2913 candidate.id != pkEntry.id &&2914 candidate.isLogin() &&2915 candidate.passkey == null &&2916 candidate.credentialId.isNullOrBlank() &&2917 !candidate.password.isNullOrBlank() &&2918 listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2919 .any { com.peachpasswords.shared.extractDomain(it) == rpId }2920 } ?: continue2921 val idx = entryList.indexOfFirst { it.id == target.id }2922 if (idx < 0) continue2923 entryList[idx] = target.copy(2924 rpId = pkEntry.rpId,2925 rpName = pkEntry.rpName ?: target.rpName,2926 credentialId = pkEntry.credentialId,2927 publicKeyCose = pkEntry.publicKeyCose,2928 privateKeyJwk = pkEntry.privateKeyJwk,2929 userHandle = pkEntry.userHandle,2930 userName = pkEntry.userName,2931 userDisplayName = pkEntry.userDisplayName,2932 algorithm = pkEntry.algorithm,2933 signCount = pkEntry.signCount,2934 lastUsedAt = pkEntry.lastUsedAt,2935 modifiedAt = now,2936 )2937 2938 val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2939 if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2940 changed = true2941 }2942 if (changed) runCatching { persistSlotA(bumpVersion = false) }2943 }29442945 2946 private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }29472948 private fun currentPayloadLocked(): VaultPayload =2949 VaultPayload(2950 entries = entryList.toList(),2951 duressConfigured = authenticatedDuressConfigured,2952 rootKeyB64 = rootKey?.let(::b64) ?: "",2953 recoveryWordHash = recoveryWordHash,2954 recoveryWordsSet = recoveryWordsSet,2955 )29562957 29582959296029612962 private fun ensureRootKey(payload: VaultPayload) {2963 if (payload.rootKeyB64.isNotBlank()) {2964 rootKey = unb64(payload.rootKeyB64)2965 return2966 }2967 rootKey = generateRecoverableRootKey()2968 runCatching { persistSlotA(bumpVersion = false) }2969 }29702971 private fun publish() {2972 _entries.value = entryList.filter { it.deletedAt == null }2973 }29742975 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2976 var plaintext = VaultCodec.encode(currentPayload())2977 return try {2978 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2979 StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob)2980 } finally {2981 2982 2983 2984 VaultCrypto.zero(plaintext)2985 }2986 }29872988 private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2989 2990 2991 2992 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2993 val noise = ByteArray(approxBytes).also(rng::nextBytes)2994 return store.writeSlotB(b64(noise))2995 }29962997 299829993000 private fun matchingCiphertextLength(slotA: StoredVault): Int =3001 (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)30023003 30043005300630073008 private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {3009 val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 163010 val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)3011 val fakeSalt = VaultCrypto.generateSalt()3012 return store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))3013 }30143015 301630173018301930203021 private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {3022 val isConfigured = mutateState { authenticatedDuressConfigured }3023 return if (isConfigured) true else writeFakeDuressSlot(slotA)3024 }30253026 3027302830293030303130323033 private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {3034 val salt = unhex(b.salt)3035 val nonce = unhex(b.nonce)3036 val ct = unhex(b.ciphertext)3037 val tag = unhex(b.tag)3038 val blob = ByteArray(nonce.size + ct.size + tag.size).also {3039 System.arraycopy(nonce, 0, it, 0, nonce.size)3040 System.arraycopy(ct, 0, it, nonce.size, ct.size)3041 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)3042 }3043 return StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))3044 }3045 3046 private fun persistSlotA(3047 bumpVersion: Boolean,3048 snapshotReason: String? = "local_save",3049 expectedEpoch: Long? = null,3050 ): Boolean {3051 val snapshot = snapshotForPersist(expectedEpoch)3052 ?: throw IllegalStateException("vault_locked_or_stale")3053 return try {3054 3055 if (snapshot.decoy) {3056 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")3057 val plaintext = VaultCodec.encode(snapshot.payload)3058 val blob = try {3059 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_B))3060 } finally {3061 3062 3063 VaultCrypto.zero(plaintext)3064 }3065 beforeDurableCommit()3066 return withEpochCommit(snapshot.epoch) {3067 store.writeDecoySlot(prior.copy(version = CURRENT_ANDROID_SLOT_VERSION, blob = blob))3068 } ?: false3069 }3070 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")3071 3072 3073 3074 3075 val priorB = store.loadSlotB()3076 beforeDurableCommit()3077 if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false3078 val plaintext = VaultCodec.encode(snapshot.payload)3079 val blob = try {3080 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))3081 } finally {3082 3083 3084 VaultCrypto.zero(plaintext)3085 }3086 val next = prior.copy(blob = blob)3087 3088 3089 3090 3091 withEpochCommit(snapshot.epoch) {3092 if (!store.writeSlotA(next)) return@withEpochCommit false3093 try {3094 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")3095 3096 3097 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")3098 if (bumpVersion) store.stampLocalMutation()3099 } catch (e: Exception) {3100 store.writeSlotA(prior)3101 if (priorB != null) runCatching { store.writeSlotB(priorB) }3102 throw e3103 }3104 true3105 } ?: false3106 } finally {3107 3108 3109 VaultCrypto.zero(snapshot.key)3110 }3111 }31123113 3114311531163117311831193120 private fun commitVaultRotation(3121 priorA: StoredVault,3122 priorB: String?,3123 nextA: StoredVault,3124 expectedEpoch: Long,3125 ): Boolean {3126 beforeDurableCommit()3127 return withEpochCommit(expectedEpoch) {3128 if (!store.writeSlotA(nextA)) return@withEpochCommit false3129 3130 3131 3132 try {3133 if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")3134 3135 3136 3137 3138 if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")3139 store.stampLocalMutation()3140 } catch (_: Exception) {3141 rollbackRotation(priorA, priorB)3142 return@withEpochCommit false3143 }3144 true3145 } ?: false3146 }31473148 31493150315131523153 private fun rollbackRotation(priorA: StoredVault, priorB: String?) {3154 val failures = mutableListOf<String>()3155 runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }3156 .onFailure { failures += "writeSlotA: $it" }3157 if (priorB != null) {3158 runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }3159 .onFailure { failures += "writeSlotB: $it" }3160 }3161 if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }3162 }31633164 3165 private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {3166 try {3167 if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {3168 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3169 throw IllegalStateException("storage_write_failed")3170 }3171 } catch (e: Exception) {3172 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }3173 throw e3174 }3175 3176 3177 3178 mutateIfCurrentEpoch(expectedEpoch) { publish() }3179 runCatching { LockedSyncSpoolHooks.refresh(this) }3180 }3181}