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 duressConfigured: 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()193194195 196197198199200201 private val _uiGateLocked = MutableStateFlow(false)202 val uiGateLocked: StateFlow<Boolean> = _uiGateLocked.asStateFlow()203204 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())205 206 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()207208 209 210 211 212 private val _settings = MutableStateFlow(store.loadSettings())213 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()214215 216 private fun clearSessionStateLocked() {217 derivedKey?.let(VaultCrypto::zero)218 rootKey?.let(VaultCrypto::zero)219 derivedKey = null220 rootKey = null221 entryList = mutableListOf()222 duressConfigured = false223 recoveryWordHash = null224 recoveryWordsSet = false225 sessionDataAvailable = false226 decoyMode = false227 _settings.value = store.loadSettings()228 _entries.value = emptyList()229 _isUnlocked.value = false230 }231232 fun hasVault(): Boolean = store.hasVault()233234 235236 237238239240241242243 fun codexVaultBlobBase64(): String? {244 val slotA = store.loadSlotA() ?: return null245 246 247 val slotD = store.loadDecoySlot() ?: return null248 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)},"b":${VaultCodec.encodeSlot(slotD)}}"""249 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))250 }251252 253254255256257 258 private fun JsonElement?.asSlotJson(): String? = when {259 this == null || this is JsonNull -> null260 this is JsonPrimitive && isString -> content261 else -> toString()262 }263264 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {265 val expectedEpoch = currentEpoch()266 var candidateKey: ByteArray? = null267 var plaintext: ByteArray? = null268 return try {269 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)270 271 272 273 274 275 276 277 val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject278 ?: return UnlockResult.Error("invalid_codex_blob")279 val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")280 281 282 283 284 285 val slotA = VaultCodec.decodeSlot(slotJson)286 ?: BrowserSlot.parse(slotJson)?.let {287 BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword288 }289 ?: return UnlockResult.Error("invalid_codex_blob")290 291 292 293 294 295 candidateKey = VaultCrypto.deriveKey(password, unb64(slotA.salt))296 plaintext = decryptSlotABlob(slotA, candidateKey)297 298 299 300 301 if (plaintext == null && password != Normalizer.normalize(password, Normalizer.Form.NFC)) {302 VaultCrypto.zero(candidateKey)303 candidateKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))304 plaintext = decryptSlotABlob(slotA, candidateKey)305 }306 if (plaintext == null) return UnlockResult.WrongPassword307 val payload = try {308 VaultCodec.decode(plaintext)309 } catch (_: Exception) {310 return UnlockResult.Error("invalid_codex_blob")311 }312313 val priorA = store.loadSlotA()314 val priorB = store.loadSlotB()315 val priorD = store.loadDecoySlot()316 317 318 319 320 321 val codexDuressJson = wrapper["b"].asSlotJson()322 val codexDuress: StoredVault? = codexDuressJson?.let {323 VaultCodec.decodeSlot(it) ?: BrowserSlot.parse(it)?.let { b ->324 325 326 327 328 329 330 browserDuressPassthrough(b)331 }332 }333334 beforeDurableCommit()335 val committed = runCatching {336 withEpochCommit(expectedEpoch) {337 try {338 339 340 341 342 if (!store.writeSlotA(slotA)) throw java.io.IOException("slot_a_commit_failed")343 344 345 if (!writeMatchingNoiseSlotB(slotA)) throw IllegalStateException("noise_slot_commit_failed")346 347 348 val duressOk = if (codexDuress != null) {349 store.writeDecoySlot(codexDuress)350 } else {351 writeFakeDuressSlot(slotA)352 }353 if (!duressOk) throw IllegalStateException("duress_slot_commit_failed")354 store.stampLocalMutation()355 true356 } catch (_: Exception) {357 reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))358 359 360 361 afterCodexRollback()362 false363 }364 } ?: false365 }.getOrDefault(false)366 if (!committed) {367 return UnlockResult.Error("storage_write_failed")368 }369370 val ownedKey = candidateKey!!371 candidateKey = null 372 adoptSlotA(ownedKey, payload, expectedEpoch)373 } catch (e: Exception) {374 375 376 377 378 379 380 if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))381 UnlockResult.Error(e.message ?: "restore_failed")382 } finally {383 plaintext?.let(VaultCrypto::zero)384 candidateKey?.let(VaultCrypto::zero)385 }386 }387388 389 private fun decryptSlotABlob(slot: StoredVault, key: ByteArray): ByteArray? =390 runCatching { VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A) }.getOrNull()391392 393394395396397398399400401 private fun rollbackRestoreLocked(402 priorA: StoredVault?,403 priorB: String?,404 priorD: StoredVault? = null,405 ): List<String> {406 val failures = mutableListOf<String>()407 if (priorA == null) {408 runCatching { store.clearVault() }.onFailure { failures += "clearVault: $it" }409 } else {410 runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }411 .onFailure { failures += "writeSlotA: $it" }412 if (priorB != null) {413 runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }414 .onFailure { failures += "writeSlotB: $it" }415 }416 417 418 419 if (priorD != null) {420 runCatching { if (!store.writeDecoySlot(priorD)) failures += "writeDecoySlot returned false" }421 .onFailure { failures += "writeDecoySlot: $it" }422 } else {423 runCatching { store.clearDecoySlot() }.onFailure { failures += "clearDecoySlot: $it" }424 }425 }426 return failures427 }428429 private fun reportRollbackFailures(failures: List<String>) {430 431 432 if (failures.isNotEmpty()) runCatching { Log.w("PeachCodex", "codex rollback incomplete: $failures") }433 }434435 436 private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {437 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)438 val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()439 val window = offset?.let {440 val from = (it - 40).coerceAtLeast(0)441 val to = (it + 40).coerceAtMost(wrapperJson.length)442 wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")443 }444 val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()445 val slot = wrapper?.get("a")446 buildString {447 append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)448 append(" | blobBase64=").append(vaultBlobBase64.length)449 append(" wrapperChars=").append(wrapperJson.length)450 append(" wrapperParses=").append(wrapper != null)451 append(" keys=").append(wrapper?.keys)452 append(" slotAKind=").append(453 when {454 slot == null -> "absent"455 slot is JsonPrimitive && slot.isString -> "string"456 slot is JsonObject -> "object:" + slot.keys457 else -> slot::class.simpleName458 },459 )460 if (window != null) append(" masked@").append(offset).append("=").append(window)461 }462 }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }463464 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {465 val expectedEpoch = currentEpoch()466 var key: ByteArray? = null467 return try {468 val salt = VaultCrypto.generateSalt()469 key = VaultCrypto.deriveKey(password, salt)470 if (mutateIfCurrentEpoch(expectedEpoch) {471 entryList = mutableListOf()472 duressConfigured = false473 recoveryWordHash = null474 recoveryWordsSet = false475 decoyMode = false476 sessionDataAvailable = false477 rootKey = generateRecoverableRootKey()478 } == null) return CreateVaultResult.Error("stale_create")479 480 481 482 483 val slotA = sealSlotA(key!!, salt)484 485 486 beforeDurableCommit()487 val created = withEpochCommit(expectedEpoch) {488 if (!store.writeSlotA(slotA)) return@withEpochCommit false489 try {490 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")491 492 493 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")494 store.stampLocalMutation()495 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")496 true497 } catch (_: Exception) {498 499 500 store.clearVault()501 false502 }503 } ?: false504 if (!created) {505 lock()506 return CreateVaultResult.Error("storage_write_failed")507 }508 val sessionKey = key ?: return CreateVaultResult.Error("create_key_missing")509 if (mutateIfCurrentEpoch(expectedEpoch) {510 derivedKey = sessionKey511 key = null512 publish()513 _isUnlocked.value = true514 sessionDataAvailable = true515 sessionEpoch = nextSessionEpoch(sessionEpoch)516 } == null) return CreateVaultResult.Error("stale_create")517 CreateVaultResult.Success518 } catch (e: Exception) {519 lock()520 CreateVaultResult.Error(e.message ?: "create_failed")521 } finally {522 key?.let(VaultCrypto::zero)523 }524 }525526 suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {527 val expectedEpoch = currentEpoch()528 if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")529 if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")530 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {531 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")532 }533 var adoptedRootKey: ByteArray? = null534 var nextDerivedKey: ByteArray? = null535 var sessionRootKey: ByteArray? = null536 return try {537 adoptedRootKey = hexToRootKey(rootKeyHex)538 if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {539 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")540 }541 val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)542 val salt = VaultCrypto.generateSalt()543 nextDerivedKey = VaultCrypto.deriveKey(password, salt)544 sessionRootKey = adoptedRootKey.copyOf()545 val payload = VaultPayload(546 entries = emptyList(),547 duressConfigured = false,548 rootKeyB64 = b64(sessionRootKey),549 recoveryWordHash = null,550 recoveryWordsSet = false,551 )552 val plaintext = VaultCodec.encode(payload)553 val blob = try {554 b64(VaultCrypto.encrypt(plaintext, nextDerivedKey, VaultCrypto.AAD_SLOT_A))555 } finally {556 VaultCrypto.zero(plaintext)557 }558 val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)559 560 561 beforeDurableCommit()562 val created = withEpochCommit(expectedEpoch) {563 if (!store.writeSlotA(slotA)) return@withEpochCommit false564 try {565 if (!writeMatchingNoiseSlotB(slotA)) throw java.io.IOException("noise_slot_b_commit_failed")566 567 568 if (!writeFakeDuressSlot(slotA)) throw java.io.IOException("duress_slot_commit_failed")569 store.stampLocalMutation()570 if (!store.writeSettings(_settings.value)) throw java.io.IOException("settings_commit_failed")571 true572 } catch (_: Exception) {573 store.clearVault()574 false575 }576 } ?: false577 if (!created) return AdoptVaultResult.Error("storage_write_failed")578579 val adopted = mutateIfCurrentEpoch(expectedEpoch) {580 val previousDerivedKey = derivedKey581 val previousRootKey = rootKey582 derivedKey = nextDerivedKey583 rootKey = sessionRootKey584 nextDerivedKey = null585 sessionRootKey = null586 entryList = mutableListOf()587 duressConfigured = false588 recoveryWordHash = null589 recoveryWordsSet = false590 decoyMode = false591 sessionDataAvailable = true592 publish()593 _isUnlocked.value = true594 sessionEpoch = nextSessionEpoch(sessionEpoch)595 previousDerivedKey to previousRootKey596 }597 if (adopted == null) return AdoptVaultResult.Error("stale_adoption")598 val (previousDerivedKey, previousRootKey) = adopted599 previousDerivedKey?.let(VaultCrypto::zero)600 previousRootKey?.let(VaultCrypto::zero)601 602 603 604 runCatching {605 val words = rootKeyToWords(rootKey!!)606 val escrow = buildRecoveryEscrow(words)607 val rkEscrow = buildRootKeyEscrow(words)608 if (escrow != null || rkEscrow != null) {609 val prior = store.loadSlotA()610 if (prior != null) {611 store.writeSlotA(prior.copy(612 recoveryEscrow = escrow ?: prior.recoveryEscrow,613 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,614 ))615 }616 mutateState {617 recoveryWordHash = recoveryWordsHash(words)618 recoveryWordsSet = true619 }620 }621 }622 AdoptVaultResult.Success(vaultId)623 } catch (e: Exception) {624 AdoptVaultResult.Error(e.message ?: "adoption_create_failed")625 } finally {626 adoptedRootKey?.let(VaultCrypto::zero)627 nextDerivedKey?.let(VaultCrypto::zero)628 sessionRootKey?.let(VaultCrypto::zero)629 }630 }631632 suspend fun unlock(password: String): UnlockResult = mutex.withLock {633 val result = unlockLocked(password, currentEpoch())634 if (result is UnlockResult.Success) ensureRecoveryEscrow()635 result636 }637638 639 private fun unlockLocked(password: String, expectedEpoch: Long): UnlockResult {640 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")641 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))642 val payload = try {643 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)644 try {645 VaultCodec.decode(plaintext)646 } finally {647 VaultCrypto.zero(plaintext)648 }649 } catch (_: Exception) {650 VaultCrypto.zero(key)651 652 653 654 if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {655 val legacy = tryLegacyRawUnlock(password, slotA, expectedEpoch)656 if (legacy != null) return legacy657 }658 return UnlockResult.WrongPassword659 }660 return adoptSlotA(key, payload, expectedEpoch)661 }662663 664665666667668669670671 private fun tryLegacyRawUnlock(password: String, slotA: StoredVault, expectedEpoch: Long): UnlockResult? {672 var rawKey: ByteArray? = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))673 var newKey: ByteArray? = null674 return try {675 val payload = try {676 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), rawKey!!, VaultCrypto.AAD_SLOT_A)677 try {678 VaultCodec.decode(plaintext)679 } finally {680 VaultCrypto.zero(plaintext)681 }682 } catch (_: Exception) {683 return null684 }685 686 687 val newSalt = VaultCrypto.generateSalt()688 newKey = VaultCrypto.deriveKey(password, newSalt)689 val plaintext = VaultCodec.encode(payload)690 val blob = try {691 b64(VaultCrypto.encrypt(plaintext, newKey!!, VaultCrypto.AAD_SLOT_A))692 } finally {693 VaultCrypto.zero(plaintext)694 }695 val next = StoredVault(696 version = slotA.version,697 salt = b64(newSalt),698 blob = blob,699 recoveryEscrow = slotA.recoveryEscrow,700 rootKeyEscrow = slotA.rootKeyEscrow,701 )702 703 704 705 val priorB = store.loadSlotB()706 beforeDurableCommit()707 val healed = withEpochCommit(expectedEpoch) {708 if (!store.writeSlotA(next)) {709 false710 } else try {711 if (!writeMatchingNoiseSlotB(next)) {712 runCatching { store.writeSlotA(slotA) }713 if (priorB != null) runCatching { store.writeSlotB(priorB) }714 false715 } else if (!writeCompanionDuressSlot(next)) {716 runCatching { store.writeSlotA(slotA) }717 if (priorB != null) runCatching { store.writeSlotB(priorB) }718 false719 } else {720 store.stampLocalMutation()721 true722 }723 } catch (_: Exception) {724 runCatching { store.writeSlotA(slotA) }725 if (priorB != null) runCatching { store.writeSlotB(priorB) }726 false727 }728 } ?: false729 if (healed) {730 VaultCrypto.zero(rawKey!!)731 rawKey = null732 val result = adoptSlotA(newKey!!, payload, expectedEpoch) 733 newKey = null734 result735 } else {736 VaultCrypto.zero(newKey!!)737 newKey = null738 val result = adoptSlotA(rawKey!!, payload, expectedEpoch) 739 rawKey = null740 result741 }742 } finally {743 744 745 rawKey?.let(VaultCrypto::zero)746 newKey?.let(VaultCrypto::zero)747 }748 }749750 751 private fun adoptSlotA(key: ByteArray, payload: VaultPayload, expectedEpoch: Long): UnlockResult {752 return try {753 754 755 756 757 758 val adopted = mutateIfCurrentEpoch(expectedEpoch) {759 derivedKey = key760 decoyMode = false761 entryList = payload.entries.toMutableList()762 duressConfigured = payload.duressConfigured763 recoveryWordHash = payload.recoveryWordHash764 recoveryWordsSet = payload.recoveryWordsSet765 sessionDataAvailable = true766 _settings.value = store.loadSettings()767 ensureRootKey(payload)768 autoPurgeExpiredTrash()769 consolidatePasskeyEntries()770 publish()771 _isUnlocked.value = true772 773 774 775 sessionEpoch = nextSessionEpoch(sessionEpoch)776 }777 if (adopted == null) {778 VaultCrypto.zero(key)779 UnlockResult.Error("stale_unlock")780 } else {781 UnlockResult.Success782 }783 } catch (e: Exception) {784 785 786 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }787 VaultCrypto.zero(key)788 UnlockResult.Error(e.message ?: "unlock_failed")789 }790 }791792 793794 795796797798799800 class SlotAUnlock internal constructor(801 key: ByteArray,802 internal val payload: VaultPayload,803 internal val epoch: Long,804 ) {805 private var ownedKey: ByteArray? = key806 private var consumed = false807808 809 internal fun takeKey(): ByteArray? = synchronized(this) {810 if (consumed) return@synchronized null811 consumed = true812 ownedKey.also { ownedKey = null }813 }814815 816 internal fun discard() = synchronized(this) {817 if (consumed) return@synchronized818 consumed = true819 ownedKey?.let(VaultCrypto::zero)820 ownedKey = null821 }822 }823824 825826827828829830 fun tryUnlockSlotA(password: String): SlotAUnlock? {831 val epoch = currentEpoch()832 val slotA = store.loadSlotA() ?: return null833 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))834 return try {835 val plaintext = VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A)836 val payload = try {837 VaultCodec.decode(plaintext)838 } finally {839 VaultCrypto.zero(plaintext)840 }841 SlotAUnlock(key, payload, epoch)842 } catch (_: Exception) {843 VaultCrypto.zero(key)844 null845 }846 }847848 849 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {850 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")851 adoptSlotA(key, unlock.payload, unlock.epoch)852 }853854 855 fun discardSlotAUnlock(unlock: SlotAUnlock) = unlock.discard()856857 858859 860861862863864 class DuressUnlock internal constructor(865 key: ByteArray,866 internal val payload: VaultPayload,867 internal val epoch: Long,868 ) {869 private var ownedKey: ByteArray? = key870 private var consumed = false871872 internal fun takeKey(): ByteArray? = synchronized(this) {873 if (consumed) return@synchronized null874 consumed = true875 ownedKey.also { ownedKey = null }876 }877878 internal fun discard() = synchronized(this) {879 if (consumed) return@synchronized880 consumed = true881 ownedKey?.let(VaultCrypto::zero)882 ownedKey = null883 }884 }885886 887888889890891892893 fun tryUnlockDuress(password: String): DuressUnlock? {894 val epoch = currentEpoch()895 val slot = store.loadDecoySlot() ?: return null896 val key = VaultCrypto.deriveKey(password, unb64(slot.salt))897 return try {898 val plaintext = VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A)899 val payload = try {900 VaultCodec.decode(plaintext)901 } finally {902 VaultCrypto.zero(plaintext)903 }904 DuressUnlock(key, payload, epoch)905 } catch (_: Exception) {906 VaultCrypto.zero(key)907 null908 }909 }910911 912 suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {913 val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")914 if (currentEpoch() != unlock.epoch) {915 VaultCrypto.zero(key)916 return@withLock UnlockResult.Error("stale_unlock")917 }918 return try {919 val adopted = mutateIfCurrentEpoch(unlock.epoch) {920 derivedKey = key921 decoyMode = true922 entryList = unlock.payload.entries.toMutableList()923 duressConfigured = false924 recoveryWordHash = unlock.payload.recoveryWordHash925 recoveryWordsSet = unlock.payload.recoveryWordsSet926 sessionDataAvailable = true927 rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)928 else VaultCrypto.generateRootKey()929 _settings.value = store.loadSettings()930 publish()931 _isUnlocked.value = true932 sessionEpoch = nextSessionEpoch(sessionEpoch)933 }934 if (adopted == null) {935 VaultCrypto.zero(key)936 UnlockResult.Error("stale_unlock")937 } else {938 UnlockResult.Success939 }940 } catch (e: Exception) {941 942 943 944 945 mutateIfCurrentEpoch(unlock.epoch) { clearSessionStateLocked() }946 VaultCrypto.zero(key)947 UnlockResult.Error(e.message ?: "decoy_unlock_failed")948 }949 }950951 952 fun discardDuressUnlock(unlock: DuressUnlock) = unlock.discard()953954 955956957958959960 suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {961 962 val expectedEpoch = mutateState {963 if (derivedKey != null && !decoyMode) sessionEpoch else null964 } ?: return false965 966 967 tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }968 var key: ByteArray? = null969 var basePlaintext: ByteArray? = null970 return try {971 val salt = VaultCrypto.generateSalt()972 key = VaultCrypto.deriveKey(duressPassphrase, salt)973 974 val decoyRoot = VaultCrypto.generateRootKey()975 val decoyRootB64 = try { b64(decoyRoot) } finally { VaultCrypto.zero(decoyRoot) }976 val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = decoyRootB64)977 basePlaintext = VaultCodec.encode(decoyPayload)978 979 980 981 982 983 984 985 986 987 val slotA = store.loadSlotA()988 val targetSize = slotA?.let(::matchingCiphertextLength) ?: 0989 val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!990 val blob = try {991 b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_A))992 } finally {993 VaultCrypto.zero(plaintext)994 995 996 if (plaintext !== basePlaintext) basePlaintext?.let(VaultCrypto::zero)997 basePlaintext = null998 key?.let(VaultCrypto::zero)999 key = null1000 }1001 beforeDurableCommit()1002 val ok = withEpochCommit(expectedEpoch) {1003 store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))1004 } ?: false1005 if (ok && mutateIfCurrentEpoch(expectedEpoch) { duressConfigured = true } != null) {1006 runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1007 } else if (ok) {1008 return false1009 }1010 ok1011 } catch (_: Exception) {1012 false1013 } finally {1014 1015 1016 key?.let(VaultCrypto::zero)1017 basePlaintext?.let(VaultCrypto::zero)1018 }1019 }102010211022 102310241025102610271028102910301031 suspend fun exportDuressSlotForAdoption(): String? = mutex.withLock {1032 if (!duressConfigured) return null1033 val slot = store.loadDecoySlot() ?: return null1034 return runCatching { androidDuressSlotToBrowserJson(slot) }.getOrNull()1035 }10361037 1038103910401041104210431044 private fun androidDuressSlotToBrowserJson(slot: StoredVault): String {1045 1046 1047 1048 1049 1050 var salt: ByteArray? = null1051 var blob: ByteArray? = null1052 var nonce: ByteArray? = null1053 var ctAndTag: ByteArray? = null1054 var ct: ByteArray? = null1055 var tag: ByteArray? = null1056 try {1057 salt = unb64(slot.salt)1058 blob = unb64(slot.blob)1059 nonce = blob.copyOfRange(0, VaultCrypto.NONCE_SIZE)1060 ctAndTag = blob.copyOfRange(VaultCrypto.NONCE_SIZE, blob.size)1061 ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)1062 tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)1063 val obj = JsonObject(mapOf(1064 "version" to JsonPrimitive(1),1065 "salt" to JsonPrimitive(salt.joinToString("") { "%02x".format(it) }),1066 "nonce" to JsonPrimitive(nonce.joinToString("") { "%02x".format(it) }),1067 "ciphertext" to JsonPrimitive(ct.joinToString("") { "%02x".format(it) }),1068 "tag" to JsonPrimitive(tag.joinToString("") { "%02x".format(it) }),1069 ))1070 return obj.toString()1071 } finally {1072 salt?.let(VaultCrypto::zero)1073 blob?.let(VaultCrypto::zero)1074 nonce?.let(VaultCrypto::zero)1075 ctAndTag?.let(VaultCrypto::zero)1076 ct?.let(VaultCrypto::zero)1077 tag?.let(VaultCrypto::zero)1078 }1079 }10801081 1082108310841085108610871088108910901091 suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {1092 val b = BrowserSlot.parse(json) ?: return false1093 var stored: StoredVault? = null1094 var salt: ByteArray? = null1095 var nonce: ByteArray? = null1096 var ct: ByteArray? = null1097 var tag: ByteArray? = null1098 var blob: ByteArray? = null1099 try {1100 salt = unhex(b.salt)1101 nonce = unhex(b.nonce)1102 ct = unhex(b.ciphertext)1103 tag = unhex(b.tag)1104 blob = ByteArray(nonce.size + ct.size + tag.size).also {1105 System.arraycopy(nonce, 0, it, 0, nonce.size)1106 System.arraycopy(ct, 0, it, nonce.size, ct.size)1107 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)1108 }1109 stored = StoredVault(version = 1, salt = b64(salt), blob = b64(blob))1110 val expectedEpoch = sessionEpoch1111 beforeDurableCommit()1112 withEpochCommit(expectedEpoch) {1113 store.writeDecoySlot(stored)1114 } ?: false1115 } catch (_: Exception) {1116 false1117 } finally {1118 salt?.let(VaultCrypto::zero)1119 nonce?.let(VaultCrypto::zero)1120 ct?.let(VaultCrypto::zero)1121 tag?.let(VaultCrypto::zero)1122 blob?.let(VaultCrypto::zero)1123 }1124 }11251126 1127 suspend fun clearDuress(): Boolean = mutex.withLock {1128 1129 1130 1131 1132 val expectedEpoch = currentEpoch()1133 val replaced = withEpochCommit(expectedEpoch) {1134 store.loadSlotA()?.let { slotA -> runCatching { writeFakeDuressSlot(slotA) }.getOrDefault(false) }1135 ?: runCatching { store.clearDecoySlot(); true }.getOrDefault(false)1136 } ?: false1137 if (!replaced) return@withLock false1138 1139 1140 if (!isSessionEpochCurrent(expectedEpoch)) return false1141 val shouldClear = mutateIfCurrentEpoch(expectedEpoch) { derivedKey != null && !decoyMode } == true1142 if (shouldClear && mutateIfCurrentEpoch(expectedEpoch) { duressConfigured = false } != null) {1143 runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1144 }1145 true1146 }11471148 1149 private fun isGcmAuthenticationFailure(error: Throwable): Boolean {1150 var current: Throwable? = error1151 while (current != null) {1152 if (current is javax.crypto.AEADBadTagException) return true1153 1154 1155 1156 1157 if (current is javax.crypto.BadPaddingException) return true1158 current = current.cause1159 }1160 return false1161 }11621163 1164 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {1165 val expectedEpoch = currentEpoch()1166 val slotA = try {1167 store.loadSlotA()1168 } catch (_: Exception) {1169 return@withLock UnlockResult.Error("unlock_key_storage_failed")1170 } ?: return@withLock UnlockResult.Error("no_vault")1171 1172 1173 1174 1175 var stagedKey: ByteArray? = key.copyOf()1176 return try {1177 val encrypted = try {1178 unb64(slotA.blob)1179 } catch (_: Exception) {1180 return@withLock UnlockResult.Error("invalid_vault_blob")1181 }1182 1183 1184 1185 1186 if (encrypted.size < VaultCrypto.NONCE_SIZE + (VaultCrypto.TAG_LENGTH_BITS / 8)) {1187 return@withLock UnlockResult.Error("invalid_vault_blob")1188 }1189 val plaintext = try {1190 VaultCrypto.decrypt(encrypted, stagedKey!!, VaultCrypto.AAD_SLOT_A)1191 } catch (e: Exception) {1192 if (isGcmAuthenticationFailure(e)) {1193 return@withLock UnlockResult.WrongPassword1194 }1195 return@withLock UnlockResult.Error("unlock_key_decrypt_failed")1196 }1197 val payload = try {1198 VaultCodec.decode(plaintext)1199 } catch (_: Exception) {1200 return@withLock UnlockResult.Error("invalid_vault_payload")1201 } finally {1202 VaultCrypto.zero(plaintext)1203 }1204 val candidate = stagedKey ?: return UnlockResult.Error("unlock_key_missing")1205 val result = adoptSlotA(candidate, payload, expectedEpoch)1206 if (result is UnlockResult.Success) { stagedKey = null; ensureRecoveryEscrow() }1207 result1208 } finally {1209 stagedKey?.let(VaultCrypto::zero)1210 }1211 }12121213 fun lock() {1214 1215 1216 1217 1218 if (mutex.tryLock()) {1219 try {1220 runCatching { LockedSyncSpoolHooks.refresh(this) }1221 } finally {1222 mutex.unlock()1223 }1224 }1225 1226 1227 1228 1229 1230 1231 stateLock.lock()1232 try {1233 sessionEpoch = nextSessionEpoch(sessionEpoch)1234 clearSessionStateLocked()1235 _uiGateLocked.value = false1236 } finally {1237 stateLock.unlock()1238 }1239 }12401241 1242124312441245124612471248 fun lockUiGate() {1249 if (_isUnlocked.value) _uiGateLocked.value = true1250 }12511252 1253 fun clearUiGate() {1254 _uiGateLocked.value = false1255 }12561257 @Volatile private var suppressNextBackgroundLockUntil: Long = 0L12581259 1260 1261 @VisibleForTesting1262 internal var nowMs: () -> Long = { SystemClock.elapsedRealtime() }12631264 126512661267126812691270127112721273127412751276 fun expectTransientBackground() {1277 suppressNextBackgroundLockUntil = nowMs() + BACKGROUND_LOCK_SUPPRESSION_TIMEOUT_MS1278 }12791280 12811282128312841285 fun consumeTransientBackgroundSuppression(): Boolean {1286 val until = suppressNextBackgroundLockUntil1287 val active = until != 0L && nowMs() < until1288 suppressNextBackgroundLockUntil = 0L1289 return active1290 }12911292 12931294 12951296129712981299 13001301130213031304130513061307130813091310 1311 1312 1313 1314 1315 internal data class SyncMasterKeySnapshot(val epoch: Long, val key: ByteArray)13161317 internal fun syncMasterKeySnapshot(): SyncMasterKeySnapshot? = mutateState {1318 if (decoyMode || !_isUnlocked.value) null1319 else rootKey?.copyOf()?.let { SyncMasterKeySnapshot(sessionEpoch, it) }1320 }13211322 internal fun isSessionEpochCurrent(epoch: Long): Boolean =1323 mutateState { sessionEpoch == epoch }13241325 internal fun unlockedSessionEpoch(): Long? = mutateState {1326 if (derivedKey != null && _isUnlocked.value) sessionEpoch else null1327 }13281329 fun syncMasterKey(): ByteArray? = syncMasterKeySnapshot()?.key13301331 133213331334133513361337133813391340 fun sessionRootKey(): ByteArray? = mutateState {1341 if (!sessionDataAvailable) null else rootKey?.copyOf()1342 }13431344 13451346 fun syncVaultId(): String? = mutateState {1347 if (decoyMode || !_isUnlocked.value) null1348 else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }1349 }13501351 13521353135413551356 suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {1357 val expectedEpoch = mutateState { if (derivedKey != null && !decoyMode) sessionEpoch else null }1358 ?: return false1359 installRootKey(generateRecoverableRootKey(), expectedEpoch)1360 }13611362 13631364136513661367136813691370137113721373137413751376137713781379 suspend fun joinVault(rootKeyHex: String): AdoptVaultResult = mutex.withLock {1380 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {1381 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 64 lowercase hex chars")1382 }1383 val expectedEpoch = mutateState {1384 when {1385 derivedKey == null -> null1386 decoyMode -> Long.MIN_VALUE1387 else -> sessionEpoch1388 }1389 }1390 if (expectedEpoch == null) return AdoptVaultResult.Error("vault_locked")1391 if (expectedEpoch == Long.MIN_VALUE) return AdoptVaultResult.Error("JOIN_DECOY_MODE")1392 if (!store.hasVault()) return AdoptVaultResult.Error("JOIN_NO_LOCAL_VAULT")13931394 val incoming = hexToRootKey(rootKeyHex)1395 if (incoming.size != VaultCrypto.KEY_SIZE) {1396 VaultCrypto.zero(incoming)1397 return AdoptVaultResult.Error("JOIN_INVALID_ROOT_KEY: expected 32 bytes")1398 }1399 1400 1401 1402 val roundTrips = runCatching { wordsToRootKeyMaterial(rootKeyToWords(incoming)) }.isSuccess1403 if (!roundTrips) {1404 VaultCrypto.zero(incoming)1405 return AdoptVaultResult.Error("JOIN_UNRECOVERABLE_ROOT_KEY")1406 }14071408 val vaultId = com.peachpasswords.sync.computeVaultId(incoming)1409 return if (installRootKey(incoming, expectedEpoch)) {1410 AdoptVaultResult.Success(vaultId)1411 } else {1412 AdoptVaultResult.Error("JOIN_INSTALL_FAILED")1413 }1414 }14151416 14171418141914201421 fun previewRecoveryWords(rootKeyHex: String): List<String>? {1422 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) return null1423 val bytes = hexToRootKey(rootKeyHex)1424 return try {1425 val words = rootKeyToWords(bytes)1426 if (runCatching { wordsToRootKeyMaterial(words) }.isSuccess) words else null1427 } catch (_: Exception) {1428 null1429 } finally {1430 VaultCrypto.zero(bytes)1431 }1432 }14331434 14351436143714381439 private suspend fun installRootKey(nextRootKey: ByteArray, expectedEpoch: Long): Boolean {1440 1441 1442 1443 1444 1445 1446 data class Snapshot(1447 val key: ByteArray,1448 val priorRootKey: ByteArray,1449 val priorRecoveryHash: String?,1450 val priorRecoverySet: Boolean,1451 )1452 val snap = mutateIfCurrentEpoch(expectedEpoch) {1453 val k = derivedKey ?: return@mutateIfCurrentEpoch null1454 if (decoyMode) return@mutateIfCurrentEpoch null1455 val priorRoot = rootKey ?: return@mutateIfCurrentEpoch null1456 Snapshot(k.copyOf(), priorRoot.copyOf(), recoveryWordHash, recoveryWordsSet)1457 } ?: run {1458 VaultCrypto.zero(nextRootKey)1459 return false1460 }1461 val priorSlot = store.loadSlotA() ?: run {1462 VaultCrypto.zero(snap.key)1463 VaultCrypto.zero(snap.priorRootKey)1464 VaultCrypto.zero(nextRootKey)1465 return false1466 }1467 val nextWords = rootKeyToWords(nextRootKey)14681469 return try {1470 beforeDurableCommit()1471 if (!takeVaultSnapshot("local_save", expectedEpoch)) throw IllegalStateException("snapshot_failed")1472 if (mutateIfCurrentEpoch(expectedEpoch) {1473 rootKey = nextRootKey1474 recoveryWordHash = recoveryWordsHash(nextWords)1475 recoveryWordsSet = false1476 } == null) throw IllegalStateException("stale_root_rotation")14771478 val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)1479 ?: throw IllegalStateException("recovery_escrow_failed")1480 val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)1481 ?: throw IllegalStateException("root_escrow_failed")1482 val plaintext = VaultCodec.encode(currentPayload())1483 val blob = try {1484 b64(VaultCrypto.encrypt(plaintext, snap.key, VaultCrypto.AAD_SLOT_A))1485 } finally {1486 VaultCrypto.zero(plaintext)1487 }1488 val nextSlot = priorSlot.copy(1489 blob = blob,1490 recoveryEscrow = nextRecoveryEscrow,1491 rootKeyEscrow = nextRootKeyEscrow,1492 )1493 val committed = withEpochCommit(expectedEpoch) {1494 if (!store.writeSlotA(nextSlot)) return@withEpochCommit false1495 try {1496 if (!writeMatchingNoiseSlotB(nextSlot)) throw IllegalStateException("noise_slot_b_commit_failed")1497 1498 1499 if (!writeCompanionDuressSlot(nextSlot)) throw IllegalStateException("duress_slot_commit_failed")1500 store.stampLocalMutation()1501 } catch (_: Exception) {1502 store.writeSlotA(priorSlot)1503 return@withEpochCommit false1504 }1505 true1506 } ?: false1507 if (!committed) throw IllegalStateException("storage_write_failed")1508 mutateIfCurrentEpoch(expectedEpoch) { publish() }1509 true1510 } catch (_: Exception) {1511 val restored = mutateIfCurrentEpoch(expectedEpoch) {1512 rootKey?.let(VaultCrypto::zero)1513 rootKey = snap.priorRootKey.copyOf()1514 recoveryWordHash = snap.priorRecoveryHash1515 recoveryWordsSet = snap.priorRecoverySet1516 }1517 if (restored != null) {1518 withEpochCommit(expectedEpoch) { store.writeSlotA(priorSlot) }1519 }1520 false1521 } finally {1522 VaultCrypto.zero(snap.key)1523 VaultCrypto.zero(snap.priorRootKey)1524 1525 1526 1527 val stillOwnedBySession = mutateState {1528 sessionEpoch == expectedEpoch && rootKey === nextRootKey1529 }1530 if (!stillOwnedBySession) VaultCrypto.zero(nextRootKey)1531 }1532 }15331534 15351536153715381539 fun currentVaultKey(): ByteArray? = mutateState {1540 if (!isFullyUnlockedLocked()) null else derivedKey?.copyOf()1541 }15421543 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {1544 val expectedEpoch = currentEpoch()1545 val slotA = store.loadSlotA() ?: return false1546 var oldKey: ByteArray? = null1547 var newKey: ByteArray? = null1548 var plaintext: ByteArray? = null1549 return try {1550 oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))1551 1552 1553 1554 1555 val decrypted = VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A)1556 val payload = try {1557 VaultCodec.decode(decrypted)1558 } finally {1559 VaultCrypto.zero(decrypted)1560 }1561 val newSalt = VaultCrypto.generateSalt()1562 newKey = VaultCrypto.deriveKey(newPassword, newSalt)1563 1564 plaintext = VaultCodec.encode(payload)1565 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1566 1567 1568 1569 1570 1571 1572 1573 val next = StoredVault(1574 version = slotA.version,1575 salt = b64(newSalt),1576 blob = blob,1577 recoveryEscrow = slotA.recoveryEscrow,1578 rootKeyEscrow = slotA.rootKeyEscrow,1579 )1580 1581 1582 1583 1584 val priorB = store.loadSlotB()1585 if (!commitVaultRotation(slotA, priorB, next, expectedEpoch)) return false1586 1587 1588 1589 if (mutateIfCurrentEpoch(expectedEpoch) {1590 oldKey?.let(VaultCrypto::zero); oldKey = null1591 derivedKey?.let(VaultCrypto::zero)1592 derivedKey = newKey; newKey = null1593 } == null) return false1594 true1595 } catch (_: Exception) {1596 false1597 } finally {1598 oldKey?.let(VaultCrypto::zero)1599 newKey?.let(VaultCrypto::zero)1600 plaintext?.let(VaultCrypto::zero)1601 }1602 }16031604 1605160616071608 suspend fun destroyVault() = mutex.withLock {1609 lock()1610 store.clearVault()1611 store.clearDecoySlot()1612 }16131614 16151616 1617161816191620162116221623162416251626162716281629 private val entryIdShape = Regex("[A-Za-z0-9_-]{1,64}")16301631 private fun String?.normalizedEntryId(): String =1632 if (this != null && entryIdShape.matches(this)) this else UUID.randomUUID().toString()16331634 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {1635 val epoch = requireUnlocked()1636 val stamp = VaultCrypto.monotonicEntryTimestamp()1637 val now = System.currentTimeMillis()1638 val entry = withDerivedLast4(draft.copy(1639 id = draft.id.normalizedEntryId(),1640 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1641 modifiedAt = stamp,1642 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1643 ))1644 1645 1646 val rollback = mutateCurrentSession(epoch) {1647 val r = entryList.toMutableList()1648 entryList.add(entry)1649 r1650 } ?: throw IllegalStateException("vault_locked")1651 persistOrRollback(rollback, epoch)1652 entry1653 }16541655 165616571658165916601661166216631664 suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {1665 val epoch = requireUnlocked()1666 if (drafts.isEmpty()) return 01667 val now = System.currentTimeMillis()1668 val ready = drafts.map { draft ->1669 val stamp = VaultCrypto.monotonicEntryTimestamp()1670 withDerivedLast4(1671 draft.copy(1672 id = draft.id.normalizedEntryId(),1673 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1674 modifiedAt = stamp,1675 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1676 ),1677 )1678 }1679 1680 val rollback = mutateCurrentSession(epoch) {1681 val r = entryList.toMutableList()1682 entryList.addAll(ready)1683 r1684 } ?: throw IllegalStateException("vault_locked")1685 persistOrRollback(rollback, epoch)1686 return drafts.size1687 }16881689 1690169116921693169416951696169716981699170017011702 suspend fun replaceEntries(newEntries: List<VaultEntry>): Int = mutex.withLock {1703 val epoch = requireUnlocked()1704 val now = System.currentTimeMillis()1705 val ready = newEntries.map { draft ->1706 val stamp = VaultCrypto.monotonicEntryTimestamp()1707 withDerivedLast4(1708 draft.copy(1709 id = draft.id.normalizedEntryId(),1710 createdAt = if (draft.createdAt > 0) draft.createdAt else now,1711 modifiedAt = stamp,1712 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,1713 ),1714 )1715 }1716 1717 1718 1719 1720 1721 1722 val incomingIds = ready.map { it.id }.toHashSet()1723 val rollback = mutateCurrentSession(epoch) {1724 val r = entryList.toMutableList()1725 val replaced = entryList.map { entry ->1726 if (entry.deletedAt != null) return@map entry1727 if (entry.id in incomingIds) return@map null1728 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1729 entry.copy(deletedAt = stamp, modifiedAt = stamp)1730 }.filterNotNull()1731 entryList = (replaced + ready).toMutableList()1732 r1733 } ?: throw IllegalStateException("vault_locked")1734 persistOrRollback(rollback, epoch)1735 return ready.size1736 }17371738 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {1739 val epoch = requireUnlocked()1740 1741 1742 1743 1744 val prepared = mutateCurrentSession(epoch) {1745 val idx = entryList.indexOfFirst { it.id == patch.id }1746 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1747 val current = entryList[idx]1748 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1749 1750 val passwordChanged = patch.password != null && patch.password != current.password1751 1752 1753 1754 1755 1756 1757 val priorPassword = current.password1758 val shouldCapture = passwordChanged &&1759 !priorPassword.isNullOrEmpty() &&1760 current.passwordHistory?.firstOrNull()?.password != priorPassword1761 val nextHistory = if (shouldCapture) {1762 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +1763 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)1764 } else {1765 current.passwordHistory1766 }1767 val updated = withDerivedLast4(patch.copy(1768 createdAt = current.createdAt,1769 modifiedAt = stamp,1770 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,1771 passwordHistory = nextHistory,1772 ))1773 val rollback = entryList.toMutableList()1774 entryList[idx] = updated1775 updated to rollback1776 } ?: throw IllegalStateException("vault_locked")1777 val (updated, rollback) = prepared1778 persistOrRollback(rollback, epoch)1779 updated1780 }17811782 1783 suspend fun deleteEntry(id: String) = mutex.withLock {1784 val epoch = requireUnlocked()1785 1786 1787 val rollback = mutateCurrentSession(epoch) {1788 val idx = entryList.indexOfFirst { it.id == id }1789 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")1790 val current = entryList[idx]1791 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)1792 val prior = entryList.toMutableList()1793 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)1794 prior1795 } ?: throw IllegalStateException("vault_locked")1796 persistOrRollback(rollback, epoch)1797 }17981799 suspend fun restoreEntry(id: String) = mutex.withLock {1800 val epoch = requireUnlocked()1801 val rollback = mutateCurrentSession(epoch) {1802 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1803 if (idx == -1) throw IllegalStateException("deleted entry not found")1804 val current = entryList[idx]1805 val prior = entryList.toMutableList()1806 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))1807 prior1808 } ?: throw IllegalStateException("vault_locked")1809 persistOrRollback(rollback, epoch)1810 }18111812 1813 suspend fun purgeEntry(id: String) = mutex.withLock {1814 val epoch = requireUnlocked()1815 val rollback = mutateCurrentSession(epoch) {1816 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }1817 if (idx == -1) throw IllegalStateException("deleted entry not found")1818 val prior = entryList.toMutableList()1819 entryList.removeAt(idx)1820 prior1821 } ?: throw IllegalStateException("vault_locked")1822 persistOrRollback(rollback, epoch)1823 }18241825 1826 suspend fun purgeDeletedEntries(): Int = mutex.withLock {1827 val epoch = requireUnlocked()1828 1829 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1830 val r = mutateCurrentSession(epoch) {1831 val rollback = entryList.toMutableList()1832 val before = entryList.size1833 entryList.removeAll { it.deletedAt != null }1834 R(rollback, before - entryList.size)1835 } ?: throw IllegalStateException("vault_locked")1836 if (r.removed > 0) persistOrRollback(r.rollback, epoch)1837 r.removed1838 }18391840 1841 suspend fun countDuplicateEntries(): Int = mutex.withLock {1842 val epoch = requireUnlocked()1843 1844 1845 mutateCurrentSession(epoch) { countDuplicateEntriesLocked() }1846 ?: throw IllegalStateException("vault_locked")1847 }18481849 18501851185218531854 suspend fun deduplicateEntries(): Int = mutex.withLock {1855 val epoch = requireUnlocked()1856 data class R(val rollback: MutableList<VaultEntry>, val removed: Int)1857 val ready = mutateCurrentSession(epoch) {1858 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")1859 val active = entryList.filter { it.deletedAt == null }1860 val keepIds = mutableSetOf<String>()1861 active.groupBy { it.duplicateKey() }.values.forEach { group ->1862 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id1863 }1864 val rollback = entryList.toMutableList()1865 var removed = 01866 entryList = entryList.map { entry ->1867 if (entry.deletedAt == null && entry.id !in keepIds) {1868 removed++1869 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)1870 entry.copy(deletedAt = stamp, modifiedAt = stamp)1871 } else {1872 entry1873 }1874 }.toMutableList()1875 R(rollback, removed)1876 } ?: throw IllegalStateException("vault_locked")1877 if (ready.removed > 0) persistOrRollback(ready.rollback, epoch)1878 ready.removed1879 }18801881 fun getEntries(): List<VaultEntry> = mutateState {1882 if (!sessionDataAvailable) emptyList() else entryList.filter { it.deletedAt == null }1883 }1884 fun getEntry(id: String): VaultEntry? = mutateState {1885 if (!sessionDataAvailable) null else entryList.firstOrNull { it.id == id && it.deletedAt == null }1886 }1887 fun getDeletedEntries(): List<VaultEntry> = mutateState {1888 if (!sessionDataAvailable) emptyList()1889 else entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }1890 }18911892 1893 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {1894 return mutateState {1895 if (!sessionDataAvailable) return@mutateState emptyList()1896 val active = entryList.filter { it.deletedAt == null }1897 if (tagFilter == null) return@mutateState active1898 val needle = tagFilter.trim().lowercase()1899 active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }1900 }1901 }19021903 1904 fun getDistinctTags(): List<String> = mutateState {1905 if (!sessionDataAvailable) return@mutateState emptyList()1906 entryList.asSequence()1907 .filter { it.deletedAt == null }1908 .flatMap { it.tags?.asSequence() ?: emptySequence() }1909 .map { it.trim().lowercase() }1910 .filter { it.isNotEmpty() }1911 .distinct()1912 .sorted()1913 .toList()1914 }19151916 191719181919192019211922 fun getDistinctFieldValues(field: String): List<String> {1923 val select: (VaultEntry) -> String? = when (field) {1924 "username" -> { e -> e.username }1925 "email" -> { e -> e.email }1926 else -> return emptyList()1927 }1928 return mutateState {1929 if (!sessionDataAvailable) return@mutateState emptyList()1930 entryList.asSequence()1931 .filter { it.deletedAt == null }1932 .mapNotNull { select(it)?.trim() }1933 .filter { it.isNotEmpty() }1934 .groupingBy { it.lowercase() }1935 .aggregate { _, acc: Pair<String, Int>?, value, _ ->1936 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)1937 }1938 .values1939 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })1940 .map { it.first }1941 }1942 }19431944 fun getTombstones(): List<Tombstone> = mutateState {1945 if (!sessionDataAvailable) emptyList()1946 else entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }1947 }1948 fun getVaultVersion(): Long = store.version()1949 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots19501951 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {1952 val expectedEpoch = currentEpoch()1953 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false1954 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false1955 1956 1957 val restoredD: StoredVault? = snapshot.vault_d?.let(VaultCodec::decodeSlot)1958 val priorA = store.loadSlotA()1959 val priorB = store.loadSlotB()1960 val priorD = store.loadDecoySlot()1961 1962 1963 1964 1965 1966 val priorHistory = store.loadVaultHistory()1967 1968 1969 1970 1971 beforeDurableCommit()1972 if (!takeVaultSnapshot("restore", expectedEpoch)) {1973 return false1974 }1975 1976 1977 1978 val nextD: StoredVault = restoredD ?: run {1979 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 161980 val fakeBlob = ByteArray(target).also(rng::nextBytes)1981 val fakeSalt = VaultCrypto.generateSalt()1982 StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob))1983 }1984 if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {1985 withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }1986 return false1987 }1988 lock()1989 true1990 }19911992 19931994199519961997199819992000200120022003 private fun commitRestoreAtomic(2004 nextA: StoredVault,2005 nextB: String,2006 nextD: StoredVault,2007 priorA: StoredVault?,2008 priorB: String?,2009 priorD: StoredVault?,2010 expectedEpoch: Long,2011 ): Boolean {2012 return withEpochCommit(expectedEpoch) {2013 if (!store.writeSlotA(nextA)) return@withEpochCommit false2014 2015 2016 2017 try {2018 if (!store.writeSlotB(nextB)) throw java.io.IOException("slot_b_commit_failed")2019 2020 2021 if (!store.writeDecoySlot(nextD)) throw java.io.IOException("duress_slot_commit_failed")2022 store.stampLocalMutation()2023 } catch (_: Exception) {2024 reportRollbackFailures(rollbackRestoreLocked(priorA, priorB, priorD))2025 return@withEpochCommit false2026 }2027 true2028 } ?: false2029 }20302031 20322033 20342035203620372038 suspend fun applyMergedRemoteEntries(2039 remoteEntries: List<VaultEntry>,2040 remoteTombstones: List<Tombstone>,2041 expectedEpoch: Long? = null,2042 ): Int = mutex.withLock {2043 val epoch = expectedEpoch ?: requireUnlocked()2044 if (expectedEpoch != null && mutateIfCurrentEpoch(epoch) { true } != true) return@withLock 02045 2046 2047 2048 2049 2050 val mergeNow = System.currentTimeMillis()2051 val clamped = remoteEntries.mapNotNull { entry ->2052 2053 2054 2055 SyncEntrySanitizer.sanitize(entry, PASSWORD_HISTORY_MAX)?.copy(2056 modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),2057 deletedAt = entry.deletedAt?.let {2058 SyncLimits.clampSyncTimestamp(it, mergeNow)2059 },2060 )2061 }2062 val tombMap = remoteTombstones.associate {2063 it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)2064 }2065 2066 2067 val applied = mutateCurrentSession(epoch) {2068 var n = 02069 val byId = entryList.associateBy { it.id }.toMutableMap()20702071 for (remote in clamped) {2072 val tomb = tombMap[remote.id]2073 if (tomb != null && tomb >= remote.modifiedAt) continue2074 val local = byId[remote.id]2075 if (local == null) {2076 entryList.add(remote); byId[remote.id] = remote; n++2077 } else if (remote.modifiedAt > local.modifiedAt) {2078 val i = entryList.indexOfFirst { it.id == local.id }2079 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; n++ }2080 }2081 }20822083 for ((id, deletedAt) in tombMap) {2084 val local = byId[id] ?: continue2085 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue2086 if (deletedAt < local.modifiedAt) continue2087 val i = entryList.indexOfFirst { it.id == id }2088 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); n++ }2089 }2090 n2091 } ?: return@withLock 020922093 if (applied > 0) {2094 persistSlotA(bumpVersion = false, snapshotReason = "sync_received", expectedEpoch = epoch)2095 mutateIfCurrentEpoch(epoch) { publish() }2096 runCatching { LockedSyncSpoolHooks.refresh(this) }2097 }2098 applied2099 }21002101 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {2102 2103 2104 2105 val epoch = requireUnlocked()2106 val prior = mutateCurrentSession(epoch) {2107 val old = _settings.value2108 _settings.value = settings2109 old2110 } ?: throw IllegalStateException("vault_locked")21112112 val committed = try {2113 beforeDurableCommit()2114 2115 2116 2117 withSessionEpochCommit(epoch) { store.writeSettings(settings) } == true2118 } catch (_: Exception) {2119 false2120 }2121 if (!committed) {2122 2123 2124 2125 mutateIfCurrentEpoch(epoch) { _settings.value = prior }2126 throw IllegalStateException("settings_write_failed")2127 }2128 }21292130 21312132 2133 fun isRecoveryWordsSet(): Boolean = mutateState { recoveryWordsSet }21342135 21362137213821392140 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {2141 val epoch = requireUnlocked()2142 2143 2144 2145 2146 2147 2148 val prior = mutateCurrentSession(epoch) {2149 val priorPair = recoveryWordHash to recoveryWordsSet2150 recoveryWordHash = recoveryWordsHash(words)2151 recoveryWordsSet = true2152 priorPair2153 } ?: return@withLock false2154 2155 2156 2157 2158 val persisted = runCatching {2159 persistSlotAWithEscrows(2160 buildRecoveryEscrow(words),2161 buildRootKeyEscrow(words),2162 expectedEpoch = epoch,2163 )2164 }.getOrDefault(false)2165 if (!persisted) {2166 mutateIfCurrentEpoch(epoch) {2167 recoveryWordHash = prior.first2168 recoveryWordsSet = prior.second2169 }2170 }2171 persisted2172 }21732174 2175 fun verifyRecoveryWords(words: List<String>): Boolean {2176 return mutateState {2177 val stored = recoveryWordHash ?: return@mutateState false2178 MessageDigest.isEqual(2179 stored.toByteArray(Charsets.UTF_8),2180 recoveryWordsHash(words).toByteArray(Charsets.UTF_8),2181 )2182 }2183 }21842185 21862187 2188 fun hasRecoveryEscrow(): Boolean =2189 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false21902191 21922193219421952196 private fun ensureRecoveryEscrow() {2197 if (hasRecoveryEscrow()) return2198 val rk = mutateState { rootKey?.copyOf() } ?: return2199 runCatching {2200 val words = rootKeyToWords(rk)2201 val escrow = buildRecoveryEscrow(words)2202 val rkEscrow = buildRootKeyEscrow(words)2203 if (escrow != null || rkEscrow != null) {2204 val prior = store.loadSlotA() ?: return@runCatching2205 store.writeSlotA(prior.copy(2206 recoveryEscrow = escrow ?: prior.recoveryEscrow,2207 rootKeyEscrow = rkEscrow ?: prior.rootKeyEscrow,2208 ))2209 mutateState {2210 recoveryWordHash = recoveryWordsHash(words)2211 recoveryWordsSet = true2212 }2213 }2214 }.also { VaultCrypto.zero(rk) }2215 }22162217 221822192220222122222223222422252226222722282229 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {2230 val expectedEpoch = currentEpoch()2231 val slotA = store.loadSlotA() ?: return false2232 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false22332234 2235 2236 val fullEscrow = slotA.recoveryEscrow2237 if (fullEscrow != null) {2238 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull()2239 if (material != null) {2240 var keyBytes: ByteArray? = null2241 var plaintext: ByteArray? = null2242 var candidateRoot: ByteArray? = null2243 var stateCommitStarted = false2244 try {2245 keyBytes = deriveRecoveryKey(material, unb64(fullEscrow.salt)).encoded2246 plaintext = VaultCrypto.decrypt(unb64(fullEscrow.blob), keyBytes!!, VaultCrypto.AAD_RECOVERY)2247 val payload = VaultCodec.decode(plaintext)2248 2249 2250 2251 2252 val candidateSettings = store.loadSettings()2253 candidateRoot = if (payload.rootKeyB64.isNotBlank()) {2254 val decodedRoot = unb64(payload.rootKeyB64)2255 if (decodedRoot.size != VaultCrypto.KEY_SIZE) {2256 2257 2258 2259 VaultCrypto.zero(decodedRoot)2260 throw IllegalArgumentException("invalid recovery root key")2261 }2262 decodedRoot2263 } else {2264 generateRecoverableRootKey()2265 }2266 stateCommitStarted = true2267 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2268 clearSessionStateLocked()2269 entryList = payload.entries.toMutableList()2270 duressConfigured = payload.duressConfigured2271 recoveryWordHash = payload.recoveryWordHash2272 recoveryWordsSet = payload.recoveryWordsSet2273 rootKey = candidateRoot2274 candidateRoot = null2275 _settings.value = candidateSettings2276 publish()2277 2278 2279 sessionDataAvailable = true2280 _isUnlocked.value = false2281 true2282 }2283 if (adopted == true) return@withLock true2284 } catch (_: Exception) {2285 2286 2287 2288 2289 if (stateCommitStarted) {2290 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2291 }2292 } finally {2293 plaintext?.let(VaultCrypto::zero)2294 VaultCrypto.zero(material)2295 keyBytes?.let(VaultCrypto::zero)2296 candidateRoot?.let(VaultCrypto::zero)2297 }2298 }2299 }23002301 2302 2303 2304 val rootEscrow = slotA.rootKeyEscrow2305 if (rootEscrow != null) {2306 var candidateRoot: ByteArray? = null2307 var stateCommitStarted = false2308 try {2309 candidateRoot = unsealRootKeyEscrow(words, rootEscrow) ?: return false2310 require(candidateRoot!!.size == VaultCrypto.KEY_SIZE) { "invalid recovery root key" }2311 val candidateSettings = store.loadSettings()2312 stateCommitStarted = true2313 val adopted = mutateIfCurrentEpoch(expectedEpoch) {2314 clearSessionStateLocked()2315 entryList = mutableListOf()2316 duressConfigured = false2317 recoveryWordHash = recoveryWordsHash(words)2318 recoveryWordsSet = true2319 rootKey = candidateRoot2320 candidateRoot = null2321 _settings.value = candidateSettings2322 publish()2323 sessionDataAvailable = true2324 _isUnlocked.value = false2325 true2326 }2327 if (adopted == true) return@withLock true2328 } catch (_: Exception) {2329 if (stateCommitStarted) {2330 mutateIfCurrentEpoch(expectedEpoch) { clearSessionStateLocked() }2331 }2332 } finally {2333 candidateRoot?.let(VaultCrypto::zero)2334 }2335 }2336 return false2337 }23382339 234023412342234323442345234623472348 suspend fun resetPasswordWithRecoveryWords(2349 words: List<String>,2350 newPassword: String,2351 ): Boolean = mutex.withLock {2352 val expectedEpoch = currentEpoch()2353 2354 2355 2356 if (mutateIfCurrentEpoch(expectedEpoch) { rootKey != null } != true) return false2357 val priorA = store.loadSlotA() ?: return false2358 var newKey: ByteArray? = null2359 var plaintext: ByteArray? = null2360 return try {2361 val newSalt = VaultCrypto.generateSalt()2362 newKey = VaultCrypto.deriveKey(newPassword, newSalt)2363 plaintext = VaultCodec.encode(currentPayload())2364 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))2365 2366 2367 2368 val valid = words.size == 12 && findInvalidWords(words).isEmpty()2369 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: priorA.recoveryEscrow else priorA.recoveryEscrow2370 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: priorA.rootKeyEscrow else priorA.rootKeyEscrow2371 val next = StoredVault(2372 version = priorA.version,2373 salt = b64(newSalt),2374 blob = blob,2375 recoveryEscrow = freshRecovery,2376 rootKeyEscrow = freshRootKey,2377 )2378 2379 2380 2381 val priorB = store.loadSlotB()2382 if (!commitVaultRotation(priorA, priorB, next, expectedEpoch)) return false2383 2384 2385 2386 if (mutateIfCurrentEpoch(expectedEpoch) {2387 derivedKey?.let(VaultCrypto::zero)2388 derivedKey = newKey; newKey = null2389 publish()2390 _isUnlocked.value = true2391 } == null) return false2392 true2393 } catch (_: Exception) {2394 false2395 } finally {2396 newKey?.let(VaultCrypto::zero)2397 plaintext?.let(VaultCrypto::zero)2398 }2399 }24002401 240224032404240524062407 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {2408 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2409 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2410 var keyBytes: ByteArray? = null2411 var plaintext: ByteArray? = null2412 return try {2413 val salt = VaultCrypto.generateSalt()2414 val recoveryKey = deriveRecoveryKey(material, salt)2415 keyBytes = recoveryKey.encoded2416 plaintext = VaultCodec.encode(currentPayload())2417 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)2418 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))2419 } finally {2420 VaultCrypto.zero(material)2421 keyBytes?.let(VaultCrypto::zero)2422 plaintext?.let(VaultCrypto::zero)2423 }2424 }24252426 24272428242924302431243224332434 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {2435 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null2436 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2437 val rk = mutateState { rootKey?.copyOf() } ?: run {2438 VaultCrypto.zero(material)2439 return null2440 }2441 var keyBytes: ByteArray? = null2442 var plaintext: ByteArray? = null2443 return try {2444 val salt = VaultCrypto.generateSalt()2445 val recoveryKey = deriveRecoveryKey(material, salt)2446 keyBytes = recoveryKey.encoded2447 plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)2448 2449 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2450 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)2451 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)2452 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)2453 val ct = ctTag.copyOfRange(0, ctTag.size - 16)2454 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))2455 } finally {2456 VaultCrypto.zero(rk)2457 VaultCrypto.zero(material)2458 keyBytes?.let(VaultCrypto::zero)2459 plaintext?.let(VaultCrypto::zero)2460 }2461 }24622463 2464 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {2465 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null2466 var keyBytes: ByteArray? = null2467 var pt: ByteArray? = null2468 return try {2469 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))2470 keyBytes = recoveryKey.encoded2471 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)2472 pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)2473 hexToRootKey(String(pt, Charsets.US_ASCII))2474 } catch (_: Exception) {2475 null2476 } finally {2477 2478 2479 2480 VaultCrypto.zero(material)2481 keyBytes?.let(VaultCrypto::zero)2482 pt?.let(VaultCrypto::zero)2483 }2484 }24852486 248724882489249024912492 private fun persistSlotAWithEscrows(2493 recoveryEscrow: RecoveryEscrow?,2494 rootKeyEscrow: RootKeyEscrow?,2495 expectedEpoch: Long? = null,2496 ): Boolean {2497 val snapshot = snapshotForPersist(expectedEpoch)2498 ?: throw IllegalStateException("vault_locked_or_stale")2499 if (snapshot.decoy) {2500 VaultCrypto.zero(snapshot.key)2501 return false2502 }2503 try {2504 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2505 val plaintext = VaultCodec.encode(snapshot.payload)2506 val blob = try {2507 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2508 } finally {2509 2510 2511 VaultCrypto.zero(plaintext)2512 }2513 val next = prior.copy(2514 blob = blob,2515 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,2516 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,2517 )2518 beforeDurableCommit()2519 return withEpochCommit(snapshot.epoch) {2520 if (!store.writeSlotA(next)) return@withEpochCommit false2521 try {2522 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2523 2524 2525 2526 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2527 } catch (e: Exception) {2528 store.writeSlotA(prior)2529 throw e2530 }2531 true2532 } ?: false2533 } finally {2534 VaultCrypto.zero(snapshot.key)2535 }2536 }25372538 25392540 private fun requireUnlocked(): Long {2541 2542 2543 2544 stateLock.lock()2545 try {2546 if (derivedKey == null) throw IllegalStateException("vault_locked")2547 return sessionEpoch2548 } finally {2549 stateLock.unlock()2550 }2551 }25522553 2554 private fun isFullyUnlockedLocked(): Boolean = _isUnlocked.value && derivedKey != null25552556 private fun countDuplicateEntriesLocked(): Int {2557 val seen = mutableMapOf<String, VaultEntry>()2558 var duplicates = 02559 for (entry in entryList.filter { it.deletedAt == null }) {2560 val key = entry.duplicateKey()2561 val existing = seen[key]2562 if (existing == null) {2563 seen[key] = entry2564 } else {2565 duplicates++2566 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt2567 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt2568 if (entryStamp > existingStamp) seen[key] = entry2569 }2570 }2571 return duplicates2572 }25732574 private fun VaultEntry.duplicateKey(): String {2575 if (type == "note") return "note|${title.lowercase()}"2576 val passkeyData = passkey2577 if (passkeyData != null) {2578 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"2579 }2580 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"2581 }25822583 258425852586258725882589 private fun takeVaultSnapshot(reason: String, expectedEpoch: Long? = null): Boolean {2590 val epoch = expectedEpoch ?: currentEpoch()2591 if (mutateIfCurrentEpoch(epoch) { true } != true) return false2592 val slotA = store.loadSlotA() ?: return false2593 val vaultA = VaultCodec.encodeSlot(slotA)2594 val vaultB = store.loadSlotB() ?: slotA.blob2595 2596 2597 2598 2599 2600 val vaultD = store.loadDecoySlot()?.let(VaultCodec::encodeSlot) ?: run {2601 val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162602 val fakeBlob = ByteArray(target).also(rng::nextBytes)2603 val fakeSalt = VaultCrypto.generateSalt()2604 VaultCodec.encodeSlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2605 }2606 val history = store.loadVaultHistory()2607 val latest = history.snapshots.firstOrNull()2608 if (latest?.vault_a == vaultA && latest.vault_b == vaultB && latest.vault_d == vaultD) return true2609 val entryCount = mutateIfCurrentEpoch(epoch) {2610 if (derivedKey != null && !decoyMode) {2611 bucketEntryCount(entryList.count { it.deletedAt == null })2612 } else {2613 null2614 }2615 } ?: return false2616 return try {2617 val snapshot = VaultSnapshot(2618 id = UUID.randomUUID().toString(),2619 savedAt = System.currentTimeMillis(),2620 reason = reason,2621 vault_a = vaultA,2622 vault_b = vaultB,2623 vault_d = vaultD,2624 entryCount = entryCount,2625 )2626 2627 2628 2629 withEpochCommit(epoch) {2630 store.writeVaultHistory(2631 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),2632 )2633 } ?: false2634 } catch (_: Exception) {2635 false2636 }2637 }26382639 private fun bucketEntryCount(n: Int): Int = when {2640 n <= 0 -> 02641 n <= 10 -> 102642 n <= 25 -> 252643 n <= 50 -> 502644 n <= 100 -> 1002645 n <= 250 -> 2502646 n <= 500 -> 5002647 else -> ((n + 499) / 500) * 5002648 }26492650 265126522653265426552656265726582659 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {2660 if (!entry.isCard()) return entry2661 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""2662 val derived = if (digits.length >= 4) digits.takeLast(4) else null2663 return entry.copy(last4 = derived ?: entry.last4)2664 }26652666 266726682669267026712672 private fun autoPurgeExpiredTrash() {2673 val days = _settings.value.trashRetentionDays ?: return2674 if (days <= 0) return2675 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L2676 val before = entryList.size2677 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }2678 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }2679 }26802681 268226832684268526862687 private fun consolidatePasskeyEntries() {2688 val passkeyOnly = entryList.filter { entry ->2689 entry.deletedAt == null &&2690 entry.isLogin() &&2691 entry.password.isNullOrBlank() &&2692 !entry.rpId.isNullOrBlank() &&2693 !entry.credentialId.isNullOrBlank()2694 }2695 if (passkeyOnly.isEmpty()) return2696 var changed = false2697 val now = System.currentTimeMillis()2698 for (pkEntry in passkeyOnly) {2699 val rpId = pkEntry.rpId ?: continue2700 val target = entryList.firstOrNull { candidate ->2701 candidate.deletedAt == null &&2702 candidate.id != pkEntry.id &&2703 candidate.isLogin() &&2704 candidate.passkey == null &&2705 candidate.credentialId.isNullOrBlank() &&2706 !candidate.password.isNullOrBlank() &&2707 listOfNotNull(candidate.url, *candidate.additionalUrls.orEmpty().toTypedArray())2708 .any { com.peachpasswords.shared.extractDomain(it) == rpId }2709 } ?: continue2710 val idx = entryList.indexOfFirst { it.id == target.id }2711 if (idx < 0) continue2712 entryList[idx] = target.copy(2713 rpId = pkEntry.rpId,2714 rpName = pkEntry.rpName ?: target.rpName,2715 credentialId = pkEntry.credentialId,2716 publicKeyCose = pkEntry.publicKeyCose,2717 privateKeyJwk = pkEntry.privateKeyJwk,2718 userHandle = pkEntry.userHandle,2719 userName = pkEntry.userName,2720 userDisplayName = pkEntry.userDisplayName,2721 algorithm = pkEntry.algorithm,2722 signCount = pkEntry.signCount,2723 lastUsedAt = pkEntry.lastUsedAt,2724 modifiedAt = now,2725 )2726 2727 val pkIdx = entryList.indexOfFirst { it.id == pkEntry.id }2728 if (pkIdx >= 0) entryList[pkIdx] = pkEntry.copy(deletedAt = now)2729 changed = true2730 }2731 if (changed) runCatching { persistSlotA(bumpVersion = false) }2732 }27332734 2735 private fun currentPayload(): VaultPayload = mutateState { currentPayloadLocked() }27362737 private fun currentPayloadLocked(): VaultPayload =2738 VaultPayload(2739 entries = entryList.toList(),2740 duressConfigured = duressConfigured,2741 rootKeyB64 = rootKey?.let(::b64) ?: "",2742 recoveryWordHash = recoveryWordHash,2743 recoveryWordsSet = recoveryWordsSet,2744 )27452746 27472748274927502751 private fun ensureRootKey(payload: VaultPayload) {2752 if (payload.rootKeyB64.isNotBlank()) {2753 rootKey = unb64(payload.rootKeyB64)2754 return2755 }2756 rootKey = generateRecoverableRootKey()2757 runCatching { persistSlotA(bumpVersion = false) }2758 }27592760 private fun publish() {2761 _entries.value = entryList.filter { it.deletedAt == null }2762 }27632764 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {2765 var plaintext = VaultCodec.encode(currentPayload())2766 return try {2767 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2768 StoredVault(version = 1, salt = b64(salt), blob = blob)2769 } finally {2770 2771 2772 2773 VaultCrypto.zero(plaintext)2774 }2775 }27762777 private fun writeMatchingNoiseSlotB(slotA: StoredVault): Boolean {2778 2779 2780 2781 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)2782 val noise = ByteArray(approxBytes).also(rng::nextBytes)2783 return store.writeSlotB(b64(noise))2784 }27852786 278727882789 private fun matchingCiphertextLength(slotA: StoredVault): Int =2790 (unb64(slotA.blob).size - VaultCrypto.NONCE_SIZE - 16).coerceAtLeast(0)27912792 27932794279527962797 private fun writeFakeDuressSlot(slotA: StoredVault): Boolean {2798 val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 162799 val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)2800 val fakeSalt = VaultCrypto.generateSalt()2801 return store.writeDecoySlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2802 }28032804 280528062807280828092810 private fun writeCompanionDuressSlot(slotA: StoredVault): Boolean {2811 val isConfigured = mutateState { duressConfigured }2812 return if (isConfigured) true else writeFakeDuressSlot(slotA)2813 }28142815 2816281728182819282028212822 private fun browserDuressPassthrough(b: BrowserSlotA): StoredVault {2823 val salt = unhex(b.salt)2824 val nonce = unhex(b.nonce)2825 val ct = unhex(b.ciphertext)2826 val tag = unhex(b.tag)2827 val blob = ByteArray(nonce.size + ct.size + tag.size).also {2828 System.arraycopy(nonce, 0, it, 0, nonce.size)2829 System.arraycopy(ct, 0, it, nonce.size, ct.size)2830 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)2831 }2832 return StoredVault(version = 1, salt = b64(salt), blob = b64(blob))2833 }28342835 2836 private fun persistSlotA(2837 bumpVersion: Boolean,2838 snapshotReason: String? = "local_save",2839 expectedEpoch: Long? = null,2840 ): Boolean {2841 val snapshot = snapshotForPersist(expectedEpoch)2842 ?: throw IllegalStateException("vault_locked_or_stale")2843 return try {2844 2845 if (snapshot.decoy) {2846 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")2847 val plaintext = VaultCodec.encode(snapshot.payload)2848 val blob = try {2849 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2850 } finally {2851 2852 2853 VaultCrypto.zero(plaintext)2854 }2855 beforeDurableCommit()2856 return withEpochCommit(snapshot.epoch) {2857 store.writeDecoySlot(prior.copy(blob = blob))2858 } ?: false2859 }2860 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")2861 2862 2863 2864 2865 val priorB = store.loadSlotB()2866 beforeDurableCommit()2867 if (snapshotReason != null && !takeVaultSnapshot(snapshotReason, snapshot.epoch)) return false2868 val plaintext = VaultCodec.encode(snapshot.payload)2869 val blob = try {2870 b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2871 } finally {2872 2873 2874 VaultCrypto.zero(plaintext)2875 }2876 val next = prior.copy(blob = blob)2877 2878 2879 2880 2881 withEpochCommit(snapshot.epoch) {2882 if (!store.writeSlotA(next)) return@withEpochCommit false2883 try {2884 if (!writeMatchingNoiseSlotB(next)) throw java.io.IOException("noise_slot_b_commit_failed")2885 2886 2887 if (!writeCompanionDuressSlot(next)) throw java.io.IOException("duress_slot_commit_failed")2888 if (bumpVersion) store.stampLocalMutation()2889 } catch (e: Exception) {2890 store.writeSlotA(prior)2891 if (priorB != null) runCatching { store.writeSlotB(priorB) }2892 throw e2893 }2894 true2895 } ?: false2896 } finally {2897 2898 2899 VaultCrypto.zero(snapshot.key)2900 }2901 }29022903 2904290529062907290829092910 private fun commitVaultRotation(2911 priorA: StoredVault,2912 priorB: String?,2913 nextA: StoredVault,2914 expectedEpoch: Long,2915 ): Boolean {2916 beforeDurableCommit()2917 return withEpochCommit(expectedEpoch) {2918 if (!store.writeSlotA(nextA)) return@withEpochCommit false2919 2920 2921 2922 try {2923 if (!writeMatchingNoiseSlotB(nextA)) throw java.io.IOException("noise_slot_b_commit_failed")2924 2925 2926 2927 2928 if (!writeCompanionDuressSlot(nextA)) throw java.io.IOException("duress_slot_commit_failed")2929 store.stampLocalMutation()2930 } catch (_: Exception) {2931 rollbackRotation(priorA, priorB)2932 return@withEpochCommit false2933 }2934 true2935 } ?: false2936 }29372938 29392940294129422943 private fun rollbackRotation(priorA: StoredVault, priorB: String?) {2944 val failures = mutableListOf<String>()2945 runCatching { if (!store.writeSlotA(priorA)) failures += "writeSlotA returned false" }2946 .onFailure { failures += "writeSlotA: $it" }2947 if (priorB != null) {2948 runCatching { if (!store.writeSlotB(priorB)) failures += "writeSlotB returned false" }2949 .onFailure { failures += "writeSlotB: $it" }2950 }2951 if (failures.isNotEmpty()) runCatching { Log.w("PeachVault", "vault rotation rollback incomplete: $failures") }2952 }29532954 2955 private fun persistOrRollback(rollback: MutableList<VaultEntry>, expectedEpoch: Long) {2956 try {2957 if (!persistSlotA(bumpVersion = true, expectedEpoch = expectedEpoch)) {2958 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }2959 throw IllegalStateException("storage_write_failed")2960 }2961 } catch (e: Exception) {2962 mutateIfCurrentEpoch(expectedEpoch) { entryList = rollback }2963 throw e2964 }2965 2966 2967 2968 mutateIfCurrentEpoch(expectedEpoch) { publish() }2969 runCatching { LockedSyncSpoolHooks.refresh(this) }2970 }2971}