ee4e7604872f

feat: D13 duress password (Pro-gated) — DuressConfigStore (Argon2id hash, never plaintext) + ProtectionBody form, LockViewModel unlock integration (decoy vault slot / destroy), decoy-mode persistence isolated from real slot A (v2.1.36)

time
2026-06-09 04:52 UTC · 5 months ago
machine
koh2
agent
claude-opus-4-8
session
peach remaining gaps
parent
ea7e63f21211
11 files app/drafts/D13/DuressConfig.kt+0 −144app/drafts/D13/DuressSection.kt+0 −201app/drafts/D13/LockViewModel_unlock_integration.kt+0 −96app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+31 −0app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+142 −5app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+15 −0app/src/main/java/com/peachpasswords/vault/DuressConfig.kt+144 −0app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+63 −0app/src/main/java/com/peachpasswords/vault/VaultStore.kt+11 −0app/src/test/java/com/peachpasswords/sync/VaultSyncAdapterTest.kt+5 −0app/src/test/java/com/peachpasswords/vault/VaultRepositoryTest.kt+5 −0
app/drafts/D13/DuressConfig.kt+0 −144
@@ -1,144 +0,0 @@1-package com.peachpasswords.vault2-3-import android.content.Context4-import androidx.security.crypto.EncryptedSharedPreferences5-import androidx.security.crypto.MasterKey6-import dagger.hilt.android.qualifiers.ApplicationContext7-import org.json.JSONObject8-import java.util.Base649-import javax.inject.Inject10-import javax.inject.Singleton11-12-/**13- * The action Peach takes when the duress password is entered at the lock screen.14- *15- *  - [DECOY]   open a separate empty/minimal "decoy" vault; the real vault stays16- *              sealed and hidden.17- *  - [DESTROY] irreversibly wipe the real vault, then drop to CreateVault.18- *19- * Persisted as the lowercase [wire] string so a future schema migration sees a20- * stable token, never an ordinal.21- */22-enum class DuressAction(val wire: String) {23-    DECOY("decoy"),24-    DESTROY("destroy");25-26-    companion object {27-        fun fromWire(s: String?): DuressAction =28-            entries.firstOrNull { it.wire == s } ?: DECOY29-    }30-}31-32-/**33- * What [DuressConfigStore.verify] reports for an entered lock-screen password.34- * [None] means "not the duress password" — the caller falls through to the35- * normal vault unlock path. The verifier never decides policy; it only matches.36- */37-sealed interface DuressMatch {38-    data object None : DuressMatch39-    data class Match(val action: DuressAction) : DuressMatch40-}41-42-/**43- * Stores the duress password as an Argon2id hash (never plaintext) plus the44- * selected [DuressAction], in a dedicated EncryptedSharedPreferences file under45- * the single key "duress_config".46- *47- * The hash is the Argon2id output of the duress password over a freshly-minted48- * 16-byte salt, using the SAME parameters as the vault KDF ([VaultCrypto]). The49- * salt is stored alongside the hash (base64) — it is not secret; it only forces50- * the verifier to re-derive rather than compare a precomputed digest. This51- * mirrors the at-rest model of slot A, whose salt is likewise in the clear.52- *53- * Why a separate prefs file (not the slot-A payload): the duress password must be54- * verifiable BEFORE the real vault is unlocked. It cannot live inside the55- * AES-GCM blob that only the real master password can open. The license store56- * uses the same EncryptedSharedPreferences pattern (see LicenseRepository).57- */58-@Singleton59-class DuressConfigStore @Inject constructor(60-    @ApplicationContext context: Context,61-) {62-    private val masterKey = MasterKey.Builder(context)63-        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)64-        .build()65-66-    private val prefs = EncryptedSharedPreferences.create(67-        context,68-        PREFS_FILE,69-        masterKey,70-        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,71-        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,72-    )73-74-    fun isConfigured(): Boolean = prefs.contains(KEY_DURESS_CONFIG)75-76-    fun storedAction(): DuressAction? =77-        load()?.let { DuressAction.fromWire(it.optString(FIELD_ACTION)) }78-79-    /**80-     * Hash [password] with Argon2id over a fresh salt and persist {salt, hash,81-     * action}. Overwrites any prior duress config. Returns false if the value82-     * could not be committed.83-     */84-    fun save(password: String, action: DuressAction): Boolean {85-        val salt = VaultCrypto.generateSalt()86-        val hash = VaultCrypto.deriveKey(password, salt)87-        val json = JSONObject().apply {88-            put(FIELD_VERSION, 1)89-            put(FIELD_SALT, b64(salt))90-            put(FIELD_HASH, b64(hash))91-            put(FIELD_ACTION, action.wire)92-        }93-        VaultCrypto.zero(hash)94-        return prefs.edit().putString(KEY_DURESS_CONFIG, json.toString()).commit()95-    }96-97-    fun clear(): Boolean = prefs.edit().remove(KEY_DURESS_CONFIG).commit()98-99-    /**100-     * Check [password] against the stored duress hash. Re-derives the Argon2id101-     * key over the stored salt and constant-time-compares against the stored102-     * hash. Returns [DuressMatch.None] when no config exists or the password is103-     * not the duress password.104-     */105-    fun verify(password: String): DuressMatch {106-        val json = load() ?: return DuressMatch.None107-        val salt = runCatching { unb64(json.getString(FIELD_SALT)) }.getOrNull()108-            ?: return DuressMatch.None109-        val expected = runCatching { unb64(json.getString(FIELD_HASH)) }.getOrNull()110-            ?: return DuressMatch.None111-        val derived = VaultCrypto.deriveKey(password, salt)112-        val matches = constantTimeEquals(derived, expected)113-        VaultCrypto.zero(derived)114-        return if (matches) {115-            DuressMatch.Match(DuressAction.fromWire(json.optString(FIELD_ACTION)))116-        } else {117-            DuressMatch.None118-        }119-    }120-121-    private fun load(): JSONObject? =122-        prefs.getString(KEY_DURESS_CONFIG, null)?.let { runCatching { JSONObject(it) }.getOrNull() }123-124-    private fun constantTimeEquals(a: ByteArray, b: ByteArray): Boolean {125-        if (a.size != b.size) return false126-        var diff = 0127-        for (i in a.indices) diff = diff or (a[i].toInt() xor b[i].toInt())128-        return diff == 0129-    }130-131-    private fun b64(bytes: ByteArray): String =132-        Base64.getEncoder().withoutPadding().encodeToString(bytes)133-134-    private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)135-136-    companion object {137-        private const val PREFS_FILE = "peach_duress_prefs"138-        private const val KEY_DURESS_CONFIG = "duress_config"139-        private const val FIELD_VERSION = "v"140-        private const val FIELD_SALT = "salt"141-        private const val FIELD_HASH = "hash"142-        private const val FIELD_ACTION = "action"143-    }144-}

