31faca9201f2
resolve all 39 findings of the 2026-09-10 independent assessment (v2.17.33)
- time
- 2026-09-11 04:36 UTC · 2 months ago
- machine
- koh2
- agent
- deepseek/deepseek-v4-flash
- session
- assessment findings remediation
- parent
- a4afc0a38baf
↓ peach-android-31faca92.tar.gzatlas at this save
files changed99 files
VERSION+1 −1app/build.gradle+25 −1app/drafts/B2-INTEGRATION.md+0 −172app/drafts/C1/C1-INTEGRATION.md+0 −218app/drafts/C2-INTEGRATION.md+0 −142app/drafts/C7/C7-INTEGRATION.md+0 −329app/drafts/MF1MF2/BROWSER-SPEC.md+0 −481app/drafts/MF1MF2/ExportRoundTripTest.kt+0 −61app/drafts/MF1MF2/ImportParsersTest.kt+0 −66app/drafts/MF1MF2/ImportScreen.kt+0 −691app/drafts/MF1MF2/PeachPayloadCodec.kt+0 −708app/drafts/MF1MF2/PeachScript.kt+0 −53app/drafts/MF1MF2/PeachScriptExport.kt+0 −24app/drafts/MF1MF2/PeachScriptImport.kt+0 −52app/drafts/MF1MF2/PeachScriptTest.kt+0 −185app/drafts/MF1MF2/RecoveryEscrowTest.kt+0 −215app/drafts/MF1MF2/RecoveryWords.kt+0 −141app/drafts/MF1MF2/VaultCrypto.kt+0 −121app/drafts/MF1MF2/VaultRepository.kt+0 −855app/drafts/MF1MF2/VaultStore.kt+0 −182app/drafts/MF1MF2/gen_peach_fixture.mjs+0 −51app/drafts/MF1MF2/mf1_kat_gen.mjs+0 −106app/drafts/MF1MF2/parse_android_export.mjs+0 −22app/src/main/AndroidManifest.xml+0 −7app/src/main/java/com/peachpasswords/PeachApplication.kt+18 −0app/src/main/java/com/peachpasswords/autofill/AssistStructureParser.kt+1 −0app/src/main/java/com/peachpasswords/autofill/AutofillIntents.kt+12 −12app/src/main/java/com/peachpasswords/autofill/AutofillOrigin.kt+4 −1app/src/main/java/com/peachpasswords/autofill/AutofillResponseBuilder.kt+8 −4app/src/main/java/com/peachpasswords/autofill/AutofillSave.kt+9 −5app/src/main/java/com/peachpasswords/autofill/PasswordPolicy.kt+8 −1app/src/main/java/com/peachpasswords/autofill/PeachAutofillService.kt+2 −1app/src/main/java/com/peachpasswords/credentials/CredentialProviderUnlockActivity.kt+1 −0app/src/main/java/com/peachpasswords/credentials/PasswordCredentialPlanner.kt+6 −2app/src/main/java/com/peachpasswords/license/LicenseCodec.kt+110 −0app/src/main/java/com/peachpasswords/license/LicenseRepository.kt+7 −90app/src/main/java/com/peachpasswords/license/ProFeature.kt+0 −5app/src/main/java/com/peachpasswords/license/ProNoticeStore.kt+1 −1app/src/main/java/com/peachpasswords/passkeys/PasskeyCallerOrigin.kt+9 −0app/src/main/java/com/peachpasswords/passkeys/PeachCredentialProviderService.kt+2 −2app/src/main/java/com/peachpasswords/shared/PeachClipboard.kt+51 −8app/src/main/java/com/peachpasswords/sync/AdoptionProtocol.kt+16 −12app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+9 −0app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+63 −21app/src/main/java/com/peachpasswords/sync/PeachSyncService.kt+9 −19app/src/main/java/com/peachpasswords/sync/RelayAdoptionHost.kt+50 −5app/src/main/java/com/peachpasswords/sync/RelayAdoptionReceiver.kt+20 −0app/src/main/java/com/peachpasswords/sync/Rendezvous.kt+0 −28app/src/main/java/com/peachpasswords/sync/SyncFreshStartResetter.kt+4 −1app/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+18 −5app/src/main/java/com/peachpasswords/ui/codex/CodexGenerateScreen.kt+6 −1app/src/main/java/com/peachpasswords/ui/codex/CodexViewModel.kt+9 −0app/src/main/java/com/peachpasswords/ui/lock/BiometricUnlockActivity.kt+0 −11app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+1 −3app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+4 −0app/src/main/java/com/peachpasswords/ui/pairing/CodePairScreen.kt+7 −3app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+7 −0app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+31 −13app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+5 −3app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+29 −6app/src/main/java/com/peachpasswords/ui/vault/CsvImport.kt+34 −12app/src/main/java/com/peachpasswords/ui/vault/ImportScreen.kt+10 −2app/src/main/java/com/peachpasswords/ui/vault/RecoveryWordsScreen.kt+60 −9app/src/main/java/com/peachpasswords/ui/vault/VaultHealthScreen.kt+2 −3app/src/main/java/com/peachpasswords/vault/DuressConfig.kt+37 −11app/src/main/java/com/peachpasswords/vault/PeachPayloadCodec.kt+11 −7app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+2 −8app/src/main/java/com/peachpasswords/vault/VaultEntry.kt+2 −0app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+94 −4app/src/main/java/com/peachpasswords/vault/VaultSettings.kt+24 −0app/src/main/java/com/peachpasswords/vault/VaultStore.kt+6 −0app/src/main/jniLibs/armeabi-v7a/libpeach_noise_core.sobinaryapp/src/main/jniLibs/x86/libpeach_noise_core.sobinaryapp/src/test/java/com/peachpasswords/autofill/AssistStructureOtpRegexTest.kt+37 −0app/src/test/java/com/peachpasswords/autofill/AutofillMatchTest.kt+17 −4app/src/test/java/com/peachpasswords/autofill/AutofillSaveTest.kt+25 −5app/src/test/java/com/peachpasswords/autofill/PasswordPolicyTest.kt+7 −2app/src/test/java/com/peachpasswords/backup/BackupRulesCoverageTest.kt+44 −10app/src/test/java/com/peachpasswords/credentials/PasswordCredentialPlannerTest.kt+20 −5app/src/test/java/com/peachpasswords/license/LicenseCodecTest.kt+120 −0app/src/test/java/com/peachpasswords/license/ProNoticeStoreTest.kt+1 −1app/src/test/java/com/peachpasswords/shared/PeachClipboardTest.kt+28 −0app/src/test/java/com/peachpasswords/sync/PairedDeviceRevocationTest.kt+23 −2app/src/test/java/com/peachpasswords/sync/RendezvousTest.kt+0 −28app/src/test/java/com/peachpasswords/sync/SourceConsentGateTest.kt+46 −0app/src/test/java/com/peachpasswords/vault/DecoySettingsIsolationTest.kt+75 −0app/src/test/java/com/peachpasswords/vault/DuressPolicyRecordTest.kt+34 −0app/src/test/java/com/peachpasswords/vault/ImportSettingsClassificationTest.kt+49 −0app/src/test/java/com/peachpasswords/vault/SlotPaddingTest.kt+2 −1app/src/test/java/com/peachpasswords/vault/VaultCryptoTest.kt+16 −3app/src/test/java/com/peachpasswords/vault/VaultKeyRotationHooksTest.kt+66 −0scripts/build-noise-core.sh+1 −3scripts/check-native-provenance.py+58 −0scripts/check-release-manifest.py+36 −4scripts/kepr-build-apk.sh+20 −0scripts/kepr-build-helpers.sh+45 −0scripts/test-kepr-build-helpers.sh+45 −1scripts/test-native-provenance.sh+26 −0scripts/test-release-manifest.sh+47 −1app/build.gradle+25 −1
@@ -72,7 +72,7 @@7272 "peachStoreFile", "peachStorePassword", "peachKeyAlias", "peachKeyPassword",7373 ]7474 def missingSigningProperties = signingProperties.findAll { !props.getProperty(it) }75- if (!missingSigningProperties.empty && gradle.startParameter.taskNames.any { it.toLowerCase().contains("assemblerelease") }) {75+ if (!missingSigningProperties.empty && gradle.startParameter.taskNames.any { it.toLowerCase().contains("release") }) {7676 throw new GradleException("Missing release signing inputs: ${missingSigningProperties.join(", ")}")7777 }7878 if (props.getProperty("peachStoreFile")) {@@ -222,4 +222,28 @@222222 // so the release-manifest parser would otherwise be untestable off-device.223223 testImplementation "org.json:json:20240303"224224 testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.1"225+}226+// PB-26-144: the alpha-train Play-Services identity-credentials artifact is227+// reviewed by decision rather than removed, pending non-Play device evidence.228+// A silent bump must fail with the review requirement named. The check is229+// deferred to release-task execution: resolving the release runtime classpath230+// at configuration time fails the variant model and would slow every build.231+def pinnedCredentialsIdentityVersion = "16.0.0-alpha02"232+233+tasks.matching { it.name in ["assembleRelease", "bundleRelease", "packageRelease"] }.configureEach {234+ doFirst {235+ def resolved = configurations.getByName("releaseRuntimeClasspath")236+ .resolvedConfiguration.resolvedArtifacts.find {237+ it.moduleVersion.id.group == "com.google.android.gms" &&238+ it.moduleVersion.id.name == "play-services-identity-credentials"239+ }240+ if (resolved == null || resolved.moduleVersion.id.version != pinnedCredentialsIdentityVersion) {241+ def resolvedVersion = resolved?.moduleVersion?.id?.version ?: "missing"242+ throw new GradleException(243+ "play-services-identity-credentials must remain pinned to ${pinnedCredentialsIdentityVersion}; " +244+ "resolved ${resolvedVersion}. Review the alpha artifact's manifest components and GMS " +245+ "metadata, and update docs/ANDROID-RELEASE-MANIFEST-INVENTORY.md, before bumping it.",246+ )247+ }248+ }225249 }app/drafts/B2-INTEGRATION.md+0 −172
@@ -1,172 +0,0 @@1-# B2 — Import Screen: Integration Note2-3-Draft implementation of spec B2 (lines 110–163). Three Kotlin files plus this note,4-all under `app/drafts/`. They are written to drop straight into the source tree —5-package is already `com.peachpasswords.ui.vault`.6-7-## Files to MOVE into the source set8-9-Move these from `app/drafts/` to10-`app/src/main/java/com/peachpasswords/ui/vault/` (package already correct —11-`package com.peachpasswords.ui.vault`):12-13-| Draft file | Destination | Contents |14-|---|---|---|15-| `CsvImport.kt` | `ui/vault/CsvImport.kt` | Pure Kotlin: `ParsedEntry`, `ImportParseResult`, `CsvImport` (provider detection + CSV/JSON parsers, RFC-4180 splitter) |16-| `PeachScriptImport.kt` | `ui/vault/PeachScriptImport.kt` | Pure Kotlin: PeachScript sniff/detect/decrypt/parse |17-| `ImportScreen.kt` | `ui/vault/ImportScreen.kt` | Compose UI + `ImportViewModel` |18-19-`B2-INTEGRATION.md` stays in drafts (or delete after wiring) — it is not source.20-21-No edits were made to any existing file. `PeachNav.kt`, `PeachAppNavHost.kt`,22-`VaultRepository.kt`, `VaultEntry.kt`, `VaultCrypto.kt` were read only.23-24-## Public composable signature25-26-```kotlin27-@Composable28-fun ImportScreen(onBack: () -> Unit)29-// (also has a defaulted vm = hiltViewModel() param, like TrashScreen)30-```31-32-## Nav wiring33-34-`PeachNav.Import` route already exists. In `PeachAppNavHost.kt`, replace the35-`Import` route's `SimpleStub` with:36-37-```kotlin38-ImportScreen(onBack = back)39-```40-41-where `back` is the same back lambda the other vault screens use (e.g. how42-`TrashScreen(onBack = back)` is wired). No new route, no nav-graph change needed.43-44-Note: `ImportScreen` also handles internal back navigation itself (preview/error →45-input view, sub-view → choose view); it only calls `onBack()` when at the top46-choose view or after Done. So a single `onBack=back` is correct.47-48-## VaultRepository methods used (all already exist — no new API assumed)49-50-- `suspend fun addEntry(draft: VaultEntry): VaultEntry` — import loops this51- per parsed entry (confirmed: no batch method exists).52-- `fun getEntries(): List<VaultEntry>` — used by REPLACE mode to enumerate53- current active entries.54-- `suspend fun deleteEntry(id: String)` — REPLACE soft-deletes existing active55- entries before adding the imported set. (Chose soft-delete over a hard wipe so56- a mistaken "Replace" is recoverable from Trash. If the orchestrator wants a true57- replace, swap to `purgeEntry` or `destroyVault` — but that is destructive.)58-59-`VaultEntry` drafts are built with `id = ""` (repo assigns UUID), `type = "login"`,60-and `createdAt/modifiedAt = now` (repo overrides modifiedAt with a monotonic stamp).61-62-## VaultCrypto API found (quoted from source)63-64-From `app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt`:65-66-```kotlin67-object VaultCrypto {68- const val ARGON2_MEMORY_KB = 6553669- const val ARGON2_ITERATIONS = 370- const val ARGON2_PARALLELISM = 471- const val ARGON2_HASH_LENGTH = 3272- const val SALT_SIZE = 1673- const val NONCE_SIZE = 1274- const val TAG_LENGTH_BITS = 12875- const val KEY_SIZE = 3276-77- fun deriveKey(password: String, salt: ByteArray): ByteArray // Argon2id (BouncyCastle)78- fun encrypt(plaintext: ByteArray, key: ByteArray, aad: String): ByteArray // nonce(12) || ct||tag79- fun decrypt(data: ByteArray, key: ByteArray, aad: String): ByteArray // expects nonce(12) prefix80- fun generateSalt(): ByteArray // 16 bytes81- fun zero(bytes: ByteArray)82-}83-```84-85-- KDF: Argon2id, 64 MiB memory, 3 iterations, parallelism 4, 32-byte output.86-- AEAD: AES-256-GCM, 128-bit tag, 12-byte random nonce **prepended** to the87- ciphertext (`encrypt` returns `nonce + cipher.doFinal(...)`; `decrypt` reads the88- first 12 bytes as the nonce). AAD is a UTF-8 string argument.89-90-`PeachScriptImport.decryptAndParse` is implemented end-to-end against this API91-(derive → decrypt → parse), since the on-the-wire shape is fully specified by the92-header format below. A GCM tag mismatch surfaces as `WrongPassword`.93-94-## PeachScript header / export format chosen (C2 export MUST mirror this)95-96-A PeachScript export is a single JSON object carrying a magic marker key97-`"peachscript"` (also the format version).98-99-**Plaintext:**100-```json101-{102- "peachscript": 1,103- "encrypted": false,104- "entries": [105- { "title": "...", "username": "...", "password": "...",106- "url": "...", "notes": "...", "totp": "..." }107- ]108-}109-```110-111-**Encrypted (backup-password protected):**112-```json113-{114- "peachscript": 1,115- "encrypted": true,116- "kdf": "argon2id",117- "salt": "<base64, 16 bytes = VaultCrypto.SALT_SIZE>",118- "blob": "<base64: 12-byte nonce || AES-256-GCM ciphertext||tag>"119-}120-```121-122-- `blob` is exactly `VaultCrypto.encrypt(plaintextJsonBytes, key, AAD)` output123- (nonce prepended). `salt` feeds `VaultCrypto.deriveKey(backupPassword, salt)`.124-- Decrypted plaintext is the UTF-8 bytes of the **plaintext-shape** JSON object125- above (with `"encrypted": false`).126-- **AAD is the constant string** `"peachscript_export_v1"`127- (`PeachScriptImport.PEACHSCRIPT_AAD`). C2 export must encrypt with this exact128- AAD or the GCM tag check fails and the user sees "Incorrect backup password."129-- Detection: `looksLikePeachScript` = trimmed text starts with `{` and contains130- `"peachscript"`. `isEncrypted` = contains `"encrypted": true`.131- Standard base64 (not URL-safe) is used for `salt`/`blob`.132-133-## CSV / provider detection summary134-135-`CsvImport.detectProvider(content)` returns one of:136-`"Bitwarden CSV"`, `"Bitwarden JSON"`, `"1Password CSV"`, `"Chrome CSV"`,137-`"Edge CSV"`, `"Safari CSV"`, `"CSV"` (generic), or `null` (unrecognised).138-139-- Chrome and Edge share the identical Chromium header140- (`name,url,username,password`) and are indistinguishable from content alone —141- detection returns `"Chrome CSV"`; UI copy says "Chrome/Edge". `parse` treats142- both identically.143-- Bitwarden JSON detection is a shape check (`{` + `"items": [`); only login144- items (`type` absent or `== 1`) are imported.145-- The CSV parser is a single RFC-4180-ish state machine handling quoted fields,146- embedded commas, doubled quotes (`""`→`"`), and CR/LF inside quotes.147-- `detectAndParse` returns a sealed `ImportParseResult` mapping to the spec error148- strings (UNRECOGNISED / CORRUPTED / NO_ENTRIES).149-150-## Spec error strings (in `ImportScreen.ImportErrors`)151-152-- Unrecognised PeachScript: "This doesn't look like a PeachScript export."153-- Wrong backup password: "Incorrect backup password."154-- Corrupted: "This export appears to be corrupted."155-- No entries: "No entries found in this export."156-- (extras) "Couldn't read that file." / "Unrecognised file format."157-158-## Assumptions / things for the orchestrator to confirm159-160-1. REPLACE uses soft-delete (recoverable via Trash). Change to a hard wipe if161- the spec's `RESTORE_ENTRIES` semantics require it.162-2. `GetContent()` launched with `"*/*"` (not `.csv,.json`) because some exporters163- report odd MIME types for CSV; the parser sniffs content regardless. Swap to164- `OpenDocument()` with `arrayOf("text/csv","application/json")` if a stricter165- picker is preferred.166-3. The minimal hand-rolled JSON scanners in `CsvImport`/`PeachScriptImport` avoid167- adding a JSON dependency to the pure modules. If `kotlinx.serialization` is168- already on the classpath (it is — `VaultEntry` is `@Serializable`), these could169- be swapped for a typed decode later; kept dependency-free here for testability.170-4. Entry-point wiring (Lock screen RestoreTabs pills, Settings → Vault → Import171- row) is out of scope for this draft — only the `PeachNav.Import` route swap is172- described. Those entry points just need to navigate to the existing route.app/drafts/C1/C1-INTEGRATION.md+0 −218
@@ -1,218 +0,0 @@1-# C1 — Forgot-Password Recovery (Recovery Key Escrow): Integration Contract2-3-Draft implementation of spec C1. All draft artifacts live under `app/drafts/C1/`.4-No shared/source file was edited by the subagent — every file below was read only:5-`VaultRepository.kt`, `VaultCrypto.kt`, `VaultStore.kt`, `VaultEntry.kt`,6-`RecoveryWords.kt`, `RecoveryWordList.kt`, `RecoveryWordsScreen.kt`,7-`LockScreen.kt`, `LockViewModel.kt`, `PeachNav.kt`, `PeachAppNavHost.kt`, theme8-files, `StrengthBar.kt`.9-10-The drafts compile against the REAL v2.1.38 signatures **once the orchestrator11-applies the data-model + repo deltas** described below (the new methods reference12-`StoredVault.recoveryEscrow`, `RecoveryEscrow`, and `VaultCrypto.AAD_RECOVERY`,13-which do not exist yet).14-15----16-17-## 1. Draft files and their destinations18-19-| Draft file | Destination | Kind |20-|---|---|---|21-| `RecoveryWordEntryScreen.kt` | `app/src/main/java/com/peachpasswords/ui/recovery/RecoveryWordEntryScreen.kt` | New Compose screen + `@HiltViewModel RecoveryEntryViewModel` (package `com.peachpasswords.ui.recovery` — **new package dir**) |22-| `C1-RecoveryEscrowTest.kt` | `app/src/test/java/com/peachpasswords/vault/RecoveryEscrowTest.kt` | New JUnit test (rename file to `RecoveryEscrowTest.kt`) |23-| `C1-repo-additions.kt` | *(not a file)* — apply its members/edits INTO `vault/VaultRepository.kt` | Snippet |24-| `C1-crypto-notes.md` | *(not a file)* — apply its model/crypto deltas | Notes |25-| `C1-INTEGRATION.md` | stays in drafts | This doc |26-27-> The screen lives in a NEW package `com.peachpasswords.ui.recovery`. If you28-> prefer to keep it under `ui.vault` or `ui.lock`, change the `package` line and29-> the one PeachAppNavHost import — nothing else depends on the package.30-31-Public composable signature:32-33-```kotlin34-@Composable35-fun RecoveryWordEntryScreen(36- onSuccess: () -> Unit,37- onBack: () -> Unit,38- onRestore: () -> Unit = onBack, // defaults to onBack if you don't wire Import39- vm: RecoveryEntryViewModel = hiltViewModel(),40-)41-```42-43----44-45-## 2. Shared-file edits the orchestrator must make46-47-### 2a. `vault/VaultStore.kt` — data model (from C1-crypto-notes.md §2)48-49-Add a nullable `recoveryEscrow` field to `StoredVault` and a new `RecoveryEscrow`50-data class:51-52-```kotlin53-@Serializable54-data class StoredVault(55- val version: Int = 1,56- val salt: String,57- val blob: String,58- val recoveryEscrow: RecoveryEscrow? = null, // NEW59-)60-61-@Serializable62-data class RecoveryEscrow(63- val salt: String, // base64, 16B — HKDF salt for deriveRecoveryKey64- val blob: String, // base64 — VaultCrypto.encrypt(slotAPlaintext, recoveryKey, AAD_RECOVERY)65-)66-```67-68-`VaultCodec` already uses `ignoreUnknownKeys = true; encodeDefaults = true`, so69-old vaults decode with `recoveryEscrow = null` and no migration is needed.70-71-### 2b. `vault/VaultCrypto.kt` — new AAD constant72-73-Add beside the other AAD constants:74-75-```kotlin76-const val AAD_RECOVERY = "recovery_escrow_v1"77-```78-79-### 2c. `vault/VaultRepository.kt` — methods + edits (from C1-repo-additions.kt)80-81-1. **REPLACE the body of the existing `setRecoveryWords`** so it also seals the82- escrow (snippet §3a) — adds `buildRecoveryEscrow()` and83- `persistSlotAWithEscrow()` private helpers.84-2. **Edit `changePassword`** (snippet §3b): the single `val next = StoredVault(...)`85- line must carry `recoveryEscrow = slotA.recoveryEscrow` forward. The escrow86- seals the slot-A *plaintext*, which a password change does not alter, so it87- stays valid — preserve it, do not regenerate.88-3. **ADD** `unlockWithRecoveryWords(words): Boolean`,89- `resetPasswordWithRecoveryWords(words, newPassword): Boolean`, and90- `hasRecoveryEscrow(): Boolean` (snippet §3c).91-4. Add import `import javax.crypto.AEADBadTagException` (referenced in notes; the92- snippet itself catches broad `Exception`, so this import is optional).93-94-> **API-shape deviation from the brief, flagged:** the brief specifies95-> `unlockWithRecoveryWords(words): ByteArray?` and96-> `resetPasswordWithRecoveryKey(vaultKey, newPassword)`. There is no single97-> detached "vault key" in this codebase that both decrypts slot A and survives a98-> password change (slot A is wrapped under the rotating Argon2id key). So the99-> escrow seals the **slot-A plaintext envelope**, `unlockWithRecoveryWords`100-> returns `Boolean` and adopts that plaintext as the live session, and101-> `resetPasswordWithRecoveryWords(words, newPassword)` re-seals + unlocks in one102-> call. If you want to preserve the brief's exact signatures, they can wrap103-> these, but the Boolean form is what the screen and tests use.104-105-### 2d. `ui/PeachNav.kt` — new route106-107-Add one destination (mirrors `RecoverySetup`/`RecoveryView`):108-109-```kotlin110-data object RecoveryEntry : PeachNav("recovery/entry")111-```112-113-### 2e. `ui/PeachAppNavHost.kt` — register the composable114-115-Add import `import com.peachpasswords.ui.recovery.RecoveryWordEntryScreen` and a116-composable. The existing `nav`/`back` lambdas are in scope:117-118-```kotlin119-composable(PeachNav.RecoveryEntry.route) {120- RecoveryWordEntryScreen(121- onSuccess = {122- navController.navigate(PeachNav.VaultList.route) {123- popUpTo(PeachNav.Lock.route) { inclusive = true }124- }125- },126- onBack = back,127- onRestore = { nav(PeachNav.Import) },128- )129-}130-```131-132-(`onSuccess` pops Lock off the back stack, matching how `RecoverySetup` routes133-into the vault. `popUpTo(0)` as in the brief also works but would clear the whole134-stack; `popUpTo(Lock)` is the established pattern here.)135-136-### 2f. `ui/lock/LockScreen.kt` — "Forgot your password?" entry point137-138-**Reality check / deviation flagged:** the brief assumes a `hasVault` unlock139-state that already shows restore affordances. In the real `LockScreen`, the140-restore tabs (`RestoreTabs`) render only in the `!state.hasVault` (create) branch.141-The "Forgot your password?" link must be added to the **unlock** branch, where142-there is currently no such affordance. Place it inside the `GlassPanel`, after143-the biometric `"Use biometrics"` block, guarded by `state.hasVault`:144-145-```kotlin146-if (state.hasVault) {147- Spacer(Modifier.height(8.dp))148- Text(149- "Forgot your password?",150- color = PeachColors.T2,151- style = PeachType.labelMono.copy(fontSize = 11.sp),152- textAlign = TextAlign.Center,153- modifier = Modifier.fillMaxWidth()154- .clip(RoundedCornerShape(8.dp))155- .clickable { onNavigate(PeachNav.RecoveryEntry) }156- .padding(vertical = 8.dp),157- )158-}159-```160-161-`LockScreen` already has `onNavigate: (PeachNav) -> Unit` in scope (it is how162-`RestoreTabs` navigates), so **no new screen parameter is needed** — do NOT add163-an `onForgotPassword` callback as the brief's pseudo-code implies; reuse164-`onNavigate`. `PeachColors`, `PeachType`, `RoundedCornerShape`, `clickable`,165-`clip`, `TextAlign` are all already imported in `LockScreen.kt`.166-167----168-169-## 3. New resources / dependencies170-171-- **No new resources.** The brief says to load BIP39 from172- `res/raw/bip39_english.txt` — that file does **not** exist and is **not**173- needed. The 2048-word list is the Kotlin `val WORD_LIST` in174- `vault/RecoveryWordList.kt`, already used by `getWordSuggestions`,175- `findInvalidWords`, `wordsToRootKeyMaterial`. The screen imports `WORD_LIST`176- and `getWordSuggestions` directly. Do not add a raw asset.177-- **No new Gradle dependencies.** Argon2id/HKDF/Blake3 are already provided by178- BouncyCastle (used by `VaultCrypto` / `RecoveryWords`). The recovery key uses179- the existing `deriveRecoveryKey` (HKDF-SHA256), not a new KDF.180-- **No new string resources** — copy is inline (the codebase uses inline literals181- throughout, e.g. LockScreen, RecoveryWordsScreen).182-183----184-185-## 4. Where the brief's assumed API differed from reality (full list)186-187-| # | Brief assumption | Reality / what the drafts use |188-|---|---|---|189-| 1 | `StoredVault` has `slotA`, `slotDuress`, `recoveryEscrow` fields | `StoredVault` = `(version, salt, blob)`, one slot. Duress/decoy is a separate `StoredVault` under a different prefs key. Drafts add ONE nullable `recoveryEscrow` field to `StoredVault`. |190-| 2 | `VaultCrypto.encryptRaw/decryptRaw/encryptSlot` | None exist. Use `encrypt(plaintext, key, aad)` / `decrypt(data, key, aad)` (12-byte nonce managed internally; AAD is a required String). New `AAD_RECOVERY` constant. |191-| 3 | `deriveRecoveryKey(joinedWordString, salt)` via **Argon2id** | `deriveRecoveryKey(material: ByteArray, salt): SecretKeySpec` ALREADY EXISTS using **HKDF-SHA256** (`info = "peach-recovery-v1"`). `material` is the 16-byte entropy from `wordsToRootKeyMaterial(words)`, not the joined string. |192-| 4 | Escrow the "vault master key" from `currentVaultKey()` | `currentVaultKey()` is the rotating Argon2id password key — escrowing it breaks after a password change. Drafts escrow the **slot-A plaintext envelope** instead (stable; carries entries + rootKey). |193-| 5 | `unlockWithRecoveryWords(): ByteArray?` + `resetPasswordWithRecoveryKey(vaultKey, …)` | Returns `Boolean` and adopts the recovered payload; reset is `resetPasswordWithRecoveryWords(words, newPassword): Boolean` (re-seal + unlock in one call). No detached vault key. |194-| 6 | BIP39 list in `res/raw/bip39_english.txt`; "add it if missing" | Lives in Kotlin `WORD_LIST` (RecoveryWordList.kt). No raw asset. Note the list has 2052 entries (index 0 and 1 both `"abandon"`); the existing encode/decode already accounts for this — do not "fix" it. |195-| 7 | `secureRandom(16)`, `blake3(...)` helpers; add `recoveryWordsHash` | `VaultCrypto.generateSalt()` (16B) and the existing `recoveryWordsHash(words)` cover these; `setRecoveryWords` already stores the BLAKE3 hash. |196-| 8 | §3b: escrow needs no re-seal because it seals "the vault master key" | Wrong rationale, right conclusion: escrow seals the slot-A plaintext (unchanged by a password change), so it stays valid — but `changePassword` rebuilds `StoredVault` and would DROP the field. Required edit: carry `recoveryEscrow` forward. |197-| 9 | A shared `PeachField` underline component exists | It does not. `LockScreen` uses a private `UnderlineField`. The draft screen uses its own local underline fields (same idiom). |198-| 10 | LockScreen `hasVault` unlock state already shows restore affordances; add `onForgotPassword` callback | Restore tabs render only in the `!hasVault` (create) branch. Add the link to the unlock branch and reuse the existing `onNavigate(PeachNav.RecoveryEntry)` — no new callback param. |199-| 11 | `MIN_PASSWORD_LENGTH` / strength gate | Reuse `MIN_PASSWORD_LENGTH = 12` and `MIN_CREATE_STRENGTH = 2` from `ui/lock/LockViewModel.kt`; `scorePassword` returns 0–4. The screen gates on `score >= 2` + match + length, matching create-vault. |200-201----202-203-## 5. Security notes (for reviewer)204-205-- The escrow blob is AES-256-GCM under a key the recovery words derive via HKDF.206- AAD `recovery_escrow_v1` is distinct from `slot_a_v1`, so an escrow blob can207- never be swapped in as a slot-A blob.208-- Wrong words surface as `AEADBadTagException` (GCM tag mismatch) or an209- `IllegalArgumentException` from `wordsToRootKeyMaterial` (bad BIP39 checksum/210- unknown word) — both map to `false` / `null` in the repo, and to the211- "Incorrect recovery words" UI error.212-- All transient key material (`wordsToRootKeyMaterial` entropy, the213- `SecretKeySpec.encoded` copy, the decoded plaintext) is zeroed in `finally`214- blocks, consistent with the existing repo's `VaultCrypto.zero` discipline.215-- The escrow weakens the threat model deliberately: anyone with the 12 words can216- decrypt the vault without the password (that is the feature). This matches the217- browser design referenced in CONTINUITY.md. Recovery is never offered for the218- decoy/duress slot (`persistSlotAWithEscrow` refuses in `decoyMode`).app/drafts/C2-INTEGRATION.md+0 −142
@@ -1,142 +0,0 @@1-# C2 — Export Screen: Integration Note2-3-Draft implementation of spec C2 (lines 289–337). Three Kotlin files plus this4-note, all under `app/drafts/`. Package is already `com.peachpasswords.ui.vault`,5-so they drop straight into the source tree. No existing file was edited6-(PeachNav.kt, PeachAppNavHost.kt, VaultRepository.kt, VaultCrypto.kt,7-VaultEntry.kt, ImportScreen.kt, RecoveryWordsScreen.kt, theme files were read8-only).9-10-## Files to MOVE into the source set11-12-| Draft file | Destination | Contents |13-|---|---|---|14-| `PeachScriptExport.kt` | `ui/vault/PeachScriptExport.kt` | Pure Kotlin: `buildPlaintext` / `buildEncrypted`, hand-rolled JSON with escaping |15-| `CsvExport.kt` | `ui/vault/CsvExport.kt` | Pure Kotlin: `toCsv` + `encodeField` (RFC-4180 + formula-injection guard) |16-| `ExportScreen.kt` | `ui/vault/ExportScreen.kt` | Compose UI + `ExportViewModel` + `scorePassword`/`strengthLabel` |17-18-`C2-INTEGRATION.md` stays in drafts (or delete after wiring) — it is not source.19-20-## Public composable signature21-22-```kotlin23-@Composable24-fun ExportScreen(onBack: () -> Unit)25-// (also has a defaulted vm = hiltViewModel() param, like ImportScreen / TrashScreen)26-```27-28-## Nav wiring (one line)29-30-`PeachNav.Export` route already exists. In `PeachAppNavHost.kt`, replace the31-`Export` route's `SimpleStub` with:32-33-```kotlin34-ExportScreen(onBack = back)35-```36-37-where `back` is the same back lambda the other vault screens use (e.g. how38-`ImportScreen(onBack = back)` is wired). No new route, no nav-graph change.39-40-`ExportScreen` handles its own internal back: a sub-view (PeachScript / CSV)41-returns to the choose view; the choose view calls `onBack()`. A single42-`onBack=back` is correct.43-44-## Strength scorer thresholds chosen45-46-`scorePassword(pw): Int` returns 0–4 (local, dependency-free, no network):47-48-- +1 if length ≥ 849-- +1 if length ≥ 1250-- +1 if ≥ 3 of {lowercase, uppercase, digit, symbol} present51-- +1 if all 4 classes present52-- empty → 0, clamped to 0..453-54-Labels: 0 very weak · 1 weak · 2 fair · 3 good · 4 strong.55-56-The C2 gate is **score ≥ 3 ("good")**. `[Generate backup]` is disabled until57-`score ≥ 3` AND the two password fields match AND the vault is non-empty. When58-a non-empty password scores < 3 the breach-colour error59-`"Backup password too weak (score < 3)"` is shown (spec line 306). The 4-segment60-bar fills `score` segments and tints to the accent once "good".61-62-## Round-trip confirmation (buildEncrypted ⇄ PeachScriptImport)63-64-`PeachScriptImport.decryptAndParse(buildEncrypted(es, pw), pw)` returns65-`Success` with the same six fields per entry. Reasoning, field by field against66-the pinned format in `B2-INTEGRATION.md` and the importer source:67-68-1. **Envelope shape.** `buildEncrypted` emits69- `{"peachscript":1,"encrypted":true,"kdf":"argon2id","salt":"<b64>","blob":"<b64>"}`.70- The importer reads `salt` and `blob` via `jsonRawString` (a `"key":"..."`71- regex) — key names and JSON-string shape match exactly.72-2. **Base64.** Both sides use `java.util.Base64` standard (non-URL-safe) codec:73- `getEncoder()` here, `getDecoder()` there. Salt is 16 bytes74- (`VaultCrypto.generateSalt()` = `SALT_SIZE`); blob is `nonce(12) || ct||tag`,75- so `blob.size > NONCE_SIZE` — passes the importer's length guards.76-3. **KDF.** `salt` feeds `VaultCrypto.deriveKey(pw, salt)` on both sides77- (Argon2id, identical params from the shared `VaultCrypto` constants).78-4. **AEAD + AAD.** `blob` is exactly `VaultCrypto.encrypt(plaintextBytes, key,79- PeachScriptImport.PEACHSCRIPT_AAD)`. The importer calls80- `VaultCrypto.decrypt(blob, key, PEACHSCRIPT_AAD)` with the **same constant**81- AAD (`"peachscript_export_v1"`). `encrypt` prepends the 12-byte nonce;82- `decrypt` strips the first 12 bytes as the nonce. The GCM tag therefore83- verifies, so wrong-password / tamper paths surface as84- `DecryptResult.WrongPassword` exactly as designed.85-5. **Inner plaintext.** The decrypted bytes are86- `buildPlaintext(es)` =87- `{"peachscript":1,"encrypted":false,"entries":[{...}]}`. The importer's88- `parsePlaintext` uses `extractArrayBody("entries")` +89- `splitTopLevelObjects` + `jsonString` for `title/username/password/url/90- notes/totp` — the exact keys this writer emits.91-6. **Escaping.** `buildPlaintext` escapes `\`, `"`, and control chars (`\n \r92- \t \b \f`, `\uXXXX` for the rest). The importer's `unescapeJson` reverses93- `\n \t \r \" \\ \/ \uXXXX`, so any value round-trips. (We never emit `\/`;94- forward slash is left literal, which is valid JSON and read back verbatim.)95-96-The only normalisation is field projection (see assumptions): empty strings97-become `null` on the way back because the importer's `jsonString` maps `""` →98-`null`, and `parsePlaintext` drops entries whose `title` is blank. So entries99-with a non-blank title and otherwise-null optional fields round-trip to the same100-`ParsedEntry` shape.101-102-## VaultRepository methods used (all already exist — no new API assumed)103-104-- `fun getEntries(): List<VaultEntry>` — returns active (non-deleted) entries105- (verified: `entryList.filter { it.deletedAt == null }`). Used for both the106- count/empty-vault gate and the export payload.107-108-`ExportViewModel` injects `VaultRepository` + `@ApplicationContext Context`109-(for SAF `openOutputStream`), exactly like `ImportViewModel`.110-111-## SAF / clipboard patterns112-113-- PeachScript save: `CreateDocument("*/*")`, suggested name `peach-backup.peach`114- (mirrors `RecoveryWordsScreen`'s `CreateDocument` save pattern). `"*/*"` is115- used because there is no registered MIME type for `.peach`.116-- CSV save: `CreateDocument("text/csv")`, suggested name `peach-export.csv`.117-- Copy to clipboard uses `ClipboardManager` /118- `ClipData.newPlainText("peach backup", json)` — same approach as119- RecoveryWordsScreen's "copy all words".120-121-## Assumptions / things for the orchestrator to confirm122-123-1. **`email` → `username` fold.** PeachScript and the CSV `username` column have124- no `email` field, and the importer reads only six keys. When `username` is125- blank we emit `email` in its place (so a webmail login's address is not lost).126- If the orchestrator prefers email dropped, change the `e.username ?: e.email`127- fallbacks in both `PeachScriptExport.appendEntry` and `CsvExport.toCsv`.128-2. **Only the six PeachScript fields are exported.** Card/passkey/tags/history129- fields are intentionally NOT in PeachScript or CSV (neither format nor the130- B2 importer model them). A full-fidelity vault backup would need a richer131- format — out of scope for C2, which targets interop with the B2 importer.132-3. **Empty-vault gate** is enforced in the UI (`entryCount() == 0` disables the133- export button and shows `"Your vault is empty — nothing to export."`). The134- spec says "Empty vault" error if 0 entries; exact copy can be tuned.135-4. **Strength gate copy** uses the spec's literal string136- `"Backup password too weak (score < 3)"` in breach colour.137-5. **CSV MIME** is `text/csv` for the picker (stricter than Import's `"*/*"`,138- since we control the extension on write). Swap to `"*/*"` if a device's SAF139- provider rejects `text/csv`.140-6. Entry-point wiring (Settings → Vault card → "Export" row) is out of scope for141- this draft — only the `PeachNav.Export` route swap is described.142-```app/drafts/C7/C7-INTEGRATION.md+0 −329
@@ -1,329 +0,0 @@1-# C7 — Chirp Sync Transport (TCP + mDNS + Noise NK): Integration Note2-3-Draft implementation of spec C7. Five Kotlin files plus this note, all under4-`app/drafts/C7/`. Package is already `com.peachpasswords.sync`, so the source5-files drop straight into the sync tree. **No existing file was edited** — every6-shared file (ChirpPairing.kt, NoiseNK.kt, VaultSyncAdapter.kt,7-ChirpSyncCoordinator.kt, ChirpPairViewModel.kt, SyncViewModel.kt,8-SettingsCardBodies.kt, VaultModule.kt, AndroidManifest.xml, build.gradle) was9-read only.10-11-> **Read this first.** The C7 brief substantially overstates what is missing and12-> invents the entire crypto surface. The transport primitives the brief assumes13-> are absent (Noise NK handshake, identity frames, per-entry sync, SAS,14-> PairedDevice) **all already exist** in `com.peachpasswords.sync`. The brief's15-> proposed `_peach._tcp` mDNS + `ServerSocket` design is also an **alternative16-> transport** to the one already shipped (audio-chirp ephemeral key exchange +17-> WebSocket/subnet-probe sync). These drafts add the TCP+mDNS transport on top of18-> the **real** crypto/sync APIs, and flag every divergence below.19-20----21-22-## Files to MOVE into the source set23-24-| Draft file | Destination | Contents |25-|---|---|---|26-| `PairedDeviceStore.kt` | `sync/PairedDeviceStore.kt` | `@Singleton` EncryptedSharedPreferences registry of the REAL `PairedDevice`; `getAll/get/upsert/remove/clear/updateLastSeen/updateLastSync/observeAll` |27-| `PairingFrames.kt` | `sync/PairingFrames.kt` | `writeFrame/readFrame` (4-byte BE length prefix), `SocketFrameIO` (implements the real `PairingTransport` interface over a TCP socket), `sendEncrypted/receiveEncrypted` |28-| `PairingServer.kt` | `sync/PairingServer.kt` | TCP `ServerSocket` + `NsdManager` `_peach._tcp` advertisement; `noiseNKResponder` handshake; `runChirpSyncResponder` round; `PairingServerEvent`. **Name clash, see below.** |29-| `PairingTransport.kt` | `sync/PairingDiscoveryClient.kt` | `NsdManager` discovery (`callbackFlow`) + TCP `connectAndSync` initiator; `DiscoveredPeer`, `PairingResult`, `PairingError`. **Renamed, see below.** |30-| `C7-ChirpTransportTest.kt` | `app/src/test/java/com/peachpasswords/sync/C7ChirpTransportTest.kt` | 5 pure-JVM/Piped-stream tests |31-32-`C7-INTEGRATION.md` stays in drafts — it is not source.33-34-### Name collisions the orchestrator MUST resolve35-36-1. **`PairingServer`** — the brief wants a `@Singleton class PairingServer`. A37- `data class PairingServer(val transport, val peerIp)` **already exists** in38- `ChirpPairing.kt`. The draft's class would collide. Options:39- - (preferred) rename the draft class to **`PairingListener`** /40- **`MdnsPairingServer`** and keep the existing `data class PairingServer`; or41- - rename the existing data class (it is only used inside `ChirpPairingDeps`).42- The draft is written as `class PairingServer` per the brief; pick a rename43- before merge or the module will not compile.44-2. **`PairingTransport`** — the brief wants a `@Singleton class PairingTransport`.45- `PairingTransport` is **already an interface** in `ChirpPairing.kt`46- (`send/receive/close`) consumed by the existing handshake. The draft file is47- therefore authored as **`class PairingDiscoveryClient`** (destination filename48- `PairingDiscoveryClient.kt`) to avoid shadowing the interface. `SocketFrameIO`49- in `PairingFrames.kt` **implements that real interface**, so the existing50- `runPairingInitiator`/`runPairingResponder` could drive a TCP socket unchanged51- if those private functions are promoted (see item 4 below).52-53----54-55-## TOP API DISCREPANCIES (brief vs reality)56-57-### 1. NoiseNK — the single most important reconciliation58-59-The brief assumes a stateful `NoiseNK` object:60-```kotlin61-val handshake = noiseNK.acceptHandshake(stream, out) // server62-val handshake = noiseNK.initiateHandshake(stream, out, remotePub) // client63-handshake.sendCipher; handshake.recvCipher; handshake.handshakeHash64-```65-**None of this exists.** `NoiseNK.kt` exposes two **suspend free functions**:66-```kotlin67-suspend fun noiseNKInitiator(68- responderStaticPublicKey: ByteArray,69- send: suspend (ByteArray) -> Unit,70- receive: suspend () -> ByteArray,71-): NoiseNKSession72-73-suspend fun noiseNKResponder(74- ourStaticPrivateKey: ByteArray,75- ourStaticPublicKey: ByteArray,76- send: suspend (ByteArray) -> Unit,77- receive: suspend () -> ByteArray,78-): NoiseNKSession79-```80-`NoiseNKSession` has **one bidirectional cipher** — `encrypt(plaintext)`,81-`decrypt(ciphertext)`, and `val handshakeHash` — **not** split82-`sendCipher`/`recvCipher`. Bound to:83-- The drafts pass `transport::send` / `transport::receive` (where `transport` is84- a `SocketFrameIO`) as the handshake's `send`/`receive`. The handshake messages85- are themselves length-prefixed frames.86-- All post-handshake encryption uses `session.encrypt` / `session.decrypt`.87-- Noise **NK** = responder has a static key, initiator does not; the initiator88- must already KNOW the responder's static public key. The drafts use the89- device's **long-term sync identity** (`deriveSyncIdentityKeypair(masterKey,90- deviceId)`) as the responder static, and publish its public half in the mDNS91- TXT `pk` record so the initiator can pin it. (The brief's `remotePublicKey`92- "from TXT pk" maps onto this exactly — but it is the *responder's static*, not93- an ephemeral.)94-- SAS: `SASDerivation.derive(session.handshakeHash)` (the existing helper; there95- is also `derivePairingSAS(hash)`). The brief's `deriveSAS(...)` does not exist.96-97-### 2. VaultSyncAdapter — no buildRequest/applyRequest/buildResponse/applyResponse98-99-The brief calls `syncAdapter.buildResponse(req)` / `applyRequest(req)` /100-`buildRequest()` / `applyResponse(resp)`. **None exist.** `VaultSyncAdapter`101-implements `ChirpSyncVaultAdapter` (`computeVaultId`, `getOurDeviceId`,102-`getLocalVersion`, `buildEntryManifest`, `buildTombstoneManifest`,103-`getEncryptedEntries`, `applyEntries`, `applyTombstones`). The actual sync is a104-**full multi-message round** driven by the existing free functions:105-```kotlin106-suspend fun runChirpSyncInitiator(session: ChirpSyncSession, vault: ChirpSyncVaultAdapter): SyncOutcome107-suspend fun runChirpSyncResponder(session: ChirpSyncSession, vault: ChirpSyncVaultAdapter): SyncOutcome108-```109-over a `ChirpSyncSession(remoteStaticPublicKey, send, receive, close)`. Bound to:110-- `PairingServer` runs `runChirpSyncResponder`; `PairingDiscoveryClient` runs111- `runChirpSyncInitiator`. Both build a `ChirpSyncSession` via112- `chirpSessionOver(noiseSession, socketFrameIO)` — `send` = `encrypt → frame`,113- `receive` = `frame → decrypt`. `ChirpSyncSession.send` is **non-suspending**114- (matches `openChirpSyncSession`), so `SocketFrameIO.sendBlocking` is used115- there, not the suspend `send`.116-- The adapter is built per round with `VaultSyncAdapter(repo, deviceId)`; pass a117- `vaultFactory: () -> ChirpSyncVaultAdapter?` (null when the vault is locked).118-119-### 3. PairedDevice / TrustStatus — already exist, different shape120-121-The brief redefines `PairedDevice(id, name, publicKey: ByteArray, lastSeen,122-trustStatus, lastSyncAt)` and a `TrustStatus { TRUSTED, UNVERIFIED, REVOKED }`123-enum. **The real `PairedDevice` (PairedDevice.kt) is reused verbatim** and has a124-different shape:125-```kotlin126-@Serializable data class PairedDevice(127- val deviceId: String, val deviceName: String?, val deviceType: String?,128- val longTermPublicKeyHex: String?, val signingPublicKeyHex: String?,129- val trustSource: String?, val wsPort: Int?, val pairedAt: Long,130- val lastSyncedAt: Long?, val lastKnownIp: String?,131-)132-```133-Field mapping (brief → real):134-- `id` → `deviceId`; `name` → `deviceName`; `publicKey: ByteArray` →135- `longTermPublicKeyHex: String?` (hex, not Base64/ByteArray); `lastSyncAt` →136- `lastSyncedAt`.137-- `lastSeen` → **no equivalent**. The store's `updateLastSeen(id, ip)` refreshes138- `lastKnownIp` instead (closest real analogue). If a real "last seen" timestamp139- is wanted, **that is an integration delta**: add `val lastSeen: Long? = null`140- to `PairedDevice` (defaulted so serialization stays backward-compatible).141-- `trustStatus: TrustStatus` → **no enum exists**; trust is `trustSource: String?`142- ("direct" / "manifest"). **Integration delta if a tri-state TRUSTED/UNVERIFIED/143- REVOKED model is required:** add an enum + field to `PairedDevice` (defaulted).144- The drafts set `trustSource = "direct"` on pair, matching145- `ChirpPairing.frameToPairedDevice`. The brief's `confirmSAS → TRUSTED` /146- `rejectSAS → remove` flow maps onto: keep the device on confirm, `remove(id)`147- on reject. If you add the enum, set it to TRUSTED on confirm.148-149-`TrustBadge`, `GhostButton`, `ChirpPairUiState`, `SyncStatus.Busy`, and150-`syncAdapter.applyResponse` referenced by the brief's UI/VM snippets **do not151-exist either** — see the wiring sections.152-153-### 4. (architectural) The mDNS+ServerSocket transport is NEW; the chirp transport already ships154-155-`ChirpPairing.runChirpPairing(...)` already implements an end-to-end pairing156-flow: ggwave **audio chirp** carries the peer's ephemeral X25519 key, then157-`noiseNKInitiator/Responder` runs over the `PairingTransport` interface, identity158-`PAIR_IDENTITY` frames are exchanged (`encodePairingFrame`/`decodePairingFrame`,159-both **file-private**), and `SASDerivation.derive` produces the SAS. Sync uses160-`openChirpSyncSession` (WebSocket) + subnet probe (`probeSubnetForPeer`). The C7161-brief's mDNS+`ServerSocket` path is a **second discovery/transport** that reuses162-the same Noise+sync primitives. The drafts re-implement the `PAIR_IDENTITY`163-encode/parse as `internal` shims (`encodePairIdentityFrame`/164-`parsePairIdentityFrame` in `PairingServer.kt`) **because the originals are165-private**. **Cleaner integration:** promote `ChirpPairing`'s166-`encodePairingFrame`/`decodePairingFrame`/`frameToPairedDevice` from `private` to167-`internal` and delete the draft shims, so there is exactly one identity-frame168-codec. Likewise consider promoting `runPairingInitiator`/`runPairingResponder` to169-`internal` so the TCP transport can reuse them via `SocketFrameIO` instead of170-re-deriving the handshake-then-identity sequence.171-172----173-174-## Shared-file edits the orchestrator must make175-176-### ChirpPairViewModel (`ui/pairing/ChirpPairViewModel.kt`)177-178-The brief's rewrite (`ChirpPairUiState.Listening/Handshake/VerifySAS/Paired/...`,179-`uiState =`) does **not** match reality. The real VM exposes:180-- `val progress: StateFlow<PairingProgress>` where181- `PairingProgress(phase: PairingPhase, peerDeviceName: String?, errorMessage:182- String?)` and `PairingPhase` ∈ {IDLE, LISTENING, CHIRPING, HANDSHAKE, PAIRED,183- TIMEOUT, MIC_DENIED, VERSION_MISMATCH, HANDSHAKE_FAILED} (PairingProgress.kt).184-- `val sasCode: StateFlow<String?>` and `fun confirmSas(accepted: Boolean)`185- (a `CompletableDeferred<Boolean>` gate) — NOT separate `confirmSAS()/rejectSAS()`.186-- `fun startPairing()` already runs the real `runChirpPairing(deps(master),187- role = INITIATOR)`.188-189-The brief's "`runChirpPairing()` throws UnsupportedOperationException" is **stale**190-— `runChirpPairing` is fully implemented. What is actually stubbed is two methods191-on the VM's `ChirpPairingDeps`:192-```kotlin193-override suspend fun completePairing(paired: PairedDevice) { /* TODO */ }194-override suspend fun openPairingTransport(endpoint): PairingTransport =195- throw UnsupportedOperationException("...until sync persistence")196-override suspend fun openPairingServer(): PairingServer =197- throw UnsupportedOperationException("...until sync persistence")198-```199-**Minimal real wiring (no UI-state rewrite needed):**200-1. Inject `PairedDeviceStore` (and `PairingDiscoveryClient` / the renamed201- `PairingServer`) into `ChirpPairViewModel`.202-2. Implement `completePairing(paired)` → `deviceStore.upsert(paired)`.203-3. Implement `openPairingTransport(endpoint)` → return a `SocketFrameIO` over204- `Socket(endpoint.ip, endpoint.port)` (this satisfies the existing205- `PairingTransport` interface and unblocks `runResponderHandshake`).206-4. Implement `openPairingServer()` → bind a `ServerSocket`, `accept()` one207- client, wrap it in `SocketFrameIO`, return `PairingServer(transport, peerIp)`208- (the existing data class). (Or fold this into the new mDNS server.)209-5. SAS confirm already persists via `confirmSas(true)` → `completePairing`; on210- `confirmSas(false)` the flow throws `sas_rejected` and nothing is stored211- (matches the brief's `rejectSAS` intent).212-213-> If the product genuinely wants the brief's mDNS pairing instead of chirp, that214-> is a larger VM change: add a path that calls215-> `PairingDiscoveryClient.discoverPeers().first()` → `connectAndSync(...)` →216-> surface SAS through `sasCode`. That is **net-new UI behavior**, not a one-line217-> swap; flag for product before building.218-219-### SyncViewModel (`ui/sync/SyncViewModel.kt`)220-221-The brief's `SyncStatus.Busy`, `deviceStore.observeAll().stateIn(...)`,222-`transport.discoverPeers(5_000L)`, `connectAndSync(peer)` map onto reality as:223-- `SyncStatus` is `{ Idle, Syncing, LastSynced(ts), Error(msg), Offline }` — use224- `Syncing` where the brief says `Busy`.225-- Add to the VM:226- ```kotlin227- // inject PairedDeviceStore + PairingDiscoveryClient228- val pairedDevices: StateFlow<List<PairedDevice>> =229- deviceStore.observeAll()230- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())231-232- fun unpairDevice(id: String) = viewModelScope.launch { deviceStore.remove(id) }233-234- fun syncNow() = viewModelScope.launch {235- val master = vault.syncMasterKey() ?: return@launch236- val identity = buildLocalIdentity(context, master)237- _status.value = SyncStatus.Syncing238- pairedDevices.value.forEach { dev ->239- discoveryClient.syncWithKnownDevice(dev.deviceId, identity, ::buildAdapter)240- }241- VaultCrypto.zero(master)242- _status.value = SyncStatus.Idle243- }244- ```245- `observeAll()` is provided by `PairedDeviceStore`. `buildAdapter()` already246- exists. `syncWithKnownDevice` is on `PairingDiscoveryClient`. (`triggerSync()`247- already returns `Offline` when there is nothing to dial — keep it, or route it248- through `syncNow`.)249-250-### SettingsCardBodies.SyncBody (`ui/settings/SettingsCardBodies.kt`)251-252-The brief's `GhostButton`, `TrustBadge`, `PeachType.bodyMono/labelMono/253-settingsLede`, `pairedDevices.forEach`, `vm.syncNow()` snippet does **not** match254-the file's vocabulary. Reality:255-- `SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit)` is a **private256- @Composable** with NO ViewModel and NO device list today — it shows static257- PAIRING/DEVICE FLOW rows and navigates to `PeachNav.ChirpPair`.258-- The real helpers are `SubLabel`, `RowLine`, `RowScope.Name`, `ValueText`,259- `SubtleButton`, `Hint`, `ProBadge` — **not** `GhostButton`/`TrustBadge`.260-- `PeachType.bodyMono`, `PeachType.labelMono`, `PeachType.settingsLede` **do261- exist** (PeachType.kt) — those three names are correct.262-263-**To show real devices:** change `SyncBody`'s signature to take the VM (or a264-`pairedDevices: List<PairedDevice>` + callbacks) and render with the existing265-helpers, e.g.:266-```kotlin267-if (pairedDevices.isEmpty()) {268- Text("No paired devices yet.", color = fg.copy(alpha = 0.7f),269- fontFamily = PeachType.Body, fontSize = 12.sp)270-} else pairedDevices.forEach { d ->271- RowLine(fg) {272- Name(d.deviceName ?: d.deviceId, fg)273- ValueText(d.lastSyncedAt?.let { "synced" } ?: "never", fg)274- }275-}276-if (pairedDevices.isNotEmpty()) RowLine(fg) { Name("Sync", fg); SubtleButton("sync now", fg) { vm.syncNow() } }277-```278-Use a `SubtleButton` (real) rather than `GhostButton` (nonexistent). Trust state:279-render `d.trustSource` as text, or add a real `TrustBadge` composable if the enum280-delta (§3) is adopted. The caller of `SyncBody` lives in this same file's card281-dispatcher — pass the VM/state through.282-283-### Hilt (`di/VaultModule.kt` or a new module)284-285-`PairedDeviceStore`, `PairingServer`/`PairingListener`, and286-`PairingDiscoveryClient` are all `@Singleton class ... @Inject constructor(...)`287-with only `@ApplicationContext Context` + other `@Inject` singletons — so Hilt288-constructs them with **no `@Provides`/`@Binds` needed**. `VaultModule` is a289-`@Binds` module and needs no change. (Add providers only if you want to inject290-them behind an interface.)291-292-### AndroidManifest.xml293-294-`INTERNET` is **already present** (line 5). Add only:295-```xml296-<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />297-<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />298-```299-`CHANGE_WIFI_MULTICAST_STATE` is required for mDNS/NSD multicast on Wi-Fi.300-(NsdManager on recent Android also benefits from acquiring a301-`WifiManager.MulticastLock` at runtime — consider adding one around discovery.)302-303-### build.gradle304-305-**No new dependencies.** `androidx.security:security-crypto:1.1.0-alpha06`306-(line 87) and `org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1` (line 107)307-are present; `NsdManager`/`ServerSocket`/`Socket` are framework/JDK. The test308-file uses only JUnit + kotlinx-coroutines + BouncyCastle, all already on the test309-classpath (see `ChirpSyncTransportTest`).310-311----312-313-## Tests (`C7-ChirpTransportTest.kt`)314-315-Pure-JVM, no Robolectric, matching `ChirpSyncTransportTest`'s idiom:316-1. `PairedDevice` list JSON round-trip (the store's serialization layer).317-2. `upsert`-by-`deviceId` replaces rather than duplicates (store list semantics).318-3. `writeFrame`/`readFrame` round-trip across sizes (0, 1, 31, 64, 1500, 65537).319-4. Full `noiseNKResponder`↔`noiseNKInitiator` handshake + encrypted320- `PAIR_IDENTITY` exchange over cross-wired `PipedInputStream/PipedOutputStream`321- via `SocketFrameIO`; asserts both sides derive the **same SAS** and the server322- decodes the client identity.323-5. Wrong responder static key → initiator handshake rejects (NK auth tag) →324- `PairingError.HANDSHAKE_FAILED` path.325-326-`PairedDeviceStore`'s on-disk persistence (EncryptedSharedPreferences) needs an327-Android `Context`; cover that in an instrumentation test (`androidTest`) — out of328-scope for the unit suite, consistent with how the project tests other329-EncryptedSharedPreferences stores.app/drafts/MF1MF2/BROWSER-SPEC.md+0 −481
@@ -1,481 +0,0 @@1-# Peach Browser — Recovery + PeachScript Specification2-3-Extracted from `peach-browser` source (read-only; never modified). Every claim cites `file:line`.4-Reference paths are relative to `peach-browser/`. Android paths are relative to5-`peach-android/app/src/main/java/com/peachpasswords/`.6-7-This document is the implementation contract for MF-1 (recovery escrow) and MF-28-(PeachScript format). A second agent should be able to implement from this without9-re-reading the browser source.10-11----12-13-## Recovery Architecture (MF-1)14-15-### A2.1 — Root key origin16-The root key is a **fully random 32-byte value**, generated by17-`crypto.getRandomValues(new Uint8Array(32))` (`vault.ts:282`, also `vault.ts:948`18-in `createVault`). It is **not** the BIP39 entropy and is **not** derived from19-the password. The recovery words encode only the **first 16 bytes** of it (see20-A2.2). The root key is the *sync identity* key — it feeds `computeVaultId`, the21-Noise static key, and the per-entry sync envelope (`SyncIdentity`), and it never22-rotates on password change. It is **not** the vault-encryption key (that is the23-Argon2id-derived `derivedKey`).24-25-> The audit's phrase "the root key *is* the BIP39 entropy" is imprecise: the root26-> key is 32 random bytes; the words capture its first 16 bytes only. The escrow27-> (A2.4) is what lets all 32 bytes be recovered from the 16-byte word material.28-29-### A2.2 — Word generation30-Generate the random 32-byte root key **first**, then derive the 12 words from it:31-`rootKeyToWords(rootKeyBytes)` (`recovery-words.ts:21-55`). Process:32-- `entropy16 = rootKeyBytes[0..16)` (`recovery-words.ts:29`)33-- `checksum = SHA-256(entropy16)[0] >> 4` — top 4 bits (`recovery-words.ts:30-36`)34-- pack `(entropy16 << 4) | checksum` into a 132-bit big-endian integer35- (`recovery-words.ts:40-44`)36-- slice MSB-first into 12 × 11-bit indices; each index → `WORD_LIST[index]`37- (`recovery-words.ts:46-52`)38-39-### A2.3 — Recovery IKM (the HKDF input keying material)40-`wordMaterial = wordsToRootKeyMaterial(words)` (`vault.ts:286` at seal,41-`vault.ts:330` at unseal). `wordsToRootKeyMaterial` (`recovery-words.ts:61-111`):42-- map each word to its index via `WORD_LIST.indexOf(word)` (`recovery-words.ts:72`)43-- repack into 132 bits, extract the top 128 bits as `entropy[16]`44- (`recovery-words.ts:88-92`)45-- verify `SHA-256(entropy)[0] >> 4 == storedChecksum`; **throw on mismatch**46- (`recovery-words.ts:98-105`)47-- return a **32-byte** buffer = `entropy(16) || zero(16)` (`recovery-words.ts:108-110`)48-49-So the IKM is **32 bytes: 16 reconstructed-entropy bytes followed by 16 zero50-bytes**. It is **not** BLAKE3 of the words and **not** the raw 32-byte root key.51-52-> **Duplicate-`abandon` quirk (shared latent bug).** `WORD_LIST` has `"abandon"`53-> at **both index 0 and index 1** (verified: browser `recovery-word-list.ts` has54-> 2049 entries; Android `RecoveryWordList.kt` is byte-identical — diff empty).55-> `indexOf("abandon")` always returns 0, so any word that `rootKeyToWords`56-> emitted from index 1 cannot be inverted, and `wordsToRootKeyMaterial` then57-> throws on the checksum. This affects ~0.6% of random root keys (P(any of 1258-> 11-bit groups == 1) ≈ 12/2048). The browser's `createVault` calls59-> `generateAndWrapRootKey` with **no retry** (`vault.ts:947`), so those ~0.6% of60-> root keys make vault creation **throw**. See Implementation Notes for how61-> Android handles this without breaking parity.62-63-### A2.4 — Wrapped object (what the escrow contains)64-The recovery escrow wraps **only the 32-byte root key**, hex-encoded to a 64-char65-ASCII string then UTF-8 encoded before encryption (`vault.ts:293`):66-`encoded = TextEncoder().encode(hex(rootKeyBytes))` → **64 bytes of ASCII hex**.67-It does **not** wrap the vault entries, the slot-A payload, or the settings.68-69-### A2.5 — HKDF + AES-GCM parameters70-Recovery-key derivation `deriveRecoveryKey(wordMaterial, salt)`71-(`recovery-words.ts:117-142`):72-- KDF: **HKDF-SHA256**73-- IKM: the 32-byte `wordMaterial` from A2.374-- salt: random **16 bytes** (`recoverySalt`, `vault.ts:287`)75-- info: UTF-8 of **`"peach-recovery-v1"`** (`recovery-words.ts:135`)76-- output: a **256-bit AES-GCM** key77-78-Wrapping (`vault.ts:292-307`):79-- AES-**256**-GCM, **12-byte** random nonce (`vault.ts:292`)80-- **AAD = the single byte `0x01`** (`new Uint8Array([1])`, `vault.ts:298`)81-- tag length 128; WebCrypto returns `ciphertext || tag`, split last 16 bytes as82- the tag (`vault.ts:304-307`)83-- stored fields on slot A: `recovery_salt`, `recovery_wrapped_root_key`84- (ciphertext, hex), `recovery_nonce` (hex), `recovery_tag` (hex)85- (`vault.ts:963-966`)86-87-Unwrap `unwrapRootKeyForRecovery` (`vault.ts:323-355`): recompute the recovery88-key from the words + stored salt, AES-GCM-decrypt `(nonce, ct||tag, AAD=0x01)`,89-UTF-8-decode to the hex string, `unhex` → the 32-byte root key.90-91-### A2.6 — `changePassword` behavior92-A password change **does not re-seal the recovery escrow**. The `recovery_*`93-fields are intentionally left untouched (`vault.ts:363-364` comment). Only the94-`pw_root_*` fields (the root key wrapped under the *password-derived* key) are95-re-wrapped (`rewrapRootKeyForPassword`, `vault.ts:366-375`). The same 12 recovery96-words therefore keep working across password changes.97-98-### A2.7 — Word list99-Standard BIP39 **English 2048-word** list — but the shipped list has a **2049th100-entry**: `"abandon"` is duplicated at index 0 and 1 (see A2.3 quirk). Android's101-`RecoveryWordList.kt` is **byte-identical** to the browser list (verified via102-diff). No further modifications.103-104-### A2.8 — Entropy length / word count / checksum105-128 bits of entropy + 4-bit checksum = 132 bits = 12 × 11-bit words106-(`recovery-words.ts:8-15`). Checksum = top 4 bits of `SHA-256(entropy16)`107-(`recovery-words.ts:36`). The root key carries 256 bits but only its first 128108-bits are word-encoded; the remaining 128 bits are recoverable solely via the109-escrow.110-111-### Recovery FLOW semantics (important — not entry recovery)112-`RECOVER_WITH_WORDS` (`messages.ts:312-347`): unwrap the **root key** only, derive113-a new password key, re-wrap root key under it, then `changePasswordWithNewKey`114-re-encrypts the vault using the **in-memory `entries`** (`vault.ts:386`). During a115-forgot-password recovery the vault was never unlocked, so `entries` is empty — the116-browser recovery **resets the password and preserves sync identity but does not117-restore entries locally**; entries return via sync. The words alone never carry118-entries.119-120----121-122-## Divergences from Android (MF-1)123-124-| # | Point | Browser | Android (current) | Status |125-|---|-------|---------|-------------------|--------|126-| 1 | Root key origin | random 32B (`vault.ts:282`) | random 32B (`VaultRepository.kt:117`) | **match** |127-| 2 | Word generation | `rootKeyToWords(rootKey)` first-16B (`recovery-words.ts:21`) | `rootKeyToWords(syncMasterKey())` (`RecoveryWordsScreen.kt:65`) | **match** |128-| 3 | Recovery IKM | `wordsToRootKeyMaterial` = 16 entropy ‖ 16 zero (`vault.ts:286`) | `wordKeyMaterial` = **BLAKE3(joined words)** (`RecoveryWords.kt:76-83`) | **DIVERGENCE** |129-| 4 | Wrapped object | the 32-byte root key as **ASCII hex** (`vault.ts:293`) | the **entire slot-A plaintext payload** (`VaultRepository.kt:639-654`) | **DIVERGENCE** |130-| 5 | HKDF (hash/info/salt/len) | SHA-256 / `peach-recovery-v1` / 16B / 32B (`recovery-words.ts:130-141`) | identical (`RecoveryWords.kt:85-91`) | **match** |131-| 6 | AEAD AAD | single byte `0x01` (`vault.ts:298`) | string `"recovery_escrow_v1"` (`VaultCrypto.kt:32`) | **DIVERGENCE** |132-| 7 | `changePassword` re-seals escrow? | **no** (`vault.ts:363-364`) | **yes** — re-seals whole-payload escrow (`VaultRepository.kt:265-289`) | divergence (Android-local; see fix) |133-| 8 | Word list / entropy / checksum | 2049-word list, 128+4 bits (`recovery-word-list.ts`) | byte-identical list (`RecoveryWordList.kt`) | **match** |134-135-**The three parity-breaking divergences are #3 (IKM), #4 (wrapped object), and136-#6 (AAD).** Fixing all three makes the **same 12 words + the same salt/nonce/ct/tag137-decrypt to the same 32-byte root key on both platforms.**138-139-### Chosen fix (per orchestrator decision: "parity + keep offline restore")140-Android keeps its offline forgot-password restore **and** gains byte-compatible141-cross-platform root-key recovery:142-143-1. Add a **browser-byte-compatible root-key escrow** on slot A:144- `RootKeyEscrow{ salt, wrappedRootKey, nonce, tag }` where the wrapped plaintext145- is the **ASCII hex of the 32-byte root key**, AES-256-GCM under146- `HKDF-SHA256(wordsToRootKeyMaterial(words), salt, info="peach-recovery-v1")`,147- **AAD = byte `0x01`**, 12-byte nonce. Byte-for-byte the browser algorithm.148-2. **Keep** Android's existing whole-payload `recoveryEscrow{salt, blob}` for149- offline entry restore — but derive its key from the **same**150- `wordsToRootKeyMaterial` IKM (not BLAKE3), under a **distinct** string AAD so151- the two blobs can never be confused.152-3. `unlockWithRecoveryWords`: prefer the whole-payload escrow (full local153- restore); fall back to the root-key escrow (root key only) for a vault that154- has only the browser-format escrow.155-4. `changePassword`: leave the root-key escrow **stable** (browser parity); keep156- refreshing the whole-payload escrow so offline restore stays current157- (Android-local behavior).158-5. Generate root keys whose words **round-trip** (retry loop) so the159- duplicate-`abandon` quirk never produces a doomed vault (see Implementation160- Notes). The resulting key space is a strict, fully cross-compatible subset.161-162----163-164-## PeachScript Format (MF-2)165-166-PeachScript = a binary payload (`peachPayload.ts`) re-encoded into Private-Use-Area167-text (`peachScript.ts`). Two layers:168-169-### B2.1 — Outer encoding (PUA text codec) — `peachScript.ts`170-Each payload **byte `b` → one code point `U+E000 + b`** (`peachScript.ts:16-24`);171-decode is the inverse, rejecting any code point outside `U+E000..U+E0FF` with172-`INVALID_PEACHSCRIPT_CHARACTER` (`peachScript.ts:33-44`). No base conversion, no173-padding. `normalisePeachScript` strips all whitespace before decode174-(`peachScript.ts:47-49`). One PUA char ↔ one byte; iterate by code point175-(`Array.from(str)`), not UTF-16 unit.176-177-### B2.2 — Magic bytes178-`MAGIC = 0x50434853` = ASCII **"PCHS"**, written **big-endian** at body offset 0179-(`peachPayload.ts:48,179`). Note: the magic lives in the **inner body** (inside180-the encrypted envelope), not at the head of the file.181-182-### B2.3 — Outer envelope and header structure183-`buildPayload` returns `[ salt(16) || nonce(12) || ciphertext || tag(16) ]`184-(`peachPayload.ts:198-203`). Decrypting the ciphertext yields the **wrapped185-plaintext**:186-187-```188-wrapped = [ FORMAT(1) | inner_len(4, LE) | inner | zero-pad to size bucket ]189-```190-- `FORMAT = 0x03` (FORMAT_V3) (`peachPayload.ts:82-86,193-194`). Old clients see191- 0x03 where they expect PCHS (0x50) and fail with BAD_MAGIC — intentional.192-- `inner_len` = u32 little-endian length of `inner` (`peachPayload.ts:195`).193-- padding: zero-fill up to the next **size bucket** (B2.8) (`peachPayload.ts:196`).194-195-`inner = [ body | checksum(4) ]` (`peachPayload.ts:186`), where:196-```197-body = [ HEADER(8) | SECTION* ]198-HEADER = [ MAGIC(4, BE) | VERSION(1)=0x01 | sectionCount(1) | reserved(2)=0 ]199- (peachPayload.ts:177-184)200-```201-Each `SECTION`:202-```203-[ type(1) | rawLen(4, LE) | compLen(4, LE) | zstdCompressed(compLen) ]204- (peachPayload.ts:316-324)205-```206-Section types: ENTRIES `0x01`, SETTINGS `0x02`, LICENSE `0x03`, RECALL `0x04`,207-DECLINED_CARDS `0x05` (`peachPayload.ts:92-96`). Decoders **skip unknown section208-types** (`peachPayload.ts:300-303`).209-210-### B2.4 — Encryption211-- KDF: **Argon2id** over the **UTF-8 bytes** of the passphrase212- (`peachPayload.ts:920-930`; `hash-wasm` UTF-8-encodes the string), params213- **m=65536 KiB, t=3, p=4, 32-byte** output, **16-byte salt**.214-- Cipher: **AES-256-GCM**, **12-byte** nonce, **128-bit** tag215- (`peachPayload.ts:944-953`). No AAD (`crypto.subtle.encrypt` called with only216- `iv` + `tagLength` — **no `additionalData`**).217-- Envelope layout: `salt(16) ‖ nonce(12) ‖ ct ‖ tag(16)` (`peachPayload.ts:203`).218-- Auth-tag failure on parse → `INVALID_PASSPHRASE` (`peachPayload.ts:232-233`).219-220-### B2.5 — Compression221-**zstd**, **level 19**, applied **per section** to the raw section bytes222-(`buildSection`, `peachPayload.ts:317`). Parse decompresses each section and223-asserts `data.length === rawLen` else `SECTION_LENGTH_MISMATCH`224-(`peachPayload.ts:281-282`). Standard zstd frames — interoperable across225-implementations (decompression is spec-deterministic; compressed bytes are not226-required to match).227-228-### B2.6 — Entry packing / string table — `peachPayload.ts:339-601`229-ENTRIES section body:230-```231-[ entryCount(4, LE) | stringTable | entryBody* ] (peachPayload.ts:412-421)232-stringTable = [ count(2, LE) | (len(2, LE) | utf8bytes)* ] (peachPayload.ts:355-373)233-```234-String table is **1-indexed**; index `0` = absent/undefined235-(`peachPayload.ts:344-352,391-394`). Titles are pre-interned for all entries236-(`peachPayload.ts:400-401`).237-238-Per-entry common prefix (`encodeEntry`, `peachPayload.ts:443-469`):239-```240-[ type(1) | uuid(16 raw) | flags(1) | flags2(1, v3 only)241- | createdSec(4, LE) | updatedDelta(4, LE) | deletedSec(4, LE) | titleIdx(2, LE) ]242-```243-- `uuid`: 16 raw bytes from the 32 hex chars (`peachPayload.ts:792-806`).244-- `createdSec = floor(createdAt/1000)`, `updatedDelta = max(0, updatedSec-createdSec)`,245- `deletedSec = deletedAt? floor(deletedAt/1000):0` (`peachPayload.ts:450-453`).246-- `flags`/`flags2` are back-patched after the body is written247- (`peachPayload.ts:598-599`).248-249-Flags (`peachPayload.ts:104-111`): `F_HAS_TOTP=1<<0`, `F_HAS_TAGS=1<<1`,250-`F_HAS_NOTES=1<<2`, `F_HAS_CANARY=1<<3`, `F_HAS_PWCHANGED=1<<4`, `F_HAS_BREACH=1<<5`,251-`F_HAS_ADDITIONAL_URLS=1<<6`, `F_HAS_DELETED=1<<7`. flags2 (`peachPayload.ts:122`):252-`F2_HAS_EMAIL=1<<0` (login, v3 only).253-254-**LOGIN** (type `0x01`, `peachPayload.ts:475-519`), written in this exact order:255-```256-urlIdx(2) | usernameIdx(2) | lpString password(u8 len)257-[ if F2_HAS_EMAIL ] lpString email(u8 len)258-[ if F_HAS_TOTP ] lpString totp(u8 len)259-[ if F_HAS_TAGS ] u8 count, count× u16 tagIdx260-[ if F_HAS_NOTES ] u16 notesIdx261-[ if F_HAS_CANARY ] u16 webhookUrlIdx, u16 labelIdx262-[ if F_HAS_PWCHANGED ] u32 (floor(pwChangedAt/1000) - createdSec)263-[ if F_HAS_BREACH ] u32 breach264-[ if F_HAS_ADDITIONAL_URLS ] u8 count, count× u16 urlIdx265-```266-`lpString` = `[ len(1 or 2) | utf8bytes ]`; password/email/totp use 1-byte length267-(`peachPayload.ts:856-867`). Tag/url counts capped at 0xff.268-269-**NOTE** (type `0x02`, `peachPayload.ts:520-531`): `[if F_HAS_NOTES] u16 notesIdx`,270-`[if F_HAS_TAGS] u8 count, count× u16 tagIdx` (notes before tags).271-272-**CARD** (type `0x03`, `peachPayload.ts:532-551`):273-```274-u16 cardholderIdx | lpString cardNumber(u8) | lpString expMonth(u8)275-| lpString expYear(u8) | lpString cvc(u8) | u16 cardNicknameIdx276-| u8 networkByte | u16 last4Idx277-[ if F_HAS_TAGS ] u8 count, count× u16 tagIdx278-[ if F_HAS_NOTES ] u16 notesIdx279-```280-`networkByte`: index into `["visa","mastercard","amex","discover","unknown"]`;281-absent → `0xff` (`peachPayload.ts:124,777-786`).282-283-**PASSKEY** (type `0x04`, `peachPayload.ts:552-596`): a JSON blob, `u32 len` then284-`len` UTF-8 bytes. The blob carries the passkey fields (rpId, rpName, credentialId,285-publicKeyCose, privateKeyJwk, userHandle, userName, userDisplayName, algorithm,286-signCount, aaguid, backupEligible, backupState, lastUsedAt) **plus the full login287-field set** (password, url, username, email, totp, notes, tags, canary,288-passwordChangedAt, breach, additionalUrls) when the entry has a nested `passkey`289-object. `entryTypeByte` returns PASSKEY when `entry.passkey` is set, regardless of290-`entry.type` (`peachPayload.ts:760-775`).291-292-### B2.7 — Checksum293-**BLAKE3 truncated to the first 4 bytes** of the hash, over `body` (header +294-sections), appended as the last 4 bytes of `inner` (`peachPayload.ts:185-186,295-988-996`). Verified with a constant-time compare before parsing; mismatch →296-`CHECKSUM_FAILED` (`peachPayload.ts:258-259`). It lives **inside** the AEAD; it297-exists to fail fast on compressed-payload corruption, not for authentication298-(AES-GCM's tag does that).299-300-### B2.8 — Size-bucket padding301-After building `[FORMAT|len|inner]`, zero-pad up to the next bucket in302-`[1024, 4096, 16384, 65536, 262144]` (`peachPayload.ts:60`); beyond the largest,303-round up to the next power of two (`peachPayload.ts:64-78`). Padding is inside the304-AEAD, so it is safe zero-fill. Purpose: coarsen file-size so vault size can't be305-inferred (privacy).306-307-### B2.9 — Version field308-Two version concepts: (a) **body VERSION = 0x01** in the header309-(`peachPayload.ts:49,180`), checked on parse → `UNSUPPORTED_VERSION` otherwise310-(`peachPayload.ts:264`); (b) **FORMAT byte** (0x01 legacy / 0x02 / **0x03 current**)311-as the first wrapped-plaintext byte (`peachPayload.ts:241-252`). v1 = no length312-prefix / no padding; v2/v3 = `[FORMAT|len|inner|pad]`; v3 adds login email + flags2.313-314-### B2.10 — Plaintext (decrypted payload) structure315-Binary, not JSON. After decrypt: `[FORMAT|inner_len|inner|pad]` →316-`inner=[body|checksum]` → `body=[header|sections]`. SETTINGS/LICENSE/RECALL/317-DECLINED_CARDS section *contents* are JSON (`encodeJsonSection`,318-`peachPayload.ts:327-333`); ENTRIES is binary-packed (B2.6).319-320-### B2.11 — Fields included321-ENTRIES carries, per type, every field listed in B2.6 — including tags, notes,322-canary, breach, passwordChangedAt, additionalUrls, email (login); all card fields323-incl. network + last4; full passkey JSON. Timestamps: createdAt, modifiedAt (as324-delta), deletedAt, passwordChangedAt (as delta). The browser export also emits325-SETTINGS, and optionally LICENSE/RECALL/DECLINED_CARDS sections326-(`peachPayload.ts:158-175`). **Not** carried in ENTRIES: `passwordHistory`,327-`isWeak`/`isReused` (computed), favicon.328-329-### B2.12 — Import parsing330-`parsePayload` is the exact reverse of `buildPayload` (`peachPayload.ts:215-310`):331-decrypt → detect FORMAT → strip length prefix/padding → checksum → header → loop332-sections (decompress, dispatch by type, **skip unknown**). Errors:333-`PAYLOAD_TOO_SHORT`, `INVALID_PASSPHRASE`, `BAD_MAGIC`, `UNSUPPORTED_VERSION:n`,334-`CHECKSUM_FAILED`, `SECTION_LENGTH_MISMATCH`, `UNKNOWN_ENTRY_TYPE:n`.335-336----337-338-## Divergences from Android (MF-2)339-340-Android current PeachScript (`ui/vault/PeachScriptExport.kt`,341-`ui/vault/PeachScriptImport.kt`) is an **entirely different format**: a JSON object342-`{"peachscript":1,"encrypted":true,"kdf":"argon2id","salt":…,"blob":…}` where343-`blob = nonce(12) ‖ AES-256-GCM(plaintext-JSON entries)` under AAD344-`"peachscript_export_v1"`. It shares **no** container, magic, compression, checksum,345-entry packing, AAD, or PUA encoding with the browser.346-347-| # | Point | Browser | Android (current) | Status |348-|---|-------|---------|-------------------|--------|349-| 1 | Outer encoding | PUA `U+E000+byte` (`peachScript.ts`) | none (raw JSON text) | **missing** |350-| 2 | Magic | `PCHS` BE in body (`peachPayload.ts:48`) | `"peachscript":1` JSON key | **divergence** |351-| 3 | Header | 8B MAGIC/VER/count (`peachPayload.ts:177`) | JSON keys | **missing** |352-| 4 | Encryption | Argon2id(UTF-8) + AES-GCM, no AAD, `salt‖nonce‖ct‖tag` | Argon2id(UTF-16 `char[]`) + AES-GCM, AAD `peachscript_export_v1`, `nonce‖ct‖tag` | **divergence** |353-| 5 | Compression | zstd L19 per section | none | **missing** |354-| 6 | Entry packing / string table | binary + u16 string table | JSON, 6 fields only | **missing** |355-| 7 | Checksum | BLAKE3[0..4) of body | none | **missing** |356-| 8 | Size-bucket padding | `[1k,4k,16k,64k,256k]` | none | **missing** |357-| 9 | Version | body VER 0x01 + FORMAT 0x03 | `"peachscript":1` | **divergence** |358-| 10 | Plaintext | binary packed | JSON | **divergence** |359-| 11 | Fields included | all (tags/card/passkey/canary/breach/ts) | 6 (title/user/pass/url/notes/totp) | **missing** |360-| 12 | Import parsing | reverse of export | bespoke JSON regex parser | **divergence** |361-362-**Every point diverges or is missing.** MF-2 requires a full port (chosen:363-implement the browser format on Android with zstd-jni — see Implementation Notes).364-365----366-367-## Implementation Notes368-369-### Library choices (Android)370-- **zstd**: `com.github.luben:zstd-jni:1.5.6-3` (reference libzstd; native `.so`371- per ABI). `Zstd.compress(raw, 19)` and `Zstd.decompress(comp, rawLen)`. Chosen372- because the format mandates zstd and decompression is interoperable across373- implementations. **Byte-exact compressed output is not portable across zstd374- builds**, so the cross-platform KAT pins the *decoded structure* (and uses a375- browser-produced fixture for parse), not raw compressed bytes.376-- **BLAKE3**: BouncyCastle `Blake3Digest(256)`, first 4 bytes (already used in377- `RecoveryWords.kt`).378-- **Argon2id**: BouncyCastle `Argon2BytesGenerator` with the **UTF-8 byte**379- overload `generateBytes(password.toByteArray(UTF_8), out)` — matches the380- browser's UTF-8 KDF input for PeachScript (avoids MF-4 *within the PeachScript381- backup path*; MF-4 for the vault slot itself is out of scope here).382-- **AES-256-GCM**: JCE `AES/GCM/NoPadding`, 12-byte nonce, 128-bit tag. The383- PeachScript envelope uses **no AAD** (unlike the vault slots).384-385-### [ANDROID BUG FOUND + FIXED] `rootKeyToWords` checksum sign-extension386-The cross-platform KAT surfaced a pre-existing Android bug: `RecoveryWords.kt`387-computed the BIP39 checksum as `entropyHash[0].toInt() ushr 4`. A `Byte` ≥ 0x80388-sign-extends to a negative `Int`, so the unsigned shift produced a 28-bit value389-instead of the 4-bit checksum — corrupting `rootKeyToWords` (and390-`wordsToRootKeyMaterial`'s check) for ~50% of root keys (those whose391-`SHA-256(entropy16)[0] >= 0x80`). It was latent because the old escrow keyed off392-BLAKE3 and never used `wordsToRootKeyMaterial`. Fixed to393-`(entropyHash[0].toInt() and 0xff) ushr 4` (browser parity, `recovery-words.ts:36`).394-Without this, no Android recovery word would match the browser. Both occurrences395-fixed (`rootKeyToWords`, `wordsToRootKeyMaterial`).396-397-### [SHARED LATENT BUG] duplicate-`abandon` root keys (~0.6%)398-The browser's `createVault` (`vault.ts:947`) and `migrateToRecovery`399-(`vault.ts:511`) call `generateAndWrapRootKey` with no retry, so ~0.6% of random400-root keys (those whose `rootKeyToWords` output includes an index-1 `"abandon"`)401-make recovery setup **throw** (`wordsToRootKeyMaterial` checksum failure). This is402-a genuine reference bug. **Android deviates deliberately and safely**: it403-generates root keys in a bounded retry loop until `rootKeyToWords` →404-`wordsToRootKeyMaterial` round-trips, producing a strict, fully cross-compatible405-**subset** of root keys. No vault Android creates is browser-incompatible, and the406-~0.6% crash is avoided. (Recommend reporting upstream; `peach-browser` was not407-modified.) A checksum-invalid phrase entered at recovery is rejected on **both**408-platforms — that is correct parity, not a divergence.409-410-### Card `last4` (relates to MF-3, out of scope)411-Android `VaultEntry` has no `last4` field (the browser does). For PeachScript412-round-trip the codec derives `last4` from the last 4 digits of `cardNumber` on413-export and drops the browser's `last4` on import (the full `cardNumber` already414-carries it). Android `cardNetwork` (String) maps to/from the browser `network`415-byte by the same value set. No `VaultEntry` change is made here; MF-3 (rename +416-`last4`) remains a separate fix.417-418-### Tests that change behavior (necessary, not regressions)419-- `RecoveryEscrowTest` test #6 (`escrow_round_trips_for_phrase_with_duplicate_abandon`)420- asserts the **old BLAKE3** behavior (round-trips a checksum-invalid all-`abandon`421- phrase). Under browser parity that phrase is **rejected**. The test is rewritten422- to assert rejection of a checksum-invalid phrase (matching the browser) + a423- parity KAT is added. Count preserved.424-- `ExportRoundTripTest` PeachScript cases and `ImportParsersTest` PeachScript cases425- assert the **old JSON** format being replaced; they are updated to the new426- format. New `PeachScriptTest.kt` adds KATs + full-fidelity round-trip.427-428----429-430-## Integration Contract431-432-### New files (drafts → integrate into `app/src/main/java/com/peachpasswords/`)433-- `vault/PeachScript.kt` — PUA text codec (`encodePeachScript`/`decodePeachScript`/434- `normalisePeachScript`/`isPeachScript`).435-- `vault/PeachPayloadCodec.kt` — binary PCHS payload (`buildPayload`/`parsePayload`,436- string table, entry packing, zstd, BLAKE3, Argon2id-UTF8, AES-GCM, uuid/network).437-438-### Files to replace439-- `ui/vault/PeachScriptExport.kt` — `buildEncrypted(entries, backupPassword): String`440- now returns the PUA-encoded PCHS payload. (Drop the JSON `buildPlaintext`.)441-- `ui/vault/PeachScriptImport.kt` — `looksLikePeachScript` → PUA sniff; `isEncrypted`442- → always true; `decryptAndParse` / new `parseFull` return **full** `VaultEntry`.443-- `vault/RecoveryWords.kt` — recovery IKM via `wordsToRootKeyMaterial` (retire444- `wordKeyMaterial` from the escrow path); add round-trip-checked root-key gen helper.445-- `vault/VaultCrypto.kt` — add raw-`ByteArray`-AAD encrypt/decrypt + `AAD_RECOVERY_ROOTKEY = byte 0x01`.446-- `vault/VaultStore.kt` — add `RootKeyEscrow{salt,wrappedRootKey,nonce,tag}` to `StoredVault`.447-- `vault/VaultRepository.kt` — seal/unseal both escrows; round-trip-checked root-key gen;448- leave root-key escrow stable on `changePassword`.449-450-### Files to update (integration)451-- `ui/vault/ImportScreen.kt` — PeachScript path consumes full `VaultEntry` (preserve all fields).452-- `ui/vault/ExportScreen.kt` — saves `.peach` (unchanged call shape).453-- Tests: `RecoveryEscrowTest.kt`, `ExportRoundTripTest.kt`, `ImportParsersTest.kt` updated;454- add `RecoveryEscrowTest`/`PeachScriptTest` KATs.455-456-### New dependency (`app/build.gradle`)457-```gradle458-implementation "com.github.luben:zstd-jni:1.5.6-3@aar" // Android jniLibs (lib/<abi>/*.so)459-testImplementation "com.github.luben:zstd-jni:1.5.6-3" // desktop natives for host unit tests460-```461-The plain jar bundles only desktop natives (would `UnsatisfiedLinkError` on-device);462-the `@aar` ships the Android `.so`. Both are needed: the AAR for the device, the jar463-for JVM unit tests. Verified: APK contains `lib/{arm64-v8a,armeabi-v7a,x86,x86_64}/libzstd-jni-1.5.6-3.so`.464-No `AndroidManifest.xml` changes.465-466-### Integration order467-1. zstd-jni dependency → sync.468-2. MF-1: `VaultCrypto` + `VaultStore` + `RecoveryWords` + `VaultRepository` → build → `RecoveryEscrowTest`.469-3. MF-2: `PeachScript` + `PeachPayloadCodec` → build → `PeachScriptTest`.470-4. Replace `PeachScriptExport`/`Import`, update `ImportScreen` → build → `ExportRoundTripTest`/`ImportParsersTest`.471-5. `assembleDebug` + `lintDebug` + full unit suite.472-473-### Known-answer vectors the orchestrator must verify against the browser474-- **MF-1 KAT**: fixed 32-byte root key → fixed words (`rootKeyToWords`); fixed475- recovery salt → `deriveRecoveryKey(wordsToRootKeyMaterial(words), salt)` → wrap476- `hex(rootKey)` (AAD 0x01) → confirm a browser-computed `recovery_wrapped_root_key`477- unwraps to the same root key. (Generate the browser vector with a tiny Node478- script against `recovery-words.ts`/`vault.ts` if a live cross-check is wanted.)479-- **MF-2 KAT**: a small browser-produced `.peach` blob (PUA text) → Android480- `parseFull` yields the expected entries (pins PUA + envelope + zstd + packing).481- Plus Android self-round-trip and Unicode/empty-vault/wrong-password cases.app/drafts/MF1MF2/ExportRoundTripTest.kt+0 −61
@@ -1,61 +0,0 @@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+0 −66
@@ -1,66 +0,0 @@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+0 −691
@@ -1,691 +0,0 @@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+0 −708
@@ -1,708 +0,0 @@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+0 −53
@@ -1,53 +0,0 @@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+0 −24
@@ -1,24 +0,0 @@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+0 −52
@@ -1,52 +0,0 @@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+0 −185
@@ -1,185 +0,0 @@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/RecoveryEscrowTest.kt+0 −215
@@ -1,215 +0,0 @@1-package com.peachpasswords.vault2-3-import kotlinx.coroutines.runBlocking4-import org.junit.Assert.assertArrayEquals5-import org.junit.Assert.assertEquals6-import org.junit.Assert.assertFalse7-import org.junit.Assert.assertNotNull8-import org.junit.Assert.assertNull9-import org.junit.Assert.assertTrue10-import org.junit.Test11-12-private class RecoveryFakeStorage : VaultStorage {13- var slotA: StoredVault? = null14- var slotB: String? = null15- private var ver: Long = 016- private var settings = VaultSettings()17- override fun loadSlotA() = slotA18- override fun hasVault() = slotA != null19- override fun writeSlotA(slot: StoredVault): Boolean { slotA = slot; return true }20- override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }21- var decoy: StoredVault? = null22- override fun loadDecoySlot() = decoy23- override fun writeDecoySlot(slot: StoredVault): Boolean { decoy = slot; return true }24- override fun hasDecoySlot() = decoy != null25- override fun clearDecoySlot() { decoy = null }26- override fun version() = ver27- override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }28- override fun loadSettings() = settings29- override fun writeSettings(s: VaultSettings): Boolean { settings = s; return true }30- override fun clearVault() { slotA = null; slotB = null; ver = 0; settings = VaultSettings() }31-}32-33-class RecoveryEscrowTest {34-35- /** Recovery words this vault would actually show — derived from its sync root key. */36- private fun recoveryWordsOf(repo: VaultRepository): List<String> {37- val key = repo.syncMasterKey()!!38- return try { rootKeyToWords(key) } finally { VaultCrypto.zero(key) }39- }40-41- private fun login(title: String, password: String = "pw") =42- VaultEntry(id = "", title = title, type = "login", password = password, createdAt = 0, modifiedAt = 0)43-44- // 1 — setRecoveryWords writes BOTH the offline-restore escrow and the45- // browser-compatible root-key escrow (MF-1).46- @Test fun set_recovery_words_writes_both_escrows() = runBlocking {47- val storage = RecoveryFakeStorage()48- val repo = VaultRepository(storage)49- repo.createVault("pw")50- assertNull(storage.slotA?.recoveryEscrow)51- assertNull(storage.slotA?.rootKeyEscrow)52- assertTrue(repo.setRecoveryWords(recoveryWordsOf(repo)))53- assertNotNull(storage.slotA?.recoveryEscrow)54- assertNotNull(storage.slotA?.rootKeyEscrow)55- assertTrue(repo.hasRecoveryEscrow())56- }57-58- // 2 — unlockWithRecoveryWords with correct words restores entries (offline escrow).59- @Test fun unlock_with_correct_words_succeeds() = runBlocking {60- val storage = RecoveryFakeStorage()61- val repo = VaultRepository(storage)62- repo.createVault("pw")63- repo.addEntry(login("GitHub"))64- val words = recoveryWordsOf(repo)65- repo.setRecoveryWords(words)66- repo.lock()67- assertTrue(repo.unlockWithRecoveryWords(words))68- assertTrue(repo.getEntries().any { it.title == "GitHub" })69- }70-71- // 3 — unlockWithRecoveryWords with wrong (still checksum-valid) words fails.72- @Test fun unlock_with_wrong_words_fails() = runBlocking {73- val storage = RecoveryFakeStorage()74- val repo = VaultRepository(storage)75- repo.createVault("pw")76- repo.setRecoveryWords(recoveryWordsOf(repo))77- repo.lock()78- val wrong = rootKeyToWords(ByteArray(32) { (it + 7).toByte() })79- assertFalse(repo.unlockWithRecoveryWords(wrong))80- }81-82- // 4 — unlockWithRecoveryWords with no escrow set returns false.83- @Test fun unlock_with_no_escrow_fails() = runBlocking {84- val storage = RecoveryFakeStorage()85- val repo = VaultRepository(storage)86- repo.createVault("pw")87- val words = recoveryWordsOf(repo) // never call setRecoveryWords88- repo.lock()89- assertFalse(repo.hasRecoveryEscrow())90- assertFalse(repo.unlockWithRecoveryWords(words))91- }92-93- // 5 — Full round-trip: create → set words → reset password via recovery → unlock with new password.94- @Test fun full_recovery_resets_password() = runBlocking {95- val storage = RecoveryFakeStorage()96- val repo = VaultRepository(storage)97- repo.createVault("old-pass")98- repo.addEntry(login("Bank"))99- val words = recoveryWordsOf(repo)100- repo.setRecoveryWords(words)101- repo.lock()102-103- assertTrue(repo.unlockWithRecoveryWords(words))104- assertTrue(repo.resetPasswordWithRecoveryWords(words, "brand-new-pass"))105- assertTrue(repo.isUnlocked.value)106- repo.lock()107-108- assertEquals(UnlockResult.WrongPassword, repo.unlock("old-pass"))109- assertEquals(UnlockResult.Success, repo.unlock("brand-new-pass"))110- assertTrue(repo.getEntries().any { it.title == "Bank" })111- assertTrue(repo.hasRecoveryEscrow())112- }113-114- // 6 — A checksum-INVALID phrase (e.g. all-"abandon") is rejected, matching the115- // browser. Under browser-parity IKM (`wordsToRootKeyMaterial`) such a phrase116- // fails the BIP39 checksum, so no escrow is sealed and recovery cannot proceed.117- // (Previously this asserted the old BLAKE3 behavior, which round-tripped any118- // phrase — that divergence is exactly what MF-1 fixes.)119- @Test fun checksum_invalid_phrase_is_rejected() = runBlocking {120- val storage = RecoveryFakeStorage()121- val repo = VaultRepository(storage)122- repo.createVault("pw")123- repo.addEntry(login("Mail"))124- val allAbandon = List(12) { "abandon" } // valid words, invalid checksum125- // No escrow gets sealed for an invalid phrase.126- repo.setRecoveryWords(allAbandon)127- assertNull(storage.slotA?.recoveryEscrow)128- assertNull(storage.slotA?.rootKeyEscrow)129- repo.lock()130- assertFalse(repo.unlockWithRecoveryWords(allAbandon))131- }132-133- // 7 — CROSS-PLATFORM KAT. Vector generated from the browser's exact algorithm134- // (recovery-words.ts) against the real browser word list (/tmp/mf1_kat_gen.mjs):135- // proves the same 12 words derive the same recovery key and unwrap the same136- // root key on both platforms.137- @Test fun kat_matches_browser_algorithm() {138- val rootKeyHex = "bfb2d5731a470e1b1a0ae9521f501ac5edad8b4ce8e064b76da4cb3cdf00b937"139- val expectedWords = listOf(140- "sauce", "notable", "frequent", "crucial", "ignore", "aspect",141- "gym", "fringe", "faint", "whip", "alley", "merge",142- )143- val wordMaterialHex = "bfb2d5731a470e1b1a0ae9521f501ac500000000000000000000000000000000"144- val recoveryKeyHex = "06880fb677e5b1cd1a65de6340a605681a55c86268885d644117401a9effd990"145- val saltHex = "000102030405060708090a0b0c0d0e0f"146- val nonceHex = "0b0a090807060504030201ff"147- val ciphertextHex = "bba39ac8dfaaff82b916ff434df340ee458c5e6b9b6a18b3a81f4748191cbf03" +148- "ac9f84707cb10c17430b9d63cd83960d2d2cd9da89aa907d2e3bd0cb78bd3628"149- val tagHex = "6f82150ebdbddef6312e5e630975089c"150-151- val rootKey = hexToRootKey(rootKeyHex)152-153- // (a) words derive from the root key exactly as the browser.154- assertEquals(expectedWords, rootKeyToWords(rootKey))155-156- // (b) IKM = 16 entropy bytes followed by 16 zero bytes.157- assertEquals(wordMaterialHex, rootKeyToHex(wordsToRootKeyMaterial(expectedWords)))158-159- // (c) HKDF-derived recovery key matches the browser's.160- val recoveryKey = deriveRecoveryKey(wordsToRootKeyMaterial(expectedWords), hexToRootKey(saltHex)).encoded161- assertEquals(recoveryKeyHex, rootKeyToHex(recoveryKey))162-163- // (d) the browser-wrapped escrow unwraps to the original root key under AAD 0x01.164- val combined = hexToRootKey(nonceHex) + hexToRootKey(ciphertextHex) + hexToRootKey(tagHex)165- val plaintext = VaultCrypto.decrypt(combined, recoveryKey, VaultCrypto.AAD_RECOVERY_ROOTKEY)166- assertEquals(rootKeyHex, String(plaintext, Charsets.US_ASCII))167- assertArrayEquals(rootKey, hexToRootKey(String(plaintext, Charsets.US_ASCII)))168- }169-170- // 8 — A browser-format vault (only the root-key escrow present) recovers the171- // root key and resets the password; entries are empty (they return via sync).172- @Test fun browser_format_vault_recovers_root_key_only() = runBlocking {173- val storage = RecoveryFakeStorage()174- val repo = VaultRepository(storage)175- repo.createVault("pw")176- repo.addEntry(login("Local"))177- val words = recoveryWordsOf(repo)178- val rootKeyBefore = repo.syncMasterKey()!!179- repo.setRecoveryWords(words)180- // Simulate a browser-made vault: drop the Android-only whole-payload escrow.181- storage.slotA = storage.slotA!!.copy(recoveryEscrow = null)182- repo.lock()183-184- assertTrue(repo.unlockWithRecoveryWords(words))185- assertArrayEquals(rootKeyBefore, repo.syncMasterKey()) // same root key recovered186- assertTrue(repo.getEntries().isEmpty()) // entries return via sync187- }188-189- // 9 — changePassword keeps the recovery escrow valid for the SAME words.190- @Test fun change_password_keeps_recovery_valid() = runBlocking {191- val storage = RecoveryFakeStorage()192- val repo = VaultRepository(storage)193- repo.createVault("old")194- repo.addEntry(login("Email"))195- val words = recoveryWordsOf(repo)196- repo.setRecoveryWords(words)197- assertTrue(repo.changePassword("old", "new"))198- // Root-key escrow is carried unchanged (browser parity); offline escrow too.199- assertNotNull(storage.slotA?.rootKeyEscrow)200- repo.lock()201- assertTrue(repo.unlockWithRecoveryWords(words))202- assertTrue(repo.getEntries().any { it.title == "Email" })203- }204-205- // 10 — Backward compat: a vault with neither escrow still opens with its password.206- @Test fun vault_without_escrow_still_opens() = runBlocking {207- val storage = RecoveryFakeStorage()208- val repo = VaultRepository(storage)209- repo.createVault("pw")210- assertNull(storage.slotA?.recoveryEscrow)211- assertNull(storage.slotA?.rootKeyEscrow)212- repo.lock()213- assertEquals(UnlockResult.Success, repo.unlock("pw"))214- }215-}app/drafts/MF1MF2/RecoveryWords.kt+0 −141
@@ -1,141 +0,0 @@1-package com.peachpasswords.vault2-3-import org.bouncycastle.crypto.generators.HKDFBytesGenerator4-import org.bouncycastle.crypto.digests.SHA256Digest5-import org.bouncycastle.crypto.params.HKDFParameters6-import java.math.BigInteger7-import java.security.MessageDigest8-import javax.crypto.spec.SecretKeySpec9-10-private const val WORD_BITS = 1111-private const val TOTAL_WORDS = 1212-13-fun rootKeyToWords(rootKeyBytes: ByteArray): List<String> {14- require(rootKeyBytes.size == 32) { "root key must be 32 bytes" }15- val entropy16 = rootKeyBytes.copyOfRange(0, 16)16- val entropyHash = MessageDigest.getInstance("SHA-256").digest(entropy16)17- // Mask to a byte before the unsigned shift: a Byte >= 0x80 sign-extends to a18- // negative Int, so `toInt() ushr 4` would yield a 28-bit value, not the 4-bit19- // checksum. The browser reads a Uint8 (`recovery-words.ts:36`). Without the20- // mask, ~50% of root keys (SHA[0] >= 0x80) produce non-browser-parity words.21- val checksum = (entropyHash[0].toInt() and 0xff) ushr 422-23- var bitsBig = BigInteger.ZERO24- for (i in 0 until 16) {25- bitsBig = bitsBig.shiftLeft(8).or(BigInteger.valueOf((rootKeyBytes[i].toInt() and 0xff).toLong()))26- }27- bitsBig = bitsBig.shiftLeft(4).or(BigInteger.valueOf(checksum.toLong()))28-29- val words = ArrayList<String>(TOTAL_WORDS)30- for (i in 0 until TOTAL_WORDS) {31- val shift = (TOTAL_WORDS - 1 - i) * WORD_BITS32- val index = bitsBig.shiftRight(shift).and(BigInteger.valueOf(0x7ffL)).toInt()33- words += WORD_LIST[index]34- }35- return words36-}37-38-fun wordsToRootKeyMaterial(words: List<String>): ByteArray {39- require(words.size == TOTAL_WORDS) { "exactly $TOTAL_WORDS words required" }40-41- val indices = IntArray(words.size)42- for (i in words.indices) {43- val word = words[i].trim().lowercase()44- val index = WORD_LIST.indexOf(word)45- require(index >= 0) { "unknown word at position ${i + 1}: \"${words[i]}\"" }46- indices[i] = index47- }48-49- var bitsBig = BigInteger.ZERO50- for (index in indices) {51- bitsBig = bitsBig.shiftLeft(WORD_BITS).or(BigInteger.valueOf(index.toLong()))52- }53-54- val entropy = ByteArray(16)55- for (i in 0 until 16) {56- val byteShift = 124 - i * 857- entropy[i] = bitsBig.shiftRight(byteShift).and(BigInteger.valueOf(0xffL)).toByte()58- }59-60- val storedChecksum = bitsBig.and(BigInteger.valueOf(0xFL)).toInt()61- val entropyHash = MessageDigest.getInstance("SHA-256").digest(entropy)62- // See rootKeyToWords: mask to a byte before the unsigned shift (browser parity).63- val computedChecksum = (entropyHash[0].toInt() and 0xff) ushr 464- require(storedChecksum == computedChecksum) { "invalid recovery words — checksum mismatch" }65-66- return ByteArray(32).also { it.fill(0); System.arraycopy(entropy, 0, it, 0, entropy.size) }67-}68-69-/**70- * Generate a random 32-byte root key whose recovery words round-trip cleanly.71- *72- * WORD_LIST carries "abandon" at both index 0 and 1 (a byte-identical parity copy73- * of the browser list), so `wordsToRootKeyMaterial` — which reconstructs entropy74- * via `indexOf` — cannot invert any phrase that `rootKeyToWords` emitted from75- * index 1; it throws on the checksum. The browser's `createVault` (`vault.ts:947`)76- * does NOT retry and therefore throws for those ~0.6% of root keys (a latent77- * reference bug). We deviate deliberately and safely: regenerate until the words78- * round-trip, yielding a strict, fully cross-compatible SUBSET of root keys. Any79- * vault created this way is recoverable by the browser too.80- */81-fun generateRecoverableRootKey(maxAttempts: Int = 64): ByteArray {82- val rng = java.security.SecureRandom()83- repeat(maxAttempts) {84- val candidate = ByteArray(32).also(rng::nextBytes)85- val words = rootKeyToWords(candidate)86- val roundTrips = runCatching { wordsToRootKeyMaterial(words) }.isSuccess87- if (roundTrips) return candidate88- candidate.fill(0)89- }90- // Astronomically unlikely (P(fail)^64 with P(fail)≈0.006). Surface rather than91- // ship a root key whose displayed words cannot be entered back.92- throw IllegalStateException("could not generate a round-tripping root key")93-}94-95-/** Lowercase, unseparated hex of [bytes] — the exact ASCII the browser wraps in the escrow. */96-fun rootKeyToHex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) }97-98-/** Inverse of [rootKeyToHex]; tolerant of upper/lower case. */99-fun hexToRootKey(hex: String): ByteArray {100- require(hex.length % 2 == 0) { "odd-length hex" }101- return ByteArray(hex.length / 2) { i -> hex.substring(i * 2, i * 2 + 2).toInt(16).toByte() }102-}103-104-fun deriveRecoveryKey(wordMaterial: ByteArray, salt: ByteArray): SecretKeySpec {105- val generator = HKDFBytesGenerator(SHA256Digest())106- generator.init(HKDFParameters(wordMaterial, salt, "peach-recovery-v1".encodeToByteArray()))107- val out = ByteArray(32)108- generator.generateBytes(out, 0, out.size)109- return SecretKeySpec(out, "AES")110-}111-112-fun findInvalidWords(words: List<String>): List<Pair<Int, String>> {113- val invalid = ArrayList<Pair<Int, String>>()114- for (i in words.indices) {115- val w = words[i].trim().lowercase()116- if (w.isBlank() || WORD_LIST.indexOf(w) == -1) {117- invalid += i to words[i]118- }119- }120- return invalid121-}122-123-fun getWordSuggestions(prefix: String, maxResults: Int = 5): List<String> {124- val p = prefix.trim().lowercase()125- if (p.length < 2) return emptyList()126- return WORD_LIST.filter { it.startsWith(p) }.take(maxResults)127-}128-129-/**130- * BLAKE3 hash (hex) of the space-joined, trimmed, lowercased recovery words.131- * Stored in vault metadata so recovery-word entry can be verified without132- * persisting the words. Mirrors the browser's recovery-hash derivation.133- */134-fun recoveryWordsHash(words: List<String>): String {135- val canonical = words.joinToString(" ") { it.trim().lowercase() }.encodeToByteArray()136- val digest = org.bouncycastle.crypto.digests.Blake3Digest(256)137- digest.update(canonical, 0, canonical.size)138- val out = ByteArray(32)139- digest.doFinal(out, 0)140- return out.joinToString("") { "%02x".format(it) }141-}app/drafts/MF1MF2/VaultCrypto.kt+0 −121
@@ -1,121 +0,0 @@1-package com.peachpasswords.vault2-3-import org.bouncycastle.crypto.generators.Argon2BytesGenerator4-import org.bouncycastle.crypto.params.Argon2Parameters5-import java.security.SecureRandom6-import javax.crypto.Cipher7-import javax.crypto.spec.GCMParameterSpec8-import javax.crypto.spec.SecretKeySpec9-10-object VaultCrypto {11- const val ARGON2_MEMORY_KB = 6553612- const val ARGON2_ITERATIONS = 313- const val ARGON2_PARALLELISM = 414- const val ARGON2_HASH_LENGTH = 3215- const val SALT_SIZE = 1616- const val NONCE_SIZE = 1217- const val TAG_LENGTH_BITS = 12818- const val KEY_SIZE = 3219- const val PAD_BLOCK = 102420- const val DURESS_SLOT_SIZE = 262_14421-22- val PADDING_BUCKETS = intArrayOf(1024, 4096, 16384, 65536, 262144)23-24- const val AAD_SLOT_A = "slot_a_v1"25- const val AAD_SLOT_B = "slot_b_v1"26- const val AAD_ROOT_KEY = "pw_root_v1"27-28- /**29- * Distinct from [AAD_SLOT_A] so a recovery-escrow blob can never be swapped in30- * as a slot-A blob (GCM auth covers the AAD). Used by Android's whole-payload31- * offline-restore escrow.32- */33- const val AAD_RECOVERY = "recovery_escrow_v1"34-35- /**36- * AAD for the browser-byte-compatible root-key escrow. The browser wraps the37- * 32-byte root key under AAD = the single byte 0x01 (`vault.ts:298`); matching38- * it byte-for-byte is what lets the same 12 words unwrap the same root key on39- * either platform. Do NOT change — it is a cross-platform wire constant.40- */41- val AAD_RECOVERY_ROOTKEY = byteArrayOf(1)42-43- private val secureRandom = SecureRandom()44- private var _lastTimestamp = 0L45-46- fun deriveKey(password: String, salt: ByteArray): ByteArray {47- val params = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)48- .withSalt(salt)49- .withParallelism(ARGON2_PARALLELISM)50- .withMemoryAsKB(ARGON2_MEMORY_KB)51- .withIterations(ARGON2_ITERATIONS)52- .build()53- val generator = Argon2BytesGenerator().apply { init(params) }54- val hash = ByteArray(ARGON2_HASH_LENGTH)55- generator.generateBytes(password.toCharArray(), hash)56- return hash57- }58-59- fun encrypt(plaintext: ByteArray, key: ByteArray, aad: String): ByteArray =60- encrypt(plaintext, key, aad.toByteArray(Charsets.UTF_8))61-62- fun decrypt(data: ByteArray, key: ByteArray, aad: String): ByteArray =63- decrypt(data, key, aad.toByteArray(Charsets.UTF_8))64-65- /**66- * Raw-AAD encrypt. Output is `nonce(12) || ciphertext || tag(16)`. The67- * [aad] bytes are authenticated, not encrypted. Used for the root-key68- * escrow whose AAD is the browser's single 0x01 byte ([AAD_RECOVERY_ROOTKEY]).69- */70- fun encrypt(plaintext: ByteArray, key: ByteArray, aad: ByteArray): ByteArray {71- val nonce = ByteArray(NONCE_SIZE).also(secureRandom::nextBytes)72- val cipher = Cipher.getInstance("AES/GCM/NoPadding")73- cipher.init(74- Cipher.ENCRYPT_MODE,75- SecretKeySpec(key, "AES"),76- GCMParameterSpec(TAG_LENGTH_BITS, nonce),77- )78- cipher.updateAAD(aad)79- return nonce + cipher.doFinal(plaintext)80- }81-82- fun decrypt(data: ByteArray, key: ByteArray, aad: ByteArray): ByteArray {83- require(data.size >= NONCE_SIZE) { "Data too short" }84- val nonce = data.copyOfRange(0, NONCE_SIZE)85- val ciphertext = data.copyOfRange(NONCE_SIZE, data.size)86- val cipher = Cipher.getInstance("AES/GCM/NoPadding")87- cipher.init(88- Cipher.DECRYPT_MODE,89- SecretKeySpec(key, "AES"),90- GCMParameterSpec(TAG_LENGTH_BITS, nonce),91- )92- cipher.updateAAD(aad)93- return cipher.doFinal(ciphertext)94- }95-96- fun generateSalt(): ByteArray = ByteArray(SALT_SIZE).also(secureRandom::nextBytes)97- fun generateRootKey(): ByteArray = ByteArray(KEY_SIZE).also(secureRandom::nextBytes)98- fun generateNoise(): ByteArray = ByteArray(DURESS_SLOT_SIZE).also(secureRandom::nextBytes)99-100- fun padToBucket(data: ByteArray): ByteArray {101- val target = PADDING_BUCKETS.firstOrNull { it >= data.size } ?: data.size102- return data.copyOf(target)103- }104-105- fun padToBlock(data: ByteArray): ByteArray {106- val remainder = data.size % PAD_BLOCK107- if (remainder == 0) return data108- return data.copyOf(data.size + (PAD_BLOCK - remainder))109- }110-111- @Synchronized112- fun monotonicEntryTimestamp(currentModifiedAt: Long? = null): Long {113- val base = maxOf(System.currentTimeMillis(), (currentModifiedAt ?: 0L) + 1L, _lastTimestamp + 1L)114- _lastTimestamp = base115- return base116- }117-118- fun zero(bytes: ByteArray) {119- bytes.fill(0)120- }121-}app/drafts/MF1MF2/VaultRepository.kt+0 −855
@@ -1,855 +0,0 @@1-package com.peachpasswords.vault2-3-import kotlinx.coroutines.flow.MutableStateFlow4-import kotlinx.coroutines.flow.StateFlow5-import kotlinx.coroutines.flow.asStateFlow6-import kotlinx.coroutines.sync.Mutex7-import kotlinx.coroutines.sync.withLock8-import java.security.SecureRandom9-import java.util.Base6410-import java.util.UUID11-import javax.inject.Inject12-import javax.inject.Singleton13-14-private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)15-private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)16-17-/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */18-private const val PASSWORD_HISTORY_MAX = 5019-20-/** Fixed in-app key material for the decoy vault — holds nothing secret by design. */21-private const val DECOY_SENTINEL = "peach_decoy_v1"22-23-sealed interface UnlockResult {24- data object Success : UnlockResult25- data object WrongPassword : UnlockResult26- data class Error(val reason: String) : UnlockResult27-}28-29-sealed interface CreateVaultResult {30- data object Success : CreateVaultResult31- data class Error(val reason: String) : CreateVaultResult32-}33-34-/**35- * In-memory vault session backed by [VaultStore]. Faithful port of the browser36- * `vault.ts` semantics that matter for correctness:37- *38- * - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched39- * noise blob so a fresh install shows two similarly-shaped records.40- * - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a41- * deletion always wins last-write-wins against an in-flight edit.42- * - Local writes bump the version counter; sync-applied writes do NOT (so a43- * sync round never cascades into another outbound sync).44- * - add/update/delete roll back in-memory state if the disk write fails.45- * - destroyVault never touches the Pro license (separate store).46- */47-@Singleton48-class VaultRepository @Inject constructor(49- private val store: VaultStorage,50-) {51- private val mutex = Mutex()52- private val rng = SecureRandom()53-54- private var derivedKey: ByteArray? = null55- private var rootKey: ByteArray? = null56- private var entryList: MutableList<VaultEntry> = mutableListOf()57- private var duressConfigured: Boolean = false58- private var recoveryWordHash: String? = null59- private var recoveryWordsSet: Boolean = false60- /** True while a decoy (duress) session is active — persistence targets the decoy slot. */61- private var decoyMode: Boolean = false62-63- private val _isUnlocked = MutableStateFlow(false)64- val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()65-66- private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())67- /** Active (non-deleted) entryList. */68- val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()69-70- private val _settings = MutableStateFlow(VaultSettings())71- val settings: StateFlow<VaultSettings> = _settings.asStateFlow()72-73- fun hasVault(): Boolean = store.hasVault()74-75- // ---- Codex (printed paper backup) -------------------------------------76-77- /**78- * The at-rest slot-A envelope as base64 JSON `{"a": <StoredVault>}` — the79- * Codex payload's vaultBlob. Slot B is noise, so it is omitted. Restorable80- * on any device that has the master password. Null when no vault exists.81- */82- fun codexVaultBlobBase64(): String? {83- val slotA = store.loadSlotA() ?: return null84- val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""85- return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))86- }87-88- /**89- * Replace the local vault from a Codex blob, then unlock with [password].90- * Writes slot A (and a size-matched noise slot B) before unlocking so the91- * restored vault is at rest exactly as a freshly-created one would be.92- */93- suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {94- return try {95- val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)96- val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)97- ?: return UnlockResult.Error("invalid_codex_blob")98- val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")99- if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")100- writeMatchingNoiseSlotB(slotA)101- store.stampLocalMutation()102- unlockLocked(password)103- } catch (e: Exception) {104- UnlockResult.Error(e.message ?: "restore_failed")105- }106- }107-108- suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {109- return try {110- val salt = VaultCrypto.generateSalt()111- val key = VaultCrypto.deriveKey(password, salt)112- entryList = mutableListOf()113- duressConfigured = false114- recoveryWordHash = null115- recoveryWordsSet = false116- decoyMode = false117- rootKey = generateRecoverableRootKey()118- val slotA = sealSlotA(key, salt)119- if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")120- writeMatchingNoiseSlotB(slotA)121- store.stampLocalMutation()122- store.writeSettings(_settings.value)123- derivedKey = key124- publish()125- _isUnlocked.value = true126- CreateVaultResult.Success127- } catch (e: Exception) {128- CreateVaultResult.Error(e.message ?: "create_failed")129- }130- }131-132- suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }133-134- /** Unlock body without acquiring the mutex — callers must already hold it. */135- private fun unlockLocked(password: String): UnlockResult {136- val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")137- return try {138- val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))139- val payload = try {140- VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))141- } catch (_: Exception) {142- VaultCrypto.zero(key)143- return UnlockResult.WrongPassword144- }145- derivedKey = key146- decoyMode = false147- entryList = payload.entries.toMutableList()148- duressConfigured = payload.duressConfigured149- recoveryWordHash = payload.recoveryWordHash150- recoveryWordsSet = payload.recoveryWordsSet151- _settings.value = store.loadSettings()152- ensureRootKey(payload)153- autoPurgeExpiredTrash()154- publish()155- _isUnlocked.value = true156- UnlockResult.Success157- } catch (e: Exception) {158- UnlockResult.Error(e.message ?: "unlock_failed")159- }160- }161-162- /**163- * Unlock into the decoy (duress) vault. Creates an empty decoy on first use,164- * sealed under a fixed in-app sentinel key with its own salt. The real slot A165- * is never read, so the real vault stays hidden. Edits during a decoy session166- * persist to the decoy slot only (see [persistSlotA]).167- */168- suspend fun unlockDecoy(): UnlockResult = mutex.withLock {169- return try {170- val existing = store.loadDecoySlot()171- if (existing == null) {172- val salt = VaultCrypto.generateSalt()173- val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)174- entryList = mutableListOf()175- duressConfigured = false176- recoveryWordHash = null177- recoveryWordsSet = false178- rootKey = VaultCrypto.generateRootKey()179- derivedKey = key180- decoyMode = true181- val plaintext = VaultCodec.encode(currentPayload())182- val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))183- if (!store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob)))184- return UnlockResult.Error("storage_write_failed")185- } else {186- val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))187- val payload = VaultCodec.decode(188- VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),189- )190- derivedKey = key191- decoyMode = true192- entryList = payload.entries.toMutableList()193- duressConfigured = false194- recoveryWordHash = payload.recoveryWordHash195- recoveryWordsSet = payload.recoveryWordsSet196- rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)197- else VaultCrypto.generateRootKey()198- }199- _settings.value = store.loadSettings()200- publish()201- _isUnlocked.value = true202- UnlockResult.Success203- } catch (e: Exception) {204- UnlockResult.Error(e.message ?: "decoy_unlock_failed")205- }206- }207-208- /** Unlock with an already-derived AES-256 key (biometric path). */209- suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {210- val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")211- return try {212- val payload = VaultCodec.decode(213- VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),214- )215- derivedKey = key.copyOf()216- decoyMode = false217- entryList = payload.entries.toMutableList()218- duressConfigured = payload.duressConfigured219- recoveryWordHash = payload.recoveryWordHash220- recoveryWordsSet = payload.recoveryWordsSet221- _settings.value = store.loadSettings()222- ensureRootKey(payload)223- autoPurgeExpiredTrash()224- publish()225- _isUnlocked.value = true226- UnlockResult.Success227- } catch (_: Exception) {228- UnlockResult.WrongPassword229- }230- }231-232- fun lock() {233- derivedKey?.let(VaultCrypto::zero)234- rootKey?.let(VaultCrypto::zero)235- derivedKey = null236- rootKey = null237- entryList = mutableListOf()238- duressConfigured = false239- recoveryWordHash = null240- recoveryWordsSet = false241- decoyMode = false242- _entries.value = emptyList()243- _isUnlocked.value = false244- }245-246- // ---- Sync identity ----------------------------------------------------247-248- /**249- * The vault's stable sync master key (a copy). Caller must zero it. Backs250- * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry251- * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].252- */253- fun syncMasterKey(): ByteArray? = rootKey?.copyOf()254-255- /** Stable per-vault id two paired devices must share to sync. Null when locked. */256- fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }257-258- /**259- * A copy of the live Argon2id-derived vault key, for biometric escrow only260- * (wrapped under a hardware KeyStore key on biometric enable). Null when261- * locked. Caller must [VaultCrypto.zero] it after use.262- */263- fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()264-265- suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {266- val slotA = store.loadSlotA() ?: return false267- return try {268- val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))269- val payload = VaultCodec.decode(270- VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),271- )272- val newSalt = VaultCrypto.generateSalt()273- val newKey = VaultCrypto.deriveKey(newPassword, newSalt)274- // Re-seal the existing payload under the new key/salt.275- val plaintext = VaultCodec.encode(payload)276- val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))277- // The escrow seals the slot-A PLAINTEXT, which a password change does not278- // alter — only the wrapping changes — so carry it forward; rebuilding the279- // StoredVault from scratch would silently drop it.280- // Carry BOTH escrows forward unchanged: each seals plaintext/root-key281- // content that a password change does not alter — only the slot-A282- // wrapping rotates. The root-key escrow staying stable across password283- // changes matches the browser (`vault.ts:363-364`).284- val next = StoredVault(285- version = slotA.version,286- salt = b64(newSalt),287- blob = blob,288- recoveryEscrow = slotA.recoveryEscrow,289- rootKeyEscrow = slotA.rootKeyEscrow,290- )291- if (!store.writeSlotA(next)) return false292- writeMatchingNoiseSlotB(next)293- store.stampLocalMutation()294- VaultCrypto.zero(oldKey)295- derivedKey?.let(VaultCrypto::zero)296- derivedKey = newKey297- true298- } catch (_: Exception) {299- false300- }301- }302-303- /**304- * Irreversible wipe. Locks the session and clears every vault key. The Pro305- * license is in a separate store and is preserved by construction.306- */307- suspend fun destroyVault() = mutex.withLock {308- lock()309- store.clearVault()310- store.clearDecoySlot()311- }312-313- // ---- Entry CRUD -------------------------------------------------------314-315- suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {316- requireUnlocked()317- val stamp = VaultCrypto.monotonicEntryTimestamp()318- val now = System.currentTimeMillis()319- val entry = draft.copy(320- id = draft.id.ifBlank { UUID.randomUUID().toString() },321- createdAt = if (draft.createdAt > 0) draft.createdAt else now,322- modifiedAt = stamp,323- passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,324- )325- val rollback = entryList.toMutableList()326- entryList.add(entry)327- persistOrRollback(rollback)328- entry329- }330-331- suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {332- requireUnlocked()333- val idx = entryList.indexOfFirst { it.id == patch.id }334- if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")335- val current = entryList[idx]336- val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)337- // Only refresh passwordChangedAt when the password value actually changes.338- val passwordChanged = patch.password != null && patch.password != current.password339- // Capture the outgoing password (newest first) so the user can reveal/copy/340- // restore it later. History is computed authoritatively from `current`, not341- // the patch — updateEntry is a full-entry replace, so trusting patch's value342- // would let a stale form clobber the real history. Record the age the old343- // password carried, skip an empty prior, and skip an immediate exact dupe344- // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.345- val priorPassword = current.password346- val shouldCapture = passwordChanged &&347- !priorPassword.isNullOrEmpty() &&348- current.passwordHistory?.firstOrNull()?.password != priorPassword349- val nextHistory = if (shouldCapture) {350- (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +351- (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)352- } else {353- current.passwordHistory354- }355- val updated = patch.copy(356- createdAt = current.createdAt,357- modifiedAt = stamp,358- passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,359- passwordHistory = nextHistory,360- )361- val rollback = entryList.toMutableList()362- entryList[idx] = updated363- persistOrRollback(rollback)364- updated365- }366-367- /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */368- suspend fun deleteEntry(id: String) = mutex.withLock {369- requireUnlocked()370- val idx = entryList.indexOfFirst { it.id == id }371- if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")372- val current = entryList[idx]373- val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)374- val rollback = entryList.toMutableList()375- entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)376- persistOrRollback(rollback)377- }378-379- suspend fun restoreEntry(id: String) = mutex.withLock {380- requireUnlocked()381- val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }382- if (idx == -1) throw IllegalStateException("deleted entry not found")383- val current = entryList[idx]384- val rollback = entryList.toMutableList()385- entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))386- persistOrRollback(rollback)387- }388-389- /** Permanent delete — no tombstone, no recovery. */390- suspend fun purgeEntry(id: String) = mutex.withLock {391- requireUnlocked()392- val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }393- if (idx == -1) throw IllegalStateException("deleted entry not found")394- val rollback = entryList.toMutableList()395- entryList.removeAt(idx)396- persistOrRollback(rollback)397- }398-399- /** Permanently empty the trash — hard-deletes every soft-deleted entry. */400- suspend fun purgeDeletedEntries(): Int = mutex.withLock {401- requireUnlocked()402- val rollback = entryList.toMutableList()403- val before = entryList.size404- entryList.removeAll { it.deletedAt != null }405- val removed = before - entryList.size406- if (removed > 0) persistOrRollback(rollback)407- removed408- }409-410- fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }411- fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }412- fun getDeletedEntries(): List<VaultEntry> =413- entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }414-415- /** Active entries, optionally narrowed to those carrying [tagFilter]. */416- fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {417- val active = entryList.filter { it.deletedAt == null }418- if (tagFilter == null) return active419- val needle = tagFilter.trim().lowercase()420- return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }421- }422-423- /** Sorted, de-duplicated tags across all active entries. */424- fun getDistinctTags(): List<String> =425- entryList.asSequence()426- .filter { it.deletedAt == null }427- .flatMap { it.tags?.asSequence() ?: emptySequence() }428- .map { it.trim().lowercase() }429- .filter { it.isNotEmpty() }430- .distinct()431- .sorted()432- .toList()433-434- /**435- * Distinct non-blank values for an identity field across active entries,436- * most-frequently-used first. Supports "username" and "email"; unknown field437- * names return an empty list. Values keep original casing (deduped438- * case-insensitively) so a suggestion matches what the user typed.439- */440- fun getDistinctFieldValues(field: String): List<String> {441- val select: (VaultEntry) -> String? = when (field) {442- "username" -> { e -> e.username }443- "email" -> { e -> e.email }444- else -> return emptyList()445- }446- return entryList.asSequence()447- .filter { it.deletedAt == null }448- .mapNotNull { select(it)?.trim() }449- .filter { it.isNotEmpty() }450- .groupingBy { it.lowercase() }451- .aggregate { _, acc: Pair<String, Int>?, value, _ ->452- Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)453- }454- .values455- .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })456- .map { it.first }457- }458-459- fun getTombstones(): List<Tombstone> =460- entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }461- fun getVaultVersion(): Long = store.version()462-463- // ---- Sync apply (does NOT advance the version) ------------------------464-465- /**466- * Apply remote entryList + tombstones with per-entry last-write-wins. Persists467- * WITHOUT bumping the version counter, so a sync round cannot cascade into468- * another outbound sync. Returns the number of locally-applied changes.469- */470- suspend fun applyMergedRemoteEntries(471- remoteEntries: List<VaultEntry>,472- remoteTombstones: List<Tombstone>,473- ): Int = mutex.withLock {474- requireUnlocked()475- val tombMap = remoteTombstones.associate { it.id to it.deletedAt }476- var applied = 0477- val byId = entryList.associateBy { it.id }.toMutableMap()478-479- for (remote in remoteEntries) {480- val tomb = tombMap[remote.id]481- if (tomb != null && tomb >= remote.modifiedAt) continue482- val local = byId[remote.id]483- if (local == null) {484- entryList.add(remote); byId[remote.id] = remote; applied++485- } else if (remote.modifiedAt > local.modifiedAt) {486- val i = entryList.indexOfFirst { it.id == local.id }487- if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }488- }489- }490-491- for ((id, deletedAt) in tombMap) {492- val local = byId[id] ?: continue493- if (local.deletedAt != null && local.deletedAt >= deletedAt) continue494- if (deletedAt < local.modifiedAt) continue495- val i = entryList.indexOfFirst { it.id == id }496- if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }497- }498-499- if (applied > 0) {500- persistSlotA(bumpVersion = false)501- publish()502- }503- applied504- }505-506- suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {507- _settings.value = settings508- store.writeSettings(settings)509- }510-511- // ---- Recovery words (vault metadata) ----------------------------------512-513- /** True once the user has confirmed their recovery words for this vault. */514- fun isRecoveryWordsSet(): Boolean = recoveryWordsSet515-516- /**517- * Record the BLAKE3 hash of the confirmed recovery words and mark them set.518- * Persisted without bumping the version — recovery metadata is local-only and519- * is not an entry mutation paired devices should sync against.520- */521- suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {522- requireUnlocked()523- recoveryWordHash = recoveryWordsHash(words)524- recoveryWordsSet = true525- // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow526- // (cross-platform recovery of the sync root key) and Android's whole-payload527- // escrow (offline forgot-password restore of entries). Both derive their key528- // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.529- runCatching {530- persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))531- }.getOrDefault(false)532- }533-534- /** Verify entered words against the stored recovery hash. */535- fun verifyRecoveryWords(words: List<String>): Boolean {536- val stored = recoveryWordHash ?: return false537- return stored == recoveryWordsHash(words)538- }539-540- // ---- Recovery escrow (forgot-password) --------------------------------541-542- /** True at rest if this vault has any recovery escrow the recovery flow can use. */543- fun hasRecoveryEscrow(): Boolean =544- store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false545-546- /**547- * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of548- * the master password. On success the slot-A plaintext sealed in the escrow is549- * adopted as the live session (entries, rootKey, settings), but no Argon2id550- * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a551- * new password and finish unlocking. Returns false when there is no escrow, the552- * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).553- *554- * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no555- * detached vault key to return here — slot A is wrapped under the rotating556- * Argon2id key — so this opens the escrowed payload directly.557- */558- suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {559- val slotA = store.loadSlotA() ?: return false560- if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false561-562- // Prefer Android's whole-payload escrow: a full offline restore of entries,563- // root key, and settings. Present for Android-created vaults.564- slotA.recoveryEscrow?.let { escrow ->565- val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let566- val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))567- val keyBytes = recoveryKey.encoded568- try {569- val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)570- val payload = VaultCodec.decode(plaintext)571- decoyMode = false572- entryList = payload.entries.toMutableList()573- duressConfigured = payload.duressConfigured574- recoveryWordHash = payload.recoveryWordHash575- recoveryWordsSet = payload.recoveryWordsSet576- rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)577- else generateRecoverableRootKey()578- _settings.value = store.loadSettings()579- VaultCrypto.zero(plaintext)580- return true581- } catch (_: Exception) {582- // Wrong words against this escrow — fall through to the root-key escrow.583- } finally {584- VaultCrypto.zero(material)585- VaultCrypto.zero(keyBytes)586- }587- }588-589- // Browser-format vault (only the root-key escrow): recover the 32-byte root590- // key (sync identity) and reset the password; entries return via sync. This591- // is exactly the browser's recovery semantics (`messages.ts:312-347`).592- slotA.rootKeyEscrow?.let { escrow ->593- val rk = unsealRootKeyEscrow(words, escrow) ?: return false594- decoyMode = false595- entryList = mutableListOf()596- duressConfigured = false597- recoveryWordHash = recoveryWordsHash(words)598- recoveryWordsSet = true599- rootKey = rk600- _settings.value = store.loadSettings()601- return true602- }603- return false604- }605-606- /**607- * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:608- * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same609- * words, mark the session fully unlocked, and publish. Returns false if called610- * without a prior successful recovery unlock (no in-memory root key).611- *612- * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`613- * into one step, since there is no detached vault key here.614- */615- suspend fun resetPasswordWithRecoveryWords(616- words: List<String>,617- newPassword: String,618- ): Boolean = mutex.withLock {619- if (rootKey == null) return false // must have recovered first620- return try {621- val newSalt = VaultCrypto.generateSalt()622- val newKey = VaultCrypto.deriveKey(newPassword, newSalt)623- val plaintext = VaultCodec.encode(currentPayload())624- val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))625- val prior = store.loadSlotA()626- // Rebuild both escrows against the recovered session so their salts rotate627- // with the password reset; fall back to the prior escrows if rebuild fails628- // (e.g. a checksum-invalid phrase). The same 12 words keep working.629- val valid = words.size == 12 && findInvalidWords(words).isEmpty()630- val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow631- val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow632- val next = StoredVault(633- version = prior?.version ?: 1,634- salt = b64(newSalt),635- blob = blob,636- recoveryEscrow = freshRecovery,637- rootKeyEscrow = freshRootKey,638- )639- if (!store.writeSlotA(next)) return false640- writeMatchingNoiseSlotB(next)641- store.stampLocalMutation()642- derivedKey?.let(VaultCrypto::zero)643- derivedKey = newKey644- VaultCrypto.zero(plaintext)645- publish()646- _isUnlocked.value = true647- true648- } catch (_: Exception) {649- false650- }651- }652-653- /**654- * Seal the current slot-A plaintext under a key derived from the 12 BIP39655- * recovery [words] (Android offline-restore escrow). IKM is the browser's656- * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].657- * Returns null for a checksum-invalid phrase.658- */659- private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {660- if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null661- val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null662- val salt = VaultCrypto.generateSalt()663- val recoveryKey = deriveRecoveryKey(material, salt)664- val keyBytes = recoveryKey.encoded665- val plaintext = VaultCodec.encode(currentPayload())666- return try {667- val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)668- RecoveryEscrow(salt = b64(salt), blob = b64(sealed))669- } finally {670- VaultCrypto.zero(material)671- VaultCrypto.zero(keyBytes)672- VaultCrypto.zero(plaintext)673- }674- }675-676- /**677- * Seal ONLY the 32-byte root key under a key the recovery [words] derive,678- * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex679- * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,680- * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap681- * the same root key on the browser. Returns null with no in-memory root key or682- * a checksum-invalid phrase.683- */684- private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {685- if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null686- val rk = rootKey ?: return null687- val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null688- val salt = VaultCrypto.generateSalt()689- val recoveryKey = deriveRecoveryKey(material, salt)690- val keyBytes = recoveryKey.encoded691- val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)692- return try {693- // combined = nonce(12) || ciphertext || tag(16)694- val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)695- val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)696- val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)697- val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)698- val ct = ctTag.copyOfRange(0, ctTag.size - 16)699- RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))700- } finally {701- VaultCrypto.zero(material)702- VaultCrypto.zero(keyBytes)703- VaultCrypto.zero(plaintext)704- }705- }706-707- /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */708- private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {709- val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null710- val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))711- val keyBytes = recoveryKey.encoded712- return try {713- val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)714- val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)715- hexToRootKey(String(pt, Charsets.US_ASCII))716- } catch (_: Exception) {717- null718- } finally {719- VaultCrypto.zero(material)720- VaultCrypto.zero(keyBytes)721- }722- }723-724- /**725- * Re-seal slot A from the current in-memory state under the live key, carrying726- * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs727- * in decoy mode (recovery is never offered for the decoy) and persists without728- * a version bump, like the recovery-words metadata write it replaces.729- */730- private fun persistSlotAWithEscrows(731- recoveryEscrow: RecoveryEscrow?,732- rootKeyEscrow: RootKeyEscrow?,733- ): Boolean {734- val key = derivedKey ?: throw IllegalStateException("vault_locked")735- if (decoyMode) return false736- val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")737- val plaintext = VaultCodec.encode(currentPayload())738- val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))739- val next = prior.copy(740- blob = blob,741- recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,742- rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,743- )744- if (!store.writeSlotA(next)) return false745- try {746- writeMatchingNoiseSlotB(next)747- } catch (e: Exception) {748- store.writeSlotA(prior)749- throw e750- }751- return true752- }753-754- // ---- Internals --------------------------------------------------------755-756- private fun requireUnlocked() {757- if (derivedKey == null) throw IllegalStateException("vault_locked")758- }759-760- /**761- * On unlock, hard-delete trashed entries older than the retention window.762- * A null or non-positive [VaultSettings.trashRetentionDays] means "never"763- * (the app's "Never" option), so nothing is purged. Persists without a764- * version bump and without touching the publish state (caller publishes).765- */766- private fun autoPurgeExpiredTrash() {767- val days = _settings.value.trashRetentionDays ?: return768- if (days <= 0) return769- val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L770- val before = entryList.size771- entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }772- if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }773- }774-775- /** The slot-A plaintext envelope for the current in-memory session. */776- private fun currentPayload(): VaultPayload =777- VaultPayload(778- entries = entryList.toList(),779- duressConfigured = duressConfigured,780- rootKeyB64 = rootKey?.let(::b64) ?: "",781- recoveryWordHash = recoveryWordHash,782- recoveryWordsSet = recoveryWordsSet,783- )784-785- /**786- * Adopt the payload's root key, lazily minting one for legacy payloads.787- * A freshly-minted key is persisted WITHOUT bumping the version — adopting788- * a root key is not a mutation paired devices should sync against.789- */790- private fun ensureRootKey(payload: VaultPayload) {791- if (payload.rootKeyB64.isNotBlank()) {792- rootKey = unb64(payload.rootKeyB64)793- return794- }795- rootKey = generateRecoverableRootKey()796- runCatching { persistSlotA(bumpVersion = false) }797- }798-799- private fun publish() {800- _entries.value = entryList.filter { it.deletedAt == null }801- }802-803- private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {804- val plaintext = VaultCodec.encode(currentPayload())805- val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))806- return StoredVault(version = 1, salt = b64(salt), blob = blob)807- }808-809- private fun writeMatchingNoiseSlotB(slotA: StoredVault) {810- val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)811- val noise = ByteArray(approxBytes).also(rng::nextBytes)812- store.writeSlotB(b64(noise))813- }814-815- /** Re-seal slot A from the current in-memory state under the live key. */816- private fun persistSlotA(bumpVersion: Boolean): Boolean {817- val key = derivedKey ?: throw IllegalStateException("vault_locked")818- // Decoy sessions persist to the decoy slot only — never touch the real slot A.819- if (decoyMode) {820- val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")821- val plaintext = VaultCodec.encode(currentPayload())822- val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))823- return store.writeDecoySlot(prior.copy(blob = blob))824- }825- val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")826- val plaintext = VaultCodec.encode(currentPayload())827- val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))828- val next = prior.copy(blob = blob)829- if (!store.writeSlotA(next)) return false830- // Slot A committed — keep slot B size-matched, then advance the version831- // for local writes only. Restore slot A if a later step fails.832- try {833- writeMatchingNoiseSlotB(next)834- if (bumpVersion) store.stampLocalMutation()835- } catch (e: Exception) {836- store.writeSlotA(prior)837- throw e838- }839- return true840- }841-842- /** Persist a local mutation, rolling the in-memory list back on failure. */843- private fun persistOrRollback(rollback: MutableList<VaultEntry>) {844- try {845- if (!persistSlotA(bumpVersion = true)) {846- entryList = rollback847- throw IllegalStateException("storage_write_failed")848- }849- } catch (e: Exception) {850- entryList = rollback851- throw e852- }853- publish()854- }855-}app/drafts/MF1MF2/VaultStore.kt+0 −182
@@ -1,182 +0,0 @@1-package com.peachpasswords.vault2-3-import android.content.Context4-import dagger.hilt.android.qualifiers.ApplicationContext5-import kotlinx.serialization.Serializable6-import kotlinx.serialization.decodeFromString7-import kotlinx.serialization.encodeToString8-import kotlinx.serialization.json.Json9-import javax.inject.Inject10-import javax.inject.Singleton11-12-/**13- * One encrypted slot at rest. [blob] is base64 of VaultCrypto's14- * `nonce || ciphertext || tag` output; [salt] (base64) drives Argon2id.15- * Mirrors the browser's StoredVault. [recoveryEscrow] is null until the user16- * sets recovery words; it is a password-independent second copy of the slot-A17- * plaintext that powers the forgot-password flow.18- */19-@Serializable20-data class StoredVault(21- val version: Int = 1,22- val salt: String,23- val blob: String,24- val recoveryEscrow: RecoveryEscrow? = null,25- val rootKeyEscrow: RootKeyEscrow? = null,26-)27-28-/**29- * Browser-byte-compatible recovery escrow that wraps ONLY the 32-byte root key,30- * so the same 12 recovery words unwrap the same root key on either platform31- * (MF-1). The wrapped plaintext is the lowercase ASCII hex of the root key; the32- * key is `HKDF-SHA256(wordsToRootKeyMaterial(words), salt, "peach-recovery-v1")`33- * and the AEAD AAD is the single byte 0x01 ([VaultCrypto.AAD_RECOVERY_ROOTKEY]) —34- * all matching the browser (`vault.ts:282-316`).35- *36- * Fields mirror the browser's slot-A `recovery_*` fields (base64 here vs hex on37- * the browser) so a future browser-slot importer can map them directly:38- * [salt] = `recovery_salt`, [wrappedRootKey] = `recovery_wrapped_root_key`39- * (ciphertext only), [nonce] = `recovery_nonce`, [tag] = `recovery_tag`.40- */41-@Serializable42-data class RootKeyEscrow(43- val salt: String,44- val wrappedRootKey: String,45- val nonce: String,46- val tag: String,47-)48-49-/**50- * A second, password-independent copy of the slot-A plaintext envelope, sealed51- * under a key the 12 BIP39 recovery words derive (HKDF). Lets the vault be52- * recovered and re-wrapped under a new password without the old password.53- *54- * [salt] (base64, 16B) is the HKDF salt for `deriveRecoveryKey`.55- * [blob] (base64) is `VaultCrypto.encrypt(slotAPlaintext, recoveryKey, AAD_RECOVERY)`56- * i.e. `nonce(12) || AES-256-GCM ciphertext||tag`.57- */58-@Serializable59-data class RecoveryEscrow(60- val salt: String,61- val blob: String,62-)63-64-/** A soft-deleted entry, exposed to the sync layer for last-write-wins merges. */65-@Serializable66-data class Tombstone(val id: String, val deletedAt: Long)67-68-/**69- * The decrypted slot-A envelope: the entry list, the duress flag, and the70- * stable sync root key.71- *72- * [rootKeyB64] is the vault's stable 32-byte sync master key (base64, no73- * padding). Unlike the Argon2id password key it never rotates on a password74- * change, so paired devices keep deriving the same vault_id, Noise static key,75- * and per-entry envelope keys across independent password rotations (browser76- * SEV-2-B). Empty on legacy payloads written before sync landed — the77- * repository lazily mints and persists one on first unlock.78- */79-@Serializable80-data class VaultPayload(81- val entries: List<VaultEntry> = emptyList(),82- val duressConfigured: Boolean = false,83- val rootKeyB64: String = "",84- /**85- * BLAKE3 hash of the space-joined 12 BIP39 recovery words. Lets the app verify86- * recovery-word entry without storing the words themselves. Null until set.87- */88- val recoveryWordHash: String? = null,89- /** True once the user has confirmed (written down) their recovery words. */90- val recoveryWordsSet: Boolean = false,91-)92-93-/** Pure JSON codec for the slot-A plaintext envelope — usable without Android. */94-object VaultCodec {95- private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }96- fun encode(payload: VaultPayload): ByteArray = json.encodeToString(payload).toByteArray(Charsets.UTF_8)97- fun decode(bytes: ByteArray): VaultPayload = json.decodeFromString(String(bytes, Charsets.UTF_8))98- fun encodeSettings(s: VaultSettings): String = json.encodeToString(s)99- fun decodeSettings(s: String): VaultSettings? = runCatching { json.decodeFromString<VaultSettings>(s) }.getOrNull()100- fun encodeSlot(s: StoredVault): String = json.encodeToString(s)101- fun decodeSlot(s: String): StoredVault? = runCatching { json.decodeFromString<StoredVault>(s) }.getOrNull()102-}103-104-/**105- * Persistence for the two vault slots, the monotonic version counter, and the106- * settings blob. Abstracted behind an interface so the repository can be107- * exercised against an in-memory fake in plain JUnit.108- */109-interface VaultStorage {110- fun loadSlotA(): StoredVault?111- fun hasVault(): Boolean112- fun writeSlotA(slot: StoredVault): Boolean113- fun writeSlotB(blobBase64: String): Boolean114- fun loadDecoySlot(): StoredVault?115- fun writeDecoySlot(slot: StoredVault): Boolean116- fun hasDecoySlot(): Boolean117- fun clearDecoySlot()118- fun version(): Long119- fun stampLocalMutation(): Long120- fun loadSettings(): VaultSettings121- fun writeSettings(settings: VaultSettings): Boolean122- fun clearVault()123-}124-125-/**126- * SharedPreferences-backed [VaultStorage]. The slot blobs are already AES-GCM127- * sealed under the Argon2id key, so plaintext prefs are fine — only the salt is128- * in the clear, exactly as in storage.local on the extension. The Pro license129- * lives in a SEPARATE prefs file (LicenseRepository), so wiping this store can130- * never touch the license — destroyVault()'s core invariant.131- */132-@Singleton133-class VaultStore @Inject constructor(134- @ApplicationContext context: Context,135-) : VaultStorage {136- private val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)137-138- override fun loadSlotA(): StoredVault? = prefs.getString(KEY_SLOT_A, null)?.let(VaultCodec::decodeSlot)139-140- override fun hasVault(): Boolean = prefs.contains(KEY_SLOT_A)141-142- override fun writeSlotA(slot: StoredVault): Boolean =143- prefs.edit().putString(KEY_SLOT_A, VaultCodec.encodeSlot(slot)).commit()144-145- override fun writeSlotB(blobBase64: String): Boolean =146- prefs.edit().putString(KEY_SLOT_B, blobBase64).commit()147-148- override fun loadDecoySlot(): StoredVault? = prefs.getString(KEY_SLOT_DURESS, null)?.let(VaultCodec::decodeSlot)149- override fun writeDecoySlot(slot: StoredVault): Boolean =150- prefs.edit().putString(KEY_SLOT_DURESS, VaultCodec.encodeSlot(slot)).commit()151- override fun hasDecoySlot(): Boolean = prefs.contains(KEY_SLOT_DURESS)152- override fun clearDecoySlot() { prefs.edit().remove(KEY_SLOT_DURESS).commit() }153-154- override fun version(): Long = prefs.getString(KEY_VERSION, null)?.toLongOrNull() ?: 0L155-156- override fun stampLocalMutation(): Long {157- val next = maxOf(System.currentTimeMillis(), version() + 1L)158- prefs.edit().putString(KEY_VERSION, next.toString()).commit()159- return next160- }161-162- override fun loadSettings(): VaultSettings =163- prefs.getString(KEY_SETTINGS, null)?.let(VaultCodec::decodeSettings) ?: VaultSettings()164-165- override fun writeSettings(settings: VaultSettings): Boolean =166- prefs.edit().putString(KEY_SETTINGS, VaultCodec.encodeSettings(settings)).commit()167-168- override fun clearVault() {169- prefs.edit()170- .remove(KEY_SLOT_A).remove(KEY_SLOT_B).remove(KEY_VERSION).remove(KEY_SETTINGS)171- .commit()172- }173-174- companion object {175- private const val PREFS = "peach_vault_store"176- private const val KEY_SLOT_A = "peach_vault_a"177- private const val KEY_SLOT_B = "peach_vault_b"178- private const val KEY_SLOT_DURESS = "peach_vault_duress"179- private const val KEY_VERSION = "peach_last_modified_at"180- private const val KEY_SETTINGS = "peach_settings"181- }182-}app/drafts/MF1MF2/gen_peach_fixture.mjs+0 −51
@@ -1,51 +0,0 @@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/drafts/MF1MF2/mf1_kat_gen.mjs+0 −106
@@ -1,106 +0,0 @@1-// Generates an MF-1 known-answer vector using the BROWSER's exact recovery2-// algorithm (recovery-words.ts) against the REAL browser word list.3-// Read-only against peach-browser. Output is pinned into the Android KAT.4-import { readFileSync } from "node:fs";5-6-const listSrc = readFileSync(7- "/Users/june/projects/peach-browser/src/shared/recovery-word-list.ts",8- "utf8"9-);10-// Extract quoted words in source order.11-const WORD_LIST = [...listSrc.matchAll(/"([a-z]+)"/g)].map((m) => m[1]);12-if (WORD_LIST.length < 2048) throw new Error("word list parse failed: " + WORD_LIST.length);13-14-const WORD_BITS = 11n;15-const TOTAL_WORDS = 12;16-const hex = (u8) => [...u8].map((b) => b.toString(16).padStart(2, "0")).join("");17-const unhex = (s) => new Uint8Array(s.match(/../g).map((h) => parseInt(h, 16)));18-19-async function rootKeyToWords(rootKeyBytes) {20- const entropy16 = rootKeyBytes.slice(0, 16);21- const entropyHash = new Uint8Array(await crypto.subtle.digest("SHA-256", entropy16));22- const checksum = entropyHash[0] >> 4;23- let bitsBig = 0n;24- for (let i = 0; i < 16; i++) bitsBig = (bitsBig << 8n) | BigInt(rootKeyBytes[i]);25- bitsBig = (bitsBig << 4n) | BigInt(checksum);26- const words = [];27- for (let i = 0; i < TOTAL_WORDS; i++) {28- const shift = BigInt(TOTAL_WORDS - 1 - i) * WORD_BITS;29- const index = Number((bitsBig >> shift) & 0x7ffn);30- words.push(WORD_LIST[index]);31- }32- return words;33-}34-35-async function wordsToRootKeyMaterial(words) {36- const indices = words.map((w) => {37- const i = WORD_LIST.indexOf(w.toLowerCase().trim());38- if (i === -1) throw new Error("unknown word " + w);39- return i;40- });41- let bitsBig = 0n;42- for (const idx of indices) bitsBig = (bitsBig << WORD_BITS) | BigInt(idx);43- const entropy = new Uint8Array(16);44- for (let i = 0; i < 16; i++) entropy[i] = Number((bitsBig >> BigInt(124 - i * 8)) & 0xffn);45- const storedChecksum = Number(bitsBig & 0xfn);46- const entropyHash = new Uint8Array(await crypto.subtle.digest("SHA-256", entropy));47- if (storedChecksum !== entropyHash[0] >> 4) throw new Error("checksum mismatch");48- const rootKey = new Uint8Array(32);49- rootKey.set(entropy);50- return rootKey;51-}52-53-async function deriveRecoveryKeyRaw(wordMaterial, salt) {54- const baseKey = await crypto.subtle.importKey("raw", wordMaterial, { name: "HKDF" }, false, ["deriveBits"]);55- const bits = await crypto.subtle.deriveBits(56- { name: "HKDF", hash: "SHA-256", salt, info: new TextEncoder().encode("peach-recovery-v1") },57- baseKey,58- 25659- );60- return new Uint8Array(bits);61-}62-63-// Find a deterministic root key whose words round-trip cleanly.64-async function findRootKey() {65- for (let seed = 1; seed < 100000; seed++) {66- const rk = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode("peach-mf1-kat-" + seed)));67- const words = await rootKeyToWords(rk);68- try {69- const mat = await wordsToRootKeyMaterial(words);70- // require exact round-trip of first 16 bytes too71- if (hex(mat.slice(0, 16)) === hex(rk.slice(0, 16))) return { rk, words, seed };72- } catch {}73- }74- throw new Error("no key found");75-}76-77-const { rk, words, seed } = await findRootKey();78-const salt = unhex("000102030405060708090a0b0c0d0e0f");79-const nonce = unhex("0b0a090807060504030201ff");80-const material = await wordsToRootKeyMaterial(words);81-const recoveryKeyRaw = await deriveRecoveryKeyRaw(material, salt);82-83-// Wrap hex(rootKey) ASCII under recoveryKey, AAD = [1], fixed nonce.84-const aesKey = await crypto.subtle.importKey("raw", recoveryKeyRaw, { name: "AES-GCM" }, false, ["encrypt"]);85-const plaintext = new TextEncoder().encode(hex(rk)); // 64 ASCII bytes86-const wrapped = new Uint8Array(87- await crypto.subtle.encrypt(88- { name: "AES-GCM", iv: nonce, additionalData: new Uint8Array([1]), tagLength: 128 },89- aesKey,90- plaintext91- )92-);93-const ct = wrapped.slice(0, wrapped.length - 16);94-const tag = wrapped.slice(wrapped.length - 16);95-96-console.log(JSON.stringify({97- seed,98- rootKeyHex: hex(rk),99- words,100- wordMaterialHex: hex(material),101- recoveryKeyHex: hex(recoveryKeyRaw),102- saltHex: hex(salt),103- nonceHex: hex(nonce),104- ciphertextHex: hex(ct),105- tagHex: hex(tag),106-}, null, 2));app/drafts/MF1MF2/parse_android_export.mjs+0 −22
@@ -1,22 +0,0 @@1-import { createServer } from "/Users/june/projects/peach-browser/node_modules/vite/dist/node/index.js";2-import { readFileSync } from "node:fs";3-4-const server = await createServer({5- root: "/Users/june/projects/peach-browser",6- configFile: false, logLevel: "silent",7- server: { middlewareMode: true, hmr: false },8-});9-try {10- const { parsePayload } = await server.ssrLoadModule("/src/crypto/peachPayload.ts");11- const b64 = readFileSync("/tmp/android_export.b64", "utf8").trim();12- const bytes = new Uint8Array(Buffer.from(b64, "base64"));13- const parsed = await parsePayload(bytes, "android-pw");14- console.log("BROWSER PARSED ANDROID EXPORT:", parsed.entries.length, "entries");15- console.log(JSON.stringify(parsed.entries.map((e) => ({16- type: e.type, title: e.title, username: e.username, password: e.password,17- email: e.email, tags: e.tags, breach: e.breach, network: e.network,18- cardNumber: e.cardNumber, notes: e.notes, canary: e.canary,19- })), null, 2));20-} finally {21- await server.close();22-}app/src/main/AndroidManifest.xml+0 −7
@@ -14,9 +14,6 @@1414 </queries>1515 1616 <uses-permission android:name="android.permission.INTERNET" />17- <!-- mDNS/NSD peer discovery for the C7 LAN sync transport -->18- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />19- <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />2017 <uses-permission android:name="android.permission.VIBRATE" />2118 <uses-permission android:name="android.permission.USE_BIOMETRIC" />2219 <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />@@ -63,10 +60,6 @@6360 android:resource="@xml/shortcuts" />6461 </activity>6562 66- <activity67- android:name=".ui.lock.BiometricUnlockActivity"68- android:exported="false"69- android:theme="@style/Theme.Peach" />7063 7164 <activity7265 android:name=".autofill.AutofillEntryPickerActivity"app/src/main/java/com/peachpasswords/PeachApplication.kt+18 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/autofill/AssistStructureParser.kt+1 −0
@@ -28,6 +28,7 @@2828 val isNewPassword: Boolean = false,2929 val webDomain: String? = null,3030 val packageName: String? = null,31+ val nativeSignerDigests: Set<String> = emptySet(),3132 val originDomains: List<String> = emptyList(),3233 /** False when an app claimed a web origin without a verified browser identity. */3334 val credentialReleaseAllowed: Boolean = true,app/src/main/java/com/peachpasswords/autofill/AutofillIntents.kt+12 −12
not shown here: too long for one page
app/src/main/java/com/peachpasswords/autofill/AutofillOrigin.kt+4 −1
@@ -34,7 +34,10 @@3434 PasskeyCallerOrigin.isVerifiedBrowser(context, parsed.packageName),3535 )3636 }37- return parsed.copy(originDomains = appLinkDomains(context, parsed.packageName))37+ return parsed.copy(38+ nativeSignerDigests = parsed.packageName?.let { PasskeyCallerOrigin.signerFingerprints(context, it) }.orEmpty(),39+ originDomains = appLinkDomains(context, parsed.packageName),40+ )3841 }3942 4043 /** Preserve an unverified web claim as a deny decision instead of reinterpreting it as native. */app/src/main/java/com/peachpasswords/autofill/AutofillResponseBuilder.kt+8 −4
not shown here: too long for one page
app/src/main/java/com/peachpasswords/autofill/AutofillSave.kt+9 −5
not shown here: too long for one page
app/src/main/java/com/peachpasswords/autofill/PasswordPolicy.kt+8 −1
not shown here: too long for one page
app/src/main/java/com/peachpasswords/autofill/PeachAutofillService.kt+2 −1
@@ -154,6 +154,7 @@154154 inlineSpec = pickerSpec,155155 unlocked = unlocked,156156 hasMatches = hasLoginMatch,157+ requestId = request.id,157158 )158159 )159160 datasetCount++@@ -208,7 +209,7 @@208209 callback.onSuccess()209210 return210211 }211- val draft = autofillSaveDraft(parsed)212+ val draft = autofillSaveDraft(parsed, parsed.nativeSignerDigests.takeIf { parsed.webDomain == null })212213 if (draft == null) {213214 callback.onSuccess()214215 returnapp/src/main/java/com/peachpasswords/credentials/CredentialProviderUnlockActivity.kt+1 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/credentials/PasswordCredentialPlanner.kt+6 −2
not shown here: too long for one page
app/src/main/java/com/peachpasswords/license/LicenseCodec.kt+110 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/license/LicenseRepository.kt+7 −90
not shown here: too long for one page
app/src/main/java/com/peachpasswords/license/ProFeature.kt+0 −5
not shown here: too long for one page
app/src/main/java/com/peachpasswords/license/ProNoticeStore.kt+1 −1
not shown here: too long for one page
app/src/main/java/com/peachpasswords/passkeys/PasskeyCallerOrigin.kt+9 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/passkeys/PeachCredentialProviderService.kt+2 −2
not shown here: too long for one page
app/src/main/java/com/peachpasswords/shared/PeachClipboard.kt+51 −8
not shown here: too long for one page
app/src/main/java/com/peachpasswords/sync/AdoptionProtocol.kt+16 −12
not shown here: too long for one page
app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+9 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+63 −21
not shown here: too long for one page
app/src/main/java/com/peachpasswords/sync/PeachSyncService.kt+9 −19
not shown here: too long for one page
app/src/main/java/com/peachpasswords/sync/RelayAdoptionHost.kt+50 −5
not shown here: too long for one page
app/src/main/java/com/peachpasswords/sync/RelayAdoptionReceiver.kt+20 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/sync/Rendezvous.kt+0 −28
not shown here: too long for one page
app/src/main/java/com/peachpasswords/sync/SyncFreshStartResetter.kt+4 −1
not shown here: too long for one page
app/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+18 −5
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/codex/CodexGenerateScreen.kt+6 −1
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/codex/CodexViewModel.kt+9 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/lock/BiometricUnlockActivity.kt+0 −11
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+1 −3
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+4 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/pairing/CodePairScreen.kt+7 −3
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+7 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+31 −13
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+5 −3
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+29 −6
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/vault/CsvImport.kt+34 −12
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/vault/ImportScreen.kt+10 −2
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/vault/RecoveryWordsScreen.kt+60 −9
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/vault/VaultHealthScreen.kt+2 −3
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/DuressConfig.kt+37 −11
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/PeachPayloadCodec.kt+11 −7
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+2 −8
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultEntry.kt+2 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+94 −4
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultSettings.kt+24 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultStore.kt+6 −0
not shown here: too long for one page
app/src/main/jniLibs/armeabi-v7a/libpeach_noise_core.sobinary
binary file, not shown
app/src/main/jniLibs/x86/libpeach_noise_core.sobinary
binary file, not shown
app/src/test/java/com/peachpasswords/autofill/AssistStructureOtpRegexTest.kt+37 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/autofill/AutofillMatchTest.kt+17 −4
not shown here: too long for one page
app/src/test/java/com/peachpasswords/autofill/AutofillSaveTest.kt+25 −5
not shown here: too long for one page
app/src/test/java/com/peachpasswords/autofill/PasswordPolicyTest.kt+7 −2
not shown here: too long for one page
app/src/test/java/com/peachpasswords/backup/BackupRulesCoverageTest.kt+44 −10
not shown here: too long for one page
app/src/test/java/com/peachpasswords/credentials/PasswordCredentialPlannerTest.kt+20 −5
not shown here: too long for one page
app/src/test/java/com/peachpasswords/license/LicenseCodecTest.kt+120 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/license/ProNoticeStoreTest.kt+1 −1
not shown here: too long for one page
app/src/test/java/com/peachpasswords/shared/PeachClipboardTest.kt+28 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/sync/PairedDeviceRevocationTest.kt+23 −2
not shown here: too long for one page
app/src/test/java/com/peachpasswords/sync/RendezvousTest.kt+0 −28
not shown here: too long for one page
app/src/test/java/com/peachpasswords/sync/SourceConsentGateTest.kt+46 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/vault/DecoySettingsIsolationTest.kt+75 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/vault/DuressPolicyRecordTest.kt+34 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/vault/ImportSettingsClassificationTest.kt+49 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/vault/SlotPaddingTest.kt+2 −1
not shown here: too long for one page
app/src/test/java/com/peachpasswords/vault/VaultCryptoTest.kt+16 −3
not shown here: too long for one page
app/src/test/java/com/peachpasswords/vault/VaultKeyRotationHooksTest.kt+66 −0
not shown here: too long for one page