1package com.peachpasswords.vault23import kotlinx.coroutines.flow.MutableStateFlow4import kotlinx.coroutines.flow.StateFlow5import kotlinx.coroutines.flow.asStateFlow6import kotlinx.coroutines.sync.Mutex7import kotlinx.coroutines.sync.withLock8import java.security.SecureRandom9import java.util.Base6410import java.util.UUID11import javax.inject.Inject12import javax.inject.Singleton1314private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)15private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)161718private const val PASSWORD_HISTORY_MAX = 50192021private const val DECOY_SENTINEL = "peach_decoy_v1"2223sealed interface UnlockResult {24 data object Success : UnlockResult25 data object WrongPassword : UnlockResult26 data class Error(val reason: String) : UnlockResult27}2829sealed interface CreateVaultResult {30 data object Success : CreateVaultResult31 data class Error(val reason: String) : CreateVaultResult32}333435363738394041424344454647@Singleton48class VaultRepository @Inject constructor(49 private val store: VaultStorage,50) {51 private val mutex = Mutex()52 private val rng = SecureRandom()5354 private var derivedKey: ByteArray? = null55 private var rootKey: ByteArray? = null56 private var entryList: MutableList<VaultEntry> = mutableListOf()57 private var duressConfigured: Boolean = false58 private var recoveryWordHash: String? = null59 private var recoveryWordsSet: Boolean = false60 61 private var decoyMode: Boolean = false6263 private val _isUnlocked = MutableStateFlow(false)64 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6566 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())67 68 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()6970 private val _settings = MutableStateFlow(VaultSettings())71 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()7273 fun hasVault(): Boolean = store.hasVault()7475 7677 7879808182 fun codexVaultBlobBase64(): String? {83 val slotA = store.loadSlotA() ?: return null84 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""85 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))86 }8788 8990919293 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {94 return try {95 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)96 val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)97 ?: return UnlockResult.Error("invalid_codex_blob")98 val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")99 if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")100 writeMatchingNoiseSlotB(slotA)101 store.stampLocalMutation()102 unlockLocked(password)103 } catch (e: Exception) {104 UnlockResult.Error(e.message ?: "restore_failed")105 }106 }107108 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {109 return try {110 val salt = VaultCrypto.generateSalt()111 val key = VaultCrypto.deriveKey(password, salt)112 entryList = mutableListOf()113 duressConfigured = false114 recoveryWordHash = null115 recoveryWordsSet = false116 decoyMode = false117 rootKey = VaultCrypto.generateRootKey()118 val slotA = sealSlotA(key, salt)119 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")120 writeMatchingNoiseSlotB(slotA)121 store.stampLocalMutation()122 store.writeSettings(_settings.value)123 derivedKey = key124 publish()125 _isUnlocked.value = true126 CreateVaultResult.Success127 } catch (e: Exception) {128 CreateVaultResult.Error(e.message ?: "create_failed")129 }130 }131132 suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }133134 135 private fun unlockLocked(password: String): UnlockResult {136 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")137 return try {138 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))139 val payload = try {140 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))141 } catch (_: Exception) {142 VaultCrypto.zero(key)143 return UnlockResult.WrongPassword144 }145 derivedKey = key146 decoyMode = false147 entryList = payload.entries.toMutableList()148 duressConfigured = payload.duressConfigured149 recoveryWordHash = payload.recoveryWordHash150 recoveryWordsSet = payload.recoveryWordsSet151 _settings.value = store.loadSettings()152 ensureRootKey(payload)153 autoPurgeExpiredTrash()154 publish()155 _isUnlocked.value = true156 UnlockResult.Success157 } catch (e: Exception) {158 UnlockResult.Error(e.message ?: "unlock_failed")159 }160 }161162 163164165166167168 suspend fun unlockDecoy(): UnlockResult = mutex.withLock {169 return try {170 val existing = store.loadDecoySlot()171 if (existing == null) {172 val salt = VaultCrypto.generateSalt()173 val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)174 entryList = mutableListOf()175 duressConfigured = false176 recoveryWordHash = null177 recoveryWordsSet = false178 rootKey = VaultCrypto.generateRootKey()179 derivedKey = key180 decoyMode = true181 val plaintext = VaultCodec.encode(currentPayload())182 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))183 if (!store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob)))184 return UnlockResult.Error("storage_write_failed")185 } else {186 val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))187 val payload = VaultCodec.decode(188 VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),189 )190 derivedKey = key191 decoyMode = true192 entryList = payload.entries.toMutableList()193 duressConfigured = false194 recoveryWordHash = payload.recoveryWordHash195 recoveryWordsSet = payload.recoveryWordsSet196 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)197 else VaultCrypto.generateRootKey()198 }199 _settings.value = store.loadSettings()200 publish()201 _isUnlocked.value = true202 UnlockResult.Success203 } catch (e: Exception) {204 UnlockResult.Error(e.message ?: "decoy_unlock_failed")205 }206 }207208 209 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {210 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")211 return try {212 val payload = VaultCodec.decode(213 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),214 )215 derivedKey = key.copyOf()216 decoyMode = false217 entryList = payload.entries.toMutableList()218 duressConfigured = payload.duressConfigured219 recoveryWordHash = payload.recoveryWordHash220 recoveryWordsSet = payload.recoveryWordsSet221 _settings.value = store.loadSettings()222 ensureRootKey(payload)223 autoPurgeExpiredTrash()224 publish()225 _isUnlocked.value = true226 UnlockResult.Success227 } catch (_: Exception) {228 UnlockResult.WrongPassword229 }230 }231232 fun lock() {233 derivedKey?.let(VaultCrypto::zero)234 rootKey?.let(VaultCrypto::zero)235 derivedKey = null236 rootKey = null237 entryList = mutableListOf()238 duressConfigured = false239 recoveryWordHash = null240 recoveryWordsSet = false241 decoyMode = false242 _entries.value = emptyList()243 _isUnlocked.value = false244 }245246 247248 249250251252253 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()254255 256 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }257258 259260261262263 fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()264265 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {266 val slotA = store.loadSlotA() ?: return false267 return try {268 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))269 val payload = VaultCodec.decode(270 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),271 )272 val newSalt = VaultCrypto.generateSalt()273 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)274 275 val plaintext = VaultCodec.encode(payload)276 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))277 val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)278 if (!store.writeSlotA(next)) return false279 writeMatchingNoiseSlotB(next)280 store.stampLocalMutation()281 VaultCrypto.zero(oldKey)282 derivedKey?.let(VaultCrypto::zero)283 derivedKey = newKey284 true285 } catch (_: Exception) {286 false287 }288 }289290 291292293294 suspend fun destroyVault() = mutex.withLock {295 lock()296 store.clearVault()297 store.clearDecoySlot()298 }299300 301302 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {303 requireUnlocked()304 val stamp = VaultCrypto.monotonicEntryTimestamp()305 val now = System.currentTimeMillis()306 val entry = draft.copy(307 id = draft.id.ifBlank { UUID.randomUUID().toString() },308 createdAt = if (draft.createdAt > 0) draft.createdAt else now,309 modifiedAt = stamp,310 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,311 )312 val rollback = entryList.toMutableList()313 entryList.add(entry)314 persistOrRollback(rollback)315 entry316 }317318 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {319 requireUnlocked()320 val idx = entryList.indexOfFirst { it.id == patch.id }321 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")322 val current = entryList[idx]323 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)324 325 val passwordChanged = patch.password != null && patch.password != current.password326 327 328 329 330 331 332 val priorPassword = current.password333 val shouldCapture = passwordChanged &&334 !priorPassword.isNullOrEmpty() &&335 current.passwordHistory?.firstOrNull()?.password != priorPassword336 val nextHistory = if (shouldCapture) {337 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +338 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)339 } else {340 current.passwordHistory341 }342 val updated = patch.copy(343 createdAt = current.createdAt,344 modifiedAt = stamp,345 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,346 passwordHistory = nextHistory,347 )348 val rollback = entryList.toMutableList()349 entryList[idx] = updated350 persistOrRollback(rollback)351 updated352 }353354 355 suspend fun deleteEntry(id: String) = mutex.withLock {356 requireUnlocked()357 val idx = entryList.indexOfFirst { it.id == id }358 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")359 val current = entryList[idx]360 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)361 val rollback = entryList.toMutableList()362 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)363 persistOrRollback(rollback)364 }365366 suspend fun restoreEntry(id: String) = mutex.withLock {367 requireUnlocked()368 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }369 if (idx == -1) throw IllegalStateException("deleted entry not found")370 val current = entryList[idx]371 val rollback = entryList.toMutableList()372 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))373 persistOrRollback(rollback)374 }375376 377 suspend fun purgeEntry(id: String) = mutex.withLock {378 requireUnlocked()379 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }380 if (idx == -1) throw IllegalStateException("deleted entry not found")381 val rollback = entryList.toMutableList()382 entryList.removeAt(idx)383 persistOrRollback(rollback)384 }385386 387 suspend fun purgeDeletedEntries(): Int = mutex.withLock {388 requireUnlocked()389 val rollback = entryList.toMutableList()390 val before = entryList.size391 entryList.removeAll { it.deletedAt != null }392 val removed = before - entryList.size393 if (removed > 0) persistOrRollback(rollback)394 removed395 }396397 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }398 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }399 fun getDeletedEntries(): List<VaultEntry> =400 entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }401402 403 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {404 val active = entryList.filter { it.deletedAt == null }405 if (tagFilter == null) return active406 val needle = tagFilter.trim().lowercase()407 return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }408 }409410 411 fun getDistinctTags(): List<String> =412 entryList.asSequence()413 .filter { it.deletedAt == null }414 .flatMap { it.tags?.asSequence() ?: emptySequence() }415 .map { it.trim().lowercase() }416 .filter { it.isNotEmpty() }417 .distinct()418 .sorted()419 .toList()420421 422423424425426427 fun getDistinctFieldValues(field: String): List<String> {428 val select: (VaultEntry) -> String? = when (field) {429 "username" -> { e -> e.username }430 "email" -> { e -> e.email }431 else -> return emptyList()432 }433 return entryList.asSequence()434 .filter { it.deletedAt == null }435 .mapNotNull { select(it)?.trim() }436 .filter { it.isNotEmpty() }437 .groupingBy { it.lowercase() }438 .aggregate { _, acc: Pair<String, Int>?, value, _ ->439 Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)440 }441 .values442 .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })443 .map { it.first }444 }445446 fun getTombstones(): List<Tombstone> =447 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }448 fun getVaultVersion(): Long = store.version()449450 451452 453454455456457 suspend fun applyMergedRemoteEntries(458 remoteEntries: List<VaultEntry>,459 remoteTombstones: List<Tombstone>,460 ): Int = mutex.withLock {461 requireUnlocked()462 val tombMap = remoteTombstones.associate { it.id to it.deletedAt }463 var applied = 0464 val byId = entryList.associateBy { it.id }.toMutableMap()465466 for (remote in remoteEntries) {467 val tomb = tombMap[remote.id]468 if (tomb != null && tomb >= remote.modifiedAt) continue469 val local = byId[remote.id]470 if (local == null) {471 entryList.add(remote); byId[remote.id] = remote; applied++472 } else if (remote.modifiedAt > local.modifiedAt) {473 val i = entryList.indexOfFirst { it.id == local.id }474 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }475 }476 }477478 for ((id, deletedAt) in tombMap) {479 val local = byId[id] ?: continue480 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue481 if (deletedAt < local.modifiedAt) continue482 val i = entryList.indexOfFirst { it.id == id }483 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }484 }485486 if (applied > 0) {487 persistSlotA(bumpVersion = false)488 publish()489 }490 applied491 }492493 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {494 _settings.value = settings495 store.writeSettings(settings)496 }497498 499500 501 fun isRecoveryWordsSet(): Boolean = recoveryWordsSet502503 504505506507508 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {509 requireUnlocked()510 recoveryWordHash = recoveryWordsHash(words)511 recoveryWordsSet = true512 runCatching { persistSlotA(bumpVersion = false) }.getOrDefault(false)513 }514515 516 fun verifyRecoveryWords(words: List<String>): Boolean {517 val stored = recoveryWordHash ?: return false518 return stored == recoveryWordsHash(words)519 }520521 522523 private fun requireUnlocked() {524 if (derivedKey == null) throw IllegalStateException("vault_locked")525 }526527 528529530531532533 private fun autoPurgeExpiredTrash() {534 val days = _settings.value.trashRetentionDays ?: return535 if (days <= 0) return536 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L537 val before = entryList.size538 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }539 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }540 }541542 543 private fun currentPayload(): VaultPayload =544 VaultPayload(545 entries = entryList.toList(),546 duressConfigured = duressConfigured,547 rootKeyB64 = rootKey?.let(::b64) ?: "",548 recoveryWordHash = recoveryWordHash,549 recoveryWordsSet = recoveryWordsSet,550 )551552 553554555556557 private fun ensureRootKey(payload: VaultPayload) {558 if (payload.rootKeyB64.isNotBlank()) {559 rootKey = unb64(payload.rootKeyB64)560 return561 }562 rootKey = VaultCrypto.generateRootKey()563 runCatching { persistSlotA(bumpVersion = false) }564 }565566 private fun publish() {567 _entries.value = entryList.filter { it.deletedAt == null }568 }569570 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {571 val plaintext = VaultCodec.encode(currentPayload())572 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))573 return StoredVault(version = 1, salt = b64(salt), blob = blob)574 }575576 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {577 val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)578 val noise = ByteArray(approxBytes).also(rng::nextBytes)579 store.writeSlotB(b64(noise))580 }581582 583 private fun persistSlotA(bumpVersion: Boolean): Boolean {584 val key = derivedKey ?: throw IllegalStateException("vault_locked")585 586 if (decoyMode) {587 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")588 val plaintext = VaultCodec.encode(currentPayload())589 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))590 return store.writeDecoySlot(prior.copy(blob = blob))591 }592 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")593 val plaintext = VaultCodec.encode(currentPayload())594 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))595 val next = prior.copy(blob = blob)596 if (!store.writeSlotA(next)) return false597 598 599 try {600 writeMatchingNoiseSlotB(next)601 if (bumpVersion) store.stampLocalMutation()602 } catch (e: Exception) {603 store.writeSlotA(prior)604 throw e605 }606 return true607 }608609 610 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {611 try {612 if (!persistSlotA(bumpVersion = true)) {613 entryList = rollback614 throw IllegalStateException("storage_write_failed")615 }616 } catch (e: Exception) {617 entryList = rollback618 throw e619 }620 publish()621 }622}