view file at the parent

app/drafts/D13/DuressSection.kt+0 −201
@@ -1,201 +0,0 @@1-package com.peachpasswords.ui.settings2-3-import androidx.compose.animation.AnimatedVisibility4-import androidx.compose.foundation.background5-import androidx.compose.foundation.border6-import androidx.compose.foundation.clickable7-import androidx.compose.foundation.layout.Arrangement8-import androidx.compose.foundation.layout.Box9-import androidx.compose.foundation.layout.Column10-import androidx.compose.foundation.layout.Row11-import androidx.compose.foundation.layout.Spacer12-import androidx.compose.foundation.layout.fillMaxWidth13-import androidx.compose.foundation.layout.height14-import androidx.compose.foundation.layout.padding15-import androidx.compose.foundation.layout.size16-import androidx.compose.foundation.layout.width17-import androidx.compose.foundation.shape.CircleShape18-import androidx.compose.foundation.shape.RoundedCornerShape19-import androidx.compose.foundation.text.BasicTextField20-import androidx.compose.material3.Text21-import androidx.compose.runtime.Composable22-import androidx.compose.runtime.collectAsState23-import androidx.compose.runtime.getValue24-import androidx.compose.runtime.mutableStateOf25-import androidx.compose.runtime.remember26-import androidx.compose.runtime.rememberCoroutineScope27-import androidx.compose.runtime.setValue28-import androidx.compose.ui.Alignment29-import androidx.compose.ui.Modifier30-import androidx.compose.ui.draw.clip31-import androidx.compose.ui.graphics.Color32-import androidx.compose.ui.graphics.SolidColor33-import androidx.compose.ui.text.TextStyle34-import androidx.compose.ui.text.input.PasswordVisualTransformation35-import androidx.compose.ui.unit.dp36-import androidx.compose.ui.unit.sp37-import com.peachpasswords.ui.theme.PeachColors38-import com.peachpasswords.ui.theme.PeachType39-import com.peachpasswords.vault.DuressAction40-import kotlinx.coroutines.launch41-42-/**43- * D13 — Duress password setup, rendered inside ProtectionBody under the44- * "DURESS PASSWORD" sub-label. Self-contained so it can drop into the existing45- * Protection card without restructuring it.46- *47- * Pro gate is the caller's responsibility: ProtectionBody renders the static48- * ProBadge row when !isPro and this composable only when isPro (see49- * INTEGRATION.md). All visuals use the card foreground [fg] like sibling rows.50- *51- * Relies on these row helpers already private in SettingsCardBodies.kt:52- * [RowLine], [RowScope.Name], [Toggle], [SubtleButton], [Hint], [PwField].53- * Because this lives in the same package it can call them directly once merged.54- */55-@Composable56-internal fun DuressSection(fg: Color, vm: SettingsViewModel) {57-    val configured by vm.duressConfigured.collectAsState()58-59-    if (configured) {60-        DuressActiveState(fg, vm)61-    } else {62-        DuressForm(fg, vm)63-    }64-}65-66-@Composable67-private fun DuressActiveState(fg: Color, vm: SettingsViewModel) {68-    RowLine(fg) {69-        Name("Duress password is active", fg)70-    }71-    Text(72-        "Duress password is active",73-        color = PeachColors.HealthOk,74-        fontFamily = PeachType.Mono,75-        fontSize = 11.sp,76-        modifier = Modifier.padding(top = 6.dp),77-    )78-    Spacer(Modifier.height(8.dp))79-    DangerGhostButton("Disable duress password", fg) { vm.disableDuress() }80-    Hint("Entering your duress password instead of your real one triggers the action you chose.", fg)81-}82-83-@Composable84-private fun DuressForm(fg: Color, vm: SettingsViewModel) {85-    var enabled by remember { mutableStateOf(false) }86-    var password by remember { mutableStateOf("") }87-    var confirm by remember { mutableStateOf("") }88-    var action by remember { mutableStateOf(DuressAction.DECOY) }89-    var error by remember { mutableStateOf<String?>(null) }90-    val scope = rememberCoroutineScope()91-92-    RowLine(fg) {93-        Name("Duress password", fg)94-        Toggle(enabled, fg) { on ->95-            enabled = on96-            if (!on) { password = ""; confirm = ""; error = null }97-        }98-    }99-    Text(100-        "Entering your duress password instead of your real one opens a decoy vault or wipes the real one.",101-        color = fg.copy(alpha = 0.7f),102-        fontFamily = PeachType.Mono,103-        fontSize = 10.sp,104-        modifier = Modifier.padding(top = 6.dp),105-    )106-107-    AnimatedVisibility(enabled) {108-        Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {109-            PwField("DURESS PASSWORD", password, fg) { password = it; error = null }110-            PwField("CONFIRM DURESS PASSWORD", confirm, fg) { confirm = it; error = null }111-112-            Text(113-                "When your duress password is entered at the lock screen, Peach will:",114-                color = fg.copy(alpha = 0.7f),115-                fontFamily = PeachType.Mono,116-                fontSize = 10.sp,117-                modifier = Modifier.padding(top = 4.dp),118-            )119-120-            RadioOption("Show a decoy vault", action == DuressAction.DECOY, fg) { action = DuressAction.DECOY }121-            RadioOption("Destroy the real vault", action == DuressAction.DESTROY, fg) { action = DuressAction.DESTROY }122-123-            error?.let {124-                Text(it, color = PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp)125-            }126-127-            val canSave = password.isNotBlank() && confirm.isNotBlank()128-            SaveButton("Save duress password", fg, canSave) {129-                error = when {130-                    password.isBlank() || confirm.isBlank() -> "Enter and confirm a duress password"131-                    password != confirm -> "Passwords do not match"132-                    else -> null133-                }134-                if (error == null) scope.launch {135-                    if (vm.saveDuress(password, action)) {136-                        password = ""; confirm = ""; enabled = false137-                    } else {138-                        error = "Couldn't save duress password"139-                    }140-                }141-            }142-        }143-    }144-}145-146-/* ── local controls (kept private to D13; the radio + variants don't exist in147-   the shared row vocabulary) ─────────────────────────────────────────────── */148-149-@Composable150-private fun RadioOption(label: String, selected: Boolean, fg: Color, onClick: () -> Unit) {151-    val accent = com.peachpasswords.ui.theme.LocalPeachAccent.current152-    Row(153-        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick)154-            .padding(vertical = 7.dp),155-        verticalAlignment = Alignment.CenterVertically,156-        horizontalArrangement = Arrangement.spacedBy(10.dp),157-    ) {158-        Box(159-            Modifier.size(16.dp).clip(CircleShape)160-                .border(1.dp, if (selected) accent else fg.copy(alpha = 0.4f), CircleShape),161-            contentAlignment = Alignment.Center,162-        ) {163-            if (selected) Box(Modifier.size(8.dp).clip(CircleShape).background(accent))164-        }165-        Text(166-            label,167-            color = if (selected) accent else fg,168-            fontFamily = PeachType.Mono,169-            fontSize = 11.sp,170-        )171-    }172-}173-174-@Composable175-private fun SaveButton(label: String, fg: Color, enabled: Boolean, onClick: () -> Unit) {176-    val accent = com.peachpasswords.ui.theme.LocalPeachAccent.current177-    val tint = if (enabled) accent else fg.copy(alpha = 0.3f)178-    Box(179-        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))180-            .border(1.dp, tint.copy(alpha = if (enabled) 0.6f else 0.3f), RoundedCornerShape(8.dp))181-            .background(tint.copy(alpha = if (enabled) 0.16f else 0.06f))182-            .let { if (enabled) it.clickable(onClick = onClick) else it }183-            .padding(vertical = 11.dp),184-        contentAlignment = Alignment.Center,185-    ) {186-        Text(label, color = if (enabled) accent else fg.copy(alpha = 0.4f), fontFamily = PeachType.Mono, fontSize = 11.sp)187-    }188-}189-190-@Composable191-private fun DangerGhostButton(label: String, fg: Color, onClick: () -> Unit) {192-    Box(193-        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))194-            .border(1.dp, PeachColors.Breach.copy(alpha = 0.5f), RoundedCornerShape(8.dp))195-            .clickable(onClick = onClick)196-            .padding(vertical = 11.dp),197-        contentAlignment = Alignment.Center,198-    ) {199-        Text(label, color = PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)200-    }201-}

