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 = false5556 private val _isUnlocked = MutableStateFlow(false)57 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()5859 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())60 61 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()6263 private val _settings = MutableStateFlow(VaultSettings())64 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()6566 fun hasVault(): Boolean = store.hasVault()6768 6970 7172737475 fun codexVaultBlobBase64(): String? {76 val slotA = store.loadSlotA() ?: return null77 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""78 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))79 }8081 8283848586 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {87 return try {88 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)89 val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)90 ?: return UnlockResult.Error("invalid_codex_blob")91 val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")92 if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")93 writeMatchingNoiseSlotB(slotA)94 store.stampLocalMutation()95 unlockLocked(password)96 } catch (e: Exception) {97 UnlockResult.Error(e.message ?: "restore_failed")98 }99 }100101 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {102 return try {103 val salt = VaultCrypto.generateSalt()104 val key = VaultCrypto.deriveKey(password, salt)105 entryList = mutableListOf()106 duressConfigured = false107 rootKey = VaultCrypto.generateRootKey()108 val slotA = sealSlotA(key, salt)109 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")110 writeMatchingNoiseSlotB(slotA)111 store.stampLocalMutation()112 store.writeSettings(_settings.value)113 derivedKey = key114 publish()115 _isUnlocked.value = true116 CreateVaultResult.Success117 } catch (e: Exception) {118 CreateVaultResult.Error(e.message ?: "create_failed")119 }120 }121122 suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }123124 125 private fun unlockLocked(password: String): UnlockResult {126 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")127 return try {128 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))129 val payload = try {130 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))131 } catch (_: Exception) {132 VaultCrypto.zero(key)133 return UnlockResult.WrongPassword134 }135 derivedKey = key136 entryList = payload.entries.toMutableList()137 duressConfigured = payload.duressConfigured138 _settings.value = store.loadSettings()139 ensureRootKey(payload)140 publish()141 _isUnlocked.value = true142 UnlockResult.Success143 } catch (e: Exception) {144 UnlockResult.Error(e.message ?: "unlock_failed")145 }146 }147148 149 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {150 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")151 return try {152 val payload = VaultCodec.decode(153 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),154 )155 derivedKey = key.copyOf()156 entryList = payload.entries.toMutableList()157 duressConfigured = payload.duressConfigured158 _settings.value = store.loadSettings()159 ensureRootKey(payload)160 publish()161 _isUnlocked.value = true162 UnlockResult.Success163 } catch (_: Exception) {164 UnlockResult.WrongPassword165 }166 }167168 fun lock() {169 derivedKey?.let(VaultCrypto::zero)170 rootKey?.let(VaultCrypto::zero)171 derivedKey = null172 rootKey = null173 entryList = mutableListOf()174 duressConfigured = false175 _entries.value = emptyList()176 _isUnlocked.value = false177 }178179 180181 182183184185186 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()187188 189 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }190191 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {192 val slotA = store.loadSlotA() ?: return false193 return try {194 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))195 val payload = VaultCodec.decode(196 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),197 )198 val newSalt = VaultCrypto.generateSalt()199 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)200 201 val plaintext = VaultCodec.encode(payload)202 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))203 val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)204 if (!store.writeSlotA(next)) return false205 writeMatchingNoiseSlotB(next)206 store.stampLocalMutation()207 VaultCrypto.zero(oldKey)208 derivedKey?.let(VaultCrypto::zero)209 derivedKey = newKey210 true211 } catch (_: Exception) {212 false213 }214 }215216 217218219220 suspend fun destroyVault() = mutex.withLock {221 lock()222 store.clearVault()223 }224225 226227 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {228 requireUnlocked()229 val stamp = VaultCrypto.monotonicEntryTimestamp()230 val now = System.currentTimeMillis()231 val entry = draft.copy(232 id = draft.id.ifBlank { UUID.randomUUID().toString() },233 createdAt = if (draft.createdAt > 0) draft.createdAt else now,234 modifiedAt = stamp,235 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,236 )237 val rollback = entryList.toMutableList()238 entryList.add(entry)239 persistOrRollback(rollback)240 entry241 }242243 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {244 requireUnlocked()245 val idx = entryList.indexOfFirst { it.id == patch.id }246 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")247 val current = entryList[idx]248 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)249 250 val passwordChanged = patch.password != null && patch.password != current.password251 252 253 254 255 256 257 val priorPassword = current.password258 val shouldCapture = passwordChanged &&259 !priorPassword.isNullOrEmpty() &&260 current.passwordHistory?.firstOrNull()?.password != priorPassword261 val nextHistory = if (shouldCapture) {262 (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +263 (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)264 } else {265 current.passwordHistory266 }267 val updated = patch.copy(268 createdAt = current.createdAt,269 modifiedAt = stamp,270 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,271 passwordHistory = nextHistory,272 )273 val rollback = entryList.toMutableList()274 entryList[idx] = updated275 persistOrRollback(rollback)276 updated277 }278279 280 suspend fun deleteEntry(id: String) = mutex.withLock {281 requireUnlocked()282 val idx = entryList.indexOfFirst { it.id == id }283 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")284 val current = entryList[idx]285 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)286 val rollback = entryList.toMutableList()287 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)288 persistOrRollback(rollback)289 }290291 suspend fun restoreEntry(id: String) = mutex.withLock {292 requireUnlocked()293 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }294 if (idx == -1) throw IllegalStateException("deleted entry not found")295 val current = entryList[idx]296 val rollback = entryList.toMutableList()297 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))298 persistOrRollback(rollback)299 }300301 302 suspend fun purgeEntry(id: String) = mutex.withLock {303 requireUnlocked()304 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }305 if (idx == -1) throw IllegalStateException("deleted entry not found")306 val rollback = entryList.toMutableList()307 entryList.removeAt(idx)308 persistOrRollback(rollback)309 }310311 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }312 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }313 fun getDeletedEntries(): List<VaultEntry> = entryList.filter { it.deletedAt != null }314 fun getTombstones(): List<Tombstone> =315 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }316 fun getVaultVersion(): Long = store.version()317318 319320 321322323324325 suspend fun applyMergedRemoteEntries(326 remoteEntries: List<VaultEntry>,327 remoteTombstones: List<Tombstone>,328 ): Int = mutex.withLock {329 requireUnlocked()330 val tombMap = remoteTombstones.associate { it.id to it.deletedAt }331 var applied = 0332 val byId = entryList.associateBy { it.id }.toMutableMap()333334 for (remote in remoteEntries) {335 val tomb = tombMap[remote.id]336 if (tomb != null && tomb >= remote.modifiedAt) continue337 val local = byId[remote.id]338 if (local == null) {339 entryList.add(remote); byId[remote.id] = remote; applied++340 } else if (remote.modifiedAt > local.modifiedAt) {341 val i = entryList.indexOfFirst { it.id == local.id }342 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }343 }344 }345346 for ((id, deletedAt) in tombMap) {347 val local = byId[id] ?: continue348 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue349 if (deletedAt < local.modifiedAt) continue350 val i = entryList.indexOfFirst { it.id == id }351 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }352 }353354 if (applied > 0) {355 persistSlotA(bumpVersion = false)356 publish()357 }358 applied359 }360361 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {362 _settings.value = settings363 store.writeSettings(settings)364 }365366 367368 private fun requireUnlocked() {369 if (derivedKey == null) throw IllegalStateException("vault_locked")370 }371372 373 private fun currentPayload(): VaultPayload =374 VaultPayload(entryList.toList(), duressConfigured, rootKey?.let(::b64) ?: "")375376 377378379380381 private fun ensureRootKey(payload: VaultPayload) {382 if (payload.rootKeyB64.isNotBlank()) {383 rootKey = unb64(payload.rootKeyB64)384 return385 }386 rootKey = VaultCrypto.generateRootKey()387 runCatching { persistSlotA(bumpVersion = false) }388 }389390 private fun publish() {391 _entries.value = entryList.filter { it.deletedAt == null }392 }393394 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {395 val plaintext = VaultCodec.encode(currentPayload())396 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))397 return StoredVault(version = 1, salt = b64(salt), blob = blob)398 }399400 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {401 val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)402 val noise = ByteArray(approxBytes).also(rng::nextBytes)403 store.writeSlotB(b64(noise))404 }405406 407 private fun persistSlotA(bumpVersion: Boolean): Boolean {408 val key = derivedKey ?: throw IllegalStateException("vault_locked")409 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")410 val plaintext = VaultCodec.encode(currentPayload())411 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))412 val next = prior.copy(blob = blob)413 if (!store.writeSlotA(next)) return false414 415 416 try {417 writeMatchingNoiseSlotB(next)418 if (bumpVersion) store.stampLocalMutation()419 } catch (e: Exception) {420 store.writeSlotA(prior)421 throw e422 }423 return true424 }425426 427 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {428 try {429 if (!persistSlotA(bumpVersion = true)) {430 entryList = rollback431 throw IllegalStateException("storage_write_failed")432 }433 } catch (e: Exception) {434 entryList = rollback435 throw e436 }437 publish()438 }439}