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.text.Normalizer10import java.util.Base6411import java.util.UUID12import javax.inject.Inject13import javax.inject.Singleton1415private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)16private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)171819private const val PASSWORD_HISTORY_MAX = 5020private const val VAULT_HISTORY_MAX = 52122sealed interface UnlockResult {23 data object Success : UnlockResult24 data object WrongPassword : UnlockResult25 data class Error(val reason: String) : UnlockResult26}2728sealed interface CreateVaultResult {29 data object Success : CreateVaultResult30 data class Error(val reason: String) : CreateVaultResult31}323334353637383940414243444546@Singleton47class VaultRepository @Inject constructor(48 private val store: VaultStorage,49) {50 private val mutex = Mutex()51 private val rng = SecureRandom()5253 private var derivedKey: ByteArray? = null54 private var rootKey: ByteArray? = null55 private var entryList: MutableList<VaultEntry> = mutableListOf()56 private var duressConfigured: Boolean = false57 private var recoveryWordHash: String? = null58 private var recoveryWordsSet: Boolean = false59 60 private var decoyMode: Boolean = false6162 private val _isUnlocked = MutableStateFlow(false)63 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6465 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())66 67 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()6869 private val _settings = MutableStateFlow(VaultSettings())70 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()7172 fun hasVault(): Boolean = store.hasVault()7374 7576 7778798081 fun codexVaultBlobBase64(): String? {82 val slotA = store.loadSlotA() ?: return null83 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""84 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))85 }8687 8889909192 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {93 return try {94 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)95 val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)96 ?: return UnlockResult.Error("invalid_codex_blob")97 val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")98 if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")99 writeMatchingNoiseSlotB(slotA)100 store.stampLocalMutation()101 unlockLocked(password)102 } catch (e: Exception) {103 UnlockResult.Error(e.message ?: "restore_failed")104 }105 }106107 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {108 return try {109 val salt = VaultCrypto.generateSalt()110 val key = VaultCrypto.deriveKey(password, salt)111 entryList = mutableListOf()112 duressConfigured = false113 recoveryWordHash = null114 recoveryWordsSet = false115 decoyMode = false116 rootKey = generateRecoverableRootKey()117 val slotA = sealSlotA(key, salt)118 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")119 writeMatchingNoiseSlotB(slotA)120 store.stampLocalMutation()121 store.writeSettings(_settings.value)122 derivedKey = key123 publish()124 _isUnlocked.value = true125 CreateVaultResult.Success126 } catch (e: Exception) {127 CreateVaultResult.Error(e.message ?: "create_failed")128 }129 }130131 suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }132133 134 private fun unlockLocked(password: String): UnlockResult {135 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")136 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))137 val payload = try {138 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))139 } catch (_: Exception) {140 VaultCrypto.zero(key)141 142 143 144 if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {145 val legacy = tryLegacyRawUnlock(password, slotA)146 if (legacy != null) return legacy147 }148 return UnlockResult.WrongPassword149 }150 return adoptSlotA(key, payload)151 }152153 154155156157158159 private fun tryLegacyRawUnlock(password: String, slotA: StoredVault): UnlockResult? {160 val rawKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))161 val payload = try {162 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), rawKey, VaultCrypto.AAD_SLOT_A))163 } catch (_: Exception) {164 VaultCrypto.zero(rawKey)165 return null166 }167 168 169 val newSalt = VaultCrypto.generateSalt()170 val newKey = VaultCrypto.deriveKey(password, newSalt)171 val healed = try {172 val blob = b64(VaultCrypto.encrypt(VaultCodec.encode(payload), newKey, VaultCrypto.AAD_SLOT_A))173 val next = StoredVault(174 version = slotA.version,175 salt = b64(newSalt),176 blob = blob,177 recoveryEscrow = slotA.recoveryEscrow,178 rootKeyEscrow = slotA.rootKeyEscrow,179 )180 if (store.writeSlotA(next)) {181 writeMatchingNoiseSlotB(next)182 store.stampLocalMutation()183 true184 } else {185 false186 }187 } catch (_: Exception) {188 false189 }190 return if (healed) {191 VaultCrypto.zero(rawKey)192 adoptSlotA(newKey, payload) 193 } else {194 VaultCrypto.zero(newKey)195 adoptSlotA(rawKey, payload) 196 }197 }198199 200 private fun adoptSlotA(key: ByteArray, payload: VaultPayload): UnlockResult {201 return try {202 derivedKey = key203 decoyMode = false204 entryList = payload.entries.toMutableList()205 duressConfigured = payload.duressConfigured206 recoveryWordHash = payload.recoveryWordHash207 recoveryWordsSet = payload.recoveryWordsSet208 _settings.value = store.loadSettings()209 ensureRootKey(payload)210 autoPurgeExpiredTrash()211 publish()212 _isUnlocked.value = true213 UnlockResult.Success214 } catch (e: Exception) {215 UnlockResult.Error(e.message ?: "unlock_failed")216 }217 }218219 220221 222223224225226227 class SlotAUnlock internal constructor(228 internal val key: ByteArray,229 internal val payload: VaultPayload,230 )231232 233234235236237238 fun tryUnlockSlotA(password: String): SlotAUnlock? {239 val slotA = store.loadSlotA() ?: return null240 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))241 return try {242 val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))243 SlotAUnlock(key, payload)244 } catch (_: Exception) {245 VaultCrypto.zero(key)246 null247 }248 }249250 251 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {252 adoptSlotA(unlock.key, unlock.payload)253 }254255 256 fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)257258 259260 261262263264265 class DuressUnlock internal constructor(266 internal val key: ByteArray,267 internal val payload: VaultPayload,268 )269270 271272273274275276277 fun tryUnlockDuress(password: String): DuressUnlock? {278 val slot = store.loadDecoySlot() ?: return null279 val key = VaultCrypto.deriveKey(password, unb64(slot.salt))280 return try {281 val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A))282 DuressUnlock(key, payload)283 } catch (_: Exception) {284 VaultCrypto.zero(key)285 null286 }287 }288289 290 suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {291 return try {292 derivedKey = unlock.key293 decoyMode = true294 entryList = unlock.payload.entries.toMutableList()295 duressConfigured = false296 recoveryWordHash = unlock.payload.recoveryWordHash297 recoveryWordsSet = unlock.payload.recoveryWordsSet298 rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)299 else VaultCrypto.generateRootKey()300 _settings.value = store.loadSettings()301 publish()302 _isUnlocked.value = true303 UnlockResult.Success304 } catch (e: Exception) {305 UnlockResult.Error(e.message ?: "decoy_unlock_failed")306 }307 }308309 310 fun discardDuressUnlock(unlock: DuressUnlock) = VaultCrypto.zero(unlock.key)311312 313314315316317318 suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {319 if (derivedKey == null || decoyMode) return false320 321 322 tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }323 return try {324 val salt = VaultCrypto.generateSalt()325 val key = VaultCrypto.deriveKey(duressPassphrase, salt)326 327 val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = b64(VaultCrypto.generateRootKey()))328 val plaintext = VaultCodec.encode(decoyPayload)329 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))330 VaultCrypto.zero(key)331 VaultCrypto.zero(plaintext)332 val ok = store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))333 if (ok) {334 duressConfigured = true335 runCatching { persistSlotA(bumpVersion = false) }336 }337 ok338 } catch (_: Exception) {339 false340 }341 }342343 344 suspend fun clearDuress(): Boolean = mutex.withLock {345 store.clearDecoySlot()346 if (derivedKey != null && !decoyMode) {347 duressConfigured = false348 runCatching { persistSlotA(bumpVersion = false) }349 }350 true351 }352353 354 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {355 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")356 return try {357 val payload = VaultCodec.decode(358 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),359 )360 derivedKey = key.copyOf()361 decoyMode = false362 entryList = payload.entries.toMutableList()363 duressConfigured = payload.duressConfigured364 recoveryWordHash = payload.recoveryWordHash365 recoveryWordsSet = payload.recoveryWordsSet366 _settings.value = store.loadSettings()367 ensureRootKey(payload)368 autoPurgeExpiredTrash()369 publish()370 _isUnlocked.value = true371 UnlockResult.Success372 } catch (_: Exception) {373 UnlockResult.WrongPassword374 }375 }376377 fun lock() {378 derivedKey?.let(VaultCrypto::zero)379 rootKey?.let(VaultCrypto::zero)380 derivedKey = null381 rootKey = null382 entryList = mutableListOf()383 duressConfigured = false384 recoveryWordHash = null385 recoveryWordsSet = false386 decoyMode = false387 _entries.value = emptyList()388 _isUnlocked.value = false389 }390391 392393 394395396397398 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()399400 401 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }402403 404405406407408 fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()409410 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {411 val slotA = store.loadSlotA() ?: return false412 return try {413 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))414 val payload = VaultCodec.decode(415 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),416 )417 val newSalt = VaultCrypto.generateSalt()418 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)419 420 val plaintext = VaultCodec.encode(payload)421 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))422 423 424 425 426 427 428 429 val next = StoredVault(430 version = slotA.version,431 salt = b64(newSalt),432 blob = blob,433 recoveryEscrow = slotA.recoveryEscrow,434 rootKeyEscrow = slotA.rootKeyEscrow,435 )436 if (!store.writeSlotA(next)) return false437 writeMatchingNoiseSlotB(next)438 store.stampLocalMutation()439 VaultCrypto.zero(oldKey)440 derivedKey?.let(VaultCrypto::zero)441 derivedKey = newKey442 true443 } catch (_: Exception) {444 false445 }446 }447448 449450451452 suspend fun destroyVault() = mutex.withLock {453 lock()454 store.clearVault()455 store.clearDecoySlot()456 }457458 459460 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {461 requireUnlocked()462 val stamp = VaultCrypto.monotonicEntryTimestamp()463 val now = System.currentTimeMillis()464 val entry = withDerivedLast4(draft.copy(465 id = draft.id.ifBlank { UUID.randomUUID().toString() },466 createdAt = if (draft.createdAt > 0) draft.createdAt else now,467 modifiedAt = stamp,468 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,469 ))470 val rollback = entryList.toMutableList()471 entryList.add(entry)472 persistOrRollback(rollback)473 entry474 }475476 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {477 requireUnlocked()478 val idx = entryList.indexOfFirst { it.id == patch.id }479 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")480 val current = entryList[idx]481 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)482 483 val passwordChanged = patch.password != null && patch.password != current.password484 485 486 487 488 489 490 val priorPassword = current.password491 val shouldCapture = passwordChanged &&492 !priorPassword.isNullOrEmpty() &&493 current.passwordHistory?.firstOrNull()?.password != priorPassword494 val nextHistory = if (shouldCapture) {495 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +496 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)497 } else {498 current.passwordHistory499 }500 val updated = withDerivedLast4(patch.copy(501 createdAt = current.createdAt,502 modifiedAt = stamp,503 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,504 passwordHistory = nextHistory,505 ))506 val rollback = entryList.toMutableList()507 entryList[idx] = updated508 persistOrRollback(rollback)509 updated510 }511512 513 suspend fun deleteEntry(id: String) = mutex.withLock {514 requireUnlocked()515 val idx = entryList.indexOfFirst { it.id == id }516 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")517 val current = entryList[idx]518 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)519 val rollback = entryList.toMutableList()520 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)521 persistOrRollback(rollback)522 }523524 suspend fun restoreEntry(id: String) = mutex.withLock {525 requireUnlocked()526 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }527 if (idx == -1) throw IllegalStateException("deleted entry not found")528 val current = entryList[idx]529 val rollback = entryList.toMutableList()530 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))531 persistOrRollback(rollback)532 }533534 535 suspend fun purgeEntry(id: String) = mutex.withLock {536 requireUnlocked()537 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }538 if (idx == -1) throw IllegalStateException("deleted entry not found")539 val rollback = entryList.toMutableList()540 entryList.removeAt(idx)541 persistOrRollback(rollback)542 }543544 545 suspend fun purgeDeletedEntries(): Int = mutex.withLock {546 requireUnlocked()547 val rollback = entryList.toMutableList()548 val before = entryList.size549 entryList.removeAll { it.deletedAt != null }550 val removed = before - entryList.size551 if (removed > 0) persistOrRollback(rollback)552 removed553 }554555 556 suspend fun countDuplicateEntries(): Int = mutex.withLock {557 requireUnlocked()558 countDuplicateEntriesLocked()559 }560561 562563564565566 suspend fun deduplicateEntries(): Int = mutex.withLock {567 requireUnlocked()568 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")569 val active = entryList.filter { it.deletedAt == null }570 val keepIds = mutableSetOf<String>()571 active.groupBy { it.duplicateKey() }.values.forEach { group ->572 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id573 }574575 val rollback = entryList.toMutableList()576 var removed = 0577 entryList = entryList.map { entry ->578 if (entry.deletedAt == null && entry.id !in keepIds) {579 removed++580 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)581 entry.copy(deletedAt = stamp, modifiedAt = stamp)582 } else {583 entry584 }585 }.toMutableList()586 if (removed > 0) persistOrRollback(rollback)587 removed588 }589590 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }591 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }592 fun getDeletedEntries(): List<VaultEntry> =593 entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }594595 596 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {597 val active = entryList.filter { it.deletedAt == null }598 if (tagFilter == null) return active599 val needle = tagFilter.trim().lowercase()600 return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }601 }602603 604 fun getDistinctTags(): List<String> =605 entryList.asSequence()606 .filter { it.deletedAt == null }607 .flatMap { it.tags?.asSequence() ?: emptySequence() }608 .map { it.trim().lowercase() }609 .filter { it.isNotEmpty() }610 .distinct()611 .sorted()612 .toList()613614 615616617618619620 fun getDistinctFieldValues(field: String): List<String> {621 val select: (VaultEntry) -> String? = when (field) {622 "username" -> { e -> e.username }623 "email" -> { e -> e.email }624 else -> return emptyList()625 }626 return entryList.asSequence()627 .filter { it.deletedAt == null }628 .mapNotNull { select(it)?.trim() }629 .filter { it.isNotEmpty() }630 .groupingBy { it.lowercase() }631 .aggregate { _, acc: Pair<String, Int>?, value, _ ->632 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)633 }634 .values635 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })636 .map { it.first }637 }638639 fun getTombstones(): List<Tombstone> =640 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }641 fun getVaultVersion(): Long = store.version()642 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots643644 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {645 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false646 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false647 takeVaultSnapshot("restore")648 if (!store.writeSlotA(restoredA)) return false649 if (!store.writeSlotB(snapshot.vault_b)) return false650 store.stampLocalMutation()651 lock()652 true653 }654655 656657 658659660661662 suspend fun applyMergedRemoteEntries(663 remoteEntries: List<VaultEntry>,664 remoteTombstones: List<Tombstone>,665 ): Int = mutex.withLock {666 requireUnlocked()667 val tombMap = remoteTombstones.associate { it.id to it.deletedAt }668 var applied = 0669 val byId = entryList.associateBy { it.id }.toMutableMap()670671 for (remote in remoteEntries) {672 val tomb = tombMap[remote.id]673 if (tomb != null && tomb >= remote.modifiedAt) continue674 val local = byId[remote.id]675 if (local == null) {676 entryList.add(remote); byId[remote.id] = remote; applied++677 } else if (remote.modifiedAt > local.modifiedAt) {678 val i = entryList.indexOfFirst { it.id == local.id }679 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }680 }681 }682683 for ((id, deletedAt) in tombMap) {684 val local = byId[id] ?: continue685 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue686 if (deletedAt < local.modifiedAt) continue687 val i = entryList.indexOfFirst { it.id == id }688 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }689 }690691 if (applied > 0) {692 persistSlotA(bumpVersion = false, snapshotReason = "sync_received")693 publish()694 }695 applied696 }697698 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {699 _settings.value = settings700 store.writeSettings(settings)701 }702703 704705 706 fun isRecoveryWordsSet(): Boolean = recoveryWordsSet707708 709710711712713 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {714 requireUnlocked()715 recoveryWordHash = recoveryWordsHash(words)716 recoveryWordsSet = true717 718 719 720 721 runCatching {722 persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))723 }.getOrDefault(false)724 }725726 727 fun verifyRecoveryWords(words: List<String>): Boolean {728 val stored = recoveryWordHash ?: return false729 return stored == recoveryWordsHash(words)730 }731732 733734 735 fun hasRecoveryEscrow(): Boolean =736 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false737738 739740741742743744745746747748749750 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {751 val slotA = store.loadSlotA() ?: return false752 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false753754 755 756 slotA.recoveryEscrow?.let { escrow ->757 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let758 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))759 val keyBytes = recoveryKey.encoded760 try {761 val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)762 val payload = VaultCodec.decode(plaintext)763 decoyMode = false764 entryList = payload.entries.toMutableList()765 duressConfigured = payload.duressConfigured766 recoveryWordHash = payload.recoveryWordHash767 recoveryWordsSet = payload.recoveryWordsSet768 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)769 else generateRecoverableRootKey()770 _settings.value = store.loadSettings()771 VaultCrypto.zero(plaintext)772 return true773 } catch (_: Exception) {774 775 } finally {776 VaultCrypto.zero(material)777 VaultCrypto.zero(keyBytes)778 }779 }780781 782 783 784 slotA.rootKeyEscrow?.let { escrow ->785 val rk = unsealRootKeyEscrow(words, escrow) ?: return false786 decoyMode = false787 entryList = mutableListOf()788 duressConfigured = false789 recoveryWordHash = recoveryWordsHash(words)790 recoveryWordsSet = true791 rootKey = rk792 _settings.value = store.loadSettings()793 return true794 }795 return false796 }797798 799800801802803804805806807 suspend fun resetPasswordWithRecoveryWords(808 words: List<String>,809 newPassword: String,810 ): Boolean = mutex.withLock {811 if (rootKey == null) return false 812 return try {813 val newSalt = VaultCrypto.generateSalt()814 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)815 val plaintext = VaultCodec.encode(currentPayload())816 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))817 val prior = store.loadSlotA()818 819 820 821 val valid = words.size == 12 && findInvalidWords(words).isEmpty()822 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow823 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow824 val next = StoredVault(825 version = prior?.version ?: 1,826 salt = b64(newSalt),827 blob = blob,828 recoveryEscrow = freshRecovery,829 rootKeyEscrow = freshRootKey,830 )831 if (!store.writeSlotA(next)) return false832 writeMatchingNoiseSlotB(next)833 store.stampLocalMutation()834 derivedKey?.let(VaultCrypto::zero)835 derivedKey = newKey836 VaultCrypto.zero(plaintext)837 publish()838 _isUnlocked.value = true839 true840 } catch (_: Exception) {841 false842 }843 }844845 846847848849850851 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {852 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null853 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null854 val salt = VaultCrypto.generateSalt()855 val recoveryKey = deriveRecoveryKey(material, salt)856 val keyBytes = recoveryKey.encoded857 val plaintext = VaultCodec.encode(currentPayload())858 return try {859 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)860 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))861 } finally {862 VaultCrypto.zero(material)863 VaultCrypto.zero(keyBytes)864 VaultCrypto.zero(plaintext)865 }866 }867868 869870871872873874875876 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {877 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null878 val rk = rootKey ?: return null879 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null880 val salt = VaultCrypto.generateSalt()881 val recoveryKey = deriveRecoveryKey(material, salt)882 val keyBytes = recoveryKey.encoded883 val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)884 return try {885 886 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)887 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)888 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)889 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)890 val ct = ctTag.copyOfRange(0, ctTag.size - 16)891 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))892 } finally {893 VaultCrypto.zero(material)894 VaultCrypto.zero(keyBytes)895 VaultCrypto.zero(plaintext)896 }897 }898899 900 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {901 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null902 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))903 val keyBytes = recoveryKey.encoded904 return try {905 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)906 val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)907 hexToRootKey(String(pt, Charsets.US_ASCII))908 } catch (_: Exception) {909 null910 } finally {911 VaultCrypto.zero(material)912 VaultCrypto.zero(keyBytes)913 }914 }915916 917918919920921922 private fun persistSlotAWithEscrows(923 recoveryEscrow: RecoveryEscrow?,924 rootKeyEscrow: RootKeyEscrow?,925 ): Boolean {926 val key = derivedKey ?: throw IllegalStateException("vault_locked")927 if (decoyMode) return false928 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")929 val plaintext = VaultCodec.encode(currentPayload())930 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))931 val next = prior.copy(932 blob = blob,933 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,934 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,935 )936 if (!store.writeSlotA(next)) return false937 try {938 writeMatchingNoiseSlotB(next)939 } catch (e: Exception) {940 store.writeSlotA(prior)941 throw e942 }943 return true944 }945946 947948 private fun requireUnlocked() {949 if (derivedKey == null) throw IllegalStateException("vault_locked")950 }951952 private fun countDuplicateEntriesLocked(): Int {953 val seen = mutableMapOf<String, VaultEntry>()954 var duplicates = 0955 for (entry in entryList.filter { it.deletedAt == null }) {956 val key = entry.duplicateKey()957 val existing = seen[key]958 if (existing == null) {959 seen[key] = entry960 } else {961 duplicates++962 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt963 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt964 if (entryStamp > existingStamp) seen[key] = entry965 }966 }967 return duplicates968 }969970 private fun VaultEntry.duplicateKey(): String {971 if (type == "note") return "note|${title.lowercase()}"972 val passkeyData = passkey973 if (passkeyData != null) {974 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"975 }976 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"977 }978979 private fun takeVaultSnapshot(reason: String) {980 runCatching {981 val slotA = store.loadSlotA() ?: return982 val vaultA = VaultCodec.encodeSlot(slotA)983 val vaultB = store.loadSlotB() ?: slotA.blob984 val history = store.loadVaultHistory()985 val latest = history.snapshots.firstOrNull()986 if (latest?.vault_a == vaultA && latest.vault_b == vaultB) return987 val entryCount = if (derivedKey != null && !decoyMode) {988 bucketEntryCount(entryList.count { it.deletedAt == null })989 } else {990 null991 }992 val snapshot = VaultSnapshot(993 id = UUID.randomUUID().toString(),994 savedAt = System.currentTimeMillis(),995 reason = reason,996 vault_a = vaultA,997 vault_b = vaultB,998 entryCount = entryCount,999 )1000 store.writeVaultHistory(1001 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),1002 )1003 }1004 }10051006 private fun bucketEntryCount(n: Int): Int = when {1007 n <= 0 -> 01008 n <= 10 -> 101009 n <= 25 -> 251010 n <= 50 -> 501011 n <= 100 -> 1001012 n <= 250 -> 2501013 n <= 500 -> 5001014 else -> ((n + 499) / 500) * 5001015 }10161017 10181019102010211022 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {1023 if (!entry.isCard()) return entry1024 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""1025 return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)1026 }10271028 102910301031103210331034 private fun autoPurgeExpiredTrash() {1035 val days = _settings.value.trashRetentionDays ?: return1036 if (days <= 0) return1037 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L1038 val before = entryList.size1039 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }1040 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }1041 }10421043 1044 private fun currentPayload(): VaultPayload =1045 VaultPayload(1046 entries = entryList.toList(),1047 duressConfigured = duressConfigured,1048 rootKeyB64 = rootKey?.let(::b64) ?: "",1049 recoveryWordHash = recoveryWordHash,1050 recoveryWordsSet = recoveryWordsSet,1051 )10521053 10541055105610571058 private fun ensureRootKey(payload: VaultPayload) {1059 if (payload.rootKeyB64.isNotBlank()) {1060 rootKey = unb64(payload.rootKeyB64)1061 return1062 }1063 rootKey = generateRecoverableRootKey()1064 runCatching { persistSlotA(bumpVersion = false) }1065 }10661067 private fun publish() {1068 _entries.value = entryList.filter { it.deletedAt == null }1069 }10701071 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {1072 val plaintext = VaultCodec.encode(currentPayload())1073 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1074 return StoredVault(version = 1, salt = b64(salt), blob = blob)1075 }10761077 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {1078 1079 1080 1081 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)1082 val noise = ByteArray(approxBytes).also(rng::nextBytes)1083 store.writeSlotB(b64(noise))1084 }10851086 1087 private fun persistSlotA(bumpVersion: Boolean, snapshotReason: String? = "local_save"): Boolean {1088 val key = derivedKey ?: throw IllegalStateException("vault_locked")1089 1090 if (decoyMode) {1091 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")1092 val plaintext = VaultCodec.encode(currentPayload())1093 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1094 return store.writeDecoySlot(prior.copy(blob = blob))1095 }1096 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1097 if (snapshotReason != null) takeVaultSnapshot(snapshotReason)1098 val plaintext = VaultCodec.encode(currentPayload())1099 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1100 val next = prior.copy(blob = blob)1101 if (!store.writeSlotA(next)) return false1102 1103 1104 try {1105 writeMatchingNoiseSlotB(next)1106 if (bumpVersion) store.stampLocalMutation()1107 } catch (e: Exception) {1108 store.writeSlotA(prior)1109 throw e1110 }1111 return true1112 }11131114 1115 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {1116 try {1117 if (!persistSlotA(bumpVersion = true)) {1118 entryList = rollback1119 throw IllegalStateException("storage_write_failed")1120 }1121 } catch (e: Exception) {1122 entryList = rollback1123 throw e1124 }1125 publish()1126 }1127}