view file at the parent

app/drafts/D13/LockViewModel_unlock_integration.kt+0 −96
@@ -1,96 +0,0 @@1-/*2- * D13 — LockViewModel.unlock duress integration (SNIPPET, NOT a drop-in file).3- *4- * This is the precise change for `LockViewModel.unlock(password)`. The5- * orchestrator integrates it by hand — D13 is the only item touching6- * LockViewModel, so it must merge cleanly with whatever else has landed.7- *8- * KEY DESIGN POINT9- * ----------------10- * The duress check happens BEFORE `vault.unlock(password)`. The duress password11- * is verified against DuressConfigStore (a separate EncryptedSharedPreferences12- * file), NOT against slot A — it must be checkable without the real master13- * password. On a match we never touch the real vault's derived key.14- *15- * The brief says "check derived key against duress hash". We deliberately verify16- * the PASSWORD, not the slot-A-derived key: the duress salt differs from the17- * vault salt, so the Argon2id outputs are not comparable. DuressConfigStore.save18- * stores its own salt; DuressConfigStore.verify re-derives over that salt. This19- * is the only correct way to compare two independently-salted Argon2id secrets.20- *21- * NEW CONSTRUCTOR DEP (Hilt-injected):22- *   private val duress: com.peachpasswords.vault.DuressConfigStore,23- *24- * NEW UI-STATE FLAGS on LockUiState:25- *   val duressDestroyed: Boolean = false,  // real vault wiped → route to CreateVault26- *   // decoy success reuses the existing `unlocked = true` path.27- */28-29-// ─── replace the body of unlock(password) with this ───────────────────────────30-31-fun unlock(password: String) {32-    if (password.isBlank() || _state.value.loading) return33-    _state.update { it.copy(loading = true, error = null) }34-    viewModelScope.launch {35-        // Duress check first: a matching duress password never reaches the real36-        // vault. Verify is a full Argon2id derivation, so keep it inside the37-        // coroutine like the normal unlock.38-        when (val d = duress.verify(password)) {39-            is DuressMatch.Match -> {40-                handleDuress(d.action)41-                return@launch42-            }43-            DuressMatch.None -> Unit // fall through to the real unlock44-        }45-46-        when (val r = vault.unlock(password)) {47-            is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }48-            is UnlockResult.WrongPassword -> _state.update {49-                it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)50-            }51-            is UnlockResult.Error -> _state.update {52-                it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1)53-            }54-        }55-    }56-}57-58-/**59- * Carry out the configured duress action.60- *61- *  - DECOY:   unlock into the decoy vault slot. The real slot A is left62- *             untouched and hidden. See VaultRepository.unlockDecoy (new).63- *  - DESTROY: irreversibly wipe the real vault, then route to CreateVault by64- *             clearing hasVault. destroyVault() preserves the Pro license.65- *66- * To an observer under coercion both paths look like an ordinary successful (or67- * fresh-install) unlock — no error, no shake.68- */69-private suspend fun handleDuress(action: DuressAction) {70-    when (action) {71-        DuressAction.DECOY -> {72-            when (vault.unlockDecoy()) {73-                is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }74-                // If the decoy can't open we still must not reveal the real vault;75-                // present a generic incorrect-password to avoid an oracle.76-                else -> _state.update {77-                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)78-                }79-            }80-        }81-        DuressAction.DESTROY -> {82-            vault.destroyVault()83-            duress.clear() // the duress config dies with the vault it protected84-            _state.update {85-                it.copy(loading = false, hasVault = false, duressDestroyed = true)86-            }87-        }88-    }89-}90-91-/*92- * REQUIRED IMPORTS to add to LockViewModel.kt:93- *   import com.peachpasswords.vault.DuressAction94- *   import com.peachpasswords.vault.DuressConfigStore95- *   import com.peachpasswords.vault.DuressMatch96- */

