VaultRepository.kt

22.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)1617/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */18private 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}3031/**32 * In-memory vault session backed by [VaultStore]. Faithful port of the browser33 * `vault.ts` semantics that matter for correctness:34 *35 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched36 *    noise blob so a fresh install shows two similarly-shaped records.37 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a38 *    deletion always wins last-write-wins against an in-flight edit.39 *  - Local writes bump the version counter; sync-applied writes do NOT (so a40 *    sync round never cascades into another outbound sync).41 *  - add/update/delete roll back in-memory state if the disk write fails.42 *  - destroyVault never touches the Pro license (separate store).43 */44@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    /** Active (non-deleted) entryList. */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    // ---- Codex (printed paper backup) -------------------------------------7172    /**73     * The at-rest slot-A envelope as base64 JSON `{"a": <StoredVault>}` — the74     * Codex payload's vaultBlob. Slot B is noise, so it is omitted. Restorable75     * on any device that has the master password. Null when no vault exists.76     */77    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    /**84     * Replace the local vault from a Codex blob, then unlock with [password].85     * Writes slot A (and a size-matched noise slot B) before unlocking so the86     * restored vault is at rest exactly as a freshly-created one would be.87     */88    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    /** Unlock body without acquiring the mutex — callers must already hold it. */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    /** Unlock with an already-derived AES-256 key (biometric path). */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    // ---- Sync identity ----------------------------------------------------192193    /**194     * The vault's stable sync master key (a copy). Caller must zero it. Backs195     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry196     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].197     */198    fun syncMasterKey(): ByteArray? = rootKey?.copyOf()199200    /** Stable per-vault id two paired devices must share to sync. Null when locked. */201    fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }202203    /**204     * A copy of the live Argon2id-derived vault key, for biometric escrow only205     * (wrapped under a hardware KeyStore key on biometric enable). Null when206     * locked. Caller must [VaultCrypto.zero] it after use.207     */208    fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()209210    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {211        val slotA = store.loadSlotA() ?: return false212        return try {213            val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))214            val payload = VaultCodec.decode(215                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),216            )217            val newSalt = VaultCrypto.generateSalt()218            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)219            // Re-seal the existing payload under the new key/salt.220            val plaintext = VaultCodec.encode(payload)221            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))222            val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)223            if (!store.writeSlotA(next)) return false224            writeMatchingNoiseSlotB(next)225            store.stampLocalMutation()226            VaultCrypto.zero(oldKey)227            derivedKey?.let(VaultCrypto::zero)228            derivedKey = newKey229            true230        } catch (_: Exception) {231            false232        }233    }234235    /**236     * Irreversible wipe. Locks the session and clears every vault key. The Pro237     * license is in a separate store and is preserved by construction.238     */239    suspend fun destroyVault() = mutex.withLock {240        lock()241        store.clearVault()242    }243244    // ---- Entry CRUD -------------------------------------------------------245246    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {247        requireUnlocked()248        val stamp = VaultCrypto.monotonicEntryTimestamp()249        val now = System.currentTimeMillis()250        val entry = draft.copy(251            id = draft.id.ifBlank { UUID.randomUUID().toString() },252            createdAt = if (draft.createdAt > 0) draft.createdAt else now,253            modifiedAt = stamp,254            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,255        )256        val rollback = entryList.toMutableList()257        entryList.add(entry)258        persistOrRollback(rollback)259        entry260    }261262    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {263        requireUnlocked()264        val idx = entryList.indexOfFirst { it.id == patch.id }265        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")266        val current = entryList[idx]267        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)268        // Only refresh passwordChangedAt when the password value actually changes.269        val passwordChanged = patch.password != null && patch.password != current.password270        // Capture the outgoing password (newest first) so the user can reveal/copy/271        // restore it later. History is computed authoritatively from `current`, not272        // the patch — updateEntry is a full-entry replace, so trusting patch's value273        // would let a stale form clobber the real history. Record the age the old274        // password carried, skip an empty prior, and skip an immediate exact dupe275        // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.276        val priorPassword = current.password277        val shouldCapture = passwordChanged &&278            !priorPassword.isNullOrEmpty() &&279            current.passwordHistory?.firstOrNull()?.password != priorPassword280        val nextHistory = if (shouldCapture) {281            (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +282                (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)283        } else {284            current.passwordHistory285        }286        val updated = patch.copy(287            createdAt = current.createdAt,288            modifiedAt = stamp,289            passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,290            passwordHistory = nextHistory,291        )292        val rollback = entryList.toMutableList()293        entryList[idx] = updated294        persistOrRollback(rollback)295        updated296    }297298    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */299    suspend fun deleteEntry(id: String) = mutex.withLock {300        requireUnlocked()301        val idx = entryList.indexOfFirst { it.id == id }302        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")303        val current = entryList[idx]304        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)305        val rollback = entryList.toMutableList()306        entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)307        persistOrRollback(rollback)308    }309310    suspend fun restoreEntry(id: String) = mutex.withLock {311        requireUnlocked()312        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }313        if (idx == -1) throw IllegalStateException("deleted entry not found")314        val current = entryList[idx]315        val rollback = entryList.toMutableList()316        entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))317        persistOrRollback(rollback)318    }319320    /** Permanent delete — no tombstone, no recovery. */321    suspend fun purgeEntry(id: String) = mutex.withLock {322        requireUnlocked()323        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }324        if (idx == -1) throw IllegalStateException("deleted entry not found")325        val rollback = entryList.toMutableList()326        entryList.removeAt(idx)327        persistOrRollback(rollback)328    }329330    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */331    suspend fun purgeDeletedEntries(): Int = mutex.withLock {332        requireUnlocked()333        val rollback = entryList.toMutableList()334        val before = entryList.size335        entryList.removeAll { it.deletedAt != null }336        val removed = before - entryList.size337        if (removed > 0) persistOrRollback(rollback)338        removed339    }340341    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }342    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }343    fun getDeletedEntries(): List<VaultEntry> =344        entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }345346    /** Active entries, optionally narrowed to those carrying [tagFilter]. */347    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {348        val active = entryList.filter { it.deletedAt == null }349        if (tagFilter == null) return active350        val needle = tagFilter.trim().lowercase()351        return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }352    }353354    /** Sorted, de-duplicated tags across all active entries. */355    fun getDistinctTags(): List<String> =356        entryList.asSequence()357            .filter { it.deletedAt == null }358            .flatMap { it.tags?.asSequence() ?: emptySequence() }359            .map { it.trim().lowercase() }360            .filter { it.isNotEmpty() }361            .distinct()362            .sorted()363            .toList()364    fun getTombstones(): List<Tombstone> =365        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }366    fun getVaultVersion(): Long = store.version()367368    // ---- Sync apply (does NOT advance the version) ------------------------369370    /**371     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists372     * WITHOUT bumping the version counter, so a sync round cannot cascade into373     * another outbound sync. Returns the number of locally-applied changes.374     */375    suspend fun applyMergedRemoteEntries(376        remoteEntries: List<VaultEntry>,377        remoteTombstones: List<Tombstone>,378    ): Int = mutex.withLock {379        requireUnlocked()380        val tombMap = remoteTombstones.associate { it.id to it.deletedAt }381        var applied = 0382        val byId = entryList.associateBy { it.id }.toMutableMap()383384        for (remote in remoteEntries) {385            val tomb = tombMap[remote.id]386            if (tomb != null && tomb >= remote.modifiedAt) continue387            val local = byId[remote.id]388            if (local == null) {389                entryList.add(remote); byId[remote.id] = remote; applied++390            } else if (remote.modifiedAt > local.modifiedAt) {391                val i = entryList.indexOfFirst { it.id == local.id }392                if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }393            }394        }395396        for ((id, deletedAt) in tombMap) {397            val local = byId[id] ?: continue398            if (local.deletedAt != null && local.deletedAt >= deletedAt) continue399            if (deletedAt < local.modifiedAt) continue400            val i = entryList.indexOfFirst { it.id == id }401            if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }402        }403404        if (applied > 0) {405            persistSlotA(bumpVersion = false)406            publish()407        }408        applied409    }410411    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {412        _settings.value = settings413        store.writeSettings(settings)414    }415416    // ---- Recovery words (vault metadata) ----------------------------------417418    /** True once the user has confirmed their recovery words for this vault. */419    fun isRecoveryWordsSet(): Boolean = recoveryWordsSet420421    /**422     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.423     * Persisted without bumping the version — recovery metadata is local-only and424     * is not an entry mutation paired devices should sync against.425     */426    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {427        requireUnlocked()428        recoveryWordHash = recoveryWordsHash(words)429        recoveryWordsSet = true430        runCatching { persistSlotA(bumpVersion = false) }.getOrDefault(false)431    }432433    /** Verify entered words against the stored recovery hash. */434    fun verifyRecoveryWords(words: List<String>): Boolean {435        val stored = recoveryWordHash ?: return false436        return stored == recoveryWordsHash(words)437    }438439    // ---- Internals --------------------------------------------------------440441    private fun requireUnlocked() {442        if (derivedKey == null) throw IllegalStateException("vault_locked")443    }444445    /**446     * On unlock, hard-delete trashed entries older than the retention window.447     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"448     * (the app's "Never" option), so nothing is purged. Persists without a449     * version bump and without touching the publish state (caller publishes).450     */451    private fun autoPurgeExpiredTrash() {452        val days = _settings.value.trashRetentionDays ?: return453        if (days <= 0) return454        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L455        val before = entryList.size456        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }457        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }458    }459460    /** The slot-A plaintext envelope for the current in-memory session. */461    private fun currentPayload(): VaultPayload =462        VaultPayload(463            entries = entryList.toList(),464            duressConfigured = duressConfigured,465            rootKeyB64 = rootKey?.let(::b64) ?: "",466            recoveryWordHash = recoveryWordHash,467            recoveryWordsSet = recoveryWordsSet,468        )469470    /**471     * Adopt the payload's root key, lazily minting one for legacy payloads.472     * A freshly-minted key is persisted WITHOUT bumping the version — adopting473     * a root key is not a mutation paired devices should sync against.474     */475    private fun ensureRootKey(payload: VaultPayload) {476        if (payload.rootKeyB64.isNotBlank()) {477            rootKey = unb64(payload.rootKeyB64)478            return479        }480        rootKey = VaultCrypto.generateRootKey()481        runCatching { persistSlotA(bumpVersion = false) }482    }483484    private fun publish() {485        _entries.value = entryList.filter { it.deletedAt == null }486    }487488    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {489        val plaintext = VaultCodec.encode(currentPayload())490        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))491        return StoredVault(version = 1, salt = b64(salt), blob = blob)492    }493494    private fun writeMatchingNoiseSlotB(slotA: StoredVault) {495        val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)496        val noise = ByteArray(approxBytes).also(rng::nextBytes)497        store.writeSlotB(b64(noise))498    }499500    /** Re-seal slot A from the current in-memory state under the live key. */501    private fun persistSlotA(bumpVersion: Boolean): Boolean {502        val key = derivedKey ?: throw IllegalStateException("vault_locked")503        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")504        val plaintext = VaultCodec.encode(currentPayload())505        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))506        val next = prior.copy(blob = blob)507        if (!store.writeSlotA(next)) return false508        // Slot A committed — keep slot B size-matched, then advance the version509        // for local writes only. Restore slot A if a later step fails.510        try {511            writeMatchingNoiseSlotB(next)512            if (bumpVersion) store.stampLocalMutation()513        } catch (e: Exception) {514            store.writeSlotA(prior)515            throw e516        }517        return true518    }519520    /** Persist a local mutation, rolling the in-memory list back on failure. */521    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {522        try {523            if (!persistSlotA(bumpVersion = true)) {524                entryList = rollback525                throw IllegalStateException("storage_write_failed")526            }527        } catch (e: Exception) {528            entryList = rollback529            throw e530        }531        publish()532    }533}