1148aa0e29cf
port MF-2 PeachScript to the browser PCHS binary format (PUA codec, zstd-jni sections, BLAKE3 checksum, Argon2id-UTF8, string-table entry packing, full field set); add zstd-jni @aar + host test jar; 104 tests green incl. real browser-payload KAT, assembleDebug+lintDebug pass
- time
- 2026-06-09 16:31 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- cross-platform recovery and peachscript parity
- parent
- 51a8e8ea9ff3
↓ peach-android-1148aa0e.tar.gzatlas at this save
files changed18 files
app/build.gradle+9 −0app/drafts/MF1MF2/ExportRoundTripTest.kt+61 −0app/drafts/MF1MF2/ImportParsersTest.kt+66 −0app/drafts/MF1MF2/ImportScreen.kt+691 −0app/drafts/MF1MF2/PeachPayloadCodec.kt+708 −0app/drafts/MF1MF2/PeachScript.kt+53 −0app/drafts/MF1MF2/PeachScriptExport.kt+24 −0app/drafts/MF1MF2/PeachScriptImport.kt+52 −0app/drafts/MF1MF2/PeachScriptTest.kt+185 −0app/drafts/MF1MF2/gen_peach_fixture.mjs+51 −0app/src/main/java/com/peachpasswords/ui/vault/ImportScreen.kt+46 −23app/src/main/java/com/peachpasswords/ui/vault/PeachScriptExport.kt+12 −129app/src/main/java/com/peachpasswords/ui/vault/PeachScriptImport.kt+30 −209app/src/main/java/com/peachpasswords/vault/PeachPayloadCodec.kt+708 −0app/src/main/java/com/peachpasswords/vault/PeachScript.kt+53 −0app/src/test/java/com/peachpasswords/ui/vault/ExportRoundTripTest.kt+10 −11app/src/test/java/com/peachpasswords/ui/vault/ImportParsersTest.kt+16 −12app/src/test/java/com/peachpasswords/vault/PeachScriptTest.kt+185 −0app/build.gradle+9 −0
@@ -103,6 +103,15 @@103103 implementation "androidx.camera:camera-view:1.3.4"104104 implementation "com.squareup.okhttp3:okhttp:4.12.0"105105 implementation "org.bouncycastle:bcprov-jdk18on:1.78.1"106+ // zstd-jni (reference libzstd) — per-section compression for the PeachScript107+ // PCHS binary format (MF-2). Required for cross-platform interop with the108+ // browser's zstd sections. The @aar variant ships the Android jniLibs109+ // (lib/<abi>/libzstd-jni.so); the plain jar bundles only desktop natives and110+ // would fail with UnsatisfiedLinkError on-device.111+ implementation "com.github.luben:zstd-jni:1.5.6-3@aar"112+ // The @aar ships only Android .so; the plain jar carries the desktop natives113+ // the host JVM unit tests need.114+ testImplementation "com.github.luben:zstd-jni:1.5.6-3"106115 implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1"107116 implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1"108117 app/drafts/MF1MF2/ExportRoundTripTest.kt+61 −0
@@ -0,0 +1,61 @@1+package com.peachpasswords.ui.vault2+3+import com.peachpasswords.vault.VaultEntry4+import org.junit.Assert.assertEquals5+import org.junit.Assert.assertTrue6+import org.junit.Test7+8+class ExportRoundTripTest {9+10+ // PeachScript packs the id as 16 raw UUID bytes (browser parity), so test11+ // entries use real UUIDs as production entries do (addEntry assigns one).12+ private fun entry() = VaultEntry(13+ id = "11111111-2222-3333-4444-555555555555", title = "GitHub", type = "login",14+ username = "june", password = "hunter2", url = "https://github.com",15+ notes = "my note", totp = "JBSWY3DPEHPK3PXP", createdAt = 0, modifiedAt = 0,16+ )17+18+ @Test fun csv_formula_injection_is_guarded() {19+ assertEquals("'=1+1", CsvExport.encodeField("=1+1"))20+ assertEquals("'@cmd", CsvExport.encodeField("@cmd"))21+ assertEquals("'-2", CsvExport.encodeField("-2"))22+ }23+24+ @Test fun csv_quotes_fields_with_commas_and_quotes() {25+ assertEquals("\"a,b\"", CsvExport.encodeField("a,b"))26+ assertEquals("\"he\"\"llo\"", CsvExport.encodeField("he\"llo"))27+ assertEquals("plain", CsvExport.encodeField("plain"))28+ }29+30+ @Test fun csv_has_header_and_row() {31+ val csv = CsvExport.toCsv(listOf(entry()))32+ val lines = csv.trim().split("\r\n")33+ assertEquals("title,username,password,url,notes", lines[0])34+ assertTrue(lines[1].startsWith("GitHub,june,hunter2,"))35+ }36+37+ @Test fun peachscript_export_is_peachscript_text() {38+ val out = PeachScriptExport.buildEncrypted(listOf(entry()), "backup-pass-12")39+ assertTrue(PeachScriptImport.looksLikePeachScript(out))40+ assertTrue(PeachScriptImport.isEncrypted(out))41+ }42+43+ @Test fun peachscript_encrypted_round_trips_with_correct_password() {44+ val blob = PeachScriptExport.buildEncrypted(listOf(entry()), "backup-pass-12")45+ assertTrue(PeachScriptImport.isEncrypted(blob))46+ val ok = PeachScriptImport.decryptAndParse(blob, "backup-pass-12")47+ assertTrue(ok is PeachScriptImport.DecryptResult.Success)48+ ok as PeachScriptImport.DecryptResult.Success49+ assertEquals(1, ok.entries.size)50+ assertEquals("hunter2", ok.entries[0].password)51+ assertEquals("june", ok.entries[0].username)52+ assertEquals("my note", ok.entries[0].notes)53+ assertEquals("JBSWY3DPEHPK3PXP", ok.entries[0].totp)54+ }55+56+ @Test fun peachscript_encrypted_rejects_wrong_password() {57+ val blob = PeachScriptExport.buildEncrypted(listOf(entry()), "backup-pass-12")58+ val r = PeachScriptImport.decryptAndParse(blob, "wrong-password")59+ assertTrue(r is PeachScriptImport.DecryptResult.WrongPassword)60+ }61+}app/drafts/MF1MF2/ImportParsersTest.kt+66 −0
@@ -0,0 +1,66 @@1+package com.peachpasswords.ui.vault2+3+import com.peachpasswords.vault.VaultEntry4+import org.junit.Assert.assertEquals5+import org.junit.Assert.assertFalse6+import org.junit.Assert.assertNull7+import org.junit.Assert.assertTrue8+import org.junit.Test9+10+class ImportParsersTest {11+12+ @Test fun detect_blank_is_null() {13+ assertNull(CsvImport.detectProvider(""))14+ assertNull(CsvImport.detectProvider(" \n "))15+ }16+17+ @Test fun chrome_csv_detects_and_parses() {18+ val csv = "name,url,username,password\nGitHub,https://github.com,june,hunter2\n"19+ assertEquals(CsvImport.CHROME_CSV, CsvImport.detectProvider(csv))20+ val rows = CsvImport.parse(csv, CsvImport.CHROME_CSV)21+ assertEquals(1, rows.size)22+ assertEquals("GitHub", rows[0].title)23+ assertEquals("https://github.com", rows[0].url)24+ assertEquals("june", rows[0].username)25+ assertEquals("hunter2", rows[0].password)26+ }27+28+ @Test fun csv_quoted_fields_with_commas_are_preserved() {29+ val rows = CsvImport.parseCsv("name,url,username,password\n\"Bank, NA\",https://b.com,j,\"p,w\"\n")30+ // Header + 1 data row.31+ assertEquals(2, rows.size)32+ assertEquals(listOf("Bank, NA", "https://b.com", "j", "p,w"), rows[1])33+ }34+35+ @Test fun csv_doubled_quotes_unescape() {36+ assertEquals(listOf("a\"b", "c"), CsvImport.splitCsvLine("\"a\"\"b\",c"))37+ }38+39+ @Test fun detect_and_parse_returns_success_for_chrome() {40+ val csv = "name,url,username,password\nA,https://a.com,u,p\nB,https://b.com,u2,p2\n"41+ val r = CsvImport.detectAndParse(csv)42+ assertTrue(r is ImportParseResult.Success)43+ r as ImportParseResult.Success44+ assertEquals(2, r.entries.size)45+ }46+47+ @Test fun peachscript_export_is_recognised() {48+ val out = PeachScriptExport.buildEncrypted(49+ listOf(50+ VaultEntry(51+ id = "11111111-2222-3333-4444-555555555555", type = "login",52+ title = "GH", username = "u", password = "p", createdAt = 0, modifiedAt = 0,53+ ),54+ ),55+ "backup-pass-123",56+ )57+ assertTrue(PeachScriptImport.looksLikePeachScript(out))58+ assertTrue(PeachScriptImport.isEncrypted(out))59+ }60+61+ @Test fun non_peachscript_text_is_rejected() {62+ assertFalse(PeachScriptImport.looksLikePeachScript("just text"))63+ // The old JSON marker is not PeachScript anymore (PUA-encoded binary only).64+ assertFalse(PeachScriptImport.looksLikePeachScript("""{"peachscript":1,"encrypted":true}"""))65+ }66+}app/drafts/MF1MF2/ImportScreen.kt+691 −0
@@ -0,0 +1,691 @@1+package com.peachpasswords.ui.vault2+3+import android.content.Context4+import android.net.Uri5+import androidx.activity.compose.rememberLauncherForActivityResult6+import androidx.activity.result.contract.ActivityResultContracts7+import androidx.compose.foundation.background8+import androidx.compose.foundation.border9+import androidx.compose.foundation.clickable10+import androidx.compose.foundation.layout.Arrangement11+import androidx.compose.foundation.layout.Box12+import androidx.compose.foundation.layout.Column13+import androidx.compose.foundation.layout.Row14+import androidx.compose.foundation.layout.Spacer15+import androidx.compose.foundation.layout.fillMaxSize16+import androidx.compose.foundation.layout.fillMaxWidth17+import androidx.compose.foundation.layout.heightIn18+import androidx.compose.foundation.layout.padding19+import androidx.compose.foundation.layout.size20+import androidx.compose.foundation.layout.systemBarsPadding21+import androidx.compose.foundation.layout.width22+import androidx.compose.foundation.rememberScrollState23+import androidx.compose.foundation.shape.RoundedCornerShape24+import androidx.compose.foundation.text.BasicTextField25+import androidx.compose.foundation.verticalScroll26+import androidx.compose.material.icons.Icons27+import androidx.compose.material.icons.automirrored.rounded.ArrowBack28+import androidx.compose.material3.Icon29+import androidx.compose.material3.Text30+import androidx.compose.runtime.Composable31+import androidx.compose.runtime.collectAsState32+import androidx.compose.runtime.getValue33+import androidx.compose.runtime.mutableStateOf34+import androidx.compose.runtime.remember35+import androidx.compose.runtime.setValue36+import androidx.compose.ui.Alignment37+import androidx.compose.ui.Modifier38+import androidx.compose.ui.draw.clip39+import androidx.compose.ui.graphics.Color40+import androidx.compose.ui.graphics.SolidColor41+import androidx.compose.ui.text.TextStyle42+import androidx.compose.ui.text.font.FontStyle43+import androidx.compose.ui.text.input.PasswordVisualTransformation44+import androidx.compose.ui.unit.dp45+import androidx.compose.ui.unit.sp46+import androidx.hilt.navigation.compose.hiltViewModel47+import androidx.lifecycle.ViewModel48+import androidx.lifecycle.viewModelScope49+import com.peachpasswords.ui.theme.LocalPeachAccent50+import com.peachpasswords.ui.theme.peachColors51+import com.peachpasswords.ui.theme.PeachType52+import com.peachpasswords.ui.theme.ShellBackground53+import com.peachpasswords.vault.VaultEntry54+import com.peachpasswords.vault.VaultRepository55+import dagger.hilt.android.lifecycle.HiltViewModel56+import dagger.hilt.android.qualifiers.ApplicationContext57+import kotlinx.coroutines.Dispatchers58+import kotlinx.coroutines.flow.MutableStateFlow59+import kotlinx.coroutines.flow.StateFlow60+import kotlinx.coroutines.flow.asStateFlow61+import kotlinx.coroutines.launch62+import kotlinx.coroutines.withContext63+import javax.inject.Inject64+65+// ─────────────────────────────────────────────────────────────────────────────66+// ViewModel67+// ─────────────────────────────────────────────────────────────────────────────68+69+/** How parsed entries land in the vault on confirm. */70+enum class ImportMode { MERGE, REPLACE }71+72+/**73+ * A staged, parsed import ready for preview + confirm. [entries] is the74+ * ParsedEntry projection used by the preview UI (shared with CSV). [fullEntries]75+ * is set only for PeachScript, carrying the complete VaultEntry field set so the76+ * import preserves tags, card fields, canary, breach, timestamps, etc.77+ */78+data class ImportPreview(79+ val sourceLabel: String,80+ val entries: List<ParsedEntry>,81+ val fullEntries: List<VaultEntry>? = null,82+)83+84+sealed interface ImportUiState {85+ data object Idle : ImportUiState86+ data object Working : ImportUiState87+ data class Preview(val preview: ImportPreview) : ImportUiState88+ data class Done(val count: Int) : ImportUiState89+ data class Failed(val message: String) : ImportUiState90+}91+92+object ImportErrors {93+ const val UNRECOGNISED = "This doesn't look like a PeachScript export."94+ const val WRONG_PASSWORD = "Incorrect backup password."95+ const val CORRUPTED = "This export appears to be corrupted."96+ const val NO_ENTRIES = "No entries found in this export."97+ const val UNREADABLE_FILE = "Couldn't read that file."98+ const val UNRECOGNISED_FILE = "Unrecognised file format."99+}100+101+@HiltViewModel102+class ImportViewModel @Inject constructor(103+ private val vault: VaultRepository,104+ @ApplicationContext private val appContext: Context,105+) : ViewModel() {106+107+ private val _state = MutableStateFlow<ImportUiState>(ImportUiState.Idle)108+ val state: StateFlow<ImportUiState> = _state.asStateFlow()109+110+ /** Detected provider label for the file sub-view ("Detected: X export"). */111+ private val _detectedProvider = MutableStateFlow<String?>(null)112+ val detectedProvider: StateFlow<String?> = _detectedProvider.asStateFlow()113+114+ fun reset() {115+ _state.value = ImportUiState.Idle116+ _detectedProvider.value = null117+ }118+119+ fun back(onBack: () -> Unit) {120+ // Preview/error back returns to the input view; otherwise leave the screen.121+ when (_state.value) {122+ is ImportUiState.Preview, is ImportUiState.Failed, is ImportUiState.Done -> reset()123+ else -> onBack()124+ }125+ }126+127+ // ---- PeachScript paste ------------------------------------------------128+129+ fun importPeachScript(text: String, backupPassword: String) {130+ val trimmed = text.trim()131+ if (trimmed.isEmpty() || !PeachScriptImport.looksLikePeachScript(trimmed)) {132+ _state.value = ImportUiState.Failed(ImportErrors.UNRECOGNISED)133+ return134+ }135+ _state.value = ImportUiState.Working136+ viewModelScope.launch {137+ val result = withContext(Dispatchers.Default) {138+ PeachScriptImport.decryptAndParse(trimmed, backupPassword)139+ }140+ _state.value = when (result) {141+ is PeachScriptImport.DecryptResult.Success ->142+ if (result.entries.isEmpty()) {143+ ImportUiState.Failed(ImportErrors.NO_ENTRIES)144+ } else {145+ val parsed = result.entries.map { e ->146+ ParsedEntry(147+ title = e.title,148+ username = e.username ?: e.email,149+ password = e.password,150+ url = e.url,151+ notes = e.notes,152+ totp = e.totp,153+ )154+ }155+ ImportUiState.Preview(ImportPreview("PeachScript", parsed, result.entries))156+ }157+ PeachScriptImport.DecryptResult.WrongPassword ->158+ ImportUiState.Failed(ImportErrors.WRONG_PASSWORD)159+ PeachScriptImport.DecryptResult.Corrupted ->160+ ImportUiState.Failed(ImportErrors.NO_ENTRIES)161+ }162+ }163+ }164+165+ /** True when the pasted text is a PeachScript export that needs a password. */166+ fun peachScriptNeedsPassword(text: String): Boolean {167+ val t = text.trim()168+ return PeachScriptImport.looksLikePeachScript(t) && PeachScriptImport.isEncrypted(t)169+ }170+171+ // ---- File import ------------------------------------------------------172+173+ fun importFile(uri: Uri) {174+ _state.value = ImportUiState.Working175+ _detectedProvider.value = null176+ viewModelScope.launch {177+ val content = withContext(Dispatchers.IO) {178+ runCatching {179+ appContext.contentResolver.openInputStream(uri)?.use {180+ it.readBytes().toString(Charsets.UTF_8)181+ }182+ }.getOrNull()183+ }184+ if (content.isNullOrBlank()) {185+ _state.value = ImportUiState.Failed(ImportErrors.UNREADABLE_FILE)186+ return@launch187+ }188+ val result = withContext(Dispatchers.Default) { CsvImport.detectAndParse(content) }189+ when (result) {190+ is ImportParseResult.Success -> {191+ _detectedProvider.value = result.provider192+ _state.value = ImportUiState.Preview(ImportPreview(result.provider, result.entries))193+ }194+ is ImportParseResult.Failure -> {195+ _state.value = ImportUiState.Failed(196+ when (result.reason) {197+ ImportParseResult.Reason.UNRECOGNISED -> ImportErrors.UNRECOGNISED_FILE198+ ImportParseResult.Reason.CORRUPTED -> ImportErrors.CORRUPTED199+ ImportParseResult.Reason.NO_ENTRIES -> ImportErrors.NO_ENTRIES200+ },201+ )202+ }203+ }204+ }205+ }206+207+ // ---- Confirm ----------------------------------------------------------208+209+ /**210+ * Persist the previewed entries. No batch API exists on VaultRepository, so211+ * import loops [VaultRepository.addEntry]. REPLACE soft-deletes the current212+ * active set first; MERGE simply appends.213+ */214+ fun confirmImport(preview: ImportPreview, mode: ImportMode) {215+ _state.value = ImportUiState.Working216+ viewModelScope.launch {217+ try {218+ if (mode == ImportMode.REPLACE) {219+ vault.getEntries().forEach { existing ->220+ runCatching { vault.deleteEntry(existing.id) }221+ }222+ }223+ val now = System.currentTimeMillis()224+ var imported = 0225+ val fulls = preview.fullEntries226+ if (fulls != null) {227+ // PeachScript: import the complete entries (all fields, all types).228+ // Re-id so an import can never overwrite an existing entry.229+ for (e in fulls) {230+ runCatching { vault.addEntry(e.copy(id = "")) }.onSuccess { imported++ }231+ }232+ } else {233+ for (p in preview.entries) {234+ val draft = VaultEntry(235+ id = "",236+ type = "login",237+ title = p.title,238+ username = p.username,239+ password = p.password,240+ url = p.url,241+ notes = p.notes,242+ totp = p.totp,243+ createdAt = now,244+ modifiedAt = now,245+ )246+ runCatching { vault.addEntry(draft) }.onSuccess { imported++ }247+ }248+ }249+ _state.value = ImportUiState.Done(imported)250+ } catch (e: Exception) {251+ _state.value = ImportUiState.Failed(ImportErrors.CORRUPTED)252+ }253+ }254+ }255+}256+257+// ─────────────────────────────────────────────────────────────────────────────258+// Screen259+// ─────────────────────────────────────────────────────────────────────────────260+261+private enum class ImportRoute { CHOOSE, PEACHSCRIPT, FILE }262+263+@Composable264+fun ImportScreen(265+ onBack: () -> Unit,266+ vm: ImportViewModel = hiltViewModel(),267+) {268+ val state by vm.state.collectAsState()269+ var route by remember { mutableStateOf(ImportRoute.CHOOSE) }270+271+ ShellBackground {272+ Column(273+ modifier = Modifier274+ .fillMaxSize()275+ .systemBarsPadding()276+ .padding(horizontal = 20.dp, vertical = 16.dp),277+ ) {278+ // Top bar: back · "Import"279+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {280+ Icon(281+ Icons.AutoMirrored.Rounded.ArrowBack,282+ contentDescription = "back",283+ tint = peachColors.T0,284+ modifier = Modifier285+ .size(22.dp)286+ .clip(RoundedCornerShape(8.dp))287+ .clickable {288+ when {289+ state !is ImportUiState.Idle -> vm.back(onBack)290+ route != ImportRoute.CHOOSE -> route = ImportRoute.CHOOSE291+ else -> onBack()292+ }293+ },294+ )295+ Spacer(Modifier.width(14.dp))296+ Text(297+ "Import",298+ color = peachColors.T0,299+ style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),300+ )301+ }302+303+ Spacer(Modifier.size(18.dp))304+305+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {306+ when (val s = state) {307+ is ImportUiState.Preview -> PreviewView(308+ preview = s.preview,309+ onConfirm = { mode -> vm.confirmImport(s.preview, mode) },310+ onCancel = { vm.reset() },311+ )312+ is ImportUiState.Done -> DoneView(count = s.count, onDone = onBack)313+ is ImportUiState.Failed -> {314+ ErrorBanner(s.message)315+ Spacer(Modifier.size(16.dp))316+ when (route) {317+ ImportRoute.PEACHSCRIPT -> PeachScriptView(vm)318+ ImportRoute.FILE -> FileView(vm)319+ ImportRoute.CHOOSE -> ChooseView(320+ onPeachScript = { route = ImportRoute.PEACHSCRIPT },321+ onFile = { route = ImportRoute.FILE },322+ )323+ }324+ }325+ ImportUiState.Working -> WorkingView()326+ ImportUiState.Idle -> when (route) {327+ ImportRoute.CHOOSE -> ChooseView(328+ onPeachScript = { route = ImportRoute.PEACHSCRIPT },329+ onFile = { route = ImportRoute.FILE },330+ )331+ ImportRoute.PEACHSCRIPT -> PeachScriptView(vm)332+ ImportRoute.FILE -> FileView(vm)333+ }334+ }335+ }336+ }337+ }338+}339+340+// ---- Choose view ----------------------------------------------------------341+342+@Composable343+private fun ChooseView(onPeachScript: () -> Unit, onFile: () -> Unit) {344+ OptionCard(345+ title = "From PeachScript",346+ subtitle = "Paste an encrypted Peach export",347+ onClick = onPeachScript,348+ )349+ Spacer(Modifier.size(12.dp))350+ OptionCard(351+ title = "From file",352+ subtitle = "Bitwarden, 1Password, Chrome, Safari, Edge CSV",353+ onClick = onFile,354+ )355+}356+357+@Composable358+private fun OptionCard(title: String, subtitle: String, onClick: () -> Unit) {359+ Column(360+ modifier = Modifier361+ .fillMaxWidth()362+ .clip(RoundedCornerShape(18.dp))363+ .background(peachColors.SurfaceElevated)364+ .border(1.dp, peachColors.T3, RoundedCornerShape(18.dp))365+ .clickable(onClick = onClick)366+ .padding(20.dp),367+ ) {368+ Text(369+ title,370+ color = peachColors.T0,371+ style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),372+ )373+ Spacer(Modifier.size(6.dp))374+ Text(subtitle, color = peachColors.T1, style = PeachType.body)375+ }376+}377+378+// ---- PeachScript sub-view -------------------------------------------------379+380+@Composable381+private fun PeachScriptView(vm: ImportViewModel) {382+ var paste by remember { mutableStateOf("") }383+ var backupPassword by remember { mutableStateOf("") }384+ val needsPassword = remember(paste) { vm.peachScriptNeedsPassword(paste) }385+386+ GlassCard {387+ FieldLabel("Paste your PeachScript export")388+ Spacer(Modifier.size(8.dp))389+ PeachMultilineField(390+ value = paste,391+ onValueChange = { paste = it },392+ minLines = 6,393+ )394+ if (needsPassword) {395+ Spacer(Modifier.size(16.dp))396+ FieldLabel("Backup password")397+ Spacer(Modifier.size(6.dp))398+ PeachUnderlineField(399+ value = backupPassword,400+ onValueChange = { backupPassword = it },401+ isPassword = true,402+ )403+ }404+ }405+ Spacer(Modifier.size(18.dp))406+ AccentButton(407+ label = "Import",408+ enabled = paste.isNotBlank(),409+ onClick = { vm.importPeachScript(paste, backupPassword) },410+ )411+}412+413+// ---- File sub-view --------------------------------------------------------414+415+@Composable416+private fun FileView(vm: ImportViewModel) {417+ val detected by vm.detectedProvider.collectAsState()418+ val picker = rememberLauncherForActivityResult(419+ ActivityResultContracts.GetContent(),420+ ) { uri -> if (uri != null) vm.importFile(uri) }421+422+ GlassCard {423+ Text(424+ "Import from a CSV or JSON export",425+ color = peachColors.T1,426+ style = PeachType.body,427+ )428+ Spacer(Modifier.size(6.dp))429+ Text(430+ "Supports Bitwarden, 1Password, Chrome/Edge, and Safari exports.",431+ color = peachColors.T2,432+ style = PeachType.hint,433+ )434+ Spacer(Modifier.size(16.dp))435+ GhostButton("Choose file", LocalPeachAccent.current) {436+ // GetContent takes a single MIME type; the chooser still lists CSV437+ // and JSON. "*/*" is intentional so providers exporting odd MIME438+ // types for .csv are not filtered out by the system picker.439+ picker.launch("*/*")440+ }441+ if (detected != null) {442+ Spacer(Modifier.size(12.dp))443+ Text(444+ "Detected: $detected export",445+ color = LocalPeachAccent.current,446+ style = PeachType.labelMono,447+ )448+ }449+ }450+}451+452+// ---- Preview --------------------------------------------------------------453+454+@Composable455+private fun PreviewView(456+ preview: ImportPreview,457+ onConfirm: (ImportMode) -> Unit,458+ onCancel: () -> Unit,459+) {460+ var mode by remember { mutableStateOf(ImportMode.MERGE) }461+462+ GlassCard {463+ Text(464+ "Detected: ${preview.sourceLabel} export",465+ color = LocalPeachAccent.current,466+ style = PeachType.labelMono,467+ )468+ Spacer(Modifier.size(10.dp))469+ Text(470+ "Found ${preview.entries.size} ${if (preview.entries.size == 1) "entry" else "entries"}",471+ color = peachColors.T0,472+ style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),473+ )474+ Spacer(Modifier.size(12.dp))475+ // Up to five entry names, scrollable if more.476+ Column(477+ modifier = Modifier478+ .fillMaxWidth()479+ .heightIn(max = 150.dp)480+ .verticalScroll(rememberScrollState()),481+ ) {482+ preview.entries.take(5).forEach { e ->483+ Text(484+ e.title,485+ color = peachColors.T1,486+ style = PeachType.entryNameList,487+ modifier = Modifier.padding(vertical = 4.dp),488+ )489+ }490+ if (preview.entries.size > 5) {491+ Text(492+ "+${preview.entries.size - 5} more",493+ color = peachColors.T2,494+ style = PeachType.tinyMono,495+ modifier = Modifier.padding(top = 4.dp),496+ )497+ }498+ }499+ Divider()500+ RadioRow("Merge with existing vault", selected = mode == ImportMode.MERGE) { mode = ImportMode.MERGE }501+ Spacer(Modifier.size(8.dp))502+ RadioRow("Replace vault", selected = mode == ImportMode.REPLACE) { mode = ImportMode.REPLACE }503+ }504+ Spacer(Modifier.size(18.dp))505+ AccentButton(label = "Confirm Import", onClick = { onConfirm(mode) })506+ Spacer(Modifier.size(8.dp))507+ GhostButton("Cancel", peachColors.T1, onCancel)508+}509+510+@Composable511+private fun RadioRow(label: String, selected: Boolean, onClick: () -> Unit) {512+ val accent = LocalPeachAccent.current513+ Row(514+ verticalAlignment = Alignment.CenterVertically,515+ modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(vertical = 4.dp),516+ ) {517+ Box(518+ modifier = Modifier519+ .size(16.dp)520+ .clip(RoundedCornerShape(999.dp))521+ .border(1.5.dp, if (selected) accent else peachColors.T2, RoundedCornerShape(999.dp)),522+ contentAlignment = Alignment.Center,523+ ) {524+ if (selected) {525+ Box(Modifier.size(8.dp).clip(RoundedCornerShape(999.dp)).background(accent))526+ }527+ }528+ Spacer(Modifier.width(12.dp))529+ Text(label, color = peachColors.T0, style = PeachType.body)530+ }531+}532+533+// ---- Done / Working / Error ----------------------------------------------534+535+@Composable536+private fun DoneView(count: Int, onDone: () -> Unit) {537+ GlassCard {538+ Text(539+ "imported.",540+ color = peachColors.T0,541+ style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 24.sp),542+ )543+ Spacer(Modifier.size(8.dp))544+ Text(545+ "$count ${if (count == 1) "entry" else "entries"} imported.",546+ color = peachColors.T1,547+ style = PeachType.body,548+ )549+ }550+ Spacer(Modifier.size(18.dp))551+ AccentButton(label = "Done", onClick = onDone)552+}553+554+@Composable555+private fun WorkingView() {556+ Box(Modifier.fillMaxWidth().padding(vertical = 40.dp), contentAlignment = Alignment.Center) {557+ Text(558+ "working…",559+ color = peachColors.T1,560+ style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp),561+ )562+ }563+}564+565+@Composable566+private fun ErrorBanner(message: String) {567+ Box(568+ modifier = Modifier569+ .fillMaxWidth()570+ .clip(RoundedCornerShape(12.dp))571+ .background(peachColors.BreachBg)572+ .border(1.dp, peachColors.BreachBorder, RoundedCornerShape(12.dp))573+ .padding(14.dp),574+ ) {575+ Text(message, color = peachColors.Breach, style = PeachType.bodyMono)576+ }577+}578+579+// ---- Shared building blocks (private to this draft) -----------------------580+581+@Composable582+private fun FieldLabel(text: String) {583+ Text(584+ text.uppercase(),585+ color = peachColors.T2,586+ style = PeachType.labelMono,587+ )588+}589+590+@Composable591+private fun PeachMultilineField(592+ value: String,593+ onValueChange: (String) -> Unit,594+ minLines: Int,595+) {596+ val accent = LocalPeachAccent.current597+ Box(598+ modifier = Modifier599+ .fillMaxWidth()600+ .clip(RoundedCornerShape(12.dp))601+ .background(peachColors.S2)602+ .border(1.dp, peachColors.T3, RoundedCornerShape(12.dp))603+ .padding(14.dp),604+ ) {605+ BasicTextField(606+ value = value,607+ onValueChange = onValueChange,608+ textStyle = PeachType.bodyMono.copy(color = peachColors.T0),609+ cursorBrush = SolidColor(accent),610+ minLines = minLines,611+ modifier = Modifier.fillMaxWidth(),612+ )613+ if (value.isEmpty()) {614+ Text(615+ "{ \"peachscript\": 1, … }",616+ color = peachColors.T2,617+ style = PeachType.bodyMono,618+ )619+ }620+ }621+}622+623+@Composable624+private fun PeachUnderlineField(625+ value: String,626+ onValueChange: (String) -> Unit,627+ isPassword: Boolean = false,628+) {629+ val accent = LocalPeachAccent.current630+ Column(Modifier.fillMaxWidth()) {631+ BasicTextField(632+ value = value,633+ onValueChange = onValueChange,634+ singleLine = true,635+ textStyle = PeachType.bodyMono.copy(color = peachColors.T0),636+ cursorBrush = SolidColor(accent),637+ visualTransformation = if (isPassword) PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None,638+ modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),639+ )640+ Box(Modifier.fillMaxWidth().size(1.dp).background(peachColors.T3))641+ }642+}643+644+@Composable645+private fun GlassCard(content: @Composable () -> Unit) {646+ Column(647+ modifier = Modifier648+ .fillMaxWidth()649+ .clip(RoundedCornerShape(18.dp))650+ .background(peachColors.SurfaceElevated)651+ .border(1.dp, peachColors.T3, RoundedCornerShape(18.dp))652+ .padding(20.dp),653+ content = { content() },654+ )655+}656+657+@Composable658+private fun Divider() {659+ Box(Modifier.fillMaxWidth().padding(vertical = 14.dp).size(1.dp).background(peachColors.T3))660+}661+662+@Composable663+private fun GhostButton(label: String, color: Color, onClick: () -> Unit) {664+ Box(665+ modifier = Modifier666+ .fillMaxWidth()667+ .clip(RoundedCornerShape(12.dp))668+ .border(1.dp, color.copy(alpha = 0.4f), RoundedCornerShape(12.dp))669+ .clickable(onClick = onClick)670+ .padding(vertical = 12.dp),671+ contentAlignment = Alignment.Center,672+ ) {673+ Text(label, color = color, style = PeachType.bodyMono)674+ }675+}676+677+@Composable678+private fun AccentButton(label: String, onClick: () -> Unit, enabled: Boolean = true) {679+ val accent = LocalPeachAccent.current680+ Box(681+ modifier = Modifier682+ .fillMaxWidth()683+ .clip(RoundedCornerShape(12.dp))684+ .background(if (enabled) accent else accent.copy(alpha = 0.3f))685+ .clickable(enabled = enabled, onClick = onClick)686+ .padding(vertical = 14.dp),687+ contentAlignment = Alignment.Center,688+ ) {689+ Text(label, color = Color(0xFF0C0A06), style = PeachType.bodyMono)690+ }691+}app/drafts/MF1MF2/PeachPayloadCodec.kt+708 −0
@@ -0,0 +1,708 @@1+package com.peachpasswords.vault2+3+import com.github.luben.zstd.Zstd4+import org.bouncycastle.crypto.digests.Blake3Digest5+import org.bouncycastle.crypto.generators.Argon2BytesGenerator6+import org.bouncycastle.crypto.params.Argon2Parameters7+import java.io.ByteArrayOutputStream8+import java.security.SecureRandom9+import javax.crypto.Cipher10+import javax.crypto.spec.GCMParameterSpec11+import javax.crypto.spec.SecretKeySpec12+import kotlinx.serialization.json.Json13+import kotlinx.serialization.json.JsonObject14+import kotlinx.serialization.json.JsonObjectBuilder15+import kotlinx.serialization.json.JsonPrimitive16+import kotlinx.serialization.json.add17+import kotlinx.serialization.json.booleanOrNull18+import kotlinx.serialization.json.buildJsonArray19+import kotlinx.serialization.json.buildJsonObject20+import kotlinx.serialization.json.contentOrNull21+import kotlinx.serialization.json.intOrNull22+import kotlinx.serialization.json.jsonArray23+import kotlinx.serialization.json.jsonObject24+import kotlinx.serialization.json.jsonPrimitive25+import kotlinx.serialization.json.longOrNull26+27+/**28+ * PeachScript binary payload (`PCHS`) — a byte-for-byte port of the browser's29+ * `peachPayload.ts` (MF-2). Produces and consumes the encrypted envelope30+ * `[ salt(16) | nonce(12) | ciphertext | tag(16) ]` whose plaintext is31+ * `[ FORMAT_V3 | inner_len(LE) | inner | zero-pad-to-bucket ]`,32+ * `inner = [ body | blake3(body)[0..4) ]`,33+ * `body = [ MAGIC "PCHS"(BE) | VERSION | sectionCount | reserved(2) | section* ]`,34+ * each section `[ type | rawLen(LE) | compLen(LE) | zstd(level 19) ]`.35+ *36+ * The output of [buildPayload] is importable by the browser, and [parsePayload]37+ * reads browser-produced payloads. Verified by a real browser-fixture KAT38+ * (PeachScriptTest). Library notes are in app/drafts/MF1MF2/BROWSER-SPEC.md.39+ */40+object PeachPayloadCodec {41+42+ // ---- header / section constants (peachPayload.ts:48-124) --------------43+ private const val MAGIC = 0x50434853 // "PCHS" big-endian44+ private const val VERSION = 0x0145+ private const val HEADER_LEN = 846+ private const val CHECKSUM_LEN = 447+ private const val SALT_LEN = 1648+ private const val NONCE_LEN = 1249+ private const val TAG_LEN = 1650+51+ private val SIZE_BUCKETS = intArrayOf(1024, 4096, 16384, 65536, 262144)52+53+ private const val FORMAT_V2 = 0x0254+ private const val FORMAT_V3 = 0x0355+56+ private const val ARGON2_MEMORY_KIB = 6553657+ private const val ARGON2_ITERATIONS = 358+ private const val ARGON2_PARALLELISM = 459+60+ private const val SECTION_ENTRIES = 0x0161+ private const val SECTION_SETTINGS = 0x0262+ private const val SECTION_LICENSE = 0x0363+ private const val SECTION_RECALL = 0x0464+ private const val SECTION_DECLINED_CARDS = 0x0565+66+ private const val ENTRY_TYPE_LOGIN = 0x0167+ private const val ENTRY_TYPE_NOTE = 0x0268+ private const val ENTRY_TYPE_CARD = 0x0369+ private const val ENTRY_TYPE_PASSKEY = 0x0470+71+ private const val F_HAS_TOTP = 1 shl 072+ private const val F_HAS_TAGS = 1 shl 173+ private const val F_HAS_NOTES = 1 shl 274+ private const val F_HAS_CANARY = 1 shl 375+ private const val F_HAS_PWCHANGED = 1 shl 476+ private const val F_HAS_BREACH = 1 shl 577+ private const val F_HAS_ADDITIONAL_URLS = 1 shl 678+ private const val F_HAS_DELETED = 1 shl 779+80+ private const val F2_HAS_EMAIL = 1 shl 081+82+ private val NETWORK_VALUES = listOf("visa", "mastercard", "amex", "discover", "unknown")83+84+ private const val ZSTD_LEVEL = 1985+ private val secureRandom = SecureRandom()86+ private val json = Json { ignoreUnknownKeys = true; encodeDefaults = false }87+88+ class PeachScriptException(message: String) : Exception(message)89+90+ // ---- public API -------------------------------------------------------91+92+ /** Build the encrypted envelope `salt||nonce||ct||tag` from [entries]. */93+ fun buildPayload(entries: List<VaultEntry>, passphrase: String): ByteArray {94+ // sectionCount = 1 (ENTRIES). The browser also emits SETTINGS etc.; Android95+ // export carries entries only — a valid payload the browser reads (it skips96+ // absent sections). See BROWSER-SPEC §B2.11.97+ val entriesRaw = encodeEntriesSection(entries)98+ val sections = listOf(buildSection(SECTION_ENTRIES, entriesRaw))99+100+ val header = ByteArray(HEADER_LEN)101+ writeU32BE(header, 0, MAGIC.toLong())102+ header[4] = VERSION.toByte()103+ header[5] = sections.size.toByte()104+ // bytes 6,7 reserved (zero)105+106+ val body = concat(listOf(header) + sections)107+ val checksum = blake3Truncated(body)108+ val inner = concat(listOf(body, checksum))109+110+ val header5 = ByteArray(5)111+ header5[0] = FORMAT_V3.toByte()112+ writeU32LE(header5, 1, inner.size.toLong())113+ val wrapped = padToNearestBucket(concat(listOf(header5, inner)))114+115+ val salt = ByteArray(SALT_LEN).also(secureRandom::nextBytes)116+ val nonce = ByteArray(NONCE_LEN).also(secureRandom::nextBytes)117+ val key = deriveKey(passphrase, salt)118+ return try {119+ val ctTag = aesGcmEncrypt(key, nonce, wrapped)120+ concat(listOf(salt, nonce, ctTag))121+ } finally {122+ key.fill(0)123+ }124+ }125+126+ /** Parse the encrypted envelope back to entries. Throws [PeachScriptException]. */127+ fun parsePayload(envelope: ByteArray, passphrase: String): List<VaultEntry> {128+ if (envelope.size < SALT_LEN + NONCE_LEN + TAG_LEN + HEADER_LEN + CHECKSUM_LEN) {129+ throw PeachScriptException("PAYLOAD_TOO_SHORT")130+ }131+ val salt = envelope.copyOfRange(0, SALT_LEN)132+ val nonce = envelope.copyOfRange(SALT_LEN, SALT_LEN + NONCE_LEN)133+ val ctTag = envelope.copyOfRange(SALT_LEN + NONCE_LEN, envelope.size)134+135+ val key = deriveKey(passphrase, salt)136+ val decrypted = try {137+ aesGcmDecrypt(key, nonce, ctTag)138+ } catch (_: Exception) {139+ throw PeachScriptException("INVALID_PASSPHRASE")140+ } finally {141+ key.fill(0)142+ }143+144+ // Detect padded v2/v3 format: leading FORMAT byte + 4-byte LE inner length.145+ val inner: ByteArray146+ if (decrypted.size >= 5 && (decrypted[0].toInt() == FORMAT_V2 || decrypted[0].toInt() == FORMAT_V3)) {147+ val innerLen = readU32LE(decrypted, 1).toInt()148+ if (5 + innerLen > decrypted.size) throw PeachScriptException("PAYLOAD_TOO_SHORT")149+ inner = decrypted.copyOfRange(5, 5 + innerLen)150+ } else {151+ inner = decrypted // v1 — no length prefix / no padding152+ }153+154+ if (inner.size < HEADER_LEN + CHECKSUM_LEN) throw PeachScriptException("PAYLOAD_TOO_SHORT")155+ val body = inner.copyOfRange(0, inner.size - CHECKSUM_LEN)156+ val stored = inner.copyOfRange(inner.size - CHECKSUM_LEN, inner.size)157+ if (!constantTimeEqual(stored, blake3Truncated(body))) throw PeachScriptException("CHECKSUM_FAILED")158+159+ if (readU32BE(body, 0) != MAGIC.toLong()) throw PeachScriptException("BAD_MAGIC")160+ val version = body[4].toInt() and 0xff161+ if (version != VERSION) throw PeachScriptException("UNSUPPORTED_VERSION:$version")162+ val sectionCount = body[5].toInt() and 0xff163+164+ var entries = emptyList<VaultEntry>()165+ var cursor = HEADER_LEN166+ for (i in 0 until sectionCount) {167+ if (cursor + 9 > body.size) throw PeachScriptException("PAYLOAD_TOO_SHORT")168+ val type = body[cursor].toInt() and 0xff169+ val length = readU32LE(body, cursor + 1).toInt()170+ val clength = readU32LE(body, cursor + 5).toInt()171+ val dataStart = cursor + 9172+ val dataEnd = dataStart + clength173+ if (dataEnd > body.size) throw PeachScriptException("PAYLOAD_TOO_SHORT")174+ val compressed = body.copyOfRange(dataStart, dataEnd)175+ val data = Zstd.decompress(compressed, length)176+ if (data.size != length) throw PeachScriptException("SECTION_LENGTH_MISMATCH")177+ when (type) {178+ SECTION_ENTRIES -> entries = decodeEntriesSection(data)179+ // SETTINGS/LICENSE/RECALL/DECLINED_CARDS and unknown types are180+ // skipped — Android needs only the entries (BROWSER-SPEC §B2.12).181+ else -> {}182+ }183+ cursor = dataEnd184+ }185+ return entries186+ }187+188+ // ---- section assembly (peachPayload.ts:316-333) -----------------------189+190+ private fun buildSection(type: Int, raw: ByteArray): ByteArray {191+ val compressed = Zstd.compress(raw, ZSTD_LEVEL)192+ val out = ByteArray(9 + compressed.size)193+ out[0] = type.toByte()194+ writeU32LE(out, 1, raw.size.toLong())195+ writeU32LE(out, 5, compressed.size.toLong())196+ System.arraycopy(compressed, 0, out, 9, compressed.size)197+ return out198+ }199+200+ // ---- entries section: string table + packed bodies --------------------201+202+ private class StringTable {203+ private val map = LinkedHashMap<String, Int>()204+205+ /** u16 index; 0 reserved for absent. */206+ fun intern(value: String?): Int {207+ if (value.isNullOrEmpty()) return 0208+ map[value]?.let { return it }209+ val idx = map.size + 1210+ if (idx > 0xffff) throw PeachScriptException("STRING_TABLE_OVERFLOW")211+ map[value] = idx212+ return idx213+ }214+215+ fun serialize(): ByteArray {216+ val out = BinaryWriter()217+ out.u16(map.size)218+ for (s in map.keys) {219+ val e = s.toByteArray(Charsets.UTF_8)220+ if (e.size > 0xffff) throw PeachScriptException("STRING_TOO_LONG")221+ out.u16(e.size)222+ out.bytes(e)223+ }224+ return out.toBytes()225+ }226+ }227+228+ private fun encodeEntriesSection(entries: List<VaultEntry>): ByteArray {229+ val table = StringTable()230+ // Pre-intern every title first (peachPayload.ts:400-401) so indices match.231+ for (e in entries) table.intern(e.title)232+ val bodies = entries.map { encodeEntry(it, table) }233+ val tableBytes = table.serialize()234+235+ val out = BinaryWriter()236+ out.u32(entries.size.toLong())237+ out.bytes(tableBytes)238+ for (b in bodies) out.bytes(b)239+ return out.toBytes()240+ }241+242+ private fun decodeEntriesSection(data: ByteArray): List<VaultEntry> {243+ val r = BinaryReader(data, 0)244+ val count = r.u32().toInt()245+ val strings = readStringTable(r)246+ val out = ArrayList<VaultEntry>(count)247+ for (i in 0 until count) out.add(decodeEntry(r, strings))248+ return out249+ }250+251+ private fun readStringTable(r: BinaryReader): List<String?> {252+ val count = r.u16()253+ val strings = ArrayList<String?>(count + 1)254+ strings.add(null) // index 0 = absent255+ for (i in 0 until count) {256+ val len = r.u16()257+ strings.add(String(r.read(len), Charsets.UTF_8))258+ }259+ return strings260+ }261+262+ private fun lookup(strings: List<String?>, idx: Int): String? =263+ if (idx == 0 || idx >= strings.size) null else strings[idx]264+265+ // ---- per-entry packing (peachPayload.ts:443-601) ----------------------266+267+ private fun encodeEntry(entry: VaultEntry, table: StringTable): ByteArray {268+ val type = entryTypeByte(entry)269+ val w = BinaryWriter()270+ w.u8(type)271+ w.bytes(uuidToBytes(entry.id))272+273+ val createdSec = entry.createdAt / 1000L274+ val updatedSec = entry.modifiedAt / 1000L275+ val updatedDelta = maxOf(0L, updatedSec - createdSec)276+ val deletedSec = entry.deletedAt?.let { it / 1000L } ?: 0L277+278+ // Compute flags up front (the browser back-patches; same bytes result).279+ var flags = 0280+ var flags2 = 0281+ if (entry.deletedAt != null) flags = flags or F_HAS_DELETED282+283+ when (type) {284+ ENTRY_TYPE_LOGIN -> {285+ if (!entry.email.isNullOrEmpty()) flags2 = flags2 or F2_HAS_EMAIL286+ if (!entry.totp.isNullOrEmpty()) flags = flags or F_HAS_TOTP287+ if (!entry.tags.isNullOrEmpty()) flags = flags or F_HAS_TAGS288+ if (!entry.notes.isNullOrEmpty()) flags = flags or F_HAS_NOTES289+ if (entry.canary != null) flags = flags or F_HAS_CANARY290+ if (entry.passwordChangedAt != null) flags = flags or F_HAS_PWCHANGED291+ if ((entry.breach ?: 0) > 0) flags = flags or F_HAS_BREACH292+ if (!entry.additionalUrls.isNullOrEmpty()) flags = flags or F_HAS_ADDITIONAL_URLS293+ }294+ ENTRY_TYPE_NOTE -> {295+ if (!entry.notes.isNullOrEmpty()) flags = flags or F_HAS_NOTES296+ if (!entry.tags.isNullOrEmpty()) flags = flags or F_HAS_TAGS297+ }298+ ENTRY_TYPE_CARD -> {299+ if (!entry.tags.isNullOrEmpty()) flags = flags or F_HAS_TAGS300+ if (!entry.notes.isNullOrEmpty()) flags = flags or F_HAS_NOTES301+ }302+ }303+304+ w.u8(flags)305+ w.u8(flags2) // FORMAT_V3 always writes flags2306+ w.u32(createdSec)307+ w.u32(updatedDelta)308+ w.u32(deletedSec)309+ w.u16(table.intern(entry.title))310+311+ when (type) {312+ ENTRY_TYPE_LOGIN -> {313+ w.u16(table.intern(entry.url))314+ w.u16(table.intern(entry.username))315+ w.lpString(entry.password ?: "")316+ if (flags2 and F2_HAS_EMAIL != 0) w.lpString(entry.email!!)317+ if (flags and F_HAS_TOTP != 0) w.lpString(entry.totp!!)318+ if (flags and F_HAS_TAGS != 0) writeTags(w, table, entry.tags!!)319+ if (flags and F_HAS_NOTES != 0) w.u16(table.intern(entry.notes))320+ if (flags and F_HAS_CANARY != 0) {321+ w.u16(table.intern(entry.canary!!.webhookUrl))322+ w.u16(table.intern(entry.canary.label))323+ }324+ if (flags and F_HAS_PWCHANGED != 0) {325+ val pwSec = entry.passwordChangedAt!! / 1000L326+ w.u32(maxOf(0L, pwSec - createdSec))327+ }328+ if (flags and F_HAS_BREACH != 0) w.u32((entry.breach ?: 0).toLong())329+ if (flags and F_HAS_ADDITIONAL_URLS != 0) writeStrings(w, table, entry.additionalUrls!!)330+ }331+ ENTRY_TYPE_NOTE -> {332+ if (flags and F_HAS_NOTES != 0) w.u16(table.intern(entry.notes))333+ if (flags and F_HAS_TAGS != 0) writeTags(w, table, entry.tags!!)334+ }335+ ENTRY_TYPE_CARD -> {336+ w.u16(table.intern(entry.cardholderName))337+ w.lpString(entry.cardNumber ?: "")338+ w.lpString(entry.expMonth ?: "")339+ w.lpString(entry.expYear ?: "")340+ w.lpString(entry.cvc ?: "")341+ w.u16(table.intern(entry.cardNickname))342+ w.u8(networkToByte(entry.cardNetwork))343+ // Android has no last4 field — derive it from the card number so the344+ // wire format matches the browser (BROWSER-SPEC: card last4 note).345+ w.u16(table.intern(deriveLast4(entry)))346+ if (flags and F_HAS_TAGS != 0) writeTags(w, table, entry.tags!!)347+ if (flags and F_HAS_NOTES != 0) w.u16(table.intern(entry.notes))348+ }349+ ENTRY_TYPE_PASSKEY -> {350+ val blob = encodePasskeyBlob(entry)351+ w.u32(blob.size.toLong())352+ w.bytes(blob)353+ }354+ }355+ return w.toBytes()356+ }357+358+ private fun decodeEntry(r: BinaryReader, strings: List<String?>): VaultEntry {359+ val type = r.u8()360+ val id = bytesToUuid(r.read(16))361+ val flags = r.u8()362+ val flags2 = r.u8() // FORMAT_V3363+ val createdSec = r.u32()364+ val updatedDelta = r.u32()365+ val deletedSec = r.u32()366+ val titleIdx = r.u16()367+368+ val createdAt = createdSec * 1000L369+ val modifiedAt = (createdSec + updatedDelta) * 1000L370+ val deletedAt = if (deletedSec > 0) deletedSec * 1000L else null371+ val title = lookup(strings, titleIdx) ?: ""372+373+ return when (type) {374+ ENTRY_TYPE_LOGIN -> {375+ val urlIdx = r.u16()376+ val usernameIdx = r.u16()377+ val password = r.lpString()378+ val email = if (flags2 and F2_HAS_EMAIL != 0) r.lpString() else null379+ val totp = if (flags and F_HAS_TOTP != 0) r.lpString() else null380+ val tags = if (flags and F_HAS_TAGS != 0) readTags(r, strings) else null381+ val notes = if (flags and F_HAS_NOTES != 0) lookup(strings, r.u16()) else null382+ var canary: Canary? = null383+ if (flags and F_HAS_CANARY != 0) {384+ val webhookUrl = lookup(strings, r.u16()) ?: ""385+ val label = lookup(strings, r.u16())386+ canary = Canary(webhookUrl = webhookUrl, label = label)387+ }388+ val pwChanged = if (flags and F_HAS_PWCHANGED != 0) (createdSec + r.u32()) * 1000L else null389+ val breach = if (flags and F_HAS_BREACH != 0) r.u32().toInt() else null390+ val additionalUrls = if (flags and F_HAS_ADDITIONAL_URLS != 0) readStrings(r, strings) else null391+ VaultEntry(392+ id = id, type = "login", title = title,393+ url = lookup(strings, urlIdx), username = lookup(strings, usernameIdx),394+ password = password, email = email, totp = totp, tags = tags, notes = notes,395+ canary = canary, passwordChangedAt = pwChanged, breach = breach,396+ additionalUrls = additionalUrls, createdAt = createdAt, modifiedAt = modifiedAt,397+ deletedAt = deletedAt,398+ )399+ }400+ ENTRY_TYPE_NOTE -> {401+ val notes = if (flags and F_HAS_NOTES != 0) lookup(strings, r.u16()) else null402+ val tags = if (flags and F_HAS_TAGS != 0) readTags(r, strings) else null403+ VaultEntry(404+ id = id, type = "note", title = title, notes = notes, tags = tags,405+ createdAt = createdAt, modifiedAt = modifiedAt, deletedAt = deletedAt,406+ )407+ }408+ ENTRY_TYPE_CARD -> {409+ val cardholderIdx = r.u16()410+ val cardNumber = r.lpString()411+ val expMonth = r.lpString()412+ val expYear = r.lpString()413+ val cvc = r.lpString()414+ val nicknameIdx = r.u16()415+ val network = networkFromByte(r.u8())416+ r.u16() // last4 index — Android has no field; dropped (number carries it)417+ val tags = if (flags and F_HAS_TAGS != 0) readTags(r, strings) else null418+ val notes = if (flags and F_HAS_NOTES != 0) lookup(strings, r.u16()) else null419+ VaultEntry(420+ id = id, type = "card", title = title,421+ cardholderName = lookup(strings, cardholderIdx),422+ cardNumber = cardNumber.ifEmpty { null }, expMonth = expMonth.ifEmpty { null },423+ expYear = expYear.ifEmpty { null }, cvc = cvc.ifEmpty { null },424+ cardNickname = lookup(strings, nicknameIdx), cardNetwork = network,425+ tags = tags, notes = notes,426+ createdAt = createdAt, modifiedAt = modifiedAt, deletedAt = deletedAt,427+ )428+ }429+ ENTRY_TYPE_PASSKEY -> {430+ val blobLen = r.u32().toInt()431+ val blob = r.read(blobLen)432+ decodePasskeyBlob(id, title, createdAt, modifiedAt, deletedAt, blob)433+ }434+ else -> throw PeachScriptException("UNKNOWN_ENTRY_TYPE:$type")435+ }436+ }437+438+ private fun writeTags(w: BinaryWriter, table: StringTable, tags: List<String>) {439+ val n = minOf(tags.size, 0xff)440+ w.u8(n)441+ for (i in 0 until n) w.u16(table.intern(tags[i]))442+ }443+444+ private fun writeStrings(w: BinaryWriter, table: StringTable, items: List<String>) {445+ val n = minOf(items.size, 0xff)446+ w.u8(n)447+ for (i in 0 until n) w.u16(table.intern(items[i]))448+ }449+450+ private fun readTags(r: BinaryReader, strings: List<String?>): List<String> {451+ val n = r.u8()452+ val out = ArrayList<String>(n)453+ for (i in 0 until n) lookup(strings, r.u16())?.let { out.add(it) }454+ return out455+ }456+457+ private fun readStrings(r: BinaryReader, strings: List<String?>): List<String> = readTags(r, strings)458+459+ private fun entryTypeByte(entry: VaultEntry): Int {460+ if (entry.passkey != null) return ENTRY_TYPE_PASSKEY461+ return when (entry.type) {462+ "note" -> ENTRY_TYPE_NOTE463+ "card" -> ENTRY_TYPE_CARD464+ "passkey" -> ENTRY_TYPE_PASSKEY465+ else -> ENTRY_TYPE_LOGIN466+ }467+ }468+469+ private fun networkToByte(network: String?): Int {470+ if (network.isNullOrEmpty()) return 0xff471+ val idx = NETWORK_VALUES.indexOf(network)472+ return if (idx >= 0) idx else NETWORK_VALUES.indexOf("unknown")473+ }474+475+ private fun networkFromByte(b: Int): String? {476+ if (b == 0xff) return null477+ return NETWORK_VALUES.getOrNull(b) ?: "unknown"478+ }479+480+ private fun deriveLast4(entry: VaultEntry): String? {481+ val digits = entry.cardNumber?.filter { it.isDigit() } ?: return null482+ return if (digits.length >= 4) digits.takeLast(4) else digits.ifEmpty { null }483+ }484+485+ // ---- passkey JSON blob (peachPayload.ts:552-596) ----------------------486+ // [PLATFORM GAP] Android's PasskeyData has no privateKeyJwk field, so a487+ // browser passkey's private key is dropped on import. All other passkey +488+ // login fields round-trip. See BROWSER-SPEC Implementation Notes.489+490+ private fun encodePasskeyBlob(entry: VaultEntry): ByteArray {491+ val pk = entry.passkey492+ val obj = buildJsonObject {493+ putIfPresent("rpId", pk?.rpId ?: entry.rpId)494+ putIfPresent("rpName", pk?.rpName ?: entry.rpName)495+ putIfPresent("credentialId", pk?.credentialId ?: entry.credentialId)496+ putIfPresent("publicKeyCose", pk?.publicKeyCose ?: entry.publicKeyCose)497+ putIfPresent("userHandle", pk?.userHandle ?: entry.userHandle)498+ putIfPresent("userName", pk?.userName ?: entry.userName)499+ putIfPresent("userDisplayName", pk?.userDisplayName ?: entry.userDisplayName)500+ putIfPresent("algorithm", (pk?.algorithm ?: entry.algorithm))501+ putIfPresent("signCount", (pk?.signCount ?: entry.signCount))502+ putIfPresent("aaguid", pk?.aaguid ?: entry.aaguid)503+ putIfPresent("backupEligible", pk?.backupEligible ?: entry.backupEligible)504+ putIfPresent("backupState", pk?.backupState ?: entry.backupState)505+ putIfPresent("lastUsedAt", entry.lastUsedAt)506+ // Login fields carried alongside a passkey-bearing login entry.507+ putIfPresent("password", entry.password)508+ putIfPresent("url", entry.url)509+ putIfPresent("username", entry.username)510+ putIfPresent("email", entry.email)511+ putIfPresent("totp", entry.totp)512+ putIfPresent("notes", entry.notes)513+ if (!entry.tags.isNullOrEmpty()) {514+ put("tags", buildJsonArray { entry.tags.forEach { add(JsonPrimitive(it)) } })515+ }516+ }517+ return json.encodeToString(JsonObject.serializer(), obj).toByteArray(Charsets.UTF_8)518+ }519+520+ private fun decodePasskeyBlob(521+ id: String, title: String, createdAt: Long, modifiedAt: Long, deletedAt: Long?, blob: ByteArray,522+ ): VaultEntry {523+ val obj = json.parseToJsonElement(String(blob, Charsets.UTF_8)).jsonObject524+ fun str(k: String) = obj[k]?.jsonPrimitive?.contentOrNull525+ fun intf(k: String) = obj[k]?.jsonPrimitive?.intOrNull526+ fun longf(k: String) = obj[k]?.jsonPrimitive?.longOrNull527+ fun boolf(k: String) = obj[k]?.jsonPrimitive?.booleanOrNull528+ val tags = obj["tags"]?.jsonArray?.mapNotNull { it.jsonPrimitive.contentOrNull }529+ val credentialId = str("credentialId")530+ val publicKeyCose = str("publicKeyCose")531+ val rpId = str("rpId")532+ val userHandle = str("userHandle")533+ val userName = str("userName")534+ val passkey = if (credentialId != null && publicKeyCose != null && rpId != null &&535+ userHandle != null && userName != null) {536+ PasskeyData(537+ credentialId = credentialId, publicKeyCose = publicKeyCose, rpId = rpId,538+ rpName = str("rpName"), userHandle = userHandle, userName = userName,539+ userDisplayName = str("userDisplayName"), algorithm = intf("algorithm") ?: -7,540+ signCount = intf("signCount") ?: 0, aaguid = str("aaguid"),541+ backupEligible = boolf("backupEligible") ?: false, backupState = boolf("backupState") ?: false,542+ )543+ } else null544+ return VaultEntry(545+ id = id, type = "passkey", title = title,546+ url = str("url"), username = str("username"), email = str("email"),547+ password = str("password"), totp = str("totp"), notes = str("notes"), tags = tags,548+ createdAt = createdAt, modifiedAt = modifiedAt, deletedAt = deletedAt,549+ passkey = passkey, lastUsedAt = longf("lastUsedAt"),550+ rpId = rpId, rpName = str("rpName"), credentialId = credentialId,551+ publicKeyCose = publicKeyCose, userHandle = userHandle, userName = userName,552+ userDisplayName = str("userDisplayName"), algorithm = intf("algorithm"),553+ aaguid = str("aaguid"), backupEligible = boolf("backupEligible"),554+ backupState = boolf("backupState"), signCount = intf("signCount"),555+ )556+ }557+558+ // ---- uuid (peachPayload.ts:792-806) -----------------------------------559+560+ fun uuidToBytes(uuid: String): ByteArray {561+ val hex = uuid.replace("-", "")562+ if (hex.length != 32) throw PeachScriptException("UUID_FORMAT")563+ return ByteArray(16) { i -> hex.substring(i * 2, i * 2 + 2).toInt(16).toByte() }564+ }565+566+ fun bytesToUuid(bytes: ByteArray): String {567+ if (bytes.size != 16) throw PeachScriptException("UUID_LENGTH")568+ val hex = bytes.joinToString("") { "%02x".format(it) }569+ return "${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-" +570+ "${hex.substring(16, 20)}-${hex.substring(20)}"571+ }572+573+ // ---- crypto / hashing -------------------------------------------------574+575+ private fun deriveKey(passphrase: String, salt: ByteArray): ByteArray {576+ // Argon2id over the UTF-8 BYTES of the passphrase, matching the browser's577+ // hash-wasm KDF input (avoids the MF-4 UTF-16 divergence in this path).578+ val params = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)579+ .withSalt(salt)580+ .withParallelism(ARGON2_PARALLELISM)581+ .withMemoryAsKB(ARGON2_MEMORY_KIB)582+ .withIterations(ARGON2_ITERATIONS)583+ .build()584+ val gen = Argon2BytesGenerator().apply { init(params) }585+ val out = ByteArray(32)586+ gen.generateBytes(passphrase.toByteArray(Charsets.UTF_8), out)587+ return out588+ }589+590+ private fun aesGcmEncrypt(key: ByteArray, nonce: ByteArray, plaintext: ByteArray): ByteArray {591+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")592+ cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))593+ return cipher.doFinal(plaintext) // ciphertext || tag; no AAD (browser uses none)594+ }595+596+ private fun aesGcmDecrypt(key: ByteArray, nonce: ByteArray, ctTag: ByteArray): ByteArray {597+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")598+ cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))599+ return cipher.doFinal(ctTag)600+ }601+602+ private fun blake3Truncated(data: ByteArray): ByteArray {603+ val digest = Blake3Digest(256)604+ digest.update(data, 0, data.size)605+ val full = ByteArray(32)606+ digest.doFinal(full, 0)607+ return full.copyOfRange(0, CHECKSUM_LEN)608+ }609+610+ private fun padToNearestBucket(data: ByteArray): ByteArray {611+ val bucket = SIZE_BUCKETS.firstOrNull { it >= data.size }612+ var target = bucket ?: run {613+ var t = 262144614+ while (t < data.size) t *= 2615+ t616+ }617+ if (target == data.size) return data618+ return data.copyOf(target)619+ }620+621+ private fun constantTimeEqual(a: ByteArray, b: ByteArray): Boolean {622+ if (a.size != b.size) return false623+ var diff = 0624+ for (i in a.indices) diff = diff or (a[i].toInt() xor b[i].toInt())625+ return diff == 0626+ }627+628+ private fun concat(parts: List<ByteArray>): ByteArray {629+ val total = parts.sumOf { it.size }630+ val out = ByteArray(total)631+ var c = 0632+ for (p in parts) { System.arraycopy(p, 0, out, c, p.size); c += p.size }633+ return out634+ }635+636+ // ---- little/big-endian helpers ----------------------------------------637+638+ private fun writeU32LE(buf: ByteArray, off: Int, v: Long) {639+ buf[off] = (v and 0xff).toByte()640+ buf[off + 1] = ((v ushr 8) and 0xff).toByte()641+ buf[off + 2] = ((v ushr 16) and 0xff).toByte()642+ buf[off + 3] = ((v ushr 24) and 0xff).toByte()643+ }644+645+ private fun writeU32BE(buf: ByteArray, off: Int, v: Long) {646+ buf[off] = ((v ushr 24) and 0xff).toByte()647+ buf[off + 1] = ((v ushr 16) and 0xff).toByte()648+ buf[off + 2] = ((v ushr 8) and 0xff).toByte()649+ buf[off + 3] = (v and 0xff).toByte()650+ }651+652+ private fun readU32LE(buf: ByteArray, off: Int): Long {653+ return (buf[off].toLong() and 0xff) or654+ ((buf[off + 1].toLong() and 0xff) shl 8) or655+ ((buf[off + 2].toLong() and 0xff) shl 16) or656+ ((buf[off + 3].toLong() and 0xff) shl 24)657+ }658+659+ private fun readU32BE(buf: ByteArray, off: Int): Long {660+ return ((buf[off].toLong() and 0xff) shl 24) or661+ ((buf[off + 1].toLong() and 0xff) shl 16) or662+ ((buf[off + 2].toLong() and 0xff) shl 8) or663+ (buf[off + 3].toLong() and 0xff)664+ }665+666+ private class BinaryWriter {667+ private val out = ByteArrayOutputStream()668+ fun u8(v: Int) { out.write(v and 0xff) }669+ fun u16(v: Int) { out.write(v and 0xff); out.write((v ushr 8) and 0xff) }670+ fun u32(v: Long) {671+ out.write((v and 0xff).toInt()); out.write(((v ushr 8) and 0xff).toInt())672+ out.write(((v ushr 16) and 0xff).toInt()); out.write(((v ushr 24) and 0xff).toInt())673+ }674+ fun bytes(b: ByteArray) { out.write(b) }675+ fun lpString(value: String) {676+ val enc = value.toByteArray(Charsets.UTF_8)677+ if (enc.size > 0xff) throw PeachScriptException("STRING_TOO_LONG_U8")678+ u8(enc.size); bytes(enc)679+ }680+ fun toBytes(): ByteArray = out.toByteArray()681+ }682+683+ private class BinaryReader(private val data: ByteArray, start: Int) {684+ private var cursor = start685+ fun u8(): Int = data[cursor++].toInt() and 0xff686+ fun u16(): Int { val v = (data[cursor].toInt() and 0xff) or ((data[cursor + 1].toInt() and 0xff) shl 8); cursor += 2; return v }687+ fun u32(): Long {688+ val v = (data[cursor].toLong() and 0xff) or ((data[cursor + 1].toLong() and 0xff) shl 8) or689+ ((data[cursor + 2].toLong() and 0xff) shl 16) or ((data[cursor + 3].toLong() and 0xff) shl 24)690+ cursor += 4; return v691+ }692+ fun read(n: Int): ByteArray { val out = data.copyOfRange(cursor, cursor + n); cursor += n; return out }693+ fun lpString(): String = String(read(u8()), Charsets.UTF_8)694+ }695+696+ private fun JsonObjectBuilder.putIfPresent(key: String, value: String?) {697+ if (!value.isNullOrEmpty()) put(key, JsonPrimitive(value))698+ }699+ private fun JsonObjectBuilder.putIfPresent(key: String, value: Int?) {700+ if (value != null) put(key, JsonPrimitive(value))701+ }702+ private fun JsonObjectBuilder.putIfPresent(key: String, value: Long?) {703+ if (value != null) put(key, JsonPrimitive(value))704+ }705+ private fun JsonObjectBuilder.putIfPresent(key: String, value: Boolean?) {706+ if (value != null) put(key, JsonPrimitive(value))707+ }708+}app/drafts/MF1MF2/PeachScript.kt+53 −0
@@ -0,0 +1,53 @@1+package com.peachpasswords.vault2+3+/**4+ * PeachScript outer codec — maps each payload byte to one Private-Use-Area code5+ * point in U+E000..U+E0FF, and back. Byte-for-byte the browser's `peachScript.ts`:6+ * byte 0 → U+E000, byte 255 → U+E0FF. The bundled PeachScript font renders those7+ * 256 code points; outside Peach the string is unreadable boxes (intended).8+ */9+object PeachScript {10+ private const val BASE = 0xE00011+12+ /** Encode binary [bytes] to a PeachScript string (one code point per byte). */13+ fun encode(bytes: ByteArray): String {14+ val sb = StringBuilder(bytes.size)15+ for (b in bytes) sb.appendCodePoint(BASE + (b.toInt() and 0xff))16+ return sb.toString()17+ }18+19+ /**20+ * Decode a PeachScript string back to bytes. Throws on any code point outside21+ * U+E000..U+E0FF (edited / truncated / not PeachScript), matching the browser's22+ * INVALID_PEACHSCRIPT_CHARACTER.23+ */24+ fun decode(str: String): ByteArray {25+ val cps = str.codePoints().toArray()26+ val out = ByteArray(cps.size)27+ for (i in cps.indices) {28+ val cp = cps[i]29+ require(cp in BASE..(BASE + 0xff)) { "INVALID_PEACHSCRIPT_CHARACTER" }30+ out[i] = (cp - BASE).toByte()31+ }32+ return out33+ }34+35+ /** Strip all whitespace before decoding (browser `normalisePeachScript`). */36+ fun normalise(str: String): String = str.replace(Regex("\\s+"), "")37+38+ /**39+ * Cheap pre-flight: non-empty and every non-whitespace char is in the PUA40+ * range. Used to gate the import button without throwing.41+ */42+ fun isPeachScript(str: String): Boolean {43+ val t = normalise(str)44+ if (t.isEmpty()) return false45+ var i = 046+ while (i < t.length) {47+ val cp = t.codePointAt(i)48+ if (cp < BASE || cp > BASE + 0xff) return false49+ i += Character.charCount(cp)50+ }51+ return true52+ }53+}app/drafts/MF1MF2/PeachScriptExport.kt+24 −0
@@ -0,0 +1,24 @@1+package com.peachpasswords.ui.vault2+3+import com.peachpasswords.vault.PeachPayloadCodec4+import com.peachpasswords.vault.PeachScript5+import com.peachpasswords.vault.VaultEntry6+7+/**8+ * PeachScript export (MF-2) — writes the browser's PCHS binary payload9+ * (Argon2id + AES-256-GCM, zstd sections, BLAKE3 checksum, size-bucket padding,10+ * string-table entry packing) re-encoded into Private-Use-Area text. The output11+ * is importable by the browser extension and carries the full entry field set.12+ *13+ * The heavy lifting lives in [PeachPayloadCodec] (binary) and [PeachScript]14+ * (PUA codec); this object is just the export entry point the UI calls.15+ */16+object PeachScriptExport {17+18+ /**19+ * Encrypted PeachScript export of [entries], protected by [backupPassword].20+ * PeachScript is always encrypted (the browser format has no plaintext mode).21+ */22+ fun buildEncrypted(entries: List<VaultEntry>, backupPassword: String): String =23+ PeachScript.encode(PeachPayloadCodec.buildPayload(entries, backupPassword))24+}app/drafts/MF1MF2/PeachScriptImport.kt+52 −0
@@ -0,0 +1,52 @@1+package com.peachpasswords.ui.vault2+3+import com.peachpasswords.vault.PeachPayloadCodec4+import com.peachpasswords.vault.PeachScript5+import com.peachpasswords.vault.VaultEntry6+7+/**8+ * PeachScript import (MF-2) — parses the browser's PCHS binary payload back into9+ * full vault entries. The PUA text is decoded to bytes ([PeachScript.decode]),10+ * then [PeachPayloadCodec.parsePayload] decrypts (Argon2id + AES-256-GCM),11+ * verifies the BLAKE3 checksum, zstd-decompresses each section, and unpacks the12+ * entries — every field the browser exported (tags, card fields, canary, breach,13+ * timestamps, passkey) is preserved.14+ */15+object PeachScriptImport {16+17+ /** Outcome of decrypting + parsing an encrypted export. */18+ sealed interface DecryptResult {19+ data class Success(val entries: List<VaultEntry>) : DecryptResult20+ data object WrongPassword : DecryptResult21+ data object Corrupted : DecryptResult22+ }23+24+ /** Cheap sniff: does this look like PeachScript (PUA-encoded) text? */25+ fun looksLikePeachScript(text: String): Boolean = PeachScript.isPeachScript(text)26+27+ /** PeachScript is always encrypted (backup-password protected). */28+ fun isEncrypted(text: String): Boolean = looksLikePeachScript(text)29+30+ /**31+ * Decrypt a PeachScript export with the user's backup password and parse the32+ * inner entries. Maps [PeachPayloadCodec] errors to the UI's result states:33+ * a GCM tag mismatch (INVALID_PASSPHRASE) surfaces as "Incorrect backup34+ * password"; structural failures surface as corrupted.35+ */36+ fun decryptAndParse(text: String, backupPassword: String): DecryptResult {37+ val normalised = PeachScript.normalise(text)38+ if (!PeachScript.isPeachScript(normalised)) return DecryptResult.Corrupted39+ val bytes = try {40+ PeachScript.decode(normalised)41+ } catch (_: Exception) {42+ return DecryptResult.Corrupted43+ }44+ return try {45+ DecryptResult.Success(PeachPayloadCodec.parsePayload(bytes, backupPassword))46+ } catch (e: PeachPayloadCodec.PeachScriptException) {47+ if (e.message == "INVALID_PASSPHRASE") DecryptResult.WrongPassword else DecryptResult.Corrupted48+ } catch (_: Exception) {49+ DecryptResult.Corrupted50+ }51+ }52+}app/drafts/MF1MF2/PeachScriptTest.kt+185 −0
@@ -0,0 +1,185 @@1+package com.peachpasswords.vault2+3+import org.junit.Assert.assertEquals4+import org.junit.Assert.assertNotNull5+import org.junit.Assert.assertNull6+import org.junit.Assert.assertThrows7+import org.junit.Assert.assertTrue8+import org.junit.Test9+import java.util.Base6410+11+class PeachScriptTest {12+13+ private fun login() = VaultEntry(14+ id = "11111111-2222-3333-4444-555555555555", type = "login", title = "GitHub",15+ url = "https://github.com", username = "june", email = "[email protected]",16+ password = "hunter2-Σ-🔐", totp = "JBSWY3DPEHPK3PXP", tags = listOf("dev", "work"),17+ notes = "primary account", additionalUrls = listOf("https://gist.github.com"),18+ breach = 3, passwordChangedAt = 1_600_000_000_000,19+ canary = Canary(webhookUrl = "https://canary.example.com/hook", label = "tripwire"),20+ createdAt = 1_500_000_000_000, modifiedAt = 1_600_000_500_000,21+ )22+23+ private fun note() = VaultEntry(24+ id = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", type = "note", title = "そふと メモ 🌸",25+ notes = "日本語のノート\nsecond line", tags = listOf("personal"),26+ createdAt = 1_500_000_000_000, modifiedAt = 1_500_000_000_000,27+ )28+29+ private fun card() = VaultEntry(30+ id = "99999999-8888-7777-6666-555544443333", type = "card", title = "Visa",31+ cardholderName = "JUNE MOON", cardNumber = "4111111111111111", expMonth = "04",32+ expYear = "2030", cvc = "123", cardNickname = "daily", cardNetwork = "visa",33+ notes = "spending card", tags = listOf("finance"),34+ createdAt = 1_500_000_000_000, modifiedAt = 1_500_000_000_000,35+ )36+37+ // ── KAT: parse a REAL browser-produced PeachScript payload ──────────────38+ // Envelope generated by the browser's own buildPayload (/tmp/gen_peach3.mjs39+ // via vite SSR), proving Android decrypts + zstd-decompresses + unpacks the40+ // exact bytes the extension writes. This is the cross-platform import proof.41+ @Test fun parses_browser_produced_payload() {42+ val envelope = Base64.getDecoder().decode(BROWSER_FIXTURE_B64)43+ val entries = PeachPayloadCodec.parsePayload(envelope, "backup-pass-123")44+ assertEquals(3, entries.size)45+46+ val l = entries[0]47+ assertEquals("11111111-2222-3333-4444-555555555555", l.id)48+ assertEquals("login", l.type)49+ assertEquals("GitHub", l.title)50+ assertEquals("https://github.com", l.url)51+ assertEquals("june", l.username)52+ assertEquals("[email protected]", l.email)53+ assertEquals("hunter2-Σ-🔐", l.password)54+ assertEquals("JBSWY3DPEHPK3PXP", l.totp)55+ assertEquals(listOf("dev", "work"), l.tags)56+ assertEquals("primary account", l.notes)57+ assertEquals(listOf("https://gist.github.com"), l.additionalUrls)58+ assertEquals(3, l.breach)59+ assertEquals(1_600_000_000_000L, l.passwordChangedAt)60+ assertEquals("https://canary.example.com/hook", l.canary?.webhookUrl)61+ assertEquals("tripwire", l.canary?.label)62+ assertEquals(1_500_000_000_000L, l.createdAt)63+ assertEquals(1_600_000_500_000L, l.modifiedAt)64+65+ val n = entries[1]66+ assertEquals("note", n.type)67+ assertEquals("そふと メモ 🌸", n.title)68+ assertEquals("日本語のノート\nsecond line", n.notes)69+ assertEquals(listOf("personal"), n.tags)70+71+ val c = entries[2]72+ assertEquals("card", c.type)73+ assertEquals("JUNE MOON", c.cardholderName)74+ assertEquals("4111111111111111", c.cardNumber)75+ assertEquals("04", c.expMonth)76+ assertEquals("2030", c.expYear)77+ assertEquals("123", c.cvc)78+ assertEquals("daily", c.cardNickname)79+ assertEquals("visa", c.cardNetwork)80+ assertEquals("spending card", c.notes)81+ assertEquals(listOf("finance"), c.tags)82+ }83+84+ // ── Android self round-trip: all fields, all entry types ────────────────85+ @Test fun self_round_trips_all_fields() {86+ val input = listOf(login(), note(), card())87+ val out = PeachPayloadCodec.buildPayload(input, "pw-123")88+ val back = PeachPayloadCodec.parsePayload(out, "pw-123")89+ assertEquals(3, back.size)90+91+ val l = back[0]92+ assertEquals(login().id, l.id)93+ assertEquals("hunter2-Σ-🔐", l.password)94+ assertEquals(listOf("dev", "work"), l.tags)95+ assertEquals(3, l.breach)96+ assertEquals(1_600_000_000_000L, l.passwordChangedAt)97+ assertEquals("tripwire", l.canary?.label)98+ assertEquals(listOf("https://gist.github.com"), l.additionalUrls)99+ assertEquals(1_500_000_000_000L, l.createdAt)100+ assertEquals(1_600_000_500_000L, l.modifiedAt)101+102+ val c = back[2]103+ assertEquals("4111111111111111", c.cardNumber)104+ assertEquals("visa", c.cardNetwork)105+ assertEquals("123", c.cvc)106+ }107+108+ // ── Cross-direction: Android export parsed by the browser's algorithm ───109+ // (Verified manually via /tmp; here we at least prove a browser-shaped110+ // envelope layout: salt(16)+nonce(12)+ct+tag, padded to a size bucket.)111+ @Test fun export_envelope_has_browser_shape() {112+ val out = PeachPayloadCodec.buildPayload(listOf(login()), "pw")113+ // salt(16)+nonce(12)+tag(16) overhead; payload padded to >= 1024 bucket,114+ // so the ciphertext alone is at least one bucket.115+ assertTrue(out.size >= 16 + 12 + 1024 + 16)116+ }117+118+ @Test fun empty_vault_round_trips() {119+ val out = PeachPayloadCodec.buildPayload(emptyList(), "pw")120+ assertEquals(0, PeachPayloadCodec.parsePayload(out, "pw").size)121+ }122+123+ @Test fun unicode_fields_round_trip() {124+ val out = PeachPayloadCodec.buildPayload(listOf(note()), "pw")125+ val n = PeachPayloadCodec.parsePayload(out, "pw").single()126+ assertEquals("そふと メモ 🌸", n.title)127+ assertEquals("日本語のノート\nsecond line", n.notes)128+ }129+130+ @Test fun wrong_password_is_invalid_passphrase() {131+ val out = PeachPayloadCodec.buildPayload(listOf(login()), "right-pw")132+ val ex = assertThrows(PeachPayloadCodec.PeachScriptException::class.java) {133+ PeachPayloadCodec.parsePayload(out, "wrong-pw")134+ }135+ assertEquals("INVALID_PASSPHRASE", ex.message)136+ }137+138+ @Test fun pua_codec_round_trips() {139+ val bytes = ByteArray(256) { it.toByte() }140+ val text = PeachScript.encode(bytes)141+ assertTrue(PeachScript.isPeachScript(text))142+ assertEquals(256, text.codePointCount(0, text.length))143+ assertTrue(bytes.contentEquals(PeachScript.decode(text)))144+ // Whitespace is stripped before decode.145+ assertTrue(bytes.contentEquals(PeachScript.decode(PeachScript.normalise(" $text \n"))))146+ }147+148+ @Test fun passkey_core_fields_round_trip() {149+ val pk = VaultEntry(150+ id = "12121212-3434-5656-7878-909090909090", type = "passkey", title = "Passkey",151+ passkey = PasskeyData(152+ credentialId = "cred-abc", publicKeyCose = "cose-xyz", rpId = "example.com",153+ rpName = "Example", userHandle = "uh-1", userName = "june", userDisplayName = "June",154+ ),155+ createdAt = 1_500_000_000_000, modifiedAt = 1_500_000_000_000,156+ )157+ val out = PeachPayloadCodec.buildPayload(listOf(pk), "pw")158+ val back = PeachPayloadCodec.parsePayload(out, "pw").single()159+ assertEquals("passkey", back.type)160+ assertNotNull(back.passkey)161+ assertEquals("cred-abc", back.passkey?.credentialId)162+ assertEquals("example.com", back.passkey?.rpId)163+ assertEquals("june", back.passkey?.userName)164+ }165+166+ @Test fun full_export_import_via_peachscript_text() {167+ val text = com.peachpasswords.ui.vault.PeachScriptExport.buildEncrypted(listOf(login(), card()), "bp")168+ assertTrue(com.peachpasswords.ui.vault.PeachScriptImport.looksLikePeachScript(text))169+ val r = com.peachpasswords.ui.vault.PeachScriptImport.decryptAndParse(text, "bp")170+ assertTrue(r is com.peachpasswords.ui.vault.PeachScriptImport.DecryptResult.Success)171+ r as com.peachpasswords.ui.vault.PeachScriptImport.DecryptResult.Success172+ assertEquals(2, r.entries.size)173+ assertEquals("hunter2-Σ-🔐", r.entries[0].password)174+ assertNull(175+ (com.peachpasswords.ui.vault.PeachScriptImport.decryptAndParse(text, "nope")176+ as? com.peachpasswords.ui.vault.PeachScriptImport.DecryptResult.Success)?.entries,177+ )178+ }179+180+ companion object {181+ // Real browser PeachScript envelope (base64) — see /tmp/gen_peach3.mjs.182+ private const val BROWSER_FIXTURE_B64 =183+ "RTRXPzyl+oHgPhKUK3DCdab09Rb+zMF5Dfphcydo2qzHWqE2PfJHdLEalnhL7jSOxCiowSjIYmrbkCLP2qCLeSHwceeSD9RhBx04bHNoc5J/ml/sXrY/7BFIZizNk5dlDt921VSQNhaNEzYmP/fKkYWjFpz+OOhUCBTUgt+WtCwa5mf8Ctf6R1UPkh21Fu3pwwb/IQjhFvij+CYgS+1skXtogw0iYTrNbSLMIxMsIKvXytFGOp4IGWbbATO/7vFPXnwc2Zh9gOkbUbVM8D7dBUBV+hTodCNHO8PsvxzPAQL0io4/t/Iu60x91eiB8+TTJEwQy9d/aNGM0hgAZq5TzBj4IpYW2tGwfMqRwhuQz07e7SrcL3ggJVlrOf+rph0UnzgdRuCeMS67/83IhNg0UUCftSqdBdQFeqE3UNLavRohLO4AaqTLR1i4UfDApjL79MVtqjztfj8xTJr+zf1SH0BZ0/6PCyIXnm526lxk4WALgJiXu1FWoIXP3xGjs/ZAe1t7RONiVak51kTLs7djQMh6WLMGxW8KVaFAu1a+jG3Zus9Ynn9FBpowipW1E4rnUnytqUzh/udY0q4Y8nJvavyD3hO5xEbHkslfbPSYqxrrGaL3OFb9llKoLyZSiYGB5p+/QM7xn5DFZ3VOtx90xf9wVEe2Uhfhq0XfQUqT384kWp8Ujlyq4pFB6nIe3f3e8C2pE+fJMou0Q2RFvotx/F56T3Ul2d0fpoN7ucyqJC94Fo6B8Peh1u5oxu5njPZEjRSUl2eBt3K8Aval7d9yYbm7I1ecUSLNJ+nHphL/DMYKL2CYQd90pdyfOeDgRCt4WML8z6hjTtW6uPUKDkd5WVu0qp2ktuzawolWi7aah1BnTZMwH2/jm6bPlLNE5r/bFwr1MAgNscjpwwa0DXTfMovbgJHLxEp6/0vpxuYcCfoRoinpTErt7Eafz2rQqw7mEit3eoUZ1Nv+AdfvBC3PN0pB/L5gdzi/cCrEtVCX2A/1NkhV91EKnx0tCQnkjZyovd9ZhKb/QNgzA6v7lugua4e0foRJJBSqwcJJ4Sr7CUXsK5/yuwXsYcJ0I+yTwiHoe4WA5I/go61xvSPsDV/5aXyS0bJbAa5DusVd/SnUM1QFFwHjOfwGUlU/PupZSr2zvZdds+ZX8B8u16L55gZE8xOdOUq7tAd25Gd3v0r6sSwcYu1amjhbfQlgw2RBQBWHmMZ8Jn715A9RblOMW95EqVu8AhG1Jfl547WdahfgC93Aw3nlT39sUBpzqRwa54N6Q9RHc81uC1q+xtU7CiTIMWJm1qqnVjP89MWMnRpYjRXOYBOop73uHh4BjomUlEzXEXmtJiaMq1nsqW85k+FKnO0bF/rGVzmFvHWuBx4cWYic9e8tmUalxdJxDsqFr+dh3h3Fp/YD9oOIT2XD"184+ }185+}app/drafts/MF1MF2/gen_peach_fixture.mjs+51 −0
@@ -0,0 +1,51 @@1+import { createServer } from "/Users/june/projects/peach-browser/node_modules/vite/dist/node/index.js";2+3+const server = await createServer({4+ root: "/Users/june/projects/peach-browser",5+ configFile: false,6+ logLevel: "silent",7+ server: { middlewareMode: true, hmr: false },8+});9+10+try {11+ const { buildPayload, parsePayload } = await server.ssrLoadModule("/src/crypto/peachPayload.ts");12+13+ const entries = [14+ {15+ id: "11111111-2222-3333-4444-555555555555",16+ type: "login", title: "GitHub", url: "https://github.com",17+ username: "june", email: "[email protected]", password: "hunter2-Σ-🔐",18+ totp: "JBSWY3DPEHPK3PXP", tags: ["dev", "work"], notes: "primary account",19+ additionalUrls: ["https://gist.github.com"], breach: 3,20+ passwordChangedAt: 1_600_000_000_000,21+ canary: { webhookUrl: "https://canary.example.com/hook", label: "tripwire" },22+ createdAt: 1_500_000_000_000, modifiedAt: 1_600_000_500_000,23+ },24+ {25+ id: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",26+ type: "note", title: "そふと メモ 🌸",27+ notes: "日本語のノート\nsecond line", tags: ["personal"],28+ createdAt: 1_500_000_000_000, modifiedAt: 1_500_000_000_000,29+ },30+ {31+ id: "99999999-8888-7777-6666-555544443333",32+ type: "card", title: "Visa", cardholderName: "JUNE MOON",33+ cardNumber: "4111111111111111", expMonth: "04", expYear: "2030", cvc: "123",34+ cardNickname: "daily", network: "visa", last4: "1111",35+ notes: "spending card", tags: ["finance"],36+ createdAt: 1_500_000_000_000, modifiedAt: 1_500_000_000_000,37+ },38+ ];39+40+ const passphrase = "backup-pass-123";41+ const envelope = await buildPayload({ entries, settings: {}, passphrase });42+ const reparsed = await parsePayload(envelope, passphrase);43+44+ console.log(JSON.stringify({45+ passphrase,46+ envelopeB64: Buffer.from(envelope).toString("base64"),47+ entries: reparsed.entries,48+ }, null, 2));49+} finally {50+ await server.close();51+}app/src/main/java/com/peachpasswords/ui/vault/ImportScreen.kt+46 −23
@@ -69,10 +69,16 @@6969 /** How parsed entries land in the vault on confirm. */7070 enum class ImportMode { MERGE, REPLACE }7171 72-/** A staged, parsed import ready for preview + confirm. */72+/**73+ * A staged, parsed import ready for preview + confirm. [entries] is the74+ * ParsedEntry projection used by the preview UI (shared with CSV). [fullEntries]75+ * is set only for PeachScript, carrying the complete VaultEntry field set so the76+ * import preserves tags, card fields, canary, breach, timestamps, etc.77+ */7378 data class ImportPreview(7479 val sourceLabel: String,7580 val entries: List<ParsedEntry>,81+ val fullEntries: List<VaultEntry>? = null,7682 )7783 7884 sealed interface ImportUiState {@@ -129,17 +135,25 @@129135 _state.value = ImportUiState.Working130136 viewModelScope.launch {131137 val result = withContext(Dispatchers.Default) {132- if (PeachScriptImport.isEncrypted(trimmed)) {133- PeachScriptImport.decryptAndParse(trimmed, backupPassword)134- } else {135- val entries = PeachScriptImport.parsePlaintext(trimmed)136- if (entries.isEmpty()) PeachScriptImport.DecryptResult.Corrupted137- else PeachScriptImport.DecryptResult.Success(entries)138- }138+ PeachScriptImport.decryptAndParse(trimmed, backupPassword)139139 }140140 _state.value = when (result) {141141 is PeachScriptImport.DecryptResult.Success ->142- ImportUiState.Preview(ImportPreview("PeachScript", result.entries))142+ if (result.entries.isEmpty()) {143+ ImportUiState.Failed(ImportErrors.NO_ENTRIES)144+ } else {145+ val parsed = result.entries.map { e ->146+ ParsedEntry(147+ title = e.title,148+ username = e.username ?: e.email,149+ password = e.password,150+ url = e.url,151+ notes = e.notes,152+ totp = e.totp,153+ )154+ }155+ ImportUiState.Preview(ImportPreview("PeachScript", parsed, result.entries))156+ }143157 PeachScriptImport.DecryptResult.WrongPassword ->144158 ImportUiState.Failed(ImportErrors.WRONG_PASSWORD)145159 PeachScriptImport.DecryptResult.Corrupted ->@@ -208,20 +222,29 @@208222 }209223 val now = System.currentTimeMillis()210224 var imported = 0211- for (p in preview.entries) {212- val draft = VaultEntry(213- id = "",214- type = "login",215- title = p.title,216- username = p.username,217- password = p.password,218- url = p.url,219- notes = p.notes,220- totp = p.totp,221- createdAt = now,222- modifiedAt = now,223- )224- runCatching { vault.addEntry(draft) }.onSuccess { imported++ }225+ val fulls = preview.fullEntries226+ if (fulls != null) {227+ // PeachScript: import the complete entries (all fields, all types).228+ // Re-id so an import can never overwrite an existing entry.229+ for (e in fulls) {230+ runCatching { vault.addEntry(e.copy(id = "")) }.onSuccess { imported++ }231+ }232+ } else {233+ for (p in preview.entries) {234+ val draft = VaultEntry(235+ id = "",236+ type = "login",237+ title = p.title,238+ username = p.username,239+ password = p.password,240+ url = p.url,241+ notes = p.notes,242+ totp = p.totp,243+ createdAt = now,244+ modifiedAt = now,245+ )246+ runCatching { vault.addEntry(draft) }.onSuccess { imported++ }247+ }225248 }226249 _state.value = ImportUiState.Done(imported)227250 } catch (e: Exception) {app/src/main/java/com/peachpasswords/ui/vault/PeachScriptExport.kt+12 −129
@@ -1,141 +1,24 @@11 package com.peachpasswords.ui.vault22 3-import com.peachpasswords.vault.VaultCrypto3+import com.peachpasswords.vault.PeachPayloadCodec4+import com.peachpasswords.vault.PeachScript45 import com.peachpasswords.vault.VaultEntry5-import java.util.Base6466 77 /**8- * Pure-Kotlin serialisation for PeachScript exports (spec C2 PeachScript sub-view).8+ * PeachScript export (MF-2) — writes the browser's PCHS binary payload9+ * (Argon2id + AES-256-GCM, zstd sections, BLAKE3 checksum, size-bucket padding,10+ * string-table entry packing) re-encoded into Private-Use-Area text. The output11+ * is importable by the browser extension and carries the full entry field set.912 *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.13+ * The heavy lifting lives in [PeachPayloadCodec] (binary) and [PeachScript]14+ * (PUA codec); this object is just the export entry point the UI calls.3815 */3916 object PeachScriptExport {4017 41- /** Format version marker emitted as `"peachscript": 1`. */42- private const val FORMAT_VERSION = 143-44- // Standard (not URL-safe) base64, matching the decoder in PeachScriptImport.45- private val b64 = Base64.getEncoder()46-4718 /**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.19+ * Encrypted PeachScript export of [entries], protected by [backupPassword].20+ * PeachScript is always encrypted (the browser format has no plaintext mode).5521 */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- }69-70- /**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- }85-86- val saltB64 = b64.encodeToString(salt)87- val blobB64 = b64.encodeToString(blob)88-89- 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- }99-100- 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- }110-111- /**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- }121-122- /** 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- }22+ fun buildEncrypted(entries: List<VaultEntry>, backupPassword: String): String =23+ PeachScript.encode(PeachPayloadCodec.buildPayload(entries, backupPassword))14124 }app/src/main/java/com/peachpasswords/ui/vault/PeachScriptImport.kt+30 −209
@@ -1,231 +1,52 @@11 package com.peachpasswords.ui.vault22 3-import com.peachpasswords.vault.VaultCrypto4-import java.util.Base643+import com.peachpasswords.vault.PeachPayloadCodec4+import com.peachpasswords.vault.PeachScript5+import com.peachpasswords.vault.VaultEntry56 67 /**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.8+ * PeachScript import (MF-2) — parses the browser's PCHS binary payload back into9+ * full vault entries. The PUA text is decoded to bytes ([PeachScript.decode]),10+ * then [PeachPayloadCodec.parsePayload] decrypts (Argon2id + AES-256-GCM),11+ * verifies the BLAKE3 checksum, zstd-decompresses each section, and unpacks the12+ * entries — every field the browser exported (tags, card fields, canary, breach,13+ * timestamps, passkey) is preserved.3814 */3915 object PeachScriptImport {4016 41- /** Magic marker key any PeachScript JSON object must carry. */42- private const val MARKER = "\"peachscript\""43-44- /**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"50-51- /**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- }59-60- /** True when the payload declares itself encrypted (`"encrypted": true`). */61- fun isEncrypted(text: String): Boolean =62- Regex("\"encrypted\"\\s*:\\s*true").containsMatchIn(text)63-64- /**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- }84-8517 /** Outcome of decrypting + parsing an encrypted export. */8618 sealed interface DecryptResult {87- data class Success(val entries: List<ParsedEntry>) : DecryptResult19+ data class Success(val entries: List<VaultEntry>) : DecryptResult8820 data object WrongPassword : DecryptResult8921 data object Corrupted : DecryptResult9022 }9123 24+ /** Cheap sniff: does this look like PeachScript (PUA-encoded) text? */25+ fun looksLikePeachScript(text: String): Boolean = PeachScript.isPeachScript(text)26+27+ /** PeachScript is always encrypted (backup-password protected). */28+ fun isEncrypted(text: String): Boolean = looksLikePeachScript(text)29+9230 /**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].31+ * Decrypt a PeachScript export with the user's backup password and parse the32+ * inner entries. Maps [PeachPayloadCodec] errors to the UI's result states:33+ * a GCM tag mismatch (INVALID_PASSPHRASE) surfaces as "Incorrect backup34+ * password"; structural failures surface as corrupted.10735 */10836 fun decryptAndParse(text: String, backupPassword: String): DecryptResult {109- val saltB64 = jsonRawString(text, "salt") ?: return DecryptResult.Corrupted110- val blobB64 = jsonRawString(text, "blob") ?: return DecryptResult.Corrupted111-112- 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) {37+ val normalised = PeachScript.normalise(text)38+ if (!PeachScript.isPeachScript(normalised)) return DecryptResult.Corrupted39+ val bytes = try {40+ PeachScript.decode(normalised)41+ } catch (_: Exception) {11742 return DecryptResult.Corrupted11843 }119-120- val key = VaultCrypto.deriveKey(backupPassword, salt)121- val plaintext = try {122- VaultCrypto.decrypt(blob, key, PEACHSCRIPT_AAD)44+ return try {45+ DecryptResult.Success(PeachPayloadCodec.parsePayload(bytes, backupPassword))46+ } catch (e: PeachPayloadCodec.PeachScriptException) {47+ if (e.message == "INVALID_PASSPHRASE") DecryptResult.WrongPassword else DecryptResult.Corrupted12348 } 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)49+ DecryptResult.Corrupted12950 }130-131- val json = String(plaintext, Charsets.UTF_8)132- val entries = parsePlaintext(json)133- return if (entries.isEmpty()) DecryptResult.Corrupted else DecryptResult.Success(entries)134- }135-136- // ---- Minimal JSON helpers (shared shape with CsvImport) ----------------137-138- 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- }162-163- 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- }187-188- 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- }193-194- /** 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- }200-201- 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()23051 }23152 }app/src/main/java/com/peachpasswords/vault/PeachPayloadCodec.kt+708 −0
@@ -0,0 +1,708 @@1+package com.peachpasswords.vault2+3+import com.github.luben.zstd.Zstd4+import org.bouncycastle.crypto.digests.Blake3Digest5+import org.bouncycastle.crypto.generators.Argon2BytesGenerator6+import org.bouncycastle.crypto.params.Argon2Parameters7+import java.io.ByteArrayOutputStream8+import java.security.SecureRandom9+import javax.crypto.Cipher10+import javax.crypto.spec.GCMParameterSpec11+import javax.crypto.spec.SecretKeySpec12+import kotlinx.serialization.json.Json13+import kotlinx.serialization.json.JsonObject14+import kotlinx.serialization.json.JsonObjectBuilder15+import kotlinx.serialization.json.JsonPrimitive16+import kotlinx.serialization.json.add17+import kotlinx.serialization.json.booleanOrNull18+import kotlinx.serialization.json.buildJsonArray19+import kotlinx.serialization.json.buildJsonObject20+import kotlinx.serialization.json.contentOrNull21+import kotlinx.serialization.json.intOrNull22+import kotlinx.serialization.json.jsonArray23+import kotlinx.serialization.json.jsonObject24+import kotlinx.serialization.json.jsonPrimitive25+import kotlinx.serialization.json.longOrNull26+27+/**28+ * PeachScript binary payload (`PCHS`) — a byte-for-byte port of the browser's29+ * `peachPayload.ts` (MF-2). Produces and consumes the encrypted envelope30+ * `[ salt(16) | nonce(12) | ciphertext | tag(16) ]` whose plaintext is31+ * `[ FORMAT_V3 | inner_len(LE) | inner | zero-pad-to-bucket ]`,32+ * `inner = [ body | blake3(body)[0..4) ]`,33+ * `body = [ MAGIC "PCHS"(BE) | VERSION | sectionCount | reserved(2) | section* ]`,34+ * each section `[ type | rawLen(LE) | compLen(LE) | zstd(level 19) ]`.35+ *36+ * The output of [buildPayload] is importable by the browser, and [parsePayload]37+ * reads browser-produced payloads. Verified by a real browser-fixture KAT38+ * (PeachScriptTest). Library notes are in app/drafts/MF1MF2/BROWSER-SPEC.md.39+ */40+object PeachPayloadCodec {41+42+ // ---- header / section constants (peachPayload.ts:48-124) --------------43+ private const val MAGIC = 0x50434853 // "PCHS" big-endian44+ private const val VERSION = 0x0145+ private const val HEADER_LEN = 846+ private const val CHECKSUM_LEN = 447+ private const val SALT_LEN = 1648+ private const val NONCE_LEN = 1249+ private const val TAG_LEN = 1650+51+ private val SIZE_BUCKETS = intArrayOf(1024, 4096, 16384, 65536, 262144)52+53+ private const val FORMAT_V2 = 0x0254+ private const val FORMAT_V3 = 0x0355+56+ private const val ARGON2_MEMORY_KIB = 6553657+ private const val ARGON2_ITERATIONS = 358+ private const val ARGON2_PARALLELISM = 459+60+ private const val SECTION_ENTRIES = 0x0161+ private const val SECTION_SETTINGS = 0x0262+ private const val SECTION_LICENSE = 0x0363+ private const val SECTION_RECALL = 0x0464+ private const val SECTION_DECLINED_CARDS = 0x0565+66+ private const val ENTRY_TYPE_LOGIN = 0x0167+ private const val ENTRY_TYPE_NOTE = 0x0268+ private const val ENTRY_TYPE_CARD = 0x0369+ private const val ENTRY_TYPE_PASSKEY = 0x0470+71+ private const val F_HAS_TOTP = 1 shl 072+ private const val F_HAS_TAGS = 1 shl 173+ private const val F_HAS_NOTES = 1 shl 274+ private const val F_HAS_CANARY = 1 shl 375+ private const val F_HAS_PWCHANGED = 1 shl 476+ private const val F_HAS_BREACH = 1 shl 577+ private const val F_HAS_ADDITIONAL_URLS = 1 shl 678+ private const val F_HAS_DELETED = 1 shl 779+80+ private const val F2_HAS_EMAIL = 1 shl 081+82+ private val NETWORK_VALUES = listOf("visa", "mastercard", "amex", "discover", "unknown")83+84+ private const val ZSTD_LEVEL = 1985+ private val secureRandom = SecureRandom()86+ private val json = Json { ignoreUnknownKeys = true; encodeDefaults = false }87+88+ class PeachScriptException(message: String) : Exception(message)89+90+ // ---- public API -------------------------------------------------------91+92+ /** Build the encrypted envelope `salt||nonce||ct||tag` from [entries]. */93+ fun buildPayload(entries: List<VaultEntry>, passphrase: String): ByteArray {94+ // sectionCount = 1 (ENTRIES). The browser also emits SETTINGS etc.; Android95+ // export carries entries only — a valid payload the browser reads (it skips96+ // absent sections). See BROWSER-SPEC §B2.11.97+ val entriesRaw = encodeEntriesSection(entries)98+ val sections = listOf(buildSection(SECTION_ENTRIES, entriesRaw))99+100+ val header = ByteArray(HEADER_LEN)101+ writeU32BE(header, 0, MAGIC.toLong())102+ header[4] = VERSION.toByte()103+ header[5] = sections.size.toByte()104+ // bytes 6,7 reserved (zero)105+106+ val body = concat(listOf(header) + sections)107+ val checksum = blake3Truncated(body)108+ val inner = concat(listOf(body, checksum))109+110+ val header5 = ByteArray(5)111+ header5[0] = FORMAT_V3.toByte()112+ writeU32LE(header5, 1, inner.size.toLong())113+ val wrapped = padToNearestBucket(concat(listOf(header5, inner)))114+115+ val salt = ByteArray(SALT_LEN).also(secureRandom::nextBytes)116+ val nonce = ByteArray(NONCE_LEN).also(secureRandom::nextBytes)117+ val key = deriveKey(passphrase, salt)118+ return try {119+ val ctTag = aesGcmEncrypt(key, nonce, wrapped)120+ concat(listOf(salt, nonce, ctTag))121+ } finally {122+ key.fill(0)123+ }124+ }125+126+ /** Parse the encrypted envelope back to entries. Throws [PeachScriptException]. */127+ fun parsePayload(envelope: ByteArray, passphrase: String): List<VaultEntry> {128+ if (envelope.size < SALT_LEN + NONCE_LEN + TAG_LEN + HEADER_LEN + CHECKSUM_LEN) {129+ throw PeachScriptException("PAYLOAD_TOO_SHORT")130+ }131+ val salt = envelope.copyOfRange(0, SALT_LEN)132+ val nonce = envelope.copyOfRange(SALT_LEN, SALT_LEN + NONCE_LEN)133+ val ctTag = envelope.copyOfRange(SALT_LEN + NONCE_LEN, envelope.size)134+135+ val key = deriveKey(passphrase, salt)136+ val decrypted = try {137+ aesGcmDecrypt(key, nonce, ctTag)138+ } catch (_: Exception) {139+ throw PeachScriptException("INVALID_PASSPHRASE")140+ } finally {141+ key.fill(0)142+ }143+144+ // Detect padded v2/v3 format: leading FORMAT byte + 4-byte LE inner length.145+ val inner: ByteArray146+ if (decrypted.size >= 5 && (decrypted[0].toInt() == FORMAT_V2 || decrypted[0].toInt() == FORMAT_V3)) {147+ val innerLen = readU32LE(decrypted, 1).toInt()148+ if (5 + innerLen > decrypted.size) throw PeachScriptException("PAYLOAD_TOO_SHORT")149+ inner = decrypted.copyOfRange(5, 5 + innerLen)150+ } else {151+ inner = decrypted // v1 — no length prefix / no padding152+ }153+154+ if (inner.size < HEADER_LEN + CHECKSUM_LEN) throw PeachScriptException("PAYLOAD_TOO_SHORT")155+ val body = inner.copyOfRange(0, inner.size - CHECKSUM_LEN)156+ val stored = inner.copyOfRange(inner.size - CHECKSUM_LEN, inner.size)157+ if (!constantTimeEqual(stored, blake3Truncated(body))) throw PeachScriptException("CHECKSUM_FAILED")158+159+ if (readU32BE(body, 0) != MAGIC.toLong()) throw PeachScriptException("BAD_MAGIC")160+ val version = body[4].toInt() and 0xff161+ if (version != VERSION) throw PeachScriptException("UNSUPPORTED_VERSION:$version")162+ val sectionCount = body[5].toInt() and 0xff163+164+ var entries = emptyList<VaultEntry>()165+ var cursor = HEADER_LEN166+ for (i in 0 until sectionCount) {167+ if (cursor + 9 > body.size) throw PeachScriptException("PAYLOAD_TOO_SHORT")168+ val type = body[cursor].toInt() and 0xff169+ val length = readU32LE(body, cursor + 1).toInt()170+ val clength = readU32LE(body, cursor + 5).toInt()171+ val dataStart = cursor + 9172+ val dataEnd = dataStart + clength173+ if (dataEnd > body.size) throw PeachScriptException("PAYLOAD_TOO_SHORT")174+ val compressed = body.copyOfRange(dataStart, dataEnd)175+ val data = Zstd.decompress(compressed, length)176+ if (data.size != length) throw PeachScriptException("SECTION_LENGTH_MISMATCH")177+ when (type) {178+ SECTION_ENTRIES -> entries = decodeEntriesSection(data)179+ // SETTINGS/LICENSE/RECALL/DECLINED_CARDS and unknown types are180+ // skipped — Android needs only the entries (BROWSER-SPEC §B2.12).181+ else -> {}182+ }183+ cursor = dataEnd184+ }185+ return entries186+ }187+188+ // ---- section assembly (peachPayload.ts:316-333) -----------------------189+190+ private fun buildSection(type: Int, raw: ByteArray): ByteArray {191+ val compressed = Zstd.compress(raw, ZSTD_LEVEL)192+ val out = ByteArray(9 + compressed.size)193+ out[0] = type.toByte()194+ writeU32LE(out, 1, raw.size.toLong())195+ writeU32LE(out, 5, compressed.size.toLong())196+ System.arraycopy(compressed, 0, out, 9, compressed.size)197+ return out198+ }199+200+ // ---- entries section: string table + packed bodies --------------------201+202+ private class StringTable {203+ private val map = LinkedHashMap<String, Int>()204+205+ /** u16 index; 0 reserved for absent. */206+ fun intern(value: String?): Int {207+ if (value.isNullOrEmpty()) return 0208+ map[value]?.let { return it }209+ val idx = map.size + 1210+ if (idx > 0xffff) throw PeachScriptException("STRING_TABLE_OVERFLOW")211+ map[value] = idx212+ return idx213+ }214+215+ fun serialize(): ByteArray {216+ val out = BinaryWriter()217+ out.u16(map.size)218+ for (s in map.keys) {219+ val e = s.toByteArray(Charsets.UTF_8)220+ if (e.size > 0xffff) throw PeachScriptException("STRING_TOO_LONG")221+ out.u16(e.size)222+ out.bytes(e)223+ }224+ return out.toBytes()225+ }226+ }227+228+ private fun encodeEntriesSection(entries: List<VaultEntry>): ByteArray {229+ val table = StringTable()230+ // Pre-intern every title first (peachPayload.ts:400-401) so indices match.231+ for (e in entries) table.intern(e.title)232+ val bodies = entries.map { encodeEntry(it, table) }233+ val tableBytes = table.serialize()234+235+ val out = BinaryWriter()236+ out.u32(entries.size.toLong())237+ out.bytes(tableBytes)238+ for (b in bodies) out.bytes(b)239+ return out.toBytes()240+ }241+242+ private fun decodeEntriesSection(data: ByteArray): List<VaultEntry> {243+ val r = BinaryReader(data, 0)244+ val count = r.u32().toInt()245+ val strings = readStringTable(r)246+ val out = ArrayList<VaultEntry>(count)247+ for (i in 0 until count) out.add(decodeEntry(r, strings))248+ return out249+ }250+251+ private fun readStringTable(r: BinaryReader): List<String?> {252+ val count = r.u16()253+ val strings = ArrayList<String?>(count + 1)254+ strings.add(null) // index 0 = absent255+ for (i in 0 until count) {256+ val len = r.u16()257+ strings.add(String(r.read(len), Charsets.UTF_8))258+ }259+ return strings260+ }261+262+ private fun lookup(strings: List<String?>, idx: Int): String? =263+ if (idx == 0 || idx >= strings.size) null else strings[idx]264+265+ // ---- per-entry packing (peachPayload.ts:443-601) ----------------------266+267+ private fun encodeEntry(entry: VaultEntry, table: StringTable): ByteArray {268+ val type = entryTypeByte(entry)269+ val w = BinaryWriter()270+ w.u8(type)271+ w.bytes(uuidToBytes(entry.id))272+273+ val createdSec = entry.createdAt / 1000L274+ val updatedSec = entry.modifiedAt / 1000L275+ val updatedDelta = maxOf(0L, updatedSec - createdSec)276+ val deletedSec = entry.deletedAt?.let { it / 1000L } ?: 0L277+278+ // Compute flags up front (the browser back-patches; same bytes result).279+ var flags = 0280+ var flags2 = 0281+ if (entry.deletedAt != null) flags = flags or F_HAS_DELETED282+283+ when (type) {284+ ENTRY_TYPE_LOGIN -> {285+ if (!entry.email.isNullOrEmpty()) flags2 = flags2 or F2_HAS_EMAIL286+ if (!entry.totp.isNullOrEmpty()) flags = flags or F_HAS_TOTP287+ if (!entry.tags.isNullOrEmpty()) flags = flags or F_HAS_TAGS288+ if (!entry.notes.isNullOrEmpty()) flags = flags or F_HAS_NOTES289+ if (entry.canary != null) flags = flags or F_HAS_CANARY290+ if (entry.passwordChangedAt != null) flags = flags or F_HAS_PWCHANGED291+ if ((entry.breach ?: 0) > 0) flags = flags or F_HAS_BREACH292+ if (!entry.additionalUrls.isNullOrEmpty()) flags = flags or F_HAS_ADDITIONAL_URLS293+ }294+ ENTRY_TYPE_NOTE -> {295+ if (!entry.notes.isNullOrEmpty()) flags = flags or F_HAS_NOTES296+ if (!entry.tags.isNullOrEmpty()) flags = flags or F_HAS_TAGS297+ }298+ ENTRY_TYPE_CARD -> {299+ if (!entry.tags.isNullOrEmpty()) flags = flags or F_HAS_TAGS300+ if (!entry.notes.isNullOrEmpty()) flags = flags or F_HAS_NOTES301+ }302+ }303+304+ w.u8(flags)305+ w.u8(flags2) // FORMAT_V3 always writes flags2306+ w.u32(createdSec)307+ w.u32(updatedDelta)308+ w.u32(deletedSec)309+ w.u16(table.intern(entry.title))310+311+ when (type) {312+ ENTRY_TYPE_LOGIN -> {313+ w.u16(table.intern(entry.url))314+ w.u16(table.intern(entry.username))315+ w.lpString(entry.password ?: "")316+ if (flags2 and F2_HAS_EMAIL != 0) w.lpString(entry.email!!)317+ if (flags and F_HAS_TOTP != 0) w.lpString(entry.totp!!)318+ if (flags and F_HAS_TAGS != 0) writeTags(w, table, entry.tags!!)319+ if (flags and F_HAS_NOTES != 0) w.u16(table.intern(entry.notes))320+ if (flags and F_HAS_CANARY != 0) {321+ w.u16(table.intern(entry.canary!!.webhookUrl))322+ w.u16(table.intern(entry.canary.label))323+ }324+ if (flags and F_HAS_PWCHANGED != 0) {325+ val pwSec = entry.passwordChangedAt!! / 1000L326+ w.u32(maxOf(0L, pwSec - createdSec))327+ }328+ if (flags and F_HAS_BREACH != 0) w.u32((entry.breach ?: 0).toLong())329+ if (flags and F_HAS_ADDITIONAL_URLS != 0) writeStrings(w, table, entry.additionalUrls!!)330+ }331+ ENTRY_TYPE_NOTE -> {332+ if (flags and F_HAS_NOTES != 0) w.u16(table.intern(entry.notes))333+ if (flags and F_HAS_TAGS != 0) writeTags(w, table, entry.tags!!)334+ }335+ ENTRY_TYPE_CARD -> {336+ w.u16(table.intern(entry.cardholderName))337+ w.lpString(entry.cardNumber ?: "")338+ w.lpString(entry.expMonth ?: "")339+ w.lpString(entry.expYear ?: "")340+ w.lpString(entry.cvc ?: "")341+ w.u16(table.intern(entry.cardNickname))342+ w.u8(networkToByte(entry.cardNetwork))343+ // Android has no last4 field — derive it from the card number so the344+ // wire format matches the browser (BROWSER-SPEC: card last4 note).345+ w.u16(table.intern(deriveLast4(entry)))346+ if (flags and F_HAS_TAGS != 0) writeTags(w, table, entry.tags!!)347+ if (flags and F_HAS_NOTES != 0) w.u16(table.intern(entry.notes))348+ }349+ ENTRY_TYPE_PASSKEY -> {350+ val blob = encodePasskeyBlob(entry)351+ w.u32(blob.size.toLong())352+ w.bytes(blob)353+ }354+ }355+ return w.toBytes()356+ }357+358+ private fun decodeEntry(r: BinaryReader, strings: List<String?>): VaultEntry {359+ val type = r.u8()360+ val id = bytesToUuid(r.read(16))361+ val flags = r.u8()362+ val flags2 = r.u8() // FORMAT_V3363+ val createdSec = r.u32()364+ val updatedDelta = r.u32()365+ val deletedSec = r.u32()366+ val titleIdx = r.u16()367+368+ val createdAt = createdSec * 1000L369+ val modifiedAt = (createdSec + updatedDelta) * 1000L370+ val deletedAt = if (deletedSec > 0) deletedSec * 1000L else null371+ val title = lookup(strings, titleIdx) ?: ""372+373+ return when (type) {374+ ENTRY_TYPE_LOGIN -> {375+ val urlIdx = r.u16()376+ val usernameIdx = r.u16()377+ val password = r.lpString()378+ val email = if (flags2 and F2_HAS_EMAIL != 0) r.lpString() else null379+ val totp = if (flags and F_HAS_TOTP != 0) r.lpString() else null380+ val tags = if (flags and F_HAS_TAGS != 0) readTags(r, strings) else null381+ val notes = if (flags and F_HAS_NOTES != 0) lookup(strings, r.u16()) else null382+ var canary: Canary? = null383+ if (flags and F_HAS_CANARY != 0) {384+ val webhookUrl = lookup(strings, r.u16()) ?: ""385+ val label = lookup(strings, r.u16())386+ canary = Canary(webhookUrl = webhookUrl, label = label)387+ }388+ val pwChanged = if (flags and F_HAS_PWCHANGED != 0) (createdSec + r.u32()) * 1000L else null389+ val breach = if (flags and F_HAS_BREACH != 0) r.u32().toInt() else null390+ val additionalUrls = if (flags and F_HAS_ADDITIONAL_URLS != 0) readStrings(r, strings) else null391+ VaultEntry(392+ id = id, type = "login", title = title,393+ url = lookup(strings, urlIdx), username = lookup(strings, usernameIdx),394+ password = password, email = email, totp = totp, tags = tags, notes = notes,395+ canary = canary, passwordChangedAt = pwChanged, breach = breach,396+ additionalUrls = additionalUrls, createdAt = createdAt, modifiedAt = modifiedAt,397+ deletedAt = deletedAt,398+ )399+ }400+ ENTRY_TYPE_NOTE -> {401+ val notes = if (flags and F_HAS_NOTES != 0) lookup(strings, r.u16()) else null402+ val tags = if (flags and F_HAS_TAGS != 0) readTags(r, strings) else null403+ VaultEntry(404+ id = id, type = "note", title = title, notes = notes, tags = tags,405+ createdAt = createdAt, modifiedAt = modifiedAt, deletedAt = deletedAt,406+ )407+ }408+ ENTRY_TYPE_CARD -> {409+ val cardholderIdx = r.u16()410+ val cardNumber = r.lpString()411+ val expMonth = r.lpString()412+ val expYear = r.lpString()413+ val cvc = r.lpString()414+ val nicknameIdx = r.u16()415+ val network = networkFromByte(r.u8())416+ r.u16() // last4 index — Android has no field; dropped (number carries it)417+ val tags = if (flags and F_HAS_TAGS != 0) readTags(r, strings) else null418+ val notes = if (flags and F_HAS_NOTES != 0) lookup(strings, r.u16()) else null419+ VaultEntry(420+ id = id, type = "card", title = title,421+ cardholderName = lookup(strings, cardholderIdx),422+ cardNumber = cardNumber.ifEmpty { null }, expMonth = expMonth.ifEmpty { null },423+ expYear = expYear.ifEmpty { null }, cvc = cvc.ifEmpty { null },424+ cardNickname = lookup(strings, nicknameIdx), cardNetwork = network,425+ tags = tags, notes = notes,426+ createdAt = createdAt, modifiedAt = modifiedAt, deletedAt = deletedAt,427+ )428+ }429+ ENTRY_TYPE_PASSKEY -> {430+ val blobLen = r.u32().toInt()431+ val blob = r.read(blobLen)432+ decodePasskeyBlob(id, title, createdAt, modifiedAt, deletedAt, blob)433+ }434+ else -> throw PeachScriptException("UNKNOWN_ENTRY_TYPE:$type")435+ }436+ }437+438+ private fun writeTags(w: BinaryWriter, table: StringTable, tags: List<String>) {439+ val n = minOf(tags.size, 0xff)440+ w.u8(n)441+ for (i in 0 until n) w.u16(table.intern(tags[i]))442+ }443+444+ private fun writeStrings(w: BinaryWriter, table: StringTable, items: List<String>) {445+ val n = minOf(items.size, 0xff)446+ w.u8(n)447+ for (i in 0 until n) w.u16(table.intern(items[i]))448+ }449+450+ private fun readTags(r: BinaryReader, strings: List<String?>): List<String> {451+ val n = r.u8()452+ val out = ArrayList<String>(n)453+ for (i in 0 until n) lookup(strings, r.u16())?.let { out.add(it) }454+ return out455+ }456+457+ private fun readStrings(r: BinaryReader, strings: List<String?>): List<String> = readTags(r, strings)458+459+ private fun entryTypeByte(entry: VaultEntry): Int {460+ if (entry.passkey != null) return ENTRY_TYPE_PASSKEY461+ return when (entry.type) {462+ "note" -> ENTRY_TYPE_NOTE463+ "card" -> ENTRY_TYPE_CARD464+ "passkey" -> ENTRY_TYPE_PASSKEY465+ else -> ENTRY_TYPE_LOGIN466+ }467+ }468+469+ private fun networkToByte(network: String?): Int {470+ if (network.isNullOrEmpty()) return 0xff471+ val idx = NETWORK_VALUES.indexOf(network)472+ return if (idx >= 0) idx else NETWORK_VALUES.indexOf("unknown")473+ }474+475+ private fun networkFromByte(b: Int): String? {476+ if (b == 0xff) return null477+ return NETWORK_VALUES.getOrNull(b) ?: "unknown"478+ }479+480+ private fun deriveLast4(entry: VaultEntry): String? {481+ val digits = entry.cardNumber?.filter { it.isDigit() } ?: return null482+ return if (digits.length >= 4) digits.takeLast(4) else digits.ifEmpty { null }483+ }484+485+ // ---- passkey JSON blob (peachPayload.ts:552-596) ----------------------486+ // [PLATFORM GAP] Android's PasskeyData has no privateKeyJwk field, so a487+ // browser passkey's private key is dropped on import. All other passkey +488+ // login fields round-trip. See BROWSER-SPEC Implementation Notes.489+490+ private fun encodePasskeyBlob(entry: VaultEntry): ByteArray {491+ val pk = entry.passkey492+ val obj = buildJsonObject {493+ putIfPresent("rpId", pk?.rpId ?: entry.rpId)494+ putIfPresent("rpName", pk?.rpName ?: entry.rpName)495+ putIfPresent("credentialId", pk?.credentialId ?: entry.credentialId)496+ putIfPresent("publicKeyCose", pk?.publicKeyCose ?: entry.publicKeyCose)497+ putIfPresent("userHandle", pk?.userHandle ?: entry.userHandle)498+ putIfPresent("userName", pk?.userName ?: entry.userName)499+ putIfPresent("userDisplayName", pk?.userDisplayName ?: entry.userDisplayName)500+ putIfPresent("algorithm", (pk?.algorithm ?: entry.algorithm))501+ putIfPresent("signCount", (pk?.signCount ?: entry.signCount))502+ putIfPresent("aaguid", pk?.aaguid ?: entry.aaguid)503+ putIfPresent("backupEligible", pk?.backupEligible ?: entry.backupEligible)504+ putIfPresent("backupState", pk?.backupState ?: entry.backupState)505+ putIfPresent("lastUsedAt", entry.lastUsedAt)506+ // Login fields carried alongside a passkey-bearing login entry.507+ putIfPresent("password", entry.password)508+ putIfPresent("url", entry.url)509+ putIfPresent("username", entry.username)510+ putIfPresent("email", entry.email)511+ putIfPresent("totp", entry.totp)512+ putIfPresent("notes", entry.notes)513+ if (!entry.tags.isNullOrEmpty()) {514+ put("tags", buildJsonArray { entry.tags.forEach { add(JsonPrimitive(it)) } })515+ }516+ }517+ return json.encodeToString(JsonObject.serializer(), obj).toByteArray(Charsets.UTF_8)518+ }519+520+ private fun decodePasskeyBlob(521+ id: String, title: String, createdAt: Long, modifiedAt: Long, deletedAt: Long?, blob: ByteArray,522+ ): VaultEntry {523+ val obj = json.parseToJsonElement(String(blob, Charsets.UTF_8)).jsonObject524+ fun str(k: String) = obj[k]?.jsonPrimitive?.contentOrNull525+ fun intf(k: String) = obj[k]?.jsonPrimitive?.intOrNull526+ fun longf(k: String) = obj[k]?.jsonPrimitive?.longOrNull527+ fun boolf(k: String) = obj[k]?.jsonPrimitive?.booleanOrNull528+ val tags = obj["tags"]?.jsonArray?.mapNotNull { it.jsonPrimitive.contentOrNull }529+ val credentialId = str("credentialId")530+ val publicKeyCose = str("publicKeyCose")531+ val rpId = str("rpId")532+ val userHandle = str("userHandle")533+ val userName = str("userName")534+ val passkey = if (credentialId != null && publicKeyCose != null && rpId != null &&535+ userHandle != null && userName != null) {536+ PasskeyData(537+ credentialId = credentialId, publicKeyCose = publicKeyCose, rpId = rpId,538+ rpName = str("rpName"), userHandle = userHandle, userName = userName,539+ userDisplayName = str("userDisplayName"), algorithm = intf("algorithm") ?: -7,540+ signCount = intf("signCount") ?: 0, aaguid = str("aaguid"),541+ backupEligible = boolf("backupEligible") ?: false, backupState = boolf("backupState") ?: false,542+ )543+ } else null544+ return VaultEntry(545+ id = id, type = "passkey", title = title,546+ url = str("url"), username = str("username"), email = str("email"),547+ password = str("password"), totp = str("totp"), notes = str("notes"), tags = tags,548+ createdAt = createdAt, modifiedAt = modifiedAt, deletedAt = deletedAt,549+ passkey = passkey, lastUsedAt = longf("lastUsedAt"),550+ rpId = rpId, rpName = str("rpName"), credentialId = credentialId,551+ publicKeyCose = publicKeyCose, userHandle = userHandle, userName = userName,552+ userDisplayName = str("userDisplayName"), algorithm = intf("algorithm"),553+ aaguid = str("aaguid"), backupEligible = boolf("backupEligible"),554+ backupState = boolf("backupState"), signCount = intf("signCount"),555+ )556+ }557+558+ // ---- uuid (peachPayload.ts:792-806) -----------------------------------559+560+ fun uuidToBytes(uuid: String): ByteArray {561+ val hex = uuid.replace("-", "")562+ if (hex.length != 32) throw PeachScriptException("UUID_FORMAT")563+ return ByteArray(16) { i -> hex.substring(i * 2, i * 2 + 2).toInt(16).toByte() }564+ }565+566+ fun bytesToUuid(bytes: ByteArray): String {567+ if (bytes.size != 16) throw PeachScriptException("UUID_LENGTH")568+ val hex = bytes.joinToString("") { "%02x".format(it) }569+ return "${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-" +570+ "${hex.substring(16, 20)}-${hex.substring(20)}"571+ }572+573+ // ---- crypto / hashing -------------------------------------------------574+575+ private fun deriveKey(passphrase: String, salt: ByteArray): ByteArray {576+ // Argon2id over the UTF-8 BYTES of the passphrase, matching the browser's577+ // hash-wasm KDF input (avoids the MF-4 UTF-16 divergence in this path).578+ val params = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)579+ .withSalt(salt)580+ .withParallelism(ARGON2_PARALLELISM)581+ .withMemoryAsKB(ARGON2_MEMORY_KIB)582+ .withIterations(ARGON2_ITERATIONS)583+ .build()584+ val gen = Argon2BytesGenerator().apply { init(params) }585+ val out = ByteArray(32)586+ gen.generateBytes(passphrase.toByteArray(Charsets.UTF_8), out)587+ return out588+ }589+590+ private fun aesGcmEncrypt(key: ByteArray, nonce: ByteArray, plaintext: ByteArray): ByteArray {591+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")592+ cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))593+ return cipher.doFinal(plaintext) // ciphertext || tag; no AAD (browser uses none)594+ }595+596+ private fun aesGcmDecrypt(key: ByteArray, nonce: ByteArray, ctTag: ByteArray): ByteArray {597+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")598+ cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))599+ return cipher.doFinal(ctTag)600+ }601+602+ private fun blake3Truncated(data: ByteArray): ByteArray {603+ val digest = Blake3Digest(256)604+ digest.update(data, 0, data.size)605+ val full = ByteArray(32)606+ digest.doFinal(full, 0)607+ return full.copyOfRange(0, CHECKSUM_LEN)608+ }609+610+ private fun padToNearestBucket(data: ByteArray): ByteArray {611+ val bucket = SIZE_BUCKETS.firstOrNull { it >= data.size }612+ var target = bucket ?: run {613+ var t = 262144614+ while (t < data.size) t *= 2615+ t616+ }617+ if (target == data.size) return data618+ return data.copyOf(target)619+ }620+621+ private fun constantTimeEqual(a: ByteArray, b: ByteArray): Boolean {622+ if (a.size != b.size) return false623+ var diff = 0624+ for (i in a.indices) diff = diff or (a[i].toInt() xor b[i].toInt())625+ return diff == 0626+ }627+628+ private fun concat(parts: List<ByteArray>): ByteArray {629+ val total = parts.sumOf { it.size }630+ val out = ByteArray(total)631+ var c = 0632+ for (p in parts) { System.arraycopy(p, 0, out, c, p.size); c += p.size }633+ return out634+ }635+636+ // ---- little/big-endian helpers ----------------------------------------637+638+ private fun writeU32LE(buf: ByteArray, off: Int, v: Long) {639+ buf[off] = (v and 0xff).toByte()640+ buf[off + 1] = ((v ushr 8) and 0xff).toByte()641+ buf[off + 2] = ((v ushr 16) and 0xff).toByte()642+ buf[off + 3] = ((v ushr 24) and 0xff).toByte()643+ }644+645+ private fun writeU32BE(buf: ByteArray, off: Int, v: Long) {646+ buf[off] = ((v ushr 24) and 0xff).toByte()647+ buf[off + 1] = ((v ushr 16) and 0xff).toByte()648+ buf[off + 2] = ((v ushr 8) and 0xff).toByte()649+ buf[off + 3] = (v and 0xff).toByte()650+ }651+652+ private fun readU32LE(buf: ByteArray, off: Int): Long {653+ return (buf[off].toLong() and 0xff) or654+ ((buf[off + 1].toLong() and 0xff) shl 8) or655+ ((buf[off + 2].toLong() and 0xff) shl 16) or656+ ((buf[off + 3].toLong() and 0xff) shl 24)657+ }658+659+ private fun readU32BE(buf: ByteArray, off: Int): Long {660+ return ((buf[off].toLong() and 0xff) shl 24) or661+ ((buf[off + 1].toLong() and 0xff) shl 16) or662+ ((buf[off + 2].toLong() and 0xff) shl 8) or663+ (buf[off + 3].toLong() and 0xff)664+ }665+666+ private class BinaryWriter {667+ private val out = ByteArrayOutputStream()668+ fun u8(v: Int) { out.write(v and 0xff) }669+ fun u16(v: Int) { out.write(v and 0xff); out.write((v ushr 8) and 0xff) }670+ fun u32(v: Long) {671+ out.write((v and 0xff).toInt()); out.write(((v ushr 8) and 0xff).toInt())672+ out.write(((v ushr 16) and 0xff).toInt()); out.write(((v ushr 24) and 0xff).toInt())673+ }674+ fun bytes(b: ByteArray) { out.write(b) }675+ fun lpString(value: String) {676+ val enc = value.toByteArray(Charsets.UTF_8)677+ if (enc.size > 0xff) throw PeachScriptException("STRING_TOO_LONG_U8")678+ u8(enc.size); bytes(enc)679+ }680+ fun toBytes(): ByteArray = out.toByteArray()681+ }682+683+ private class BinaryReader(private val data: ByteArray, start: Int) {684+ private var cursor = start685+ fun u8(): Int = data[cursor++].toInt() and 0xff686+ fun u16(): Int { val v = (data[cursor].toInt() and 0xff) or ((data[cursor + 1].toInt() and 0xff) shl 8); cursor += 2; return v }687+ fun u32(): Long {688+ val v = (data[cursor].toLong() and 0xff) or ((data[cursor + 1].toLong() and 0xff) shl 8) or689+ ((data[cursor + 2].toLong() and 0xff) shl 16) or ((data[cursor + 3].toLong() and 0xff) shl 24)690+ cursor += 4; return v691+ }692+ fun read(n: Int): ByteArray { val out = data.copyOfRange(cursor, cursor + n); cursor += n; return out }693+ fun lpString(): String = String(read(u8()), Charsets.UTF_8)694+ }695+696+ private fun JsonObjectBuilder.putIfPresent(key: String, value: String?) {697+ if (!value.isNullOrEmpty()) put(key, JsonPrimitive(value))698+ }699+ private fun JsonObjectBuilder.putIfPresent(key: String, value: Int?) {700+ if (value != null) put(key, JsonPrimitive(value))701+ }702+ private fun JsonObjectBuilder.putIfPresent(key: String, value: Long?) {703+ if (value != null) put(key, JsonPrimitive(value))704+ }705+ private fun JsonObjectBuilder.putIfPresent(key: String, value: Boolean?) {706+ if (value != null) put(key, JsonPrimitive(value))707+ }708+}app/src/main/java/com/peachpasswords/vault/PeachScript.kt+53 −0
@@ -0,0 +1,53 @@1+package com.peachpasswords.vault2+3+/**4+ * PeachScript outer codec — maps each payload byte to one Private-Use-Area code5+ * point in U+E000..U+E0FF, and back. Byte-for-byte the browser's `peachScript.ts`:6+ * byte 0 → U+E000, byte 255 → U+E0FF. The bundled PeachScript font renders those7+ * 256 code points; outside Peach the string is unreadable boxes (intended).8+ */9+object PeachScript {10+ private const val BASE = 0xE00011+12+ /** Encode binary [bytes] to a PeachScript string (one code point per byte). */13+ fun encode(bytes: ByteArray): String {14+ val sb = StringBuilder(bytes.size)15+ for (b in bytes) sb.appendCodePoint(BASE + (b.toInt() and 0xff))16+ return sb.toString()17+ }18+19+ /**20+ * Decode a PeachScript string back to bytes. Throws on any code point outside21+ * U+E000..U+E0FF (edited / truncated / not PeachScript), matching the browser's22+ * INVALID_PEACHSCRIPT_CHARACTER.23+ */24+ fun decode(str: String): ByteArray {25+ val cps = str.codePoints().toArray()26+ val out = ByteArray(cps.size)27+ for (i in cps.indices) {28+ val cp = cps[i]29+ require(cp in BASE..(BASE + 0xff)) { "INVALID_PEACHSCRIPT_CHARACTER" }30+ out[i] = (cp - BASE).toByte()31+ }32+ return out33+ }34+35+ /** Strip all whitespace before decoding (browser `normalisePeachScript`). */36+ fun normalise(str: String): String = str.replace(Regex("\\s+"), "")37+38+ /**39+ * Cheap pre-flight: non-empty and every non-whitespace char is in the PUA40+ * range. Used to gate the import button without throwing.41+ */42+ fun isPeachScript(str: String): Boolean {43+ val t = normalise(str)44+ if (t.isEmpty()) return false45+ var i = 046+ while (i < t.length) {47+ val cp = t.codePointAt(i)48+ if (cp < BASE || cp > BASE + 0xff) return false49+ i += Character.charCount(cp)50+ }51+ return true52+ }53+}app/src/test/java/com/peachpasswords/ui/vault/ExportRoundTripTest.kt+10 −11
@@ -7,8 +7,10 @@77 88 class ExportRoundTripTest {99 10+ // PeachScript packs the id as 16 raw UUID bytes (browser parity), so test11+ // entries use real UUIDs as production entries do (addEntry assigns one).1012 private fun entry() = VaultEntry(11- id = "1", title = "GitHub", type = "login",13+ id = "11111111-2222-3333-4444-555555555555", title = "GitHub", type = "login",1214 username = "june", password = "hunter2", url = "https://github.com",1315 notes = "my note", totp = "JBSWY3DPEHPK3PXP", createdAt = 0, modifiedAt = 0,1416 )@@ -32,16 +34,10 @@3234 assertTrue(lines[1].startsWith("GitHub,june,hunter2,"))3335 }3436 35- @Test fun peachscript_plaintext_round_trips_through_importer() {36- val json = PeachScriptExport.buildPlaintext(listOf(entry()))37- assertTrue(PeachScriptImport.looksLikePeachScript(json))38- val parsed = PeachScriptImport.parsePlaintext(json)39- assertEquals(1, parsed.size)40- assertEquals("GitHub", parsed[0].title)41- assertEquals("june", parsed[0].username)42- assertEquals("hunter2", parsed[0].password)43- assertEquals("my note", parsed[0].notes)44- assertEquals("JBSWY3DPEHPK3PXP", parsed[0].totp)37+ @Test fun peachscript_export_is_peachscript_text() {38+ val out = PeachScriptExport.buildEncrypted(listOf(entry()), "backup-pass-12")39+ assertTrue(PeachScriptImport.looksLikePeachScript(out))40+ assertTrue(PeachScriptImport.isEncrypted(out))4541 }4642 4743 @Test fun peachscript_encrypted_round_trips_with_correct_password() {@@ -52,6 +48,9 @@5248 ok as PeachScriptImport.DecryptResult.Success5349 assertEquals(1, ok.entries.size)5450 assertEquals("hunter2", ok.entries[0].password)51+ assertEquals("june", ok.entries[0].username)52+ assertEquals("my note", ok.entries[0].notes)53+ assertEquals("JBSWY3DPEHPK3PXP", ok.entries[0].totp)5554 }5655 5756 @Test fun peachscript_encrypted_rejects_wrong_password() {app/src/test/java/com/peachpasswords/ui/vault/ImportParsersTest.kt+16 −12
@@ -1,5 +1,6 @@11 package com.peachpasswords.ui.vault22 3+import com.peachpasswords.vault.VaultEntry34 import org.junit.Assert.assertEquals45 import org.junit.Assert.assertFalse56 import org.junit.Assert.assertNull@@ -43,20 +44,23 @@4344 assertEquals(2, r.entries.size)4445 }4546 46- @Test fun peachscript_plaintext_round_trips() {47- val json = """{"peachscript":1,"encrypted":false,"entries":[""" +48- """{"title":"GH","username":"u","password":"p","url":"x","notes":"n","totp":"t"}]}"""49- assertTrue(PeachScriptImport.looksLikePeachScript(json))50- assertFalse(PeachScriptImport.isEncrypted(json))51- val entries = PeachScriptImport.parsePlaintext(json)52- assertEquals(1, entries.size)53- assertEquals("GH", entries[0].title)54- assertEquals("u", entries[0].username)55- assertEquals("t", entries[0].totp)47+ @Test fun peachscript_export_is_recognised() {48+ val out = PeachScriptExport.buildEncrypted(49+ listOf(50+ VaultEntry(51+ id = "11111111-2222-3333-4444-555555555555", type = "login",52+ title = "GH", username = "u", password = "p", createdAt = 0, modifiedAt = 0,53+ ),54+ ),55+ "backup-pass-123",56+ )57+ assertTrue(PeachScriptImport.looksLikePeachScript(out))58+ assertTrue(PeachScriptImport.isEncrypted(out))5659 }5760 58- @Test fun peachscript_detects_encrypted_flag() {59- assertTrue(PeachScriptImport.isEncrypted("""{"peachscript":1,"encrypted":true,"salt":"x","blob":"y"}"""))61+ @Test fun non_peachscript_text_is_rejected() {6062 assertFalse(PeachScriptImport.looksLikePeachScript("just text"))63+ // The old JSON marker is not PeachScript anymore (PUA-encoded binary only).64+ assertFalse(PeachScriptImport.looksLikePeachScript("""{"peachscript":1,"encrypted":true}"""))6165 }6266 }app/src/test/java/com/peachpasswords/vault/PeachScriptTest.kt+185 −0
@@ -0,0 +1,185 @@1+package com.peachpasswords.vault2+3+import org.junit.Assert.assertEquals4+import org.junit.Assert.assertNotNull5+import org.junit.Assert.assertNull6+import org.junit.Assert.assertThrows7+import org.junit.Assert.assertTrue8+import org.junit.Test9+import java.util.Base6410+11+class PeachScriptTest {12+13+ private fun login() = VaultEntry(14+ id = "11111111-2222-3333-4444-555555555555", type = "login", title = "GitHub",15+ url = "https://github.com", username = "june", email = "[email protected]",16+ password = "hunter2-Σ-🔐", totp = "JBSWY3DPEHPK3PXP", tags = listOf("dev", "work"),17+ notes = "primary account", additionalUrls = listOf("https://gist.github.com"),18+ breach = 3, passwordChangedAt = 1_600_000_000_000,19+ canary = Canary(webhookUrl = "https://canary.example.com/hook", label = "tripwire"),20+ createdAt = 1_500_000_000_000, modifiedAt = 1_600_000_500_000,21+ )22+23+ private fun note() = VaultEntry(24+ id = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", type = "note", title = "そふと メモ 🌸",25+ notes = "日本語のノート\nsecond line", tags = listOf("personal"),26+ createdAt = 1_500_000_000_000, modifiedAt = 1_500_000_000_000,27+ )28+29+ private fun card() = VaultEntry(30+ id = "99999999-8888-7777-6666-555544443333", type = "card", title = "Visa",31+ cardholderName = "JUNE MOON", cardNumber = "4111111111111111", expMonth = "04",32+ expYear = "2030", cvc = "123", cardNickname = "daily", cardNetwork = "visa",33+ notes = "spending card", tags = listOf("finance"),34+ createdAt = 1_500_000_000_000, modifiedAt = 1_500_000_000_000,35+ )36+37+ // ── KAT: parse a REAL browser-produced PeachScript payload ──────────────38+ // Envelope generated by the browser's own buildPayload (/tmp/gen_peach3.mjs39+ // via vite SSR), proving Android decrypts + zstd-decompresses + unpacks the40+ // exact bytes the extension writes. This is the cross-platform import proof.41+ @Test fun parses_browser_produced_payload() {42+ val envelope = Base64.getDecoder().decode(BROWSER_FIXTURE_B64)43+ val entries = PeachPayloadCodec.parsePayload(envelope, "backup-pass-123")44+ assertEquals(3, entries.size)45+46+ val l = entries[0]47+ assertEquals("11111111-2222-3333-4444-555555555555", l.id)48+ assertEquals("login", l.type)49+ assertEquals("GitHub", l.title)50+ assertEquals("https://github.com", l.url)51+ assertEquals("june", l.username)52+ assertEquals("[email protected]", l.email)53+ assertEquals("hunter2-Σ-🔐", l.password)54+ assertEquals("JBSWY3DPEHPK3PXP", l.totp)55+ assertEquals(listOf("dev", "work"), l.tags)56+ assertEquals("primary account", l.notes)57+ assertEquals(listOf("https://gist.github.com"), l.additionalUrls)58+ assertEquals(3, l.breach)59+ assertEquals(1_600_000_000_000L, l.passwordChangedAt)60+ assertEquals("https://canary.example.com/hook", l.canary?.webhookUrl)61+ assertEquals("tripwire", l.canary?.label)62+ assertEquals(1_500_000_000_000L, l.createdAt)63+ assertEquals(1_600_000_500_000L, l.modifiedAt)64+65+ val n = entries[1]66+ assertEquals("note", n.type)67+ assertEquals("そふと メモ 🌸", n.title)68+ assertEquals("日本語のノート\nsecond line", n.notes)69+ assertEquals(listOf("personal"), n.tags)70+71+ val c = entries[2]72+ assertEquals("card", c.type)73+ assertEquals("JUNE MOON", c.cardholderName)74+ assertEquals("4111111111111111", c.cardNumber)75+ assertEquals("04", c.expMonth)76+ assertEquals("2030", c.expYear)77+ assertEquals("123", c.cvc)78+ assertEquals("daily", c.cardNickname)79+ assertEquals("visa", c.cardNetwork)80+ assertEquals("spending card", c.notes)81+ assertEquals(listOf("finance"), c.tags)82+ }83+84+ // ── Android self round-trip: all fields, all entry types ────────────────85+ @Test fun self_round_trips_all_fields() {86+ val input = listOf(login(), note(), card())87+ val out = PeachPayloadCodec.buildPayload(input, "pw-123")88+ val back = PeachPayloadCodec.parsePayload(out, "pw-123")89+ assertEquals(3, back.size)90+91+ val l = back[0]92+ assertEquals(login().id, l.id)93+ assertEquals("hunter2-Σ-🔐", l.password)94+ assertEquals(listOf("dev", "work"), l.tags)95+ assertEquals(3, l.breach)96+ assertEquals(1_600_000_000_000L, l.passwordChangedAt)97+ assertEquals("tripwire", l.canary?.label)98+ assertEquals(listOf("https://gist.github.com"), l.additionalUrls)99+ assertEquals(1_500_000_000_000L, l.createdAt)100+ assertEquals(1_600_000_500_000L, l.modifiedAt)101+102+ val c = back[2]103+ assertEquals("4111111111111111", c.cardNumber)104+ assertEquals("visa", c.cardNetwork)105+ assertEquals("123", c.cvc)106+ }107+108+ // ── Cross-direction: Android export parsed by the browser's algorithm ───109+ // (Verified manually via /tmp; here we at least prove a browser-shaped110+ // envelope layout: salt(16)+nonce(12)+ct+tag, padded to a size bucket.)111+ @Test fun export_envelope_has_browser_shape() {112+ val out = PeachPayloadCodec.buildPayload(listOf(login()), "pw")113+ // salt(16)+nonce(12)+tag(16) overhead; payload padded to >= 1024 bucket,114+ // so the ciphertext alone is at least one bucket.115+ assertTrue(out.size >= 16 + 12 + 1024 + 16)116+ }117+118+ @Test fun empty_vault_round_trips() {119+ val out = PeachPayloadCodec.buildPayload(emptyList(), "pw")120+ assertEquals(0, PeachPayloadCodec.parsePayload(out, "pw").size)121+ }122+123+ @Test fun unicode_fields_round_trip() {124+ val out = PeachPayloadCodec.buildPayload(listOf(note()), "pw")125+ val n = PeachPayloadCodec.parsePayload(out, "pw").single()126+ assertEquals("そふと メモ 🌸", n.title)127+ assertEquals("日本語のノート\nsecond line", n.notes)128+ }129+130+ @Test fun wrong_password_is_invalid_passphrase() {131+ val out = PeachPayloadCodec.buildPayload(listOf(login()), "right-pw")132+ val ex = assertThrows(PeachPayloadCodec.PeachScriptException::class.java) {133+ PeachPayloadCodec.parsePayload(out, "wrong-pw")134+ }135+ assertEquals("INVALID_PASSPHRASE", ex.message)136+ }137+138+ @Test fun pua_codec_round_trips() {139+ val bytes = ByteArray(256) { it.toByte() }140+ val text = PeachScript.encode(bytes)141+ assertTrue(PeachScript.isPeachScript(text))142+ assertEquals(256, text.codePointCount(0, text.length))143+ assertTrue(bytes.contentEquals(PeachScript.decode(text)))144+ // Whitespace is stripped before decode.145+ assertTrue(bytes.contentEquals(PeachScript.decode(PeachScript.normalise(" $text \n"))))146+ }147+148+ @Test fun passkey_core_fields_round_trip() {149+ val pk = VaultEntry(150+ id = "12121212-3434-5656-7878-909090909090", type = "passkey", title = "Passkey",151+ passkey = PasskeyData(152+ credentialId = "cred-abc", publicKeyCose = "cose-xyz", rpId = "example.com",153+ rpName = "Example", userHandle = "uh-1", userName = "june", userDisplayName = "June",154+ ),155+ createdAt = 1_500_000_000_000, modifiedAt = 1_500_000_000_000,156+ )157+ val out = PeachPayloadCodec.buildPayload(listOf(pk), "pw")158+ val back = PeachPayloadCodec.parsePayload(out, "pw").single()159+ assertEquals("passkey", back.type)160+ assertNotNull(back.passkey)161+ assertEquals("cred-abc", back.passkey?.credentialId)162+ assertEquals("example.com", back.passkey?.rpId)163+ assertEquals("june", back.passkey?.userName)164+ }165+166+ @Test fun full_export_import_via_peachscript_text() {167+ val text = com.peachpasswords.ui.vault.PeachScriptExport.buildEncrypted(listOf(login(), card()), "bp")168+ assertTrue(com.peachpasswords.ui.vault.PeachScriptImport.looksLikePeachScript(text))169+ val r = com.peachpasswords.ui.vault.PeachScriptImport.decryptAndParse(text, "bp")170+ assertTrue(r is com.peachpasswords.ui.vault.PeachScriptImport.DecryptResult.Success)171+ r as com.peachpasswords.ui.vault.PeachScriptImport.DecryptResult.Success172+ assertEquals(2, r.entries.size)173+ assertEquals("hunter2-Σ-🔐", r.entries[0].password)174+ assertNull(175+ (com.peachpasswords.ui.vault.PeachScriptImport.decryptAndParse(text, "nope")176+ as? com.peachpasswords.ui.vault.PeachScriptImport.DecryptResult.Success)?.entries,177+ )178+ }179+180+ companion object {181+ // Real browser PeachScript envelope (base64) — see /tmp/gen_peach3.mjs.182+ private const val BROWSER_FIXTURE_B64 =183+ "RTRXPzyl+oHgPhKUK3DCdab09Rb+zMF5Dfphcydo2qzHWqE2PfJHdLEalnhL7jSOxCiowSjIYmrbkCLP2qCLeSHwceeSD9RhBx04bHNoc5J/ml/sXrY/7BFIZizNk5dlDt921VSQNhaNEzYmP/fKkYWjFpz+OOhUCBTUgt+WtCwa5mf8Ctf6R1UPkh21Fu3pwwb/IQjhFvij+CYgS+1skXtogw0iYTrNbSLMIxMsIKvXytFGOp4IGWbbATO/7vFPXnwc2Zh9gOkbUbVM8D7dBUBV+hTodCNHO8PsvxzPAQL0io4/t/Iu60x91eiB8+TTJEwQy9d/aNGM0hgAZq5TzBj4IpYW2tGwfMqRwhuQz07e7SrcL3ggJVlrOf+rph0UnzgdRuCeMS67/83IhNg0UUCftSqdBdQFeqE3UNLavRohLO4AaqTLR1i4UfDApjL79MVtqjztfj8xTJr+zf1SH0BZ0/6PCyIXnm526lxk4WALgJiXu1FWoIXP3xGjs/ZAe1t7RONiVak51kTLs7djQMh6WLMGxW8KVaFAu1a+jG3Zus9Ynn9FBpowipW1E4rnUnytqUzh/udY0q4Y8nJvavyD3hO5xEbHkslfbPSYqxrrGaL3OFb9llKoLyZSiYGB5p+/QM7xn5DFZ3VOtx90xf9wVEe2Uhfhq0XfQUqT384kWp8Ujlyq4pFB6nIe3f3e8C2pE+fJMou0Q2RFvotx/F56T3Ul2d0fpoN7ucyqJC94Fo6B8Peh1u5oxu5njPZEjRSUl2eBt3K8Aval7d9yYbm7I1ecUSLNJ+nHphL/DMYKL2CYQd90pdyfOeDgRCt4WML8z6hjTtW6uPUKDkd5WVu0qp2ktuzawolWi7aah1BnTZMwH2/jm6bPlLNE5r/bFwr1MAgNscjpwwa0DXTfMovbgJHLxEp6/0vpxuYcCfoRoinpTErt7Eafz2rQqw7mEit3eoUZ1Nv+AdfvBC3PN0pB/L5gdzi/cCrEtVCX2A/1NkhV91EKnx0tCQnkjZyovd9ZhKb/QNgzA6v7lugua4e0foRJJBSqwcJJ4Sr7CUXsK5/yuwXsYcJ0I+yTwiHoe4WA5I/go61xvSPsDV/5aXyS0bJbAa5DusVd/SnUM1QFFwHjOfwGUlU/PupZSr2zvZdds+ZX8B8u16L55gZE8xOdOUq7tAd25Gd3v0r6sSwcYu1amjhbfQlgw2RBQBWHmMZ8Jn715A9RblOMW95EqVu8AhG1Jfl547WdahfgC93Aw3nlT39sUBpzqRwa54N6Q9RHc81uC1q+xtU7CiTIMWJm1qqnVjP89MWMnRpYjRXOYBOop73uHh4BjomUlEzXEXmtJiaMq1nsqW85k+FKnO0bF/rGVzmFvHWuBx4cWYic9e8tmUalxdJxDsqFr+dh3h3Fp/YD9oOIT2XD"184+ }185+}