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}3233sealed interface AdoptVaultResult {34 data class Success(val vaultId: String) : AdoptVaultResult35 data class Error(val reason: String) : AdoptVaultResult36}373839404142434445464748495051@Singleton52class VaultRepository @Inject constructor(53 private val store: VaultStorage,54) {55 private val mutex = Mutex()56 private val rng = SecureRandom()5758 private var derivedKey: ByteArray? = null59 private var rootKey: ByteArray? = null60 private var entryList: MutableList<VaultEntry> = mutableListOf()61 private var duressConfigured: Boolean = false62 private var recoveryWordHash: String? = null63 private var recoveryWordsSet: Boolean = false64 65 private var decoyMode: Boolean = false6667 private val _isUnlocked = MutableStateFlow(false)68 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6970 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())71 72 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()7374 private val _settings = MutableStateFlow(VaultSettings())75 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()7677 fun hasVault(): Boolean = store.hasVault()7879 8081 8283848586 fun codexVaultBlobBase64(): String? {87 val slotA = store.loadSlotA() ?: return null88 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""89 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))90 }9192 9394959697 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {98 return try {99 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)100 val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)101 ?: return UnlockResult.Error("invalid_codex_blob")102 val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")103 if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")104 writeMatchingNoiseSlotB(slotA)105 store.stampLocalMutation()106 unlockLocked(password)107 } catch (e: Exception) {108 UnlockResult.Error(e.message ?: "restore_failed")109 }110 }111112 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {113 return try {114 val salt = VaultCrypto.generateSalt()115 val key = VaultCrypto.deriveKey(password, salt)116 entryList = mutableListOf()117 duressConfigured = false118 recoveryWordHash = null119 recoveryWordsSet = false120 decoyMode = false121 rootKey = generateRecoverableRootKey()122 val slotA = sealSlotA(key, salt)123 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")124 writeMatchingNoiseSlotB(slotA)125 store.stampLocalMutation()126 store.writeSettings(_settings.value)127 derivedKey = key128 publish()129 _isUnlocked.value = true130 CreateVaultResult.Success131 } catch (e: Exception) {132 CreateVaultResult.Error(e.message ?: "create_failed")133 }134 }135136 suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {137 if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")138 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {139 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")140 }141 var adoptedRootKey: ByteArray? = null142 var nextDerivedKey: ByteArray? = null143 var sessionRootKey: ByteArray? = null144 return try {145 adoptedRootKey = hexToRootKey(rootKeyHex)146 if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {147 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")148 }149 val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)150 val salt = VaultCrypto.generateSalt()151 nextDerivedKey = VaultCrypto.deriveKey(password, salt)152 sessionRootKey = adoptedRootKey.copyOf()153 val payload = VaultPayload(154 entries = emptyList(),155 duressConfigured = false,156 rootKeyB64 = b64(sessionRootKey),157 recoveryWordHash = null,158 recoveryWordsSet = false,159 )160 val blob = b64(VaultCrypto.encrypt(VaultCodec.encode(payload), nextDerivedKey, VaultCrypto.AAD_SLOT_A))161 val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)162 if (!store.writeSlotA(slotA)) return AdoptVaultResult.Error("storage_write_failed")163 writeMatchingNoiseSlotB(slotA)164 store.stampLocalMutation()165 store.writeSettings(_settings.value)166167 val previousDerivedKey = derivedKey168 val previousRootKey = rootKey169 derivedKey = nextDerivedKey170 rootKey = sessionRootKey171 nextDerivedKey = null172 sessionRootKey = null173 entryList = mutableListOf()174 duressConfigured = false175 recoveryWordHash = null176 recoveryWordsSet = false177 decoyMode = false178 publish()179 _isUnlocked.value = true180 previousDerivedKey?.let(VaultCrypto::zero)181 previousRootKey?.let(VaultCrypto::zero)182 AdoptVaultResult.Success(vaultId)183 } catch (e: Exception) {184 AdoptVaultResult.Error(e.message ?: "adoption_create_failed")185 } finally {186 adoptedRootKey?.let(VaultCrypto::zero)187 nextDerivedKey?.let(VaultCrypto::zero)188 sessionRootKey?.let(VaultCrypto::zero)189 }190 }191192 suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }193194 195 private fun unlockLocked(password: String): UnlockResult {196 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")197 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))198 val payload = try {199 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))200 } catch (_: Exception) {201 VaultCrypto.zero(key)202 203 204 205 if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {206 val legacy = tryLegacyRawUnlock(password, slotA)207 if (legacy != null) return legacy208 }209 return UnlockResult.WrongPassword210 }211 return adoptSlotA(key, payload)212 }213214 215216217218219220 private fun tryLegacyRawUnlock(password: String, slotA: StoredVault): UnlockResult? {221 val rawKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))222 val payload = try {223 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), rawKey, VaultCrypto.AAD_SLOT_A))224 } catch (_: Exception) {225 VaultCrypto.zero(rawKey)226 return null227 }228 229 230 val newSalt = VaultCrypto.generateSalt()231 val newKey = VaultCrypto.deriveKey(password, newSalt)232 val healed = try {233 val blob = b64(VaultCrypto.encrypt(VaultCodec.encode(payload), newKey, VaultCrypto.AAD_SLOT_A))234 val next = StoredVault(235 version = slotA.version,236 salt = b64(newSalt),237 blob = blob,238 recoveryEscrow = slotA.recoveryEscrow,239 rootKeyEscrow = slotA.rootKeyEscrow,240 )241 if (store.writeSlotA(next)) {242 writeMatchingNoiseSlotB(next)243 store.stampLocalMutation()244 true245 } else {246 false247 }248 } catch (_: Exception) {249 false250 }251 return if (healed) {252 VaultCrypto.zero(rawKey)253 adoptSlotA(newKey, payload) 254 } else {255 VaultCrypto.zero(newKey)256 adoptSlotA(rawKey, payload) 257 }258 }259260 261 private fun adoptSlotA(key: ByteArray, payload: VaultPayload): UnlockResult {262 return try {263 derivedKey = key264 decoyMode = false265 entryList = payload.entries.toMutableList()266 duressConfigured = payload.duressConfigured267 recoveryWordHash = payload.recoveryWordHash268 recoveryWordsSet = payload.recoveryWordsSet269 _settings.value = store.loadSettings()270 ensureRootKey(payload)271 autoPurgeExpiredTrash()272 publish()273 _isUnlocked.value = true274 UnlockResult.Success275 } catch (e: Exception) {276 UnlockResult.Error(e.message ?: "unlock_failed")277 }278 }279280 281282 283284285286287288 class SlotAUnlock internal constructor(289 internal val key: ByteArray,290 internal val payload: VaultPayload,291 )292293 294295296297298299 fun tryUnlockSlotA(password: String): SlotAUnlock? {300 val slotA = store.loadSlotA() ?: return null301 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))302 return try {303 val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))304 SlotAUnlock(key, payload)305 } catch (_: Exception) {306 VaultCrypto.zero(key)307 null308 }309 }310311 312 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {313 adoptSlotA(unlock.key, unlock.payload)314 }315316 317 fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)318319 320321 322323324325326 class DuressUnlock internal constructor(327 internal val key: ByteArray,328 internal val payload: VaultPayload,329 )330331 332333334335336337338 fun tryUnlockDuress(password: String): DuressUnlock? {339 val slot = store.loadDecoySlot() ?: return null340 val key = VaultCrypto.deriveKey(password, unb64(slot.salt))341 return try {342 val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A))343 DuressUnlock(key, payload)344 } catch (_: Exception) {345 VaultCrypto.zero(key)346 null347 }348 }349350 351 suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {352 return try {353 derivedKey = unlock.key354 decoyMode = true355 entryList = unlock.payload.entries.toMutableList()356 duressConfigured = false357 recoveryWordHash = unlock.payload.recoveryWordHash358 recoveryWordsSet = unlock.payload.recoveryWordsSet359 rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)360 else VaultCrypto.generateRootKey()361 _settings.value = store.loadSettings()362 publish()363 _isUnlocked.value = true364 UnlockResult.Success365 } catch (e: Exception) {366 UnlockResult.Error(e.message ?: "decoy_unlock_failed")367 }368 }369370 371 fun discardDuressUnlock(unlock: DuressUnlock) = VaultCrypto.zero(unlock.key)372373 374375376377378379 suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {380 if (derivedKey == null || decoyMode) return false381 382 383 tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }384 return try {385 val salt = VaultCrypto.generateSalt()386 val key = VaultCrypto.deriveKey(duressPassphrase, salt)387 388 val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = b64(VaultCrypto.generateRootKey()))389 val plaintext = VaultCodec.encode(decoyPayload)390 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))391 VaultCrypto.zero(key)392 VaultCrypto.zero(plaintext)393 val ok = store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))394 if (ok) {395 duressConfigured = true396 runCatching { persistSlotA(bumpVersion = false) }397 }398 ok399 } catch (_: Exception) {400 false401 }402 }403404 405 suspend fun clearDuress(): Boolean = mutex.withLock {406 store.clearDecoySlot()407 if (derivedKey != null && !decoyMode) {408 duressConfigured = false409 runCatching { persistSlotA(bumpVersion = false) }410 }411 true412 }413414 415 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {416 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")417 return try {418 val payload = VaultCodec.decode(419 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),420 )421 derivedKey = key.copyOf()422 decoyMode = false423 entryList = payload.entries.toMutableList()424 duressConfigured = payload.duressConfigured425 recoveryWordHash = payload.recoveryWordHash426 recoveryWordsSet = payload.recoveryWordsSet427 _settings.value = store.loadSettings()428 ensureRootKey(payload)429 autoPurgeExpiredTrash()430 publish()431 _isUnlocked.value = true432 UnlockResult.Success433 } catch (_: Exception) {434 UnlockResult.WrongPassword435 }436 }437438 fun lock() {439 derivedKey?.let(VaultCrypto::zero)440 rootKey?.let(VaultCrypto::zero)441 derivedKey = null442 rootKey = null443 entryList = mutableListOf()444 duressConfigured = false445 recoveryWordHash = null446 recoveryWordsSet = false447 decoyMode = false448 _entries.value = emptyList()449 _isUnlocked.value = false450 }451452 453454 455456457458459 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()460461 462 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }463464 465466467468469 suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {470 val key = derivedKey ?: return false471 if (decoyMode) return false472 val priorSlot = store.loadSlotA() ?: return false473 val priorRootKey = rootKey ?: return false474 val priorRecoveryHash = recoveryWordHash475 val priorRecoverySet = recoveryWordsSet476 val nextRootKey = generateRecoverableRootKey()477 val nextWords = rootKeyToWords(nextRootKey)478479 try {480 takeVaultSnapshot("local_save")481 rootKey = nextRootKey482 recoveryWordHash = recoveryWordsHash(nextWords)483 recoveryWordsSet = false484485 val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)486 ?: throw IllegalStateException("recovery_escrow_failed")487 val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)488 ?: throw IllegalStateException("root_escrow_failed")489 val plaintext = VaultCodec.encode(currentPayload())490 val blob = try {491 b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))492 } finally {493 VaultCrypto.zero(plaintext)494 }495 val nextSlot = priorSlot.copy(496 blob = blob,497 recoveryEscrow = nextRecoveryEscrow,498 rootKeyEscrow = nextRootKeyEscrow,499 )500 if (!store.writeSlotA(nextSlot)) throw IllegalStateException("storage_write_failed")501 try {502 writeMatchingNoiseSlotB(nextSlot)503 store.stampLocalMutation()504 } catch (e: Exception) {505 store.writeSlotA(priorSlot)506 throw e507 }508 VaultCrypto.zero(priorRootKey)509 publish()510 true511 } catch (_: Exception) {512 rootKey = priorRootKey513 recoveryWordHash = priorRecoveryHash514 recoveryWordsSet = priorRecoverySet515 VaultCrypto.zero(nextRootKey)516 store.writeSlotA(priorSlot)517 false518 }519 }520521 522523524525526 fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()527528 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {529 val slotA = store.loadSlotA() ?: return false530 return try {531 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))532 val payload = VaultCodec.decode(533 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),534 )535 val newSalt = VaultCrypto.generateSalt()536 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)537 538 val plaintext = VaultCodec.encode(payload)539 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))540 541 542 543 544 545 546 547 val next = StoredVault(548 version = slotA.version,549 salt = b64(newSalt),550 blob = blob,551 recoveryEscrow = slotA.recoveryEscrow,552 rootKeyEscrow = slotA.rootKeyEscrow,553 )554 if (!store.writeSlotA(next)) return false555 writeMatchingNoiseSlotB(next)556 store.stampLocalMutation()557 VaultCrypto.zero(oldKey)558 derivedKey?.let(VaultCrypto::zero)559 derivedKey = newKey560 true561 } catch (_: Exception) {562 false563 }564 }565566 567568569570 suspend fun destroyVault() = mutex.withLock {571 lock()572 store.clearVault()573 store.clearDecoySlot()574 }575576 577578 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {579 requireUnlocked()580 val stamp = VaultCrypto.monotonicEntryTimestamp()581 val now = System.currentTimeMillis()582 val entry = withDerivedLast4(draft.copy(583 id = draft.id.ifBlank { UUID.randomUUID().toString() },584 createdAt = if (draft.createdAt > 0) draft.createdAt else now,585 modifiedAt = stamp,586 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,587 ))588 val rollback = entryList.toMutableList()589 entryList.add(entry)590 persistOrRollback(rollback)591 entry592 }593594 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {595 requireUnlocked()596 val idx = entryList.indexOfFirst { it.id == patch.id }597 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")598 val current = entryList[idx]599 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)600 601 val passwordChanged = patch.password != null && patch.password != current.password602 603 604 605 606 607 608 val priorPassword = current.password609 val shouldCapture = passwordChanged &&610 !priorPassword.isNullOrEmpty() &&611 current.passwordHistory?.firstOrNull()?.password != priorPassword612 val nextHistory = if (shouldCapture) {613 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +614 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)615 } else {616 current.passwordHistory617 }618 val updated = withDerivedLast4(patch.copy(619 createdAt = current.createdAt,620 modifiedAt = stamp,621 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,622 passwordHistory = nextHistory,623 ))624 val rollback = entryList.toMutableList()625 entryList[idx] = updated626 persistOrRollback(rollback)627 updated628 }629630 631 suspend fun deleteEntry(id: String) = mutex.withLock {632 requireUnlocked()633 val idx = entryList.indexOfFirst { it.id == id }634 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")635 val current = entryList[idx]636 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)637 val rollback = entryList.toMutableList()638 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)639 persistOrRollback(rollback)640 }641642 suspend fun restoreEntry(id: String) = mutex.withLock {643 requireUnlocked()644 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }645 if (idx == -1) throw IllegalStateException("deleted entry not found")646 val current = entryList[idx]647 val rollback = entryList.toMutableList()648 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))649 persistOrRollback(rollback)650 }651652 653 suspend fun purgeEntry(id: String) = mutex.withLock {654 requireUnlocked()655 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }656 if (idx == -1) throw IllegalStateException("deleted entry not found")657 val rollback = entryList.toMutableList()658 entryList.removeAt(idx)659 persistOrRollback(rollback)660 }661662 663 suspend fun purgeDeletedEntries(): Int = mutex.withLock {664 requireUnlocked()665 val rollback = entryList.toMutableList()666 val before = entryList.size667 entryList.removeAll { it.deletedAt != null }668 val removed = before - entryList.size669 if (removed > 0) persistOrRollback(rollback)670 removed671 }672673 674 suspend fun countDuplicateEntries(): Int = mutex.withLock {675 requireUnlocked()676 countDuplicateEntriesLocked()677 }678679 680681682683684 suspend fun deduplicateEntries(): Int = mutex.withLock {685 requireUnlocked()686 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")687 val active = entryList.filter { it.deletedAt == null }688 val keepIds = mutableSetOf<String>()689 active.groupBy { it.duplicateKey() }.values.forEach { group ->690 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id691 }692693 val rollback = entryList.toMutableList()694 var removed = 0695 entryList = entryList.map { entry ->696 if (entry.deletedAt == null && entry.id !in keepIds) {697 removed++698 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)699 entry.copy(deletedAt = stamp, modifiedAt = stamp)700 } else {701 entry702 }703 }.toMutableList()704 if (removed > 0) persistOrRollback(rollback)705 removed706 }707708 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }709 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }710 fun getDeletedEntries(): List<VaultEntry> =711 entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }712713 714 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {715 val active = entryList.filter { it.deletedAt == null }716 if (tagFilter == null) return active717 val needle = tagFilter.trim().lowercase()718 return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }719 }720721 722 fun getDistinctTags(): List<String> =723 entryList.asSequence()724 .filter { it.deletedAt == null }725 .flatMap { it.tags?.asSequence() ?: emptySequence() }726 .map { it.trim().lowercase() }727 .filter { it.isNotEmpty() }728 .distinct()729 .sorted()730 .toList()731732 733734735736737738 fun getDistinctFieldValues(field: String): List<String> {739 val select: (VaultEntry) -> String? = when (field) {740 "username" -> { e -> e.username }741 "email" -> { e -> e.email }742 else -> return emptyList()743 }744 return entryList.asSequence()745 .filter { it.deletedAt == null }746 .mapNotNull { select(it)?.trim() }747 .filter { it.isNotEmpty() }748 .groupingBy { it.lowercase() }749 .aggregate { _, acc: Pair<String, Int>?, value, _ ->750 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)751 }752 .values753 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })754 .map { it.first }755 }756757 fun getTombstones(): List<Tombstone> =758 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }759 fun getVaultVersion(): Long = store.version()760 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots761762 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {763 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false764 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false765 takeVaultSnapshot("restore")766 if (!store.writeSlotA(restoredA)) return false767 if (!store.writeSlotB(snapshot.vault_b)) return false768 store.stampLocalMutation()769 lock()770 true771 }772773 774775 776777778779780 suspend fun applyMergedRemoteEntries(781 remoteEntries: List<VaultEntry>,782 remoteTombstones: List<Tombstone>,783 ): Int = mutex.withLock {784 requireUnlocked()785 val tombMap = remoteTombstones.associate { it.id to it.deletedAt }786 var applied = 0787 val byId = entryList.associateBy { it.id }.toMutableMap()788789 for (remote in remoteEntries) {790 val tomb = tombMap[remote.id]791 if (tomb != null && tomb >= remote.modifiedAt) continue792 val local = byId[remote.id]793 if (local == null) {794 entryList.add(remote); byId[remote.id] = remote; applied++795 } else if (remote.modifiedAt > local.modifiedAt) {796 val i = entryList.indexOfFirst { it.id == local.id }797 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }798 }799 }800801 for ((id, deletedAt) in tombMap) {802 val local = byId[id] ?: continue803 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue804 if (deletedAt < local.modifiedAt) continue805 val i = entryList.indexOfFirst { it.id == id }806 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }807 }808809 if (applied > 0) {810 persistSlotA(bumpVersion = false, snapshotReason = "sync_received")811 publish()812 }813 applied814 }815816 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {817 _settings.value = settings818 store.writeSettings(settings)819 }820821 822823 824 fun isRecoveryWordsSet(): Boolean = recoveryWordsSet825826 827828829830831 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {832 requireUnlocked()833 recoveryWordHash = recoveryWordsHash(words)834 recoveryWordsSet = true835 836 837 838 839 runCatching {840 persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))841 }.getOrDefault(false)842 }843844 845 fun verifyRecoveryWords(words: List<String>): Boolean {846 val stored = recoveryWordHash ?: return false847 return stored == recoveryWordsHash(words)848 }849850 851852 853 fun hasRecoveryEscrow(): Boolean =854 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false855856 857858859860861862863864865866867868 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {869 val slotA = store.loadSlotA() ?: return false870 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false871872 873 874 slotA.recoveryEscrow?.let { escrow ->875 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let876 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))877 val keyBytes = recoveryKey.encoded878 try {879 val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)880 val payload = VaultCodec.decode(plaintext)881 decoyMode = false882 entryList = payload.entries.toMutableList()883 duressConfigured = payload.duressConfigured884 recoveryWordHash = payload.recoveryWordHash885 recoveryWordsSet = payload.recoveryWordsSet886 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)887 else generateRecoverableRootKey()888 _settings.value = store.loadSettings()889 VaultCrypto.zero(plaintext)890 return true891 } catch (_: Exception) {892 893 } finally {894 VaultCrypto.zero(material)895 VaultCrypto.zero(keyBytes)896 }897 }898899 900 901 902 slotA.rootKeyEscrow?.let { escrow ->903 val rk = unsealRootKeyEscrow(words, escrow) ?: return false904 decoyMode = false905 entryList = mutableListOf()906 duressConfigured = false907 recoveryWordHash = recoveryWordsHash(words)908 recoveryWordsSet = true909 rootKey = rk910 _settings.value = store.loadSettings()911 return true912 }913 return false914 }915916 917918919920921922923924925 suspend fun resetPasswordWithRecoveryWords(926 words: List<String>,927 newPassword: String,928 ): Boolean = mutex.withLock {929 if (rootKey == null) return false 930 return try {931 val newSalt = VaultCrypto.generateSalt()932 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)933 val plaintext = VaultCodec.encode(currentPayload())934 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))935 val prior = store.loadSlotA()936 937 938 939 val valid = words.size == 12 && findInvalidWords(words).isEmpty()940 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow941 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow942 val next = StoredVault(943 version = prior?.version ?: 1,944 salt = b64(newSalt),945 blob = blob,946 recoveryEscrow = freshRecovery,947 rootKeyEscrow = freshRootKey,948 )949 if (!store.writeSlotA(next)) return false950 writeMatchingNoiseSlotB(next)951 store.stampLocalMutation()952 derivedKey?.let(VaultCrypto::zero)953 derivedKey = newKey954 VaultCrypto.zero(plaintext)955 publish()956 _isUnlocked.value = true957 true958 } catch (_: Exception) {959 false960 }961 }962963 964965966967968969 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {970 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null971 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null972 val salt = VaultCrypto.generateSalt()973 val recoveryKey = deriveRecoveryKey(material, salt)974 val keyBytes = recoveryKey.encoded975 val plaintext = VaultCodec.encode(currentPayload())976 return try {977 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)978 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))979 } finally {980 VaultCrypto.zero(material)981 VaultCrypto.zero(keyBytes)982 VaultCrypto.zero(plaintext)983 }984 }985986 987988989990991992993994 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {995 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null996 val rk = rootKey ?: return null997 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null998 val salt = VaultCrypto.generateSalt()999 val recoveryKey = deriveRecoveryKey(material, salt)1000 val keyBytes = recoveryKey.encoded1001 val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)1002 return try {1003 1004 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1005 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)1006 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)1007 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)1008 val ct = ctTag.copyOfRange(0, ctTag.size - 16)1009 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))1010 } finally {1011 VaultCrypto.zero(material)1012 VaultCrypto.zero(keyBytes)1013 VaultCrypto.zero(plaintext)1014 }1015 }10161017 1018 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {1019 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1020 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))1021 val keyBytes = recoveryKey.encoded1022 return try {1023 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)1024 val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1025 hexToRootKey(String(pt, Charsets.US_ASCII))1026 } catch (_: Exception) {1027 null1028 } finally {1029 VaultCrypto.zero(material)1030 VaultCrypto.zero(keyBytes)1031 }1032 }10331034 103510361037103810391040 private fun persistSlotAWithEscrows(1041 recoveryEscrow: RecoveryEscrow?,1042 rootKeyEscrow: RootKeyEscrow?,1043 ): Boolean {1044 val key = derivedKey ?: throw IllegalStateException("vault_locked")1045 if (decoyMode) return false1046 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1047 val plaintext = VaultCodec.encode(currentPayload())1048 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1049 val next = prior.copy(1050 blob = blob,1051 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,1052 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,1053 )1054 if (!store.writeSlotA(next)) return false1055 try {1056 writeMatchingNoiseSlotB(next)1057 } catch (e: Exception) {1058 store.writeSlotA(prior)1059 throw e1060 }1061 return true1062 }10631064 10651066 private fun requireUnlocked() {1067 if (derivedKey == null) throw IllegalStateException("vault_locked")1068 }10691070 private fun countDuplicateEntriesLocked(): Int {1071 val seen = mutableMapOf<String, VaultEntry>()1072 var duplicates = 01073 for (entry in entryList.filter { it.deletedAt == null }) {1074 val key = entry.duplicateKey()1075 val existing = seen[key]1076 if (existing == null) {1077 seen[key] = entry1078 } else {1079 duplicates++1080 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt1081 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt1082 if (entryStamp > existingStamp) seen[key] = entry1083 }1084 }1085 return duplicates1086 }10871088 private fun VaultEntry.duplicateKey(): String {1089 if (type == "note") return "note|${title.lowercase()}"1090 val passkeyData = passkey1091 if (passkeyData != null) {1092 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"1093 }1094 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"1095 }10961097 private fun takeVaultSnapshot(reason: String) {1098 runCatching {1099 val slotA = store.loadSlotA() ?: return1100 val vaultA = VaultCodec.encodeSlot(slotA)1101 val vaultB = store.loadSlotB() ?: slotA.blob1102 val history = store.loadVaultHistory()1103 val latest = history.snapshots.firstOrNull()1104 if (latest?.vault_a == vaultA && latest.vault_b == vaultB) return1105 val entryCount = if (derivedKey != null && !decoyMode) {1106 bucketEntryCount(entryList.count { it.deletedAt == null })1107 } else {1108 null1109 }1110 val snapshot = VaultSnapshot(1111 id = UUID.randomUUID().toString(),1112 savedAt = System.currentTimeMillis(),1113 reason = reason,1114 vault_a = vaultA,1115 vault_b = vaultB,1116 entryCount = entryCount,1117 )1118 store.writeVaultHistory(1119 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),1120 )1121 }1122 }11231124 private fun bucketEntryCount(n: Int): Int = when {1125 n <= 0 -> 01126 n <= 10 -> 101127 n <= 25 -> 251128 n <= 50 -> 501129 n <= 100 -> 1001130 n <= 250 -> 2501131 n <= 500 -> 5001132 else -> ((n + 499) / 500) * 5001133 }11341135 11361137113811391140 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {1141 if (!entry.isCard()) return entry1142 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""1143 return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)1144 }11451146 114711481149115011511152 private fun autoPurgeExpiredTrash() {1153 val days = _settings.value.trashRetentionDays ?: return1154 if (days <= 0) return1155 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L1156 val before = entryList.size1157 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }1158 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }1159 }11601161 1162 private fun currentPayload(): VaultPayload =1163 VaultPayload(1164 entries = entryList.toList(),1165 duressConfigured = duressConfigured,1166 rootKeyB64 = rootKey?.let(::b64) ?: "",1167 recoveryWordHash = recoveryWordHash,1168 recoveryWordsSet = recoveryWordsSet,1169 )11701171 11721173117411751176 private fun ensureRootKey(payload: VaultPayload) {1177 if (payload.rootKeyB64.isNotBlank()) {1178 rootKey = unb64(payload.rootKeyB64)1179 return1180 }1181 rootKey = generateRecoverableRootKey()1182 runCatching { persistSlotA(bumpVersion = false) }1183 }11841185 private fun publish() {1186 _entries.value = entryList.filter { it.deletedAt == null }1187 }11881189 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {1190 val plaintext = VaultCodec.encode(currentPayload())1191 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1192 return StoredVault(version = 1, salt = b64(salt), blob = blob)1193 }11941195 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {1196 1197 1198 1199 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)1200 val noise = ByteArray(approxBytes).also(rng::nextBytes)1201 store.writeSlotB(b64(noise))1202 }12031204 1205 private fun persistSlotA(bumpVersion: Boolean, snapshotReason: String? = "local_save"): Boolean {1206 val key = derivedKey ?: throw IllegalStateException("vault_locked")1207 1208 if (decoyMode) {1209 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")1210 val plaintext = VaultCodec.encode(currentPayload())1211 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1212 return store.writeDecoySlot(prior.copy(blob = blob))1213 }1214 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1215 if (snapshotReason != null) takeVaultSnapshot(snapshotReason)1216 val plaintext = VaultCodec.encode(currentPayload())1217 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1218 val next = prior.copy(blob = blob)1219 if (!store.writeSlotA(next)) return false1220 1221 1222 try {1223 writeMatchingNoiseSlotB(next)1224 if (bumpVersion) store.stampLocalMutation()1225 } catch (e: Exception) {1226 store.writeSlotA(prior)1227 throw e1228 }1229 return true1230 }12311232 1233 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {1234 try {1235 if (!persistSlotA(bumpVersion = true)) {1236 entryList = rollback1237 throw IllegalStateException("storage_write_failed")1238 }1239 } catch (e: Exception) {1240 entryList = rollback1241 throw e1242 }1243 publish()1244 }1245}