VaultStore.kt

5.9 KB · raw

1package com.peachpasswords.vault23import android.content.Context4import dagger.hilt.android.qualifiers.ApplicationContext5import kotlinx.serialization.Serializable6import kotlinx.serialization.decodeFromString7import kotlinx.serialization.encodeToString8import kotlinx.serialization.json.Json9import javax.inject.Inject10import javax.inject.Singleton1112/**13 * One encrypted slot at rest. [blob] is base64 of VaultCrypto's14 * `nonce || ciphertext || tag` output; [salt] (base64) drives Argon2id.15 * Mirrors the browser's StoredVault, minus the recovery-escrow fields which16 * the Android port wires in a later phase.17 */18@Serializable19data class StoredVault(20    val version: Int = 1,21    val salt: String,22    val blob: String,23)2425/** A soft-deleted entry, exposed to the sync layer for last-write-wins merges. */26@Serializable27data class Tombstone(val id: String, val deletedAt: Long)2829/**30 * The decrypted slot-A envelope: the entry list, the duress flag, and the31 * stable sync root key.32 *33 * [rootKeyB64] is the vault's stable 32-byte sync master key (base64, no34 * padding). Unlike the Argon2id password key it never rotates on a password35 * change, so paired devices keep deriving the same vault_id, Noise static key,36 * and per-entry envelope keys across independent password rotations (browser37 * SEV-2-B). Empty on legacy payloads written before sync landed — the38 * repository lazily mints and persists one on first unlock.39 */40@Serializable41data class VaultPayload(42    val entries: List<VaultEntry> = emptyList(),43    val duressConfigured: Boolean = false,44    val rootKeyB64: String = "",45    /**46     * BLAKE3 hash of the space-joined 12 BIP39 recovery words. Lets the app verify47     * recovery-word entry without storing the words themselves. Null until set.48     */49    val recoveryWordHash: String? = null,50    /** True once the user has confirmed (written down) their recovery words. */51    val recoveryWordsSet: Boolean = false,52)5354/** Pure JSON codec for the slot-A plaintext envelope — usable without Android. */55object VaultCodec {56    private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }57    fun encode(payload: VaultPayload): ByteArray = json.encodeToString(payload).toByteArray(Charsets.UTF_8)58    fun decode(bytes: ByteArray): VaultPayload = json.decodeFromString(String(bytes, Charsets.UTF_8))59    fun encodeSettings(s: VaultSettings): String = json.encodeToString(s)60    fun decodeSettings(s: String): VaultSettings? = runCatching { json.decodeFromString<VaultSettings>(s) }.getOrNull()61    fun encodeSlot(s: StoredVault): String = json.encodeToString(s)62    fun decodeSlot(s: String): StoredVault? = runCatching { json.decodeFromString<StoredVault>(s) }.getOrNull()63}6465/**66 * Persistence for the two vault slots, the monotonic version counter, and the67 * settings blob. Abstracted behind an interface so the repository can be68 * exercised against an in-memory fake in plain JUnit.69 */70interface VaultStorage {71    fun loadSlotA(): StoredVault?72    fun hasVault(): Boolean73    fun writeSlotA(slot: StoredVault): Boolean74    fun writeSlotB(blobBase64: String): Boolean75    fun loadDecoySlot(): StoredVault?76    fun writeDecoySlot(slot: StoredVault): Boolean77    fun hasDecoySlot(): Boolean78    fun clearDecoySlot()79    fun version(): Long80    fun stampLocalMutation(): Long81    fun loadSettings(): VaultSettings82    fun writeSettings(settings: VaultSettings): Boolean83    fun clearVault()84}8586/**87 * SharedPreferences-backed [VaultStorage]. The slot blobs are already AES-GCM88 * sealed under the Argon2id key, so plaintext prefs are fine — only the salt is89 * in the clear, exactly as in storage.local on the extension. The Pro license90 * lives in a SEPARATE prefs file (LicenseRepository), so wiping this store can91 * never touch the license — destroyVault()'s core invariant.92 */93@Singleton94class VaultStore @Inject constructor(95    @ApplicationContext context: Context,96) : VaultStorage {97    private val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)9899    override fun loadSlotA(): StoredVault? = prefs.getString(KEY_SLOT_A, null)?.let(VaultCodec::decodeSlot)100101    override fun hasVault(): Boolean = prefs.contains(KEY_SLOT_A)102103    override fun writeSlotA(slot: StoredVault): Boolean =104        prefs.edit().putString(KEY_SLOT_A, VaultCodec.encodeSlot(slot)).commit()105106    override fun writeSlotB(blobBase64: String): Boolean =107        prefs.edit().putString(KEY_SLOT_B, blobBase64).commit()108109    override fun loadDecoySlot(): StoredVault? = prefs.getString(KEY_SLOT_DURESS, null)?.let(VaultCodec::decodeSlot)110    override fun writeDecoySlot(slot: StoredVault): Boolean =111        prefs.edit().putString(KEY_SLOT_DURESS, VaultCodec.encodeSlot(slot)).commit()112    override fun hasDecoySlot(): Boolean = prefs.contains(KEY_SLOT_DURESS)113    override fun clearDecoySlot() { prefs.edit().remove(KEY_SLOT_DURESS).commit() }114115    override fun version(): Long = prefs.getString(KEY_VERSION, null)?.toLongOrNull() ?: 0L116117    override fun stampLocalMutation(): Long {118        val next = maxOf(System.currentTimeMillis(), version() + 1L)119        prefs.edit().putString(KEY_VERSION, next.toString()).commit()120        return next121    }122123    override fun loadSettings(): VaultSettings =124        prefs.getString(KEY_SETTINGS, null)?.let(VaultCodec::decodeSettings) ?: VaultSettings()125126    override fun writeSettings(settings: VaultSettings): Boolean =127        prefs.edit().putString(KEY_SETTINGS, VaultCodec.encodeSettings(settings)).commit()128129    override fun clearVault() {130        prefs.edit()131            .remove(KEY_SLOT_A).remove(KEY_SLOT_B).remove(KEY_VERSION).remove(KEY_SETTINGS)132            .commit()133    }134135    companion object {136        private const val PREFS = "peach_vault_store"137        private const val KEY_SLOT_A = "peach_vault_a"138        private const val KEY_SLOT_B = "peach_vault_b"139        private const val KEY_SLOT_DURESS = "peach_vault_duress"140        private const val KEY_VERSION = "peach_last_modified_at"141        private const val KEY_SETTINGS = "peach_settings"142    }143}