view file at the parent

app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+31 −0
@@ -7,6 +7,9 @@77 import androidx.lifecycle.viewModelScope88 import com.peachpasswords.vault.CreateVaultResult99 import com.peachpasswords.ui.security.scorePassword10+import com.peachpasswords.vault.DuressAction11+import com.peachpasswords.vault.DuressConfigStore12+import com.peachpasswords.vault.DuressMatch1013 import com.peachpasswords.vault.UnlockResult1114 import com.peachpasswords.vault.VaultCrypto1215 import com.peachpasswords.vault.VaultRepository@@ -28,6 +31,8 @@2831     val created: Boolean = false,2932     /** Increments on each failed unlock so the screen can fire its shake animation. */3033     val shakeNonce: Int = 0,34+    /** Real vault was wiped by a destroy-duress unlock → screen drops to CreateVault. */35+    val duressDestroyed: Boolean = false,3136 )3237 3338 const val MIN_PASSWORD_LENGTH = 12@@ -38,6 +43,7 @@3843 @HiltViewModel3944 class LockViewModel @Inject constructor(4045     private val vault: VaultRepository,46+    private val duress: DuressConfigStore,4147     @ApplicationContext private val appContext: Context,4248 ) : ViewModel() {4349     private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))@@ -47,6 +53,11 @@4753         if (password.isBlank() || _state.value.loading) return4854         _state.update { it.copy(loading = true, error = null) }4955         viewModelScope.launch {56+            // Duress check first: a matching duress password never reaches the real vault.57+            when (val d = duress.verify(password)) {58+                is DuressMatch.Match -> { handleDuress(d.action); return@launch }59+                DuressMatch.None -> Unit60+            }5061             when (val r = vault.unlock(password)) {5162                 is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }5263                 is UnlockResult.WrongPassword -> _state.update {@@ -55,6 +66,26 @@5566                 is UnlockResult.Error -> _state.update {5667                     it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1)5768                 }69+            }70+        }71+    }72+73+    /**74+     * Carry out the configured duress action. Both paths look like an ordinary75+     * successful (decoy) or fresh-install (destroy) unlock to a coercer — no error.76+     */77+    private suspend fun handleDuress(action: DuressAction) {78+        when (action) {79+            DuressAction.DECOY -> when (vault.unlockDecoy()) {80+                is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }81+                else -> _state.update {82+                    it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)83+                }84+            }85+            DuressAction.DESTROY -> {86+                vault.destroyVault()87+                duress.clear()88+                _state.update { it.copy(loading = false, hasVault = false, duressDestroyed = true) }5889             }5990         }6091     }

view file

app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+142 −5
@@ -30,6 +30,7 @@3030 import androidx.compose.runtime.getValue3131 import com.peachpasswords.feedback.FeedbackState3232 import com.peachpasswords.ui.theme.LocalPeachAccent33+import com.peachpasswords.vault.DuressAction3334 import com.peachpasswords.ui.theme.PeachColors3435 import androidx.compose.runtime.mutableStateOf3536 import androidx.compose.runtime.remember@@ -275,13 +276,18 @@275276     ChangePasswordRow(fg, vm)276277 277278     SubLabel("DURESS PASSWORD", fg)278-    RowLine(fg) {279-        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {280-            Name("Duress password", fg); ProBadge(fg)279+    val duressIsPro by vm.isPro.collectAsState()280+    if (!duressIsPro) {281+        RowLine(fg) {282+            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {283+                Name("Duress password", fg); ProBadge(fg)284+            }285+            ValueText("off", fg)281286         }282-        ValueText("off", fg)287+        Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Pro feature.", fg)288+    } else {289+        DuressSection(fg, vm)283290     }284-    Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Arrives with Pro sync.", fg)285291 }286292 287293 @Composable@@ -666,4 +672,135 @@666672     }667673 668674     Hint("Sent anonymously · no account required", fg)675+}676+677+/* ──────────────────────────────  D13 Duress  ─────────────────────────────── */678+679+@Composable680+internal fun DuressSection(fg: Color, vm: SettingsViewModel) {681+    val configured by vm.duressConfigured.collectAsState()682+    if (configured) DuressActiveState(fg, vm) else DuressForm(fg, vm)683+}684+685+@Composable686+private fun DuressActiveState(fg: Color, vm: SettingsViewModel) {687+    Text(688+        "Duress password is active",689+        color = PeachColors.HealthOk,690+        fontFamily = PeachType.Mono,691+        fontSize = 11.sp,692+        modifier = Modifier.padding(top = 6.dp),693+    )694+    Spacer(Modifier.height(8.dp))695+    DuressDangerGhostButton("Disable duress password", fg) { vm.disableDuress() }696+    Hint("Entering your duress password instead of your real one triggers the action you chose.", fg)697+}698+699+@Composable700+private fun DuressForm(fg: Color, vm: SettingsViewModel) {701+    var enabled by remember { mutableStateOf(false) }702+    var password by remember { mutableStateOf("") }703+    var confirm by remember { mutableStateOf("") }704+    var action by remember { mutableStateOf(DuressAction.DECOY) }705+    var error by remember { mutableStateOf<String?>(null) }706+    val scope = rememberCoroutineScope()707+708+    RowLine(fg) {709+        Name("Duress password", fg)710+        Toggle(enabled, fg) { on ->711+            enabled = on712+            if (!on) { password = ""; confirm = ""; error = null }713+        }714+    }715+    Text(716+        "Entering your duress password instead of your real one opens a decoy vault or wipes the real one.",717+        color = fg.copy(alpha = 0.7f),718+        fontFamily = PeachType.Mono,719+        fontSize = 10.sp,720+        modifier = Modifier.padding(top = 6.dp),721+    )722+723+    AnimatedVisibility(enabled) {724+        Column(Modifier.fillMaxWidth().padding(top = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {725+            PwField("DURESS PASSWORD", password, fg) { password = it; error = null }726+            PwField("CONFIRM DURESS PASSWORD", confirm, fg) { confirm = it; error = null }727+728+            Text(729+                "When your duress password is entered at the lock screen, Peach will:",730+                color = fg.copy(alpha = 0.7f),731+                fontFamily = PeachType.Mono,732+                fontSize = 10.sp,733+                modifier = Modifier.padding(top = 4.dp),734+            )735+736+            DuressRadioOption("Show a decoy vault", action == DuressAction.DECOY, fg) { action = DuressAction.DECOY }737+            DuressRadioOption("Destroy the real vault", action == DuressAction.DESTROY, fg) { action = DuressAction.DESTROY }738+739+            error?.let { Text(it, color = PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp) }740+741+            val canSave = password.isNotBlank() && confirm.isNotBlank()742+            DuressSaveButton("Save duress password", fg, canSave) {743+                error = when {744+                    password.isBlank() || confirm.isBlank() -> "Enter and confirm a duress password"745+                    password != confirm -> "Passwords do not match"746+                    else -> null747+                }748+                if (error == null) scope.launch {749+                    if (vm.saveDuress(password, action)) {750+                        password = ""; confirm = ""; enabled = false751+                    } else {752+                        error = "Couldn't save duress password"753+                    }754+                }755+            }756+        }757+    }758+}759+760+@Composable761+private fun DuressRadioOption(label: String, selected: Boolean, fg: Color, onClick: () -> Unit) {762+    val accent = LocalPeachAccent.current763+    Row(764+        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick).padding(vertical = 7.dp),765+        verticalAlignment = Alignment.CenterVertically,766+        horizontalArrangement = Arrangement.spacedBy(10.dp),767+    ) {768+        Box(769+            Modifier.size(16.dp).clip(CircleShape)770+                .border(1.dp, if (selected) accent else fg.copy(alpha = 0.4f), CircleShape),771+            contentAlignment = Alignment.Center,772+        ) {773+            if (selected) Box(Modifier.size(8.dp).clip(CircleShape).background(accent))774+        }775+        Text(label, color = if (selected) accent else fg, fontFamily = PeachType.Mono, fontSize = 11.sp)776+    }777+}778+779+@Composable780+private fun DuressSaveButton(label: String, fg: Color, enabled: Boolean, onClick: () -> Unit) {781+    val accent = LocalPeachAccent.current782+    val tint = if (enabled) accent else fg.copy(alpha = 0.3f)783+    Box(784+        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))785+            .border(1.dp, tint.copy(alpha = if (enabled) 0.6f else 0.3f), RoundedCornerShape(8.dp))786+            .background(tint.copy(alpha = if (enabled) 0.16f else 0.06f))787+            .let { if (enabled) it.clickable(onClick = onClick) else it }788+            .padding(vertical = 11.dp),789+        contentAlignment = Alignment.Center,790+    ) {791+        Text(label, color = if (enabled) accent else fg.copy(alpha = 0.4f), fontFamily = PeachType.Mono, fontSize = 11.sp)792+    }793+}794+795+@Composable796+private fun DuressDangerGhostButton(label: String, fg: Color, onClick: () -> Unit) {797+    Box(798+        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))799+            .border(1.dp, PeachColors.Breach.copy(alpha = 0.5f), RoundedCornerShape(8.dp))800+            .clickable(onClick = onClick)801+            .padding(vertical = 11.dp),802+        contentAlignment = Alignment.Center,803+    ) {804+        Text(label, color = PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 11.sp)805+    }669806 }

