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)1617sealed interface UnlockResult {18 data object Success : UnlockResult19 data object WrongPassword : UnlockResult20 data class Error(val reason: String) : UnlockResult21}2223sealed interface CreateVaultResult {24 data object Success : CreateVaultResult25 data class Error(val reason: String) : CreateVaultResult26}272829303132333435363738394041@Singleton42class VaultRepository @Inject constructor(43 private val store: VaultStorage,44) {45 private val mutex = Mutex()46 private val rng = SecureRandom()4748 private var derivedKey: ByteArray? = null49 private var rootKey: ByteArray? = null50 private var entryList: MutableList<VaultEntry> = mutableListOf()51 private var duressConfigured: Boolean = false5253 private val _isUnlocked = MutableStateFlow(false)54 val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()5556 private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())57 58 val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()5960 private val _settings = MutableStateFlow(VaultSettings())61 val settings: StateFlow<VaultSettings> = _settings.asStateFlow()6263 fun hasVault(): Boolean = store.hasVault()6465 6667 6869707172 fun codexVaultBlobBase64(): String? {73 val slotA = store.loadSlotA() ?: return null74 val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""75 return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))76 }7778 7980818283 suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {84 return try {85 val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)86 val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)87 ?: return UnlockResult.Error("invalid_codex_blob")88 val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")89 if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")90 writeMatchingNoiseSlotB(slotA)91 store.stampLocalMutation()92 unlockLocked(password)93 } catch (e: Exception) {94 UnlockResult.Error(e.message ?: "restore_failed")95 }96 }9798 suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {99 return try {100 val salt = VaultCrypto.generateSalt()101 val key = VaultCrypto.deriveKey(password, salt)102 entryList = mutableListOf()103 duressConfigured = false104 rootKey = VaultCrypto.generateRootKey()105 val slotA = sealSlotA(key, salt)106 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")107 writeMatchingNoiseSlotB(slotA)108 store.stampLocalMutation()109 store.writeSettings(_settings.value)110 derivedKey = key111 publish()112 _isUnlocked.value = true113 CreateVaultResult.Success114 } catch (e: Exception) {115 CreateVaultResult.Error(e.message ?: "create_failed")116 }117 }118119 suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }120121 122 private fun unlockLocked(password: String): UnlockResult {123 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")124 return try {125 val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))126 val payload = try {127 VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))128 } catch (_: Exception) {129 VaultCrypto.zero(key)130 return UnlockResult.WrongPassword131 }132 derivedKey = key133 entryList = payload.entries.toMutableList()134 duressConfigured = payload.duressConfigured135 _settings.value = store.loadSettings()136 ensureRootKey(payload)137 publish()138 _isUnlocked.value = true139 UnlockResult.Success140 } catch (e: Exception) {141 UnlockResult.Error(e.message ?: "unlock_failed")142 }143 }144145 146 suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {147 val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")148 return try {149 val payload = VaultCodec.decode(150 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),151 )152 derivedKey = key.copyOf()153 entryList = payload.entries.toMutableList()154 duressConfigured = payload.duressConfigured155 _settings.value = store.loadSettings()156 ensureRootKey(payload)157 publish()158 _isUnlocked.value = true159 UnlockResult.Success160 } catch (_: Exception) {161 UnlockResult.WrongPassword162 }163 }164165 fun lock() {166 derivedKey?.let(VaultCrypto::zero)167 rootKey?.let(VaultCrypto::zero)168 derivedKey = null169 rootKey = null170 entryList = mutableListOf()171 duressConfigured = false172 _entries.value = emptyList()173 _isUnlocked.value = false174 }175176 177178 179180181182183 fun syncMasterKey(): ByteArray? = rootKey?.copyOf()184185 186 fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }187188 suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {189 val slotA = store.loadSlotA() ?: return false190 return try {191 val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))192 val payload = VaultCodec.decode(193 VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),194 )195 val newSalt = VaultCrypto.generateSalt()196 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)197 198 val plaintext = VaultCodec.encode(payload)199 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))200 val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)201 if (!store.writeSlotA(next)) return false202 writeMatchingNoiseSlotB(next)203 store.stampLocalMutation()204 VaultCrypto.zero(oldKey)205 derivedKey?.let(VaultCrypto::zero)206 derivedKey = newKey207 true208 } catch (_: Exception) {209 false210 }211 }212213 214215216217 suspend fun destroyVault() = mutex.withLock {218 lock()219 store.clearVault()220 }221222 223224 suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {225 requireUnlocked()226 val stamp = VaultCrypto.monotonicEntryTimestamp()227 val now = System.currentTimeMillis()228 val entry = draft.copy(229 id = draft.id.ifBlank { UUID.randomUUID().toString() },230 createdAt = if (draft.createdAt > 0) draft.createdAt else now,231 modifiedAt = stamp,232 passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,233 )234 val rollback = entryList.toMutableList()235 entryList.add(entry)236 persistOrRollback(rollback)237 entry238 }239240 suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {241 requireUnlocked()242 val idx = entryList.indexOfFirst { it.id == patch.id }243 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")244 val current = entryList[idx]245 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)246 247 val passwordChanged = patch.password != null && patch.password != current.password248 val updated = patch.copy(249 createdAt = current.createdAt,250 modifiedAt = stamp,251 passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,252 )253 val rollback = entryList.toMutableList()254 entryList[idx] = updated255 persistOrRollback(rollback)256 updated257 }258259 260 suspend fun deleteEntry(id: String) = mutex.withLock {261 requireUnlocked()262 val idx = entryList.indexOfFirst { it.id == id }263 if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")264 val current = entryList[idx]265 val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)266 val rollback = entryList.toMutableList()267 entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)268 persistOrRollback(rollback)269 }270271 suspend fun restoreEntry(id: String) = mutex.withLock {272 requireUnlocked()273 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }274 if (idx == -1) throw IllegalStateException("deleted entry not found")275 val current = entryList[idx]276 val rollback = entryList.toMutableList()277 entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))278 persistOrRollback(rollback)279 }280281 282 suspend fun purgeEntry(id: String) = mutex.withLock {283 requireUnlocked()284 val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }285 if (idx == -1) throw IllegalStateException("deleted entry not found")286 val rollback = entryList.toMutableList()287 entryList.removeAt(idx)288 persistOrRollback(rollback)289 }290291 fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }292 fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }293 fun getDeletedEntries(): List<VaultEntry> = entryList.filter { it.deletedAt != null }294 fun getTombstones(): List<Tombstone> =295 entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }296 fun getVaultVersion(): Long = store.version()297298 299300 301302303304305 suspend fun applyMergedRemoteEntries(306 remoteEntries: List<VaultEntry>,307 remoteTombstones: List<Tombstone>,308 ): Int = mutex.withLock {309 requireUnlocked()310 val tombMap = remoteTombstones.associate { it.id to it.deletedAt }311 var applied = 0312 val byId = entryList.associateBy { it.id }.toMutableMap()313314 for (remote in remoteEntries) {315 val tomb = tombMap[remote.id]316 if (tomb != null && tomb >= remote.modifiedAt) continue317 val local = byId[remote.id]318 if (local == null) {319 entryList.add(remote); byId[remote.id] = remote; applied++320 } else if (remote.modifiedAt > local.modifiedAt) {321 val i = entryList.indexOfFirst { it.id == local.id }322 if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }323 }324 }325326 for ((id, deletedAt) in tombMap) {327 val local = byId[id] ?: continue328 if (local.deletedAt != null && local.deletedAt >= deletedAt) continue329 if (deletedAt < local.modifiedAt) continue330 val i = entryList.indexOfFirst { it.id == id }331 if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }332 }333334 if (applied > 0) {335 persistSlotA(bumpVersion = false)336 publish()337 }338 applied339 }340341 suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {342 _settings.value = settings343 store.writeSettings(settings)344 }345346 347348 private fun requireUnlocked() {349 if (derivedKey == null) throw IllegalStateException("vault_locked")350 }351352 353 private fun currentPayload(): VaultPayload =354 VaultPayload(entryList.toList(), duressConfigured, rootKey?.let(::b64) ?: "")355356 357358359360361 private fun ensureRootKey(payload: VaultPayload) {362 if (payload.rootKeyB64.isNotBlank()) {363 rootKey = unb64(payload.rootKeyB64)364 return365 }366 rootKey = VaultCrypto.generateRootKey()367 runCatching { persistSlotA(bumpVersion = false) }368 }369370 private fun publish() {371 _entries.value = entryList.filter { it.deletedAt == null }372 }373374 private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {375 val plaintext = VaultCodec.encode(currentPayload())376 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))377 return StoredVault(version = 1, salt = b64(salt), blob = blob)378 }379380 private fun writeMatchingNoiseSlotB(slotA: StoredVault) {381 val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)382 val noise = ByteArray(approxBytes).also(rng::nextBytes)383 store.writeSlotB(b64(noise))384 }385386 387 private fun persistSlotA(bumpVersion: Boolean): Boolean {388 val key = derivedKey ?: throw IllegalStateException("vault_locked")389 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")390 val plaintext = VaultCodec.encode(currentPayload())391 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))392 val next = prior.copy(blob = blob)393 if (!store.writeSlotA(next)) return false394 395 396 try {397 writeMatchingNoiseSlotB(next)398 if (bumpVersion) store.stampLocalMutation()399 } catch (e: Exception) {400 store.writeSlotA(prior)401 throw e402 }403 return true404 }405406 407 private fun persistOrRollback(rollback: MutableList<VaultEntry>) {408 try {409 if (!persistSlotA(bumpVersion = true)) {410 entryList = rollback411 throw IllegalStateException("storage_write_failed")412 }413 } catch (e: Exception) {414 entryList = rollback415 throw e416 }417 publish()418 }419}