a324fae09c49

feat: C4 Pro license activation — make LicenseRepository Hilt @Singleton, SettingsViewModel.isPro now reactive StateFlow seeded from stored license; ProBody license-key input + offline Ed25519 activate (Invalid-key error) + active state w/ Deactivate; ProCelebration full-screen bloom overlay fires on activation then card-fan (v2.1.24)

time
2026-06-09 02:32 UTC · 5 months ago
machine
koh2
agent
claude-opus-4-8
session
peach gap implementation
parent
a2171a3f8ecc
10 files app/build.gradle+2 −2app/drafts/B2-INTEGRATION.md+172 −0app/drafts/CsvImport.kt+414 −0app/drafts/ImportScreen.kt+668 −0app/drafts/PeachScriptImport.kt+231 −0app/src/main/java/com/peachpasswords/license/LicenseRepository.kt+5 −1app/src/main/java/com/peachpasswords/ui/settings/ProCelebration.kt+110 −0app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+82 −3app/src/main/java/com/peachpasswords/ui/settings/SettingsScreen.kt+7 −2app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+53 −4
app/build.gradle+2 −2
@@ -16,8 +16,8 @@1616         applicationId "com.peachpasswords"1717         minSdk 261818         targetSdk 3519-        versionCode 20102320-        versionName "2.1.23"19+        versionCode 20102420+        versionName "2.1.24"2121 2222         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"2323         vectorDrawables {

view file

app/drafts/B2-INTEGRATION.md+172 −0
@@ -0,0 +1,172 @@1+# B2 — Import Screen: Integration Note2+3+Draft implementation of spec B2 (lines 110–163). Three Kotlin files plus this note,4+all under `app/drafts/`. They are written to drop straight into the source tree —5+package is already `com.peachpasswords.ui.vault`.6+7+## Files to MOVE into the source set8+9+Move these from `app/drafts/` to10+`app/src/main/java/com/peachpasswords/ui/vault/` (package already correct —11+`package com.peachpasswords.ui.vault`):12+13+| Draft file | Destination | Contents |14+|---|---|---|15+| `CsvImport.kt` | `ui/vault/CsvImport.kt` | Pure Kotlin: `ParsedEntry`, `ImportParseResult`, `CsvImport` (provider detection + CSV/JSON parsers, RFC-4180 splitter) |16+| `PeachScriptImport.kt` | `ui/vault/PeachScriptImport.kt` | Pure Kotlin: PeachScript sniff/detect/decrypt/parse |17+| `ImportScreen.kt` | `ui/vault/ImportScreen.kt` | Compose UI + `ImportViewModel` |18+19+`B2-INTEGRATION.md` stays in drafts (or delete after wiring) — it is not source.20+21+No edits were made to any existing file. `PeachNav.kt`, `PeachAppNavHost.kt`,22+`VaultRepository.kt`, `VaultEntry.kt`, `VaultCrypto.kt` were read only.23+24+## Public composable signature25+26+```kotlin27+@Composable28+fun ImportScreen(onBack: () -> Unit)29+// (also has a defaulted vm = hiltViewModel() param, like TrashScreen)30+```31+32+## Nav wiring33+34+`PeachNav.Import` route already exists. In `PeachAppNavHost.kt`, replace the35+`Import` route's `SimpleStub` with:36+37+```kotlin38+ImportScreen(onBack = back)39+```40+41+where `back` is the same back lambda the other vault screens use (e.g. how42+`TrashScreen(onBack = back)` is wired). No new route, no nav-graph change needed.43+44+Note: `ImportScreen` also handles internal back navigation itself (preview/error →45+input view, sub-view → choose view); it only calls `onBack()` when at the top46+choose view or after Done. So a single `onBack=back` is correct.47+48+## VaultRepository methods used (all already exist — no new API assumed)49+50+- `suspend fun addEntry(draft: VaultEntry): VaultEntry` — import loops this51+  per parsed entry (confirmed: no batch method exists).52+- `fun getEntries(): List<VaultEntry>` — used by REPLACE mode to enumerate53+  current active entries.54+- `suspend fun deleteEntry(id: String)` — REPLACE soft-deletes existing active55+  entries before adding the imported set. (Chose soft-delete over a hard wipe so56+  a mistaken "Replace" is recoverable from Trash. If the orchestrator wants a true57+  replace, swap to `purgeEntry` or `destroyVault` — but that is destructive.)58+59+`VaultEntry` drafts are built with `id = ""` (repo assigns UUID), `type = "login"`,60+and `createdAt/modifiedAt = now` (repo overrides modifiedAt with a monotonic stamp).61+62+## VaultCrypto API found (quoted from source)63+64+From `app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt`:65+66+```kotlin67+object VaultCrypto {68+    const val ARGON2_MEMORY_KB = 6553669+    const val ARGON2_ITERATIONS = 370+    const val ARGON2_PARALLELISM = 471+    const val ARGON2_HASH_LENGTH = 3272+    const val SALT_SIZE = 1673+    const val NONCE_SIZE = 1274+    const val TAG_LENGTH_BITS = 12875+    const val KEY_SIZE = 3276+77+    fun deriveKey(password: String, salt: ByteArray): ByteArray   // Argon2id (BouncyCastle)78+    fun encrypt(plaintext: ByteArray, key: ByteArray, aad: String): ByteArray  // nonce(12) || ct||tag79+    fun decrypt(data: ByteArray, key: ByteArray, aad: String): ByteArray       // expects nonce(12) prefix80+    fun generateSalt(): ByteArray   // 16 bytes81+    fun zero(bytes: ByteArray)82+}83+```84+85+- KDF: Argon2id, 64 MiB memory, 3 iterations, parallelism 4, 32-byte output.86+- AEAD: AES-256-GCM, 128-bit tag, 12-byte random nonce **prepended** to the87+  ciphertext (`encrypt` returns `nonce + cipher.doFinal(...)`; `decrypt` reads the88+  first 12 bytes as the nonce). AAD is a UTF-8 string argument.89+90+`PeachScriptImport.decryptAndParse` is implemented end-to-end against this API91+(derive → decrypt → parse), since the on-the-wire shape is fully specified by the92+header format below. A GCM tag mismatch surfaces as `WrongPassword`.93+94+## PeachScript header / export format chosen (C2 export MUST mirror this)95+96+A PeachScript export is a single JSON object carrying a magic marker key97+`"peachscript"` (also the format version).98+99+**Plaintext:**100+```json101+{102+  "peachscript": 1,103+  "encrypted": false,104+  "entries": [105+    { "title": "...", "username": "...", "password": "...",106+      "url": "...", "notes": "...", "totp": "..." }107+  ]108+}109+```110+111+**Encrypted (backup-password protected):**112+```json113+{114+  "peachscript": 1,115+  "encrypted": true,116+  "kdf": "argon2id",117+  "salt": "<base64, 16 bytes = VaultCrypto.SALT_SIZE>",118+  "blob": "<base64: 12-byte nonce || AES-256-GCM ciphertext||tag>"119+}120+```121+122+- `blob` is exactly `VaultCrypto.encrypt(plaintextJsonBytes, key, AAD)` output123+  (nonce prepended). `salt` feeds `VaultCrypto.deriveKey(backupPassword, salt)`.124+- Decrypted plaintext is the UTF-8 bytes of the **plaintext-shape** JSON object125+  above (with `"encrypted": false`).126+- **AAD is the constant string** `"peachscript_export_v1"`127+  (`PeachScriptImport.PEACHSCRIPT_AAD`). C2 export must encrypt with this exact128+  AAD or the GCM tag check fails and the user sees "Incorrect backup password."129+- Detection: `looksLikePeachScript` = trimmed text starts with `{` and contains130+  `"peachscript"`. `isEncrypted` = contains `"encrypted": true`.131+  Standard base64 (not URL-safe) is used for `salt`/`blob`.132+133+## CSV / provider detection summary134+135+`CsvImport.detectProvider(content)` returns one of:136+`"Bitwarden CSV"`, `"Bitwarden JSON"`, `"1Password CSV"`, `"Chrome CSV"`,137+`"Edge CSV"`, `"Safari CSV"`, `"CSV"` (generic), or `null` (unrecognised).138+139+- Chrome and Edge share the identical Chromium header140+  (`name,url,username,password`) and are indistinguishable from content alone —141+  detection returns `"Chrome CSV"`; UI copy says "Chrome/Edge". `parse` treats142+  both identically.143+- Bitwarden JSON detection is a shape check (`{` + `"items": [`); only login144+  items (`type` absent or `== 1`) are imported.145+- The CSV parser is a single RFC-4180-ish state machine handling quoted fields,146+  embedded commas, doubled quotes (`""`→`"`), and CR/LF inside quotes.147+- `detectAndParse` returns a sealed `ImportParseResult` mapping to the spec error148+  strings (UNRECOGNISED / CORRUPTED / NO_ENTRIES).149+150+## Spec error strings (in `ImportScreen.ImportErrors`)151+152+- Unrecognised PeachScript: "This doesn't look like a PeachScript export."153+- Wrong backup password: "Incorrect backup password."154+- Corrupted: "This export appears to be corrupted."155+- No entries: "No entries found in this export."156+- (extras) "Couldn't read that file." / "Unrecognised file format."157+158+## Assumptions / things for the orchestrator to confirm159+160+1. REPLACE uses soft-delete (recoverable via Trash). Change to a hard wipe if161+   the spec's `RESTORE_ENTRIES` semantics require it.162+2. `GetContent()` launched with `"*/*"` (not `.csv,.json`) because some exporters163+   report odd MIME types for CSV; the parser sniffs content regardless. Swap to164+   `OpenDocument()` with `arrayOf("text/csv","application/json")` if a stricter165+   picker is preferred.166+3. The minimal hand-rolled JSON scanners in `CsvImport`/`PeachScriptImport` avoid167+   adding a JSON dependency to the pure modules. If `kotlinx.serialization` is168+   already on the classpath (it is — `VaultEntry` is `@Serializable`), these could169+   be swapped for a typed decode later; kept dependency-free here for testability.170+4. Entry-point wiring (Lock screen RestoreTabs pills, Settings → Vault → Import171+   row) is out of scope for this draft — only the `PeachNav.Import` route swap is172+   described. Those entry points just need to navigate to the existing route.