view file

app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+15 −0
@@ -26,8 +26,23 @@2626     private val vault: VaultRepository,2727     private val license: LicenseRepository,2828     private val feedback: FeedbackRepository,29+    private val duress: com.peachpasswords.vault.DuressConfigStore,2930     @ApplicationContext private val appContext: Context,3031 ) : ViewModel() {32+33+    private val _duressConfigured = MutableStateFlow(duress.isConfigured())34+    val duressConfigured: StateFlow<Boolean> = _duressConfigured.asStateFlow()35+36+    suspend fun saveDuress(password: String, action: com.peachpasswords.vault.DuressAction): Boolean {37+        val ok = duress.save(password, action)38+        if (ok) _duressConfigured.value = true39+        return ok40+    }41+42+    fun disableDuress() {43+        duress.clear()44+        _duressConfigured.value = false45+    }3146 3247     private val _feedbackState = MutableStateFlow<FeedbackState>(FeedbackState.Idle)3348     val feedbackState: StateFlow<FeedbackState> = _feedbackState.asStateFlow()

view file

app/src/main/java/com/peachpasswords/vault/DuressConfig.kt+144 −0
@@ -0,0 +1,144 @@1+package com.peachpasswords.vault2+3+import android.content.Context4+import androidx.security.crypto.EncryptedSharedPreferences5+import androidx.security.crypto.MasterKey6+import dagger.hilt.android.qualifiers.ApplicationContext7+import org.json.JSONObject8+import java.util.Base649+import javax.inject.Inject10+import javax.inject.Singleton11+12+/**13+ * The action Peach takes when the duress password is entered at the lock screen.14+ *15+ *  - [DECOY]   open a separate empty/minimal "decoy" vault; the real vault stays16+ *              sealed and hidden.17+ *  - [DESTROY] irreversibly wipe the real vault, then drop to CreateVault.18+ *19+ * Persisted as the lowercase [wire] string so a future schema migration sees a20+ * stable token, never an ordinal.21+ */22+enum class DuressAction(val wire: String) {23+    DECOY("decoy"),24+    DESTROY("destroy");25+26+    companion object {27+        fun fromWire(s: String?): DuressAction =28+            entries.firstOrNull { it.wire == s } ?: DECOY29+    }30+}31+32+/**33+ * What [DuressConfigStore.verify] reports for an entered lock-screen password.34+ * [None] means "not the duress password" — the caller falls through to the35+ * normal vault unlock path. The verifier never decides policy; it only matches.36+ */37+sealed interface DuressMatch {38+    data object None : DuressMatch39+    data class Match(val action: DuressAction) : DuressMatch40+}41+42+/**43+ * Stores the duress password as an Argon2id hash (never plaintext) plus the44+ * selected [DuressAction], in a dedicated EncryptedSharedPreferences file under45+ * the single key "duress_config".46+ *47+ * The hash is the Argon2id output of the duress password over a freshly-minted48+ * 16-byte salt, using the SAME parameters as the vault KDF ([VaultCrypto]). The49+ * salt is stored alongside the hash (base64) — it is not secret; it only forces50+ * the verifier to re-derive rather than compare a precomputed digest. This51+ * mirrors the at-rest model of slot A, whose salt is likewise in the clear.52+ *53+ * Why a separate prefs file (not the slot-A payload): the duress password must be54+ * verifiable BEFORE the real vault is unlocked. It cannot live inside the55+ * AES-GCM blob that only the real master password can open. The license store56+ * uses the same EncryptedSharedPreferences pattern (see LicenseRepository).57+ */58+@Singleton59+class DuressConfigStore @Inject constructor(60+    @ApplicationContext context: Context,61+) {62+    private val masterKey = MasterKey.Builder(context)63+        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)64+        .build()65+66+    private val prefs = EncryptedSharedPreferences.create(67+        context,68+        PREFS_FILE,69+        masterKey,70+        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,71+        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,72+    )73+74+    fun isConfigured(): Boolean = prefs.contains(KEY_DURESS_CONFIG)75+76+    fun storedAction(): DuressAction? =77+        load()?.let { DuressAction.fromWire(it.optString(FIELD_ACTION)) }78+79+    /**80+     * Hash [password] with Argon2id over a fresh salt and persist {salt, hash,81+     * action}. Overwrites any prior duress config. Returns false if the value82+     * could not be committed.83+     */84+    fun save(password: String, action: DuressAction): Boolean {85+        val salt = VaultCrypto.generateSalt()86+        val hash = VaultCrypto.deriveKey(password, salt)87+        val json = JSONObject().apply {88+            put(FIELD_VERSION, 1)89+            put(FIELD_SALT, b64(salt))90+            put(FIELD_HASH, b64(hash))91+            put(FIELD_ACTION, action.wire)92+        }93+        VaultCrypto.zero(hash)94+        return prefs.edit().putString(KEY_DURESS_CONFIG, json.toString()).commit()95+    }96+97+    fun clear(): Boolean = prefs.edit().remove(KEY_DURESS_CONFIG).commit()98+99+    /**100+     * Check [password] against the stored duress hash. Re-derives the Argon2id101+     * key over the stored salt and constant-time-compares against the stored102+     * hash. Returns [DuressMatch.None] when no config exists or the password is103+     * not the duress password.104+     */105+    fun verify(password: String): DuressMatch {106+        val json = load() ?: return DuressMatch.None107+        val salt = runCatching { unb64(json.getString(FIELD_SALT)) }.getOrNull()108+            ?: return DuressMatch.None109+        val expected = runCatching { unb64(json.getString(FIELD_HASH)) }.getOrNull()110+            ?: return DuressMatch.None111+        val derived = VaultCrypto.deriveKey(password, salt)112+        val matches = constantTimeEquals(derived, expected)113+        VaultCrypto.zero(derived)114+        return if (matches) {115+            DuressMatch.Match(DuressAction.fromWire(json.optString(FIELD_ACTION)))116+        } else {117+            DuressMatch.None118+        }119+    }120+121+    private fun load(): JSONObject? =122+        prefs.getString(KEY_DURESS_CONFIG, null)?.let { runCatching { JSONObject(it) }.getOrNull() }123+124+    private fun constantTimeEquals(a: ByteArray, b: ByteArray): Boolean {125+        if (a.size != b.size) return false126+        var diff = 0127+        for (i in a.indices) diff = diff or (a[i].toInt() xor b[i].toInt())128+        return diff == 0129+    }130+131+    private fun b64(bytes: ByteArray): String =132+        Base64.getEncoder().withoutPadding().encodeToString(bytes)133+134+    private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)135+136+    companion object {137+        private const val PREFS_FILE = "peach_duress_prefs"138+        private const val KEY_DURESS_CONFIG = "duress_config"139+        private const val FIELD_VERSION = "v"140+        private const val FIELD_SALT = "salt"141+        private const val FIELD_HASH = "hash"142+        private const val FIELD_ACTION = "action"143+    }144+}

