VaultStore.kt

13.7 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    /** Version 1 is the legacy Slot-A-AAD record; current decoys use version 2. */22    val version: Int = LEGACY_ANDROID_SLOT_VERSION,23    val salt: String,24    val blob: String,25    val recoveryEscrow: RecoveryEscrow? = null,26    val rootKeyEscrow: RootKeyEscrow? = null,27)2829const val LEGACY_ANDROID_SLOT_VERSION = 130const val CURRENT_ANDROID_SLOT_VERSION = 23132/**33 * Browser-byte-compatible recovery escrow that wraps ONLY the 32-byte root key,34 * so the same 12 recovery words unwrap the same root key on either platform35 * (MF-1). The wrapped plaintext is the lowercase ASCII hex of the root key; the36 * key is `HKDF-SHA256(wordsToRootKeyMaterial(words), salt, "peach-recovery-v1")`37 * and the AEAD AAD is the single byte 0x01 ([VaultCrypto.AAD_RECOVERY_ROOTKEY]) —38 * all matching the browser (`vault.ts:282-316`).39 *40 * Fields mirror the browser's slot-A `recovery_*` fields (base64 here vs hex on41 * the browser) so a future browser-slot importer can map them directly:42 * [salt] = `recovery_salt`, [wrappedRootKey] = `recovery_wrapped_root_key`43 * (ciphertext only), [nonce] = `recovery_nonce`, [tag] = `recovery_tag`.44 */45@Serializable46data class RootKeyEscrow(47    val salt: String,48    val wrappedRootKey: String,49    val nonce: String,50    val tag: String,51)5253/**54 * A second, password-independent copy of the slot-A plaintext envelope, sealed55 * under a key the 12 BIP39 recovery words derive (HKDF). Lets the vault be56 * recovered and re-wrapped under a new password without the old password.57 *58 * [salt] (base64, 16B) is the HKDF salt for `deriveRecoveryKey`.59 * [blob] (base64) is `VaultCrypto.encrypt(slotAPlaintext, recoveryKey, AAD_RECOVERY)`60 *   i.e. `nonce(12) || AES-256-GCM ciphertext||tag`.61 */62@Serializable63data class RecoveryEscrow(64    val salt: String,65    val blob: String,66)6768@Serializable69data class VaultHistory(70    val snapshots: List<VaultSnapshot> = emptyList(),71)7273/** A soft-deleted entry, exposed to the sync layer for last-write-wins merges. */74@Serializable75data class Tombstone(val id: String, val deletedAt: Long)7677/**78 * The decrypted slot-A envelope: the entry list, the duress flag, and the79 * stable sync root key.80 *81 * [rootKeyB64] is the vault's stable 32-byte sync master key (base64, no82 * padding). Unlike the Argon2id password key it never rotates on a password83 * change, so paired devices keep deriving the same vault_id, Noise static key,84 * and per-entry envelope keys across independent password rotations (browser85 * SEV-2-B). Empty on legacy payloads written before sync landed — the86 * repository lazily mints and persists one on first unlock.87 */88@Serializable89data class VaultPayload(90    val entries: List<VaultEntry> = emptyList(),91    val duressConfigured: Boolean = false,92    val rootKeyB64: String = "",93    /**94     * BLAKE3 hash of the space-joined 12 BIP39 recovery words. Lets the app verify95     * recovery-word entry without storing the words themselves. Null until set.96     */97    val recoveryWordHash: String? = null,98    /** True once the user has confirmed (written down) their recovery words. */99    val recoveryWordsSet: Boolean = false,100)101102const val SLOT_RECORD_PAD: Char = '\u0000'103104/** Pure JSON codec for the slot-A plaintext envelope — usable without Android. */105object VaultCodec {106    private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }107108    // MN-1: pad every sealed plaintext to a size bucket before encryption so that109    // slot A (real) and slot B (duress decoy) — and the recovery escrow — quantise110    // to the same lengths and an at-rest observer cannot tell which slot is which111    // from its size. Padding is trailing NULs (never valid inside JSON); decode112    // strips them, so an unpadded legacy blob (no trailing NULs) still decodes.113    fun encode(payload: VaultPayload): ByteArray =114        VaultCrypto.padToBucket(json.encodeToString(payload).toByteArray(Charsets.UTF_8))115    fun decode(bytes: ByteArray): VaultPayload =116        json.decodeFromString(String(bytes, Charsets.UTF_8).trimEnd('\u0000'))117    /** Test seam: the entry codec is only reachable through a whole payload otherwise. */118    internal fun decodeEntryForTest(entryJson: String): VaultEntry = json.decodeFromString(entryJson)119    internal fun encodeEntryForTest(entry: VaultEntry): String = json.encodeToString(entry)120121    fun encodeSettings(s: VaultSettings): String = json.encodeToString(s)122    fun decodeSettings(s: String): VaultSettings? = runCatching { json.decodeFromString<VaultSettings>(s) }.getOrNull()123    fun encodeSlot(s: StoredVault): String = json.encodeToString(s)124    fun decodeSlot(s: String): StoredVault? =125        runCatching { json.decodeFromString<StoredVault>(s.trimEnd(SLOT_RECORD_PAD)) }.getOrNull()126127    /**128     * Trailing NULs pad a slot record to its sibling's length. NUL cannot occur129     * inside the JSON — the same reason [encode] can pad plaintext with it — so130     * [decodeSlot] only has to trim it.131     */132    fun padSlotRecord(record: String, targetLength: Int): String =133        if (record.length >= targetLength) record else record.padEnd(targetLength, SLOT_RECORD_PAD)134135    fun slotRecordLength(record: String): Int = record.trimEnd(SLOT_RECORD_PAD).length136137    /**138     * The (written, sibling) record pair after alignment, so both slots are the139     * same length at rest (PAI-2026-004).140     *141     * A real decoy cannot be re-sealed without the duress passphrase, so its142     * blob keeps the length it had when duress was configured while slot A143     * keeps growing through the padding buckets. Padding the shorter record to144     * the longer one is what keeps an at-rest observer from reading duress145     * configuration, or how far the vault has grown, out of the pair.146     *147     * The target is the longer TRUE record, not the longer stored one, so the148     * pair tracks the current vault instead of ratcheting up to a high-water149     * mark every time the vault temporarily grows.150     */151    fun alignSlotRecords(record: String, sibling: String?): Pair<String, String?> {152        if (sibling == null) return record to null153        val target = maxOf(record.length, slotRecordLength(sibling))154        return padSlotRecord(record, target) to padSlotRecord(sibling, target)155    }156    fun encodeHistory(h: VaultHistory): String = json.encodeToString(h)157    fun decodeHistory(s: String): VaultHistory? = runCatching { json.decodeFromString<VaultHistory>(s) }.getOrNull()158}159160interface VaultStorage {161    fun loadDecoySlot(): StoredVault?162    fun loadSlotA(): StoredVault?163    fun hasVault(): Boolean164    fun writeSlotA(slot: StoredVault): Boolean165    fun loadSlotB(): String? = null166    fun writeSlotB(blobBase64: String): Boolean167    fun writeDecoySlot(slot: StoredVault): Boolean168    /** Restore the exact triad, rolling back each write if a later write fails. */169    fun restoreVaultTriad(slotA: StoredVault, slotB: String?, decoy: StoredVault): Boolean {170        val priorA = loadSlotA()171        val priorB = loadSlotB()172        val priorD = loadDecoySlot()173        return try {174            if (!writeSlotA(slotA)) return false175            if (slotB == null) clearSlotB() else if (!writeSlotB(slotB)) throw IllegalStateException("slot_b_restore_failed")176            if (!writeDecoySlot(decoy)) throw IllegalStateException("decoy_restore_failed")177            true178        } catch (_: Exception) {179            runCatching { if (priorA == null) clearVault() else writeSlotA(priorA) }180            runCatching { if (priorB == null) clearSlotB() else writeSlotB(priorB) }181            runCatching { if (priorD == null) clearDecoySlot() else writeDecoySlot(priorD) }182            false183        }184    }185    fun clearSlotB() {}186    fun hasDecoySlot(): Boolean = loadDecoySlot() != null187    fun clearDecoySlot()188    fun version(): Long189    fun stampLocalMutation(): Long190    fun loadSettings(): VaultSettings191    fun writeSettings(settings: VaultSettings): Boolean192    fun loadVaultHistory(): VaultHistory = VaultHistory()193    fun writeVaultHistory(history: VaultHistory): Boolean = true194    fun clearVaultHistory() {}195    fun clearVault()196}197198/**199 * SharedPreferences-backed [VaultStorage]. The slot blobs are already AES-GCM200 * sealed under the Argon2id key, so plaintext prefs are fine — only the salt is201 * in the clear, exactly as in storage.local on the extension. The Pro license202 * lives in a SEPARATE prefs file (LicenseRepository), so wiping this store can203 * never touch the license — destroyVault()'s core invariant.204 */205@Singleton206class VaultStore @Inject constructor(207    @ApplicationContext context: Context,208) : VaultStorage {209    private val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)210211    override fun loadSlotA(): StoredVault? = prefs.getString(KEY_SLOT_A, null)?.let(VaultCodec::decodeSlot)212213    override fun hasVault(): Boolean = prefs.contains(KEY_SLOT_A)214215    override fun writeSlotA(slot: StoredVault): Boolean =216        writeAligned(KEY_SLOT_A, VaultCodec.encodeSlot(slot), KEY_SLOT_DURESS)217    override fun clearSlotB() { prefs.edit().remove(KEY_SLOT_B).commit() }218    override fun loadSlotB(): String? = prefs.getString(KEY_SLOT_B, null)219220    override fun writeSlotB(blobBase64: String): Boolean =221        prefs.edit().putString(KEY_SLOT_B, blobBase64).commit()222223    override fun loadDecoySlot(): StoredVault? = prefs.getString(KEY_SLOT_DURESS, null)?.let(VaultCodec::decodeSlot)224    override fun writeDecoySlot(slot: StoredVault): Boolean =225        writeAligned(KEY_SLOT_DURESS, VaultCodec.encodeSlot(slot), KEY_SLOT_A)226227    /** Both slot records are written in one commit so the pair can never be caught misaligned. */228    private fun writeAligned(key: String, record: String, siblingKey: String): Boolean {229        val (aligned, alignedSibling) = VaultCodec.alignSlotRecords(230            record,231            prefs.getString(siblingKey, null),232        )233        val edits = prefs.edit().putString(key, aligned)234        if (alignedSibling != null) edits.putString(siblingKey, alignedSibling)235        return edits.commit()236    }237238    override fun restoreVaultTriad(slotA: StoredVault, slotB: String?, decoy: StoredVault): Boolean {239        val edits = prefs.edit()240            .putString(KEY_SLOT_A, VaultCodec.encodeSlot(slotA))241            .putString(KEY_SLOT_DURESS, VaultCodec.encodeSlot(decoy))242        if (slotB != null) edits.putString(KEY_SLOT_B, slotB) else edits.remove(KEY_SLOT_B)243        return edits.commit()244    }245    override fun hasDecoySlot(): Boolean = prefs.contains(KEY_SLOT_DURESS)246    override fun clearDecoySlot() { prefs.edit().remove(KEY_SLOT_DURESS).commit() }247248    override fun version(): Long = prefs.getString(KEY_VERSION, null)?.toLongOrNull() ?: 0L249250    override fun stampLocalMutation(): Long {251        val next = maxOf(System.currentTimeMillis(), version() + 1L)252        // commit() returning false must surface as a failure — every caller253        // either treats an exception as a rollback trigger (H-01/H-02 helpers,254        // persistSlotA) or advances a version it has not actually persisted.255        // Throwing keeps the boolean-visible failure mode aligned with codex P1-2.256        if (!prefs.edit().putString(KEY_VERSION, next.toString()).commit()) {257            throw java.io.IOException("version_stamp_commit_failed")258        }259        return next260    }261262    override fun loadSettings(): VaultSettings =263        prefs.getString(KEY_SETTINGS, null)?.let(VaultCodec::decodeSettings) ?: VaultSettings()264265    override fun writeSettings(settings: VaultSettings): Boolean =266        prefs.edit().putString(KEY_SETTINGS, VaultCodec.encodeSettings(settings)).commit()267268    override fun loadVaultHistory(): VaultHistory =269        prefs.getString(KEY_HISTORY, null)?.let(VaultCodec::decodeHistory) ?: VaultHistory()270271    override fun writeVaultHistory(history: VaultHistory): Boolean =272        prefs.edit().putString(KEY_HISTORY, VaultCodec.encodeHistory(history)).commit()273274    override fun clearVaultHistory() {275        prefs.edit().remove(KEY_HISTORY).commit()276    }277278    override fun clearVault() {279        // H-04: the duress record is part of the vault's at-rest surface and must280        // go with slot A — leaving it behind on a half-built vault is the281        // forensic tell the audit flagged.282        prefs.edit()283            .remove(KEY_SLOT_A).remove(KEY_SLOT_B).remove(KEY_SLOT_DURESS)284            .remove(KEY_VERSION).remove(KEY_SETTINGS).remove(KEY_HISTORY)285            .remove("peach_pin_salt").remove("peach_pin_verifier").remove("peach_pin_wrapped_key")286            .remove("peach_pin_preferred")287            .remove("peach_pin_format").remove("peach_pin_salt_v2")288            .remove("peach_pin_verifier_v2").remove("peach_pin_wrapped_key_v2")289            .remove("peach_pin_wrapped_iv_v2").remove("peach_pin_attempt_aliases_v2")290            .remove("peach_pin_preferred_v2")291            .commit()292    }293294    companion object {295        private const val PREFS = "peach_vault_store"296        private const val KEY_SLOT_A = "peach_vault_a"297        private const val KEY_SLOT_B = "peach_vault_b"298        private const val KEY_SLOT_DURESS = "peach_vault_duress"299        private const val KEY_VERSION = "peach_last_modified_at"300        private const val KEY_SETTINGS = "peach_settings"301        private const val KEY_HISTORY = "peach_vault_history"302    }303}