af22b155c547

feat: C2 ExportScreen — choose view; PeachScript encrypted backup (Argon2id+AES-GCM, mirrors pinned .peach format, strength-gated ≥good) w/ copy + SAF save; CSV export (formula-injection guard, RFC-4180, unencrypted-warning checkbox gate); 6 tests incl. export⇄import encrypted round-trip; wired nav (v2.1.28)

time
2026-06-09 03:12 UTC · 5 months ago
machine
koh2
agent
claude-opus-4-8
session
peach gap implementation
parent
127c9f027940
10 files app/build.gradle+2 −2app/drafts/C2-INTEGRATION.md+142 −0app/drafts/CsvExport.kt+0 −54app/drafts/ExportScreen.kt+0 −538app/drafts/PeachScriptExport.kt+0 −141app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+2 −1app/src/main/java/com/peachpasswords/ui/vault/CsvExport.kt+54 −0app/src/main/java/com/peachpasswords/ui/vault/ExportScreen.kt+538 −0app/src/main/java/com/peachpasswords/ui/vault/PeachScriptExport.kt+141 −0app/src/test/java/com/peachpasswords/ui/vault/ExportRoundTripTest.kt+62 −0
app/build.gradle+2 −2
@@ -16,8 +16,8 @@1616         applicationId "com.peachpasswords"1717         minSdk 261818         targetSdk 3519-        versionCode 20102720-        versionName "2.1.27"19+        versionCode 20102820+        versionName "2.1.28"2121 2222         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"2323         vectorDrawables {

view file

app/drafts/C2-INTEGRATION.md+142 −0
@@ -0,0 +1,142 @@1+# C2 — Export Screen: Integration Note2+3+Draft implementation of spec C2 (lines 289–337). Three Kotlin files plus this4+note, all under `app/drafts/`. Package is already `com.peachpasswords.ui.vault`,5+so they drop straight into the source tree. No existing file was edited6+(PeachNav.kt, PeachAppNavHost.kt, VaultRepository.kt, VaultCrypto.kt,7+VaultEntry.kt, ImportScreen.kt, RecoveryWordsScreen.kt, theme files were read8+only).9+10+## Files to MOVE into the source set11+12+| Draft file | Destination | Contents |13+|---|---|---|14+| `PeachScriptExport.kt` | `ui/vault/PeachScriptExport.kt` | Pure Kotlin: `buildPlaintext` / `buildEncrypted`, hand-rolled JSON with escaping |15+| `CsvExport.kt` | `ui/vault/CsvExport.kt` | Pure Kotlin: `toCsv` + `encodeField` (RFC-4180 + formula-injection guard) |16+| `ExportScreen.kt` | `ui/vault/ExportScreen.kt` | Compose UI + `ExportViewModel` + `scorePassword`/`strengthLabel` |17+18+`C2-INTEGRATION.md` stays in drafts (or delete after wiring) — it is not source.19+20+## Public composable signature21+22+```kotlin23+@Composable24+fun ExportScreen(onBack: () -> Unit)25+// (also has a defaulted vm = hiltViewModel() param, like ImportScreen / TrashScreen)26+```27+28+## Nav wiring (one line)29+30+`PeachNav.Export` route already exists. In `PeachAppNavHost.kt`, replace the31+`Export` route's `SimpleStub` with:32+33+```kotlin34+ExportScreen(onBack = back)35+```36+37+where `back` is the same back lambda the other vault screens use (e.g. how38+`ImportScreen(onBack = back)` is wired). No new route, no nav-graph change.39+40+`ExportScreen` handles its own internal back: a sub-view (PeachScript / CSV)41+returns to the choose view; the choose view calls `onBack()`. A single42+`onBack=back` is correct.43+44+## Strength scorer thresholds chosen45+46+`scorePassword(pw): Int` returns 0–4 (local, dependency-free, no network):47+48+- +1 if length ≥ 849+- +1 if length ≥ 1250+- +1 if ≥ 3 of {lowercase, uppercase, digit, symbol} present51+- +1 if all 4 classes present52+- empty → 0, clamped to 0..453+54+Labels: 0 very weak · 1 weak · 2 fair · 3 good · 4 strong.55+56+The C2 gate is **score ≥ 3 ("good")**. `[Generate backup]` is disabled until57+`score ≥ 3` AND the two password fields match AND the vault is non-empty. When58+a non-empty password scores < 3 the breach-colour error59+`"Backup password too weak (score < 3)"` is shown (spec line 306). The 4-segment60+bar fills `score` segments and tints to the accent once "good".61+62+## Round-trip confirmation (buildEncrypted ⇄ PeachScriptImport)63+64+`PeachScriptImport.decryptAndParse(buildEncrypted(es, pw), pw)` returns65+`Success` with the same six fields per entry. Reasoning, field by field against66+the pinned format in `B2-INTEGRATION.md` and the importer source:67+68+1. **Envelope shape.** `buildEncrypted` emits69+   `{"peachscript":1,"encrypted":true,"kdf":"argon2id","salt":"<b64>","blob":"<b64>"}`.70+   The importer reads `salt` and `blob` via `jsonRawString` (a `"key":"..."`71+   regex) — key names and JSON-string shape match exactly.72+2. **Base64.** Both sides use `java.util.Base64` standard (non-URL-safe) codec:73+   `getEncoder()` here, `getDecoder()` there. Salt is 16 bytes74+   (`VaultCrypto.generateSalt()` = `SALT_SIZE`); blob is `nonce(12) || ct||tag`,75+   so `blob.size > NONCE_SIZE` — passes the importer's length guards.76+3. **KDF.** `salt` feeds `VaultCrypto.deriveKey(pw, salt)` on both sides77+   (Argon2id, identical params from the shared `VaultCrypto` constants).78+4. **AEAD + AAD.** `blob` is exactly `VaultCrypto.encrypt(plaintextBytes, key,79+   PeachScriptImport.PEACHSCRIPT_AAD)`. The importer calls80+   `VaultCrypto.decrypt(blob, key, PEACHSCRIPT_AAD)` with the **same constant**81+   AAD (`"peachscript_export_v1"`). `encrypt` prepends the 12-byte nonce;82+   `decrypt` strips the first 12 bytes as the nonce. The GCM tag therefore83+   verifies, so wrong-password / tamper paths surface as84+   `DecryptResult.WrongPassword` exactly as designed.85+5. **Inner plaintext.** The decrypted bytes are86+   `buildPlaintext(es)` =87+   `{"peachscript":1,"encrypted":false,"entries":[{...}]}`. The importer's88+   `parsePlaintext` uses `extractArrayBody("entries")` +89+   `splitTopLevelObjects` + `jsonString` for `title/username/password/url/90+   notes/totp` — the exact keys this writer emits.91+6. **Escaping.** `buildPlaintext` escapes `\`, `"`, and control chars (`\n \r92+   \t \b \f`, `\uXXXX` for the rest). The importer's `unescapeJson` reverses93+   `\n \t \r \" \\ \/ \uXXXX`, so any value round-trips. (We never emit `\/`;94+   forward slash is left literal, which is valid JSON and read back verbatim.)95+96+The only normalisation is field projection (see assumptions): empty strings97+become `null` on the way back because the importer's `jsonString` maps `""` →98+`null`, and `parsePlaintext` drops entries whose `title` is blank. So entries99+with a non-blank title and otherwise-null optional fields round-trip to the same100+`ParsedEntry` shape.101+102+## VaultRepository methods used (all already exist — no new API assumed)103+104+- `fun getEntries(): List<VaultEntry>` — returns active (non-deleted) entries105+  (verified: `entryList.filter { it.deletedAt == null }`). Used for both the106+  count/empty-vault gate and the export payload.107+108+`ExportViewModel` injects `VaultRepository` + `@ApplicationContext Context`109+(for SAF `openOutputStream`), exactly like `ImportViewModel`.110+111+## SAF / clipboard patterns112+113+- PeachScript save: `CreateDocument("*/*")`, suggested name `peach-backup.peach`114+  (mirrors `RecoveryWordsScreen`'s `CreateDocument` save pattern). `"*/*"` is115+  used because there is no registered MIME type for `.peach`.116+- CSV save: `CreateDocument("text/csv")`, suggested name `peach-export.csv`.117+- Copy to clipboard uses `ClipboardManager` /118+  `ClipData.newPlainText("peach backup", json)` — same approach as119+  RecoveryWordsScreen's "copy all words".120+121+## Assumptions / things for the orchestrator to confirm122+123+1. **`email` → `username` fold.** PeachScript and the CSV `username` column have124+   no `email` field, and the importer reads only six keys. When `username` is125+   blank we emit `email` in its place (so a webmail login's address is not lost).126+   If the orchestrator prefers email dropped, change the `e.username ?: e.email`127+   fallbacks in both `PeachScriptExport.appendEntry` and `CsvExport.toCsv`.128+2. **Only the six PeachScript fields are exported.** Card/passkey/tags/history129+   fields are intentionally NOT in PeachScript or CSV (neither format nor the130+   B2 importer model them). A full-fidelity vault backup would need a richer131+   format — out of scope for C2, which targets interop with the B2 importer.132+3. **Empty-vault gate** is enforced in the UI (`entryCount() == 0` disables the133+   export button and shows `"Your vault is empty — nothing to export."`). The134+   spec says "Empty vault" error if 0 entries; exact copy can be tuned.135+4. **Strength gate copy** uses the spec's literal string136+   `"Backup password too weak (score < 3)"` in breach colour.137+5. **CSV MIME** is `text/csv` for the picker (stricter than Import's `"*/*"`,138+   since we control the extension on write). Swap to `"*/*"` if a device's SAF139+   provider rejects `text/csv`.140+6. Entry-point wiring (Settings → Vault card → "Export" row) is out of scope for141+   this draft — only the `PeachNav.Export` route swap is described.142+```