view file

app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+63 −0
@@ -17,6 +17,9 @@1717 /** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */1818 private const val PASSWORD_HISTORY_MAX = 501919 20+/** Fixed in-app key material for the decoy vault — holds nothing secret by design. */21+private const val DECOY_SENTINEL = "peach_decoy_v1"22+2023 sealed interface UnlockResult {2124     data object Success : UnlockResult2225     data object WrongPassword : UnlockResult@@ -54,6 +57,8 @@5457     private var duressConfigured: Boolean = false5558     private var recoveryWordHash: String? = null5659     private var recoveryWordsSet: Boolean = false60+    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */61+    private var decoyMode: Boolean = false5762 5863     private val _isUnlocked = MutableStateFlow(false)5964     val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()@@ -108,6 +113,7 @@108113             duressConfigured = false109114             recoveryWordHash = null110115             recoveryWordsSet = false116+            decoyMode = false111117             rootKey = VaultCrypto.generateRootKey()112118             val slotA = sealSlotA(key, salt)113119             if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")@@ -137,6 +143,7 @@137143                 return UnlockResult.WrongPassword138144             }139145             derivedKey = key146+            decoyMode = false140147             entryList = payload.entries.toMutableList()141148             duressConfigured = payload.duressConfigured142149             recoveryWordHash = payload.recoveryWordHash@@ -152,6 +159,52 @@152159         }153160     }154161 162+    /**163+     * Unlock into the decoy (duress) vault. Creates an empty decoy on first use,164+     * sealed under a fixed in-app sentinel key with its own salt. The real slot A165+     * is never read, so the real vault stays hidden. Edits during a decoy session166+     * persist to the decoy slot only (see [persistSlotA]).167+     */168+    suspend fun unlockDecoy(): UnlockResult = mutex.withLock {169+        return try {170+            val existing = store.loadDecoySlot()171+            if (existing == null) {172+                val salt = VaultCrypto.generateSalt()173+                val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)174+                entryList = mutableListOf()175+                duressConfigured = false176+                recoveryWordHash = null177+                recoveryWordsSet = false178+                rootKey = VaultCrypto.generateRootKey()179+                derivedKey = key180+                decoyMode = true181+                val plaintext = VaultCodec.encode(currentPayload())182+                val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))183+                if (!store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob)))184+                    return UnlockResult.Error("storage_write_failed")185+            } else {186+                val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))187+                val payload = VaultCodec.decode(188+                    VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),189+                )190+                derivedKey = key191+                decoyMode = true192+                entryList = payload.entries.toMutableList()193+                duressConfigured = false194+                recoveryWordHash = payload.recoveryWordHash195+                recoveryWordsSet = payload.recoveryWordsSet196+                rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)197+                          else VaultCrypto.generateRootKey()198+            }199+            _settings.value = store.loadSettings()200+            publish()201+            _isUnlocked.value = true202+            UnlockResult.Success203+        } catch (e: Exception) {204+            UnlockResult.Error(e.message ?: "decoy_unlock_failed")205+        }206+    }207+155208     /** Unlock with an already-derived AES-256 key (biometric path). */156209     suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {157210         val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")@@ -160,6 +213,7 @@160213                 VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),161214             )162215             derivedKey = key.copyOf()216+            decoyMode = false163217             entryList = payload.entries.toMutableList()164218             duressConfigured = payload.duressConfigured165219             recoveryWordHash = payload.recoveryWordHash@@ -184,6 +238,7 @@184238         duressConfigured = false185239         recoveryWordHash = null186240         recoveryWordsSet = false241+        decoyMode = false187242         _entries.value = emptyList()188243         _isUnlocked.value = false189244     }@@ -239,6 +294,7 @@239294     suspend fun destroyVault() = mutex.withLock {240295         lock()241296         store.clearVault()297+        store.clearDecoySlot()242298     }243299 244300     // ---- Entry CRUD -------------------------------------------------------@@ -526,6 +582,13 @@526582     /** Re-seal slot A from the current in-memory state under the live key. */527583     private fun persistSlotA(bumpVersion: Boolean): Boolean {528584         val key = derivedKey ?: throw IllegalStateException("vault_locked")585+        // Decoy sessions persist to the decoy slot only — never touch the real slot A.586+        if (decoyMode) {587+            val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")588+            val plaintext = VaultCodec.encode(currentPayload())589+            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))590+            return store.writeDecoySlot(prior.copy(blob = blob))591+        }529592         val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")530593         val plaintext = VaultCodec.encode(currentPayload())531594         val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))

