ba886da3b279
feat: B2 ImportScreen — choose view, PeachScript paste (plaintext + Argon2id/AES-GCM decrypt, documented .peach format for C2 to mirror) + file import w/ provider detection (Bitwarden CSV/JSON, 1Password, Chrome/Edge, Safari, generic CSV; RFC-4180 parser), preview + merge/replace (soft-delete), success/error states; 7 parser unit tests; wired nav (v2.1.25)
- time
- 2026-06-09 02:35 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- peach gap implementation
- parent
- a324fae09c49
↓ peach-android-ba886da3.tar.gzatlas at this save
files changed9 files
app/build.gradle+2 −2app/drafts/CsvImport.kt+0 −414app/drafts/ImportScreen.kt+0 −668app/drafts/PeachScriptImport.kt+0 −231app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+2 −1app/src/main/java/com/peachpasswords/ui/vault/CsvImport.kt+414 −0app/src/main/java/com/peachpasswords/ui/vault/ImportScreen.kt+668 −0app/src/main/java/com/peachpasswords/ui/vault/PeachScriptImport.kt+231 −0app/src/test/java/com/peachpasswords/ui/vault/ImportParsersTest.kt+62 −0app/build.gradle+2 −2
@@ -16,8 +16,8 @@1616 applicationId "com.peachpasswords"1717 minSdk 261818 targetSdk 3519- versionCode 20102420- versionName "2.1.24"19+ versionCode 20102520+ versionName "2.1.25"2121 2222 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"2323 vectorDrawables {app/drafts/CsvImport.kt+0 −414
@@ -1,414 +0,0 @@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-}app/drafts/ImportScreen.kt+0 −668
@@ -1,668 +0,0 @@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-}app/drafts/PeachScriptImport.kt+0 −231
@@ -1,231 +0,0 @@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-}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.ImportScreen2627 import com.peachpasswords.ui.vault.RecoveryWordsScreen2728 import com.peachpasswords.ui.vault.TrashScreen2829 import com.peachpasswords.ui.vault.VaultListScreen@@ -102,7 +103,7 @@102103 VaultHealthScreen(onBack = back, onEditEntry = { nav(PeachNav.EntryEdit(it)) })103104 }104105 composable(PeachNav.Trash.route) { TrashScreen(onBack = back) }105- composable(PeachNav.Import.route) { SimpleStub("Import", back) }106+ composable(PeachNav.Import.route) { ImportScreen(onBack = back) }106107 composable(PeachNav.Export.route) { SimpleStub("Export", back) }107108 composable(PeachNav.Panic.route) {108109 PanicScreen(app/src/main/java/com/peachpasswords/ui/vault/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+}app/src/main/java/com/peachpasswords/ui/vault/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+}app/src/main/java/com/peachpasswords/ui/vault/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+}app/src/test/java/com/peachpasswords/ui/vault/ImportParsersTest.kt+62 −0
@@ -0,0 +1,62 @@1+package com.peachpasswords.ui.vault2+3+import org.junit.Assert.assertEquals4+import org.junit.Assert.assertFalse5+import org.junit.Assert.assertNull6+import org.junit.Assert.assertTrue7+import org.junit.Test8+9+class ImportParsersTest {10+11+ @Test fun detect_blank_is_null() {12+ assertNull(CsvImport.detectProvider(""))13+ assertNull(CsvImport.detectProvider(" \n "))14+ }15+16+ @Test fun chrome_csv_detects_and_parses() {17+ val csv = "name,url,username,password\nGitHub,https://github.com,june,hunter2\n"18+ assertEquals(CsvImport.CHROME_CSV, CsvImport.detectProvider(csv))19+ val rows = CsvImport.parse(csv, CsvImport.CHROME_CSV)20+ assertEquals(1, rows.size)21+ assertEquals("GitHub", rows[0].title)22+ assertEquals("https://github.com", rows[0].url)23+ assertEquals("june", rows[0].username)24+ assertEquals("hunter2", rows[0].password)25+ }26+27+ @Test fun csv_quoted_fields_with_commas_are_preserved() {28+ val rows = CsvImport.parseCsv("name,url,username,password\n\"Bank, NA\",https://b.com,j,\"p,w\"\n")29+ // Header + 1 data row.30+ assertEquals(2, rows.size)31+ assertEquals(listOf("Bank, NA", "https://b.com", "j", "p,w"), rows[1])32+ }33+34+ @Test fun csv_doubled_quotes_unescape() {35+ assertEquals(listOf("a\"b", "c"), CsvImport.splitCsvLine("\"a\"\"b\",c"))36+ }37+38+ @Test fun detect_and_parse_returns_success_for_chrome() {39+ val csv = "name,url,username,password\nA,https://a.com,u,p\nB,https://b.com,u2,p2\n"40+ val r = CsvImport.detectAndParse(csv)41+ assertTrue(r is ImportParseResult.Success)42+ r as ImportParseResult.Success43+ assertEquals(2, r.entries.size)44+ }45+46+ @Test fun peachscript_plaintext_round_trips() {47+ val json = """{"peachscript":1,"encrypted":false,"entries":[""" +48+ """{"title":"GH","username":"u","password":"p","url":"x","notes":"n","totp":"t"}]}"""49+ assertTrue(PeachScriptImport.looksLikePeachScript(json))50+ assertFalse(PeachScriptImport.isEncrypted(json))51+ val entries = PeachScriptImport.parsePlaintext(json)52+ assertEquals(1, entries.size)53+ assertEquals("GH", entries[0].title)54+ assertEquals("u", entries[0].username)55+ assertEquals("t", entries[0].totp)56+ }57+58+ @Test fun peachscript_detects_encrypted_flag() {59+ assertTrue(PeachScriptImport.isEncrypted("""{"peachscript":1,"encrypted":true,"salt":"x","blob":"y"}"""))60+ assertFalse(PeachScriptImport.looksLikePeachScript("just text"))61+ }62+}