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 561562563564565566567568569570571 fun syncMasterKey(): ByteArray? = if (decoyMode) null else rootKey?.copyOf()572573 574575576577578579580581582 fun sessionRootKey(): ByteArray? = rootKey?.copyOf()583584 585586 fun syncVaultId(): String? =587 if (decoyMode) null else rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }588589 590591592593594 suspend fun rotateSyncIdentity(): Boolean = mutex.withLock {595 val key = derivedKey ?: return false596 if (decoyMode) return false597 val priorSlot = store.loadSlotA() ?: return false598 val priorRootKey = rootKey ?: return false599 val priorRecoveryHash = recoveryWordHash600 val priorRecoverySet = recoveryWordsSet601 val nextRootKey = generateRecoverableRootKey()602 val nextWords = rootKeyToWords(nextRootKey)603604 try {605 takeVaultSnapshot("local_save")606 rootKey = nextRootKey607 recoveryWordHash = recoveryWordsHash(nextWords)608 recoveryWordsSet = false609610 val nextRecoveryEscrow = buildRecoveryEscrow(nextWords)611 ?: throw IllegalStateException("recovery_escrow_failed")612 val nextRootKeyEscrow = buildRootKeyEscrow(nextWords)613 ?: throw IllegalStateException("root_escrow_failed")614 val plaintext = VaultCodec.encode(currentPayload())615 val blob = try {616 b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))617 } finally {618 VaultCrypto.zero(plaintext)619 }620 val nextSlot = priorSlot.copy(621 blob = blob,622 recoveryEscrow = nextRecoveryEscrow,623 rootKeyEscrow = nextRootKeyEscrow,624 )625 if (!store.writeSlotA(nextSlot)) throw IllegalStateException("storage_write_failed")626 try {627 writeMatchingNoiseSlotB(nextSlot)628 store.stampLocalMutation()629 } catch (e: Exception) {630 store.writeSlotA(priorSlot)631 throw e632 }633 VaultCrypto.zero(priorRootKey)634 publish()635 true636 } catch (_: Exception) {637 rootKey = priorRootKey638 recoveryWordHash = priorRecoveryHash639 recoveryWordsSet = priorRecoverySet640 VaultCrypto.zero(nextRootKey)641 store.writeSlotA(priorSlot)642 false643 }644 }645646 647648649650651 fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()652653 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {654 val slotA = store.loadSlotA() ?: return false655 return try {656 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))657 val payload = VaultCodec.decode(658 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),659 )660 val newSalt = VaultCrypto.generateSalt()661 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)662 663 val plaintext = VaultCodec.encode(payload)664 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))665 666 667 668 669 670 671 672 val next = StoredVault(673 version = slotA.version,674 salt = b64(newSalt),675 blob = blob,676 recoveryEscrow = slotA.recoveryEscrow,677 rootKeyEscrow = slotA.rootKeyEscrow,678 )679 if (!store.writeSlotA(next)) return false680 writeMatchingNoiseSlotB(next)681 store.stampLocalMutation()682 VaultCrypto.zero(oldKey)683 derivedKey?.let(VaultCrypto::zero)684 derivedKey = newKey685 true686 } catch (_: Exception) {687 false688 }689 }690691 692693694695 suspend fun destroyVault() = mutex.withLock {696 lock()697 store.clearVault()698 store.clearDecoySlot()699 }700701 702703 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {704 requireUnlocked()705 val stamp = VaultCrypto.monotonicEntryTimestamp()706 val now = System.currentTimeMillis()707 val entry = withDerivedLast4(draft.copy(708 id = draft.id.ifBlank { UUID.randomUUID().toString() },709 createdAt = if (draft.createdAt > 0) draft.createdAt else now,710 modifiedAt = stamp,711 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,712 ))713 val rollback = entryList.toMutableList()714 entryList.add(entry)715 persistOrRollback(rollback)716 entry717 }718719 720721722723724725726727728 suspend fun addEntries(drafts: List<VaultEntry>): Int = mutex.withLock {729 requireUnlocked()730 if (drafts.isEmpty()) return 0731 val rollback = entryList.toMutableList()732 val now = System.currentTimeMillis()733 for (draft in drafts) {734 val stamp = VaultCrypto.monotonicEntryTimestamp()735 entryList.add(736 withDerivedLast4(737 draft.copy(738 id = draft.id.ifBlank { UUID.randomUUID().toString() },739 createdAt = if (draft.createdAt > 0) draft.createdAt else now,740 modifiedAt = stamp,741 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,742 ),743 ),744 )745 }746 persistOrRollback(rollback)747 return drafts.size748 }749750 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {751 requireUnlocked()752 val idx = entryList.indexOfFirst { it.id == patch.id }753 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")754 val current = entryList[idx]755 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)756 757 val passwordChanged = patch.password != null && patch.password != current.password758 759 760 761 762 763 764 val priorPassword = current.password765 val shouldCapture = passwordChanged &&766 !priorPassword.isNullOrEmpty() &&767 current.passwordHistory?.firstOrNull()?.password != priorPassword768 val nextHistory = if (shouldCapture) {769 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +770 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)771 } else {772 current.passwordHistory773 }774 val updated = withDerivedLast4(patch.copy(775 createdAt = current.createdAt,776 modifiedAt = stamp,777 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,778 passwordHistory = nextHistory,779 ))780 val rollback = entryList.toMutableList()781 entryList[idx] = updated782 persistOrRollback(rollback)783 updated784 }785786 787 suspend fun deleteEntry(id: String) = mutex.withLock {788 requireUnlocked()789 val idx = entryList.indexOfFirst { it.id == id }790 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")791 val current = entryList[idx]792 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)793 val rollback = entryList.toMutableList()794 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)795 persistOrRollback(rollback)796 }797798 suspend fun restoreEntry(id: String) = mutex.withLock {799 requireUnlocked()800 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }801 if (idx == -1) throw IllegalStateException("deleted entry not found")802 val current = entryList[idx]803 val rollback = entryList.toMutableList()804 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))805 persistOrRollback(rollback)806 }807808 809 suspend fun purgeEntry(id: String) = mutex.withLock {810 requireUnlocked()811 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }812 if (idx == -1) throw IllegalStateException("deleted entry not found")813 val rollback = entryList.toMutableList()814 entryList.removeAt(idx)815 persistOrRollback(rollback)816 }817818 819 suspend fun purgeDeletedEntries(): Int = mutex.withLock {820 requireUnlocked()821 val rollback = entryList.toMutableList()822 val before = entryList.size823 entryList.removeAll { it.deletedAt != null }824 val removed = before - entryList.size825 if (removed > 0) persistOrRollback(rollback)826 removed827 }828829 830 suspend fun countDuplicateEntries(): Int = mutex.withLock {831 requireUnlocked()832 countDuplicateEntriesLocked()833 }834835 836837838839840 suspend fun deduplicateEntries(): Int = mutex.withLock {841 requireUnlocked()842 if (decoyMode) throw IllegalStateException("deduplicate disabled in decoy mode")843 val active = entryList.filter { it.deletedAt == null }844 val keepIds = mutableSetOf<String>()845 active.groupBy { it.duplicateKey() }.values.forEach { group ->846 keepIds += group.maxBy { it.modifiedAt.takeIf { ts -> ts > 0 } ?: it.createdAt }.id847 }848849 val rollback = entryList.toMutableList()850 var removed = 0851 entryList = entryList.map { entry ->852 if (entry.deletedAt == null && entry.id !in keepIds) {853 removed++854 val stamp = VaultCrypto.monotonicEntryTimestamp(entry.modifiedAt)855 entry.copy(deletedAt = stamp, modifiedAt = stamp)856 } else {857 entry858 }859 }.toMutableList()860 if (removed > 0) persistOrRollback(rollback)861 removed862 }863864 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }865 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }866 fun getDeletedEntries(): List<VaultEntry> =867 entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }868869 870 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {871 val active = entryList.filter { it.deletedAt == null }872 if (tagFilter == null) return active873 val needle = tagFilter.trim().lowercase()874 return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }875 }876877 878 fun getDistinctTags(): List<String> =879 entryList.asSequence()880 .filter { it.deletedAt == null }881 .flatMap { it.tags?.asSequence() ?: emptySequence() }882 .map { it.trim().lowercase() }883 .filter { it.isNotEmpty() }884 .distinct()885 .sorted()886 .toList()887888 889890891892893894 fun getDistinctFieldValues(field: String): List<String> {895 val select: (VaultEntry) -> String? = when (field) {896 "username" -> { e -> e.username }897 "email" -> { e -> e.email }898 else -> return emptyList()899 }900 return entryList.asSequence()901 .filter { it.deletedAt == null }902 .mapNotNull { select(it)?.trim() }903 .filter { it.isNotEmpty() }904 .groupingBy { it.lowercase() }905 .aggregate { _, acc: Pair<String, Int>?, value, _ ->906 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)907 }908 .values909 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })910 .map { it.first }911 }912913 fun getTombstones(): List<Tombstone> =914 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }915 fun getVaultVersion(): Long = store.version()916 fun getVaultHistory(): List<VaultSnapshot> = store.loadVaultHistory().snapshots917918 suspend fun restoreVaultSnapshot(snapshotId: String): Boolean = mutex.withLock {919 val snapshot = store.loadVaultHistory().snapshots.firstOrNull { it.id == snapshotId } ?: return false920 val restoredA = VaultCodec.decodeSlot(snapshot.vault_a) ?: return false921 takeVaultSnapshot("restore")922 if (!store.writeSlotA(restoredA)) return false923 if (!store.writeSlotB(snapshot.vault_b)) return false924 store.stampLocalMutation()925 lock()926 true927 }928929 930931 932933934935936 suspend fun applyMergedRemoteEntries(937 remoteEntries: List<VaultEntry>,938 remoteTombstones: List<Tombstone>,939 ): Int = mutex.withLock {940 requireUnlocked()941 942 943 944 945 946 val mergeNow = System.currentTimeMillis()947 val clamped = remoteEntries.map { entry ->948 entry.copy(949 modifiedAt = SyncLimits.clampSyncTimestamp(entry.modifiedAt, mergeNow),950 deletedAt = entry.deletedAt?.let {951 SyncLimits.clampSyncTimestamp(it, mergeNow)952 },953 )954 }955 val tombMap = remoteTombstones.associate {956 it.id to SyncLimits.clampSyncTimestamp(it.deletedAt, mergeNow)957 }958 var applied = 0959 val byId = entryList.associateBy { it.id }.toMutableMap()960961 for (remote in clamped) {962 val tomb = tombMap[remote.id]963 if (tomb != null && tomb >= remote.modifiedAt) continue964 val local = byId[remote.id]965 if (local == null) {966 entryList.add(remote); byId[remote.id] = remote; applied++967 } else if (remote.modifiedAt > local.modifiedAt) {968 val i = entryList.indexOfFirst { it.id == local.id }969 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }970 }971 }972973 for ((id, deletedAt) in tombMap) {974 val local = byId[id] ?: continue975 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue976 if (deletedAt < local.modifiedAt) continue977 val i = entryList.indexOfFirst { it.id == id }978 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }979 }980981 if (applied > 0) {982 persistSlotA(bumpVersion = false, snapshotReason = "sync_received")983 publish()984 }985 applied986 }987988 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {989 _settings.value = settings990 store.writeSettings(settings)991 }992993 994995 996 fun isRecoveryWordsSet(): Boolean = recoveryWordsSet997998 9991000100110021003 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {1004 requireUnlocked()1005 recoveryWordHash = recoveryWordsHash(words)1006 recoveryWordsSet = true1007 1008 1009 1010 1011 runCatching {1012 persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))1013 }.getOrDefault(false)1014 }10151016 1017 fun verifyRecoveryWords(words: List<String>): Boolean {1018 val stored = recoveryWordHash ?: return false1019 return stored == recoveryWordsHash(words)1020 }10211022 10231024 1025 fun hasRecoveryEscrow(): Boolean =1026 store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false10271028 102910301031103210331034103510361037103810391040 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {1041 val slotA = store.loadSlotA() ?: return false1042 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false10431044 1045 1046 slotA.recoveryEscrow?.let { escrow ->1047 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let1048 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))1049 val keyBytes = recoveryKey.encoded1050 try {1051 val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)1052 val payload = VaultCodec.decode(plaintext)1053 decoyMode = false1054 entryList = payload.entries.toMutableList()1055 duressConfigured = payload.duressConfigured1056 recoveryWordHash = payload.recoveryWordHash1057 recoveryWordsSet = payload.recoveryWordsSet1058 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)1059 else generateRecoverableRootKey()1060 _settings.value = store.loadSettings()1061 VaultCrypto.zero(plaintext)1062 return true1063 } catch (_: Exception) {1064 1065 } finally {1066 VaultCrypto.zero(material)1067 VaultCrypto.zero(keyBytes)1068 }1069 }10701071 1072 1073 1074 slotA.rootKeyEscrow?.let { escrow ->1075 val rk = unsealRootKeyEscrow(words, escrow) ?: return false1076 decoyMode = false1077 entryList = mutableListOf()1078 duressConfigured = false1079 recoveryWordHash = recoveryWordsHash(words)1080 recoveryWordsSet = true1081 rootKey = rk1082 _settings.value = store.loadSettings()1083 return true1084 }1085 return false1086 }10871088 108910901091109210931094109510961097 suspend fun resetPasswordWithRecoveryWords(1098 words: List<String>,1099 newPassword: String,1100 ): Boolean = mutex.withLock {1101 if (rootKey == null) return false 1102 return try {1103 val newSalt = VaultCrypto.generateSalt()1104 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)1105 val plaintext = VaultCodec.encode(currentPayload())1106 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))1107 val prior = store.loadSlotA()1108 1109 1110 1111 val valid = words.size == 12 && findInvalidWords(words).isEmpty()1112 val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow1113 val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow1114 val next = StoredVault(1115 version = prior?.version ?: 1,1116 salt = b64(newSalt),1117 blob = blob,1118 recoveryEscrow = freshRecovery,1119 rootKeyEscrow = freshRootKey,1120 )1121 if (!store.writeSlotA(next)) return false1122 writeMatchingNoiseSlotB(next)1123 store.stampLocalMutation()1124 derivedKey?.let(VaultCrypto::zero)1125 derivedKey = newKey1126 VaultCrypto.zero(plaintext)1127 publish()1128 _isUnlocked.value = true1129 true1130 } catch (_: Exception) {1131 false1132 }1133 }11341135 113611371138113911401141 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {1142 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null1143 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1144 val salt = VaultCrypto.generateSalt()1145 val recoveryKey = deriveRecoveryKey(material, salt)1146 val keyBytes = recoveryKey.encoded1147 val plaintext = VaultCodec.encode(currentPayload())1148 return try {1149 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)1150 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))1151 } finally {1152 VaultCrypto.zero(material)1153 VaultCrypto.zero(keyBytes)1154 VaultCrypto.zero(plaintext)1155 }1156 }11571158 11591160116111621163116411651166 private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {1167 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null1168 val rk = rootKey ?: return null1169 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1170 val salt = VaultCrypto.generateSalt()1171 val recoveryKey = deriveRecoveryKey(material, salt)1172 val keyBytes = recoveryKey.encoded1173 val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)1174 return try {1175 1176 val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1177 val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)1178 val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)1179 val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)1180 val ct = ctTag.copyOfRange(0, ctTag.size - 16)1181 RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))1182 } finally {1183 VaultCrypto.zero(material)1184 VaultCrypto.zero(keyBytes)1185 VaultCrypto.zero(plaintext)1186 }1187 }11881189 1190 private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {1191 val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null1192 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))1193 val keyBytes = recoveryKey.encoded1194 return try {1195 val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)1196 val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)1197 hexToRootKey(String(pt, Charsets.US_ASCII))1198 } catch (_: Exception) {1199 null1200 } finally {1201 VaultCrypto.zero(material)1202 VaultCrypto.zero(keyBytes)1203 }1204 }12051206 120712081209121012111212 private fun persistSlotAWithEscrows(1213 recoveryEscrow: RecoveryEscrow?,1214 rootKeyEscrow: RootKeyEscrow?,1215 ): Boolean {1216 val key = derivedKey ?: throw IllegalStateException("vault_locked")1217 if (decoyMode) return false1218 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1219 val plaintext = VaultCodec.encode(currentPayload())1220 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1221 val next = prior.copy(1222 blob = blob,1223 recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,1224 rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,1225 )1226 if (!store.writeSlotA(next)) return false1227 try {1228 writeMatchingNoiseSlotB(next)1229 } catch (e: Exception) {1230 store.writeSlotA(prior)1231 throw e1232 }1233 return true1234 }12351236 12371238 private fun requireUnlocked() {1239 if (derivedKey == null) throw IllegalStateException("vault_locked")1240 }12411242 private fun countDuplicateEntriesLocked(): Int {1243 val seen = mutableMapOf<String, VaultEntry>()1244 var duplicates = 01245 for (entry in entryList.filter { it.deletedAt == null }) {1246 val key = entry.duplicateKey()1247 val existing = seen[key]1248 if (existing == null) {1249 seen[key] = entry1250 } else {1251 duplicates++1252 val entryStamp = entry.modifiedAt.takeIf { it > 0 } ?: entry.createdAt1253 val existingStamp = existing.modifiedAt.takeIf { it > 0 } ?: existing.createdAt1254 if (entryStamp > existingStamp) seen[key] = entry1255 }1256 }1257 return duplicates1258 }12591260 private fun VaultEntry.duplicateKey(): String {1261 if (type == "note") return "note|${title.lowercase()}"1262 val passkeyData = passkey1263 if (passkeyData != null) {1264 return "passkey|${passkeyData.rpId.lowercase()}|${passkeyData.userName.lowercase()}"1265 }1266 return "login|${title.lowercase()}|${url.orEmpty().lowercase()}|${username.orEmpty().lowercase()}"1267 }12681269 private fun takeVaultSnapshot(reason: String) {1270 runCatching {1271 val slotA = store.loadSlotA() ?: return1272 val vaultA = VaultCodec.encodeSlot(slotA)1273 val vaultB = store.loadSlotB() ?: slotA.blob1274 val history = store.loadVaultHistory()1275 val latest = history.snapshots.firstOrNull()1276 if (latest?.vault_a == vaultA && latest.vault_b == vaultB) return1277 val entryCount = if (derivedKey != null && !decoyMode) {1278 bucketEntryCount(entryList.count { it.deletedAt == null })1279 } else {1280 null1281 }1282 val snapshot = VaultSnapshot(1283 id = UUID.randomUUID().toString(),1284 savedAt = System.currentTimeMillis(),1285 reason = reason,1286 vault_a = vaultA,1287 vault_b = vaultB,1288 entryCount = entryCount,1289 )1290 store.writeVaultHistory(1291 history.copy(snapshots = (listOf(snapshot) + history.snapshots).take(VAULT_HISTORY_MAX)),1292 )1293 }1294 }12951296 private fun bucketEntryCount(n: Int): Int = when {1297 n <= 0 -> 01298 n <= 10 -> 101299 n <= 25 -> 251300 n <= 50 -> 501301 n <= 100 -> 1001302 n <= 250 -> 2501303 n <= 500 -> 5001304 else -> ((n + 499) / 500) * 5001305 }13061307 13081309131013111312 private fun withDerivedLast4(entry: VaultEntry): VaultEntry {1313 if (!entry.isCard()) return entry1314 val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""1315 return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)1316 }13171318 131913201321132213231324 private fun autoPurgeExpiredTrash() {1325 val days = _settings.value.trashRetentionDays ?: return1326 if (days <= 0) return1327 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L1328 val before = entryList.size1329 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }1330 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }1331 }13321333 1334 private fun currentPayload(): VaultPayload =1335 VaultPayload(1336 entries = entryList.toList(),1337 duressConfigured = duressConfigured,1338 rootKeyB64 = rootKey?.let(::b64) ?: "",1339 recoveryWordHash = recoveryWordHash,1340 recoveryWordsSet = recoveryWordsSet,1341 )13421343 13441345134613471348 private fun ensureRootKey(payload: VaultPayload) {1349 if (payload.rootKeyB64.isNotBlank()) {1350 rootKey = unb64(payload.rootKeyB64)1351 return1352 }1353 rootKey = generateRecoverableRootKey()1354 runCatching { persistSlotA(bumpVersion = false) }1355 }13561357 private fun publish() {1358 _entries.value = entryList.filter { it.deletedAt == null }1359 }13601361 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {1362 val plaintext = VaultCodec.encode(currentPayload())1363 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1364 return StoredVault(version = 1, salt = b64(salt), blob = blob)1365 }13661367 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {1368 1369 1370 1371 val approxBytes = (slotA.blob.length * 3 / 4).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)1372 val noise = ByteArray(approxBytes).also(rng::nextBytes)1373 store.writeSlotB(b64(noise))1374 }13751376 1377 private fun persistSlotA(bumpVersion: Boolean, snapshotReason: String? = "local_save"): Boolean {1378 val key = derivedKey ?: throw IllegalStateException("vault_locked")1379 1380 if (decoyMode) {1381 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")1382 val plaintext = VaultCodec.encode(currentPayload())1383 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1384 return store.writeDecoySlot(prior.copy(blob = blob))1385 }1386 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")1387 if (snapshotReason != null) takeVaultSnapshot(snapshotReason)1388 val plaintext = VaultCodec.encode(currentPayload())1389 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))1390 val next = prior.copy(blob = blob)1391 if (!store.writeSlotA(next)) return false1392 1393 1394 try {1395 writeMatchingNoiseSlotB(next)1396 if (bumpVersion) store.stampLocalMutation()1397 } catch (e: Exception) {1398 store.writeSlotA(prior)1399 throw e1400 }1401 return true1402 }14031404 1405 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {1406 try {1407 if (!persistSlotA(bumpVersion = true)) {1408 entryList = rollback1409 throw IllegalStateException("storage_write_failed")1410 }1411 } catch (e: Exception) {1412 entryList = rollback1413 throw e1414 }1415 publish()1416 }1417}