view file

app/src/main/java/com/peachpasswords/vault/VaultStore.kt+11 −0
@@ -72,6 +72,10 @@7272     fun hasVault(): Boolean7373     fun writeSlotA(slot: StoredVault): Boolean7474     fun writeSlotB(blobBase64: String): Boolean75+    fun loadDecoySlot(): StoredVault?76+    fun writeDecoySlot(slot: StoredVault): Boolean77+    fun hasDecoySlot(): Boolean78+    fun clearDecoySlot()7579     fun version(): Long7680     fun stampLocalMutation(): Long7781     fun loadSettings(): VaultSettings@@ -102,6 +106,12 @@102106     override fun writeSlotB(blobBase64: String): Boolean =103107         prefs.edit().putString(KEY_SLOT_B, blobBase64).commit()104108 109+    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() }114+105115     override fun version(): Long = prefs.getString(KEY_VERSION, null)?.toLongOrNull() ?: 0L106116 107117     override fun stampLocalMutation(): Long {@@ -126,6 +136,7 @@126136         private const val PREFS = "peach_vault_store"127137         private const val KEY_SLOT_A = "peach_vault_a"128138         private const val KEY_SLOT_B = "peach_vault_b"139+        private const val KEY_SLOT_DURESS = "peach_vault_duress"129140         private const val KEY_VERSION = "peach_last_modified_at"130141         private const val KEY_SETTINGS = "peach_settings"131142     }