view file

app/drafts/CsvExport.kt+0 −54
@@ -1,54 +0,0 @@1-package com.peachpasswords.ui.vault2-3-import com.peachpasswords.vault.VaultEntry4-5-/**6- * Pure-Kotlin CSV serialisation for the C2 Export screen (CSV sub-view).7- *8- * Columns (fixed order, spec line 325): title, username, password, url, notes.9- * `username` falls back to `email` when blank, mirroring PeachScript export.10- *11- * Two layers of quoting are applied, in order:12- *   1. Formula-injection guard (spec line 326): if a field's first character is13- *      one of `= + - @`, TAB (0x09) or CR (0x0D), a leading single quote `'` is14- *      prefixed so spreadsheet apps treat it as text, not a formula. This happens15- *      BEFORE RFC-4180 quoting so the guard char lands inside the quotes.16- *   2. RFC-4180 quoting: a field containing a comma, double-quote, CR or LF is17- *      wrapped in double quotes, and any internal `"` is doubled (`""`).18- *19- * No Compose / Android UI here — unit-testable pure functions.20- */21-object CsvExport {22-23-    private val HEADER = listOf("title", "username", "password", "url", "notes")24-25-    // Spreadsheet formula triggers. TAB/CR are included because some apps strip26-    // leading whitespace and then re-evaluate the first visible char as a formula.27-    private val INJECTION_PREFIXES = charArrayOf('=', '+', '-', '@', '\t', '\r')28-29-    // RFC-4180 line terminator.30-    private const val CRLF = "\r\n"31-32-    fun toCsv(entries: List<VaultEntry>): String {33-        val sb = StringBuilder(64 + entries.size * 64)34-        sb.append(HEADER.joinToString(",") { encodeField(it) }).append(CRLF)35-        for (e in entries) {36-            val row = listOf(37-                e.title,38-                e.username ?: e.email ?: "",39-                e.password ?: "",40-                e.url ?: "",41-                e.notes ?: "",42-            )43-            sb.append(row.joinToString(",") { encodeField(it) }).append(CRLF)44-        }45-        return sb.toString()46-    }47-48-    /** Apply the formula-injection guard, then RFC-4180 quoting. */49-    fun encodeField(raw: String): String {50-        val guarded = if (raw.isNotEmpty() && raw[0] in INJECTION_PREFIXES) "'$raw" else raw51-        val needsQuoting = guarded.any { it == ',' || it == '"' || it == '\n' || it == '\r' }52-        return if (needsQuoting) "\"" + guarded.replace("\"", "\"\"") + "\"" else guarded53-    }54-}

view file at the parent

app/drafts/ExportScreen.kt+0 −538
@@ -1,538 +0,0 @@1-package com.peachpasswords.ui.vault2-3-import android.content.ClipData4-import android.content.ClipboardManager5-import android.content.Context6-import android.net.Uri7-import androidx.activity.compose.rememberLauncherForActivityResult8-import androidx.activity.result.contract.ActivityResultContracts9-import androidx.compose.foundation.background10-import androidx.compose.foundation.border11-import androidx.compose.foundation.clickable12-import androidx.compose.foundation.layout.Box13-import androidx.compose.foundation.layout.Column14-import androidx.compose.foundation.layout.Row15-import androidx.compose.foundation.layout.Spacer16-import androidx.compose.foundation.layout.fillMaxSize17-import androidx.compose.foundation.layout.fillMaxWidth18-import androidx.compose.foundation.layout.height19-import androidx.compose.foundation.layout.padding20-import androidx.compose.foundation.layout.size21-import androidx.compose.foundation.layout.systemBarsPadding22-import androidx.compose.foundation.layout.width23-import androidx.compose.foundation.rememberScrollState24-import androidx.compose.foundation.shape.RoundedCornerShape25-import androidx.compose.foundation.text.BasicTextField26-import androidx.compose.foundation.verticalScroll27-import androidx.compose.material.icons.Icons28-import androidx.compose.material.icons.automirrored.rounded.ArrowBack29-import androidx.compose.material3.Icon30-import androidx.compose.material3.Text31-import androidx.compose.runtime.Composable32-import androidx.compose.runtime.getValue33-import androidx.compose.runtime.mutableStateOf34-import androidx.compose.runtime.remember35-import androidx.compose.runtime.setValue36-import androidx.compose.ui.Alignment37-import androidx.compose.ui.Modifier38-import androidx.compose.ui.draw.clip39-import androidx.compose.ui.graphics.Color40-import androidx.compose.ui.graphics.SolidColor41-import androidx.compose.ui.platform.LocalContext42-import androidx.compose.ui.text.TextStyle43-import androidx.compose.ui.text.font.FontStyle44-import androidx.compose.ui.text.input.PasswordVisualTransformation45-import androidx.compose.ui.text.input.VisualTransformation46-import androidx.compose.ui.unit.dp47-import androidx.compose.ui.unit.sp48-import androidx.hilt.navigation.compose.hiltViewModel49-import androidx.lifecycle.ViewModel50-import com.peachpasswords.ui.theme.LocalPeachAccent51-import com.peachpasswords.ui.theme.PeachColors52-import com.peachpasswords.ui.theme.PeachType53-import com.peachpasswords.ui.theme.ShellBackground54-import com.peachpasswords.vault.VaultEntry55-import com.peachpasswords.vault.VaultRepository56-import dagger.hilt.android.lifecycle.HiltViewModel57-import dagger.hilt.android.qualifiers.ApplicationContext58-import javax.inject.Inject59-60-// ─────────────────────────────────────────────────────────────────────────────61-// Password strength scorer (local, dependency-free)62-// ─────────────────────────────────────────────────────────────────────────────63-64-/**65- * Lightweight 0–4 strength score from length + character-class variety. No66- * external lib, no network — this is a UI gate, not a security guarantee.67- *68- * Thresholds (deliberately simple and explainable):69- *   - +1 if length >= 870- *   - +1 if length >= 1271- *   - +1 if at least 3 of {lowercase, uppercase, digit, symbol} are present72- *   - +1 if all 4 classes are present73- * Empty input scores 0. Result is clamped to 0..4. The C2 gate requires >= 374- * ("good"); see [strengthLabel].75- */76-internal fun scorePassword(pw: String): Int {77-    if (pw.isEmpty()) return 078-    var classes = 079-    if (pw.any { it in 'a'..'z' }) classes++80-    if (pw.any { it in 'A'..'Z' }) classes++81-    if (pw.any { it.isDigit() }) classes++82-    if (pw.any { !it.isLetterOrDigit() }) classes++83-84-    var score = 085-    if (pw.length >= 8) score++86-    if (pw.length >= 12) score++87-    if (classes >= 3) score++88-    if (classes >= 4) score++89-    return score.coerceIn(0, 4)90-}91-92-internal fun strengthLabel(score: Int): String = when (score) {93-    0 -> "very weak"94-    1 -> "weak"95-    2 -> "fair"96-    3 -> "good"97-    else -> "strong"98-}99-100-// ─────────────────────────────────────────────────────────────────────────────101-// ViewModel102-// ─────────────────────────────────────────────────────────────────────────────103-104-@HiltViewModel105-class ExportViewModel @Inject constructor(106-    private val vault: VaultRepository,107-    @ApplicationContext private val appContext: Context,108-) : ViewModel() {109-110-    /** Active (non-deleted) entries to export. */111-    fun entries(): List<VaultEntry> = vault.getEntries()112-113-    fun entryCount(): Int = vault.getEntries().size114-115-    /** Encrypted PeachScript export (backup-password protected). */116-    fun buildPeachScript(backupPassword: String): String =117-        PeachScriptExport.buildEncrypted(entries(), backupPassword)118-119-    /** Unencrypted CSV export. */120-    fun buildCsv(): String = CsvExport.toCsv(entries())121-122-    /** Write [content] to the SAF [uri]; returns false on any IO failure. */123-    fun writeToUri(uri: Uri, content: String): Boolean =124-        runCatching {125-            appContext.contentResolver.openOutputStream(uri)?.use {126-                it.write(content.toByteArray(Charsets.UTF_8))127-            } ?: return false128-            true129-        }.getOrDefault(false)130-}131-132-// ─────────────────────────────────────────────────────────────────────────────133-// Screen134-// ─────────────────────────────────────────────────────────────────────────────135-136-object ExportStrings {137-    const val EMPTY_VAULT = "Your vault is empty — nothing to export."138-    const val WEAK_PASSWORD = "Backup password too weak (score < 3)"139-    const val MISMATCH = "Passwords don't match."140-    const val SAVE_FAILED = "Couldn't write that file."141-    const val SAVED = "Saved."142-    const val COPIED = "Copied to clipboard."143-}144-145-private enum class ExportRoute { CHOOSE, PEACHSCRIPT, CSV }146-147-@Composable148-fun ExportScreen(149-    onBack: () -> Unit,150-    vm: ExportViewModel = hiltViewModel(),151-) {152-    var route by remember { mutableStateOf(ExportRoute.CHOOSE) }153-154-    ShellBackground {155-        Column(156-            modifier = Modifier157-                .fillMaxSize()158-                .systemBarsPadding()159-                .padding(horizontal = 20.dp, vertical = 16.dp),160-        ) {161-            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {162-                Icon(163-                    Icons.AutoMirrored.Rounded.ArrowBack,164-                    contentDescription = "back",165-                    tint = PeachColors.T0,166-                    modifier = Modifier167-                        .size(22.dp)168-                        .clip(RoundedCornerShape(8.dp))169-                        .clickable {170-                            if (route != ExportRoute.CHOOSE) route = ExportRoute.CHOOSE else onBack()171-                        },172-                )173-                Spacer(Modifier.width(14.dp))174-                Text(175-                    "Export",176-                    color = PeachColors.T0,177-                    style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),178-                )179-            }180-181-            Spacer(Modifier.size(18.dp))182-183-            Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {184-                when (route) {185-                    ExportRoute.CHOOSE -> ChooseView(186-                        onPeachScript = { route = ExportRoute.PEACHSCRIPT },187-                        onCsv = { route = ExportRoute.CSV },188-                    )189-                    ExportRoute.PEACHSCRIPT -> PeachScriptExportView(vm)190-                    ExportRoute.CSV -> CsvExportView(vm)191-                }192-            }193-        }194-    }195-}196-197-// ---- Choose view ----------------------------------------------------------198-199-@Composable200-private fun ChooseView(onPeachScript: () -> Unit, onCsv: () -> Unit) {201-    OptionCard(202-        title = "PeachScript (encrypted)",203-        subtitle = "A backup encrypted with a separate password. Restores into Peach.",204-        onClick = onPeachScript,205-    )206-    Spacer(Modifier.size(12.dp))207-    OptionCard(208-        title = "CSV (unencrypted)",209-        subtitle = "Plain text for moving into another manager. Not encrypted.",210-        onClick = onCsv,211-    )212-}213-214-@Composable215-private fun OptionCard(title: String, subtitle: String, onClick: () -> Unit) {216-    Column(217-        modifier = Modifier218-            .fillMaxWidth()219-            .clip(RoundedCornerShape(18.dp))220-            .background(PeachColors.SurfaceElevated)221-            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))222-            .clickable(onClick = onClick)223-            .padding(20.dp),224-    ) {225-        Text(226-            title,227-            color = PeachColors.T0,228-            style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),229-        )230-        Spacer(Modifier.size(6.dp))231-        Text(subtitle, color = PeachColors.T1, style = PeachType.body)232-    }233-}234-235-// ---- PeachScript sub-view -------------------------------------------------236-237-@Composable238-private fun PeachScriptExportView(vm: ExportViewModel) {239-    val accent = LocalPeachAccent.current240-    val context = LocalContext.current241-    val isEmpty = remember { vm.entryCount() == 0 }242-243-    var password by remember { mutableStateOf("") }244-    var confirm by remember { mutableStateOf("") }245-246-    // Generated artefact (the encrypted JSON string), set after [Generate backup].247-    var output by remember { mutableStateOf<String?>(null) }248-    var status by remember { mutableStateOf<String?>(null) }249-250-    val score = remember(password) { scorePassword(password) }251-    val matches = password.isNotEmpty() && password == confirm252-    val strongEnough = score >= 3253-    val canGenerate = !isEmpty && strongEnough && matches254-255-    val saveLauncher = rememberLauncherForActivityResult(256-        ActivityResultContracts.CreateDocument("*/*"),257-    ) { uri ->258-        val text = output259-        if (uri != null && text != null) {260-            status = if (vm.writeToUri(uri, text)) ExportStrings.SAVED else ExportStrings.SAVE_FAILED261-        }262-    }263-264-    GlassCard {265-        Text(266-            "create a\nbackup.",267-            color = PeachColors.T0,268-            style = TextStyle(269-                fontFamily = PeachType.Display, fontStyle = FontStyle.Italic,270-                fontSize = 24.sp, lineHeight = 26.sp,271-            ),272-        )273-        Spacer(Modifier.size(10.dp))274-        Text(275-            "Your vault will be encrypted with a separate backup password.",276-            color = PeachColors.T1, style = PeachType.body,277-        )278-279-        if (isEmpty) {280-            Spacer(Modifier.size(16.dp))281-            InlineError(ExportStrings.EMPTY_VAULT)282-        }283-284-        Spacer(Modifier.size(18.dp))285-        FieldLabel("Backup password")286-        Spacer(Modifier.size(6.dp))287-        PeachUnderlineField(value = password, onValueChange = { password = it; output = null; status = null }, isPassword = true)288-289-        Spacer(Modifier.size(16.dp))290-        FieldLabel("Confirm backup password")291-        Spacer(Modifier.size(6.dp))292-        PeachUnderlineField(value = confirm, onValueChange = { confirm = it; output = null; status = null }, isPassword = true)293-294-        Spacer(Modifier.size(16.dp))295-        StrengthBar(score = score, accent = accent)296-        Spacer(Modifier.size(6.dp))297-        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {298-            Text(299-                "strength: ${strengthLabel(score)}",300-                color = if (strongEnough) accent else PeachColors.T2,301-                style = PeachType.labelMono,302-            )303-        }304-305-        if (password.isNotEmpty() && !strongEnough) {306-            Spacer(Modifier.size(8.dp))307-            Text(ExportStrings.WEAK_PASSWORD, color = PeachColors.Breach, style = PeachType.bodyMono)308-        }309-        if (confirm.isNotEmpty() && !matches) {310-            Spacer(Modifier.size(8.dp))311-            Text(ExportStrings.MISMATCH, color = PeachColors.Breach, style = PeachType.bodyMono)312-        }313-    }314-315-    Spacer(Modifier.size(18.dp))316-317-    if (output == null) {318-        AccentButton(319-            label = "Generate backup",320-            enabled = canGenerate,321-            onClick = {322-                output = vm.buildPeachScript(password)323-                status = null324-            },325-        )326-    } else {327-        val text = output!!328-        GhostButton("Copy to clipboard", accent) {329-            val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager330-            cm.setPrimaryClip(ClipData.newPlainText("peach backup", text))331-            status = ExportStrings.COPIED332-        }333-        Spacer(Modifier.size(8.dp))334-        GhostButton("Save to file", PeachColors.T1) {335-            saveLauncher.launch("peach-backup.peach")336-        }337-        status?.let {338-            Spacer(Modifier.size(12.dp))339-            Text(340-                it,341-                color = if (it == ExportStrings.SAVE_FAILED) PeachColors.Breach else accent,342-                style = PeachType.labelMono,343-            )344-        }345-    }346-}347-348-@Composable349-private fun StrengthBar(score: Int, accent: Color) {350-    // Four segments; filled count == score. Color shifts to accent once "good".351-    val fillColor = if (score >= 3) accent else PeachColors.T2352-    Row(modifier = Modifier.fillMaxWidth()) {353-        repeat(4) { i ->354-            Box(355-                modifier = Modifier356-                    .weight(1f)357-                    .height(4.dp)358-                    .padding(end = if (i < 3) 4.dp else 0.dp)359-                    .clip(RoundedCornerShape(2.dp))360-                    .background(if (i < score) fillColor else PeachColors.T3),361-            )362-        }363-    }364-}365-366-// ---- CSV sub-view ---------------------------------------------------------367-368-@Composable369-private fun CsvExportView(vm: ExportViewModel) {370-    val accent = LocalPeachAccent.current371-    val isEmpty = remember { vm.entryCount() == 0 }372-373-    var acknowledged by remember { mutableStateOf(false) }374-    var status by remember { mutableStateOf<String?>(null) }375-376-    val saveLauncher = rememberLauncherForActivityResult(377-        ActivityResultContracts.CreateDocument("text/csv"),378-    ) { uri ->379-        if (uri != null) {380-            val csv = vm.buildCsv()381-            status = if (vm.writeToUri(uri, csv)) ExportStrings.SAVED else ExportStrings.SAVE_FAILED382-        }383-    }384-385-    WarningCard(accent) {386-        Text(387-            "⚠ CSV exports are not encrypted. Store this file securely and delete it after importing.",388-            color = PeachColors.T0, style = PeachType.body,389-        )390-        Spacer(Modifier.size(16.dp))391-        CheckboxRow(392-            label = "I understand this file is unencrypted",393-            checked = acknowledged,394-            accent = accent,395-            onToggle = { acknowledged = !acknowledged },396-        )397-    }398-399-    if (isEmpty) {400-        Spacer(Modifier.size(16.dp))401-        InlineError(ExportStrings.EMPTY_VAULT)402-    }403-404-    Spacer(Modifier.size(18.dp))405-    AccentButton(406-        label = "Export CSV",407-        enabled = acknowledged && !isEmpty,408-        onClick = { saveLauncher.launch("peach-export.csv") },409-    )410-    status?.let {411-        Spacer(Modifier.size(12.dp))412-        Text(413-            it,414-            color = if (it == ExportStrings.SAVE_FAILED) PeachColors.Breach else accent,415-            style = PeachType.labelMono,416-        )417-    }418-}419-420-@Composable421-private fun WarningCard(accent: Color, content: @Composable () -> Unit) {422-    Column(423-        modifier = Modifier424-            .fillMaxWidth()425-            .clip(RoundedCornerShape(18.dp))426-            .background(accent.copy(alpha = 0.08f))427-            .border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(18.dp))428-            .padding(20.dp),429-        content = { content() },430-    )431-}432-433-@Composable434-private fun CheckboxRow(label: String, checked: Boolean, accent: Color, onToggle: () -> Unit) {435-    Row(436-        verticalAlignment = Alignment.CenterVertically,437-        modifier = Modifier.fillMaxWidth().clickable(onClick = onToggle).padding(vertical = 4.dp),438-    ) {439-        Box(440-            modifier = Modifier441-                .size(18.dp)442-                .clip(RoundedCornerShape(5.dp))443-                .background(if (checked) accent else Color.Transparent)444-                .border(1.5.dp, if (checked) accent else PeachColors.T2, RoundedCornerShape(5.dp)),445-            contentAlignment = Alignment.Center,446-        ) {447-            if (checked) Text("✓", color = Color(0xFF0C0A06), style = PeachType.tinyMono.copy(fontSize = 12.sp))448-        }449-        Spacer(Modifier.width(12.dp))450-        Text(label, color = PeachColors.T0, style = PeachType.body)451-    }452-}453-454-// ---- Shared building blocks (private to this draft) -----------------------455-456-@Composable457-private fun InlineError(message: String) {458-    Box(459-        modifier = Modifier460-            .fillMaxWidth()461-            .clip(RoundedCornerShape(12.dp))462-            .background(PeachColors.BreachBg)463-            .border(1.dp, PeachColors.BreachBorder, RoundedCornerShape(12.dp))464-            .padding(14.dp),465-    ) {466-        Text(message, color = PeachColors.Breach, style = PeachType.bodyMono)467-    }468-}469-470-@Composable471-private fun FieldLabel(text: String) {472-    Text(text.uppercase(), color = PeachColors.T2, style = PeachType.labelMono)473-}474-475-@Composable476-private fun PeachUnderlineField(477-    value: String,478-    onValueChange: (String) -> Unit,479-    isPassword: Boolean = false,480-) {481-    val accent = LocalPeachAccent.current482-    Column(Modifier.fillMaxWidth()) {483-        BasicTextField(484-            value = value,485-            onValueChange = onValueChange,486-            singleLine = true,487-            textStyle = PeachType.bodyMono.copy(color = PeachColors.T0),488-            cursorBrush = SolidColor(accent),489-            visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None,490-            modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),491-        )492-        Box(Modifier.fillMaxWidth().height(1.dp).background(PeachColors.T3))493-    }494-}495-496-@Composable497-private fun GlassCard(content: @Composable () -> Unit) {498-    Column(499-        modifier = Modifier500-            .fillMaxWidth()501-            .clip(RoundedCornerShape(18.dp))502-            .background(PeachColors.SurfaceElevated)503-            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))504-            .padding(20.dp),505-        content = { content() },506-    )507-}508-509-@Composable510-private fun GhostButton(label: String, color: Color, onClick: () -> Unit) {511-    Box(512-        modifier = Modifier513-            .fillMaxWidth()514-            .clip(RoundedCornerShape(12.dp))515-            .border(1.dp, color.copy(alpha = 0.4f), RoundedCornerShape(12.dp))516-            .clickable(onClick = onClick)517-            .padding(vertical = 12.dp),518-        contentAlignment = Alignment.Center,519-    ) {520-        Text(label, color = color, style = PeachType.bodyMono)521-    }522-}523-524-@Composable525-private fun AccentButton(label: String, onClick: () -> Unit, enabled: Boolean = true) {526-    val accent = LocalPeachAccent.current527-    Box(528-        modifier = Modifier529-            .fillMaxWidth()530-            .clip(RoundedCornerShape(12.dp))531-            .background(if (enabled) accent else accent.copy(alpha = 0.3f))532-            .clickable(enabled = enabled, onClick = onClick)533-            .padding(vertical = 14.dp),534-        contentAlignment = Alignment.Center,535-    ) {536-        Text(label, color = Color(0xFF0C0A06), style = PeachType.bodyMono)537-    }538-}

view file at the parent

app/drafts/PeachScriptExport.kt+0 −141
@@ -1,141 +0,0 @@1-package com.peachpasswords.ui.vault2-3-import com.peachpasswords.vault.VaultCrypto4-import com.peachpasswords.vault.VaultEntry5-import java.util.Base646-7-/**8- * Pure-Kotlin serialisation for PeachScript exports (spec C2 PeachScript sub-view).9- *10- * This is the WRITE side of the format that [PeachScriptImport] reads. The shapes11- * below are pinned by B2 (see `B2-INTEGRATION.md`) and MUST round-trip:12- *13- *   PeachScriptImport.decryptAndParse(buildEncrypted(es, pw), pw)14- *       == DecryptResult.Success(es-as-ParsedEntry)15- *16- *   Plaintext:17- *     {18- *       "peachscript": 1,19- *       "encrypted": false,20- *       "entries": [ { "title", "username", "password", "url", "notes", "totp" }, ... ]21- *     }22- *23- *   Encrypted (backup-password protected):24- *     {25- *       "peachscript": 1,26- *       "encrypted": true,27- *       "kdf": "argon2id",28- *       "salt": "<base64 16 bytes = VaultCrypto.SALT_SIZE>",29- *       "blob": "<base64: 12-byte nonce || AES-256-GCM ciphertext||tag>"30- *     }31- *32- * The "blob" is exactly VaultCrypto.encrypt(plaintextJsonBytes, key, AAD) output33- * (nonce prepended). AAD is the constant [PeachScriptImport.PEACHSCRIPT_AAD]34- * ("peachscript_export_v1") — using any other AAD makes the importer's GCM tag35- * check fail and the user sees "Incorrect backup password."36- *37- * No Compose / Android UI here — unit-testable pure functions.38- */39-object PeachScriptExport {40-41-    /** Format version marker emitted as `"peachscript": 1`. */42-    private const val FORMAT_VERSION = 143-44-    // Standard (not URL-safe) base64, matching the decoder in PeachScriptImport.45-    private val b64 = Base64.getEncoder()46-47-    /**48-     * Serialise [entries] to the plaintext-shape PeachScript JSON. This is the49-     * exact byte sequence that gets encrypted for [buildEncrypted] (with50-     * "encrypted": false), so the importer reconstructs the same entries.51-     *52-     * Emits the importer's recognised keys (title/username/password/url/notes/totp).53-     * `email` is folded into `username` only when `username` is absent, since the54-     * PeachScript schema has no `email` field and the importer only reads these six.55-     */56-    fun buildPlaintext(entries: List<VaultEntry>): String {57-        val sb = StringBuilder(256 + entries.size * 96)58-        sb.append('{')59-        sb.append("\"peachscript\":").append(FORMAT_VERSION).append(',')60-        sb.append("\"encrypted\":false,")61-        sb.append("\"entries\":[")62-        entries.forEachIndexed { i, e ->63-            if (i > 0) sb.append(',')64-            appendEntry(sb, e)65-        }66-        sb.append("]}")67-        return sb.toString()68-    }69-70-    /**71-     * Build the encrypted-shape PeachScript JSON: generate a 16-byte salt, derive72-     * an Argon2id key from [backupPassword], AES-256-GCM encrypt the plaintext73-     * JSON with AAD [PeachScriptImport.PEACHSCRIPT_AAD], then base64 the salt and74-     * the nonce||ciphertext||tag blob. The derived key is zeroed after use.75-     */76-    fun buildEncrypted(entries: List<VaultEntry>, backupPassword: String): String {77-        val plaintext = buildPlaintext(entries).toByteArray(Charsets.UTF_8)78-        val salt = VaultCrypto.generateSalt()79-        val key = VaultCrypto.deriveKey(backupPassword, salt)80-        val blob = try {81-            VaultCrypto.encrypt(plaintext, key, PeachScriptImport.PEACHSCRIPT_AAD)82-        } finally {83-            VaultCrypto.zero(key)84-        }85-86-        val saltB64 = b64.encodeToString(salt)87-        val blobB64 = b64.encodeToString(blob)88-89-        val sb = StringBuilder(saltB64.length + blobB64.length + 96)90-        sb.append('{')91-        sb.append("\"peachscript\":").append(FORMAT_VERSION).append(',')92-        sb.append("\"encrypted\":true,")93-        sb.append("\"kdf\":\"argon2id\",")94-        sb.append("\"salt\":\"").append(saltB64).append("\",")95-        sb.append("\"blob\":\"").append(blobB64).append('"')96-        sb.append('}')97-        return sb.toString()98-    }99-100-    private fun appendEntry(sb: StringBuilder, e: VaultEntry) {101-        sb.append('{')102-        appendField(sb, "title", e.title, first = true)103-        appendField(sb, "username", e.username ?: e.email)104-        appendField(sb, "password", e.password)105-        appendField(sb, "url", e.url)106-        appendField(sb, "notes", e.notes)107-        appendField(sb, "totp", e.totp)108-        sb.append('}')109-    }110-111-    /**112-     * Append `"key":"<escaped value>"` (always emitted, even when null/empty, so113-     * the object shape is stable). [first] controls the leading comma.114-     */115-    private fun appendField(sb: StringBuilder, key: String, value: String?, first: Boolean = false) {116-        if (!first) sb.append(',')117-        sb.append('"').append(key).append("\":\"")118-        appendEscaped(sb, value ?: "")119-        sb.append('"')120-    }121-122-    /** Escape a JSON string body: backslash, quote, and control chars. */123-    private fun appendEscaped(sb: StringBuilder, s: String) {124-        for (c in s) {125-            when (c.code) {126-                '\\'.code -> sb.append("\\\\")127-                '"'.code -> sb.append("\\\"")128-                '\n'.code -> sb.append("\\n")129-                '\r'.code -> sb.append("\\r")130-                '\t'.code -> sb.append("\\t")131-                0x08 -> sb.append("\\b")132-                0x0C -> sb.append("\\f")133-                else -> if (c.code < 0x20) {134-                    sb.append("\\u").append(c.code.toString(16).padStart(4, '0'))135-                } else {136-                    sb.append(c)137-                }138-            }139-        }140-    }141-}

view file at the parent

app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+2 −1
@@ -23,6 +23,7 @@2323 import com.peachpasswords.ui.theme.PeachMotion2424 import com.peachpasswords.ui.vault.EntryDetailScreen2525 import com.peachpasswords.ui.vault.EntryEditScreen26+import com.peachpasswords.ui.vault.ExportScreen2627 import com.peachpasswords.ui.vault.ImportScreen2728 import com.peachpasswords.ui.vault.RecoveryWordsScreen2829 import com.peachpasswords.ui.vault.TrashScreen@@ -104,7 +105,7 @@104105         }105106         composable(PeachNav.Trash.route) { TrashScreen(onBack = back) }106107         composable(PeachNav.Import.route) { ImportScreen(onBack = back) }107-        composable(PeachNav.Export.route) { SimpleStub("Export", back) }108+        composable(PeachNav.Export.route) { ExportScreen(onBack = back) }108109         composable(PeachNav.Panic.route) {109110             PanicScreen(110111                 onBack = back,

view file

app/src/main/java/com/peachpasswords/ui/vault/CsvExport.kt+54 −0
@@ -0,0 +1,54 @@1+package com.peachpasswords.ui.vault2+3+import com.peachpasswords.vault.VaultEntry4+5+/**6+ * Pure-Kotlin CSV serialisation for the C2 Export screen (CSV sub-view).7+ *8+ * Columns (fixed order, spec line 325): title, username, password, url, notes.9+ * `username` falls back to `email` when blank, mirroring PeachScript export.10+ *11+ * Two layers of quoting are applied, in order:12+ *   1. Formula-injection guard (spec line 326): if a field's first character is13+ *      one of `= + - @`, TAB (0x09) or CR (0x0D), a leading single quote `'` is14+ *      prefixed so spreadsheet apps treat it as text, not a formula. This happens15+ *      BEFORE RFC-4180 quoting so the guard char lands inside the quotes.16+ *   2. RFC-4180 quoting: a field containing a comma, double-quote, CR or LF is17+ *      wrapped in double quotes, and any internal `"` is doubled (`""`).18+ *19+ * No Compose / Android UI here — unit-testable pure functions.20+ */21+object CsvExport {22+23+    private val HEADER = listOf("title", "username", "password", "url", "notes")24+25+    // Spreadsheet formula triggers. TAB/CR are included because some apps strip26+    // leading whitespace and then re-evaluate the first visible char as a formula.27+    private val INJECTION_PREFIXES = charArrayOf('=', '+', '-', '@', '\t', '\r')28+29+    // RFC-4180 line terminator.30+    private const val CRLF = "\r\n"31+32+    fun toCsv(entries: List<VaultEntry>): String {33+        val sb = StringBuilder(64 + entries.size * 64)34+        sb.append(HEADER.joinToString(",") { encodeField(it) }).append(CRLF)35+        for (e in entries) {36+            val row = listOf(37+                e.title,38+                e.username ?: e.email ?: "",39+                e.password ?: "",40+                e.url ?: "",41+                e.notes ?: "",42+            )43+            sb.append(row.joinToString(",") { encodeField(it) }).append(CRLF)44+        }45+        return sb.toString()46+    }47+48+    /** Apply the formula-injection guard, then RFC-4180 quoting. */49+    fun encodeField(raw: String): String {50+        val guarded = if (raw.isNotEmpty() && raw[0] in INJECTION_PREFIXES) "'$raw" else raw51+        val needsQuoting = guarded.any { it == ',' || it == '"' || it == '\n' || it == '\r' }52+        return if (needsQuoting) "\"" + guarded.replace("\"", "\"\"") + "\"" else guarded53+    }54+}

view file

app/src/main/java/com/peachpasswords/ui/vault/ExportScreen.kt+538 −0
@@ -0,0 +1,538 @@1+package com.peachpasswords.ui.vault2+3+import android.content.ClipData4+import android.content.ClipboardManager5+import android.content.Context6+import android.net.Uri7+import androidx.activity.compose.rememberLauncherForActivityResult8+import androidx.activity.result.contract.ActivityResultContracts9+import androidx.compose.foundation.background10+import androidx.compose.foundation.border11+import androidx.compose.foundation.clickable12+import androidx.compose.foundation.layout.Box13+import androidx.compose.foundation.layout.Column14+import androidx.compose.foundation.layout.Row15+import androidx.compose.foundation.layout.Spacer16+import androidx.compose.foundation.layout.fillMaxSize17+import androidx.compose.foundation.layout.fillMaxWidth18+import androidx.compose.foundation.layout.height19+import androidx.compose.foundation.layout.padding20+import androidx.compose.foundation.layout.size21+import androidx.compose.foundation.layout.systemBarsPadding22+import androidx.compose.foundation.layout.width23+import androidx.compose.foundation.rememberScrollState24+import androidx.compose.foundation.shape.RoundedCornerShape25+import androidx.compose.foundation.text.BasicTextField26+import androidx.compose.foundation.verticalScroll27+import androidx.compose.material.icons.Icons28+import androidx.compose.material.icons.automirrored.rounded.ArrowBack29+import androidx.compose.material3.Icon30+import androidx.compose.material3.Text31+import androidx.compose.runtime.Composable32+import androidx.compose.runtime.getValue33+import androidx.compose.runtime.mutableStateOf34+import androidx.compose.runtime.remember35+import androidx.compose.runtime.setValue36+import androidx.compose.ui.Alignment37+import androidx.compose.ui.Modifier38+import androidx.compose.ui.draw.clip39+import androidx.compose.ui.graphics.Color40+import androidx.compose.ui.graphics.SolidColor41+import androidx.compose.ui.platform.LocalContext42+import androidx.compose.ui.text.TextStyle43+import androidx.compose.ui.text.font.FontStyle44+import androidx.compose.ui.text.input.PasswordVisualTransformation45+import androidx.compose.ui.text.input.VisualTransformation46+import androidx.compose.ui.unit.dp47+import androidx.compose.ui.unit.sp48+import androidx.hilt.navigation.compose.hiltViewModel49+import androidx.lifecycle.ViewModel50+import com.peachpasswords.ui.theme.LocalPeachAccent51+import com.peachpasswords.ui.theme.PeachColors52+import com.peachpasswords.ui.theme.PeachType53+import com.peachpasswords.ui.theme.ShellBackground54+import com.peachpasswords.vault.VaultEntry55+import com.peachpasswords.vault.VaultRepository56+import dagger.hilt.android.lifecycle.HiltViewModel57+import dagger.hilt.android.qualifiers.ApplicationContext58+import javax.inject.Inject59+60+// ─────────────────────────────────────────────────────────────────────────────61+// Password strength scorer (local, dependency-free)62+// ─────────────────────────────────────────────────────────────────────────────63+64+/**65+ * Lightweight 0–4 strength score from length + character-class variety. No66+ * external lib, no network — this is a UI gate, not a security guarantee.67+ *68+ * Thresholds (deliberately simple and explainable):69+ *   - +1 if length >= 870+ *   - +1 if length >= 1271+ *   - +1 if at least 3 of {lowercase, uppercase, digit, symbol} are present72+ *   - +1 if all 4 classes are present73+ * Empty input scores 0. Result is clamped to 0..4. The C2 gate requires >= 374+ * ("good"); see [strengthLabel].75+ */76+internal fun scorePassword(pw: String): Int {77+    if (pw.isEmpty()) return 078+    var classes = 079+    if (pw.any { it in 'a'..'z' }) classes++80+    if (pw.any { it in 'A'..'Z' }) classes++81+    if (pw.any { it.isDigit() }) classes++82+    if (pw.any { !it.isLetterOrDigit() }) classes++83+84+    var score = 085+    if (pw.length >= 8) score++86+    if (pw.length >= 12) score++87+    if (classes >= 3) score++88+    if (classes >= 4) score++89+    return score.coerceIn(0, 4)90+}91+92+internal fun strengthLabel(score: Int): String = when (score) {93+    0 -> "very weak"94+    1 -> "weak"95+    2 -> "fair"96+    3 -> "good"97+    else -> "strong"98+}99+100+// ─────────────────────────────────────────────────────────────────────────────101+// ViewModel102+// ─────────────────────────────────────────────────────────────────────────────103+104+@HiltViewModel105+class ExportViewModel @Inject constructor(106+    private val vault: VaultRepository,107+    @ApplicationContext private val appContext: Context,108+) : ViewModel() {109+110+    /** Active (non-deleted) entries to export. */111+    fun entries(): List<VaultEntry> = vault.getEntries()112+113+    fun entryCount(): Int = vault.getEntries().size114+115+    /** Encrypted PeachScript export (backup-password protected). */116+    fun buildPeachScript(backupPassword: String): String =117+        PeachScriptExport.buildEncrypted(entries(), backupPassword)118+119+    /** Unencrypted CSV export. */120+    fun buildCsv(): String = CsvExport.toCsv(entries())121+122+    /** Write [content] to the SAF [uri]; returns false on any IO failure. */123+    fun writeToUri(uri: Uri, content: String): Boolean =124+        runCatching {125+            appContext.contentResolver.openOutputStream(uri)?.use {126+                it.write(content.toByteArray(Charsets.UTF_8))127+            } ?: return false128+            true129+        }.getOrDefault(false)130+}131+132+// ─────────────────────────────────────────────────────────────────────────────133+// Screen134+// ─────────────────────────────────────────────────────────────────────────────135+136+object ExportStrings {137+    const val EMPTY_VAULT = "Your vault is empty — nothing to export."138+    const val WEAK_PASSWORD = "Backup password too weak (score < 3)"139+    const val MISMATCH = "Passwords don't match."140+    const val SAVE_FAILED = "Couldn't write that file."141+    const val SAVED = "Saved."142+    const val COPIED = "Copied to clipboard."143+}144+145+private enum class ExportRoute { CHOOSE, PEACHSCRIPT, CSV }146+147+@Composable148+fun ExportScreen(149+    onBack: () -> Unit,150+    vm: ExportViewModel = hiltViewModel(),151+) {152+    var route by remember { mutableStateOf(ExportRoute.CHOOSE) }153+154+    ShellBackground {155+        Column(156+            modifier = Modifier157+                .fillMaxSize()158+                .systemBarsPadding()159+                .padding(horizontal = 20.dp, vertical = 16.dp),160+        ) {161+            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {162+                Icon(163+                    Icons.AutoMirrored.Rounded.ArrowBack,164+                    contentDescription = "back",165+                    tint = PeachColors.T0,166+                    modifier = Modifier167+                        .size(22.dp)168+                        .clip(RoundedCornerShape(8.dp))169+                        .clickable {170+                            if (route != ExportRoute.CHOOSE) route = ExportRoute.CHOOSE else onBack()171+                        },172+                )173+                Spacer(Modifier.width(14.dp))174+                Text(175+                    "Export",176+                    color = PeachColors.T0,177+                    style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),178+                )179+            }180+181+            Spacer(Modifier.size(18.dp))182+183+            Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {184+                when (route) {185+                    ExportRoute.CHOOSE -> ChooseView(186+                        onPeachScript = { route = ExportRoute.PEACHSCRIPT },187+                        onCsv = { route = ExportRoute.CSV },188+                    )189+                    ExportRoute.PEACHSCRIPT -> PeachScriptExportView(vm)190+                    ExportRoute.CSV -> CsvExportView(vm)191+                }192+            }193+        }194+    }195+}196+197+// ---- Choose view ----------------------------------------------------------198+199+@Composable200+private fun ChooseView(onPeachScript: () -> Unit, onCsv: () -> Unit) {201+    OptionCard(202+        title = "PeachScript (encrypted)",203+        subtitle = "A backup encrypted with a separate password. Restores into Peach.",204+        onClick = onPeachScript,205+    )206+    Spacer(Modifier.size(12.dp))207+    OptionCard(208+        title = "CSV (unencrypted)",209+        subtitle = "Plain text for moving into another manager. Not encrypted.",210+        onClick = onCsv,211+    )212+}213+214+@Composable215+private fun OptionCard(title: String, subtitle: String, onClick: () -> Unit) {216+    Column(217+        modifier = Modifier218+            .fillMaxWidth()219+            .clip(RoundedCornerShape(18.dp))220+            .background(PeachColors.SurfaceElevated)221+            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))222+            .clickable(onClick = onClick)223+            .padding(20.dp),224+    ) {225+        Text(226+            title,227+            color = PeachColors.T0,228+            style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),229+        )230+        Spacer(Modifier.size(6.dp))231+        Text(subtitle, color = PeachColors.T1, style = PeachType.body)232+    }233+}234+235+// ---- PeachScript sub-view -------------------------------------------------236+237+@Composable238+private fun PeachScriptExportView(vm: ExportViewModel) {239+    val accent = LocalPeachAccent.current240+    val context = LocalContext.current241+    val isEmpty = remember { vm.entryCount() == 0 }242+243+    var password by remember { mutableStateOf("") }244+    var confirm by remember { mutableStateOf("") }245+246+    // Generated artefact (the encrypted JSON string), set after [Generate backup].247+    var output by remember { mutableStateOf<String?>(null) }248+    var status by remember { mutableStateOf<String?>(null) }249+250+    val score = remember(password) { scorePassword(password) }251+    val matches = password.isNotEmpty() && password == confirm252+    val strongEnough = score >= 3253+    val canGenerate = !isEmpty && strongEnough && matches254+255+    val saveLauncher = rememberLauncherForActivityResult(256+        ActivityResultContracts.CreateDocument("*/*"),257+    ) { uri ->258+        val text = output259+        if (uri != null && text != null) {260+            status = if (vm.writeToUri(uri, text)) ExportStrings.SAVED else ExportStrings.SAVE_FAILED261+        }262+    }263+264+    GlassCard {265+        Text(266+            "create a\nbackup.",267+            color = PeachColors.T0,268+            style = TextStyle(269+                fontFamily = PeachType.Display, fontStyle = FontStyle.Italic,270+                fontSize = 24.sp, lineHeight = 26.sp,271+            ),272+        )273+        Spacer(Modifier.size(10.dp))274+        Text(275+            "Your vault will be encrypted with a separate backup password.",276+            color = PeachColors.T1, style = PeachType.body,277+        )278+279+        if (isEmpty) {280+            Spacer(Modifier.size(16.dp))281+            InlineError(ExportStrings.EMPTY_VAULT)282+        }283+284+        Spacer(Modifier.size(18.dp))285+        FieldLabel("Backup password")286+        Spacer(Modifier.size(6.dp))287+        PeachUnderlineField(value = password, onValueChange = { password = it; output = null; status = null }, isPassword = true)288+289+        Spacer(Modifier.size(16.dp))290+        FieldLabel("Confirm backup password")291+        Spacer(Modifier.size(6.dp))292+        PeachUnderlineField(value = confirm, onValueChange = { confirm = it; output = null; status = null }, isPassword = true)293+294+        Spacer(Modifier.size(16.dp))295+        StrengthBar(score = score, accent = accent)296+        Spacer(Modifier.size(6.dp))297+        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {298+            Text(299+                "strength: ${strengthLabel(score)}",300+                color = if (strongEnough) accent else PeachColors.T2,301+                style = PeachType.labelMono,302+            )303+        }304+305+        if (password.isNotEmpty() && !strongEnough) {306+            Spacer(Modifier.size(8.dp))307+            Text(ExportStrings.WEAK_PASSWORD, color = PeachColors.Breach, style = PeachType.bodyMono)308+        }309+        if (confirm.isNotEmpty() && !matches) {310+            Spacer(Modifier.size(8.dp))311+            Text(ExportStrings.MISMATCH, color = PeachColors.Breach, style = PeachType.bodyMono)312+        }313+    }314+315+    Spacer(Modifier.size(18.dp))316+317+    if (output == null) {318+        AccentButton(319+            label = "Generate backup",320+            enabled = canGenerate,321+            onClick = {322+                output = vm.buildPeachScript(password)323+                status = null324+            },325+        )326+    } else {327+        val text = output!!328+        GhostButton("Copy to clipboard", accent) {329+            val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager330+            cm.setPrimaryClip(ClipData.newPlainText("peach backup", text))331+            status = ExportStrings.COPIED332+        }333+        Spacer(Modifier.size(8.dp))334+        GhostButton("Save to file", PeachColors.T1) {335+            saveLauncher.launch("peach-backup.peach")336+        }337+        status?.let {338+            Spacer(Modifier.size(12.dp))339+            Text(340+                it,341+                color = if (it == ExportStrings.SAVE_FAILED) PeachColors.Breach else accent,342+                style = PeachType.labelMono,343+            )344+        }345+    }346+}347+348+@Composable349+private fun StrengthBar(score: Int, accent: Color) {350+    // Four segments; filled count == score. Color shifts to accent once "good".351+    val fillColor = if (score >= 3) accent else PeachColors.T2352+    Row(modifier = Modifier.fillMaxWidth()) {353+        repeat(4) { i ->354+            Box(355+                modifier = Modifier356+                    .weight(1f)357+                    .height(4.dp)358+                    .padding(end = if (i < 3) 4.dp else 0.dp)359+                    .clip(RoundedCornerShape(2.dp))360+                    .background(if (i < score) fillColor else PeachColors.T3),361+            )362+        }363+    }364+}365+366+// ---- CSV sub-view ---------------------------------------------------------367+368+@Composable369+private fun CsvExportView(vm: ExportViewModel) {370+    val accent = LocalPeachAccent.current371+    val isEmpty = remember { vm.entryCount() == 0 }372+373+    var acknowledged by remember { mutableStateOf(false) }374+    var status by remember { mutableStateOf<String?>(null) }375+376+    val saveLauncher = rememberLauncherForActivityResult(377+        ActivityResultContracts.CreateDocument("text/csv"),378+    ) { uri ->379+        if (uri != null) {380+            val csv = vm.buildCsv()381+            status = if (vm.writeToUri(uri, csv)) ExportStrings.SAVED else ExportStrings.SAVE_FAILED382+        }383+    }384+385+    WarningCard(accent) {386+        Text(387+            "⚠ CSV exports are not encrypted. Store this file securely and delete it after importing.",388+            color = PeachColors.T0, style = PeachType.body,389+        )390+        Spacer(Modifier.size(16.dp))391+        CheckboxRow(392+            label = "I understand this file is unencrypted",393+            checked = acknowledged,394+            accent = accent,395+            onToggle = { acknowledged = !acknowledged },396+        )397+    }398+399+    if (isEmpty) {400+        Spacer(Modifier.size(16.dp))401+        InlineError(ExportStrings.EMPTY_VAULT)402+    }403+404+    Spacer(Modifier.size(18.dp))405+    AccentButton(406+        label = "Export CSV",407+        enabled = acknowledged && !isEmpty,408+        onClick = { saveLauncher.launch("peach-export.csv") },409+    )410+    status?.let {411+        Spacer(Modifier.size(12.dp))412+        Text(413+            it,414+            color = if (it == ExportStrings.SAVE_FAILED) PeachColors.Breach else accent,415+            style = PeachType.labelMono,416+        )417+    }418+}419+420+@Composable421+private fun WarningCard(accent: Color, content: @Composable () -> Unit) {422+    Column(423+        modifier = Modifier424+            .fillMaxWidth()425+            .clip(RoundedCornerShape(18.dp))426+            .background(accent.copy(alpha = 0.08f))427+            .border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(18.dp))428+            .padding(20.dp),429+        content = { content() },430+    )431+}432+433+@Composable434+private fun CheckboxRow(label: String, checked: Boolean, accent: Color, onToggle: () -> Unit) {435+    Row(436+        verticalAlignment = Alignment.CenterVertically,437+        modifier = Modifier.fillMaxWidth().clickable(onClick = onToggle).padding(vertical = 4.dp),438+    ) {439+        Box(440+            modifier = Modifier441+                .size(18.dp)442+                .clip(RoundedCornerShape(5.dp))443+                .background(if (checked) accent else Color.Transparent)444+                .border(1.5.dp, if (checked) accent else PeachColors.T2, RoundedCornerShape(5.dp)),445+            contentAlignment = Alignment.Center,446+        ) {447+            if (checked) Text("✓", color = Color(0xFF0C0A06), style = PeachType.tinyMono.copy(fontSize = 12.sp))448+        }449+        Spacer(Modifier.width(12.dp))450+        Text(label, color = PeachColors.T0, style = PeachType.body)451+    }452+}453+454+// ---- Shared building blocks (private to this draft) -----------------------455+456+@Composable457+private fun InlineError(message: String) {458+    Box(459+        modifier = Modifier460+            .fillMaxWidth()461+            .clip(RoundedCornerShape(12.dp))462+            .background(PeachColors.BreachBg)463+            .border(1.dp, PeachColors.BreachBorder, RoundedCornerShape(12.dp))464+            .padding(14.dp),465+    ) {466+        Text(message, color = PeachColors.Breach, style = PeachType.bodyMono)467+    }468+}469+470+@Composable471+private fun FieldLabel(text: String) {472+    Text(text.uppercase(), color = PeachColors.T2, style = PeachType.labelMono)473+}474+475+@Composable476+private fun PeachUnderlineField(477+    value: String,478+    onValueChange: (String) -> Unit,479+    isPassword: Boolean = false,480+) {481+    val accent = LocalPeachAccent.current482+    Column(Modifier.fillMaxWidth()) {483+        BasicTextField(484+            value = value,485+            onValueChange = onValueChange,486+            singleLine = true,487+            textStyle = PeachType.bodyMono.copy(color = PeachColors.T0),488+            cursorBrush = SolidColor(accent),489+            visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None,490+            modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),491+        )492+        Box(Modifier.fillMaxWidth().height(1.dp).background(PeachColors.T3))493+    }494+}495+496+@Composable497+private fun GlassCard(content: @Composable () -> Unit) {498+    Column(499+        modifier = Modifier500+            .fillMaxWidth()501+            .clip(RoundedCornerShape(18.dp))502+            .background(PeachColors.SurfaceElevated)503+            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))504+            .padding(20.dp),505+        content = { content() },506+    )507+}508+509+@Composable510+private fun GhostButton(label: String, color: Color, onClick: () -> Unit) {511+    Box(512+        modifier = Modifier513+            .fillMaxWidth()514+            .clip(RoundedCornerShape(12.dp))515+            .border(1.dp, color.copy(alpha = 0.4f), RoundedCornerShape(12.dp))516+            .clickable(onClick = onClick)517+            .padding(vertical = 12.dp),518+        contentAlignment = Alignment.Center,519+    ) {520+        Text(label, color = color, style = PeachType.bodyMono)521+    }522+}523+524+@Composable525+private fun AccentButton(label: String, onClick: () -> Unit, enabled: Boolean = true) {526+    val accent = LocalPeachAccent.current527+    Box(528+        modifier = Modifier529+            .fillMaxWidth()530+            .clip(RoundedCornerShape(12.dp))531+            .background(if (enabled) accent else accent.copy(alpha = 0.3f))532+            .clickable(enabled = enabled, onClick = onClick)533+            .padding(vertical = 14.dp),534+        contentAlignment = Alignment.Center,535+    ) {536+        Text(label, color = Color(0xFF0C0A06), style = PeachType.bodyMono)537+    }538+}

view file

app/src/main/java/com/peachpasswords/ui/vault/PeachScriptExport.kt+141 −0
@@ -0,0 +1,141 @@1+package com.peachpasswords.ui.vault2+3+import com.peachpasswords.vault.VaultCrypto4+import com.peachpasswords.vault.VaultEntry5+import java.util.Base646+7+/**8+ * Pure-Kotlin serialisation for PeachScript exports (spec C2 PeachScript sub-view).9+ *10+ * This is the WRITE side of the format that [PeachScriptImport] reads. The shapes11+ * below are pinned by B2 (see `B2-INTEGRATION.md`) and MUST round-trip:12+ *13+ *   PeachScriptImport.decryptAndParse(buildEncrypted(es, pw), pw)14+ *       == DecryptResult.Success(es-as-ParsedEntry)15+ *16+ *   Plaintext:17+ *     {18+ *       "peachscript": 1,19+ *       "encrypted": false,20+ *       "entries": [ { "title", "username", "password", "url", "notes", "totp" }, ... ]21+ *     }22+ *23+ *   Encrypted (backup-password protected):24+ *     {25+ *       "peachscript": 1,26+ *       "encrypted": true,27+ *       "kdf": "argon2id",28+ *       "salt": "<base64 16 bytes = VaultCrypto.SALT_SIZE>",29+ *       "blob": "<base64: 12-byte nonce || AES-256-GCM ciphertext||tag>"30+ *     }31+ *32+ * The "blob" is exactly VaultCrypto.encrypt(plaintextJsonBytes, key, AAD) output33+ * (nonce prepended). AAD is the constant [PeachScriptImport.PEACHSCRIPT_AAD]34+ * ("peachscript_export_v1") — using any other AAD makes the importer's GCM tag35+ * check fail and the user sees "Incorrect backup password."36+ *37+ * No Compose / Android UI here — unit-testable pure functions.38+ */39+object PeachScriptExport {40+41+    /** Format version marker emitted as `"peachscript": 1`. */42+    private const val FORMAT_VERSION = 143+44+    // Standard (not URL-safe) base64, matching the decoder in PeachScriptImport.45+    private val b64 = Base64.getEncoder()46+47+    /**48+     * Serialise [entries] to the plaintext-shape PeachScript JSON. This is the49+     * exact byte sequence that gets encrypted for [buildEncrypted] (with50+     * "encrypted": false), so the importer reconstructs the same entries.51+     *52+     * Emits the importer's recognised keys (title/username/password/url/notes/totp).53+     * `email` is folded into `username` only when `username` is absent, since the54+     * PeachScript schema has no `email` field and the importer only reads these six.55+     */56+    fun buildPlaintext(entries: List<VaultEntry>): String {57+        val sb = StringBuilder(256 + entries.size * 96)58+        sb.append('{')59+        sb.append("\"peachscript\":").append(FORMAT_VERSION).append(',')60+        sb.append("\"encrypted\":false,")61+        sb.append("\"entries\":[")62+        entries.forEachIndexed { i, e ->63+            if (i > 0) sb.append(',')64+            appendEntry(sb, e)65+        }66+        sb.append("]}")67+        return sb.toString()68+    }69+70+    /**71+     * Build the encrypted-shape PeachScript JSON: generate a 16-byte salt, derive72+     * an Argon2id key from [backupPassword], AES-256-GCM encrypt the plaintext73+     * JSON with AAD [PeachScriptImport.PEACHSCRIPT_AAD], then base64 the salt and74+     * the nonce||ciphertext||tag blob. The derived key is zeroed after use.75+     */76+    fun buildEncrypted(entries: List<VaultEntry>, backupPassword: String): String {77+        val plaintext = buildPlaintext(entries).toByteArray(Charsets.UTF_8)78+        val salt = VaultCrypto.generateSalt()79+        val key = VaultCrypto.deriveKey(backupPassword, salt)80+        val blob = try {81+            VaultCrypto.encrypt(plaintext, key, PeachScriptImport.PEACHSCRIPT_AAD)82+        } finally {83+            VaultCrypto.zero(key)84+        }85+86+        val saltB64 = b64.encodeToString(salt)87+        val blobB64 = b64.encodeToString(blob)88+89+        val sb = StringBuilder(saltB64.length + blobB64.length + 96)90+        sb.append('{')91+        sb.append("\"peachscript\":").append(FORMAT_VERSION).append(',')92+        sb.append("\"encrypted\":true,")93+        sb.append("\"kdf\":\"argon2id\",")94+        sb.append("\"salt\":\"").append(saltB64).append("\",")95+        sb.append("\"blob\":\"").append(blobB64).append('"')96+        sb.append('}')97+        return sb.toString()98+    }99+100+    private fun appendEntry(sb: StringBuilder, e: VaultEntry) {101+        sb.append('{')102+        appendField(sb, "title", e.title, first = true)103+        appendField(sb, "username", e.username ?: e.email)104+        appendField(sb, "password", e.password)105+        appendField(sb, "url", e.url)106+        appendField(sb, "notes", e.notes)107+        appendField(sb, "totp", e.totp)108+        sb.append('}')109+    }110+111+    /**112+     * Append `"key":"<escaped value>"` (always emitted, even when null/empty, so113+     * the object shape is stable). [first] controls the leading comma.114+     */115+    private fun appendField(sb: StringBuilder, key: String, value: String?, first: Boolean = false) {116+        if (!first) sb.append(',')117+        sb.append('"').append(key).append("\":\"")118+        appendEscaped(sb, value ?: "")119+        sb.append('"')120+    }121+122+    /** Escape a JSON string body: backslash, quote, and control chars. */123+    private fun appendEscaped(sb: StringBuilder, s: String) {124+        for (c in s) {125+            when (c.code) {126+                '\\'.code -> sb.append("\\\\")127+                '"'.code -> sb.append("\\\"")128+                '\n'.code -> sb.append("\\n")129+                '\r'.code -> sb.append("\\r")130+                '\t'.code -> sb.append("\\t")131+                0x08 -> sb.append("\\b")132+                0x0C -> sb.append("\\f")133+                else -> if (c.code < 0x20) {134+                    sb.append("\\u").append(c.code.toString(16).padStart(4, '0'))135+                } else {136+                    sb.append(c)137+                }138+            }139+        }140+    }141+}

view file

app/src/test/java/com/peachpasswords/ui/vault/ExportRoundTripTest.kt+62 −0
@@ -0,0 +1,62 @@1+package com.peachpasswords.ui.vault2+3+import com.peachpasswords.vault.VaultEntry4+import org.junit.Assert.assertEquals5+import org.junit.Assert.assertTrue6+import org.junit.Test7+8+class ExportRoundTripTest {9+10+    private fun entry() = VaultEntry(11+        id = "1", title = "GitHub", type = "login",12+        username = "june", password = "hunter2", url = "https://github.com",13+        notes = "my note", totp = "JBSWY3DPEHPK3PXP", createdAt = 0, modifiedAt = 0,14+    )15+16+    @Test fun csv_formula_injection_is_guarded() {17+        assertEquals("'=1+1", CsvExport.encodeField("=1+1"))18+        assertEquals("'@cmd", CsvExport.encodeField("@cmd"))19+        assertEquals("'-2", CsvExport.encodeField("-2"))20+    }21+22+    @Test fun csv_quotes_fields_with_commas_and_quotes() {23+        assertEquals("\"a,b\"", CsvExport.encodeField("a,b"))24+        assertEquals("\"he\"\"llo\"", CsvExport.encodeField("he\"llo"))25+        assertEquals("plain", CsvExport.encodeField("plain"))26+    }27+28+    @Test fun csv_has_header_and_row() {29+        val csv = CsvExport.toCsv(listOf(entry()))30+        val lines = csv.trim().split("\r\n")31+        assertEquals("title,username,password,url,notes", lines[0])32+        assertTrue(lines[1].startsWith("GitHub,june,hunter2,"))33+    }34+35+    @Test fun peachscript_plaintext_round_trips_through_importer() {36+        val json = PeachScriptExport.buildPlaintext(listOf(entry()))37+        assertTrue(PeachScriptImport.looksLikePeachScript(json))38+        val parsed = PeachScriptImport.parsePlaintext(json)39+        assertEquals(1, parsed.size)40+        assertEquals("GitHub", parsed[0].title)41+        assertEquals("june", parsed[0].username)42+        assertEquals("hunter2", parsed[0].password)43+        assertEquals("my note", parsed[0].notes)44+        assertEquals("JBSWY3DPEHPK3PXP", parsed[0].totp)45+    }46+47+    @Test fun peachscript_encrypted_round_trips_with_correct_password() {48+        val blob = PeachScriptExport.buildEncrypted(listOf(entry()), "backup-pass-12")49+        assertTrue(PeachScriptImport.isEncrypted(blob))50+        val ok = PeachScriptImport.decryptAndParse(blob, "backup-pass-12")51+        assertTrue(ok is PeachScriptImport.DecryptResult.Success)52+        ok as PeachScriptImport.DecryptResult.Success53+        assertEquals(1, ok.entries.size)54+        assertEquals("hunter2", ok.entries[0].password)55+    }56+57+    @Test fun peachscript_encrypted_rejects_wrong_password() {58+        val blob = PeachScriptExport.buildEncrypted(listOf(entry()), "backup-pass-12")59+        val r = PeachScriptImport.decryptAndParse(blob, "wrong-password")60+        assertTrue(r is PeachScriptImport.DecryptResult.WrongPassword)61+    }62+}

view file