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 = 501920sealed interface UnlockResult {21 data object Success : UnlockResult22 data object WrongPassword : UnlockResult23 data class Error(val reason: String) : UnlockResult24}2526sealed interface CreateVaultResult {27 data object Success : CreateVaultResult28 data class Error(val reason: String) : CreateVaultResult29}303132333435363738394041424344@Singleton45class VaultRepository @Inject constructor(46 private val store: VaultStorage,47) {48 private val mutex = Mutex()49 private val rng = SecureRandom()5051 private var derivedKey: ByteArray? = null52 private var rootKey: ByteArray? = null53 private var entryList: MutableList<VaultEntry> = mutableListOf()54 private var duressConfigured: Boolean = false55 private var recoveryWordHash: String? = null56 private var recoveryWordsSet: Boolean = false5758 private val _isUnlocked = MutableStateFlow(false)59 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6061 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())62 63 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()6465 private val _settings = MutableStateFlow(VaultSettings())66 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()6768 fun hasVault(): Boolean = store.hasVault()6970 7172 7374757677 fun codexVaultBlobBase64(): String? {78 val slotA = store.loadSlotA() ?: return null79 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""80 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))81 }8283 8485868788 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {89 return try {90 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)91 val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)92 ?: return UnlockResult.Error("invalid_codex_blob")93 val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")94 if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")95 writeMatchingNoiseSlotB(slotA)96 store.stampLocalMutation()97 unlockLocked(password)98 } catch (e: Exception) {99 UnlockResult.Error(e.message ?: "restore_failed")100 }101 }102103 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {104 return try {105 val salt = VaultCrypto.generateSalt()106 val key = VaultCrypto.deriveKey(password, salt)107 entryList = mutableListOf()108 duressConfigured = false109 recoveryWordHash = null110 recoveryWordsSet = false111 rootKey = VaultCrypto.generateRootKey()112 val slotA = sealSlotA(key, salt)113 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")114 writeMatchingNoiseSlotB(slotA)115 store.stampLocalMutation()116 store.writeSettings(_settings.value)117 derivedKey = key118 publish()119 _isUnlocked.value = true120 CreateVaultResult.Success121 } catch (e: Exception) {122 CreateVaultResult.Error(e.message ?: "create_failed")123 }124 }125126 suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }127128 129 private fun unlockLocked(password: String): UnlockResult {130 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")131 return try {132 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))133 val payload = try {134 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))135 } catch (_: Exception) {136 VaultCrypto.zero(key)137 return UnlockResult.WrongPassword138 }139 derivedKey = key140 entryList = payload.entries.toMutableList()141 duressConfigured = payload.duressConfigured142 recoveryWordHash = payload.recoveryWordHash143 recoveryWordsSet = payload.recoveryWordsSet144 _settings.value = store.loadSettings()145 ensureRootKey(payload)146 autoPurgeExpiredTrash()147 publish()148 _isUnlocked.value = true149 UnlockResult.Success150 } catch (e: Exception) {151 UnlockResult.Error(e.message ?: "unlock_failed")152 }153 }154155 156 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {157 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")158 return try {159 val payload = VaultCodec.decode(160 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),161 )162 derivedKey = key.copyOf()163 entryList = payload.entries.toMutableList()164 duressConfigured = payload.duressConfigured165 recoveryWordHash = payload.recoveryWordHash166 recoveryWordsSet = payload.recoveryWordsSet167 _settings.value = store.loadSettings()168 ensureRootKey(payload)169 autoPurgeExpiredTrash()170 publish()171 _isUnlocked.value = true172 UnlockResult.Success173 } catch (_: Exception) {174 UnlockResult.WrongPassword175 }176 }177178 fun lock() {179 derivedKey?.let(VaultCrypto::zero)180 rootKey?.let(VaultCrypto::zero)181 derivedKey = null182 rootKey = null183 entryList = mutableListOf()184 duressConfigured = false185 recoveryWordHash = null186 recoveryWordsSet = false187 _entries.value = emptyList()188 _isUnlocked.value = false189 }190191 192193 194195196197198 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()199200 201 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }202203 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {204 val slotA = store.loadSlotA() ?: return false205 return try {206 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))207 val payload = VaultCodec.decode(208 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),209 )210 val newSalt = VaultCrypto.generateSalt()211 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)212 213 val plaintext = VaultCodec.encode(payload)214 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))215 val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)216 if (!store.writeSlotA(next)) return false217 writeMatchingNoiseSlotB(next)218 store.stampLocalMutation()219 VaultCrypto.zero(oldKey)220 derivedKey?.let(VaultCrypto::zero)221 derivedKey = newKey222 true223 } catch (_: Exception) {224 false225 }226 }227228 229230231232 suspend fun destroyVault() = mutex.withLock {233 lock()234 store.clearVault()235 }236237 238239 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {240 requireUnlocked()241 val stamp = VaultCrypto.monotonicEntryTimestamp()242 val now = System.currentTimeMillis()243 val entry = draft.copy(244 id = draft.id.ifBlank { UUID.randomUUID().toString() },245 createdAt = if (draft.createdAt > 0) draft.createdAt else now,246 modifiedAt = stamp,247 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,248 )249 val rollback = entryList.toMutableList()250 entryList.add(entry)251 persistOrRollback(rollback)252 entry253 }254255 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {256 requireUnlocked()257 val idx = entryList.indexOfFirst { it.id == patch.id }258 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")259 val current = entryList[idx]260 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)261 262 val passwordChanged = patch.password != null && patch.password != current.password263 264 265 266 267 268 269 val priorPassword = current.password270 val shouldCapture = passwordChanged &&271 !priorPassword.isNullOrEmpty() &&272 current.passwordHistory?.firstOrNull()?.password != priorPassword273 val nextHistory = if (shouldCapture) {274 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +275 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)276 } else {277 current.passwordHistory278 }279 val updated = patch.copy(280 createdAt = current.createdAt,281 modifiedAt = stamp,282 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,283 passwordHistory = nextHistory,284 )285 val rollback = entryList.toMutableList()286 entryList[idx] = updated287 persistOrRollback(rollback)288 updated289 }290291 292 suspend fun deleteEntry(id: String) = mutex.withLock {293 requireUnlocked()294 val idx = entryList.indexOfFirst { it.id == id }295 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")296 val current = entryList[idx]297 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)298 val rollback = entryList.toMutableList()299 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)300 persistOrRollback(rollback)301 }302303 suspend fun restoreEntry(id: String) = mutex.withLock {304 requireUnlocked()305 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }306 if (idx == -1) throw IllegalStateException("deleted entry not found")307 val current = entryList[idx]308 val rollback = entryList.toMutableList()309 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))310 persistOrRollback(rollback)311 }312313 314 suspend fun purgeEntry(id: String) = mutex.withLock {315 requireUnlocked()316 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }317 if (idx == -1) throw IllegalStateException("deleted entry not found")318 val rollback = entryList.toMutableList()319 entryList.removeAt(idx)320 persistOrRollback(rollback)321 }322323 324 suspend fun purgeDeletedEntries(): Int = mutex.withLock {325 requireUnlocked()326 val rollback = entryList.toMutableList()327 val before = entryList.size328 entryList.removeAll { it.deletedAt != null }329 val removed = before - entryList.size330 if (removed > 0) persistOrRollback(rollback)331 removed332 }333334 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }335 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }336 fun getDeletedEntries(): List<VaultEntry> =337 entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }338339 340 fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {341 val active = entryList.filter { it.deletedAt == null }342 if (tagFilter == null) return active343 val needle = tagFilter.trim().lowercase()344 return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }345 }346347 348 fun getDistinctTags(): List<String> =349 entryList.asSequence()350 .filter { it.deletedAt == null }351 .flatMap { it.tags?.asSequence() ?: emptySequence() }352 .map { it.trim().lowercase() }353 .filter { it.isNotEmpty() }354 .distinct()355 .sorted()356 .toList()357 fun getTombstones(): List<Tombstone> =358 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }359 fun getVaultVersion(): Long = store.version()360361 362363 364365366367368 suspend fun applyMergedRemoteEntries(369 remoteEntries: List<VaultEntry>,370 remoteTombstones: List<Tombstone>,371 ): Int = mutex.withLock {372 requireUnlocked()373 val tombMap = remoteTombstones.associate { it.id to it.deletedAt }374 var applied = 0375 val byId = entryList.associateBy { it.id }.toMutableMap()376377 for (remote in remoteEntries) {378 val tomb = tombMap[remote.id]379 if (tomb != null && tomb >= remote.modifiedAt) continue380 val local = byId[remote.id]381 if (local == null) {382 entryList.add(remote); byId[remote.id] = remote; applied++383 } else if (remote.modifiedAt > local.modifiedAt) {384 val i = entryList.indexOfFirst { it.id == local.id }385 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }386 }387 }388389 for ((id, deletedAt) in tombMap) {390 val local = byId[id] ?: continue391 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue392 if (deletedAt < local.modifiedAt) continue393 val i = entryList.indexOfFirst { it.id == id }394 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }395 }396397 if (applied > 0) {398 persistSlotA(bumpVersion = false)399 publish()400 }401 applied402 }403404 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {405 _settings.value = settings406 store.writeSettings(settings)407 }408409 410411 412 fun isRecoveryWordsSet(): Boolean = recoveryWordsSet413414 415416417418419 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {420 requireUnlocked()421 recoveryWordHash = recoveryWordsHash(words)422 recoveryWordsSet = true423 runCatching { persistSlotA(bumpVersion = false) }.getOrDefault(false)424 }425426 427 fun verifyRecoveryWords(words: List<String>): Boolean {428 val stored = recoveryWordHash ?: return false429 return stored == recoveryWordsHash(words)430 }431432 433434 private fun requireUnlocked() {435 if (derivedKey == null) throw IllegalStateException("vault_locked")436 }437438 439440441442443444 private fun autoPurgeExpiredTrash() {445 val days = _settings.value.trashRetentionDays ?: return446 if (days <= 0) return447 val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L448 val before = entryList.size449 entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }450 if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }451 }452453 454 private fun currentPayload(): VaultPayload =455 VaultPayload(456 entries = entryList.toList(),457 duressConfigured = duressConfigured,458 rootKeyB64 = rootKey?.let(::b64) ?: "",459 recoveryWordHash = recoveryWordHash,460 recoveryWordsSet = recoveryWordsSet,461 )462463 464465466467468 private fun ensureRootKey(payload: VaultPayload) {469 if (payload.rootKeyB64.isNotBlank()) {470 rootKey = unb64(payload.rootKeyB64)471 return472 }473 rootKey = VaultCrypto.generateRootKey()474 runCatching { persistSlotA(bumpVersion = false) }475 }476477 private fun publish() {478 _entries.value = entryList.filter { it.deletedAt == null }479 }480481 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {482 val plaintext = VaultCodec.encode(currentPayload())483 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))484 return StoredVault(version = 1, salt = b64(salt), blob = blob)485 }486487 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {488 val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)489 val noise = ByteArray(approxBytes).also(rng::nextBytes)490 store.writeSlotB(b64(noise))491 }492493 494 private fun persistSlotA(bumpVersion: Boolean): Boolean {495 val key = derivedKey ?: throw IllegalStateException("vault_locked")496 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")497 val plaintext = VaultCodec.encode(currentPayload())498 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))499 val next = prior.copy(blob = blob)500 if (!store.writeSlotA(next)) return false501 502 503 try {504 writeMatchingNoiseSlotB(next)505 if (bumpVersion) store.stampLocalMutation()506 } catch (e: Exception) {507 store.writeSlotA(prior)508 throw e509 }510 return true511 }512513 514 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {515 try {516 if (!persistSlotA(bumpVersion = true)) {517 entryList = rollback518 throw IllegalStateException("storage_write_failed")519 }520 } catch (e: Exception) {521 entryList = rollback522 throw e523 }524 publish()525 }526}