1package com.peachpasswords.vault23import kotlinx.coroutines.flow.MutableStateFlow4import kotlinx.coroutines.flow.StateFlow5import kotlinx.coroutines.flow.asStateFlow6import kotlinx.coroutines.sync.Mutex7import kotlinx.coroutines.sync.withLock8import java.security.MessageDigest9import java.security.SecureRandom10import java.text.Normalizer11import kotlinx.serialization.json.Json12import android.os.SystemClock13import android.util.Log14import androidx.annotation.VisibleForTesting15import com.peachpasswords.BuildConfig16import com.peachpasswords.sync.SyncLimits17import com.peachpasswords.sync.LockedSyncSpoolHooks18import kotlinx.serialization.json.JsonElement19import kotlinx.serialization.json.JsonNull20import kotlinx.serialization.json.JsonObject21import kotlinx.serialization.json.JsonPrimitive22import java.util.Base6423import java.util.UUID24import java.util.concurrent.locks.ReentrantLock25import javax.inject.Inject26import javax.inject.Singleton272829private val CodexJson = Json { ignoreUnknownKeys = true; isLenient = true }3031private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)32private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)333435private const val PASSWORD_HISTORY_MAX = 5036private const val VAULT_HISTORY_MAX = 537383940414243private const val BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS = 30_000L4445sealed interface UnlockResult {46 data object Success : UnlockResult47 data object WrongPassword : UnlockResult48 data class Error(val reason: String) : UnlockResult49}5051sealed interface CreateVaultResult {52 data object Success : CreateVaultResult53 data class Error(val reason: String) : CreateVaultResult54}5556sealed interface AdoptVaultResult {57 data class Success(val vaultId: String) : AdoptVaultResult58 data class Error(val reason: String) : AdoptVaultResult59}606162636465666768697071727374@Singleton75class VaultRepository @Inject constructor(76 private val store: VaultStorage,77) {78 private val mutex = Mutex()79 80 81 82 83 84 85 86 private val stateLock = ReentrantLock()87 private val rng = SecureRandom()8889 9091929394 private var sessionEpoch: Long = 0L9596 private fun nextSessionEpoch(epoch: Long): Long =97 if (epoch == Long.MAX_VALUE) 0L else epoch + 1L9899 100 @VisibleForTesting101 internal var beforeDurableCommit: () -> Unit = {}102103 104 @VisibleForTesting105 internal var afterCodexRollback: () -> Unit = {}106107 108109110111112 private inline fun <T> mutateState(block: () -> T): T {113 stateLock.lock()114 return try { block() } finally { stateLock.unlock() }115 }116117 118 private inline fun <T> withEpochCommit(epoch: Long, block: () -> T): T? {119 stateLock.lock()120 return try {121 if (sessionEpoch != epoch) null else block()122 } finally {123 stateLock.unlock()124 }125 }126127 128 @VisibleForTesting129 internal var beforeSessionEpochCommit: () -> Unit = {}130131 132133134135136 @VisibleForTesting137 internal var beforeSessionStateMutation: () -> Unit = {}138139 140141142143144145 internal fun <T> withSessionEpochCommit(epoch: Long, block: () -> T): T? {146 beforeSessionEpochCommit()147 return withEpochCommit(epoch, block)148 }149150 private fun currentEpoch(): Long = mutateState { sessionEpoch }151152 private inline fun <T> mutateIfCurrentEpoch(epoch: Long, block: () -> T): T? =153 mutateState { if (sessionEpoch == epoch) block() else null }154155 156 private inline fun <T> mutateCurrentSession(epoch: Long, block: () -> T): T? {157 beforeSessionStateMutation()158 return mutateIfCurrentEpoch(epoch, block)159 }160161 private data class PersistSnapshot(162 val epoch: Long,163 val key: ByteArray,164 val payload: VaultPayload,165 val decoy: Boolean,166 )167168 169 private fun snapshotForPersist(expectedEpoch: Long? = null): PersistSnapshot? = mutateState {170 if (expectedEpoch != null && sessionEpoch != expectedEpoch) return@mutateState null171 val liveKey = derivedKey ?: return@mutateState null172 PersistSnapshot(173 epoch = sessionEpoch,174 key = liveKey.copyOf(),175 payload = currentPayloadLocked(),176 decoy = decoyMode,177 )178 }179180 private var derivedKey: ByteArray? = null181 private var rootKey: ByteArray? = null182 private var entryList: MutableList<VaultEntry> = mutableListOf()183 private var authenticatedDuressConfigured: Boolean = false184 private var recoveryWordHash: String? = null185 private var recoveryWordsSet: Boolean = false186 187 private var sessionDataAvailable: Boolean = false188 189 private var decoyMode: Boolean = false190191 private val _isUnlocked = MutableStateFlow(false)192 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()193194 private val _duressConfigured = MutableStateFlow(false)195 196 val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()197198199 200201202203204205 private val _uiGateLocked = MutableStateFlow(false)206 val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()207208 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())209 210 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()211212 213 214 215 216 private val _settings = MutableStateFlow(store.loadSettings())217 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()218219 220 private fun clearSessionStateLocked() {221 derivedKey?.let(VaultCrypto::zero)222 rootKey?.let(VaultCrypto::zero)223 derivedKey = null224 rootKey = null225 entryList = mutableListOf()226 authenticatedDuressConfigured = false227 _duressConfigured.value = false228 recoveryWordHash = null229 recoveryWordsSet = false230 sessionDataAvailable = false231 decoyMode = false232 _settings.value = store.loadSettings()233 _entries.value = emptyList()234 _isUnlocked.value = false235 }236237 fun hasVault(): Boolean = store.hasVault()238239 240241 242243244245246247248 fun codexVaultBlobBase64(): String? {249 val slotA = store.loadSlotA() ?: return null250 251 252 val slotD = store.loadDecoySlot() ?: return null253 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""254 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))255 }256257 258259260261262 263 private fun JsonElement?.asSlotJson(): String? = when {264 this == null || this is JsonNull -> null265 this is JsonPrimitive && isString -> content266 else -> toString()267 }268269 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {270 val expectedEpoch = currentEpoch()271 var candidateKey: ByteArray? = null272 var plaintext: ByteArray? = null273 return try {274 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)275 276 277 278 279 280 281 282 val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject283 ?: return UnlockResult.Error("invalid_codex_blob")284 val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")285 286 287 288 289 290 val slotA = VaultCodec.decodeSlot(slotJson)291 ?: BrowserSlot.parse(slotJson)?.let {292 BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword293 }294 ?: return UnlockResult.Error("invalid_codex_blob")295 296 297 298 299 300 candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))301 plaintext = decryptSlotABlob(slotA, candidateKey)302 303 304 305 306 if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {307 VaultCrypto.zero(candidateKey)308 candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))309 plaintext = decryptSlotABlob(slotA, candidateKey)310 }311 if (plaintext == null) return UnlockResult.WrongPassword312 val payload = try {313 VaultCodec.decode(plaintext)314 } catch (_: Exception) {315 return UnlockResult.Error("invalid_codex_blob")316 }317318 val priorA = store.loadSlotA()319 val priorB = store.loadSlotB()320 val priorD = store.loadDecoySlot()321 322 323 324 325 326 val codexDuressJson = wrapper["b"].asSlotJson()327 val codexDuress: StoredVault? = codexDuressJson?.let {328 VaultCodec.decodeSlot(it) ?: BrowserSlot.parse(it)?.let { b ->329 330 331 332 333 334 335 browserDuressPassthrough(b)336 }337 }338339 beforeDurableCommit()340 val committed = runCatching {341 withEpochCommit(expectedEpoch) {342 try {343 344 345 346 347 if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")348 349 350 if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")351 352 353 val duressOk = if (codexDuress != null) {354 store.writeDecoySlot(codexDuress)355 } else {356 writeFakeDuressSlot(slotA)357 }358 if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")359 store.stampLocalMutation()360 true361 } catch (_: Exception) {362 reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))363 364 365 366 afterCodexRollback()367 false368 }369 } ?: false370 }.getOrDefault(false)371 if (!committed) {372 return UnlockResult.Error("storage_write_failed")373 }374375 val ownedKey = candidateKey!!376 candidateKey = null 377 adoptSlotA(ownedKey, payload, expectedEpoch)378 } catch (e: Exception) {379 380 381 382 383 384 385 if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))386 UnlockResult.Error(e.message ?: "restore_failed")387 } finally {388 plaintext?.let(VaultCrypto::zero)389 candidateKey?.let(VaultCrypto::zero)390 }391 }392393 394 private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =395 runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()396397 398399400401402403404405406 private fun rollbackRestoreLocked(407 priorA: StoredVault?,408 priorB: String?,409 priorD: StoredVault? = null,410 ): List<String> {411 val failures = mutableListOf<String>()412 if (priorA == null) {413 runCatching { store.clearVault() }.onFailure { failures += "clearVault: $it" }414 } else {415 runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }416 .onFailure { failures += "writeSlotA: $it" }417 if (priorB != null) {418 runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }419 .onFailure { failures += "writeSlotB: $it" }420 }421 422 423 424 if (priorD != null) {425 runCatching { if (!store.writeDecoySlot(priorD)) failures += "writeDecoySlot returned false" }426 .onFailure { failures += "writeDecoySlot: $it" }427 } else {428 runCatching { store.clearDecoySlot() }.onFailure { failures += "clearDecoySlot: $it" }429 }430 }431 return failures432 }433434 private fun reportRollbackFailures(failures: List<String>) {435 436 437 if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }438 }439440 441 private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {442 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)443 val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()444 val window = offset?.let {445 val from = (it - 40).coerceAtLeast(0)446 val to = (it + 40).coerceAtMost(wrapperJson.length)447 wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")448 }449 val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()450 val slot = wrapper?.get("a")451 buildString {452 append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)453 append(" | blobBase64=").append(vaultBlobBase64.length)454 append(" wrapperChars=").append(wrapperJson.length)455 append(" wrapperParses=").append(wrapper != null)456 append(" keys=").append(wrapper?.keys)457 append(" slotAKind=").append(458 when {459 slot == null -> "absent"460 slot is JsonPrimitive && slot.isString -> "string"461 slot is JsonObject -> "object:" + slot.keys462 else -> slot::class.simpleName463 },464 )465 if (window != null) append(" masked@").append(offset).append("=").append(window)466 }467 }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }468469 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {470 val expectedEpoch = currentEpoch()471 var key: ByteArray? = null472 return try {473 val salt = VaultCrypto.generateSalt()474 key = VaultCrypto.deriveKey(password, salt)475 if (mutateIfCurrentEpoch(expectedEpoch) {476 entryList = mutableListOf()477 authenticatedDuressConfigured = false478 _duressConfigured.value = false479 recoveryWordHash = null480 recoveryWordsSet = false481 decoyMode = false482 sessionDataAvailable = false483 rootKey = generateRecoverableRootKey()484 } == null) return CreateVaultResult.Error("stale_create")485 486 487 488 489 val slotA = sealSlotA(key!!, salt)490 491 492 beforeDurableCommit()493 val created = withEpochCommit(expectedEpoch) {494 if (!store.writeSlotA(slotA)) return@withEpochCommit false495 try {496 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")497 498 499 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")500 store.stampLocalMutation()501 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")502 true503 } catch (_: Exception) {504 505 506 store.clearVault()507 false508 }509 } ?: false510 if (!created) {511 lock()512 return CreateVaultResult.Error("storage_write_failed")513 }514 val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")515 if (mutateIfCurrentEpoch(expectedEpoch) {516 derivedKey = sessionKey517 key = null518 publish()519 _isUnlocked.value = true520 sessionDataAvailable = true521 sessionEpoch = nextSessionEpoch(sessionEpoch)522 } == null) return CreateVaultResult.Error("stale_create")523 CreateVaultResult.Success524 } catch (e: Exception) {525 lock()526 CreateVaultResult.Error(e.message ?: "create_failed")527 } finally {528 key?.let(VaultCrypto::zero)529 }530 }531532 suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {533 val expectedEpoch = currentEpoch()534 if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")535 if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")536 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {537 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")538 }539 var adoptedRootKey: ByteArray? = null540 var nextDerivedKey: ByteArray? = null541 var sessionRootKey: ByteArray? = null542 return try {543 adoptedRootKey = hexToRootKey(rootKeyHex)544 if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {545 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")546 }547 val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)548 val salt = VaultCrypto.generateSalt()549 nextDerivedKey = VaultCrypto.deriveKey(password, salt)550 sessionRootKey = adoptedRootKey.copyOf()551 val payload = VaultPayload(552 entries = emptyList(),553 duressConfigured = false,554 rootKeyB64 = b64(sessionRootKey),555 recoveryWordHash = null,556 recoveryWordsSet = false,557 )558 val plaintext = VaultCodec.encode(payload)559 val blob = try {560 b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))561 } finally {562 VaultCrypto.zero(plaintext)563 }564 val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)565 566 567 beforeDurableCommit()568 val created = withEpochCommit(expectedEpoch) {569 if (!store.writeSlotA(slotA)) return@withEpochCommit false570 try {571 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")572 573 574 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")575 store.stampLocalMutation()576 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")577 true578 } catch (_: Exception) {579 store.clearVault()580 false581 }582 } ?: false583 if (!created) return AdoptVaultResult.Error("storage_write_failed")584585 val adopted = mutateIfCurrentEpoch(expectedEpoch) {586 val previousDerivedKey = derivedKey587 val previousRootKey = rootKey588 derivedKey = nextDerivedKey589 rootKey = sessionRootKey590 nextDerivedKey = null591 sessionRootKey = null592 entryList = mutableListOf()593 authenticatedDuressConfigured = false594 _duressConfigured.value = false595 recoveryWordHash = null596 recoveryWordsSet = false597 decoyMode = false598 sessionDataAvailable = true599 publish()600 _isUnlocked.value = true601 sessionEpoch = nextSessionEpoch(sessionEpoch)602 previousDerivedKey to previousRootKey603 }604 if (adopted == null) return AdoptVaultResult.Error("stale_adoption")605 val (previousDerivedKey, previousRootKey) = adopted606 previousDerivedKey?.let(VaultCrypto::zero)607 previousRootKey?.let(VaultCrypto::zero)608 609 610 611 runCatching {612 val words = rootKeyToWords(rootKey!!)613 val escrow = buildRecoveryEscrow(words)614 val rkEscrow = buildRootKeyEscrow(words)615 if (escrow != null || rkEscrow != null) {616 val prior = store.loadSlotA()617 if (prior != null) {618 store.writeSlotA(prior.copy(619 recoveryEscrow = escrow ?: prior.recoveryEscrow,620 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,621 ))622 }623 mutateState {624 recoveryWordHash = recoveryWordsHash(words)625 recoveryWordsSet = true626 }627 }628 }629 AdoptVaultResult.Success(vaultId)630 } catch (e: Exception) {631 AdoptVaultResult.Error(e.message ?: "adoption_create_failed")632 } finally {633 adoptedRootKey?.let(VaultCrypto::zero)634 nextDerivedKey?.let(VaultCrypto::zero)635 sessionRootKey?.let(VaultCrypto::zero)636 }637 }638639 suspend fun unlock(password: String): UnlockResult = mutex.withLock {640 val result = unlockLocked(password, currentEpoch())641 if (result is UnlockResult.Success) ensureRecoveryEscrow()642 result643 }644645 646 private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {647 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")648 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))649 val payload = try {650 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)651 try {652 VaultCodec.decode(plaintext)653 } finally {654 VaultCrypto.zero(plaintext)655 }656 } catch (_: Exception) {657 VaultCrypto.zero(key)658 659 660 661 if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {662 val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)663 if (legacy != null) return legacy664 }665 return UnlockResult.WrongPassword666 }667 return adoptSlotA(key, payload, expectedEpoch)668 }669670 671672673674675676677678 private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {679 var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))680 var newKey: ByteArray? = null681 return try {682 val payload = try {683 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)684 try {685 VaultCodec.decode(plaintext)686 } finally {687 VaultCrypto.zero(plaintext)688 }689 } catch (_: Exception) {690 return null691 }692 693 694 val newSalt = VaultCrypto.generateSalt()695 newKey = VaultCrypto.deriveKey(password, newSalt)696 val plaintext = VaultCodec.encode(payload)697 val blob = try {698 b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))699 } finally {700 VaultCrypto.zero(plaintext)701 }702 val next = StoredVault(703 version = slotA.version,704 salt = b64(newSalt),705 blob = blob,706 recoveryEscrow = slotA.recoveryEscrow,707 rootKeyEscrow = slotA.rootKeyEscrow,708 )709 710 711 712 val priorB = store.loadSlotB()713 beforeDurableCommit()714 val healed = withEpochCommit(expectedEpoch) {715 if (!store.writeSlotA(next)) {716 false717 } else try {718 if (!writeMatchingNoiseSlotB(next)) {719 runCatching { store.writeSlotA(slotA) }720 if (priorB != null) runCatching { store.writeSlotB(priorB) }721 false722 } else if (!writeCompanionDuressSlot(next)) {723 runCatching { store.writeSlotA(slotA) }724 if (priorB != null) runCatching { store.writeSlotB(priorB) }725 false726 } else {727 store.stampLocalMutation()728 true729 }730 } catch (_: Exception) {731 runCatching { store.writeSlotA(slotA) }732 if (priorB != null) runCatching { store.writeSlotB(priorB) }733 false734 }735 } ?: false736 if (healed) {737 VaultCrypto.zero(rawKey!!)738 rawKey = null739 val result = adoptSlotA(newKey!!, payload, expectedEpoch) 740 newKey = null741 result742 } else {743 VaultCrypto.zero(newKey!!)744 newKey = null745 val result = adoptSlotA(rawKey!!, payload, expectedEpoch) 746 rawKey = null747 result748 }749 } finally {750 751 752 rawKey?.let(VaultCrypto::zero)753 newKey?.let(VaultCrypto::zero)754 }755 }756757 758 private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {759 return try {760 761 762 763 764 765 val adopted = mutateIfCurrentEpoch(expectedEpoch) {766 derivedKey = key767 decoyMode = false768 entryList = payload.entries.toMutableList()769 authenticatedDuressConfigured = payload.duressConfigured770 _duressConfigured.value = payload.duressConfigured771 recoveryWordHash = payload.recoveryWordHash772 recoveryWordsSet = payload.recoveryWordsSet773 sessionDataAvailable = true774 _settings.value = store.loadSettings()775 ensureRootKey(payload)776 autoPurgeExpiredTrash()777 consolidatePasskeyEntries()778 publish()779 _isUnlocked.value = true780 781 782 783 sessionEpoch = nextSessionEpoch(sessionEpoch)784 }785 if (adopted == null) {786 VaultCrypto.zero(key)787 UnlockResult.Error("stale_unlock")788 } else {789 UnlockResult.Success790 }791 } catch (e: Exception) {792 793 794 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }795 VaultCrypto.zero(key)796 UnlockResult.Error(e.message ?: "unlock_failed")797 }798 }799800 801802 803804805806807808 class SlotAUnlock internal constructor(809 key: ByteArray,810 internal val payload: VaultPayload,811 internal val epoch: Long,812 ) {813 private var ownedKey: ByteArray? = key814 private var consumed = false815816 817 internal fun takeKey(): ByteArray? = synchronized(this) {818 if (consumed) return@synchronized null819 consumed = true820 ownedKey.also { ownedKey = null }821 }822823 824 internal fun discard() = synchronized(this) {825 if (consumed) return@synchronized826 consumed = true827 ownedKey?.let(VaultCrypto::zero)828 ownedKey = null829 }830 }831832 833834835836837838 fun tryUnlockSlotA(password: String): SlotAUnlock? {839 val epoch = currentEpoch()840 val slotA = store.loadSlotA() ?: return null841 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))842 return try {843 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)844 val payload = try {845 VaultCodec.decode(plaintext)846 } finally {847 VaultCrypto.zero(plaintext)848 }849 SlotAUnlock(key, payload, epoch)850 } catch (_: Exception) {851 VaultCrypto.zero(key)852 null853 }854 }855856 857 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {858 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")859 adoptSlotA(key, unlock.payload, unlock.epoch)860 }861862 863 fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()864865 866867 868869870871872 class DuressUnlock internal constructor(873 key: ByteArray,874 internal val payload: VaultPayload,875 internal val epoch: Long,876 ) {877 private var ownedKey: ByteArray? = key878 private var consumed = false879880 internal fun takeKey(): ByteArray? = synchronized(this) {881 if (consumed) return@synchronized null882 consumed = true883 ownedKey.also { ownedKey = null }884 }885886 internal fun discard() = synchronized(this) {887 if (consumed) return@synchronized888 consumed = true889 ownedKey?.let(VaultCrypto::zero)890 ownedKey = null891 }892 }893894 895896897898899900901 fun tryUnlockDuress(password: String): DuressUnlock? {902 val epoch = currentEpoch()903 val slot = store.loadDecoySlot() ?: return null904 val key = VaultCrypto.deriveKey(password, unb64(slot.salt))905 return try {906 val plaintext = VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A)907 val payload = try {908 VaultCodec.decode(plaintext)909 } finally {910 VaultCrypto.zero(plaintext)911 }912 DuressUnlock(key, payload, epoch)913 } catch (_: Exception) {914 VaultCrypto.zero(key)915 null916 }917 }918919 920 suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {921 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")922 if (currentEpoch() != unlock.epoch) {923 VaultCrypto.zero(key)924 return@withLock UnlockResult.Error("stale_unlock")925 }926 return try {927 val adopted = mutateIfCurrentEpoch(unlock.epoch) {928 derivedKey = key929 decoyMode = true930 entryList = unlock.payload.entries.toMutableList()931 authenticatedDuressConfigured = false932 _duressConfigured.value = false933 recoveryWordHash = unlock.payload.recoveryWordHash934 recoveryWordsSet = unlock.payload.recoveryWordsSet935 sessionDataAvailable = true936 rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)937 else VaultCrypto.generateRootKey()938 _settings.value = store.loadSettings()939 publish()940 _isUnlocked.value = true941 sessionEpoch = nextSessionEpoch(sessionEpoch)942 }943 if (adopted == null) {944 VaultCrypto.zero(key)945 UnlockResult.Error("stale_unlock")946 } else {947 UnlockResult.Success948 }949 } catch (e: Exception) {950 951 952 953 954 mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }955 VaultCrypto.zero(key)956 UnlockResult.Error(e.message ?: "decoy_unlock_failed")957 }958 }959960 961 fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()962963 964965966967968969 suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {970 971 val expectedEpoch = mutateState {972 if (derivedKey != null && !decoyMode) sessionEpoch else null973 } ?: return false974 975 976 tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }977 var key: ByteArray? = null978 var basePlaintext: ByteArray? = null979 return try {980 val salt = VaultCrypto.generateSalt()981 key = VaultCrypto.deriveKey(duressPassphrase, salt)982 983 val decoyRoot = VaultCrypto.generateRootKey()984 val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }985 val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)986 basePlaintext = VaultCodec.encode(decoyPayload)987 988 989 990 991 992 993 994 995 996 val slotA = store.loadSlotA()997 val targetSize = slotA?.let(::matchingCiphertextLength) ?: 0998 val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!999 val blob = try {1000 b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_A))1001 } finally {1002 VaultCrypto.zero(plaintext)1003 1004 1005 if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)1006 basePlaintext = null1007 key?.let(VaultCrypto::zero)1008 key = null1009 }1010 beforeDurableCommit()1011 val ok = withEpochCommit(expectedEpoch) {1012 store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))1013 } ?: false1014 if (ok && mutateIfCurrentEpoch(expectedEpoch) {1015 authenticatedDuressConfigured = true1016 _duressConfigured.value = true1017 } != null) {1018 runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1019 } else if (ok) {1020 return false1021 }1022 ok1023 } catch (_: Exception) {1024 false1025 } finally {1026 1027 1028 key?.let(VaultCrypto::zero)1029 basePlaintext?.let(VaultCrypto::zero)1030 }1031 }103210331034 103510361037103810391040104110421043 suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1044 if (!authenticatedDuressConfigured) return null1045 val slot = store.loadDecoySlot() ?: return null1046 return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1047 }10481049 1050105110521053105410551056 private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1057 1058 1059 1060 1061 1062 var salt: ByteArray? = null1063 var blob: ByteArray? = null1064 var nonce: ByteArray? = null1065 var ctAndTag: ByteArray? = null1066 var ct: ByteArray? = null1067 var tag: ByteArray? = null1068 try {1069 salt = unb64(slot.salt)1070 blob = unb64(slot.blob)1071 nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1072 ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1073 ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1074 tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1075 val obj = JsonObject(mapOf(1076 "version" to JsonPrimitive(1),1077 "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1078 "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1079 "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1080 "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1081 ))1082 return obj.toString()1083 } finally {1084 salt?.let(VaultCrypto::zero)1085 blob?.let(VaultCrypto::zero)1086 nonce?.let(VaultCrypto::zero)1087 ctAndTag?.let(VaultCrypto::zero)1088 ct?.let(VaultCrypto::zero)1089 tag?.let(VaultCrypto::zero)1090 }1091 }10921093 1094109510961097109810991100110111021103 suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1104 val b = BrowserSlot.parse(json) ?: return false1105 var stored: StoredVault? = null1106 var salt: ByteArray? = null1107 var nonce: ByteArray? = null1108 var ct: ByteArray? = null1109 var tag: ByteArray? = null1110 var blob: ByteArray? = null1111 try {1112 salt = unhex(b.salt)1113 nonce = unhex(b.nonce)1114 ct = unhex(b.ciphertext)1115 tag = unhex(b.tag)1116 blob = ByteArray(nonce.size + ct.size + tag.size).also {1117 System.arraycopy(nonce, 0, it, 0, nonce.size)1118 System.arraycopy(ct, 0, it, nonce.size, ct.size)1119 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1120 }1121 stored = StoredVault(version = 1, salt = b64(salt), blob = b64(blob))1122 val expectedEpoch = sessionEpoch1123 beforeDurableCommit()1124 withEpochCommit(expectedEpoch) {1125 store.writeDecoySlot(stored)1126 } ?: false1127 } catch (_: Exception) {1128 false1129 } finally {1130 salt?.let(VaultCrypto::zero)1131 nonce?.let(VaultCrypto::zero)1132 ct?.let(VaultCrypto::zero)1133 tag?.let(VaultCrypto::zero)1134 blob?.let(VaultCrypto::zero)1135 }1136 }11371138 1139 suspend fun clearDuress(): Boolean = mutex.withLock {1140 1141 1142 1143 1144 val expectedEpoch = currentEpoch()1145 val replaced = withEpochCommit(expectedEpoch) {1146 store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1147 ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1148 } ?: false1149 if (!replaced) return@withLock false1150 1151 1152 if (!isSessionEpochCurrent(expectedEpoch)) return false1153 val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1154 if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) {1155 authenticatedDuressConfigured = false1156 _duressConfigured.value = false1157 } != null) {1158 runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1159 }1160 true1161 }11621163 1164 private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1165 var current: Throwable? = error1166 while (current != null) {1167 if (current is javax.crypto.AEADBadTagException) return true1168 1169 1170 1171 1172 if (current is javax.crypto.BadPaddingException) return true1173 current = current.cause1174 }1175 return false1176 }11771178 1179 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1180 val expectedEpoch = currentEpoch()1181 val slotA = try {1182 store.loadSlotA()1183 } catch (_: Exception) {1184 return@withLock UnlockResult.Error("unlock_key_storage_failed")1185 } ?: return@withLock UnlockResult.Error("no_vault")1186 1187 1188 1189 1190 var stagedKey: ByteArray? = key.copyOf()1191 return try {1192 val encrypted = try {1193 unb64(slotA.blob)1194 } catch (_: Exception) {1195 return@withLock UnlockResult.Error("invalid_vault_blob")1196 }1197 1198 1199 1200 1201 if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1202 return@withLock UnlockResult.Error("invalid_vault_blob")1203 }1204 val plaintext = try {1205 VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1206 } catch (e: Exception) {1207 if (isGcmAuthenticationFailure(e)) {1208 return@withLock UnlockResult.WrongPassword1209 }1210 return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1211 }1212 val payload = try {1213 VaultCodec.decode(plaintext)1214 } catch (_: Exception) {1215 return@withLock UnlockResult.Error("invalid_vault_payload")1216 } finally {1217 VaultCrypto.zero(plaintext)1218 }1219 val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1220 val result = adoptSlotA(candidate, payload, expectedEpoch)1221 if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1222 result1223 } finally {1224 stagedKey?.let(VaultCrypto::zero)1225 }1226 }12271228 fun lock() {1229 1230 1231 1232 1233 if (mutex.tryLock()) {1234 try {1235 runCatching { LockedSyncSpoolHooks.refresh(this) }1236 } finally {1237 mutex.unlock()1238 }1239 }1240 1241 1242 1243 1244 1245 1246 stateLock.lock()1247 try {1248 sessionEpoch = nextSessionEpoch(sessionEpoch)1249 clearSessionStateLocked()1250 _uiGateLocked.value = false1251 } finally {1252 stateLock.unlock()1253 }1254 }12551256 1257125812591260126112621263 fun lockUiGate() {1264 if (_isUnlocked.value) _uiGateLocked.value = true1265 }12661267 1268 fun clearUiGate() {1269 _uiGateLocked.value = false1270 }12711272 @Volatile private var suppressNextBackgroundLockUntil: Long = 0L12731274 1275 1276 @VisibleForTesting1277 internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }12781279 128012811282128312841285128612871288128912901291 fun expectTransientBackground() {1292 suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1293 }12941295 12961297129812991300 fun consumeTransientBackgroundSuppression(): Boolean {1301 val until = suppressNextBackgroundLockUntil1302 val active = until != 0L && nowMs() < until1303 suppressNextBackgroundLockUntil = 0L1304 return active1305 }13061307 13081309 13101311131213131314 13151316131713181319132013211322132313241325 1326 1327 1328 1329 1330 internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)13311332 internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1333 if (decoyMode || !_isUnlocked.value) null1334 else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1335 }13361337 internal fun isSessionEpochCurrent(epoch: Long): Boolean =1338 mutateState { sessionEpoch == epoch }13391340 internal fun unlockedSessionEpoch(): Long? = mutateState {1341 if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1342 }13431344 fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key13451346 134713481349135013511352135313541355 fun sessionRootKey(): ByteArray? = mutateState {1356 if (!sessionDataAvailable) null else rootKey?.copyOf()1357 }13581359 13601361 fun syncVaultId(): String? = mutateState {1362 if (decoyMode || !_isUnlocked.value) null1363 else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1364 }13651366 13671368136913701371 suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1372 val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1373 ?: return false1374 installRootKey(generateRecoverableRootKey(), expectedEpoch)1375 }13761377 13781379138013811382138313841385138613871388138913901391139213931394 suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1395 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1396 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1397 }1398 val expectedEpoch = mutateState {1399 when {1400 derivedKey == null -> null1401 decoyMode -> Long.MIN_VALUE1402 else -> sessionEpoch1403 }1404 }1405 if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1406 if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1407 if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")14081409 val incoming = hexToRootKey(rootKeyHex)1410 if (incoming.size != VaultCrypto.KEY_SIZE) {1411 VaultCrypto.zero(incoming)1412 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1413 }1414 1415 1416 1417 val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1418 if (!roundTrips) {1419 VaultCrypto.zero(incoming)1420 return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1421 }14221423 val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1424 return if (installRootKey(incoming, expectedEpoch)) {1425 AdoptVaultResult.Success(vaultId)1426 } else {1427 AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1428 }1429 }14301431 14321433143414351436 fun previewRecoveryWords(rootKeyHex: String): List<String>? {1437 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1438 val bytes = hexToRootKey(rootKeyHex)1439 return try {1440 val words = rootKeyToWords(bytes)1441 if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1442 } catch (_: Exception) {1443 null1444 } finally {1445 VaultCrypto.zero(bytes)1446 }1447 }14481449 14501451145214531454 private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1455 1456 1457 1458 1459 1460 1461 data class Snapshot(1462 val key: ByteArray,1463 val priorRootKey: ByteArray,1464 val priorRecoveryHash: String?,1465 val priorRecoverySet: Boolean,1466 )1467 val snap = mutateIfCurrentEpoch(expectedEpoch) {1468 val k = derivedKey ?: return@mutateIfCurrentEpoch null1469 if (decoyMode) return@mutateIfCurrentEpoch null1470 val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1471 Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1472 } ?: run {1473 VaultCrypto.zero(nextRootKey)1474 return false1475 }1476 val priorSlot = store.loadSlotA() ?: run {1477 VaultCrypto.zero(snap.key)1478 VaultCrypto.zero(snap.priorRootKey)1479 VaultCrypto.zero(nextRootKey)1480 return false1481 }1482 val nextWords = rootKeyToWords(nextRootKey)14831484 return try {1485 beforeDurableCommit()1486 if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1487 if (mutateIfCurrentEpoch(expectedEpoch) {1488 rootKey = nextRootKey1489 recoveryWordHash = recoveryWordsHash(nextWords)1490 recoveryWordsSet = false1491 } == null) throw IllegalStateException("stale_root_rotation")14921493 val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1494 ?: throw IllegalStateException("recovery_escrow_failed")1495 val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1496 ?: throw IllegalStateException("root_escrow_failed")1497 val plaintext = VaultCodec.encode(currentPayload())1498 val blob = try {1499 b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1500 } finally {1501 VaultCrypto.zero(plaintext)1502 }1503 val nextSlot = priorSlot.copy(1504 blob = blob,1505 recoveryEscrow = nextRecoveryEscrow,1506 rootKeyEscrow = nextRootKeyEscrow,1507 )1508 val committed = withEpochCommit(expectedEpoch) {1509 if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1510 try {1511 if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1512 1513 1514 if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1515 store.stampLocalMutation()1516 } catch (_: Exception) {1517 store.writeSlotA(priorSlot)1518 return@withEpochCommit false1519 }1520 true1521 } ?: false1522 if (!committed) throw IllegalStateException("storage_write_failed")1523 mutateIfCurrentEpoch(expectedEpoch) { publish() }1524 true1525 } catch (_: Exception) {1526 val restored = mutateIfCurrentEpoch(expectedEpoch) {1527 rootKey?.let(VaultCrypto::zero)1528 rootKey = snap.priorRootKey.copyOf()1529 recoveryWordHash = snap.priorRecoveryHash1530 recoveryWordsSet = snap.priorRecoverySet1531 }1532 if (restored != null) {1533 withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1534 }1535 false1536 } finally {1537 VaultCrypto.zero(snap.key)1538 VaultCrypto.zero(snap.priorRootKey)1539 1540 1541 1542 val stillOwnedBySession = mutateState {1543 sessionEpoch == expectedEpoch && rootKey === nextRootKey1544 }1545 if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1546 }1547 }15481549 15501551155215531554 fun currentVaultKey(): ByteArray? = mutateState {1555 if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1556 }15571558 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1559 val expectedEpoch = currentEpoch()1560 val slotA = store.loadSlotA() ?: return false1561 var oldKey: ByteArray? = null1562 var newKey: ByteArray? = null1563 var plaintext: ByteArray? = null1564 return try {1565 oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1566 1567 1568 1569 1570 val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1571 val payload = try {1572 VaultCodec.decode(decrypted)1573 } finally {1574 VaultCrypto.zero(decrypted)1575 }1576 val newSalt = VaultCrypto.generateSalt()1577 newKey = VaultCrypto.deriveKey(newPassword, newSalt)1578 1579 plaintext = VaultCodec.encode(payload)1580 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1581 1582 1583 1584 1585 1586 1587 1588 val next = StoredVault(1589 version = slotA.version,1590 salt = b64(newSalt),1591 blob = blob,1592 recoveryEscrow = slotA.recoveryEscrow,1593 rootKeyEscrow = slotA.rootKeyEscrow,1594 )1595 1596 1597 1598 1599 val priorB = store.loadSlotB()1600 if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1601 1602 1603 1604 if (mutateIfCurrentEpoch(expectedEpoch) {1605 oldKey?.let(VaultCrypto::zero); oldKey = null1606 derivedKey?.let(VaultCrypto::zero)1607 derivedKey = newKey; newKey = null1608 } == null) return false1609 true1610 } catch (_: Exception) {1611 false1612 } finally {1613 oldKey?.let(VaultCrypto::zero)1614 newKey?.let(VaultCrypto::zero)1615 plaintext?.let(VaultCrypto::zero)1616 }1617 }16181619 1620162116221623 suspend fun destroyVault() = mutex.withLock {1624 lock()1625 store.clearVault()1626 store.clearDecoySlot()1627 }16281629 16301631 1632163316341635163616371638163916401641164216431644 private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")16451646 private fun String?.normalizedEntryId(): String =1647 if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()16481649 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1650 val epoch = requireUnlocked()1651 val stamp = VaultCrypto.monotonicEntryTimestamp()1652 val now = System.currentTimeMillis()1653 val entry = withDerivedLast4(draft.copy(1654 id = draft.id.normalizedEntryId(),1655 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1656 modifiedAt = stamp,1657 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1658 ))1659 1660 1661 val rollback = mutateCurrentSession(epoch) {1662 val r = entryList.toMutableList()1663 entryList.add(entry)1664 r1665 } ?: throw IllegalStateException("vault_locked")1666 persistOrRollback(rollback, epoch)1667 entry1668 }16691670 167116721673167416751676167716781679 suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1680 val epoch = requireUnlocked()1681 if (drafts.isEmpty()) return 01682 val now = System.currentTimeMillis()1683 val ready = drafts.map { draft ->1684 val stamp = VaultCrypto.monotonicEntryTimestamp()1685 withDerivedLast4(1686 draft.copy(1687 id = draft.id.normalizedEntryId(),1688 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1689 modifiedAt = stamp,1690 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1691 ),1692 )1693 }1694 1695 val rollback = mutateCurrentSession(epoch) {1696 val r = entryList.toMutableList()1697 entryList.addAll(ready)1698 r1699 } ?: throw IllegalStateException("vault_locked")1700 persistOrRollback(rollback, epoch)1701 return drafts.size1702 }17031704 1705170617071708170917101711171217131714171517161717 suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1718 val epoch = requireUnlocked()1719 val now = System.currentTimeMillis()1720 val ready = newEntries.map { draft ->1721 val stamp = VaultCrypto.monotonicEntryTimestamp()1722 withDerivedLast4(1723 draft.copy(1724 id = draft.id.normalizedEntryId(),1725 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1726 modifiedAt = stamp,1727 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1728 ),1729 )1730 }1731 1732 1733 1734 1735 1736 1737 val incomingIds = ready.map { it.id }.toHashSet()1738 val rollback = mutateCurrentSession(epoch) {1739 val r = entryList.toMutableList()1740 val replaced = entryList.map { entry ->1741 if (entry.deletedAt != null) return@map entry1742 if (entry.id in incomingIds) return@map null1743 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1744 entry.copy(deletedAt = stamp, modifiedAt = stamp)1745 }.filterNotNull()1746 entryList = (replaced + ready).toMutableList()1747 r1748 } ?: throw IllegalStateException("vault_locked")1749 persistOrRollback(rollback, epoch)1750 return ready.size1751 }17521753 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1754 val epoch = requireUnlocked()1755 1756 1757 1758 1759 val prepared = mutateCurrentSession(epoch) {1760 val idx = entryList.indexOfFirst { it.id == patch.id }1761 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1762 val current = entryList[idx]1763 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1764 1765 val passwordChanged = patch.password != null && patch.password != current.password1766 1767 1768 1769 1770 1771 1772 val priorPassword = current.password1773 val shouldCapture = passwordChanged &&1774 !priorPassword.isNullOrEmpty() &&1775 current.passwordHistory?.firstOrNull()?.password != priorPassword1776 val nextHistory = if (shouldCapture) {1777 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1778 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1779 } else {1780 current.passwordHistory1781 }1782 val updated = withDerivedLast4(patch.copy(1783 createdAt = current.createdAt,1784 modifiedAt = stamp,1785 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1786 passwordHistory = nextHistory,1787 ))1788 val rollback = entryList.toMutableList()1789 entryList[idx] = updated1790 updated to rollback1791 } ?: throw IllegalStateException("vault_locked")1792 val (updated, rollback) = prepared1793 persistOrRollback(rollback, epoch)1794 updated1795 }17961797 1798 suspend fun deleteEntry(id: String) = mutex.withLock {1799 val epoch = requireUnlocked()1800 1801 1802 val rollback = mutateCurrentSession(epoch) {1803 val idx = entryList.indexOfFirst { it.id == id }1804 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1805 val current = entryList[idx]1806 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1807 val prior = entryList.toMutableList()1808 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1809 prior1810 } ?: throw IllegalStateException("vault_locked")1811 persistOrRollback(rollback, epoch)1812 }18131814 suspend fun restoreEntry(id: String) = mutex.withLock {1815 val epoch = requireUnlocked()1816 val rollback = mutateCurrentSession(epoch) {1817 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1818 if (idx == -1) throw IllegalStateException("deleted entry not found")1819 val current = entryList[idx]1820 val prior = entryList.toMutableList()1821 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))1822 prior1823 } ?: throw IllegalStateException("vault_locked")1824 persistOrRollback(rollback, epoch)1825 }18261827 1828 suspend fun purgeEntry(id: String) = mutex.withLock {1829 val epoch = requireUnlocked()1830 val rollback = mutateCurrentSession(epoch) {1831 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1832 if (idx == -1) throw IllegalStateException("deleted entry not found")1833 val prior = entryList.toMutableList()1834 entryList.removeAt(idx)1835 prior1836 } ?: throw IllegalStateException("vault_locked")1837 persistOrRollback(rollback, epoch)1838 }18391840 1841 suspend fun purgeDeletedEntries(): Int = mutex.withLock {1842 val epoch = requireUnlocked()1843 1844 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1845 val r = mutateCurrentSession(epoch) {1846 val rollback = entryList.toMutableList()1847 val before = entryList.size1848 entryList.removeAll { it.deletedAt != null }1849 R(rollback, before - entryList.size)1850 } ?: throw IllegalStateException("vault_locked")1851 if (r.removed > 0) persistOrRollback(r.rollback, epoch)1852 r.removed1853 }18541855 1856 suspend fun countDuplicateEntries(): Int = mutex.withLock {1857 val epoch = requireUnlocked()1858 1859 1860 mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }1861 ?: throw IllegalStateException("vault_locked")1862 }18631864 18651866186718681869 suspend fun deduplicateEntries(): Int = mutex.withLock {1870 val epoch = requireUnlocked()1871 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1872 val ready = mutateCurrentSession(epoch) {1873 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")1874 val active = entryList.filter { it.deletedAt == null }1875 val keepIds = mutableSetOf<String>()1876 active.groupBy { it.duplicateKey() }.values.forEach { group ->1877 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id1878 }1879 val rollback = entryList.toMutableList()1880 var removed = 01881 entryList = entryList.map { entry ->1882 if (entry.deletedAt == null && entry.id !in keepIds) {1883 removed++1884 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1885 entry.copy(deletedAt = stamp, modifiedAt = stamp)1886 } else {1887 entry1888 }1889 }.toMutableList()1890 R(rollback, removed)1891 } ?: throw IllegalStateException("vault_locked")1892 if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)1893 ready.removed1894 }18951896 fun getEntries(): List<VaultEntry> = mutateState {1897 if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }1898 }1899 fun getEntry(id: String): VaultEntry? = mutateState {1900 if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }1901 }1902 fun getDeletedEntries(): List<VaultEntry> = mutateState {1903 if (!sessionDataAvailable) emptyList()1904 else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }1905 }19061907 1908 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {1909 return mutateState {1910 if (!sessionDataAvailable) return@mutateState emptyList()1911 val active = entryList.filter { it.deletedAt == null }1912 if (tagFilter == null) return@mutateState active1913 val needle = tagFilter.trim().lowercase()1914 active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }1915 }1916 }19171918 1919 fun getDistinctTags(): List<String> = mutateState {1920 if (!sessionDataAvailable) return@mutateState emptyList()1921 entryList.asSequence()1922 .filter { it.deletedAt == null }1923 .flatMap { it.tags?.asSequence() ?: emptySequence() }1924 .map { it.trim().lowercase() }1925 .filter { it.isNotEmpty() }1926 .distinct()1927 .sorted()1928 .toList()1929 }19301931 193219331934193519361937 fun getDistinctFieldValues(field: String): List<String> {1938 val select: (VaultEntry) -> String? = when (field) {1939 "username" -> { e -> e.username }1940 "email" -> { e -> e.email }1941 else -> return emptyList()1942 }1943 return mutateState {1944 if (!sessionDataAvailable) return@mutateState emptyList()1945 entryList.asSequence()1946 .filter { it.deletedAt == null }1947 .mapNotNull { select(it)?.trim() }1948 .filter { it.isNotEmpty() }1949 .groupingBy { it.lowercase() }1950 .aggregate { _, acc: Pair<String, Int>?, value, _ ->1951 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)1952 }1953 .values1954 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })1955 .map { it.first }1956 }1957 }19581959 fun getTombstones(): List<Tombstone> = mutateState {1960 if (!sessionDataAvailable) emptyList()1961 else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }1962 }1963 fun getVaultVersion(): Long = store.version()1964 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots19651966 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {1967 val expectedEpoch = currentEpoch()1968 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false1969 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false1970 1971 1972 val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)1973 val priorA = store.loadSlotA()1974 val priorB = store.loadSlotB()1975 val priorD = store.loadDecoySlot()1976 1977 1978 1979 1980 1981 val priorHistory = store.loadVaultHistory()1982 1983 1984 1985 1986 beforeDurableCommit()1987 if (!takeVaultSnapshot("restore", expectedEpoch)) {1988 return false1989 }1990 1991 1992 1993 val nextD: StoredVault = restoredD ?: run {1994 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 161995 val fakeBlob = ByteArray(target).also(rng::nextBytes)1996 val fakeSalt = VaultCrypto.generateSalt()1997 StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob))1998 }1999 if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {2000 withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }2001 return false2002 }2003 lock()2004 true2005 }20062007 20082009201020112012201320142015201620172018 private fun commitRestoreAtomic(2019 nextA: StoredVault,2020 nextB: String,2021 nextD: StoredVault,2022 priorA: StoredVault?,2023 priorB: String?,2024 priorD: StoredVault?,2025 expectedEpoch: Long,2026 ): Boolean {2027 return withEpochCommit(expectedEpoch) {2028 if (!store.writeSlotA(nextA)) return@withEpochCommit false2029 2030 2031 2032 try {2033 if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2034 2035 2036 if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2037 store.stampLocalMutation()2038 } catch (_: Exception) {2039 reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2040 return@withEpochCommit false2041 }2042 true2043 } ?: false2044 }20452046 20472048 20492050205120522053 suspend fun applyMergedRemoteEntries(2054 remoteEntries: List<VaultEntry>,2055 remoteTombstones: List<Tombstone>,2056 expectedEpoch: Long? = null,2057 ): Int = mutex.withLock {2058 val epoch = expectedEpoch ?: requireUnlocked()2059 if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02060 2061 2062 2063 2064 2065 val mergeNow = System.currentTimeMillis()2066 val clamped = remoteEntries.mapNotNull { entry ->2067 2068 2069 2070 SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2071 modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2072 deletedAt = entry.deletedAt?.let {2073 SyncLimits.clampSyncTimestamp(it, mergeNow)2074 },2075 )2076 }2077 val tombMap = remoteTombstones.associate {2078 it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2079 }2080 2081 2082 val applied = mutateCurrentSession(epoch) {2083 var n = 02084 val byId = entryList.associateBy { it.id }.toMutableMap()20852086 for (remote in clamped) {2087 val tomb = tombMap[remote.id]2088 if (tomb != null && tomb >= remote.modifiedAt) continue2089 val local = byId[remote.id]2090 if (local == null) {2091 entryList.add(remote); byId[remote.id] = remote; n++2092 } else if (remote.modifiedAt > local.modifiedAt) {2093 val i = entryList.indexOfFirst { it.id == local.id }2094 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2095 }2096 }20972098 for ((id, deletedAt) in tombMap) {2099 val local = byId[id] ?: continue2100 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2101 if (deletedAt < local.modifiedAt) continue2102 val i = entryList.indexOfFirst { it.id == id }2103 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2104 }2105 n2106 } ?: return@withLock 021072108 if (applied > 0) {2109 persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2110 mutateIfCurrentEpoch(epoch) { publish() }2111 runCatching { LockedSyncSpoolHooks.refresh(this) }2112 }2113 applied2114 }21152116 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2117 2118 2119 2120 val epoch = requireUnlocked()2121 val prior = mutateCurrentSession(epoch) {2122 val old = _settings.value2123 _settings.value = settings2124 old2125 } ?: throw IllegalStateException("vault_locked")21262127 val committed = try {2128 beforeDurableCommit()2129 2130 2131 2132 withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2133 } catch (_: Exception) {2134 false2135 }2136 if (!committed) {2137 2138 2139 2140 mutateIfCurrentEpoch(epoch) { _settings.value = prior }2141 throw IllegalStateException("settings_write_failed")2142 }2143 }21442145 21462147 2148 fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }21492150 21512152215321542155 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2156 val epoch = requireUnlocked()2157 2158 2159 2160 2161 2162 2163 val prior = mutateCurrentSession(epoch) {2164 val priorPair = recoveryWordHash to recoveryWordsSet2165 recoveryWordHash = recoveryWordsHash(words)2166 recoveryWordsSet = true2167 priorPair2168 } ?: return@withLock false2169 2170 2171 2172 2173 val persisted = runCatching {2174 persistSlotAWithEscrows(2175 buildRecoveryEscrow(words),2176 buildRootKeyEscrow(words),2177 expectedEpoch = epoch,2178 )2179 }.getOrDefault(false)2180 if (!persisted) {2181 mutateIfCurrentEpoch(epoch) {2182 recoveryWordHash = prior.first2183 recoveryWordsSet = prior.second2184 }2185 }2186 persisted2187 }21882189 2190 fun verifyRecoveryWords(words: List<String>): Boolean {2191 return mutateState {2192 val stored = recoveryWordHash ?: return@mutateState false2193 MessageDigest.isEqual(2194 stored.toByteArray(Charsets.UTF_8),2195 recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2196 )2197 }2198 }21992200 22012202 2203 fun hasRecoveryEscrow(): Boolean =2204 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false22052206 22072208220922102211 private fun ensureRecoveryEscrow() {2212 if (hasRecoveryEscrow()) return2213 val rk = mutateState { rootKey?.copyOf() } ?: return2214 runCatching {2215 val words = rootKeyToWords(rk)2216 val escrow = buildRecoveryEscrow(words)2217 val rkEscrow = buildRootKeyEscrow(words)2218 if (escrow != null || rkEscrow != null) {2219 val prior = store.loadSlotA() ?: return@runCatching2220 store.writeSlotA(prior.copy(2221 recoveryEscrow = escrow ?: prior.recoveryEscrow,2222 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2223 ))2224 mutateState {2225 recoveryWordHash = recoveryWordsHash(words)2226 recoveryWordsSet = true2227 }2228 }2229 }.also { VaultCrypto.zero(rk) }2230 }22312232 223322342235223622372238223922402241224222432244 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2245 val expectedEpoch = currentEpoch()2246 val slotA = store.loadSlotA() ?: return false2247 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false22482249 2250 2251 val fullEscrow = slotA.recoveryEscrow2252 if (fullEscrow != null) {2253 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2254 if (material != null) {2255 var keyBytes: ByteArray? = null2256 var plaintext: ByteArray? = null2257 var candidateRoot: ByteArray? = null2258 var stateCommitStarted = false2259 try {2260 keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2261 plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2262 val payload = VaultCodec.decode(plaintext)2263 2264 2265 2266 2267 val candidateSettings = store.loadSettings()2268 candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2269 val decodedRoot = unb64(payload.rootKeyB64)2270 if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2271 2272 2273 2274 VaultCrypto.zero(decodedRoot)2275 throw IllegalArgumentException("invalid recovery root key")2276 }2277 decodedRoot2278 } else {2279 generateRecoverableRootKey()2280 }2281 stateCommitStarted = true2282 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2283 clearSessionStateLocked()2284 entryList = payload.entries.toMutableList()2285 authenticatedDuressConfigured = payload.duressConfigured2286 _duressConfigured.value = payload.duressConfigured2287 recoveryWordHash = payload.recoveryWordHash2288 recoveryWordsSet = payload.recoveryWordsSet2289 rootKey = candidateRoot2290 candidateRoot = null2291 _settings.value = candidateSettings2292 publish()2293 2294 2295 sessionDataAvailable = true2296 _isUnlocked.value = false2297 true2298 }2299 if (adopted == true) return@withLock true2300 } catch (_: Exception) {2301 2302 2303 2304 2305 if (stateCommitStarted) {2306 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2307 }2308 } finally {2309 plaintext?.let(VaultCrypto::zero)2310 VaultCrypto.zero(material)2311 keyBytes?.let(VaultCrypto::zero)2312 candidateRoot?.let(VaultCrypto::zero)2313 }2314 }2315 }23162317 2318 2319 2320 val rootEscrow = slotA.rootKeyEscrow2321 if (rootEscrow != null) {2322 var candidateRoot: ByteArray? = null2323 var stateCommitStarted = false2324 try {2325 candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2326 require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2327 val candidateSettings = store.loadSettings()2328 stateCommitStarted = true2329 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2330 clearSessionStateLocked()2331 entryList = mutableListOf()2332 authenticatedDuressConfigured = false2333 _duressConfigured.value = false2334 recoveryWordHash = recoveryWordsHash(words)2335 recoveryWordsSet = true2336 rootKey = candidateRoot2337 candidateRoot = null2338 _settings.value = candidateSettings2339 publish()2340 sessionDataAvailable = true2341 _isUnlocked.value = false2342 true2343 }2344 if (adopted == true) return@withLock true2345 } catch (_: Exception) {2346 if (stateCommitStarted) {2347 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2348 }2349 } finally {2350 candidateRoot?.let(VaultCrypto::zero)2351 }2352 }2353 return false2354 }23552356 235723582359236023612362236323642365 suspend fun resetPasswordWithRecoveryWords(2366 words: List<String>,2367 newPassword: String,2368 ): Boolean = mutex.withLock {2369 val expectedEpoch = currentEpoch()2370 2371 2372 2373 if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2374 val priorA = store.loadSlotA() ?: return false2375 var newKey: ByteArray? = null2376 var plaintext: ByteArray? = null2377 return try {2378 val newSalt = VaultCrypto.generateSalt()2379 newKey = VaultCrypto.deriveKey(newPassword, newSalt)2380 plaintext = VaultCodec.encode(currentPayload())2381 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2382 2383 2384 2385 val valid = words.size == 12 && findInvalidWords(words).isEmpty()2386 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2387 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2388 val next = StoredVault(2389 version = priorA.version,2390 salt = b64(newSalt),2391 blob = blob,2392 recoveryEscrow = freshRecovery,2393 rootKeyEscrow = freshRootKey,2394 )2395 2396 2397 2398 val priorB = store.loadSlotB()2399 if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2400 2401 2402 2403 if (mutateIfCurrentEpoch(expectedEpoch) {2404 derivedKey?.let(VaultCrypto::zero)2405 derivedKey = newKey; newKey = null2406 publish()2407 _isUnlocked.value = true2408 } == null) return false2409 true2410 } catch (_: Exception) {2411 false2412 } finally {2413 newKey?.let(VaultCrypto::zero)2414 plaintext?.let(VaultCrypto::zero)2415 }2416 }24172418 241924202421242224232424 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2425 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2426 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2427 var keyBytes: ByteArray? = null2428 var plaintext: ByteArray? = null2429 return try {2430 val salt = VaultCrypto.generateSalt()2431 val recoveryKey = deriveRecoveryKey(material, salt)2432 keyBytes = recoveryKey.encoded2433 plaintext = VaultCodec.encode(currentPayload())2434 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2435 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2436 } finally {2437 VaultCrypto.zero(material)2438 keyBytes?.let(VaultCrypto::zero)2439 plaintext?.let(VaultCrypto::zero)2440 }2441 }24422443 24442445244624472448244924502451 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2452 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2453 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2454 val rk = mutateState { rootKey?.copyOf() } ?: run {2455 VaultCrypto.zero(material)2456 return null2457 }2458 var keyBytes: ByteArray? = null2459 var plaintext: ByteArray? = null2460 return try {2461 val salt = VaultCrypto.generateSalt()2462 val recoveryKey = deriveRecoveryKey(material, salt)2463 keyBytes = recoveryKey.encoded2464 plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2465 2466 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2467 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2468 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2469 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2470 val ct = ctTag.copyOfRange(0, ctTag.size - 16)2471 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2472 } finally {2473 VaultCrypto.zero(rk)2474 VaultCrypto.zero(material)2475 keyBytes?.let(VaultCrypto::zero)2476 plaintext?.let(VaultCrypto::zero)2477 }2478 }24792480 2481 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2482 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2483 var keyBytes: ByteArray? = null2484 var pt: ByteArray? = null2485 return try {2486 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2487 keyBytes = recoveryKey.encoded2488 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2489 pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2490 hexToRootKey(String(pt, Charsets.US_ASCII))2491 } catch (_: Exception) {2492 null2493 } finally {2494 2495 2496 2497 VaultCrypto.zero(material)2498 keyBytes?.let(VaultCrypto::zero)2499 pt?.let(VaultCrypto::zero)2500 }2501 }25022503 250425052506250725082509 private fun persistSlotAWithEscrows(2510 recoveryEscrow: RecoveryEscrow?,2511 rootKeyEscrow: RootKeyEscrow?,2512 expectedEpoch: Long? = null,2513 ): Boolean {2514 val snapshot = snapshotForPersist(expectedEpoch)2515 ?: throw IllegalStateException("vault_locked_or_stale")2516 if (snapshot.decoy) {2517 VaultCrypto.zero(snapshot.key)2518 return false2519 }2520 try {2521 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2522 val plaintext = VaultCodec.encode(snapshot.payload)2523 val blob = try {2524 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2525 } finally {2526 2527 2528 VaultCrypto.zero(plaintext)2529 }2530 val next = prior.copy(2531 blob = blob,2532 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2533 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2534 )2535 beforeDurableCommit()2536 return withEpochCommit(snapshot.epoch) {2537 if (!store.writeSlotA(next)) return@withEpochCommit false2538 try {2539 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2540 2541 2542 2543 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2544 } catch (e: Exception) {2545 store.writeSlotA(prior)2546 throw e2547 }2548 true2549 } ?: false2550 } finally {2551 VaultCrypto.zero(snapshot.key)2552 }2553 }25542555 25562557 private fun requireUnlocked(): Long {2558 2559 2560 2561 stateLock.lock()2562 try {2563 if (derivedKey == null) throw IllegalStateException("vault_locked")2564 return sessionEpoch2565 } finally {2566 stateLock.unlock()2567 }2568 }25692570 2571 private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null25722573 private fun countDuplicateEntriesLocked(): Int {2574 val seen = mutableMapOf<String, VaultEntry>()2575 var duplicates = 02576 for (entry in entryList.filter { it.deletedAt == null }) {2577 val key = entry.duplicateKey()2578 val existing = seen[key]2579 if (existing == null) {2580 seen[key] = entry2581 } else {2582 duplicates++2583 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2584 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2585 if (entryStamp > existingStamp) seen[key] = entry2586 }2587 }2588 return duplicates2589 }25902591 private fun VaultEntry.duplicateKey(): String {2592 if (type == "note") return "note|${title.lowercase()}"2593 val passkeyData = passkey2594 if (passkeyData != null) {2595 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2596 }2597 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2598 }25992600 260126022603260426052606 private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2607 val epoch = expectedEpoch ?: currentEpoch()2608 if (mutateIfCurrentEpoch(epoch) { true } != true) return false2609 val slotA = store.loadSlotA() ?: return false2610 val vaultA = VaultCodec.encodeSlot(slotA)2611 val vaultB = store.loadSlotB() ?: slotA.blob2612 2613 2614 2615 2616 2617 val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2618 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162619 val fakeBlob = ByteArray(target).also(rng::nextBytes)2620 val fakeSalt = VaultCrypto.generateSalt()2621 VaultCodec.encodeSlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2622 }2623 val history = store.loadVaultHistory()2624 val latest = history.snapshots.firstOrNull()2625 if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2626 val entryCount = mutateIfCurrentEpoch(epoch) {2627 if (derivedKey != null && !decoyMode) {2628 bucketEntryCount(entryList.count { it.deletedAt == null })2629 } else {2630 null2631 }2632 } ?: return false2633 return try {2634 val snapshot = VaultSnapshot(2635 id = UUID.randomUUID().toString(),2636 savedAt = System.currentTimeMillis(),2637 reason = reason,2638 vault_a = vaultA,2639 vault_b = vaultB,2640 vault_d = vaultD,2641 entryCount = entryCount,2642 )2643 2644 2645 2646 withEpochCommit(epoch) {2647 store.writeVaultHistory(2648 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2649 )2650 } ?: false2651 } catch (_: Exception) {2652 false2653 }2654 }26552656 private fun bucketEntryCount(n: Int): Int = when {2657 n <= 0 -> 02658 n <= 10 -> 102659 n <= 25 -> 252660 n <= 50 -> 502661 n <= 100 -> 1002662 n <= 250 -> 2502663 n <= 500 -> 5002664 else -> ((n + 499) / 500) * 5002665 }26662667 266826692670267126722673267426752676 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2677 if (!entry.isCard()) return entry2678 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2679 val derived = if (digits.length >= 4) digits.takeLast(4) else null2680 return entry.copy(last4 = derived ?: entry.last4)2681 }26822683 268426852686268726882689 private fun autoPurgeExpiredTrash() {2690 val days = _settings.value.trashRetentionDays ?: return2691 if (days <= 0) return2692 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2693 val before = entryList.size2694 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2695 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2696 }26972698 269927002701270227032704 private fun consolidatePasskeyEntries() {2705 val passkeyOnly = entryList.filter { entry ->2706 entry.deletedAt == null &&2707 entry.isLogin() &&2708 entry.password.isNullOrBlank() &&2709 !entry.rpId.isNullOrBlank() &&2710 !entry.credentialId.isNullOrBlank()2711 }2712 if (passkeyOnly.isEmpty()) return2713 var changed = false2714 val now = System.currentTimeMillis()2715 for (pkEntry in passkeyOnly) {2716 val rpId = pkEntry.rpId ?: continue2717 val target = entryList.firstOrNull { candidate ->2718 candidate.deletedAt == null &&2719 candidate.id != pkEntry.id &&2720 candidate.isLogin() &&2721 candidate.passkey == null &&2722 candidate.credentialId.isNullOrBlank() &&2723 !candidate.password.isNullOrBlank() &&2724 listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2725 .any { com.peachpasswords.shared.extractDomain(it) == rpId }2726 } ?: continue2727 val idx = entryList.indexOfFirst { it.id == target.id }2728 if (idx < 0) continue2729 entryList[idx] = target.copy(2730 rpId = pkEntry.rpId,2731 rpName = pkEntry.rpName ?: target.rpName,2732 credentialId = pkEntry.credentialId,2733 publicKeyCose = pkEntry.publicKeyCose,2734 privateKeyJwk = pkEntry.privateKeyJwk,2735 userHandle = pkEntry.userHandle,2736 userName = pkEntry.userName,2737 userDisplayName = pkEntry.userDisplayName,2738 algorithm = pkEntry.algorithm,2739 signCount = pkEntry.signCount,2740 lastUsedAt = pkEntry.lastUsedAt,2741 modifiedAt = now,2742 )2743 2744 val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2745 if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2746 changed = true2747 }2748 if (changed) runCatching { persistSlotA(bumpVersion = false) }2749 }27502751 2752 private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }27532754 private fun currentPayloadLocked(): VaultPayload =2755 VaultPayload(2756 entries = entryList.toList(),2757 duressConfigured = authenticatedDuressConfigured,2758 rootKeyB64 = rootKey?.let(::b64) ?: "",2759 recoveryWordHash = recoveryWordHash,2760 recoveryWordsSet = recoveryWordsSet,2761 )27622763 27642765276627672768 private fun ensureRootKey(payload: VaultPayload) {2769 if (payload.rootKeyB64.isNotBlank()) {2770 rootKey = unb64(payload.rootKeyB64)2771 return2772 }2773 rootKey = generateRecoverableRootKey()2774 runCatching { persistSlotA(bumpVersion = false) }2775 }27762777 private fun publish() {2778 _entries.value = entryList.filter { it.deletedAt == null }2779 }27802781 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2782 var plaintext = VaultCodec.encode(currentPayload())2783 return try {2784 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2785 StoredVault(version = 1, salt = b64(salt), blob = blob)2786 } finally {2787 2788 2789 2790 VaultCrypto.zero(plaintext)2791 }2792 }27932794 private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2795 2796 2797 2798 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2799 val noise = ByteArray(approxBytes).also(rng::nextBytes)2800 return store.writeSlotB(b64(noise))2801 }28022803 280428052806 private fun matchingCiphertextLength(slotA: StoredVault): Int =2807 (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)28082809 28102811281228132814 private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {2815 val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162816 val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)2817 val fakeSalt = VaultCrypto.generateSalt()2818 return store.writeDecoySlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2819 }28202821 282228232824282528262827 private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {2828 val isConfigured = mutateState { authenticatedDuressConfigured }2829 return if (isConfigured) true else writeFakeDuressSlot(slotA)2830 }28312832 2833283428352836283728382839 private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {2840 val salt = unhex(b.salt)2841 val nonce = unhex(b.nonce)2842 val ct = unhex(b.ciphertext)2843 val tag = unhex(b.tag)2844 val blob = ByteArray(nonce.size + ct.size + tag.size).also {2845 System.arraycopy(nonce, 0, it, 0, nonce.size)2846 System.arraycopy(ct, 0, it, nonce.size, ct.size)2847 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)2848 }2849 return StoredVault(version = 1, salt = b64(salt), blob = b64(blob))2850 }28512852 2853 private fun persistSlotA(2854 bumpVersion: Boolean,2855 snapshotReason: String? = "local_save",2856 expectedEpoch: Long? = null,2857 ): Boolean {2858 val snapshot = snapshotForPersist(expectedEpoch)2859 ?: throw IllegalStateException("vault_locked_or_stale")2860 return try {2861 2862 if (snapshot.decoy) {2863 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")2864 val plaintext = VaultCodec.encode(snapshot.payload)2865 val blob = try {2866 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2867 } finally {2868 2869 2870 VaultCrypto.zero(plaintext)2871 }2872 beforeDurableCommit()2873 return withEpochCommit(snapshot.epoch) {2874 store.writeDecoySlot(prior.copy(blob = blob))2875 } ?: false2876 }2877 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2878 2879 2880 2881 2882 val priorB = store.loadSlotB()2883 beforeDurableCommit()2884 if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false2885 val plaintext = VaultCodec.encode(snapshot.payload)2886 val blob = try {2887 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2888 } finally {2889 2890 2891 VaultCrypto.zero(plaintext)2892 }2893 val next = prior.copy(blob = blob)2894 2895 2896 2897 2898 withEpochCommit(snapshot.epoch) {2899 if (!store.writeSlotA(next)) return@withEpochCommit false2900 try {2901 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2902 2903 2904 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2905 if (bumpVersion) store.stampLocalMutation()2906 } catch (e: Exception) {2907 store.writeSlotA(prior)2908 if (priorB != null) runCatching { store.writeSlotB(priorB) }2909 throw e2910 }2911 true2912 } ?: false2913 } finally {2914 2915 2916 VaultCrypto.zero(snapshot.key)2917 }2918 }29192920 2921292229232924292529262927 private fun commitVaultRotation(2928 priorA: StoredVault,2929 priorB: String?,2930 nextA: StoredVault,2931 expectedEpoch: Long,2932 ): Boolean {2933 beforeDurableCommit()2934 return withEpochCommit(expectedEpoch) {2935 if (!store.writeSlotA(nextA)) return@withEpochCommit false2936 2937 2938 2939 try {2940 if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")2941 2942 2943 2944 2945 if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")2946 store.stampLocalMutation()2947 } catch (_: Exception) {2948 rollbackRotation(priorA, priorB)2949 return@withEpochCommit false2950 }2951 true2952 } ?: false2953 }29542955 29562957295829592960 private fun rollbackRotation(priorA: StoredVault, priorB: String?) {2961 val failures = mutableListOf<String>()2962 runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }2963 .onFailure { failures += "writeSlotA: $it" }2964 if (priorB != null) {2965 runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }2966 .onFailure { failures += "writeSlotB: $it" }2967 }2968 if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }2969 }29702971 2972 private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {2973 try {2974 if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {2975 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }2976 throw IllegalStateException("storage_write_failed")2977 }2978 } catch (e: Exception) {2979 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }2980 throw e2981 }2982 2983 2984 2985 mutateIfCurrentEpoch(expectedEpoch) { publish() }2986 runCatching { LockedSyncSpoolHooks.refresh(this) }2987 }2988}