VaultStore.kt

6.6 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. [recoveryEscrow] is null until the user16 * sets recovery words; it is a password-independent second copy of the slot-A17 * plaintext that powers the forgot-password flow.18 */19@Serializable20data class StoredVault(21    val version: Int = 1,22    val salt: String,23    val blob: String,24    val recoveryEscrow: RecoveryEscrow? = null,25)2627/**28 * A second, password-independent copy of the slot-A plaintext envelope, sealed29 * under a key the 12 BIP39 recovery words derive (HKDF). Lets the vault be30 * recovered and re-wrapped under a new password without the old password.31 *32 * [salt] (base64, 16B) is the HKDF salt for `deriveRecoveryKey`.33 * [blob] (base64) is `VaultCrypto.encrypt(slotAPlaintext, recoveryKey, AAD_RECOVERY)`34 *   i.e. `nonce(12) || AES-256-GCM ciphertext||tag`.35 */36@Serializable37data class RecoveryEscrow(38    val salt: String,39    val blob: String,40)4142/** A soft-deleted entry, exposed to the sync layer for last-write-wins merges. */43@Serializable44data class Tombstone(val id: String, val deletedAt: Long)4546/**47 * The decrypted slot-A envelope: the entry list, the duress flag, and the48 * stable sync root key.49 *50 * [rootKeyB64] is the vault's stable 32-byte sync master key (base64, no51 * padding). Unlike the Argon2id password key it never rotates on a password52 * change, so paired devices keep deriving the same vault_id, Noise static key,53 * and per-entry envelope keys across independent password rotations (browser54 * SEV-2-B). Empty on legacy payloads written before sync landed — the55 * repository lazily mints and persists one on first unlock.56 */57@Serializable58data class VaultPayload(59    val entries: List<VaultEntry> = emptyList(),60    val duressConfigured: Boolean = false,61    val rootKeyB64: String = "",62    /**63     * BLAKE3 hash of the space-joined 12 BIP39 recovery words. Lets the app verify64     * recovery-word entry without storing the words themselves. Null until set.65     */66    val recoveryWordHash: String? = null,67    /** True once the user has confirmed (written down) their recovery words. */68    val recoveryWordsSet: Boolean = false,69)7071/** Pure JSON codec for the slot-A plaintext envelope — usable without Android. */72object VaultCodec {73    private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }74    fun encode(payload: VaultPayload): ByteArray = json.encodeToString(payload).toByteArray(Charsets.UTF_8)75    fun decode(bytes: ByteArray): VaultPayload = json.decodeFromString(String(bytes, Charsets.UTF_8))76    fun encodeSettings(s: VaultSettings): String = json.encodeToString(s)77    fun decodeSettings(s: String): VaultSettings? = runCatching { json.decodeFromString<VaultSettings>(s) }.getOrNull()78    fun encodeSlot(s: StoredVault): String = json.encodeToString(s)79    fun decodeSlot(s: String): StoredVault? = runCatching { json.decodeFromString<StoredVault>(s) }.getOrNull()80}8182/**83 * Persistence for the two vault slots, the monotonic version counter, and the84 * settings blob. Abstracted behind an interface so the repository can be85 * exercised against an in-memory fake in plain JUnit.86 */87interface VaultStorage {88    fun loadSlotA(): StoredVault?89    fun hasVault(): Boolean90    fun writeSlotA(slot: StoredVault): Boolean91    fun writeSlotB(blobBase64: String): Boolean92    fun loadDecoySlot(): StoredVault?93    fun writeDecoySlot(slot: StoredVault): Boolean94    fun hasDecoySlot(): Boolean95    fun clearDecoySlot()96    fun version(): Long97    fun stampLocalMutation(): Long98    fun loadSettings(): VaultSettings99    fun writeSettings(settings: VaultSettings): Boolean100    fun clearVault()101}102103/**104 * SharedPreferences-backed [VaultStorage]. The slot blobs are already AES-GCM105 * sealed under the Argon2id key, so plaintext prefs are fine — only the salt is106 * in the clear, exactly as in storage.local on the extension. The Pro license107 * lives in a SEPARATE prefs file (LicenseRepository), so wiping this store can108 * never touch the license — destroyVault()'s core invariant.109 */110@Singleton111class VaultStore @Inject constructor(112    @ApplicationContext context: Context,113) : VaultStorage {114    private val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)115116    override fun loadSlotA(): StoredVault? = prefs.getString(KEY_SLOT_A, null)?.let(VaultCodec::decodeSlot)117118    override fun hasVault(): Boolean = prefs.contains(KEY_SLOT_A)119120    override fun writeSlotA(slot: StoredVault): Boolean =121        prefs.edit().putString(KEY_SLOT_A, VaultCodec.encodeSlot(slot)).commit()122123    override fun writeSlotB(blobBase64: String): Boolean =124        prefs.edit().putString(KEY_SLOT_B, blobBase64).commit()125126    override fun loadDecoySlot(): StoredVault? = prefs.getString(KEY_SLOT_DURESS, null)?.let(VaultCodec::decodeSlot)127    override fun writeDecoySlot(slot: StoredVault): Boolean =128        prefs.edit().putString(KEY_SLOT_DURESS, VaultCodec.encodeSlot(slot)).commit()129    override fun hasDecoySlot(): Boolean = prefs.contains(KEY_SLOT_DURESS)130    override fun clearDecoySlot() { prefs.edit().remove(KEY_SLOT_DURESS).commit() }131132    override fun version(): Long = prefs.getString(KEY_VERSION, null)?.toLongOrNull() ?: 0L133134    override fun stampLocalMutation(): Long {135        val next = maxOf(System.currentTimeMillis(), version() + 1L)136        prefs.edit().putString(KEY_VERSION, next.toString()).commit()137        return next138    }139140    override fun loadSettings(): VaultSettings =141        prefs.getString(KEY_SETTINGS, null)?.let(VaultCodec::decodeSettings) ?: VaultSettings()142143    override fun writeSettings(settings: VaultSettings): Boolean =144        prefs.edit().putString(KEY_SETTINGS, VaultCodec.encodeSettings(settings)).commit()145146    override fun clearVault() {147        prefs.edit()148            .remove(KEY_SLOT_A).remove(KEY_SLOT_B).remove(KEY_VERSION).remove(KEY_SETTINGS)149            .commit()150    }151152    companion object {153        private const val PREFS = "peach_vault_store"154        private const val KEY_SLOT_A = "peach_vault_a"155        private const val KEY_SLOT_B = "peach_vault_b"156        private const val KEY_SLOT_DURESS = "peach_vault_duress"157        private const val KEY_VERSION = "peach_last_modified_at"158        private const val KEY_SETTINGS = "peach_settings"159    }160}