PeachScriptImport.kt

8.9 KB · raw

1package com.peachpasswords.ui.vault23import com.peachpasswords.vault.VaultCrypto4import java.util.Base6456/**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 */39object PeachScriptImport {4041    /** Magic marker key any PeachScript JSON object must carry. */42    private const val MARKER = "\"peachscript\""4344    /**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"5051    /**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    }5960    /** True when the payload declares itself encrypted (`"encrypted": true`). */61    fun isEncrypted(text: String): Boolean =62        Regex("\"encrypted\"\\s*:\\s*true").containsMatchIn(text)6364    /**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    }8485    /** 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    }9192    /**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.Corrupted111112        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        }119120        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        }130131        val json = String(plaintext, Charsets.UTF_8)132        val entries = parsePlaintext(json)133        return if (entries.isEmpty()) DecryptResult.Corrupted else DecryptResult.Success(entries)134    }135136    // ---- Minimal JSON helpers (shared shape with CsvImport) ----------------137138    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    }162163    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    }187188    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    }193194    /** 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    }200201    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}