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 kotlinx.serialization.json.Json11import android.util.Log12import com.peachpasswords.BuildConfig13import com.peachpasswords.sync.SyncLimits14import kotlinx.serialization.json.JsonElement15import kotlinx.serialization.json.JsonNull16import kotlinx.serialization.json.JsonObject17import kotlinx.serialization.json.JsonPrimitive18import java.util.Base6419import java.util.UUID20import javax.inject.Inject21import javax.inject.Singleton222324private val CodexJson = Json { ignoreUnknownKeys = true; isLenient = true }2526private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)27private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)282930private const val PASSWORD_HISTORY_MAX = 5031private const val VAULT_HISTORY_MAX = 53233sealed interface UnlockResult {34 data object Success : UnlockResult35 data object WrongPassword : UnlockResult36 data class Error(val reason: String) : UnlockResult37}3839sealed interface CreateVaultResult {40 data object Success : CreateVaultResult41 data class Error(val reason: String) : CreateVaultResult42}4344sealed interface AdoptVaultResult {45 data class Success(val vaultId: String) : AdoptVaultResult46 data class Error(val reason: String) : AdoptVaultResult47}484950515253545556575859606162@Singleton63class VaultRepository @Inject constructor(64 private val store: VaultStorage,65) {66 private val mutex = Mutex()67 private val rng = SecureRandom()6869 private var derivedKey: ByteArray? = null70 private var rootKey: ByteArray? = null71 private var entryList: MutableList<VaultEntry> = mutableListOf()72 private var duressConfigured: Boolean = false73 private var recoveryWordHash: String? = null74 private var recoveryWordsSet: Boolean = false75 76 private var decoyMode: Boolean = false7778 private val _isUnlocked = MutableStateFlow(false)79 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()8081 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())82 83 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()8485 private val _settings = MutableStateFlow(VaultSettings())86 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()8788 fun hasVault(): Boolean = store.hasVault()8990 9192 9394959697 fun codexVaultBlobBase64(): String? {98 val slotA = store.loadSlotA() ?: return null99 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""100 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))101 }102103 104105106107108 109 private fun JsonElement?.asSlotJson(): String? = when {110 this == null || this is JsonNull -> null111 this is JsonPrimitive && isString -> content112 else -> toString()113 }114115 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {116 return try {117 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)118 119 120 121 122 123 124 125 val wrapper = CodexJson.parseToJsonElement(wrapperJson) as? JsonObject126 ?: return UnlockResult.Error("invalid_codex_blob")127 val slotJson = wrapper["a"].asSlotJson() ?: return UnlockResult.Error("invalid_codex_blob")128 129 130 131 132 133 val slotA = VaultCodec.decodeSlot(slotJson)134 ?: BrowserSlot.parse(slotJson)?.let {135 BrowserSlot.toAndroidSlot(it, password) ?: return UnlockResult.WrongPassword136 }137 ?: return UnlockResult.Error("invalid_codex_blob")138 if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")139 140 141 val slotB = wrapper["b"].asSlotJson()142 if (slotB != null) {143 store.writeSlotB(Base64.getEncoder().encodeToString(slotB.toByteArray(Charsets.UTF_8)))144 } else {145 writeMatchingNoiseSlotB(slotA)146 }147 store.stampLocalMutation()148 unlockLocked(password)149 } catch (e: Exception) {150 151 152 153 154 155 156 if (BuildConfig.DEBUG) Log.w("PeachCodex", codexFailureShape(vaultBlobBase64, e))157 UnlockResult.Error(e.message ?: "restore_failed")158 }159 }160161 162 private fun codexFailureShape(vaultBlobBase64: String, e: Exception): String = runCatching {163 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)164 val offset = Regex("offset (\\d+)").find(e.message.orEmpty())?.groupValues?.get(1)?.toIntOrNull()165 val window = offset?.let {166 val from = (it - 40).coerceAtLeast(0)167 val to = (it + 40).coerceAtMost(wrapperJson.length)168 wrapperJson.substring(from, to).replace(Regex("[A-Za-z0-9+/=_-]"), "x")169 }170 val wrapper = runCatching { CodexJson.parseToJsonElement(wrapperJson) as? JsonObject }.getOrNull()171 val slot = wrapper?.get("a")172 buildString {173 append("codex restore failed: ").append(e::class.simpleName).append(": ").append(e.message)174 append(" | blobBase64=").append(vaultBlobBase64.length)175 append(" wrapperChars=").append(wrapperJson.length)176 append(" wrapperParses=").append(wrapper != null)177 append(" keys=").append(wrapper?.keys)178 append(" slotAKind=").append(179 when {180 slot == null -> "absent"181 slot is JsonPrimitive && slot.isString -> "string"182 slot is JsonObject -> "object:" + slot.keys183 else -> slot::class.simpleName184 },185 )186 if (window != null) append(" masked@").append(offset).append("=").append(window)187 }188 }.getOrElse { "codex restore failed: ${e.message} (shape unavailable: $it)" }189190 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {191 return try {192 val salt = VaultCrypto.generateSalt()193 val key = VaultCrypto.deriveKey(password, salt)194 entryList = mutableListOf()195 duressConfigured = false196 recoveryWordHash = null197 recoveryWordsSet = false198 decoyMode = false199 rootKey = generateRecoverableRootKey()200 val slotA = sealSlotA(key, salt)201 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")202 writeMatchingNoiseSlotB(slotA)203 store.stampLocalMutation()204 store.writeSettings(_settings.value)205 derivedKey = key206 publish()207 _isUnlocked.value = true208 CreateVaultResult.Success209 } catch (e: Exception) {210 CreateVaultResult.Error(e.message ?: "create_failed")211 }212 }213214 suspend fun createVaultFromRootKey(password: String, rootKeyHex: String): AdoptVaultResult = mutex.withLock {215 if (password.isEmpty()) return AdoptVaultResult.Error("ADOPT_INVALID_PASSWORD")216 if (store.hasVault()) return AdoptVaultResult.Error("ADOPT_VAULT_ALREADY_EXISTS")217 if (!rootKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {218 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 64 lowercase hex chars")219 }220 var adoptedRootKey: ByteArray? = null221 var nextDerivedKey: ByteArray? = null222 var sessionRootKey: ByteArray? = null223 return try {224 adoptedRootKey = hexToRootKey(rootKeyHex)225 if (adoptedRootKey.size != VaultCrypto.KEY_SIZE) {226 return AdoptVaultResult.Error("ADOPT_INVALID_ROOT_KEY: expected 32 bytes")227 }228 val vaultId = com.peachpasswords.sync.computeVaultId(adoptedRootKey)229 val salt = VaultCrypto.generateSalt()230 nextDerivedKey = VaultCrypto.deriveKey(password, salt)231 sessionRootKey = adoptedRootKey.copyOf()232 val payload = VaultPayload(233 entries = emptyList(),234 duressConfigured = false,235 rootKeyB64 = b64(sessionRootKey),236 recoveryWordHash = null,237 recoveryWordsSet = false,238 )239 val blob = b64(VaultCrypto.encrypt(VaultCodec.encode(payload), nextDerivedKey, VaultCrypto.AAD_SLOT_A))240 val slotA = StoredVault(version = 1, salt = b64(salt), blob = blob)241 if (!store.writeSlotA(slotA)) return AdoptVaultResult.Error("storage_write_failed")242 writeMatchingNoiseSlotB(slotA)243 store.stampLocalMutation()244 store.writeSettings(_settings.value)245246 val previousDerivedKey = derivedKey247 val previousRootKey = rootKey248 derivedKey = nextDerivedKey249 rootKey = sessionRootKey250 nextDerivedKey = null251 sessionRootKey = null252 entryList = mutableListOf()253 duressConfigured = false254 recoveryWordHash = null255 recoveryWordsSet = false256 decoyMode = false257 publish()258 _isUnlocked.value = true259 previousDerivedKey?.let(VaultCrypto::zero)260 previousRootKey?.let(VaultCrypto::zero)261 AdoptVaultResult.Success(vaultId)262 } catch (e: Exception) {263 AdoptVaultResult.Error(e.message ?: "adoption_create_failed")264 } finally {265 adoptedRootKey?.let(VaultCrypto::zero)266 nextDerivedKey?.let(VaultCrypto::zero)267 sessionRootKey?.let(VaultCrypto::zero)268 }269 }270271 suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }272273 274 private fun unlockLocked(password: String): UnlockResult {275 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")276 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))277 val payload = try {278 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))279 } catch (_: Exception) {280 VaultCrypto.zero(key)281 282 283 284 if (password != Normalizer.normalize(password, Normalizer.Form.NFC)) {285 val legacy = tryLegacyRawUnlock(password, slotA)286 if (legacy != null) return legacy287 }288 return UnlockResult.WrongPassword289 }290 return adoptSlotA(key, payload)291 }292293 294295296297298299 private fun tryLegacyRawUnlock(password: String, slotA: StoredVault): UnlockResult? {300 val rawKey = VaultCrypto.deriveKeyRaw(password, unb64(slotA.salt))301 val payload = try {302 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), rawKey, VaultCrypto.AAD_SLOT_A))303 } catch (_: Exception) {304 VaultCrypto.zero(rawKey)305 return null306 }307 308 309 val newSalt = VaultCrypto.generateSalt()310 val newKey = VaultCrypto.deriveKey(password, newSalt)311 val healed = try {312 val blob = b64(VaultCrypto.encrypt(VaultCodec.encode(payload), newKey, VaultCrypto.AAD_SLOT_A))313 val next = StoredVault(314 version = slotA.version,315 salt = b64(newSalt),316 blob = blob,317 recoveryEscrow = slotA.recoveryEscrow,318 rootKeyEscrow = slotA.rootKeyEscrow,319 )320 if (store.writeSlotA(next)) {321 writeMatchingNoiseSlotB(next)322 store.stampLocalMutation()323 true324 } else {325 false326 }327 } catch (_: Exception) {328 false329 }330 return if (healed) {331 VaultCrypto.zero(rawKey)332 adoptSlotA(newKey, payload) 333 } else {334 VaultCrypto.zero(newKey)335 adoptSlotA(rawKey, payload) 336 }337 }338339 340 private fun adoptSlotA(key: ByteArray, payload: VaultPayload): UnlockResult {341 return try {342 derivedKey = key343 decoyMode = false344 entryList = payload.entries.toMutableList()345 duressConfigured = payload.duressConfigured346 recoveryWordHash = payload.recoveryWordHash347 recoveryWordsSet = payload.recoveryWordsSet348 _settings.value = store.loadSettings()349 ensureRootKey(payload)350 autoPurgeExpiredTrash()351 publish()352 _isUnlocked.value = true353 UnlockResult.Success354 } catch (e: Exception) {355 UnlockResult.Error(e.message ?: "unlock_failed")356 }357 }358359 360361 362363364365366367 class SlotAUnlock internal constructor(368 internal val key: ByteArray,369 internal val payload: VaultPayload,370 )371372 373374375376377378 fun tryUnlockSlotA(password: String): SlotAUnlock? {379 val slotA = store.loadSlotA() ?: return null380 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))381 return try {382 val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))383 SlotAUnlock(key, payload)384 } catch (_: Exception) {385 VaultCrypto.zero(key)386 null387 }388 }389390 391 suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {392 adoptSlotA(unlock.key, unlock.payload)393 }394395 396 fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)397398 399400 401402403404405 class DuressUnlock internal constructor(406 internal val key: ByteArray,407 internal val payload: VaultPayload,408 )409410 411412413414415416417 fun tryUnlockDuress(password: String): DuressUnlock? {418 val slot = store.loadDecoySlot() ?: return null419 val key = VaultCrypto.deriveKey(password, unb64(slot.salt))420 return try {421 val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A))422 DuressUnlock(key, payload)423 } catch (_: Exception) {424 VaultCrypto.zero(key)425 null426 }427 }428429 430 suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {431 return try {432 derivedKey = unlock.key433 decoyMode = true434 entryList = unlock.payload.entries.toMutableList()435 duressConfigured = false436 recoveryWordHash = unlock.payload.recoveryWordHash437 recoveryWordsSet = unlock.payload.recoveryWordsSet438 rootKey = if (unlock.payload.rootKeyB64.isNotBlank()) unb64(unlock.payload.rootKeyB64)439 else VaultCrypto.generateRootKey()440 _settings.value = store.loadSettings()441 publish()442 _isUnlocked.value = true443 UnlockResult.Success444 } catch (e: Exception) {445 UnlockResult.Error(e.message ?: "decoy_unlock_failed")446 }447 }448449 450 fun discardDuressUnlock(unlock: DuressUnlock) = VaultCrypto.zero(unlock.key)451452 453454455456457458 suspend fun setDuressPassphrase(duressPassphrase: String): Boolean = mutex.withLock {459 if (derivedKey == null || decoyMode) return false460 461 462 tryUnlockSlotA(duressPassphrase)?.let { discardSlotAUnlock(it); return false }463 return try {464 val salt = VaultCrypto.generateSalt()465 val key = VaultCrypto.deriveKey(duressPassphrase, salt)466 467 val decoyPayload = VaultPayload(entries = emptyList(), rootKeyB64 = b64(VaultCrypto.generateRootKey()))468 val plaintext = VaultCodec.encode(decoyPayload)469 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))470 VaultCrypto.zero(key)471 VaultCrypto.zero(plaintext)472 val ok = store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))473 if (ok) {474 duressConfigured = true475 runCatching { persistSlotA(bumpVersion = false) }476 }477 ok478 } catch (_: Exception) {479 false480 }481 }482483 484 suspend fun clearDuress(): Boolean = mutex.withLock {485 store.clearDecoySlot()486 if (derivedKey != null && !decoyMode) {487 duressConfigured = false488 runCatching { persistSlotA(bumpVersion = false) }489 }490 true491 }492493 494 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {495 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")496 return try {497 val payload = VaultCodec.decode(498 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),499 )500 derivedKey = key.copyOf()501 decoyMode = false502 entryList = payload.entries.toMutableList()503 duressConfigured = payload.duressConfigured504 recoveryWordHash = payload.recoveryWordHash505 recoveryWordsSet = payload.recoveryWordsSet506 _settings.value = store.loadSettings()507 ensureRootKey(payload)508 autoPurgeExpiredTrash()509 publish()510 _isUnlocked.value = true511 UnlockResult.Success512 } catch (_: Exception) {513 UnlockResult.WrongPassword514 }515 }516517 fun lock() {518 derivedKey?.let(VaultCrypto::zero)519 rootKey?.let(VaultCrypto::zero)520 derivedKey = null521 rootKey = null522 entryList = mutableListOf()523 duressConfigured = false524 recoveryWordHash = null525 recoveryWordsSet = false526 decoyMode = false527 _entries.value = emptyList()528 _isUnlocked.value = false529 }530531 @Volatile private var suppressNextBackgroundLock = false532533 534535536537538539540541542 fun expectTransientBackground() {543 suppressNextBackgroundLock = true544 }545546 547 fun consumeTransientBackgroundSuppression(): Boolean {548 val suppressed = suppressNextBackgroundLock549 suppressNextBackgroundLock = false550 return suppressed551 }552553 554555 556557558559560 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()561562 563 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }564565 566567568569570 suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {571 val key = derivedKey ?: return false572 if (decoyMode) return false573 val priorSlot = store.loadSlotA() ?: return false574 val priorRootKey = rootKey ?: return false575 val priorRecoveryHash = recoveryWordHash576 val priorRecoverySet = recoveryWordsSet577 val nextRootKey = generateRecoverableRootKey()578 val nextWords = rootKeyToWords(nextRootKey)579580 try {581 takeVaultSnapshot("local_save")582 rootKey = nextRootKey583 recoveryWordHash = recoveryWordsHash(nextWords)584 recoveryWordsSet = false585586 val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)587 ?: throw IllegalStateException("recovery_escrow_failed")588 val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)589 ?: throw IllegalStateException("root_escrow_failed")590 val plaintext = VaultCodec.encode(currentPayload())591 val blob = try {592 b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))593 } finally {594 VaultCrypto.zero(plaintext)595 }596 val nextSlot = priorSlot.copy(597 blob = blob,598 recoveryEscrow = nextRecoveryEscrow,599 rootKeyEscrow = nextRootKeyEscrow,600 )601 if (!store.writeSlotA(nextSlot)) throw IllegalStateException("storage_write_failed")602 try {603 writeMatchingNoiseSlotB(nextSlot)604 store.stampLocalMutation()605 } catch (e: Exception) {606 store.writeSlotA(priorSlot)607 throw e608 }609 VaultCrypto.zero(priorRootKey)610 publish()611 true612 } catch (_: Exception) {613 rootKey = priorRootKey614 recoveryWordHash = priorRecoveryHash615 recoveryWordsSet = priorRecoverySet616 VaultCrypto.zero(nextRootKey)617 store.writeSlotA(priorSlot)618 false619 }620 }621622 623624625626627 fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()628629 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {630 val slotA = store.loadSlotA() ?: return false631 return try {632 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))633 val payload = VaultCodec.decode(634 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),635 )636 val newSalt = VaultCrypto.generateSalt()637 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)638 639 val plaintext = VaultCodec.encode(payload)640 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))641 642 643 644 645 646 647 648 val next = StoredVault(649 version = slotA.version,650 salt = b64(newSalt),651 blob = blob,652 recoveryEscrow = slotA.recoveryEscrow,653 rootKeyEscrow = slotA.rootKeyEscrow,654 )655 if (!store.writeSlotA(next)) return false656 writeMatchingNoiseSlotB(next)657 store.stampLocalMutation()658 VaultCrypto.zero(oldKey)659 derivedKey?.let(VaultCrypto::zero)660 derivedKey = newKey661 true662 } catch (_: Exception) {663 false664 }665 }666667 668669670671 suspend fun destroyVault() = mutex.withLock {672 lock()673 store.clearVault()674 store.clearDecoySlot()675 }676677 678679 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {680 requireUnlocked()681 val stamp = VaultCrypto.monotonicEntryTimestamp()682 val now = System.currentTimeMillis()683 val entry = withDerivedLast4(draft.copy(684 id = draft.id.ifBlank { UUID.randomUUID().toString() },685 createdAt = if (draft.createdAt > 0) draft.createdAt else now,686 modifiedAt = stamp,687 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,688 ))689 val rollback = entryList.toMutableList()690 entryList.add(entry)691 persistOrRollback(rollback)692 entry693 }694695 696697698699700701702703704 suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {705 requireUnlocked()706 if (drafts.isEmpty()) return 0707 val rollback = entryList.toMutableList()708 val now = System.currentTimeMillis()709 for (draft in drafts) {710 val stamp = VaultCrypto.monotonicEntryTimestamp()711 entryList.add(712 withDerivedLast4(713 draft.copy(714 id = draft.id.ifBlank { UUID.randomUUID().toString() },715 createdAt = if (draft.createdAt > 0) draft.createdAt else now,716 modifiedAt = stamp,717 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,718 ),719 ),720 )721 }722 persistOrRollback(rollback)723 return drafts.size724 }725726 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {727 requireUnlocked()728 val idx = entryList.indexOfFirst { it.id == patch.id }729 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")730 val current = entryList[idx]731 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)732 733 val passwordChanged = patch.password != null && patch.password != current.password734 735 736 737 738 739 740 val priorPassword = current.password741 val shouldCapture = passwordChanged &&742 !priorPassword.isNullOrEmpty() &&743 current.passwordHistory?.firstOrNull()?.password != priorPassword744 val nextHistory = if (shouldCapture) {745 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +746 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)747 } else {748 current.passwordHistory749 }750 val updated = withDerivedLast4(patch.copy(751 createdAt = current.createdAt,752 modifiedAt = stamp,753 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,754 passwordHistory = nextHistory,755 ))756 val rollback = entryList.toMutableList()757 entryList[idx] = updated758 persistOrRollback(rollback)759 updated760 }761762 763 suspend fun deleteEntry(id: String) = mutex.withLock {764 requireUnlocked()765 val idx = entryList.indexOfFirst { it.id == id }766 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")767 val current = entryList[idx]768 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)769 val rollback = entryList.toMutableList()770 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)771 persistOrRollback(rollback)772 }773774 suspend fun restoreEntry(id: String) = mutex.withLock {775 requireUnlocked()776 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }777 if (idx == -1) throw IllegalStateException("deleted entry not found")778 val current = entryList[idx]779 val rollback = entryList.toMutableList()780 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))781 persistOrRollback(rollback)782 }783784 785 suspend fun purgeEntry(id: String) = mutex.withLock {786 requireUnlocked()787 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }788 if (idx == -1) throw IllegalStateException("deleted entry not found")789 val rollback = entryList.toMutableList()790 entryList.removeAt(idx)791 persistOrRollback(rollback)792 }793794 795 suspend fun purgeDeletedEntries(): Int = mutex.withLock {796 requireUnlocked()797 val rollback = entryList.toMutableList()798 val before = entryList.size799 entryList.removeAll { it.deletedAt != null }800 val removed = before - entryList.size801 if (removed > 0) persistOrRollback(rollback)802 removed803 }804805 806 suspend fun countDuplicateEntries(): Int = mutex.withLock {807 requireUnlocked()808 countDuplicateEntriesLocked()809 }810811 812813814815816 suspend fun deduplicateEntries(): Int = mutex.withLock {817 requireUnlocked()818 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")819 val active = entryList.filter { it.deletedAt == null }820 val keepIds = mutableSetOf<String>()821 active.groupBy { it.duplicateKey() }.values.forEach { group ->822 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id823 }824825 val rollback = entryList.toMutableList()826 var removed = 0827 entryList = entryList.map { entry ->828 if (entry.deletedAt == null && entry.id !in keepIds) {829 removed++830 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)831 entry.copy(deletedAt = stamp, modifiedAt = stamp)832 } else {833 entry834 }835 }.toMutableList()836 if (removed > 0) persistOrRollback(rollback)837 removed838 }839840 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }841 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }842 fun getDeletedEntries(): List<VaultEntry> =843 entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }844845 846 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {847 val active = entryList.filter { it.deletedAt == null }848 if (tagFilter == null) return active849 val needle = tagFilter.trim().lowercase()850 return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }851 }852853 854 fun getDistinctTags(): List<String> =855 entryList.asSequence()856 .filter { it.deletedAt == null }857 .flatMap { it.tags?.asSequence() ?: emptySequence() }858 .map { it.trim().lowercase() }859 .filter { it.isNotEmpty() }860 .distinct()861 .sorted()862 .toList()863864 865866867868869870 fun getDistinctFieldValues(field: String): List<String> {871 val select: (VaultEntry) -> String? = when (field) {872 "username" -> { e -> e.username }873 "email" -> { e -> e.email }874 else -> return emptyList()875 }876 return entryList.asSequence()877 .filter { it.deletedAt == null }878 .mapNotNull { select(it)?.trim() }879 .filter { it.isNotEmpty() }880 .groupingBy { it.lowercase() }881 .aggregate { _, acc: Pair<String, Int>?, value, _ ->882 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)883 }884 .values885 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })886 .map { it.first }887 }888889 fun getTombstones(): List<Tombstone> =890 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }891 fun getVaultVersion(): Long = store.version()892 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots893894 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {895 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false896 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false897 takeVaultSnapshot("restore")898 if (!store.writeSlotA(restoredA)) return false899 if (!store.writeSlotB(snapshot.vault_b)) return false900 store.stampLocalMutation()901 lock()902 true903 }904905 906907 908909910911912 suspend fun applyMergedRemoteEntries(913 remoteEntries: List<VaultEntry>,914 remoteTombstones: List<Tombstone>,915 ): Int = mutex.withLock {916 requireUnlocked()917 918 919 920 921 922 val mergeNow = System.currentTimeMillis()923 val clamped = remoteEntries.map { entry ->924 entry.copy(925 modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),926 deletedAt = entry.deletedAt?.let {927 SyncLimits.clampSyncTimestamp(it, mergeNow)928 },929 )930 }931 val tombMap = remoteTombstones.associate {932 it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)933 }934 var applied = 0935 val byId = entryList.associateBy { it.id }.toMutableMap()936937 for (remote in clamped) {938 val tomb = tombMap[remote.id]939 if (tomb != null && tomb >= remote.modifiedAt) continue940 val local = byId[remote.id]941 if (local == null) {942 entryList.add(remote); byId[remote.id] = remote; applied++943 } else if (remote.modifiedAt > local.modifiedAt) {944 val i = entryList.indexOfFirst { it.id == local.id }945 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }946 }947 }948949 for ((id, deletedAt) in tombMap) {950 val local = byId[id] ?: continue951 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue952 if (deletedAt < local.modifiedAt) continue953 val i = entryList.indexOfFirst { it.id == id }954 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }955 }956957 if (applied > 0) {958 persistSlotA(bumpVersion = false, snapshotReason = "sync_received")959 publish()960 }961 applied962 }963964 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {965 _settings.value = settings966 store.writeSettings(settings)967 }968969 970971 972 fun isRecoveryWordsSet(): Boolean = recoveryWordsSet973974 975976977978979 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {980 requireUnlocked()981 recoveryWordHash = recoveryWordsHash(words)982 recoveryWordsSet = true983 984 985 986 987 runCatching {988 persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))989 }.getOrDefault(false)990 }991992 993 fun verifyRecoveryWords(words: List<String>): Boolean {994 val stored = recoveryWordHash ?: return false995 return stored == recoveryWordsHash(words)996 }997998 9991000 1001 fun hasRecoveryEscrow(): Boolean =1002 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false10031004 100510061007100810091010101110121013101410151016 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {1017 val slotA = store.loadSlotA() ?: return false1018 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false10191020 1021 1022 slotA.recoveryEscrow?.let { escrow ->1023 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let1024 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))1025 val keyBytes = recoveryKey.encoded1026 try {1027 val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)1028 val payload = VaultCodec.decode(plaintext)1029 decoyMode = false1030 entryList = payload.entries.toMutableList()1031 duressConfigured = payload.duressConfigured1032 recoveryWordHash = payload.recoveryWordHash1033 recoveryWordsSet = payload.recoveryWordsSet1034 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)1035 else generateRecoverableRootKey()1036 _settings.value = store.loadSettings()1037 VaultCrypto.zero(plaintext)1038 return true1039 } catch (_: Exception) {1040 1041 } finally {1042 VaultCrypto.zero(material)1043 VaultCrypto.zero(keyBytes)1044 }1045 }10461047 1048 1049 1050 slotA.rootKeyEscrow?.let { escrow ->1051 val rk = unsealRootKeyEscrow(words, escrow) ?: return false1052 decoyMode = false1053 entryList = mutableListOf()1054 duressConfigured = false1055 recoveryWordHash = recoveryWordsHash(words)1056 recoveryWordsSet = true1057 rootKey = rk1058 _settings.value = store.loadSettings()1059 return true1060 }1061 return false1062 }10631064 106510661067106810691070107110721073 suspend fun resetPasswordWithRecoveryWords(1074 words: List<String>,1075 newPassword: String,1076 ): Boolean = mutex.withLock {1077 if (rootKey == null) return false 1078 return try {1079 val newSalt = VaultCrypto.generateSalt()1080 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)1081 val plaintext = VaultCodec.encode(currentPayload())1082 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1083 val prior = store.loadSlotA()1084 1085 1086 1087 val valid = words.size == 12 && findInvalidWords(words).isEmpty()1088 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow1089 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow1090 val next = StoredVault(1091 version = prior?.version ?: 1,1092 salt = b64(newSalt),1093 blob = blob,1094 recoveryEscrow = freshRecovery,1095 rootKeyEscrow = freshRootKey,1096 )1097 if (!store.writeSlotA(next)) return false1098 writeMatchingNoiseSlotB(next)1099 store.stampLocalMutation()1100 derivedKey?.let(VaultCrypto::zero)1101 derivedKey = newKey1102 VaultCrypto.zero(plaintext)1103 publish()1104 _isUnlocked.value = true1105 true1106 } catch (_: Exception) {1107 false1108 }1109 }11101111 111211131114111511161117 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {1118 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null1119 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1120 val salt = VaultCrypto.generateSalt()1121 val recoveryKey = deriveRecoveryKey(material, salt)1122 val keyBytes = recoveryKey.encoded1123 val plaintext = VaultCodec.encode(currentPayload())1124 return try {1125 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)1126 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))1127 } finally {1128 VaultCrypto.zero(material)1129 VaultCrypto.zero(keyBytes)1130 VaultCrypto.zero(plaintext)1131 }1132 }11331134 11351136113711381139114011411142 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {1143 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null1144 val rk = rootKey ?: return null1145 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1146 val salt = VaultCrypto.generateSalt()1147 val recoveryKey = deriveRecoveryKey(material, salt)1148 val keyBytes = recoveryKey.encoded1149 val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)1150 return try {1151 1152 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1153 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)1154 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)1155 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)1156 val ct = ctTag.copyOfRange(0, ctTag.size - 16)1157 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))1158 } finally {1159 VaultCrypto.zero(material)1160 VaultCrypto.zero(keyBytes)1161 VaultCrypto.zero(plaintext)1162 }1163 }11641165 1166 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {1167 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1168 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))1169 val keyBytes = recoveryKey.encoded1170 return try {1171 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)1172 val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1173 hexToRootKey(String(pt, Charsets.US_ASCII))1174 } catch (_: Exception) {1175 null1176 } finally {1177 VaultCrypto.zero(material)1178 VaultCrypto.zero(keyBytes)1179 }1180 }11811182 118311841185118611871188 private fun persistSlotAWithEscrows(1189 recoveryEscrow: RecoveryEscrow?,1190 rootKeyEscrow: RootKeyEscrow?,1191 ): Boolean {1192 val key = derivedKey ?: throw IllegalStateException("vault_locked")1193 if (decoyMode) return false1194 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1195 val plaintext = VaultCodec.encode(currentPayload())1196 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1197 val next = prior.copy(1198 blob = blob,1199 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,1200 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,1201 )1202 if (!store.writeSlotA(next)) return false1203 try {1204 writeMatchingNoiseSlotB(next)1205 } catch (e: Exception) {1206 store.writeSlotA(prior)1207 throw e1208 }1209 return true1210 }12111212 12131214 private fun requireUnlocked() {1215 if (derivedKey == null) throw IllegalStateException("vault_locked")1216 }12171218 private fun countDuplicateEntriesLocked(): Int {1219 val seen = mutableMapOf<String, VaultEntry>()1220 var duplicates = 01221 for (entry in entryList.filter { it.deletedAt == null }) {1222 val key = entry.duplicateKey()1223 val existing = seen[key]1224 if (existing == null) {1225 seen[key] = entry1226 } else {1227 duplicates++1228 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt1229 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt1230 if (entryStamp > existingStamp) seen[key] = entry1231 }1232 }1233 return duplicates1234 }12351236 private fun VaultEntry.duplicateKey(): String {1237 if (type == "note") return "note|${title.lowercase()}"1238 val passkeyData = passkey1239 if (passkeyData != null) {1240 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"1241 }1242 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"1243 }12441245 private fun takeVaultSnapshot(reason: String) {1246 runCatching {1247 val slotA = store.loadSlotA() ?: return1248 val vaultA = VaultCodec.encodeSlot(slotA)1249 val vaultB = store.loadSlotB() ?: slotA.blob1250 val history = store.loadVaultHistory()1251 val latest = history.snapshots.firstOrNull()1252 if (latest?.vault_a == vaultA && latest.vault_b == vaultB) return1253 val entryCount = if (derivedKey != null && !decoyMode) {1254 bucketEntryCount(entryList.count { it.deletedAt == null })1255 } else {1256 null1257 }1258 val snapshot = VaultSnapshot(1259 id = UUID.randomUUID().toString(),1260 savedAt = System.currentTimeMillis(),1261 reason = reason,1262 vault_a = vaultA,1263 vault_b = vaultB,1264 entryCount = entryCount,1265 )1266 store.writeVaultHistory(1267 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),1268 )1269 }1270 }12711272 private fun bucketEntryCount(n: Int): Int = when {1273 n <= 0 -> 01274 n <= 10 -> 101275 n <= 25 -> 251276 n <= 50 -> 501277 n <= 100 -> 1001278 n <= 250 -> 2501279 n <= 500 -> 5001280 else -> ((n + 499) / 500) * 5001281 }12821283 12841285128612871288 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {1289 if (!entry.isCard()) return entry1290 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""1291 return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)1292 }12931294 129512961297129812991300 private fun autoPurgeExpiredTrash() {1301 val days = _settings.value.trashRetentionDays ?: return1302 if (days <= 0) return1303 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L1304 val before = entryList.size1305 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }1306 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }1307 }13081309 1310 private fun currentPayload(): VaultPayload =1311 VaultPayload(1312 entries = entryList.toList(),1313 duressConfigured = duressConfigured,1314 rootKeyB64 = rootKey?.let(::b64) ?: "",1315 recoveryWordHash = recoveryWordHash,1316 recoveryWordsSet = recoveryWordsSet,1317 )13181319 13201321132213231324 private fun ensureRootKey(payload: VaultPayload) {1325 if (payload.rootKeyB64.isNotBlank()) {1326 rootKey = unb64(payload.rootKeyB64)1327 return1328 }1329 rootKey = generateRecoverableRootKey()1330 runCatching { persistSlotA(bumpVersion = false) }1331 }13321333 private fun publish() {1334 _entries.value = entryList.filter { it.deletedAt == null }1335 }13361337 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {1338 val plaintext = VaultCodec.encode(currentPayload())1339 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1340 return StoredVault(version = 1, salt = b64(salt), blob = blob)1341 }13421343 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {1344 1345 1346 1347 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)1348 val noise = ByteArray(approxBytes).also(rng::nextBytes)1349 store.writeSlotB(b64(noise))1350 }13511352 1353 private fun persistSlotA(bumpVersion: Boolean, snapshotReason: String? = "local_save"): Boolean {1354 val key = derivedKey ?: throw IllegalStateException("vault_locked")1355 1356 if (decoyMode) {1357 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")1358 val plaintext = VaultCodec.encode(currentPayload())1359 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1360 return store.writeDecoySlot(prior.copy(blob = blob))1361 }1362 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1363 if (snapshotReason != null) takeVaultSnapshot(snapshotReason)1364 val plaintext = VaultCodec.encode(currentPayload())1365 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1366 val next = prior.copy(blob = blob)1367 if (!store.writeSlotA(next)) return false1368 1369 1370 try {1371 writeMatchingNoiseSlotB(next)1372 if (bumpVersion) store.stampLocalMutation()1373 } catch (e: Exception) {1374 store.writeSlotA(prior)1375 throw e1376 }1377 return true1378 }13791380 1381 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {1382 try {1383 if (!persistSlotA(bumpVersion = true)) {1384 entryList = rollback1385 throw IllegalStateException("storage_write_failed")1386 }1387 } catch (e: Exception) {1388 entryList = rollback1389 throw e1390 }1391 publish()1392 }1393}