VaultRepository.kt

15.6 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 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    /** Active (non-deleted) entryList. */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    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {66        return try {67            val salt = VaultCrypto.generateSalt()68            val key = VaultCrypto.deriveKey(password, salt)69            entryList = mutableListOf()70            duressConfigured = false71            rootKey = VaultCrypto.generateRootKey()72            val slotA = sealSlotA(key, salt)73            if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")74            writeMatchingNoiseSlotB(slotA)75            store.stampLocalMutation()76            store.writeSettings(_settings.value)77            derivedKey = key78            publish()79            _isUnlocked.value = true80            CreateVaultResult.Success81        } catch (e: Exception) {82            CreateVaultResult.Error(e.message ?: "create_failed")83        }84    }8586    suspend fun unlock(password: String): UnlockResult = mutex.withLock {87        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")88        return try {89            val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))90            val payload = try {91                VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))92            } catch (_: Exception) {93                VaultCrypto.zero(key)94                return UnlockResult.WrongPassword95            }96            derivedKey = key97            entryList = payload.entries.toMutableList()98            duressConfigured = payload.duressConfigured99            _settings.value = store.loadSettings()100            ensureRootKey(payload)101            publish()102            _isUnlocked.value = true103            UnlockResult.Success104        } catch (e: Exception) {105            UnlockResult.Error(e.message ?: "unlock_failed")106        }107    }108109    /** Unlock with an already-derived AES-256 key (biometric path). */110    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {111        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")112        return try {113            val payload = VaultCodec.decode(114                VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),115            )116            derivedKey = key.copyOf()117            entryList = payload.entries.toMutableList()118            duressConfigured = payload.duressConfigured119            _settings.value = store.loadSettings()120            ensureRootKey(payload)121            publish()122            _isUnlocked.value = true123            UnlockResult.Success124        } catch (_: Exception) {125            UnlockResult.WrongPassword126        }127    }128129    fun lock() {130        derivedKey?.let(VaultCrypto::zero)131        rootKey?.let(VaultCrypto::zero)132        derivedKey = null133        rootKey = null134        entryList = mutableListOf()135        duressConfigured = false136        _entries.value = emptyList()137        _isUnlocked.value = false138    }139140    // ---- Sync identity ----------------------------------------------------141142    /**143     * The vault's stable sync master key (a copy). Caller must zero it. Backs144     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry145     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].146     */147    fun syncMasterKey(): ByteArray? = rootKey?.copyOf()148149    /** Stable per-vault id two paired devices must share to sync. Null when locked. */150    fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }151152    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {153        val slotA = store.loadSlotA() ?: return false154        return try {155            val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))156            val payload = VaultCodec.decode(157                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),158            )159            val newSalt = VaultCrypto.generateSalt()160            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)161            // Re-seal the existing payload under the new key/salt.162            val plaintext = VaultCodec.encode(payload)163            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))164            val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)165            if (!store.writeSlotA(next)) return false166            writeMatchingNoiseSlotB(next)167            store.stampLocalMutation()168            VaultCrypto.zero(oldKey)169            derivedKey?.let(VaultCrypto::zero)170            derivedKey = newKey171            true172        } catch (_: Exception) {173            false174        }175    }176177    /**178     * Irreversible wipe. Locks the session and clears every vault key. The Pro179     * license is in a separate store and is preserved by construction.180     */181    suspend fun destroyVault() = mutex.withLock {182        lock()183        store.clearVault()184    }185186    // ---- Entry CRUD -------------------------------------------------------187188    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {189        requireUnlocked()190        val stamp = VaultCrypto.monotonicEntryTimestamp()191        val now = System.currentTimeMillis()192        val entry = draft.copy(193            id = draft.id.ifBlank { UUID.randomUUID().toString() },194            createdAt = if (draft.createdAt > 0) draft.createdAt else now,195            modifiedAt = stamp,196            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,197        )198        val rollback = entryList.toMutableList()199        entryList.add(entry)200        persistOrRollback(rollback)201        entry202    }203204    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {205        requireUnlocked()206        val idx = entryList.indexOfFirst { it.id == patch.id }207        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")208        val current = entryList[idx]209        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)210        // Only refresh passwordChangedAt when the password value actually changes.211        val passwordChanged = patch.password != null && patch.password != current.password212        val updated = patch.copy(213            createdAt = current.createdAt,214            modifiedAt = stamp,215            passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,216        )217        val rollback = entryList.toMutableList()218        entryList[idx] = updated219        persistOrRollback(rollback)220        updated221    }222223    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */224    suspend fun deleteEntry(id: String) = mutex.withLock {225        requireUnlocked()226        val idx = entryList.indexOfFirst { it.id == id }227        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")228        val current = entryList[idx]229        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)230        val rollback = entryList.toMutableList()231        entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)232        persistOrRollback(rollback)233    }234235    suspend fun restoreEntry(id: String) = mutex.withLock {236        requireUnlocked()237        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }238        if (idx == -1) throw IllegalStateException("deleted entry not found")239        val current = entryList[idx]240        val rollback = entryList.toMutableList()241        entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))242        persistOrRollback(rollback)243    }244245    /** Permanent delete — no tombstone, no recovery. */246    suspend fun purgeEntry(id: String) = mutex.withLock {247        requireUnlocked()248        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }249        if (idx == -1) throw IllegalStateException("deleted entry not found")250        val rollback = entryList.toMutableList()251        entryList.removeAt(idx)252        persistOrRollback(rollback)253    }254255    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }256    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }257    fun getDeletedEntries(): List<VaultEntry> = entryList.filter { it.deletedAt != null }258    fun getTombstones(): List<Tombstone> =259        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }260    fun getVaultVersion(): Long = store.version()261262    // ---- Sync apply (does NOT advance the version) ------------------------263264    /**265     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists266     * WITHOUT bumping the version counter, so a sync round cannot cascade into267     * another outbound sync. Returns the number of locally-applied changes.268     */269    suspend fun applyMergedRemoteEntries(270        remoteEntries: List<VaultEntry>,271        remoteTombstones: List<Tombstone>,272    ): Int = mutex.withLock {273        requireUnlocked()274        val tombMap = remoteTombstones.associate { it.id to it.deletedAt }275        var applied = 0276        val byId = entryList.associateBy { it.id }.toMutableMap()277278        for (remote in remoteEntries) {279            val tomb = tombMap[remote.id]280            if (tomb != null && tomb >= remote.modifiedAt) continue281            val local = byId[remote.id]282            if (local == null) {283                entryList.add(remote); byId[remote.id] = remote; applied++284            } else if (remote.modifiedAt > local.modifiedAt) {285                val i = entryList.indexOfFirst { it.id == local.id }286                if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }287            }288        }289290        for ((id, deletedAt) in tombMap) {291            val local = byId[id] ?: continue292            if (local.deletedAt != null && local.deletedAt >= deletedAt) continue293            if (deletedAt < local.modifiedAt) continue294            val i = entryList.indexOfFirst { it.id == id }295            if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }296        }297298        if (applied > 0) {299            persistSlotA(bumpVersion = false)300            publish()301        }302        applied303    }304305    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {306        _settings.value = settings307        store.writeSettings(settings)308    }309310    // ---- Internals --------------------------------------------------------311312    private fun requireUnlocked() {313        if (derivedKey == null) throw IllegalStateException("vault_locked")314    }315316    /** The slot-A plaintext envelope for the current in-memory session. */317    private fun currentPayload(): VaultPayload =318        VaultPayload(entryList.toList(), duressConfigured, rootKey?.let(::b64) ?: "")319320    /**321     * Adopt the payload's root key, lazily minting one for legacy payloads.322     * A freshly-minted key is persisted WITHOUT bumping the version — adopting323     * a root key is not a mutation paired devices should sync against.324     */325    private fun ensureRootKey(payload: VaultPayload) {326        if (payload.rootKeyB64.isNotBlank()) {327            rootKey = unb64(payload.rootKeyB64)328            return329        }330        rootKey = VaultCrypto.generateRootKey()331        runCatching { persistSlotA(bumpVersion = false) }332    }333334    private fun publish() {335        _entries.value = entryList.filter { it.deletedAt == null }336    }337338    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {339        val plaintext = VaultCodec.encode(currentPayload())340        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))341        return StoredVault(version = 1, salt = b64(salt), blob = blob)342    }343344    private fun writeMatchingNoiseSlotB(slotA: StoredVault) {345        val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)346        val noise = ByteArray(approxBytes).also(rng::nextBytes)347        store.writeSlotB(b64(noise))348    }349350    /** Re-seal slot A from the current in-memory state under the live key. */351    private fun persistSlotA(bumpVersion: Boolean): Boolean {352        val key = derivedKey ?: throw IllegalStateException("vault_locked")353        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")354        val plaintext = VaultCodec.encode(currentPayload())355        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))356        val next = prior.copy(blob = blob)357        if (!store.writeSlotA(next)) return false358        // Slot A committed — keep slot B size-matched, then advance the version359        // for local writes only. Restore slot A if a later step fails.360        try {361            writeMatchingNoiseSlotB(next)362            if (bumpVersion) store.stampLocalMutation()363        } catch (e: Exception) {364            store.writeSlotA(prior)365            throw e366        }367        return true368    }369370    /** Persist a local mutation, rolling the in-memory list back on failure. */371    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {372        try {373            if (!persistSlotA(bumpVersion = true)) {374                entryList = rollback375                throw IllegalStateException("storage_write_failed")376            }377        } catch (e: Exception) {378            entryList = rollback379            throw e380        }381        publish()382    }383}