VaultRepository.kt

14.2 KB · raw

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}2728/**29 * In-memory vault session backed by [VaultStore]. Faithful port of the browser30 * `vault.ts` semantics that matter for correctness:31 *32 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched33 *    noise blob so a fresh install shows two similarly-shaped records.34 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a35 *    deletion always wins last-write-wins against an in-flight edit.36 *  - Local writes bump the version counter; sync-applied writes do NOT (so a37 *    sync round never cascades into another outbound sync).38 *  - add/update/delete roll back in-memory state if the disk write fails.39 *  - destroyVault never touches the Pro license (separate store).40 */41@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 entryList: MutableList<VaultEntry> = mutableListOf()50    private var duressConfigured: Boolean = false5152    private val _isUnlocked = MutableStateFlow(false)53    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()5455    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())56    /** Active (non-deleted) entryList. */57    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()5859    private val _settings = MutableStateFlow(VaultSettings())60    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()6162    fun hasVault(): Boolean = store.hasVault()6364    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {65        return try {66            val salt = VaultCrypto.generateSalt()67            val key = VaultCrypto.deriveKey(password, salt)68            entryList = mutableListOf()69            duressConfigured = false70            val slotA = sealSlotA(key, salt)71            if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")72            writeMatchingNoiseSlotB(slotA)73            store.stampLocalMutation()74            store.writeSettings(_settings.value)75            derivedKey = key76            publish()77            _isUnlocked.value = true78            CreateVaultResult.Success79        } catch (e: Exception) {80            CreateVaultResult.Error(e.message ?: "create_failed")81        }82    }8384    suspend fun unlock(password: String): UnlockResult = mutex.withLock {85        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")86        return try {87            val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))88            val payload = try {89                VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))90            } catch (_: Exception) {91                VaultCrypto.zero(key)92                return UnlockResult.WrongPassword93            }94            derivedKey = key95            entryList = payload.entries.toMutableList()96            duressConfigured = payload.duressConfigured97            _settings.value = store.loadSettings()98            publish()99            _isUnlocked.value = true100            UnlockResult.Success101        } catch (e: Exception) {102            UnlockResult.Error(e.message ?: "unlock_failed")103        }104    }105106    /** Unlock with an already-derived AES-256 key (biometric path). */107    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {108        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")109        return try {110            val payload = VaultCodec.decode(111                VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),112            )113            derivedKey = key.copyOf()114            entryList = payload.entries.toMutableList()115            duressConfigured = payload.duressConfigured116            _settings.value = store.loadSettings()117            publish()118            _isUnlocked.value = true119            UnlockResult.Success120        } catch (_: Exception) {121            UnlockResult.WrongPassword122        }123    }124125    fun lock() {126        derivedKey?.let(VaultCrypto::zero)127        derivedKey = null128        entryList = mutableListOf()129        duressConfigured = false130        _entries.value = emptyList()131        _isUnlocked.value = false132    }133134    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {135        val slotA = store.loadSlotA() ?: return false136        return try {137            val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))138            val payload = VaultCodec.decode(139                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),140            )141            val newSalt = VaultCrypto.generateSalt()142            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)143            // Re-seal the existing payload under the new key/salt.144            val plaintext = VaultCodec.encode(payload)145            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))146            val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)147            if (!store.writeSlotA(next)) return false148            writeMatchingNoiseSlotB(next)149            store.stampLocalMutation()150            VaultCrypto.zero(oldKey)151            derivedKey?.let(VaultCrypto::zero)152            derivedKey = newKey153            true154        } catch (_: Exception) {155            false156        }157    }158159    /**160     * Irreversible wipe. Locks the session and clears every vault key. The Pro161     * license is in a separate store and is preserved by construction.162     */163    suspend fun destroyVault() = mutex.withLock {164        lock()165        store.clearVault()166    }167168    // ---- Entry CRUD -------------------------------------------------------169170    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {171        requireUnlocked()172        val stamp = VaultCrypto.monotonicEntryTimestamp()173        val now = System.currentTimeMillis()174        val entry = draft.copy(175            id = draft.id.ifBlank { UUID.randomUUID().toString() },176            createdAt = if (draft.createdAt > 0) draft.createdAt else now,177            modifiedAt = stamp,178            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,179        )180        val rollback = entryList.toMutableList()181        entryList.add(entry)182        persistOrRollback(rollback)183        entry184    }185186    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {187        requireUnlocked()188        val idx = entryList.indexOfFirst { it.id == patch.id }189        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")190        val current = entryList[idx]191        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)192        // Only refresh passwordChangedAt when the password value actually changes.193        val passwordChanged = patch.password != null && patch.password != current.password194        val updated = patch.copy(195            createdAt = current.createdAt,196            modifiedAt = stamp,197            passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,198        )199        val rollback = entryList.toMutableList()200        entryList[idx] = updated201        persistOrRollback(rollback)202        updated203    }204205    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */206    suspend fun deleteEntry(id: String) = mutex.withLock {207        requireUnlocked()208        val idx = entryList.indexOfFirst { it.id == id }209        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")210        val current = entryList[idx]211        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)212        val rollback = entryList.toMutableList()213        entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)214        persistOrRollback(rollback)215    }216217    suspend fun restoreEntry(id: String) = mutex.withLock {218        requireUnlocked()219        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }220        if (idx == -1) throw IllegalStateException("deleted entry not found")221        val current = entryList[idx]222        val rollback = entryList.toMutableList()223        entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))224        persistOrRollback(rollback)225    }226227    /** Permanent delete — no tombstone, no recovery. */228    suspend fun purgeEntry(id: String) = mutex.withLock {229        requireUnlocked()230        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }231        if (idx == -1) throw IllegalStateException("deleted entry not found")232        val rollback = entryList.toMutableList()233        entryList.removeAt(idx)234        persistOrRollback(rollback)235    }236237    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }238    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }239    fun getDeletedEntries(): List<VaultEntry> = entryList.filter { it.deletedAt != null }240    fun getTombstones(): List<Tombstone> =241        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }242    fun getVaultVersion(): Long = store.version()243244    // ---- Sync apply (does NOT advance the version) ------------------------245246    /**247     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists248     * WITHOUT bumping the version counter, so a sync round cannot cascade into249     * another outbound sync. Returns the number of locally-applied changes.250     */251    suspend fun applyMergedRemoteEntries(252        remoteEntries: List<VaultEntry>,253        remoteTombstones: List<Tombstone>,254    ): Int = mutex.withLock {255        requireUnlocked()256        val tombMap = remoteTombstones.associate { it.id to it.deletedAt }257        var applied = 0258        val byId = entryList.associateBy { it.id }.toMutableMap()259260        for (remote in remoteEntries) {261            val tomb = tombMap[remote.id]262            if (tomb != null && tomb >= remote.modifiedAt) continue263            val local = byId[remote.id]264            if (local == null) {265                entryList.add(remote); byId[remote.id] = remote; applied++266            } else if (remote.modifiedAt > local.modifiedAt) {267                val i = entryList.indexOfFirst { it.id == local.id }268                if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }269            }270        }271272        for ((id, deletedAt) in tombMap) {273            val local = byId[id] ?: continue274            if (local.deletedAt != null && local.deletedAt >= deletedAt) continue275            if (deletedAt < local.modifiedAt) continue276            val i = entryList.indexOfFirst { it.id == id }277            if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }278        }279280        if (applied > 0) {281            persistSlotA(bumpVersion = false)282            publish()283        }284        applied285    }286287    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {288        _settings.value = settings289        store.writeSettings(settings)290    }291292    // ---- Internals --------------------------------------------------------293294    private fun requireUnlocked() {295        if (derivedKey == null) throw IllegalStateException("vault_locked")296    }297298    private fun publish() {299        _entries.value = entryList.filter { it.deletedAt == null }300    }301302    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {303        val plaintext = VaultCodec.encode(VaultPayload(entryList.toList(), duressConfigured))304        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))305        return StoredVault(version = 1, salt = b64(salt), blob = blob)306    }307308    private fun writeMatchingNoiseSlotB(slotA: StoredVault) {309        val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)310        val noise = ByteArray(approxBytes).also(rng::nextBytes)311        store.writeSlotB(b64(noise))312    }313314    /** Re-seal slot A from the current in-memory state under the live key. */315    private fun persistSlotA(bumpVersion: Boolean): Boolean {316        val key = derivedKey ?: throw IllegalStateException("vault_locked")317        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")318        val plaintext = VaultCodec.encode(VaultPayload(entryList.toList(), duressConfigured))319        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))320        val next = prior.copy(blob = blob)321        if (!store.writeSlotA(next)) return false322        // Slot A committed — keep slot B size-matched, then advance the version323        // for local writes only. Restore slot A if a later step fails.324        try {325            writeMatchingNoiseSlotB(next)326            if (bumpVersion) store.stampLocalMutation()327        } catch (e: Exception) {328            store.writeSlotA(prior)329            throw e330        }331        return true332    }333334    /** Persist a local mutation, rolling the in-memory list back on failure. */335    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {336        try {337            if (!persistSlotA(bumpVersion = true)) {338                entryList = rollback339                throw IllegalStateException("storage_write_failed")340            }341        } catch (e: Exception) {342            entryList = rollback343            throw e344        }345        publish()346    }347}