# D13 — Duress Password Setup — Integration Guide Three drafted files in `app/drafts/D13/`: | Draft file | Destination | Kind | |---|---|---| | `DuressConfig.kt` | `app/src/main/java/com/peachpasswords/vault/DuressConfig.kt` | new drop-in file (package `com.peachpasswords.vault`) | | `DuressSection.kt` | merge into `ui/settings/SettingsCardBodies.kt` (or drop as a sibling file in package `com.peachpasswords.ui.settings`) | UI composable | | `LockViewModel_unlock_integration.kt` | hand-merge into `ui/lock/LockViewModel.kt` | snippet, NOT a file | D13 is the **only** item touching `LockViewModel`. Integrate the unlock snippet last and carefully. --- ## 1. `DuressConfig.kt` — drop in as-is New file, package `com.peachpasswords.vault`. No edits to existing files needed for this piece. - `@Singleton class DuressConfigStore @Inject constructor(@ApplicationContext context)` — Hilt provides it automatically (constructor injection, same pattern as `LicenseRepository`). - Stores `{v, salt, hash, action}` JSON under key `"duress_config"` in its own `EncryptedSharedPreferences` file `peach_duress_prefs`. **Never plaintext** — only the Argon2id hash + its salt. - Public API: - `fun isConfigured(): Boolean` - `fun storedAction(): DuressAction?` - `fun save(password: String, action: DuressAction): Boolean` - `fun clear(): Boolean` - `fun verify(password: String): DuressMatch` (`DuressMatch.None` | `DuressMatch.Match(action)`) - `enum class DuressAction(val wire)` = `DECOY` / `DESTROY`. - 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. > **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. --- ## 2. `DuressSection.kt` — wire into `ProtectionBody` ### 2a. New VM members on `SettingsViewModel` `SettingsViewModel` already injects `private val vault: VaultRepository` and `@ApplicationContext appContext`. Add the duress store + three members: ```kotlin // constructor param (add): private val duress: com.peachpasswords.vault.DuressConfigStore, // state — seed from the store; flip on save/disable: private val _duressConfigured = MutableStateFlow(duress.isConfigured()) val duressConfigured: StateFlow = _duressConfigured.asStateFlow() suspend fun saveDuress(password: String, action: com.peachpasswords.vault.DuressAction): Boolean { val ok = duress.save(password, action) if (ok) _duressConfigured.value = true return ok } fun disableDuress() { duress.clear() _duressConfigured.value = false } ``` Import `com.peachpasswords.vault.DuressAction` (or use the FQN as above). ### 2b. Replace the static duress row in `ProtectionBody` Current anchor in `SettingsCardBodies.kt` (lines ~272–279): ```kotlin SubLabel("DURESS PASSWORD", fg) RowLine(fg) { Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Name("Duress password", fg); ProBadge(fg) } ValueText("off", fg) } Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Arrives with Pro sync.", fg) ``` Replace the `RowLine { … }` + `Hint(…)` block (keep the `SubLabel`) with the Pro gate: ```kotlin SubLabel("DURESS PASSWORD", fg) val isPro by vm.isPro.collectAsState() // already imported in this file if (!isPro) { RowLine(fg) { Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Name("Duress password", fg); ProBadge(fg) } ValueText("off", fg) } Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg) } else { DuressSection(fg, vm) } ``` `isPro` is already collected elsewhere in this file (e.g. `VaultBody`), so the `collectAsState` import is present. ### 2c. Visibility of shared row helpers — REQUIRED edit `DuressSection` calls helpers that are currently **`private`** in `SettingsCardBodies.kt`: `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. Pick ONE: - **(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. - **(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. `DuressSection` itself is declared `internal`. --- ## 3. `LockViewModel.unlock` integration (the careful one) See `LockViewModel_unlock_integration.kt` for the full annotated snippet. Summary: ### 3a. New constructor dep ```kotlin private val duress: com.peachpasswords.vault.DuressConfigStore, ``` ### 3b. New `LockUiState` flag ```kotlin /** Real vault was wiped by a destroy-duress unlock → route to CreateVault. */ val duressDestroyed: Boolean = false, ``` The LockScreen should treat `duressDestroyed == true` like `hasVault == false` (drop to CreateVault). The decoy path reuses the existing `unlocked = true`. ### 3c. Insertion point Anchor — the current `unlock` body (lines 42–56): ```kotlin fun unlock(password: String) { if (password.isBlank() || _state.value.loading) return _state.update { it.copy(loading = true, error = null) } viewModelScope.launch { when (val r = vault.unlock(password)) { ``` Insert the duress check as the **first** thing inside the `viewModelScope.launch`, before `vault.unlock(password)`: ```kotlin when (val d = duress.verify(password)) { is DuressMatch.Match -> { handleDuress(d.action); return@launch } DuressMatch.None -> Unit } ``` Add the `private suspend fun handleDuress(action: DuressAction)` helper (full body in the snippet file). ### 3d. New imports for LockViewModel.kt ```kotlin import com.peachpasswords.vault.DuressAction import com.peachpasswords.vault.DuressConfigStore import com.peachpasswords.vault.DuressMatch ``` > 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`). --- ## 4. Decoy vault — `"duress_vault"` slot — NEW VaultRepository + VaultStorage API The 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. ### 4a. `VaultStorage` interface + `VaultStore` (in `VaultStore.kt`) Add a third slot keyed `peach_vault_duress`. New interface methods: ```kotlin interface VaultStorage { // …existing… fun loadDecoySlot(): StoredVault? fun writeDecoySlot(slot: StoredVault): Boolean fun hasDecoySlot(): Boolean fun clearDecoySlot() } ``` `VaultStore` impl (mirror the slot-A methods): ```kotlin override fun loadDecoySlot(): StoredVault? = prefs.getString(KEY_SLOT_DURESS, null)?.let(VaultCodec::decodeSlot) override fun writeDecoySlot(slot: StoredVault): Boolean = prefs.edit().putString(KEY_SLOT_DURESS, VaultCodec.encodeSlot(slot)).commit() override fun hasDecoySlot(): Boolean = prefs.contains(KEY_SLOT_DURESS) override fun clearDecoySlot() { prefs.edit().remove(KEY_SLOT_DURESS).commit() } // companion: private const val KEY_SLOT_DURESS = "peach_vault_duress" ``` Note: 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. ### 4b. `VaultRepository.unlockDecoy()` The decoy must be sealed under a key the **decoy** can re-open without a password. Simplest faithful approach: derive the decoy key from a **fixed decoy salt + the duress action's own marker**, OR — cleaner — seal the decoy slot under a random key wrapped by the duress hash. Recommended minimal implementation: create the decoy on first use with a fresh salt and a fixed sentinel password derived from the duress store, and keep it as an ordinary `StoredVault` the repo can open with a key it derives the same way each time. Reference impl: ```kotlin /** * Unlock into the decoy vault. Creates an empty decoy on first use. The real * slot A is never read here, so the real vault stays sealed and hidden. The * decoy session is a normal unlocked session over a separate, empty entry list. */ suspend fun unlockDecoy(): UnlockResult = mutex.withLock { return try { val existing = store.loadDecoySlot() if (existing == null) { // mint an empty decoy: fresh salt + fresh random key (stored wrapped // is overkill — the decoy holds nothing secret). Use a fixed-derived // key so a later unlockDecoy re-opens the same blob. val salt = VaultCrypto.generateSalt() val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt) entryList = mutableListOf() duressConfigured = false recoveryWordHash = null recoveryWordsSet = false rootKey = VaultCrypto.generateRootKey() val plaintext = VaultCodec.encode(currentPayload()) val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A)) store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob)) derivedKey = key publish(); _isUnlocked.value = true UnlockResult.Success } else { val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt)) val payload = VaultCodec.decode( VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A), ) derivedKey = key entryList = payload.entries.toMutableList() rootKey = unb64(payload.rootKeyB64.ifBlank { b64(VaultCrypto.generateRootKey()) }) publish(); _isUnlocked.value = true UnlockResult.Success } } catch (e: Exception) { UnlockResult.Error(e.message ?: "decoy_unlock_failed") } } private companion object { const val DECOY_SENTINEL = "peach_decoy_v1" } ``` `destroyVault()` should also `store.clearDecoySlot()` so a wipe removes the decoy too (one-line add inside the existing `destroyVault`). > **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. ### 4c. Persistence note for decoy edits Existing `persistSlotA()` always writes the **real** slot A. If the user can add entries inside the decoy session, those writes would currently hit slot A — WRONG. Either (a) make the decoy session read-only/non-persistent (simplest; the decoy is throwaway), or (b) add a `private var activeSlot` flag so `persistSlotA` targets the decoy slot during a decoy session. **Recommend (a)** for this pass: the decoy is a believable empty vault, not a working one. Note it in the save message. --- ## 5. Summary of all new APIs the orchestrator must add | Where | Signature | |---|---| | `vault/DuressConfig.kt` (new file) | whole file — `DuressConfigStore`, `DuressAction`, `DuressMatch` | | `SettingsViewModel` | ctor `duress: DuressConfigStore`; `val duressConfigured: StateFlow`; `suspend fun saveDuress(pw, action): Boolean`; `fun disableDuress()` | | `SettingsCardBodies.kt` | replace duress `RowLine`+`Hint` with Pro gate calling `DuressSection`; loosen `private`→`internal` on shared helpers OR inline the section | | `LockViewModel` | ctor `duress: DuressConfigStore`; `LockUiState.duressDestroyed: Boolean`; duress check at top of `unlock`; `private suspend fun handleDuress(action)` | | `VaultStorage`/`VaultStore` + test fake | `loadDecoySlot/writeDecoySlot/hasDecoySlot/clearDecoySlot` + `KEY_SLOT_DURESS = "peach_vault_duress"` | | `VaultRepository` | `suspend fun unlockDecoy(): UnlockResult`; `DECOY_SENTINEL` const; `clearDecoySlot()` call inside `destroyVault()` | | LockScreen UI | treat `duressDestroyed` like `!hasVault` → CreateVault | ## 6. Risks / assumptions - `EncryptedSharedPreferences` + `MasterKey` are already used (LicenseRepository), so the `androidx.security:security-crypto` dep is present — no gradle change. - `org.json` used for the duress blob (platform built-in). Swap to kotlinx-serialization if you prefer parity with `VaultCodec`. - Decoy slot is intentionally low-security (fixed sentinel key) — documented trade-off in §4b. The real vault's protection is unchanged. - Decoy session is recommended read-only this pass (§4c) to avoid clobbering slot A through `persistSlotA`. - 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. - 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.