package com.peachpasswords.ui.vault /** * Pure-Kotlin CSV / JSON import parsing for the Import screen (spec B2). * * No Android or Compose dependencies — everything here is deterministic and * unit-testable. The UI layer ([ImportScreen]) calls [detectProvider] then * [parse]; the parsed rows are mapped to VaultEntry drafts at the call site. * * Supported providers (detected from header / content shape): * - "Bitwarden CSV" (folder,favorite,type,name,login_uri,login_username,login_password,login_totp,notes) * - "Bitwarden JSON" ({"items":[...]}) * - "1Password CSV" (Title,Url,Username,Password,... — 1Password v8 export) * - "Chrome CSV" (name,url,username,password) * - "Edge CSV" (same columns as Chrome — Chromium family) * - "Safari CSV" (Title,URL,Username,Password,Notes,OTPAuth) * - "CSV" (generic fallback: best-effort column matching) */ /** One parsed credential, provider-agnostic. Null/blank fields are omitted later. */ data class ParsedEntry( val title: String, val username: String? = null, val password: String? = null, val url: String? = null, val notes: String? = null, val totp: String? = null, ) /** Result of an import attempt: the detected provider label plus parsed rows. */ sealed interface ImportParseResult { data class Success(val provider: String, val entries: List) : ImportParseResult data class Failure(val reason: Reason) : ImportParseResult enum class Reason { UNRECOGNISED, CORRUPTED, NO_ENTRIES } } object CsvImport { // Display labels used both for detection return values and "Detected: X export". const val BITWARDEN_CSV = "Bitwarden CSV" const val BITWARDEN_JSON = "Bitwarden JSON" const val ONEPASSWORD_CSV = "1Password CSV" const val CHROME_CSV = "Chrome CSV" const val EDGE_CSV = "Edge CSV" const val SAFARI_CSV = "Safari CSV" const val GENERIC_CSV = "CSV" /** * Sniff the provider from raw file content. Returns a provider label or null * when the content is neither recognisable JSON nor a parseable CSV header. */ fun detectProvider(content: String): String? { val trimmed = content.trim() if (trimmed.isEmpty()) return null // Bitwarden JSON: an object carrying an "items" array. Cheap shape check // rather than a full parse — the parser does the real decode. if (trimmed.startsWith("{") && Regex("\"items\"\\s*:\\s*\\[").containsMatchIn(trimmed)) { return BITWARDEN_JSON } // Any other top-level JSON we don't understand is not a CSV. if (trimmed.startsWith("{") || trimmed.startsWith("[")) return null val header = firstNonBlankLine(trimmed) ?: return null val cols = splitCsvLine(header).map { it.trim().lowercase() } val set = cols.toSet() return when { set.containsAll(listOf("name", "login_uri", "login_username", "login_password")) -> BITWARDEN_CSV // Chrome and Edge share the exact Chromium export header. They are // indistinguishable from content alone; default to Chrome, the UI // copy says "Chrome/Edge export" so the label is honest. cols == listOf("name", "url", "username", "password") -> CHROME_CSV set.containsAll(listOf("title", "url", "username", "password")) && (set.contains("otpauth") || set.contains("notes")) -> SAFARI_CSV set.containsAll(listOf("title", "url", "username", "password")) -> ONEPASSWORD_CSV // Generic: any header with at least a name/title and a password column. (set.contains("name") || set.contains("title")) && set.any { it.contains("password") } -> GENERIC_CSV else -> null } } /** * Parse [content] as the given [provider]. Provider should come from * [detectProvider]; passing an unknown label falls back to generic CSV. * Throws nothing — malformed content yields an empty list, which the UI * surfaces as the "No entries found" error. */ fun parse(content: String, provider: String): List = when (provider) { BITWARDEN_JSON -> parseBitwardenJson(content) BITWARDEN_CSV -> parseCsvByHeader(content, BitwardenCsvMap) CHROME_CSV, EDGE_CSV -> parseCsvByHeader(content, ChromeCsvMap) SAFARI_CSV -> parseCsvByHeader(content, SafariCsvMap) ONEPASSWORD_CSV -> parseCsvByHeader(content, OnePasswordCsvMap) else -> parseCsvByHeader(content, GenericCsvMap) } /** Convenience: detect + parse in one call, returning a sealed result. */ fun detectAndParse(content: String): ImportParseResult { val provider = detectProvider(content) ?: return ImportParseResult.Failure(ImportParseResult.Reason.UNRECOGNISED) val entries = parse(content, provider) return if (entries.isEmpty()) { ImportParseResult.Failure(ImportParseResult.Reason.NO_ENTRIES) } else { ImportParseResult.Success(provider, entries) } } // ---- CSV column maps -------------------------------------------------- /** * Maps lower-cased CSV header names to the [ParsedEntry] field they feed. * Each list is tried in order; the first present column wins. This lets one * generic row-builder serve every CSV provider. */ private class CsvColumnMap( val title: List, val username: List, val password: List, val url: List, val notes: List, val totp: List, ) private val BitwardenCsvMap = CsvColumnMap( title = listOf("name"), username = listOf("login_username"), password = listOf("login_password"), url = listOf("login_uri"), notes = listOf("notes"), totp = listOf("login_totp"), ) private val ChromeCsvMap = CsvColumnMap( title = listOf("name"), username = listOf("username"), password = listOf("password"), url = listOf("url"), notes = listOf("note", "notes"), totp = emptyList(), ) private val SafariCsvMap = CsvColumnMap( title = listOf("title"), username = listOf("username"), password = listOf("password"), url = listOf("url"), notes = listOf("notes"), totp = listOf("otpauth"), ) private val OnePasswordCsvMap = CsvColumnMap( title = listOf("title"), username = listOf("username"), password = listOf("password"), url = listOf("url", "website"), notes = listOf("notes"), totp = listOf("otpauth", "one-time password", "totp"), ) private val GenericCsvMap = CsvColumnMap( title = listOf("name", "title"), username = listOf("username", "user", "login", "email"), password = listOf("password", "login_password", "pass"), url = listOf("url", "login_uri", "website", "uri"), notes = listOf("notes", "note"), totp = listOf("totp", "login_totp", "otpauth"), ) private fun parseCsvByHeader(content: String, map: CsvColumnMap): List { val rows = parseCsv(content) if (rows.size < 2) return emptyList() val header = rows.first().map { it.trim().lowercase() } fun col(names: List): Int = names.firstNotNullOfOrNull { n -> header.indexOf(n).takeIf { it >= 0 } } ?: -1 val ti = col(map.title) val ui = col(map.username) val pi = col(map.password) val urli = col(map.url) val ni = col(map.notes) val toi = col(map.totp) fun cell(row: List, idx: Int): String? = if (idx in row.indices) row[idx].trim().ifEmpty { null } else null return rows.drop(1).mapNotNull { row -> if (row.all { it.isBlank() }) return@mapNotNull null val title = cell(row, ti) ?: cell(row, urli) ?: cell(row, ui) ?: return@mapNotNull null ParsedEntry( title = title, username = cell(row, ui), password = cell(row, pi), url = cell(row, urli), notes = cell(row, ni), totp = cell(row, toi), ) } } // ---- Bitwarden JSON --------------------------------------------------- /** * Minimal extractor for Bitwarden's unencrypted JSON export. Avoids pulling * a JSON dependency into this pure module by walking the `items` array with a * tolerant brace-aware scanner; only login items (type 1) are imported. */ private fun parseBitwardenJson(content: String): List { val itemsArray = extractItemsArray(content) ?: return emptyList() val objects = splitTopLevelObjects(itemsArray) return objects.mapNotNull { obj -> val type = jsonNumber(obj, "type") // Bitwarden type 1 == login. Skip cards/notes/identities for now. if (type != null && type != 1) return@mapNotNull null val name = jsonString(obj, "name") ?: return@mapNotNull null val loginBlock = extractObject(obj, "login") ?: "" ParsedEntry( title = name, username = jsonString(loginBlock, "username"), password = jsonString(loginBlock, "password"), url = extractFirstUri(loginBlock), notes = jsonString(obj, "notes"), totp = jsonString(loginBlock, "totp"), ) } } private fun extractItemsArray(content: String): String? { val key = Regex("\"items\"\\s*:\\s*\\[").find(content) ?: return null val start = key.range.last // index of '[' var depth = 0 var i = start var inStr = false var esc = false while (i < content.length) { val c = content[i] if (inStr) { when { esc -> esc = false c == '\\' -> esc = true c == '"' -> inStr = false } } else when (c) { '"' -> inStr = true '[' -> depth++ ']' -> { depth--; if (depth == 0) return content.substring(start + 1, i) } } i++ } return null } /** Split a JSON array body into its top-level `{...}` object substrings. */ private fun splitTopLevelObjects(arrayBody: String): List { val out = mutableListOf() var depth = 0 var startIdx = -1 var inStr = false var esc = false for (i in arrayBody.indices) { val c = arrayBody[i] if (inStr) { when { esc -> esc = false c == '\\' -> esc = true c == '"' -> inStr = false } continue } when (c) { '"' -> inStr = true '{' -> { if (depth == 0) startIdx = i; depth++ } '}' -> { depth--; if (depth == 0 && startIdx >= 0) { out.add(arrayBody.substring(startIdx, i + 1)); startIdx = -1 } } } } return out } /** Extract the substring of a nested object value for [key], braces balanced. */ private fun extractObject(obj: String, key: String): String? { val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*\\{").find(obj) ?: return null var depth = 0 var inStr = false var esc = false var i = m.range.last // index of '{' val start = i while (i < obj.length) { val c = obj[i] if (inStr) { when { esc -> esc = false c == '\\' -> esc = true c == '"' -> inStr = false } } else when (c) { '"' -> inStr = true '{' -> depth++ '}' -> { depth--; if (depth == 0) return obj.substring(start, i + 1) } } i++ } return null } private fun extractFirstUri(loginBlock: String): String? { // login.uris is [{ "match": null, "uri": "https://..." }, ...] val uriInArray = Regex("\"uris\"\\s*:\\s*\\[(.*?)]", RegexOption.DOT_MATCHES_ALL) .find(loginBlock)?.groupValues?.get(1) if (uriInArray != null) { jsonString(uriInArray, "uri")?.let { return it } } return jsonString(loginBlock, "uri") } private fun jsonString(scope: String, key: String): String? { val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"").find(scope) ?: return null return unescapeJson(m.groupValues[1]).ifEmpty { null } } private fun jsonNumber(scope: String, key: String): Int? { val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*(-?\\d+)").find(scope) ?: return null return m.groupValues[1].toIntOrNull() } private fun unescapeJson(s: String): String { val sb = StringBuilder(s.length) var i = 0 while (i < s.length) { val c = s[i] if (c == '\\' && i + 1 < s.length) { when (val n = s[i + 1]) { 'n' -> sb.append('\n') 't' -> sb.append('\t') 'r' -> sb.append('\r') '"' -> sb.append('"') '\\' -> sb.append('\\') '/' -> sb.append('/') 'u' -> { if (i + 5 < s.length) { val code = s.substring(i + 2, i + 6).toIntOrNull(16) if (code != null) { sb.append(code.toChar()); i += 6; continue } } sb.append(n) } else -> sb.append(n) } i += 2 } else { sb.append(c) i++ } } return sb.toString() } // ---- RFC-4180-ish CSV -------------------------------------------------- /** * Parse a whole CSV document into rows of fields. Handles quoted fields, * embedded commas, doubled quotes ("" -> "), and newlines inside quotes * (CRLF or LF). Trailing blank line is ignored. */ fun parseCsv(content: String): List> { val rows = mutableListOf>() var field = StringBuilder() var row = mutableListOf() var inQuotes = false var i = 0 val n = content.length fun endField() { row.add(field.toString()); field = StringBuilder() } fun endRow() { endField(); rows.add(row); row = mutableListOf() } while (i < n) { val c = content[i] if (inQuotes) { when { c == '"' && i + 1 < n && content[i + 1] == '"' -> { field.append('"'); i++ } c == '"' -> inQuotes = false else -> field.append(c) } } else { when (c) { '"' -> inQuotes = true ',' -> endField() '\r' -> { /* swallow; \n handles row end */ } '\n' -> endRow() else -> field.append(c) } } i++ } // Flush trailing field/row if the file does not end with a newline, or if // any content accumulated after the last newline. if (field.isNotEmpty() || row.isNotEmpty()) endRow() // Drop a final fully-empty row produced by a trailing newline. return rows.filterNot { it.size == 1 && it[0].isEmpty() } } /** Split a single CSV line into fields (used only for header sniffing). */ fun splitCsvLine(line: String): List = parseCsv(line).firstOrNull() ?: emptyList() private fun firstNonBlankLine(s: String): String? = s.lineSequence().firstOrNull { it.isNotBlank() } }