INTEGRATION.md

14.2 KB · raw

rendered · source

1# D13 — Duress Password Setup — Integration Guide23Three drafted files in `app/drafts/D13/`:45| Draft file | Destination | Kind |6|---|---|---|7| `DuressConfig.kt` | `app/src/main/java/com/peachpasswords/vault/DuressConfig.kt` | new drop-in file (package `com.peachpasswords.vault`) |8| `DuressSection.kt` | merge into `ui/settings/SettingsCardBodies.kt` (or drop as a sibling file in package `com.peachpasswords.ui.settings`) | UI composable |9| `LockViewModel_unlock_integration.kt` | hand-merge into `ui/lock/LockViewModel.kt` | snippet, NOT a file |1011D13 is the **only** item touching `LockViewModel`. Integrate the unlock snippet last and carefully.1213---1415## 1. `DuressConfig.kt` — drop in as-is1617New file, package `com.peachpasswords.vault`. No edits to existing files needed for this piece.1819- `@Singleton class DuressConfigStore @Inject constructor(@ApplicationContext context)` — Hilt provides it automatically (constructor injection, same pattern as `LicenseRepository`).20- Stores `{v, salt, hash, action}` JSON under key `"duress_config"` in its own21  `EncryptedSharedPreferences` file `peach_duress_prefs`. **Never plaintext** — only the Argon2id hash + its salt.22- Public API:23  - `fun isConfigured(): Boolean`24  - `fun storedAction(): DuressAction?`25  - `fun save(password: String, action: DuressAction): Boolean`26  - `fun clear(): Boolean`27  - `fun verify(password: String): DuressMatch`  (`DuressMatch.None` | `DuressMatch.Match(action)`)28- `enum class DuressAction(val wire)` = `DECOY` / `DESTROY`.29- Uses `org.json.JSONObject` (already on the Android platform — no new dep). If you prefer kotlinx-serialization for consistency with `VaultCodec`, swap the JSON block; the rest is unaffected.3031> **Salt design note:** the duress hash uses its OWN fresh salt, stored beside the hash. The duress password therefore CANNOT be verified by comparing against the slot-A-derived key (different salt). `verify()` re-derives Argon2id over the stored salt and constant-time-compares. This is the only correct comparison of two independently-salted Argon2id secrets, and is why the unlock integration verifies the *password*, not a key.3233---3435## 2. `DuressSection.kt` — wire into `ProtectionBody`3637### 2a. New VM members on `SettingsViewModel`3839`SettingsViewModel` already injects `private val vault: VaultRepository` and `@ApplicationContext appContext`. Add the duress store + three members:4041```kotlin42// constructor param (add):43private val duress: com.peachpasswords.vault.DuressConfigStore,4445// state — seed from the store; flip on save/disable:46private val _duressConfigured = MutableStateFlow(duress.isConfigured())47val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()4849suspend fun saveDuress(password: String, action: com.peachpasswords.vault.DuressAction): Boolean {50    val ok = duress.save(password, action)51    if (ok) _duressConfigured.value = true52    return ok53}5455fun disableDuress() {56    duress.clear()57    _duressConfigured.value = false58}59```6061Import `com.peachpasswords.vault.DuressAction` (or use the FQN as above).6263### 2b. Replace the static duress row in `ProtectionBody`6465Current anchor in `SettingsCardBodies.kt` (lines ~272–279):6667```kotlin68    SubLabel("DURESS PASSWORD", fg)69    RowLine(fg) {70        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {71            Name("Duress password", fg); ProBadge(fg)72        }73        ValueText("off", fg)74    }75    Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Arrives with Pro sync.", fg)76```7778Replace the `RowLine { … }` + `Hint(…)` block (keep the `SubLabel`) with the Pro gate:7980```kotlin81    SubLabel("DURESS PASSWORD", fg)82    val isPro by vm.isPro.collectAsState()   // already imported in this file83    if (!isPro) {84        RowLine(fg) {85            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {86                Name("Duress password", fg); ProBadge(fg)87            }88            ValueText("off", fg)89        }90        Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg)91    } else {92        DuressSection(fg, vm)93    }94```9596`isPro` is already collected elsewhere in this file (e.g. `VaultBody`), so the `collectAsState` import is present.9798### 2c. Visibility of shared row helpers — REQUIRED edit99100`DuressSection` calls helpers that are currently **`private`** in `SettingsCardBodies.kt`:101`RowLine`, `RowScope.Name`, `Toggle`, `PwField`, `Hint`. Kotlin `private` is *file*-scoped, so they are NOT visible from a separate file even in the same package.102103Pick ONE:104105- **(preferred)** Paste the `DuressSection.kt` composables (everything from `DuressSection` down, dropping the `package`/`import` header) directly into `SettingsCardBodies.kt` near `ChangePasswordRow`. Then no visibility change is needed. Reconcile imports: `DuressSection.kt` adds `PeachColors`, `DuressAction`, `LocalPeachAccent`, `CircleShape`, `SolidColor` usages — most already imported; add any missing.106- **(alt)** Change `RowLine`, `Name`, `Toggle`, `PwField`, `Hint` from `private` to `internal` and keep `DuressSection.kt` as a sibling file. Lowest-churn but widens their scope.107108`DuressSection` itself is declared `internal`.109110---111112## 3. `LockViewModel.unlock` integration (the careful one)113114See `LockViewModel_unlock_integration.kt` for the full annotated snippet. Summary:115116### 3a. New constructor dep117```kotlin118private val duress: com.peachpasswords.vault.DuressConfigStore,119```120121### 3b. New `LockUiState` flag122```kotlin123/** Real vault was wiped by a destroy-duress unlock → route to CreateVault. */124val duressDestroyed: Boolean = false,125```126The LockScreen should treat `duressDestroyed == true` like `hasVault == false` (drop to CreateVault). The decoy path reuses the existing `unlocked = true`.127128### 3c. Insertion point129Anchor — the current `unlock` body (lines 42–56):130131```kotlin132    fun unlock(password: String) {133        if (password.isBlank() || _state.value.loading) return134        _state.update { it.copy(loading = true, error = null) }135        viewModelScope.launch {136            when (val r = vault.unlock(password)) {137```138139Insert the duress check as the **first** thing inside the `viewModelScope.launch`, before `vault.unlock(password)`:140141```kotlin142            when (val d = duress.verify(password)) {143                is DuressMatch.Match -> { handleDuress(d.action); return@launch }144                DuressMatch.None -> Unit145            }146```147148Add the `private suspend fun handleDuress(action: DuressAction)` helper (full body in the snippet file).149150### 3d. New imports for LockViewModel.kt151```kotlin152import com.peachpasswords.vault.DuressAction153import com.peachpasswords.vault.DuressConfigStore154import com.peachpasswords.vault.DuressMatch155```156157> Duress verify runs an Argon2id derivation (≈ same cost as a normal unlock). It runs once per unlock attempt, inside the existing coroutine — acceptable. If you want to avoid the cost when no duress is set, guard with `if (duress.isConfigured()) { … }` (cheap prefs `contains`).158159---160161## 4. Decoy vault — `"duress_vault"` slot — NEW VaultRepository + VaultStorage API162163The brief: decoy action "unlock into a separate empty/minimal vault (creates one if not present, stored under `duress_vault` slot)". This needs new methods on the (read-only here) repo + store. Specify, don't edit.164165### 4a. `VaultStorage` interface + `VaultStore` (in `VaultStore.kt`)166167Add a third slot keyed `peach_vault_duress`. New interface methods:168169```kotlin170interface VaultStorage {171    // …existing…172    fun loadDecoySlot(): StoredVault?173    fun writeDecoySlot(slot: StoredVault): Boolean174    fun hasDecoySlot(): Boolean175    fun clearDecoySlot()176}177```178179`VaultStore` impl (mirror the slot-A methods):180181```kotlin182override fun loadDecoySlot(): StoredVault? =183    prefs.getString(KEY_SLOT_DURESS, null)?.let(VaultCodec::decodeSlot)184override fun writeDecoySlot(slot: StoredVault): Boolean =185    prefs.edit().putString(KEY_SLOT_DURESS, VaultCodec.encodeSlot(slot)).commit()186override fun hasDecoySlot(): Boolean = prefs.contains(KEY_SLOT_DURESS)187override fun clearDecoySlot() { prefs.edit().remove(KEY_SLOT_DURESS).commit() }188189// companion:190private const val KEY_SLOT_DURESS = "peach_vault_duress"191```192193Note: the **in-memory fake** used by repository tests must also implement these four methods (add no-op/MutableMap-backed versions) or the tests won't compile.194195### 4b. `VaultRepository.unlockDecoy()`196197The decoy must be sealed under a key the **decoy** can re-open without a password.198Simplest faithful approach: derive the decoy key from a **fixed decoy salt + the199duress action's own marker**, OR — cleaner — seal the decoy slot under a random200key wrapped by the duress hash. Recommended minimal implementation: create the201decoy on first use with a fresh salt and a fixed sentinel password derived from202the duress store, and keep it as an ordinary `StoredVault` the repo can open with203a key it derives the same way each time. Reference impl:204205```kotlin206/**207 * Unlock into the decoy vault. Creates an empty decoy on first use. The real208 * slot A is never read here, so the real vault stays sealed and hidden. The209 * decoy session is a normal unlocked session over a separate, empty entry list.210 */211suspend fun unlockDecoy(): UnlockResult = mutex.withLock {212    return try {213        val existing = store.loadDecoySlot()214        if (existing == null) {215            // mint an empty decoy: fresh salt + fresh random key (stored wrapped216            // is overkill — the decoy holds nothing secret). Use a fixed-derived217            // key so a later unlockDecoy re-opens the same blob.218            val salt = VaultCrypto.generateSalt()219            val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)220            entryList = mutableListOf()221            duressConfigured = false222            recoveryWordHash = null223            recoveryWordsSet = false224            rootKey = VaultCrypto.generateRootKey()225            val plaintext = VaultCodec.encode(currentPayload())226            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))227            store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))228            derivedKey = key229            publish(); _isUnlocked.value = true230            UnlockResult.Success231        } else {232            val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))233            val payload = VaultCodec.decode(234                VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),235            )236            derivedKey = key237            entryList = payload.entries.toMutableList()238            rootKey = unb64(payload.rootKeyB64.ifBlank { b64(VaultCrypto.generateRootKey()) })239            publish(); _isUnlocked.value = true240            UnlockResult.Success241        }242    } catch (e: Exception) {243        UnlockResult.Error(e.message ?: "decoy_unlock_failed")244    }245}246247private companion object { const val DECOY_SENTINEL = "peach_decoy_v1" }248```249250`destroyVault()` should also `store.clearDecoySlot()` so a wipe removes the decoy too (one-line add inside the existing `destroyVault`).251252> **Trade-off to flag for the orchestrator:** `DECOY_SENTINEL` is a fixed in-app constant, so a forensic attacker with the APK could open the decoy slot. That's acceptable — the decoy holds nothing secret by design; its only job is to look like a real (empty) vault to a coercer. The *real* vault remains protected by the master password. If stronger separation is wanted, wrap the decoy key under the duress Argon2id hash instead (the duress password would then open the decoy directly), but that couples the two stores. Recommend shipping the simple version.253254### 4c. Persistence note for decoy edits255Existing `persistSlotA()` always writes the **real** slot A. If the user can add256entries inside the decoy session, those writes would currently hit slot A — WRONG.257Either (a) make the decoy session read-only/non-persistent (simplest; the decoy is258throwaway), or (b) add a `private var activeSlot` flag so `persistSlotA` targets the259decoy slot during a decoy session. **Recommend (a)** for this pass: the decoy is a260believable empty vault, not a working one. Note it in the save message.261262---263264## 5. Summary of all new APIs the orchestrator must add265266| Where | Signature |267|---|---|268| `vault/DuressConfig.kt` (new file) | whole file — `DuressConfigStore`, `DuressAction`, `DuressMatch` |269| `SettingsViewModel` | ctor `duress: DuressConfigStore`; `val duressConfigured: StateFlow<Boolean>`; `suspend fun saveDuress(pw, action): Boolean`; `fun disableDuress()` |270| `SettingsCardBodies.kt` | replace duress `RowLine`+`Hint` with Pro gate calling `DuressSection`; loosen `private`→`internal` on shared helpers OR inline the section |271| `LockViewModel` | ctor `duress: DuressConfigStore`; `LockUiState.duressDestroyed: Boolean`; duress check at top of `unlock`; `private suspend fun handleDuress(action)` |272| `VaultStorage`/`VaultStore` + test fake | `loadDecoySlot/writeDecoySlot/hasDecoySlot/clearDecoySlot` + `KEY_SLOT_DURESS = "peach_vault_duress"` |273| `VaultRepository` | `suspend fun unlockDecoy(): UnlockResult`; `DECOY_SENTINEL` const; `clearDecoySlot()` call inside `destroyVault()` |274| LockScreen UI | treat `duressDestroyed` like `!hasVault` → CreateVault |275276## 6. Risks / assumptions277- `EncryptedSharedPreferences` + `MasterKey` are already used (LicenseRepository), so the `androidx.security:security-crypto` dep is present — no gradle change.278- `org.json` used for the duress blob (platform built-in). Swap to kotlinx-serialization if you prefer parity with `VaultCodec`.279- Decoy slot is intentionally low-security (fixed sentinel key) — documented trade-off in §4b. The real vault's protection is unchanged.280- Decoy session is recommended read-only this pass (§4c) to avoid clobbering slot A through `persistSlotA`.281- Existing `VaultSettings.duressConfigured` / `VaultPayload.duressConfigured` flags are NOT the source of truth here — the encrypted `DuressConfigStore` is. Leave those legacy flags alone (they predate D13); the UI reads `vm.duressConfigured` which is backed by the store. Optionally keep them in sync, but the store must remain authoritative since it's the only thing readable before unlock.282- No new tests drafted (cannot run gradle). Suggested coverage for the orchestrator: `DuressConfigStore.save → verify` round-trip (match + non-match), `clear` removes config, decoy round-trip via the repo fake.