view file

app/src/test/java/com/peachpasswords/sync/VaultSyncAdapterTest.kt+5 −0
@@ -20,6 +20,11 @@2020     override fun hasVault() = slotA != null2121     override fun writeSlotA(slot: StoredVault): Boolean { slotA = slot; return true }2222     override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }23+    private var decoy: StoredVault? = null24+    override fun loadDecoySlot() = decoy25+    override fun writeDecoySlot(slot: StoredVault): Boolean { decoy = slot; return true }26+    override fun hasDecoySlot() = decoy != null27+    override fun clearDecoySlot() { decoy = null }2328     override fun version() = ver2429     override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }2530     override fun loadSettings() = settings

view file

app/src/test/java/com/peachpasswords/vault/VaultRepositoryTest.kt+5 −0
@@ -17,6 +17,11 @@1717     override fun hasVault() = slotA != null1818     override fun writeSlotA(slot: StoredVault): Boolean { slotA = slot; return true }1919     override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }20+    var decoy: StoredVault? = null21+    override fun loadDecoySlot() = decoy22+    override fun writeDecoySlot(slot: StoredVault): Boolean { decoy = slot; return true }23+    override fun hasDecoySlot() = decoy != null24+    override fun clearDecoySlot() { decoy = null }2025     override fun version() = ver2126     override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }2227     override fun loadSettings() = settings

view file