view file

app/drafts/CsvImport.kt+414 −0
@@ -0,0 +1,414 @@1+package com.peachpasswords.ui.vault2+3+/**4+ * Pure-Kotlin CSV / JSON import parsing for the Import screen (spec B2).5+ *6+ * No Android or Compose dependencies — everything here is deterministic and7+ * unit-testable. The UI layer ([ImportScreen]) calls [detectProvider] then8+ * [parse]; the parsed rows are mapped to VaultEntry drafts at the call site.9+ *10+ * Supported providers (detected from header / content shape):11+ *   - "Bitwarden CSV"  (folder,favorite,type,name,login_uri,login_username,login_password,login_totp,notes)12+ *   - "Bitwarden JSON" ({"items":[...]})13+ *   - "1Password CSV"  (Title,Url,Username,Password,... — 1Password v8 export)14+ *   - "Chrome CSV"     (name,url,username,password)15+ *   - "Edge CSV"       (same columns as Chrome — Chromium family)16+ *   - "Safari CSV"     (Title,URL,Username,Password,Notes,OTPAuth)17+ *   - "CSV"            (generic fallback: best-effort column matching)18+ */19+20+/** One parsed credential, provider-agnostic. Null/blank fields are omitted later. */21+data class ParsedEntry(22+    val title: String,23+    val username: String? = null,24+    val password: String? = null,25+    val url: String? = null,26+    val notes: String? = null,27+    val totp: String? = null,28+)29+30+/** Result of an import attempt: the detected provider label plus parsed rows. */31+sealed interface ImportParseResult {32+    data class Success(val provider: String, val entries: List<ParsedEntry>) : ImportParseResult33+    data class Failure(val reason: Reason) : ImportParseResult34+35+    enum class Reason { UNRECOGNISED, CORRUPTED, NO_ENTRIES }36+}37+38+object CsvImport {39+40+    // Display labels used both for detection return values and "Detected: X export".41+    const val BITWARDEN_CSV = "Bitwarden CSV"42+    const val BITWARDEN_JSON = "Bitwarden JSON"43+    const val ONEPASSWORD_CSV = "1Password CSV"44+    const val CHROME_CSV = "Chrome CSV"45+    const val EDGE_CSV = "Edge CSV"46+    const val SAFARI_CSV = "Safari CSV"47+    const val GENERIC_CSV = "CSV"48+49+    /**50+     * Sniff the provider from raw file content. Returns a provider label or null51+     * when the content is neither recognisable JSON nor a parseable CSV header.52+     */53+    fun detectProvider(content: String): String? {54+        val trimmed = content.trim()55+        if (trimmed.isEmpty()) return null56+57+        // Bitwarden JSON: an object carrying an "items" array. Cheap shape check58+        // rather than a full parse — the parser does the real decode.59+        if (trimmed.startsWith("{") && Regex("\"items\"\\s*:\\s*\\[").containsMatchIn(trimmed)) {60+            return BITWARDEN_JSON61+        }62+        // Any other top-level JSON we don't understand is not a CSV.63+        if (trimmed.startsWith("{") || trimmed.startsWith("[")) return null64+65+        val header = firstNonBlankLine(trimmed) ?: return null66+        val cols = splitCsvLine(header).map { it.trim().lowercase() }67+        val set = cols.toSet()68+69+        return when {70+            set.containsAll(listOf("name", "login_uri", "login_username", "login_password")) -> BITWARDEN_CSV71+            // Chrome and Edge share the exact Chromium export header. They are72+            // indistinguishable from content alone; default to Chrome, the UI73+            // copy says "Chrome/Edge export" so the label is honest.74+            cols == listOf("name", "url", "username", "password") -> CHROME_CSV75+            set.containsAll(listOf("title", "url", "username", "password")) &&76+                (set.contains("otpauth") || set.contains("notes")) -> SAFARI_CSV77+            set.containsAll(listOf("title", "url", "username", "password")) -> ONEPASSWORD_CSV78+            // Generic: any header with at least a name/title and a password column.79+            (set.contains("name") || set.contains("title")) &&80+                set.any { it.contains("password") } -> GENERIC_CSV81+            else -> null82+        }83+    }84+85+    /**86+     * Parse [content] as the given [provider]. Provider should come from87+     * [detectProvider]; passing an unknown label falls back to generic CSV.88+     * Throws nothing — malformed content yields an empty list, which the UI89+     * surfaces as the "No entries found" error.90+     */91+    fun parse(content: String, provider: String): List<ParsedEntry> = when (provider) {92+        BITWARDEN_JSON -> parseBitwardenJson(content)93+        BITWARDEN_CSV -> parseCsvByHeader(content, BitwardenCsvMap)94+        CHROME_CSV, EDGE_CSV -> parseCsvByHeader(content, ChromeCsvMap)95+        SAFARI_CSV -> parseCsvByHeader(content, SafariCsvMap)96+        ONEPASSWORD_CSV -> parseCsvByHeader(content, OnePasswordCsvMap)97+        else -> parseCsvByHeader(content, GenericCsvMap)98+    }99+100+    /** Convenience: detect + parse in one call, returning a sealed result. */101+    fun detectAndParse(content: String): ImportParseResult {102+        val provider = detectProvider(content)103+            ?: return ImportParseResult.Failure(ImportParseResult.Reason.UNRECOGNISED)104+        val entries = parse(content, provider)105+        return if (entries.isEmpty()) {106+            ImportParseResult.Failure(ImportParseResult.Reason.NO_ENTRIES)107+        } else {108+            ImportParseResult.Success(provider, entries)109+        }110+    }111+112+    // ---- CSV column maps --------------------------------------------------113+114+    /**115+     * Maps lower-cased CSV header names to the [ParsedEntry] field they feed.116+     * Each list is tried in order; the first present column wins. This lets one117+     * generic row-builder serve every CSV provider.118+     */119+    private class CsvColumnMap(120+        val title: List<String>,121+        val username: List<String>,122+        val password: List<String>,123+        val url: List<String>,124+        val notes: List<String>,125+        val totp: List<String>,126+    )127+128+    private val BitwardenCsvMap = CsvColumnMap(129+        title = listOf("name"),130+        username = listOf("login_username"),131+        password = listOf("login_password"),132+        url = listOf("login_uri"),133+        notes = listOf("notes"),134+        totp = listOf("login_totp"),135+    )136+137+    private val ChromeCsvMap = CsvColumnMap(138+        title = listOf("name"),139+        username = listOf("username"),140+        password = listOf("password"),141+        url = listOf("url"),142+        notes = listOf("note", "notes"),143+        totp = emptyList(),144+    )145+146+    private val SafariCsvMap = CsvColumnMap(147+        title = listOf("title"),148+        username = listOf("username"),149+        password = listOf("password"),150+        url = listOf("url"),151+        notes = listOf("notes"),152+        totp = listOf("otpauth"),153+    )154+155+    private val OnePasswordCsvMap = CsvColumnMap(156+        title = listOf("title"),157+        username = listOf("username"),158+        password = listOf("password"),159+        url = listOf("url", "website"),160+        notes = listOf("notes"),161+        totp = listOf("otpauth", "one-time password", "totp"),162+    )163+164+    private val GenericCsvMap = CsvColumnMap(165+        title = listOf("name", "title"),166+        username = listOf("username", "user", "login", "email"),167+        password = listOf("password", "login_password", "pass"),168+        url = listOf("url", "login_uri", "website", "uri"),169+        notes = listOf("notes", "note"),170+        totp = listOf("totp", "login_totp", "otpauth"),171+    )172+173+    private fun parseCsvByHeader(content: String, map: CsvColumnMap): List<ParsedEntry> {174+        val rows = parseCsv(content)175+        if (rows.size < 2) return emptyList()176+        val header = rows.first().map { it.trim().lowercase() }177+        fun col(names: List<String>): Int = names.firstNotNullOfOrNull { n ->178+            header.indexOf(n).takeIf { it >= 0 }179+        } ?: -1180+181+        val ti = col(map.title)182+        val ui = col(map.username)183+        val pi = col(map.password)184+        val urli = col(map.url)185+        val ni = col(map.notes)186+        val toi = col(map.totp)187+188+        fun cell(row: List<String>, idx: Int): String? =189+            if (idx in row.indices) row[idx].trim().ifEmpty { null } else null190+191+        return rows.drop(1).mapNotNull { row ->192+            if (row.all { it.isBlank() }) return@mapNotNull null193+            val title = cell(row, ti)194+                ?: cell(row, urli)195+                ?: cell(row, ui)196+                ?: return@mapNotNull null197+            ParsedEntry(198+                title = title,199+                username = cell(row, ui),200+                password = cell(row, pi),201+                url = cell(row, urli),202+                notes = cell(row, ni),203+                totp = cell(row, toi),204+            )205+        }206+    }207+208+    // ---- Bitwarden JSON ---------------------------------------------------209+210+    /**211+     * Minimal extractor for Bitwarden's unencrypted JSON export. Avoids pulling212+     * a JSON dependency into this pure module by walking the `items` array with a213+     * tolerant brace-aware scanner; only login items (type 1) are imported.214+     */215+    private fun parseBitwardenJson(content: String): List<ParsedEntry> {216+        val itemsArray = extractItemsArray(content) ?: return emptyList()217+        val objects = splitTopLevelObjects(itemsArray)218+        return objects.mapNotNull { obj ->219+            val type = jsonNumber(obj, "type")220+            // Bitwarden type 1 == login. Skip cards/notes/identities for now.221+            if (type != null && type != 1) return@mapNotNull null222+            val name = jsonString(obj, "name") ?: return@mapNotNull null223+            val loginBlock = extractObject(obj, "login") ?: ""224+            ParsedEntry(225+                title = name,226+                username = jsonString(loginBlock, "username"),227+                password = jsonString(loginBlock, "password"),228+                url = extractFirstUri(loginBlock),229+                notes = jsonString(obj, "notes"),230+                totp = jsonString(loginBlock, "totp"),231+            )232+        }233+    }234+235+    private fun extractItemsArray(content: String): String? {236+        val key = Regex("\"items\"\\s*:\\s*\\[").find(content) ?: return null237+        val start = key.range.last // index of '['238+        var depth = 0239+        var i = start240+        var inStr = false241+        var esc = false242+        while (i < content.length) {243+            val c = content[i]244+            if (inStr) {245+                when {246+                    esc -> esc = false247+                    c == '\\' -> esc = true248+                    c == '"' -> inStr = false249+                }250+            } else when (c) {251+                '"' -> inStr = true252+                '[' -> depth++253+                ']' -> { depth--; if (depth == 0) return content.substring(start + 1, i) }254+            }255+            i++256+        }257+        return null258+    }259+260+    /** Split a JSON array body into its top-level `{...}` object substrings. */261+    private fun splitTopLevelObjects(arrayBody: String): List<String> {262+        val out = mutableListOf<String>()263+        var depth = 0264+        var startIdx = -1265+        var inStr = false266+        var esc = false267+        for (i in arrayBody.indices) {268+            val c = arrayBody[i]269+            if (inStr) {270+                when {271+                    esc -> esc = false272+                    c == '\\' -> esc = true273+                    c == '"' -> inStr = false274+                }275+                continue276+            }277+            when (c) {278+                '"' -> inStr = true279+                '{' -> { if (depth == 0) startIdx = i; depth++ }280+                '}' -> { depth--; if (depth == 0 && startIdx >= 0) { out.add(arrayBody.substring(startIdx, i + 1)); startIdx = -1 } }281+            }282+        }283+        return out284+    }285+286+    /** Extract the substring of a nested object value for [key], braces balanced. */287+    private fun extractObject(obj: String, key: String): String? {288+        val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*\\{").find(obj) ?: return null289+        var depth = 0290+        var inStr = false291+        var esc = false292+        var i = m.range.last // index of '{'293+        val start = i294+        while (i < obj.length) {295+            val c = obj[i]296+            if (inStr) {297+                when {298+                    esc -> esc = false299+                    c == '\\' -> esc = true300+                    c == '"' -> inStr = false301+                }302+            } else when (c) {303+                '"' -> inStr = true304+                '{' -> depth++305+                '}' -> { depth--; if (depth == 0) return obj.substring(start, i + 1) }306+            }307+            i++308+        }309+        return null310+    }311+312+    private fun extractFirstUri(loginBlock: String): String? {313+        // login.uris is [{ "match": null, "uri": "https://..." }, ...]314+        val uriInArray = Regex("\"uris\"\\s*:\\s*\\[(.*?)]", RegexOption.DOT_MATCHES_ALL)315+            .find(loginBlock)?.groupValues?.get(1)316+        if (uriInArray != null) {317+            jsonString(uriInArray, "uri")?.let { return it }318+        }319+        return jsonString(loginBlock, "uri")320+    }321+322+    private fun jsonString(scope: String, key: String): String? {323+        val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"").find(scope)324+            ?: return null325+        return unescapeJson(m.groupValues[1]).ifEmpty { null }326+    }327+328+    private fun jsonNumber(scope: String, key: String): Int? {329+        val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*(-?\\d+)").find(scope) ?: return null330+        return m.groupValues[1].toIntOrNull()331+    }332+333+    private fun unescapeJson(s: String): String {334+        val sb = StringBuilder(s.length)335+        var i = 0336+        while (i < s.length) {337+            val c = s[i]338+            if (c == '\\' && i + 1 < s.length) {339+                when (val n = s[i + 1]) {340+                    'n' -> sb.append('\n')341+                    't' -> sb.append('\t')342+                    'r' -> sb.append('\r')343+                    '"' -> sb.append('"')344+                    '\\' -> sb.append('\\')345+                    '/' -> sb.append('/')346+                    'u' -> {347+                        if (i + 5 < s.length) {348+                            val code = s.substring(i + 2, i + 6).toIntOrNull(16)349+                            if (code != null) { sb.append(code.toChar()); i += 6; continue }350+                        }351+                        sb.append(n)352+                    }353+                    else -> sb.append(n)354+                }355+                i += 2356+            } else {357+                sb.append(c)358+                i++359+            }360+        }361+        return sb.toString()362+    }363+364+    // ---- RFC-4180-ish CSV --------------------------------------------------365+366+    /**367+     * Parse a whole CSV document into rows of fields. Handles quoted fields,368+     * embedded commas, doubled quotes ("" -> "), and newlines inside quotes369+     * (CRLF or LF). Trailing blank line is ignored.370+     */371+    fun parseCsv(content: String): List<List<String>> {372+        val rows = mutableListOf<List<String>>()373+        var field = StringBuilder()374+        var row = mutableListOf<String>()375+        var inQuotes = false376+        var i = 0377+        val n = content.length378+379+        fun endField() { row.add(field.toString()); field = StringBuilder() }380+        fun endRow() { endField(); rows.add(row); row = mutableListOf() }381+382+        while (i < n) {383+            val c = content[i]384+            if (inQuotes) {385+                when {386+                    c == '"' && i + 1 < n && content[i + 1] == '"' -> { field.append('"'); i++ }387+                    c == '"' -> inQuotes = false388+                    else -> field.append(c)389+                }390+            } else {391+                when (c) {392+                    '"' -> inQuotes = true393+                    ',' -> endField()394+                    '\r' -> { /* swallow; \n handles row end */ }395+                    '\n' -> endRow()396+                    else -> field.append(c)397+                }398+            }399+            i++400+        }401+        // Flush trailing field/row if the file does not end with a newline, or if402+        // any content accumulated after the last newline.403+        if (field.isNotEmpty() || row.isNotEmpty()) endRow()404+        // Drop a final fully-empty row produced by a trailing newline.405+        return rows.filterNot { it.size == 1 && it[0].isEmpty() }406+    }407+408+    /** Split a single CSV line into fields (used only for header sniffing). */409+    fun splitCsvLine(line: String): List<String> =410+        parseCsv(line).firstOrNull() ?: emptyList()411+412+    private fun firstNonBlankLine(s: String): String? =413+        s.lineSequence().firstOrNull { it.isNotBlank() }414+}

view file

app/drafts/ImportScreen.kt+668 −0
@@ -0,0 +1,668 @@1+package com.peachpasswords.ui.vault2+3+import android.content.Context4+import android.net.Uri5+import androidx.activity.compose.rememberLauncherForActivityResult6+import androidx.activity.result.contract.ActivityResultContracts7+import androidx.compose.foundation.background8+import androidx.compose.foundation.border9+import androidx.compose.foundation.clickable10+import androidx.compose.foundation.layout.Arrangement11+import androidx.compose.foundation.layout.Box12+import androidx.compose.foundation.layout.Column13+import androidx.compose.foundation.layout.Row14+import androidx.compose.foundation.layout.Spacer15+import androidx.compose.foundation.layout.fillMaxSize16+import androidx.compose.foundation.layout.fillMaxWidth17+import androidx.compose.foundation.layout.heightIn18+import androidx.compose.foundation.layout.padding19+import androidx.compose.foundation.layout.size20+import androidx.compose.foundation.layout.systemBarsPadding21+import androidx.compose.foundation.layout.width22+import androidx.compose.foundation.rememberScrollState23+import androidx.compose.foundation.shape.RoundedCornerShape24+import androidx.compose.foundation.text.BasicTextField25+import androidx.compose.foundation.verticalScroll26+import androidx.compose.material.icons.Icons27+import androidx.compose.material.icons.automirrored.rounded.ArrowBack28+import androidx.compose.material3.Icon29+import androidx.compose.material3.Text30+import androidx.compose.runtime.Composable31+import androidx.compose.runtime.collectAsState32+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.text.TextStyle42+import androidx.compose.ui.text.font.FontStyle43+import androidx.compose.ui.text.input.PasswordVisualTransformation44+import androidx.compose.ui.unit.dp45+import androidx.compose.ui.unit.sp46+import androidx.hilt.navigation.compose.hiltViewModel47+import androidx.lifecycle.ViewModel48+import androidx.lifecycle.viewModelScope49+import com.peachpasswords.ui.theme.LocalPeachAccent50+import com.peachpasswords.ui.theme.PeachColors51+import com.peachpasswords.ui.theme.PeachType52+import com.peachpasswords.ui.theme.ShellBackground53+import com.peachpasswords.vault.VaultEntry54+import com.peachpasswords.vault.VaultRepository55+import dagger.hilt.android.lifecycle.HiltViewModel56+import dagger.hilt.android.qualifiers.ApplicationContext57+import kotlinx.coroutines.Dispatchers58+import kotlinx.coroutines.flow.MutableStateFlow59+import kotlinx.coroutines.flow.StateFlow60+import kotlinx.coroutines.flow.asStateFlow61+import kotlinx.coroutines.launch62+import kotlinx.coroutines.withContext63+import javax.inject.Inject64+65+// ─────────────────────────────────────────────────────────────────────────────66+// ViewModel67+// ─────────────────────────────────────────────────────────────────────────────68+69+/** How parsed entries land in the vault on confirm. */70+enum class ImportMode { MERGE, REPLACE }71+72+/** A staged, parsed import ready for preview + confirm. */73+data class ImportPreview(74+    val sourceLabel: String,75+    val entries: List<ParsedEntry>,76+)77+78+sealed interface ImportUiState {79+    data object Idle : ImportUiState80+    data object Working : ImportUiState81+    data class Preview(val preview: ImportPreview) : ImportUiState82+    data class Done(val count: Int) : ImportUiState83+    data class Failed(val message: String) : ImportUiState84+}85+86+object ImportErrors {87+    const val UNRECOGNISED = "This doesn't look like a PeachScript export."88+    const val WRONG_PASSWORD = "Incorrect backup password."89+    const val CORRUPTED = "This export appears to be corrupted."90+    const val NO_ENTRIES = "No entries found in this export."91+    const val UNREADABLE_FILE = "Couldn't read that file."92+    const val UNRECOGNISED_FILE = "Unrecognised file format."93+}94+95+@HiltViewModel96+class ImportViewModel @Inject constructor(97+    private val vault: VaultRepository,98+    @ApplicationContext private val appContext: Context,99+) : ViewModel() {100+101+    private val _state = MutableStateFlow<ImportUiState>(ImportUiState.Idle)102+    val state: StateFlow<ImportUiState> = _state.asStateFlow()103+104+    /** Detected provider label for the file sub-view ("Detected: X export"). */105+    private val _detectedProvider = MutableStateFlow<String?>(null)106+    val detectedProvider: StateFlow<String?> = _detectedProvider.asStateFlow()107+108+    fun reset() {109+        _state.value = ImportUiState.Idle110+        _detectedProvider.value = null111+    }112+113+    fun back(onBack: () -> Unit) {114+        // Preview/error back returns to the input view; otherwise leave the screen.115+        when (_state.value) {116+            is ImportUiState.Preview, is ImportUiState.Failed, is ImportUiState.Done -> reset()117+            else -> onBack()118+        }119+    }120+121+    // ---- PeachScript paste ------------------------------------------------122+123+    fun importPeachScript(text: String, backupPassword: String) {124+        val trimmed = text.trim()125+        if (trimmed.isEmpty() || !PeachScriptImport.looksLikePeachScript(trimmed)) {126+            _state.value = ImportUiState.Failed(ImportErrors.UNRECOGNISED)127+            return128+        }129+        _state.value = ImportUiState.Working130+        viewModelScope.launch {131+            val result = withContext(Dispatchers.Default) {132+                if (PeachScriptImport.isEncrypted(trimmed)) {133+                    PeachScriptImport.decryptAndParse(trimmed, backupPassword)134+                } else {135+                    val entries = PeachScriptImport.parsePlaintext(trimmed)136+                    if (entries.isEmpty()) PeachScriptImport.DecryptResult.Corrupted137+                    else PeachScriptImport.DecryptResult.Success(entries)138+                }139+            }140+            _state.value = when (result) {141+                is PeachScriptImport.DecryptResult.Success ->142+                    ImportUiState.Preview(ImportPreview("PeachScript", result.entries))143+                PeachScriptImport.DecryptResult.WrongPassword ->144+                    ImportUiState.Failed(ImportErrors.WRONG_PASSWORD)145+                PeachScriptImport.DecryptResult.Corrupted ->146+                    ImportUiState.Failed(ImportErrors.NO_ENTRIES)147+            }148+        }149+    }150+151+    /** True when the pasted text is a PeachScript export that needs a password. */152+    fun peachScriptNeedsPassword(text: String): Boolean {153+        val t = text.trim()154+        return PeachScriptImport.looksLikePeachScript(t) && PeachScriptImport.isEncrypted(t)155+    }156+157+    // ---- File import ------------------------------------------------------158+159+    fun importFile(uri: Uri) {160+        _state.value = ImportUiState.Working161+        _detectedProvider.value = null162+        viewModelScope.launch {163+            val content = withContext(Dispatchers.IO) {164+                runCatching {165+                    appContext.contentResolver.openInputStream(uri)?.use {166+                        it.readBytes().toString(Charsets.UTF_8)167+                    }168+                }.getOrNull()169+            }170+            if (content.isNullOrBlank()) {171+                _state.value = ImportUiState.Failed(ImportErrors.UNREADABLE_FILE)172+                return@launch173+            }174+            val result = withContext(Dispatchers.Default) { CsvImport.detectAndParse(content) }175+            when (result) {176+                is ImportParseResult.Success -> {177+                    _detectedProvider.value = result.provider178+                    _state.value = ImportUiState.Preview(ImportPreview(result.provider, result.entries))179+                }180+                is ImportParseResult.Failure -> {181+                    _state.value = ImportUiState.Failed(182+                        when (result.reason) {183+                            ImportParseResult.Reason.UNRECOGNISED -> ImportErrors.UNRECOGNISED_FILE184+                            ImportParseResult.Reason.CORRUPTED -> ImportErrors.CORRUPTED185+                            ImportParseResult.Reason.NO_ENTRIES -> ImportErrors.NO_ENTRIES186+                        },187+                    )188+                }189+            }190+        }191+    }192+193+    // ---- Confirm ----------------------------------------------------------194+195+    /**196+     * Persist the previewed entries. No batch API exists on VaultRepository, so197+     * import loops [VaultRepository.addEntry]. REPLACE soft-deletes the current198+     * active set first; MERGE simply appends.199+     */200+    fun confirmImport(preview: ImportPreview, mode: ImportMode) {201+        _state.value = ImportUiState.Working202+        viewModelScope.launch {203+            try {204+                if (mode == ImportMode.REPLACE) {205+                    vault.getEntries().forEach { existing ->206+                        runCatching { vault.deleteEntry(existing.id) }207+                    }208+                }209+                val now = System.currentTimeMillis()210+                var imported = 0211+                for (p in preview.entries) {212+                    val draft = VaultEntry(213+                        id = "",214+                        type = "login",215+                        title = p.title,216+                        username = p.username,217+                        password = p.password,218+                        url = p.url,219+                        notes = p.notes,220+                        totp = p.totp,221+                        createdAt = now,222+                        modifiedAt = now,223+                    )224+                    runCatching { vault.addEntry(draft) }.onSuccess { imported++ }225+                }226+                _state.value = ImportUiState.Done(imported)227+            } catch (e: Exception) {228+                _state.value = ImportUiState.Failed(ImportErrors.CORRUPTED)229+            }230+        }231+    }232+}233+234+// ─────────────────────────────────────────────────────────────────────────────235+// Screen236+// ─────────────────────────────────────────────────────────────────────────────237+238+private enum class ImportRoute { CHOOSE, PEACHSCRIPT, FILE }239+240+@Composable241+fun ImportScreen(242+    onBack: () -> Unit,243+    vm: ImportViewModel = hiltViewModel(),244+) {245+    val state by vm.state.collectAsState()246+    var route by remember { mutableStateOf(ImportRoute.CHOOSE) }247+248+    ShellBackground {249+        Column(250+            modifier = Modifier251+                .fillMaxSize()252+                .systemBarsPadding()253+                .padding(horizontal = 20.dp, vertical = 16.dp),254+        ) {255+            // Top bar: back · "Import"256+            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {257+                Icon(258+                    Icons.AutoMirrored.Rounded.ArrowBack,259+                    contentDescription = "back",260+                    tint = PeachColors.T0,261+                    modifier = Modifier262+                        .size(22.dp)263+                        .clip(RoundedCornerShape(8.dp))264+                        .clickable {265+                            when {266+                                state !is ImportUiState.Idle -> vm.back(onBack)267+                                route != ImportRoute.CHOOSE -> route = ImportRoute.CHOOSE268+                                else -> onBack()269+                            }270+                        },271+                )272+                Spacer(Modifier.width(14.dp))273+                Text(274+                    "Import",275+                    color = PeachColors.T0,276+                    style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),277+                )278+            }279+280+            Spacer(Modifier.size(18.dp))281+282+            Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {283+                when (val s = state) {284+                    is ImportUiState.Preview -> PreviewView(285+                        preview = s.preview,286+                        onConfirm = { mode -> vm.confirmImport(s.preview, mode) },287+                        onCancel = { vm.reset() },288+                    )289+                    is ImportUiState.Done -> DoneView(count = s.count, onDone = onBack)290+                    is ImportUiState.Failed -> {291+                        ErrorBanner(s.message)292+                        Spacer(Modifier.size(16.dp))293+                        when (route) {294+                            ImportRoute.PEACHSCRIPT -> PeachScriptView(vm)295+                            ImportRoute.FILE -> FileView(vm)296+                            ImportRoute.CHOOSE -> ChooseView(297+                                onPeachScript = { route = ImportRoute.PEACHSCRIPT },298+                                onFile = { route = ImportRoute.FILE },299+                            )300+                        }301+                    }302+                    ImportUiState.Working -> WorkingView()303+                    ImportUiState.Idle -> when (route) {304+                        ImportRoute.CHOOSE -> ChooseView(305+                            onPeachScript = { route = ImportRoute.PEACHSCRIPT },306+                            onFile = { route = ImportRoute.FILE },307+                        )308+                        ImportRoute.PEACHSCRIPT -> PeachScriptView(vm)309+                        ImportRoute.FILE -> FileView(vm)310+                    }311+                }312+            }313+        }314+    }315+}316+317+// ---- Choose view ----------------------------------------------------------318+319+@Composable320+private fun ChooseView(onPeachScript: () -> Unit, onFile: () -> Unit) {321+    OptionCard(322+        title = "From PeachScript",323+        subtitle = "Paste an encrypted Peach export",324+        onClick = onPeachScript,325+    )326+    Spacer(Modifier.size(12.dp))327+    OptionCard(328+        title = "From file",329+        subtitle = "Bitwarden, 1Password, Chrome, Safari, Edge CSV",330+        onClick = onFile,331+    )332+}333+334+@Composable335+private fun OptionCard(title: String, subtitle: String, onClick: () -> Unit) {336+    Column(337+        modifier = Modifier338+            .fillMaxWidth()339+            .clip(RoundedCornerShape(18.dp))340+            .background(PeachColors.SurfaceElevated)341+            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))342+            .clickable(onClick = onClick)343+            .padding(20.dp),344+    ) {345+        Text(346+            title,347+            color = PeachColors.T0,348+            style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),349+        )350+        Spacer(Modifier.size(6.dp))351+        Text(subtitle, color = PeachColors.T1, style = PeachType.body)352+    }353+}354+355+// ---- PeachScript sub-view -------------------------------------------------356+357+@Composable358+private fun PeachScriptView(vm: ImportViewModel) {359+    var paste by remember { mutableStateOf("") }360+    var backupPassword by remember { mutableStateOf("") }361+    val needsPassword = remember(paste) { vm.peachScriptNeedsPassword(paste) }362+363+    GlassCard {364+        FieldLabel("Paste your PeachScript export")365+        Spacer(Modifier.size(8.dp))366+        PeachMultilineField(367+            value = paste,368+            onValueChange = { paste = it },369+            minLines = 6,370+        )371+        if (needsPassword) {372+            Spacer(Modifier.size(16.dp))373+            FieldLabel("Backup password")374+            Spacer(Modifier.size(6.dp))375+            PeachUnderlineField(376+                value = backupPassword,377+                onValueChange = { backupPassword = it },378+                isPassword = true,379+            )380+        }381+    }382+    Spacer(Modifier.size(18.dp))383+    AccentButton(384+        label = "Import",385+        enabled = paste.isNotBlank(),386+        onClick = { vm.importPeachScript(paste, backupPassword) },387+    )388+}389+390+// ---- File sub-view --------------------------------------------------------391+392+@Composable393+private fun FileView(vm: ImportViewModel) {394+    val detected by vm.detectedProvider.collectAsState()395+    val picker = rememberLauncherForActivityResult(396+        ActivityResultContracts.GetContent(),397+    ) { uri -> if (uri != null) vm.importFile(uri) }398+399+    GlassCard {400+        Text(401+            "Import from a CSV or JSON export",402+            color = PeachColors.T1,403+            style = PeachType.body,404+        )405+        Spacer(Modifier.size(6.dp))406+        Text(407+            "Supports Bitwarden, 1Password, Chrome/Edge, and Safari exports.",408+            color = PeachColors.T2,409+            style = PeachType.hint,410+        )411+        Spacer(Modifier.size(16.dp))412+        GhostButton("Choose file", LocalPeachAccent.current) {413+            // GetContent takes a single MIME type; the chooser still lists CSV414+            // and JSON. "*/*" is intentional so providers exporting odd MIME415+            // types for .csv are not filtered out by the system picker.416+            picker.launch("*/*")417+        }418+        if (detected != null) {419+            Spacer(Modifier.size(12.dp))420+            Text(421+                "Detected: $detected export",422+                color = LocalPeachAccent.current,423+                style = PeachType.labelMono,424+            )425+        }426+    }427+}428+429+// ---- Preview --------------------------------------------------------------430+431+@Composable432+private fun PreviewView(433+    preview: ImportPreview,434+    onConfirm: (ImportMode) -> Unit,435+    onCancel: () -> Unit,436+) {437+    var mode by remember { mutableStateOf(ImportMode.MERGE) }438+439+    GlassCard {440+        Text(441+            "Detected: ${preview.sourceLabel} export",442+            color = LocalPeachAccent.current,443+            style = PeachType.labelMono,444+        )445+        Spacer(Modifier.size(10.dp))446+        Text(447+            "Found ${preview.entries.size} ${if (preview.entries.size == 1) "entry" else "entries"}",448+            color = PeachColors.T0,449+            style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),450+        )451+        Spacer(Modifier.size(12.dp))452+        // Up to five entry names, scrollable if more.453+        Column(454+            modifier = Modifier455+                .fillMaxWidth()456+                .heightIn(max = 150.dp)457+                .verticalScroll(rememberScrollState()),458+        ) {459+            preview.entries.take(5).forEach { e ->460+                Text(461+                    e.title,462+                    color = PeachColors.T1,463+                    style = PeachType.entryNameList,464+                    modifier = Modifier.padding(vertical = 4.dp),465+                )466+            }467+            if (preview.entries.size > 5) {468+                Text(469+                    "+${preview.entries.size - 5} more",470+                    color = PeachColors.T2,471+                    style = PeachType.tinyMono,472+                    modifier = Modifier.padding(top = 4.dp),473+                )474+            }475+        }476+        Divider()477+        RadioRow("Merge with existing vault", selected = mode == ImportMode.MERGE) { mode = ImportMode.MERGE }478+        Spacer(Modifier.size(8.dp))479+        RadioRow("Replace vault", selected = mode == ImportMode.REPLACE) { mode = ImportMode.REPLACE }480+    }481+    Spacer(Modifier.size(18.dp))482+    AccentButton(label = "Confirm Import", onClick = { onConfirm(mode) })483+    Spacer(Modifier.size(8.dp))484+    GhostButton("Cancel", PeachColors.T1, onCancel)485+}486+487+@Composable488+private fun RadioRow(label: String, selected: Boolean, onClick: () -> Unit) {489+    val accent = LocalPeachAccent.current490+    Row(491+        verticalAlignment = Alignment.CenterVertically,492+        modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(vertical = 4.dp),493+    ) {494+        Box(495+            modifier = Modifier496+                .size(16.dp)497+                .clip(RoundedCornerShape(999.dp))498+                .border(1.5.dp, if (selected) accent else PeachColors.T2, RoundedCornerShape(999.dp)),499+            contentAlignment = Alignment.Center,500+        ) {501+            if (selected) {502+                Box(Modifier.size(8.dp).clip(RoundedCornerShape(999.dp)).background(accent))503+            }504+        }505+        Spacer(Modifier.width(12.dp))506+        Text(label, color = PeachColors.T0, style = PeachType.body)507+    }508+}509+510+// ---- Done / Working / Error ----------------------------------------------511+512+@Composable513+private fun DoneView(count: Int, onDone: () -> Unit) {514+    GlassCard {515+        Text(516+            "imported.",517+            color = PeachColors.T0,518+            style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 24.sp),519+        )520+        Spacer(Modifier.size(8.dp))521+        Text(522+            "$count ${if (count == 1) "entry" else "entries"} imported.",523+            color = PeachColors.T1,524+            style = PeachType.body,525+        )526+    }527+    Spacer(Modifier.size(18.dp))528+    AccentButton(label = "Done", onClick = onDone)529+}530+531+@Composable532+private fun WorkingView() {533+    Box(Modifier.fillMaxWidth().padding(vertical = 40.dp), contentAlignment = Alignment.Center) {534+        Text(535+            "working…",536+            color = PeachColors.T1,537+            style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp),538+        )539+    }540+}541+542+@Composable543+private fun ErrorBanner(message: String) {544+    Box(545+        modifier = Modifier546+            .fillMaxWidth()547+            .clip(RoundedCornerShape(12.dp))548+            .background(PeachColors.BreachBg)549+            .border(1.dp, PeachColors.BreachBorder, RoundedCornerShape(12.dp))550+            .padding(14.dp),551+    ) {552+        Text(message, color = PeachColors.Breach, style = PeachType.bodyMono)553+    }554+}555+556+// ---- Shared building blocks (private to this draft) -----------------------557+558+@Composable559+private fun FieldLabel(text: String) {560+    Text(561+        text.uppercase(),562+        color = PeachColors.T2,563+        style = PeachType.labelMono,564+    )565+}566+567+@Composable568+private fun PeachMultilineField(569+    value: String,570+    onValueChange: (String) -> Unit,571+    minLines: Int,572+) {573+    val accent = LocalPeachAccent.current574+    Box(575+        modifier = Modifier576+            .fillMaxWidth()577+            .clip(RoundedCornerShape(12.dp))578+            .background(PeachColors.S2)579+            .border(1.dp, PeachColors.T3, RoundedCornerShape(12.dp))580+            .padding(14.dp),581+    ) {582+        BasicTextField(583+            value = value,584+            onValueChange = onValueChange,585+            textStyle = PeachType.bodyMono.copy(color = PeachColors.T0),586+            cursorBrush = SolidColor(accent),587+            minLines = minLines,588+            modifier = Modifier.fillMaxWidth(),589+        )590+        if (value.isEmpty()) {591+            Text(592+                "{ \"peachscript\": 1, … }",593+                color = PeachColors.T2,594+                style = PeachType.bodyMono,595+            )596+        }597+    }598+}599+600+@Composable601+private fun PeachUnderlineField(602+    value: String,603+    onValueChange: (String) -> Unit,604+    isPassword: Boolean = false,605+) {606+    val accent = LocalPeachAccent.current607+    Column(Modifier.fillMaxWidth()) {608+        BasicTextField(609+            value = value,610+            onValueChange = onValueChange,611+            singleLine = true,612+            textStyle = PeachType.bodyMono.copy(color = PeachColors.T0),613+            cursorBrush = SolidColor(accent),614+            visualTransformation = if (isPassword) PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None,615+            modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),616+        )617+        Box(Modifier.fillMaxWidth().size(1.dp).background(PeachColors.T3))618+    }619+}620+621+@Composable622+private fun GlassCard(content: @Composable () -> Unit) {623+    Column(624+        modifier = Modifier625+            .fillMaxWidth()626+            .clip(RoundedCornerShape(18.dp))627+            .background(PeachColors.SurfaceElevated)628+            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))629+            .padding(20.dp),630+        content = { content() },631+    )632+}633+634+@Composable635+private fun Divider() {636+    Box(Modifier.fillMaxWidth().padding(vertical = 14.dp).size(1.dp).background(PeachColors.T3))637+}638+639+@Composable640+private fun GhostButton(label: String, color: Color, onClick: () -> Unit) {641+    Box(642+        modifier = Modifier643+            .fillMaxWidth()644+            .clip(RoundedCornerShape(12.dp))645+            .border(1.dp, color.copy(alpha = 0.4f), RoundedCornerShape(12.dp))646+            .clickable(onClick = onClick)647+            .padding(vertical = 12.dp),648+        contentAlignment = Alignment.Center,649+    ) {650+        Text(label, color = color, style = PeachType.bodyMono)651+    }652+}653+654+@Composable655+private fun AccentButton(label: String, onClick: () -> Unit, enabled: Boolean = true) {656+    val accent = LocalPeachAccent.current657+    Box(658+        modifier = Modifier659+            .fillMaxWidth()660+            .clip(RoundedCornerShape(12.dp))661+            .background(if (enabled) accent else accent.copy(alpha = 0.3f))662+            .clickable(enabled = enabled, onClick = onClick)663+            .padding(vertical = 14.dp),664+        contentAlignment = Alignment.Center,665+    ) {666+        Text(label, color = Color(0xFF0C0A06), style = PeachType.bodyMono)667+    }668+}

view file

app/drafts/PeachScriptImport.kt+231 −0
@@ -0,0 +1,231 @@1+package com.peachpasswords.ui.vault2+3+import com.peachpasswords.vault.VaultCrypto4+import java.util.Base645+6+/**7+ * Pure-Kotlin parsing for PeachScript exports (spec B2 PeachScript sub-view).8+ *9+ * PEACHSCRIPT FORMAT (chosen here — C2 export MUST mirror this):10+ *11+ * A PeachScript export is a single JSON object with a magic marker so it can be12+ * sniffed without a full parse:13+ *14+ *   Plaintext:15+ *     {16+ *       "peachscript": 1,                  // magic marker + format version17+ *       "encrypted": false,18+ *       "entries": [ { "title": "...", "username": "...", "password": "...",19+ *                      "url": "...", "notes": "...", "totp": "..." }, ... ]20+ *     }21+ *22+ *   Encrypted (backup-password protected):23+ *     {24+ *       "peachscript": 1,25+ *       "encrypted": true,26+ *       "kdf": "argon2id",27+ *       "salt": "<base64 16 bytes>",       // VaultCrypto.SALT_SIZE28+ *       "blob": "<base64: 12-byte nonce || AES-256-GCM ciphertext||tag>"29+ *     }30+ *31+ * The encrypted "blob" is exactly what [VaultCrypto.encrypt]/[VaultCrypto.decrypt]32+ * produce/consume: nonce (NONCE_SIZE=12) prepended to ciphertext+tag. The33+ * decrypted plaintext is the UTF-8 bytes of the plaintext-shape JSON object34+ * above (with "encrypted": false). The AAD for the GCM envelope is defined below35+ * as [PEACHSCRIPT_AAD]; C2 export must use the same AAD string.36+ *37+ * No Compose / Android UI here — unit-testable pure functions.38+ */39+object PeachScriptImport {40+41+    /** Magic marker key any PeachScript JSON object must carry. */42+    private const val MARKER = "\"peachscript\""43+44+    /**45+     * AAD for the encrypted-export GCM envelope. Distinct from the vault's46+     * internal AADs (slot_a_v1 etc.) so a backup blob can never be confused with47+     * an at-rest vault slot. C2 export must encrypt with this exact string.48+     */49+    const val PEACHSCRIPT_AAD = "peachscript_export_v1"50+51+    /**52+     * Magic-header check: does this text look like a PeachScript export at all?53+     * Cheap sniff (object start + marker key) — does not validate the payload.54+     */55+    fun looksLikePeachScript(text: String): Boolean {56+        val t = text.trim()57+        return t.startsWith("{") && t.contains(MARKER)58+    }59+60+    /** True when the payload declares itself encrypted (`"encrypted": true`). */61+    fun isEncrypted(text: String): Boolean =62+        Regex("\"encrypted\"\\s*:\\s*true").containsMatchIn(text)63+64+    /**65+     * Parse an unencrypted PeachScript export's entry array. Returns an empty66+     * list when the marker is absent or no entries are present; the UI maps that67+     * to the "No entries found" / "unrecognised" errors.68+     */69+    fun parsePlaintext(text: String): List<ParsedEntry> {70+        if (!looksLikePeachScript(text)) return emptyList()71+        val entriesBody = extractArrayBody(text, "entries") ?: return emptyList()72+        return splitTopLevelObjects(entriesBody).mapNotNull { obj ->73+            val title = jsonString(obj, "title") ?: jsonString(obj, "name") ?: return@mapNotNull null74+            ParsedEntry(75+                title = title,76+                username = jsonString(obj, "username"),77+                password = jsonString(obj, "password"),78+                url = jsonString(obj, "url"),79+                notes = jsonString(obj, "notes"),80+                totp = jsonString(obj, "totp"),81+            )82+        }83+    }84+85+    /** Outcome of decrypting + parsing an encrypted export. */86+    sealed interface DecryptResult {87+        data class Success(val entries: List<ParsedEntry>) : DecryptResult88+        data object WrongPassword : DecryptResult89+        data object Corrupted : DecryptResult90+    }91+92+    /**93+     * Decrypt an encrypted PeachScript export with the user's backup password,94+     * then parse the inner plaintext entries.95+     *96+     * IMPLEMENTED against the exact VaultCrypto API found in the source:97+     *   - KDF:     VaultCrypto.deriveKey(password, salt)  (Argon2id,98+     *              MEMORY=65536KB, ITER=3, PARALLELISM=4, 32-byte key)99+     *   - decrypt: VaultCrypto.decrypt(data, key, aad)    (AES-256-GCM, expects100+     *              NONCE_SIZE=12 prepended; AAD = [PEACHSCRIPT_AAD])101+     *   - zero:    VaultCrypto.zero(key)102+     *103+     * The on-the-wire shape (salt + nonce||ct||tag base64) is fully specified in104+     * the file header, so this path is implemented end to end. C2 export must105+     * produce a blob with the matching AAD/nonce layout or decryption will fail106+     * the GCM tag check and surface as [DecryptResult.WrongPassword].107+     */108+    fun decryptAndParse(text: String, backupPassword: String): DecryptResult {109+        val saltB64 = jsonRawString(text, "salt") ?: return DecryptResult.Corrupted110+        val blobB64 = jsonRawString(text, "blob") ?: return DecryptResult.Corrupted111+112+        val salt = runCatching { Base64.getDecoder().decode(saltB64) }.getOrNull()113+            ?: return DecryptResult.Corrupted114+        val blob = runCatching { Base64.getDecoder().decode(blobB64) }.getOrNull()115+            ?: return DecryptResult.Corrupted116+        if (salt.size != VaultCrypto.SALT_SIZE || blob.size <= VaultCrypto.NONCE_SIZE) {117+            return DecryptResult.Corrupted118+        }119+120+        val key = VaultCrypto.deriveKey(backupPassword, salt)121+        val plaintext = try {122+            VaultCrypto.decrypt(blob, key, PEACHSCRIPT_AAD)123+        } catch (_: Exception) {124+            // GCM tag mismatch ⇒ wrong password (or tampered blob). Spec treats125+            // this as "Incorrect backup password."126+            return DecryptResult.WrongPassword127+        } finally {128+            VaultCrypto.zero(key)129+        }130+131+        val json = String(plaintext, Charsets.UTF_8)132+        val entries = parsePlaintext(json)133+        return if (entries.isEmpty()) DecryptResult.Corrupted else DecryptResult.Success(entries)134+    }135+136+    // ---- Minimal JSON helpers (shared shape with CsvImport) ----------------137+138+    private fun extractArrayBody(scope: String, key: String): String? {139+        val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*\\[").find(scope) ?: return null140+        val start = m.range.last // index of '['141+        var depth = 0142+        var inStr = false143+        var esc = false144+        var i = start145+        while (i < scope.length) {146+            val c = scope[i]147+            if (inStr) {148+                when {149+                    esc -> esc = false150+                    c == '\\' -> esc = true151+                    c == '"' -> inStr = false152+                }153+            } else when (c) {154+                '"' -> inStr = true155+                '[' -> depth++156+                ']' -> { depth--; if (depth == 0) return scope.substring(start + 1, i) }157+            }158+            i++159+        }160+        return null161+    }162+163+    private fun splitTopLevelObjects(arrayBody: String): List<String> {164+        val out = mutableListOf<String>()165+        var depth = 0166+        var startIdx = -1167+        var inStr = false168+        var esc = false169+        for (i in arrayBody.indices) {170+            val c = arrayBody[i]171+            if (inStr) {172+                when {173+                    esc -> esc = false174+                    c == '\\' -> esc = true175+                    c == '"' -> inStr = false176+                }177+                continue178+            }179+            when (c) {180+                '"' -> inStr = true181+                '{' -> { if (depth == 0) startIdx = i; depth++ }182+                '}' -> { depth--; if (depth == 0 && startIdx >= 0) { out.add(arrayBody.substring(startIdx, i + 1)); startIdx = -1 } }183+            }184+        }185+        return out186+    }187+188+    private fun jsonString(scope: String, key: String): String? {189+        val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"").find(scope)190+            ?: return null191+        return unescapeJson(m.groupValues[1]).ifEmpty { null }192+    }193+194+    /** Like [jsonString] but keeps an empty string (used for base64 fields). */195+    private fun jsonRawString(scope: String, key: String): String? {196+        val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"").find(scope)197+            ?: return null198+        return unescapeJson(m.groupValues[1])199+    }200+201+    private fun unescapeJson(s: String): String {202+        val sb = StringBuilder(s.length)203+        var i = 0204+        while (i < s.length) {205+            val c = s[i]206+            if (c == '\\' && i + 1 < s.length) {207+                when (val n = s[i + 1]) {208+                    'n' -> sb.append('\n')209+                    't' -> sb.append('\t')210+                    'r' -> sb.append('\r')211+                    '"' -> sb.append('"')212+                    '\\' -> sb.append('\\')213+                    '/' -> sb.append('/')214+                    'u' -> {215+                        if (i + 5 < s.length) {216+                            val code = s.substring(i + 2, i + 6).toIntOrNull(16)217+                            if (code != null) { sb.append(code.toChar()); i += 6; continue }218+                        }219+                        sb.append(n)220+                    }221+                    else -> sb.append(n)222+                }223+                i += 2224+            } else {225+                sb.append(c)226+                i++227+            }228+        }229+        return sb.toString()230+    }231+}

view file

app/src/main/java/com/peachpasswords/license/LicenseRepository.kt+5 −1
@@ -3,12 +3,16 @@33 import android.content.Context44 import androidx.security.crypto.EncryptedSharedPreferences55 import androidx.security.crypto.MasterKey6+import dagger.hilt.android.qualifiers.ApplicationContext67 import java.math.BigInteger78 import java.security.KeyFactory89 import java.security.Signature910 import java.security.spec.X509EncodedKeySpec11+import javax.inject.Inject12+import javax.inject.Singleton1013 11-class LicenseRepository(context: Context) {14+@Singleton15+class LicenseRepository @Inject constructor(@ApplicationContext context: Context) {1216     companion object {1317         private const val PUBLIC_KEY_HEX =1418             "c7dc52d2c484696cf8566dbe6cfe69025d114cb47f6cf53c25088ecfd539bdfa"

view file

app/src/main/java/com/peachpasswords/ui/settings/ProCelebration.kt+110 −0
@@ -0,0 +1,110 @@1+package com.peachpasswords.ui.settings2+3+import androidx.compose.animation.core.LinearEasing4+import androidx.compose.animation.core.animateFloat5+import androidx.compose.animation.core.rememberInfiniteTransition6+import androidx.compose.animation.core.infiniteRepeatable7+import androidx.compose.animation.core.tween8+import androidx.compose.foundation.background9+import androidx.compose.foundation.clickable10+import androidx.compose.foundation.layout.Box11+import androidx.compose.foundation.layout.Column12+import androidx.compose.foundation.layout.fillMaxSize13+import androidx.compose.foundation.layout.padding14+import androidx.compose.foundation.Canvas15+import androidx.compose.material3.Text16+import androidx.compose.runtime.Composable17+import androidx.compose.runtime.LaunchedEffect18+import androidx.compose.runtime.getValue19+import androidx.compose.ui.Alignment20+import androidx.compose.ui.Modifier21+import androidx.compose.ui.geometry.Offset22+import androidx.compose.ui.graphics.Color23+import androidx.compose.ui.text.TextStyle24+import androidx.compose.ui.text.font.FontStyle25+import androidx.compose.ui.text.style.TextAlign26+import androidx.compose.ui.unit.dp27+import androidx.compose.ui.unit.sp28+import com.peachpasswords.ui.components.PeachMark29+import com.peachpasswords.ui.theme.LocalPeachAccent30+import com.peachpasswords.ui.theme.LocalReduceMotion31+import com.peachpasswords.ui.theme.PeachColors32+import com.peachpasswords.ui.theme.PeachType33+import kotlinx.coroutines.delay34+import kotlin.math.cos35+import kotlin.math.sin36+37+/**38+ * Full-screen Pro activation celebration. Auto-dismisses after ~1800ms (calls [onDone]);39+ * a tap dismisses early. Accent bloom + PeachMark + a ring of staggered sparkle dots.40+ */41+@Composable42+fun ProCelebration(onDone: () -> Unit) {43+    val accent = LocalPeachAccent.current44+    val reduceMotion = LocalReduceMotion.current45+46+    LaunchedEffect(Unit) {47+        delay(1800)48+        onDone()49+    }50+51+    val phase by if (reduceMotion) {52+        rememberInfiniteTransition(label = "spark").animateFloat(53+            0f, 0f, infiniteRepeatable(tween(1)), label = "sparkStatic",54+        )55+    } else {56+        rememberInfiniteTransition(label = "spark").animateFloat(57+            initialValue = 0f, targetValue = 1f,58+            animationSpec = infiniteRepeatable(tween(1800, easing = LinearEasing)),59+            label = "sparkPhase",60+        )61+    }62+63+    Box(64+        modifier = Modifier65+            .fillMaxSize()66+            .background(PeachColors.Bg)67+            .clickable(onClick = onDone),68+        contentAlignment = Alignment.Center,69+    ) {70+        // Accent bloom (higher opacity than the shell).71+        Canvas(Modifier.fillMaxSize()) {72+            drawCircle(73+                color = accent.copy(alpha = 0.18f),74+                radius = size.minDimension * 0.55f,75+                center = Offset(size.width / 2f, size.height * 0.42f),76+            )77+            // 12 sparkle dots radiating from centre, staggered fade.78+            val cx = size.width / 2f79+            val cy = size.height * 0.42f80+            val ringR = size.minDimension * 0.34f81+            for (i in 0 until 12) {82+                val ang = (i / 12f) * 2f * Math.PI.toFloat()83+                val local = ((phase + i / 12f) % 1f)84+                val a = (1f - kotlin.math.abs(local - 0.5f) * 2f).coerceIn(0f, 1f)85+                drawCircle(86+                    color = accent.copy(alpha = 0.7f * a),87+                    radius = 4f,88+                    center = Offset(cx + cos(ang) * ringR, cy + sin(ang) * ringR),89+                )90+            }91+        }92+        Column(horizontalAlignment = Alignment.CenterHorizontally) {93+            PeachMark(size = 80.dp)94+            Text(95+                "peach pro",96+                color = accent,97+                style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 44.sp),98+                textAlign = TextAlign.Center,99+                modifier = Modifier.padding(top = 18.dp),100+            )101+            Text(102+                "thank you.",103+                color = PeachColors.T1,104+                style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp),105+                textAlign = TextAlign.Center,106+                modifier = Modifier.padding(top = 6.dp),107+            )108+        }109+    }110+}

view file

app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+82 −3
@@ -24,6 +24,7 @@2424 import androidx.compose.foundation.shape.RoundedCornerShape2525 import androidx.compose.foundation.text.BasicTextField2626 import androidx.compose.runtime.Composable27+import androidx.compose.runtime.collectAsState2728 import androidx.compose.runtime.getValue2829 import androidx.compose.runtime.mutableStateOf2930 import androidx.compose.runtime.remember@@ -73,7 +74,7 @@7374         CardId.Vault -> VaultBody(fg, vm, settings, entriesCount, onNavigate)7475         CardId.Sync -> SyncBody(fg, onNavigate)7576         CardId.Shortcuts -> ShortcutsBody(fg)76-        CardId.Pro -> ProBody(fg)77+        CardId.Pro -> ProBody(fg, vm)7778         CardId.Feedback -> FeedbackBody(fg)7879     }7980 }@@ -433,8 +434,13 @@433434 /* ────────────────────────────────  Pro  ─────────────────────────────────── */434435 435436 @Composable436-private fun ProBody(fg: Color) {437+private fun ProBody(fg: Color, vm: SettingsViewModel) {437438     val ctx = LocalContext.current439+    val isPro by vm.isPro.collectAsState()440+    if (isPro) {441+        ProActiveBody(fg, vm)442+        return443+    }438444     val features = listOf(439445         "Peach Sync" to "Encrypted · peer-to-peer",440446         "Peach Codex" to "Restore from paper",@@ -481,7 +487,80 @@481487             .padding(vertical = 12.dp),482488         contentAlignment = Alignment.Center,483489     ) { Text("Get Peach Pro", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }484-    Hint("Already have a key? License activation arrives with Pro sync in a later update.", fg)490+491+    Spacer(Modifier.height(16.dp))492+    Text("LICENSE KEY", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)493+    var key by remember { mutableStateOf("") }494+    val activating by vm.activating.collectAsState()495+    val activationError by vm.activationError.collectAsState()496+    Box(497+        Modifier.fillMaxWidth().padding(top = 6.dp)498+            .border(1.dp, fg.copy(alpha = 0.3f), RoundedCornerShape(8.dp))499+            .padding(horizontal = 12.dp, vertical = 10.dp),500+    ) {501+        BasicTextField(502+            value = key,503+            onValueChange = { key = it.uppercase(); vm.clearActivationError() },504+            singleLine = true,505+            textStyle = TextStyle(fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em, color = fg),506+            cursorBrush = SolidColor(fg),507+            modifier = Modifier.fillMaxWidth(),508+            decorationBox = { inner ->509+                if (key.isEmpty()) Text("PPK-XXXX-XXXX-XXXX", color = fg.copy(alpha = 0.3f), fontFamily = PeachType.Mono, fontSize = 13.sp, letterSpacing = 0.12.em)510+                inner()511+            },512+        )513+    }514+    if (activationError != null) {515+        Text(activationError!!, color = com.peachpasswords.ui.theme.PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(top = 6.dp))516+    }517+    Spacer(Modifier.height(8.dp))518+    Box(519+        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))520+            .background(fg.copy(alpha = if (activating || key.isBlank()) 0.08f else 0.16f))521+            .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))522+            .clickable(enabled = !activating && key.isNotBlank()) { vm.activateLicense(key) }523+            .padding(vertical = 12.dp),524+        contentAlignment = Alignment.Center,525+    ) { Text(if (activating) "Activating…" else "Activate", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }526+}527+528+@Composable529+private fun ProActiveBody(fg: Color, vm: SettingsViewModel) {530+    val features = listOf("Peach Sync", "Peach Codex", "Passkeys", "Advanced Vault Health", "Canary entries", "Duress vault")531+    Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {532+        com.peachpasswords.ui.components.PeachMark(size = 60.dp)533+    }534+    Text(535+        "Peach Pro",536+        modifier = Modifier.fillMaxWidth(),537+        color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp,538+        textAlign = androidx.compose.ui.text.style.TextAlign.Center,539+    )540+    Text(541+        "active · yours forever",542+        modifier = Modifier.fillMaxWidth().padding(top = 4.dp),543+        color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em,544+        textAlign = androidx.compose.ui.text.style.TextAlign.Center,545+    )546+    Spacer(Modifier.height(12.dp))547+    features.forEachIndexed { i, name ->548+        RowLine(fg) {549+            Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {550+                Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))551+                Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)552+            }553+            Text("unlocked", color = com.peachpasswords.ui.theme.PeachColors.HealthOk, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)554+        }555+    }556+    Spacer(Modifier.height(12.dp))557+    Box(558+        Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))559+            .border(1.dp, com.peachpasswords.ui.theme.PeachColors.Breach.copy(alpha = 0.4f), RoundedCornerShape(10.dp))560+            .clickable { vm.deactivate() }561+            .padding(vertical = 12.dp),562+        contentAlignment = Alignment.Center,563+    ) { Text("Deactivate", color = com.peachpasswords.ui.theme.PeachColors.Breach, fontFamily = PeachType.Mono, fontSize = 12.sp) }485564 }486565 487566 /* ──────────────────────────────  Feedback  ───────────────────────────────── */

view file

app/src/main/java/com/peachpasswords/ui/settings/SettingsScreen.kt+7 −2
@@ -82,6 +82,8 @@8282 ) {8383     val entries by vm.entries.collectAsState()8484     val settings by vm.settings.collectAsState()85+    val isPro by vm.isPro.collectAsState()86+    val showCelebration by vm.showCelebration.collectAsState()8587     val reduceMotion = LocalReduceMotion.current8688     val scope = rememberCoroutineScope()8789 @@ -213,8 +215,8 @@213215                         active = isActive,214216                         focused = isActive && !deckOpen,215217                         lede = vm.lede(card.id, entries.count { it.deletedAt == null }, settings),216-                        showSparkle = card.id == CardId.Pro && vm.isPro,217-                        onIconClick = if (card.id == CardId.Pro && vm.isPro) ({ celebrate() }) else null,218+                        showSparkle = card.id == CardId.Pro && isPro,219+                        onIconClick = if (card.id == CardId.Pro && isPro) ({ celebrate() }) else null,218220                         body = {219221                             CardBody(220222                                 id = card.id,@@ -247,6 +249,9 @@247249                     )248250                 }249251             }252+        }253+        if (showCelebration) {254+            ProCelebration(onDone = { vm.dismissCelebration(); celebrate() })250255         }251256     }252257 }

