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.SecureRandom9import java.util.Base6410import java.util.UUID11import javax.inject.Inject12import javax.inject.Singleton1314private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)15private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)161718private const val PASSWORD_HISTORY_MAX = 50192021private const val DECOY_SENTINEL = "peach_decoy_v1"2223sealed interface UnlockResult {24 data object Success : UnlockResult25 data object WrongPassword : UnlockResult26 data class Error(val reason: String) : UnlockResult27}2829sealed interface CreateVaultResult {30 data object Success : CreateVaultResult31 data class Error(val reason: String) : CreateVaultResult32}333435363738394041424344454647@Singleton48class VaultRepository @Inject constructor(49 private val store: VaultStorage,50) {51 private val mutex = Mutex()52 private val rng = SecureRandom()5354 private var derivedKey: ByteArray? = null55 private var rootKey: ByteArray? = null56 private var entryList: MutableList<VaultEntry> = mutableListOf()57 private var duressConfigured: Boolean = false58 private var recoveryWordHash: String? = null59 private var recoveryWordsSet: Boolean = false60 61 private var decoyMode: Boolean = false6263 private val _isUnlocked = MutableStateFlow(false)64 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6566 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())67 68 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()6970 private val _settings = MutableStateFlow(VaultSettings())71 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()7273 fun hasVault(): Boolean = store.hasVault()7475 7677 7879808182 fun codexVaultBlobBase64(): String? {83 val slotA = store.loadSlotA() ?: return null84 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""85 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))86 }8788 8990919293 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {94 return try {95 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)96 val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)97 ?: return UnlockResult.Error("invalid_codex_blob")98 val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")99 if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")100 writeMatchingNoiseSlotB(slotA)101 store.stampLocalMutation()102 unlockLocked(password)103 } catch (e: Exception) {104 UnlockResult.Error(e.message ?: "restore_failed")105 }106 }107108 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {109 return try {110 val salt = VaultCrypto.generateSalt()111 val key = VaultCrypto.deriveKey(password, salt)112 entryList = mutableListOf()113 duressConfigured = false114 recoveryWordHash = null115 recoveryWordsSet = false116 decoyMode = false117 rootKey = generateRecoverableRootKey()118 val slotA = sealSlotA(key, salt)119 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")120 writeMatchingNoiseSlotB(slotA)121 store.stampLocalMutation()122 store.writeSettings(_settings.value)123 derivedKey = key124 publish()125 _isUnlocked.value = true126 CreateVaultResult.Success127 } catch (e: Exception) {128 CreateVaultResult.Error(e.message ?: "create_failed")129 }130 }131132 suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }133134 135 private fun unlockLocked(password: String): UnlockResult {136 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")137 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))138 val payload = try {139 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))140 } catch (_: Exception) {141 VaultCrypto.zero(key)142 return UnlockResult.WrongPassword143 }144 return adoptSlotA(key, payload)145 }146147 148 private fun adoptSlotA(key: ByteArray, payload: VaultPayload): UnlockResult {149 return try {150 derivedKey = key151 decoyMode = false152 entryList = payload.entries.toMutableList()153 duressConfigured = payload.duressConfigured154 recoveryWordHash = payload.recoveryWordHash155 recoveryWordsSet = payload.recoveryWordsSet156 _settings.value = store.loadSettings()157 ensureRootKey(payload)158 autoPurgeExpiredTrash()159 publish()160 _isUnlocked.value = true161 UnlockResult.Success162 } catch (e: Exception) {163 UnlockResult.Error(e.message ?: "unlock_failed")164 }165 }166167 168169 170171172173174175 class SlotAUnlock internal constructor(176 internal val key: ByteArray,177 internal val payload: VaultPayload,178 )179180 181182183184185186 fun tryUnlockSlotA(password: String): SlotAUnlock? {187 val slotA = store.loadSlotA() ?: return null188 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))189 return try {190 val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))191 SlotAUnlock(key, payload)192 } catch (_: Exception) {193 VaultCrypto.zero(key)194 null195 }196 }197198 199 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {200 adoptSlotA(unlock.key, unlock.payload)201 }202203 204 fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)205206 207208209210211212 suspend fun unlockDecoy(): UnlockResult = mutex.withLock {213 return try {214 val existing = store.loadDecoySlot()215 if (existing == null) {216 val salt = VaultCrypto.generateSalt()217 val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)218 entryList = mutableListOf()219 duressConfigured = false220 recoveryWordHash = null221 recoveryWordsSet = false222 rootKey = VaultCrypto.generateRootKey()223 derivedKey = key224 decoyMode = true225 val plaintext = VaultCodec.encode(currentPayload())226 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))227 if (!store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob)))228 return UnlockResult.Error("storage_write_failed")229 } else {230 val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))231 val payload = VaultCodec.decode(232 VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),233 )234 derivedKey = key235 decoyMode = true236 entryList = payload.entries.toMutableList()237 duressConfigured = false238 recoveryWordHash = payload.recoveryWordHash239 recoveryWordsSet = payload.recoveryWordsSet240 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)241 else VaultCrypto.generateRootKey()242 }243 _settings.value = store.loadSettings()244 publish()245 _isUnlocked.value = true246 UnlockResult.Success247 } catch (e: Exception) {248 UnlockResult.Error(e.message ?: "decoy_unlock_failed")249 }250 }251252 253 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {254 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")255 return try {256 val payload = VaultCodec.decode(257 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),258 )259 derivedKey = key.copyOf()260 decoyMode = false261 entryList = payload.entries.toMutableList()262 duressConfigured = payload.duressConfigured263 recoveryWordHash = payload.recoveryWordHash264 recoveryWordsSet = payload.recoveryWordsSet265 _settings.value = store.loadSettings()266 ensureRootKey(payload)267 autoPurgeExpiredTrash()268 publish()269 _isUnlocked.value = true270 UnlockResult.Success271 } catch (_: Exception) {272 UnlockResult.WrongPassword273 }274 }275276 fun lock() {277 derivedKey?.let(VaultCrypto::zero)278 rootKey?.let(VaultCrypto::zero)279 derivedKey = null280 rootKey = null281 entryList = mutableListOf()282 duressConfigured = false283 recoveryWordHash = null284 recoveryWordsSet = false285 decoyMode = false286 _entries.value = emptyList()287 _isUnlocked.value = false288 }289290 291292 293294295296297 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()298299 300 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }301302 303304305306307 fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()308309 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {310 val slotA = store.loadSlotA() ?: return false311 return try {312 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))313 val payload = VaultCodec.decode(314 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),315 )316 val newSalt = VaultCrypto.generateSalt()317 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)318 319 val plaintext = VaultCodec.encode(payload)320 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))321 322 323 324 325 326 327 328 val next = StoredVault(329 version = slotA.version,330 salt = b64(newSalt),331 blob = blob,332 recoveryEscrow = slotA.recoveryEscrow,333 rootKeyEscrow = slotA.rootKeyEscrow,334 )335 if (!store.writeSlotA(next)) return false336 writeMatchingNoiseSlotB(next)337 store.stampLocalMutation()338 VaultCrypto.zero(oldKey)339 derivedKey?.let(VaultCrypto::zero)340 derivedKey = newKey341 true342 } catch (_: Exception) {343 false344 }345 }346347 348349350351 suspend fun destroyVault() = mutex.withLock {352 lock()353 store.clearVault()354 store.clearDecoySlot()355 }356357 358359 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {360 requireUnlocked()361 val stamp = VaultCrypto.monotonicEntryTimestamp()362 val now = System.currentTimeMillis()363 val entry = withDerivedLast4(draft.copy(364 id = draft.id.ifBlank { UUID.randomUUID().toString() },365 createdAt = if (draft.createdAt > 0) draft.createdAt else now,366 modifiedAt = stamp,367 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,368 ))369 val rollback = entryList.toMutableList()370 entryList.add(entry)371 persistOrRollback(rollback)372 entry373 }374375 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {376 requireUnlocked()377 val idx = entryList.indexOfFirst { it.id == patch.id }378 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")379 val current = entryList[idx]380 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)381 382 val passwordChanged = patch.password != null && patch.password != current.password383 384 385 386 387 388 389 val priorPassword = current.password390 val shouldCapture = passwordChanged &&391 !priorPassword.isNullOrEmpty() &&392 current.passwordHistory?.firstOrNull()?.password != priorPassword393 val nextHistory = if (shouldCapture) {394 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +395 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)396 } else {397 current.passwordHistory398 }399 val updated = withDerivedLast4(patch.copy(400 createdAt = current.createdAt,401 modifiedAt = stamp,402 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,403 passwordHistory = nextHistory,404 ))405 val rollback = entryList.toMutableList()406 entryList[idx] = updated407 persistOrRollback(rollback)408 updated409 }410411 412 suspend fun deleteEntry(id: String) = mutex.withLock {413 requireUnlocked()414 val idx = entryList.indexOfFirst { it.id == id }415 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")416 val current = entryList[idx]417 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)418 val rollback = entryList.toMutableList()419 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)420 persistOrRollback(rollback)421 }422423 suspend fun restoreEntry(id: String) = mutex.withLock {424 requireUnlocked()425 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }426 if (idx == -1) throw IllegalStateException("deleted entry not found")427 val current = entryList[idx]428 val rollback = entryList.toMutableList()429 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))430 persistOrRollback(rollback)431 }432433 434 suspend fun purgeEntry(id: String) = mutex.withLock {435 requireUnlocked()436 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }437 if (idx == -1) throw IllegalStateException("deleted entry not found")438 val rollback = entryList.toMutableList()439 entryList.removeAt(idx)440 persistOrRollback(rollback)441 }442443 444 suspend fun purgeDeletedEntries(): Int = mutex.withLock {445 requireUnlocked()446 val rollback = entryList.toMutableList()447 val before = entryList.size448 entryList.removeAll { it.deletedAt != null }449 val removed = before - entryList.size450 if (removed > 0) persistOrRollback(rollback)451 removed452 }453454 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }455 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }456 fun getDeletedEntries(): List<VaultEntry> =457 entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }458459 460 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {461 val active = entryList.filter { it.deletedAt == null }462 if (tagFilter == null) return active463 val needle = tagFilter.trim().lowercase()464 return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }465 }466467 468 fun getDistinctTags(): List<String> =469 entryList.asSequence()470 .filter { it.deletedAt == null }471 .flatMap { it.tags?.asSequence() ?: emptySequence() }472 .map { it.trim().lowercase() }473 .filter { it.isNotEmpty() }474 .distinct()475 .sorted()476 .toList()477478 479480481482483484 fun getDistinctFieldValues(field: String): List<String> {485 val select: (VaultEntry) -> String? = when (field) {486 "username" -> { e -> e.username }487 "email" -> { e -> e.email }488 else -> return emptyList()489 }490 return entryList.asSequence()491 .filter { it.deletedAt == null }492 .mapNotNull { select(it)?.trim() }493 .filter { it.isNotEmpty() }494 .groupingBy { it.lowercase() }495 .aggregate { _, acc: Pair<String, Int>?, value, _ ->496 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)497 }498 .values499 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })500 .map { it.first }501 }502503 fun getTombstones(): List<Tombstone> =504 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }505 fun getVaultVersion(): Long = store.version()506507 508509 510511512513514 suspend fun applyMergedRemoteEntries(515 remoteEntries: List<VaultEntry>,516 remoteTombstones: List<Tombstone>,517 ): Int = mutex.withLock {518 requireUnlocked()519 val tombMap = remoteTombstones.associate { it.id to it.deletedAt }520 var applied = 0521 val byId = entryList.associateBy { it.id }.toMutableMap()522523 for (remote in remoteEntries) {524 val tomb = tombMap[remote.id]525 if (tomb != null && tomb >= remote.modifiedAt) continue526 val local = byId[remote.id]527 if (local == null) {528 entryList.add(remote); byId[remote.id] = remote; applied++529 } else if (remote.modifiedAt > local.modifiedAt) {530 val i = entryList.indexOfFirst { it.id == local.id }531 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }532 }533 }534535 for ((id, deletedAt) in tombMap) {536 val local = byId[id] ?: continue537 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue538 if (deletedAt < local.modifiedAt) continue539 val i = entryList.indexOfFirst { it.id == id }540 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }541 }542543 if (applied > 0) {544 persistSlotA(bumpVersion = false)545 publish()546 }547 applied548 }549550 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {551 _settings.value = settings552 store.writeSettings(settings)553 }554555 556557 558 fun isRecoveryWordsSet(): Boolean = recoveryWordsSet559560 561562563564565 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {566 requireUnlocked()567 recoveryWordHash = recoveryWordsHash(words)568 recoveryWordsSet = true569 570 571 572 573 runCatching {574 persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))575 }.getOrDefault(false)576 }577578 579 fun verifyRecoveryWords(words: List<String>): Boolean {580 val stored = recoveryWordHash ?: return false581 return stored == recoveryWordsHash(words)582 }583584 585586 587 fun hasRecoveryEscrow(): Boolean =588 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false589590 591592593594595596597598599600601602 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {603 val slotA = store.loadSlotA() ?: return false604 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false605606 607 608 slotA.recoveryEscrow?.let { escrow ->609 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let610 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))611 val keyBytes = recoveryKey.encoded612 try {613 val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)614 val payload = VaultCodec.decode(plaintext)615 decoyMode = false616 entryList = payload.entries.toMutableList()617 duressConfigured = payload.duressConfigured618 recoveryWordHash = payload.recoveryWordHash619 recoveryWordsSet = payload.recoveryWordsSet620 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)621 else generateRecoverableRootKey()622 _settings.value = store.loadSettings()623 VaultCrypto.zero(plaintext)624 return true625 } catch (_: Exception) {626 627 } finally {628 VaultCrypto.zero(material)629 VaultCrypto.zero(keyBytes)630 }631 }632633 634 635 636 slotA.rootKeyEscrow?.let { escrow ->637 val rk = unsealRootKeyEscrow(words, escrow) ?: return false638 decoyMode = false639 entryList = mutableListOf()640 duressConfigured = false641 recoveryWordHash = recoveryWordsHash(words)642 recoveryWordsSet = true643 rootKey = rk644 _settings.value = store.loadSettings()645 return true646 }647 return false648 }649650 651652653654655656657658659 suspend fun resetPasswordWithRecoveryWords(660 words: List<String>,661 newPassword: String,662 ): Boolean = mutex.withLock {663 if (rootKey == null) return false 664 return try {665 val newSalt = VaultCrypto.generateSalt()666 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)667 val plaintext = VaultCodec.encode(currentPayload())668 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))669 val prior = store.loadSlotA()670 671 672 673 val valid = words.size == 12 && findInvalidWords(words).isEmpty()674 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow675 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow676 val next = StoredVault(677 version = prior?.version ?: 1,678 salt = b64(newSalt),679 blob = blob,680 recoveryEscrow = freshRecovery,681 rootKeyEscrow = freshRootKey,682 )683 if (!store.writeSlotA(next)) return false684 writeMatchingNoiseSlotB(next)685 store.stampLocalMutation()686 derivedKey?.let(VaultCrypto::zero)687 derivedKey = newKey688 VaultCrypto.zero(plaintext)689 publish()690 _isUnlocked.value = true691 true692 } catch (_: Exception) {693 false694 }695 }696697 698699700701702703 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {704 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null705 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null706 val salt = VaultCrypto.generateSalt()707 val recoveryKey = deriveRecoveryKey(material, salt)708 val keyBytes = recoveryKey.encoded709 val plaintext = VaultCodec.encode(currentPayload())710 return try {711 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)712 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))713 } finally {714 VaultCrypto.zero(material)715 VaultCrypto.zero(keyBytes)716 VaultCrypto.zero(plaintext)717 }718 }719720 721722723724725726727728 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {729 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null730 val rk = rootKey ?: return null731 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null732 val salt = VaultCrypto.generateSalt()733 val recoveryKey = deriveRecoveryKey(material, salt)734 val keyBytes = recoveryKey.encoded735 val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)736 return try {737 738 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)739 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)740 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)741 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)742 val ct = ctTag.copyOfRange(0, ctTag.size - 16)743 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))744 } finally {745 VaultCrypto.zero(material)746 VaultCrypto.zero(keyBytes)747 VaultCrypto.zero(plaintext)748 }749 }750751 752 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {753 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null754 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))755 val keyBytes = recoveryKey.encoded756 return try {757 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)758 val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)759 hexToRootKey(String(pt, Charsets.US_ASCII))760 } catch (_: Exception) {761 null762 } finally {763 VaultCrypto.zero(material)764 VaultCrypto.zero(keyBytes)765 }766 }767768 769770771772773774 private fun persistSlotAWithEscrows(775 recoveryEscrow: RecoveryEscrow?,776 rootKeyEscrow: RootKeyEscrow?,777 ): Boolean {778 val key = derivedKey ?: throw IllegalStateException("vault_locked")779 if (decoyMode) return false780 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")781 val plaintext = VaultCodec.encode(currentPayload())782 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))783 val next = prior.copy(784 blob = blob,785 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,786 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,787 )788 if (!store.writeSlotA(next)) return false789 try {790 writeMatchingNoiseSlotB(next)791 } catch (e: Exception) {792 store.writeSlotA(prior)793 throw e794 }795 return true796 }797798 799800 private fun requireUnlocked() {801 if (derivedKey == null) throw IllegalStateException("vault_locked")802 }803804 805806807808809 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {810 if (!entry.isCard()) return entry811 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""812 return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)813 }814815 816817818819820821 private fun autoPurgeExpiredTrash() {822 val days = _settings.value.trashRetentionDays ?: return823 if (days <= 0) return824 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L825 val before = entryList.size826 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }827 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }828 }829830 831 private fun currentPayload(): VaultPayload =832 VaultPayload(833 entries = entryList.toList(),834 duressConfigured = duressConfigured,835 rootKeyB64 = rootKey?.let(::b64) ?: "",836 recoveryWordHash = recoveryWordHash,837 recoveryWordsSet = recoveryWordsSet,838 )839840 841842843844845 private fun ensureRootKey(payload: VaultPayload) {846 if (payload.rootKeyB64.isNotBlank()) {847 rootKey = unb64(payload.rootKeyB64)848 return849 }850 rootKey = generateRecoverableRootKey()851 runCatching { persistSlotA(bumpVersion = false) }852 }853854 private fun publish() {855 _entries.value = entryList.filter { it.deletedAt == null }856 }857858 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {859 val plaintext = VaultCodec.encode(currentPayload())860 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))861 return StoredVault(version = 1, salt = b64(salt), blob = blob)862 }863864 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {865 val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)866 val noise = ByteArray(approxBytes).also(rng::nextBytes)867 store.writeSlotB(b64(noise))868 }869870 871 private fun persistSlotA(bumpVersion: Boolean): Boolean {872 val key = derivedKey ?: throw IllegalStateException("vault_locked")873 874 if (decoyMode) {875 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")876 val plaintext = VaultCodec.encode(currentPayload())877 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))878 return store.writeDecoySlot(prior.copy(blob = blob))879 }880 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")881 val plaintext = VaultCodec.encode(currentPayload())882 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))883 val next = prior.copy(blob = blob)884 if (!store.writeSlotA(next)) return false885 886 887 try {888 writeMatchingNoiseSlotB(next)889 if (bumpVersion) store.stampLocalMutation()890 } catch (e: Exception) {891 store.writeSlotA(prior)892 throw e893 }894 return true895 }896897 898 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {899 try {900 if (!persistSlotA(bumpVersion = true)) {901 entryList = rollback902 throw IllegalStateException("storage_write_failed")903 }904 } catch (e: Exception) {905 entryList = rollback906 throw e907 }908 publish()909 }910}