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 = 501920sealed interface UnlockResult {21 data object Success : UnlockResult22 data object WrongPassword : UnlockResult23 data class Error(val reason: String) : UnlockResult24}2526sealed interface CreateVaultResult {27 data object Success : CreateVaultResult28 data class Error(val reason: String) : CreateVaultResult29}303132333435363738394041424344@Singleton45class VaultRepository @Inject constructor(46 private val store: VaultStorage,47) {48 private val mutex = Mutex()49 private val rng = SecureRandom()5051 private var derivedKey: ByteArray? = null52 private var rootKey: ByteArray? = null53 private var entryList: MutableList<VaultEntry> = mutableListOf()54 private var duressConfigured: Boolean = false55 private var recoveryWordHash: String? = null56 private var recoveryWordsSet: Boolean = false57 58 private var decoyMode: Boolean = false5960 private val _isUnlocked = MutableStateFlow(false)61 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6263 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())64 65 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()6667 private val _settings = MutableStateFlow(VaultSettings())68 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()6970 fun hasVault(): Boolean = store.hasVault()7172 7374 7576777879 fun codexVaultBlobBase64(): String? {80 val slotA = store.loadSlotA() ?: return null81 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""82 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))83 }8485 8687888990 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {91 return try {92 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)93 val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)94 ?: return UnlockResult.Error("invalid_codex_blob")95 val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")96 if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")97 writeMatchingNoiseSlotB(slotA)98 store.stampLocalMutation()99 unlockLocked(password)100 } catch (e: Exception) {101 UnlockResult.Error(e.message ?: "restore_failed")102 }103 }104105 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {106 return try {107 val salt = VaultCrypto.generateSalt()108 val key = VaultCrypto.deriveKey(password, salt)109 entryList = mutableListOf()110 duressConfigured = false111 recoveryWordHash = null112 recoveryWordsSet = false113 decoyMode = false114 rootKey = generateRecoverableRootKey()115 val slotA = sealSlotA(key, salt)116 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")117 writeMatchingNoiseSlotB(slotA)118 store.stampLocalMutation()119 store.writeSettings(_settings.value)120 derivedKey = key121 publish()122 _isUnlocked.value = true123 CreateVaultResult.Success124 } catch (e: Exception) {125 CreateVaultResult.Error(e.message ?: "create_failed")126 }127 }128129 suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }130131 132 private fun unlockLocked(password: String): UnlockResult {133 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")134 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))135 val payload = try {136 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))137 } catch (_: Exception) {138 VaultCrypto.zero(key)139 return UnlockResult.WrongPassword140 }141 return adoptSlotA(key, payload)142 }143144 145 private fun adoptSlotA(key: ByteArray, payload: VaultPayload): UnlockResult {146 return try {147 derivedKey = key148 decoyMode = false149 entryList = payload.entries.toMutableList()150 duressConfigured = payload.duressConfigured151 recoveryWordHash = payload.recoveryWordHash152 recoveryWordsSet = payload.recoveryWordsSet153 _settings.value = store.loadSettings()154 ensureRootKey(payload)155 autoPurgeExpiredTrash()156 publish()157 _isUnlocked.value = true158 UnlockResult.Success159 } catch (e: Exception) {160 UnlockResult.Error(e.message ?: "unlock_failed")161 }162 }163164 165166 167168169170171172 class SlotAUnlock internal constructor(173 internal val key: ByteArray,174 internal val payload: VaultPayload,175 )176177 178179180181182183 fun tryUnlockSlotA(password: String): SlotAUnlock? {184 val slotA = store.loadSlotA() ?: return null185 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))186 return try {187 val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))188 SlotAUnlock(key, payload)189 } catch (_: Exception) {190 VaultCrypto.zero(key)191 null192 }193 }194195 196 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {197 adoptSlotA(unlock.key, unlock.payload)198 }199200 201 fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)202203 204205 206207208209210 class DuressUnlock internal constructor(211 internal val key: ByteArray,212 internal val payload: VaultPayload,213 )214215 216217218219220221222 fun tryUnlockDuress(password: String): DuressUnlock? {223 val slot = store.loadDecoySlot() ?: return null224 val key = VaultCrypto.deriveKey(password, unb64(slot.salt))225 return try {226 val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A))227 DuressUnlock(key, payload)228 } catch (_: Exception) {229 VaultCrypto.zero(key)230 null231 }232 }233234 235 suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {236 return try {237 derivedKey = unlock.key238 decoyMode = true239 entryList = unlock.payload.entries.toMutableList()240 duressConfigured = false241 recoveryWordHash = unlock.payload.recoveryWordHash242 recoveryWordsSet = unlock.payload.recoveryWordsSet243 rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)244 else VaultCrypto.generateRootKey()245 _settings.value = store.loadSettings()246 publish()247 _isUnlocked.value = true248 UnlockResult.Success249 } catch (e: Exception) {250 UnlockResult.Error(e.message ?: "decoy_unlock_failed")251 }252 }253254 255 fun discardDuressUnlock(unlock: DuressUnlock) = VaultCrypto.zero(unlock.key)256257 258259260261262263 suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {264 if (derivedKey == null || decoyMode) return false265 266 267 tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }268 return try {269 val salt = VaultCrypto.generateSalt()270 val key = VaultCrypto.deriveKey(duressPassphrase, salt)271 272 val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = b64(VaultCrypto.generateRootKey()))273 val plaintext = VaultCodec.encode(decoyPayload)274 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))275 VaultCrypto.zero(key)276 VaultCrypto.zero(plaintext)277 val ok = store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))278 if (ok) {279 duressConfigured = true280 runCatching { persistSlotA(bumpVersion = false) }281 }282 ok283 } catch (_: Exception) {284 false285 }286 }287288 289 suspend fun clearDuress(): Boolean = mutex.withLock {290 store.clearDecoySlot()291 if (derivedKey != null && !decoyMode) {292 duressConfigured = false293 runCatching { persistSlotA(bumpVersion = false) }294 }295 true296 }297298 299 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {300 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")301 return try {302 val payload = VaultCodec.decode(303 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),304 )305 derivedKey = key.copyOf()306 decoyMode = false307 entryList = payload.entries.toMutableList()308 duressConfigured = payload.duressConfigured309 recoveryWordHash = payload.recoveryWordHash310 recoveryWordsSet = payload.recoveryWordsSet311 _settings.value = store.loadSettings()312 ensureRootKey(payload)313 autoPurgeExpiredTrash()314 publish()315 _isUnlocked.value = true316 UnlockResult.Success317 } catch (_: Exception) {318 UnlockResult.WrongPassword319 }320 }321322 fun lock() {323 derivedKey?.let(VaultCrypto::zero)324 rootKey?.let(VaultCrypto::zero)325 derivedKey = null326 rootKey = null327 entryList = mutableListOf()328 duressConfigured = false329 recoveryWordHash = null330 recoveryWordsSet = false331 decoyMode = false332 _entries.value = emptyList()333 _isUnlocked.value = false334 }335336 337338 339340341342343 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()344345 346 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }347348 349350351352353 fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()354355 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {356 val slotA = store.loadSlotA() ?: return false357 return try {358 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))359 val payload = VaultCodec.decode(360 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),361 )362 val newSalt = VaultCrypto.generateSalt()363 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)364 365 val plaintext = VaultCodec.encode(payload)366 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))367 368 369 370 371 372 373 374 val next = StoredVault(375 version = slotA.version,376 salt = b64(newSalt),377 blob = blob,378 recoveryEscrow = slotA.recoveryEscrow,379 rootKeyEscrow = slotA.rootKeyEscrow,380 )381 if (!store.writeSlotA(next)) return false382 writeMatchingNoiseSlotB(next)383 store.stampLocalMutation()384 VaultCrypto.zero(oldKey)385 derivedKey?.let(VaultCrypto::zero)386 derivedKey = newKey387 true388 } catch (_: Exception) {389 false390 }391 }392393 394395396397 suspend fun destroyVault() = mutex.withLock {398 lock()399 store.clearVault()400 store.clearDecoySlot()401 }402403 404405 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {406 requireUnlocked()407 val stamp = VaultCrypto.monotonicEntryTimestamp()408 val now = System.currentTimeMillis()409 val entry = withDerivedLast4(draft.copy(410 id = draft.id.ifBlank { UUID.randomUUID().toString() },411 createdAt = if (draft.createdAt > 0) draft.createdAt else now,412 modifiedAt = stamp,413 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,414 ))415 val rollback = entryList.toMutableList()416 entryList.add(entry)417 persistOrRollback(rollback)418 entry419 }420421 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {422 requireUnlocked()423 val idx = entryList.indexOfFirst { it.id == patch.id }424 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")425 val current = entryList[idx]426 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)427 428 val passwordChanged = patch.password != null && patch.password != current.password429 430 431 432 433 434 435 val priorPassword = current.password436 val shouldCapture = passwordChanged &&437 !priorPassword.isNullOrEmpty() &&438 current.passwordHistory?.firstOrNull()?.password != priorPassword439 val nextHistory = if (shouldCapture) {440 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +441 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)442 } else {443 current.passwordHistory444 }445 val updated = withDerivedLast4(patch.copy(446 createdAt = current.createdAt,447 modifiedAt = stamp,448 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,449 passwordHistory = nextHistory,450 ))451 val rollback = entryList.toMutableList()452 entryList[idx] = updated453 persistOrRollback(rollback)454 updated455 }456457 458 suspend fun deleteEntry(id: String) = mutex.withLock {459 requireUnlocked()460 val idx = entryList.indexOfFirst { it.id == id }461 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")462 val current = entryList[idx]463 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)464 val rollback = entryList.toMutableList()465 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)466 persistOrRollback(rollback)467 }468469 suspend fun restoreEntry(id: String) = mutex.withLock {470 requireUnlocked()471 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }472 if (idx == -1) throw IllegalStateException("deleted entry not found")473 val current = entryList[idx]474 val rollback = entryList.toMutableList()475 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))476 persistOrRollback(rollback)477 }478479 480 suspend fun purgeEntry(id: String) = mutex.withLock {481 requireUnlocked()482 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }483 if (idx == -1) throw IllegalStateException("deleted entry not found")484 val rollback = entryList.toMutableList()485 entryList.removeAt(idx)486 persistOrRollback(rollback)487 }488489 490 suspend fun purgeDeletedEntries(): Int = mutex.withLock {491 requireUnlocked()492 val rollback = entryList.toMutableList()493 val before = entryList.size494 entryList.removeAll { it.deletedAt != null }495 val removed = before - entryList.size496 if (removed > 0) persistOrRollback(rollback)497 removed498 }499500 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }501 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }502 fun getDeletedEntries(): List<VaultEntry> =503 entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }504505 506 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {507 val active = entryList.filter { it.deletedAt == null }508 if (tagFilter == null) return active509 val needle = tagFilter.trim().lowercase()510 return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }511 }512513 514 fun getDistinctTags(): List<String> =515 entryList.asSequence()516 .filter { it.deletedAt == null }517 .flatMap { it.tags?.asSequence() ?: emptySequence() }518 .map { it.trim().lowercase() }519 .filter { it.isNotEmpty() }520 .distinct()521 .sorted()522 .toList()523524 525526527528529530 fun getDistinctFieldValues(field: String): List<String> {531 val select: (VaultEntry) -> String? = when (field) {532 "username" -> { e -> e.username }533 "email" -> { e -> e.email }534 else -> return emptyList()535 }536 return entryList.asSequence()537 .filter { it.deletedAt == null }538 .mapNotNull { select(it)?.trim() }539 .filter { it.isNotEmpty() }540 .groupingBy { it.lowercase() }541 .aggregate { _, acc: Pair<String, Int>?, value, _ ->542 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)543 }544 .values545 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })546 .map { it.first }547 }548549 fun getTombstones(): List<Tombstone> =550 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }551 fun getVaultVersion(): Long = store.version()552553 554555 556557558559560 suspend fun applyMergedRemoteEntries(561 remoteEntries: List<VaultEntry>,562 remoteTombstones: List<Tombstone>,563 ): Int = mutex.withLock {564 requireUnlocked()565 val tombMap = remoteTombstones.associate { it.id to it.deletedAt }566 var applied = 0567 val byId = entryList.associateBy { it.id }.toMutableMap()568569 for (remote in remoteEntries) {570 val tomb = tombMap[remote.id]571 if (tomb != null && tomb >= remote.modifiedAt) continue572 val local = byId[remote.id]573 if (local == null) {574 entryList.add(remote); byId[remote.id] = remote; applied++575 } else if (remote.modifiedAt > local.modifiedAt) {576 val i = entryList.indexOfFirst { it.id == local.id }577 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }578 }579 }580581 for ((id, deletedAt) in tombMap) {582 val local = byId[id] ?: continue583 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue584 if (deletedAt < local.modifiedAt) continue585 val i = entryList.indexOfFirst { it.id == id }586 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }587 }588589 if (applied > 0) {590 persistSlotA(bumpVersion = false)591 publish()592 }593 applied594 }595596 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {597 _settings.value = settings598 store.writeSettings(settings)599 }600601 602603 604 fun isRecoveryWordsSet(): Boolean = recoveryWordsSet605606 607608609610611 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {612 requireUnlocked()613 recoveryWordHash = recoveryWordsHash(words)614 recoveryWordsSet = true615 616 617 618 619 runCatching {620 persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))621 }.getOrDefault(false)622 }623624 625 fun verifyRecoveryWords(words: List<String>): Boolean {626 val stored = recoveryWordHash ?: return false627 return stored == recoveryWordsHash(words)628 }629630 631632 633 fun hasRecoveryEscrow(): Boolean =634 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false635636 637638639640641642643644645646647648 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {649 val slotA = store.loadSlotA() ?: return false650 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false651652 653 654 slotA.recoveryEscrow?.let { escrow ->655 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let656 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))657 val keyBytes = recoveryKey.encoded658 try {659 val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)660 val payload = VaultCodec.decode(plaintext)661 decoyMode = false662 entryList = payload.entries.toMutableList()663 duressConfigured = payload.duressConfigured664 recoveryWordHash = payload.recoveryWordHash665 recoveryWordsSet = payload.recoveryWordsSet666 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)667 else generateRecoverableRootKey()668 _settings.value = store.loadSettings()669 VaultCrypto.zero(plaintext)670 return true671 } catch (_: Exception) {672 673 } finally {674 VaultCrypto.zero(material)675 VaultCrypto.zero(keyBytes)676 }677 }678679 680 681 682 slotA.rootKeyEscrow?.let { escrow ->683 val rk = unsealRootKeyEscrow(words, escrow) ?: return false684 decoyMode = false685 entryList = mutableListOf()686 duressConfigured = false687 recoveryWordHash = recoveryWordsHash(words)688 recoveryWordsSet = true689 rootKey = rk690 _settings.value = store.loadSettings()691 return true692 }693 return false694 }695696 697698699700701702703704705 suspend fun resetPasswordWithRecoveryWords(706 words: List<String>,707 newPassword: String,708 ): Boolean = mutex.withLock {709 if (rootKey == null) return false 710 return try {711 val newSalt = VaultCrypto.generateSalt()712 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)713 val plaintext = VaultCodec.encode(currentPayload())714 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))715 val prior = store.loadSlotA()716 717 718 719 val valid = words.size == 12 && findInvalidWords(words).isEmpty()720 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow721 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow722 val next = StoredVault(723 version = prior?.version ?: 1,724 salt = b64(newSalt),725 blob = blob,726 recoveryEscrow = freshRecovery,727 rootKeyEscrow = freshRootKey,728 )729 if (!store.writeSlotA(next)) return false730 writeMatchingNoiseSlotB(next)731 store.stampLocalMutation()732 derivedKey?.let(VaultCrypto::zero)733 derivedKey = newKey734 VaultCrypto.zero(plaintext)735 publish()736 _isUnlocked.value = true737 true738 } catch (_: Exception) {739 false740 }741 }742743 744745746747748749 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {750 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null751 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null752 val salt = VaultCrypto.generateSalt()753 val recoveryKey = deriveRecoveryKey(material, salt)754 val keyBytes = recoveryKey.encoded755 val plaintext = VaultCodec.encode(currentPayload())756 return try {757 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)758 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))759 } finally {760 VaultCrypto.zero(material)761 VaultCrypto.zero(keyBytes)762 VaultCrypto.zero(plaintext)763 }764 }765766 767768769770771772773774 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {775 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null776 val rk = rootKey ?: return null777 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null778 val salt = VaultCrypto.generateSalt()779 val recoveryKey = deriveRecoveryKey(material, salt)780 val keyBytes = recoveryKey.encoded781 val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)782 return try {783 784 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)785 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)786 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)787 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)788 val ct = ctTag.copyOfRange(0, ctTag.size - 16)789 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))790 } finally {791 VaultCrypto.zero(material)792 VaultCrypto.zero(keyBytes)793 VaultCrypto.zero(plaintext)794 }795 }796797 798 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {799 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null800 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))801 val keyBytes = recoveryKey.encoded802 return try {803 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)804 val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)805 hexToRootKey(String(pt, Charsets.US_ASCII))806 } catch (_: Exception) {807 null808 } finally {809 VaultCrypto.zero(material)810 VaultCrypto.zero(keyBytes)811 }812 }813814 815816817818819820 private fun persistSlotAWithEscrows(821 recoveryEscrow: RecoveryEscrow?,822 rootKeyEscrow: RootKeyEscrow?,823 ): Boolean {824 val key = derivedKey ?: throw IllegalStateException("vault_locked")825 if (decoyMode) return false826 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")827 val plaintext = VaultCodec.encode(currentPayload())828 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))829 val next = prior.copy(830 blob = blob,831 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,832 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,833 )834 if (!store.writeSlotA(next)) return false835 try {836 writeMatchingNoiseSlotB(next)837 } catch (e: Exception) {838 store.writeSlotA(prior)839 throw e840 }841 return true842 }843844 845846 private fun requireUnlocked() {847 if (derivedKey == null) throw IllegalStateException("vault_locked")848 }849850 851852853854855 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {856 if (!entry.isCard()) return entry857 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""858 return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)859 }860861 862863864865866867 private fun autoPurgeExpiredTrash() {868 val days = _settings.value.trashRetentionDays ?: return869 if (days <= 0) return870 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L871 val before = entryList.size872 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }873 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }874 }875876 877 private fun currentPayload(): VaultPayload =878 VaultPayload(879 entries = entryList.toList(),880 duressConfigured = duressConfigured,881 rootKeyB64 = rootKey?.let(::b64) ?: "",882 recoveryWordHash = recoveryWordHash,883 recoveryWordsSet = recoveryWordsSet,884 )885886 887888889890891 private fun ensureRootKey(payload: VaultPayload) {892 if (payload.rootKeyB64.isNotBlank()) {893 rootKey = unb64(payload.rootKeyB64)894 return895 }896 rootKey = generateRecoverableRootKey()897 runCatching { persistSlotA(bumpVersion = false) }898 }899900 private fun publish() {901 _entries.value = entryList.filter { it.deletedAt == null }902 }903904 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {905 val plaintext = VaultCodec.encode(currentPayload())906 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))907 return StoredVault(version = 1, salt = b64(salt), blob = blob)908 }909910 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {911 val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)912 val noise = ByteArray(approxBytes).also(rng::nextBytes)913 store.writeSlotB(b64(noise))914 }915916 917 private fun persistSlotA(bumpVersion: Boolean): Boolean {918 val key = derivedKey ?: throw IllegalStateException("vault_locked")919 920 if (decoyMode) {921 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")922 val plaintext = VaultCodec.encode(currentPayload())923 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))924 return store.writeDecoySlot(prior.copy(blob = blob))925 }926 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")927 val plaintext = VaultCodec.encode(currentPayload())928 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))929 val next = prior.copy(blob = blob)930 if (!store.writeSlotA(next)) return false931 932 933 try {934 writeMatchingNoiseSlotB(next)935 if (bumpVersion) store.stampLocalMutation()936 } catch (e: Exception) {937 store.writeSlotA(prior)938 throw e939 }940 return true941 }942943 944 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {945 try {946 if (!persistSlotA(bumpVersion = true)) {947 entryList = rollback948 throw IllegalStateException("storage_write_failed")949 }950 } catch (e: Exception) {951 entryList = rollback952 throw e953 }954 publish()955 }956}