view file

app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+53 −4
@@ -2,23 +2,72 @@22 33 import androidx.lifecycle.ViewModel44 import androidx.lifecycle.viewModelScope5+import com.peachpasswords.license.LicenseRepository56 import com.peachpasswords.vault.VaultRepository67 import com.peachpasswords.vault.VaultSettings78 import dagger.hilt.android.lifecycle.HiltViewModel9+import kotlinx.coroutines.flow.MutableStateFlow810 import kotlinx.coroutines.flow.StateFlow11+import kotlinx.coroutines.flow.asStateFlow912 import kotlinx.coroutines.launch1013 import javax.inject.Inject1114 1215 @HiltViewModel1316 class SettingsViewModel @Inject constructor(1417     private val vault: VaultRepository,18+    private val license: LicenseRepository,1519 ) : ViewModel() {1620     val entries: StateFlow<List<com.peachpasswords.vault.VaultEntry>> = vault.entries1721     val settings: StateFlow<VaultSettings> = vault.settings1822 19-    /** Pro entitlement is not wired until Phase 8 sync/license — Pro-gated for now. */20-    val isPro: Boolean = false23+    /** Live Pro entitlement, seeded from the stored (locally Ed25519-validated) license. */24+    private val _isPro = MutableStateFlow(license.isProActive())25+    val isPro: StateFlow<Boolean> = _isPro.asStateFlow()2126 27+    private val _activating = MutableStateFlow(false)28+    val activating: StateFlow<Boolean> = _activating.asStateFlow()29+30+    private val _activationError = MutableStateFlow<String?>(null)31+    val activationError: StateFlow<String?> = _activationError.asStateFlow()32+33+    /** Set true after a fresh activation so the screen can fire ProCelebration once. */34+    private val _showCelebration = MutableStateFlow(false)35+    val showCelebration: StateFlow<Boolean> = _showCelebration.asStateFlow()36+37+    /**38+     * Validate a license key locally (offline Ed25519 — there is no activation server)39+     * and, on success, persist it and flip Pro on. Surfaces only outcomes that can40+     * actually occur offline.41+     */42+    fun activateLicense(rawKey: String) {43+        if (_activating.value) return44+        _activating.value = true45+        _activationError.value = null46+        viewModelScope.launch {47+            val key = rawKey.trim()48+            if (license.validateLicense(key)) {49+                license.storeLicense(key)50+                _isPro.value = true51+                _showCelebration.value = true52+            } else {53+                _activationError.value = "Invalid license key"54+            }55+            _activating.value = false56+        }57+    }58+59+    fun clearActivationError() { _activationError.value = null }60+61+    fun dismissCelebration() {62+        license.markProCelebrated()63+        _showCelebration.value = false64+    }65+66+    fun deactivate() {67+        license.clearLicense()68+        _isPro.value = false69+    }70+2271     private fun mutate(block: (VaultSettings) -> VaultSettings) {2372         viewModelScope.launch { vault.updateSettings(block(vault.settings.value)) }2473     }@@ -37,12 +86,12 @@3786 3887     /** One-line summary shown under each card title; mirrors the browser ledes. */3988     fun lede(id: CardId, entriesCount: Int, s: VaultSettings): String = when (id) {40-        CardId.Pro -> if (isPro) "active · paid once, yours forever" else "$39 once · yours forever"89+        CardId.Pro -> if (_isPro.value) "active · paid once, yours forever" else "$39 once · yours forever"4190         CardId.Protection ->4291             "${if (s.breachMonitoring) "breaches watched" else "breach watch off"} · manual lock"4392         CardId.Vault ->4493             "$entriesCount ${if (entriesCount == 1) "entry" else "entries"} · backups, history, cleanup"45-        CardId.Sync -> if (isPro) "pair by chirp, keep in step" else "Pro · encrypted device pairing"94+        CardId.Sync -> if (_isPro.value) "pair by chirp, keep in step" else "Pro · encrypted device pairing"4695         CardId.Appearance -> "${s.theme} · ${s.accentColor} · ${s.textSize}"4796         CardId.Shortcuts -> "bindings · what your fingers know"4897         CardId.Feedback -> "tell us what would make it better"

view file