PeachScriptExport.kt

5.3 KB · raw

1package com.peachpasswords.ui.vault23import com.peachpasswords.vault.VaultCrypto4import com.peachpasswords.vault.VaultEntry5import java.util.Base6467/**8 * Pure-Kotlin serialisation for PeachScript exports (spec C2 PeachScript sub-view).9 *10 * This is the WRITE side of the format that [PeachScriptImport] reads. The shapes11 * below are pinned by B2 (see `B2-INTEGRATION.md`) and MUST round-trip:12 *13 *   PeachScriptImport.decryptAndParse(buildEncrypted(es, pw), pw)14 *       == DecryptResult.Success(es-as-ParsedEntry)15 *16 *   Plaintext:17 *     {18 *       "peachscript": 1,19 *       "encrypted": false,20 *       "entries": [ { "title", "username", "password", "url", "notes", "totp" }, ... ]21 *     }22 *23 *   Encrypted (backup-password protected):24 *     {25 *       "peachscript": 1,26 *       "encrypted": true,27 *       "kdf": "argon2id",28 *       "salt": "<base64 16 bytes = VaultCrypto.SALT_SIZE>",29 *       "blob": "<base64: 12-byte nonce || AES-256-GCM ciphertext||tag>"30 *     }31 *32 * The "blob" is exactly VaultCrypto.encrypt(plaintextJsonBytes, key, AAD) output33 * (nonce prepended). AAD is the constant [PeachScriptImport.PEACHSCRIPT_AAD]34 * ("peachscript_export_v1") — using any other AAD makes the importer's GCM tag35 * check fail and the user sees "Incorrect backup password."36 *37 * No Compose / Android UI here — unit-testable pure functions.38 */39object PeachScriptExport {4041    /** Format version marker emitted as `"peachscript": 1`. */42    private const val FORMAT_VERSION = 14344    // Standard (not URL-safe) base64, matching the decoder in PeachScriptImport.45    private val b64 = Base64.getEncoder()4647    /**48     * Serialise [entries] to the plaintext-shape PeachScript JSON. This is the49     * exact byte sequence that gets encrypted for [buildEncrypted] (with50     * "encrypted": false), so the importer reconstructs the same entries.51     *52     * Emits the importer's recognised keys (title/username/password/url/notes/totp).53     * `email` is folded into `username` only when `username` is absent, since the54     * PeachScript schema has no `email` field and the importer only reads these six.55     */56    fun buildPlaintext(entries: List<VaultEntry>): String {57        val sb = StringBuilder(256 + entries.size * 96)58        sb.append('{')59        sb.append("\"peachscript\":").append(FORMAT_VERSION).append(',')60        sb.append("\"encrypted\":false,")61        sb.append("\"entries\":[")62        entries.forEachIndexed { i, e ->63            if (i > 0) sb.append(',')64            appendEntry(sb, e)65        }66        sb.append("]}")67        return sb.toString()68    }6970    /**71     * Build the encrypted-shape PeachScript JSON: generate a 16-byte salt, derive72     * an Argon2id key from [backupPassword], AES-256-GCM encrypt the plaintext73     * JSON with AAD [PeachScriptImport.PEACHSCRIPT_AAD], then base64 the salt and74     * the nonce||ciphertext||tag blob. The derived key is zeroed after use.75     */76    fun buildEncrypted(entries: List<VaultEntry>, backupPassword: String): String {77        val plaintext = buildPlaintext(entries).toByteArray(Charsets.UTF_8)78        val salt = VaultCrypto.generateSalt()79        val key = VaultCrypto.deriveKey(backupPassword, salt)80        val blob = try {81            VaultCrypto.encrypt(plaintext, key, PeachScriptImport.PEACHSCRIPT_AAD)82        } finally {83            VaultCrypto.zero(key)84        }8586        val saltB64 = b64.encodeToString(salt)87        val blobB64 = b64.encodeToString(blob)8889        val sb = StringBuilder(saltB64.length + blobB64.length + 96)90        sb.append('{')91        sb.append("\"peachscript\":").append(FORMAT_VERSION).append(',')92        sb.append("\"encrypted\":true,")93        sb.append("\"kdf\":\"argon2id\",")94        sb.append("\"salt\":\"").append(saltB64).append("\",")95        sb.append("\"blob\":\"").append(blobB64).append('"')96        sb.append('}')97        return sb.toString()98    }99100    private fun appendEntry(sb: StringBuilder, e: VaultEntry) {101        sb.append('{')102        appendField(sb, "title", e.title, first = true)103        appendField(sb, "username", e.username ?: e.email)104        appendField(sb, "password", e.password)105        appendField(sb, "url", e.url)106        appendField(sb, "notes", e.notes)107        appendField(sb, "totp", e.totp)108        sb.append('}')109    }110111    /**112     * Append `"key":"<escaped value>"` (always emitted, even when null/empty, so113     * the object shape is stable). [first] controls the leading comma.114     */115    private fun appendField(sb: StringBuilder, key: String, value: String?, first: Boolean = false) {116        if (!first) sb.append(',')117        sb.append('"').append(key).append("\":\"")118        appendEscaped(sb, value ?: "")119        sb.append('"')120    }121122    /** Escape a JSON string body: backslash, quote, and control chars. */123    private fun appendEscaped(sb: StringBuilder, s: String) {124        for (c in s) {125            when (c.code) {126                '\\'.code -> sb.append("\\\\")127                '"'.code -> sb.append("\\\"")128                '\n'.code -> sb.append("\\n")129                '\r'.code -> sb.append("\\r")130                '\t'.code -> sb.append("\\t")131                0x08 -> sb.append("\\b")132                0x0C -> sb.append("\\f")133                else -> if (c.code < 0x20) {134                    sb.append("\\u").append(c.code.toString(16).padStart(4, '0'))135                } else {136                    sb.append(c)137                }138            }139        }140    }141}