INTEGRATION.md

14.2 KB · raw

rendered · source

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.

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:

// 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<Boolean> = _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):

    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:

    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:

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

private val duress: com.peachpasswords.vault.DuressConfigStore,

3b. New LockUiState flag

/** 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):

    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):

            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

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:

interface VaultStorage {
    // …existing…
    fun loadDecoySlot(): StoredVault?
    fun writeDecoySlot(slot: StoredVault): Boolean
    fun hasDecoySlot(): Boolean
    fun clearDecoySlot()
}

VaultStore impl (mirror the slot-A methods):

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:

/**
 * 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<Boolean>; 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