package com.peachpasswords.ui.vault import com.peachpasswords.vault.VaultCrypto import java.util.Base64 /** * Pure-Kotlin parsing for PeachScript exports (spec B2 PeachScript sub-view). * * PEACHSCRIPT FORMAT (chosen here — C2 export MUST mirror this): * * A PeachScript export is a single JSON object with a magic marker so it can be * sniffed without a full parse: * * Plaintext: * { * "peachscript": 1, // magic marker + format version * "encrypted": false, * "entries": [ { "title": "...", "username": "...", "password": "...", * "url": "...", "notes": "...", "totp": "..." }, ... ] * } * * Encrypted (backup-password protected): * { * "peachscript": 1, * "encrypted": true, * "kdf": "argon2id", * "salt": "", // VaultCrypto.SALT_SIZE * "blob": "" * } * * The encrypted "blob" is exactly what [VaultCrypto.encrypt]/[VaultCrypto.decrypt] * produce/consume: nonce (NONCE_SIZE=12) prepended to ciphertext+tag. The * decrypted plaintext is the UTF-8 bytes of the plaintext-shape JSON object * above (with "encrypted": false). The AAD for the GCM envelope is defined below * as [PEACHSCRIPT_AAD]; C2 export must use the same AAD string. * * No Compose / Android UI here — unit-testable pure functions. */ object PeachScriptImport { /** Magic marker key any PeachScript JSON object must carry. */ private const val MARKER = "\"peachscript\"" /** * AAD for the encrypted-export GCM envelope. Distinct from the vault's * internal AADs (slot_a_v1 etc.) so a backup blob can never be confused with * an at-rest vault slot. C2 export must encrypt with this exact string. */ const val PEACHSCRIPT_AAD = "peachscript_export_v1" /** * Magic-header check: does this text look like a PeachScript export at all? * Cheap sniff (object start + marker key) — does not validate the payload. */ fun looksLikePeachScript(text: String): Boolean { val t = text.trim() return t.startsWith("{") && t.contains(MARKER) } /** True when the payload declares itself encrypted (`"encrypted": true`). */ fun isEncrypted(text: String): Boolean = Regex("\"encrypted\"\\s*:\\s*true").containsMatchIn(text) /** * Parse an unencrypted PeachScript export's entry array. Returns an empty * list when the marker is absent or no entries are present; the UI maps that * to the "No entries found" / "unrecognised" errors. */ fun parsePlaintext(text: String): List { if (!looksLikePeachScript(text)) return emptyList() val entriesBody = extractArrayBody(text, "entries") ?: return emptyList() return splitTopLevelObjects(entriesBody).mapNotNull { obj -> val title = jsonString(obj, "title") ?: jsonString(obj, "name") ?: return@mapNotNull null ParsedEntry( title = title, username = jsonString(obj, "username"), password = jsonString(obj, "password"), url = jsonString(obj, "url"), notes = jsonString(obj, "notes"), totp = jsonString(obj, "totp"), ) } } /** Outcome of decrypting + parsing an encrypted export. */ sealed interface DecryptResult { data class Success(val entries: List) : DecryptResult data object WrongPassword : DecryptResult data object Corrupted : DecryptResult } /** * Decrypt an encrypted PeachScript export with the user's backup password, * then parse the inner plaintext entries. * * IMPLEMENTED against the exact VaultCrypto API found in the source: * - KDF: VaultCrypto.deriveKey(password, salt) (Argon2id, * MEMORY=65536KB, ITER=3, PARALLELISM=4, 32-byte key) * - decrypt: VaultCrypto.decrypt(data, key, aad) (AES-256-GCM, expects * NONCE_SIZE=12 prepended; AAD = [PEACHSCRIPT_AAD]) * - zero: VaultCrypto.zero(key) * * The on-the-wire shape (salt + nonce||ct||tag base64) is fully specified in * the file header, so this path is implemented end to end. C2 export must * produce a blob with the matching AAD/nonce layout or decryption will fail * the GCM tag check and surface as [DecryptResult.WrongPassword]. */ fun decryptAndParse(text: String, backupPassword: String): DecryptResult { val saltB64 = jsonRawString(text, "salt") ?: return DecryptResult.Corrupted val blobB64 = jsonRawString(text, "blob") ?: return DecryptResult.Corrupted val salt = runCatching { Base64.getDecoder().decode(saltB64) }.getOrNull() ?: return DecryptResult.Corrupted val blob = runCatching { Base64.getDecoder().decode(blobB64) }.getOrNull() ?: return DecryptResult.Corrupted if (salt.size != VaultCrypto.SALT_SIZE || blob.size <= VaultCrypto.NONCE_SIZE) { return DecryptResult.Corrupted } val key = VaultCrypto.deriveKey(backupPassword, salt) val plaintext = try { VaultCrypto.decrypt(blob, key, PEACHSCRIPT_AAD) } catch (_: Exception) { // GCM tag mismatch ⇒ wrong password (or tampered blob). Spec treats // this as "Incorrect backup password." return DecryptResult.WrongPassword } finally { VaultCrypto.zero(key) } val json = String(plaintext, Charsets.UTF_8) val entries = parsePlaintext(json) return if (entries.isEmpty()) DecryptResult.Corrupted else DecryptResult.Success(entries) } // ---- Minimal JSON helpers (shared shape with CsvImport) ---------------- private fun extractArrayBody(scope: String, key: String): String? { val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*\\[").find(scope) ?: return null val start = m.range.last // index of '[' var depth = 0 var inStr = false var esc = false var i = start while (i < scope.length) { val c = scope[i] if (inStr) { when { esc -> esc = false c == '\\' -> esc = true c == '"' -> inStr = false } } else when (c) { '"' -> inStr = true '[' -> depth++ ']' -> { depth--; if (depth == 0) return scope.substring(start + 1, i) } } i++ } return null } 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 } 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 } } /** Like [jsonString] but keeps an empty string (used for base64 fields). */ private fun jsonRawString(scope: String, key: String): String? { val m = Regex("\"${Regex.escape(key)}\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"").find(scope) ?: return null return unescapeJson(m.groupValues[1]) } 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() } }