1package com.peachpasswords.ui.vault23456789101112131415161718192021data 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)293031sealed interface ImportParseResult {32 data class Success(val provider: String, val entries: List<ParsedEntry>) : ImportParseResult33 data class Failure(val reason: Reason) : ImportParseResult3435 enum class Reason { UNRECOGNISED, CORRUPTED, NO_ENTRIES }36}3738object CsvImport {3940 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"4849 50515253 fun detectProvider(content: String): String? {54 val trimmed = content.trim()55 if (trimmed.isEmpty()) return null5657 58 59 if (trimmed.startsWith("{") && Regex("\"items\"\\s*:\\s*\\[").containsMatchIn(trimmed)) {60 return BITWARDEN_JSON61 }62 63 if (trimmed.startsWith("{") || trimmed.startsWith("[")) return null6465 val header = firstNonBlankLine(trimmed) ?: return null66 val cols = splitCsvLine(header).map { it.trim().lowercase() }67 val set = cols.toSet()6869 return when {70 set.containsAll(listOf("name", "login_uri", "login_username", "login_password")) -> BITWARDEN_CSV71 72 73 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 79 (set.contains("name") || set.contains("title")) &&80 set.any { it.contains("password") } -> GENERIC_CSV81 else -> null82 }83 }8485 868788899091 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 }99100 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 }111112 113114 115116117118119 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 )127128 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 )136137 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 )145146 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 )154155 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 )163164 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 )172173 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 } ?: -1180181 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)187188 fun cell(row: List<String>, idx: Int): String? =189 if (idx in row.indices) row[idx].trim().ifEmpty { null } else null190191 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 }207208 209210 211212213214215 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 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 }234235 private fun extractItemsArray(content: String): String? {236 val key = Regex("\"items\"\\s*:\\s*\\[").find(content) ?: return null237 val start = key.range.last 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 }259260 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 }285286 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 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 }311312 private fun extractFirstUri(loginBlock: String): String? {313 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 }321322 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 }327328 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 }332333 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 }363364 365366 367368369370371 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.length378379 fun endField() { row.add(field.toString()); field = StringBuilder() }380 fun endRow() { endField(); rows.add(row); row = mutableListOf() }381382 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' -> { }395 '\n' -> endRow()396 else -> field.append(c)397 }398 }399 i++400 }401 402 403 if (field.isNotEmpty() || row.isNotEmpty()) endRow()404 405 return rows.filterNot { it.size == 1 && it[0].isEmpty() }406 }407408 409 fun splitCsvLine(line: String): List<String> =410 parseCsv(line).firstOrNull() ?: emptyList()411412 private fun firstNonBlankLine(s: String): String? =413 s.lineSequence().firstOrNull { it.isNotBlank() }414}