package com.peachpasswords.ui.vault import com.peachpasswords.vault.VaultCrypto import com.peachpasswords.vault.VaultEntry import java.util.Base64 /** * Pure-Kotlin serialisation for PeachScript exports (spec C2 PeachScript sub-view). * * This is the WRITE side of the format that [PeachScriptImport] reads. The shapes * below are pinned by B2 (see `B2-INTEGRATION.md`) and MUST round-trip: * * PeachScriptImport.decryptAndParse(buildEncrypted(es, pw), pw) * == DecryptResult.Success(es-as-ParsedEntry) * * Plaintext: * { * "peachscript": 1, * "encrypted": false, * "entries": [ { "title", "username", "password", "url", "notes", "totp" }, ... ] * } * * Encrypted (backup-password protected): * { * "peachscript": 1, * "encrypted": true, * "kdf": "argon2id", * "salt": "", * "blob": "" * } * * The "blob" is exactly VaultCrypto.encrypt(plaintextJsonBytes, key, AAD) output * (nonce prepended). AAD is the constant [PeachScriptImport.PEACHSCRIPT_AAD] * ("peachscript_export_v1") — using any other AAD makes the importer's GCM tag * check fail and the user sees "Incorrect backup password." * * No Compose / Android UI here — unit-testable pure functions. */ object PeachScriptExport { /** Format version marker emitted as `"peachscript": 1`. */ private const val FORMAT_VERSION = 1 // Standard (not URL-safe) base64, matching the decoder in PeachScriptImport. private val b64 = Base64.getEncoder() /** * Serialise [entries] to the plaintext-shape PeachScript JSON. This is the * exact byte sequence that gets encrypted for [buildEncrypted] (with * "encrypted": false), so the importer reconstructs the same entries. * * Emits the importer's recognised keys (title/username/password/url/notes/totp). * `email` is folded into `username` only when `username` is absent, since the * PeachScript schema has no `email` field and the importer only reads these six. */ fun buildPlaintext(entries: List): String { val sb = StringBuilder(256 + entries.size * 96) sb.append('{') sb.append("\"peachscript\":").append(FORMAT_VERSION).append(',') sb.append("\"encrypted\":false,") sb.append("\"entries\":[") entries.forEachIndexed { i, e -> if (i > 0) sb.append(',') appendEntry(sb, e) } sb.append("]}") return sb.toString() } /** * Build the encrypted-shape PeachScript JSON: generate a 16-byte salt, derive * an Argon2id key from [backupPassword], AES-256-GCM encrypt the plaintext * JSON with AAD [PeachScriptImport.PEACHSCRIPT_AAD], then base64 the salt and * the nonce||ciphertext||tag blob. The derived key is zeroed after use. */ fun buildEncrypted(entries: List, backupPassword: String): String { val plaintext = buildPlaintext(entries).toByteArray(Charsets.UTF_8) val salt = VaultCrypto.generateSalt() val key = VaultCrypto.deriveKey(backupPassword, salt) val blob = try { VaultCrypto.encrypt(plaintext, key, PeachScriptImport.PEACHSCRIPT_AAD) } finally { VaultCrypto.zero(key) } val saltB64 = b64.encodeToString(salt) val blobB64 = b64.encodeToString(blob) val sb = StringBuilder(saltB64.length + blobB64.length + 96) sb.append('{') sb.append("\"peachscript\":").append(FORMAT_VERSION).append(',') sb.append("\"encrypted\":true,") sb.append("\"kdf\":\"argon2id\",") sb.append("\"salt\":\"").append(saltB64).append("\",") sb.append("\"blob\":\"").append(blobB64).append('"') sb.append('}') return sb.toString() } private fun appendEntry(sb: StringBuilder, e: VaultEntry) { sb.append('{') appendField(sb, "title", e.title, first = true) appendField(sb, "username", e.username ?: e.email) appendField(sb, "password", e.password) appendField(sb, "url", e.url) appendField(sb, "notes", e.notes) appendField(sb, "totp", e.totp) sb.append('}') } /** * Append `"key":""` (always emitted, even when null/empty, so * the object shape is stable). [first] controls the leading comma. */ private fun appendField(sb: StringBuilder, key: String, value: String?, first: Boolean = false) { if (!first) sb.append(',') sb.append('"').append(key).append("\":\"") appendEscaped(sb, value ?: "") sb.append('"') } /** Escape a JSON string body: backslash, quote, and control chars. */ private fun appendEscaped(sb: StringBuilder, s: String) { for (c in s) { when (c.code) { '\\'.code -> sb.append("\\\\") '"'.code -> sb.append("\\\"") '\n'.code -> sb.append("\\n") '\r'.code -> sb.append("\\r") '\t'.code -> sb.append("\\t") 0x08 -> sb.append("\\b") ' ' -> sb.append("\\f") else -> if (c < ' ') { sb.append("\\u").append(c.code.toString(16).padStart(4, '0')) } else { sb.append(c) } } } } }