51a8e8ea9ff3
port MF-1 recovery escrow to browser parity (wordsToRootKeyMaterial IKM, browser-compatible root-key escrow AAD 0x01) and fix rootKeyToWords checksum sign-extension bug; cross-platform KAT + 95 tests green, assembleDebug+lintDebug pass
- time
- 2026-06-09 16:16 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- cross-platform recovery and peachscript parity
- parent
- 4813b7ed6274
↓ peach-android-51a8e8ea.tar.gzatlas at this save
files changed13 files
app/drafts/MF1MF2/BROWSER-SPEC.md+465 −0app/drafts/MF1MF2/RecoveryEscrowTest.kt+215 −0app/drafts/MF1MF2/RecoveryWords.kt+141 −0app/drafts/MF1MF2/VaultCrypto.kt+121 −0app/drafts/MF1MF2/VaultRepository.kt+855 −0app/drafts/MF1MF2/VaultStore.kt+182 −0app/drafts/MF1MF2/mf1_kat_gen.mjs+106 −0app/src/main/java/com/peachpasswords/vault/RecoveryWords.kt+37 −18app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+25 −5app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+129 −55app/src/main/java/com/peachpasswords/vault/VaultStore.kt+22 −0app/src/test/java/com/peachpasswords/vault/RecoveryEscrowTest.kt+101 −15peach-android-audit-report.md+330 −0app/drafts/MF1MF2/BROWSER-SPEC.md+465 −0
@@ -0,0 +1,465 @@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+### [SHARED LATENT BUG] duplicate-`abandon` root keys (~0.6%)386+The browser's `createVault` (`vault.ts:947`) and `migrateToRecovery`387+(`vault.ts:511`) call `generateAndWrapRootKey` with no retry, so ~0.6% of random388+root keys (those whose `rootKeyToWords` output includes an index-1 `"abandon"`)389+make recovery setup **throw** (`wordsToRootKeyMaterial` checksum failure). This is390+a genuine reference bug. **Android deviates deliberately and safely**: it391+generates root keys in a bounded retry loop until `rootKeyToWords` →392+`wordsToRootKeyMaterial` round-trips, producing a strict, fully cross-compatible393+**subset** of root keys. No vault Android creates is browser-incompatible, and the394+~0.6% crash is avoided. (Recommend reporting upstream; `peach-browser` was not395+modified.) A checksum-invalid phrase entered at recovery is rejected on **both**396+platforms — that is correct parity, not a divergence.397+398+### Card `last4` (relates to MF-3, out of scope)399+Android `VaultEntry` has no `last4` field (the browser does). For PeachScript400+round-trip the codec derives `last4` from the last 4 digits of `cardNumber` on401+export and drops the browser's `last4` on import (the full `cardNumber` already402+carries it). Android `cardNetwork` (String) maps to/from the browser `network`403+byte by the same value set. No `VaultEntry` change is made here; MF-3 (rename +404+`last4`) remains a separate fix.405+406+### Tests that change behavior (necessary, not regressions)407+- `RecoveryEscrowTest` test #6 (`escrow_round_trips_for_phrase_with_duplicate_abandon`)408+ asserts the **old BLAKE3** behavior (round-trips a checksum-invalid all-`abandon`409+ phrase). Under browser parity that phrase is **rejected**. The test is rewritten410+ to assert rejection of a checksum-invalid phrase (matching the browser) + a411+ parity KAT is added. Count preserved.412+- `ExportRoundTripTest` PeachScript cases and `ImportParsersTest` PeachScript cases413+ assert the **old JSON** format being replaced; they are updated to the new414+ format. New `PeachScriptTest.kt` adds KATs + full-fidelity round-trip.415+416+---417+418+## Integration Contract419+420+### New files (drafts → integrate into `app/src/main/java/com/peachpasswords/`)421+- `vault/PeachScript.kt` — PUA text codec (`encodePeachScript`/`decodePeachScript`/422+ `normalisePeachScript`/`isPeachScript`).423+- `vault/PeachPayloadCodec.kt` — binary PCHS payload (`buildPayload`/`parsePayload`,424+ string table, entry packing, zstd, BLAKE3, Argon2id-UTF8, AES-GCM, uuid/network).425+426+### Files to replace427+- `ui/vault/PeachScriptExport.kt` — `buildEncrypted(entries, backupPassword): String`428+ now returns the PUA-encoded PCHS payload. (Drop the JSON `buildPlaintext`.)429+- `ui/vault/PeachScriptImport.kt` — `looksLikePeachScript` → PUA sniff; `isEncrypted`430+ → always true; `decryptAndParse` / new `parseFull` return **full** `VaultEntry`.431+- `vault/RecoveryWords.kt` — recovery IKM via `wordsToRootKeyMaterial` (retire432+ `wordKeyMaterial` from the escrow path); add round-trip-checked root-key gen helper.433+- `vault/VaultCrypto.kt` — add raw-`ByteArray`-AAD encrypt/decrypt + `AAD_RECOVERY_ROOTKEY = byte 0x01`.434+- `vault/VaultStore.kt` — add `RootKeyEscrow{salt,wrappedRootKey,nonce,tag}` to `StoredVault`.435+- `vault/VaultRepository.kt` — seal/unseal both escrows; round-trip-checked root-key gen;436+ leave root-key escrow stable on `changePassword`.437+438+### Files to update (integration)439+- `ui/vault/ImportScreen.kt` — PeachScript path consumes full `VaultEntry` (preserve all fields).440+- `ui/vault/ExportScreen.kt` — saves `.peach` (unchanged call shape).441+- Tests: `RecoveryEscrowTest.kt`, `ExportRoundTripTest.kt`, `ImportParsersTest.kt` updated;442+ add `RecoveryEscrowTest`/`PeachScriptTest` KATs.443+444+### New dependency (`app/build.gradle`)445+```gradle446+implementation 'com.github.luben:zstd-jni:1.5.6-3'447+```448+No `AndroidManifest.xml` changes.449+450+### Integration order451+1. zstd-jni dependency → sync.452+2. MF-1: `VaultCrypto` + `VaultStore` + `RecoveryWords` + `VaultRepository` → build → `RecoveryEscrowTest`.453+3. MF-2: `PeachScript` + `PeachPayloadCodec` → build → `PeachScriptTest`.454+4. Replace `PeachScriptExport`/`Import`, update `ImportScreen` → build → `ExportRoundTripTest`/`ImportParsersTest`.455+5. `assembleDebug` + `lintDebug` + full unit suite.456+457+### Known-answer vectors the orchestrator must verify against the browser458+- **MF-1 KAT**: fixed 32-byte root key → fixed words (`rootKeyToWords`); fixed459+ recovery salt → `deriveRecoveryKey(wordsToRootKeyMaterial(words), salt)` → wrap460+ `hex(rootKey)` (AAD 0x01) → confirm a browser-computed `recovery_wrapped_root_key`461+ unwraps to the same root key. (Generate the browser vector with a tiny Node462+ script against `recovery-words.ts`/`vault.ts` if a live cross-check is wanted.)463+- **MF-2 KAT**: a small browser-produced `.peach` blob (PUA text) → Android464+ `parseFull` yields the expected entries (pins PUA + envelope + zstd + packing).465+ Plus Android self-round-trip and Unicode/empty-vault/wrong-password cases.app/drafts/MF1MF2/RecoveryEscrowTest.kt+215 −0
@@ -0,0 +1,215 @@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+141 −0
@@ -0,0 +1,141 @@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+121 −0
@@ -0,0 +1,121 @@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+855 −0
@@ -0,0 +1,855 @@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+182 −0
@@ -0,0 +1,182 @@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/mf1_kat_gen.mjs+106 −0
@@ -0,0 +1,106 @@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/src/main/java/com/peachpasswords/vault/RecoveryWords.kt+37 −18
@@ -14,7 +14,11 @@1414 require(rootKeyBytes.size == 32) { "root key must be 32 bytes" }1515 val entropy16 = rootKeyBytes.copyOfRange(0, 16)1616 val entropyHash = MessageDigest.getInstance("SHA-256").digest(entropy16)17- val checksum = entropyHash[0].toInt() ushr 417+ // 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 41822 1923 var bitsBig = BigInteger.ZERO2024 for (i in 0 until 16) {@@ -55,31 +59,46 @@5559 5660 val storedChecksum = bitsBig.and(BigInteger.valueOf(0xFL)).toInt()5761 val entropyHash = MessageDigest.getInstance("SHA-256").digest(entropy)58- val computedChecksum = entropyHash[0].toInt() ushr 462+ // See rootKeyToWords: mask to a byte before the unsigned shift (browser parity).63+ val computedChecksum = (entropyHash[0].toInt() and 0xff) ushr 45964 require(storedChecksum == computedChecksum) { "invalid recovery words — checksum mismatch" }6065 6166 return ByteArray(32).also { it.fill(0); System.arraycopy(entropy, 0, it, 0, entropy.size) }6267 }6368 6469 /**65- * Collision-stable key material for the recovery escrow, derived from the canonical66- * word *strings* rather than reconstructed entropy indices.70+ * Generate a random 32-byte root key whose recovery words round-trip cleanly.6771 *68- * WORD_LIST carries "abandon" at both index 0 and 1 (a deliberate parity copy of69- * the browser list), so `wordsToRootKeyMaterial` — which reconstructs entropy via70- * `indexOf` — is NOT a perfect inverse of `rootKeyToWords` for any phrase that uses71- * index 1: the words become ambiguous. The escrow must round-trip for EVERY vault,72- * so it keys off BLAKE3 of the space-joined words (the same canonical form73- * [recoveryWordsHash] verifies), which is identical whichever "abandon" index the74- * phrase was generated from.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.7580 */76-fun wordKeyMaterial(words: List<String>): ByteArray {77- val canonical = words.joinToString(" ") { it.trim().lowercase() }.encodeToByteArray()78- val digest = org.bouncycastle.crypto.digests.Blake3Digest(256)79- digest.update(canonical, 0, canonical.size)80- val out = ByteArray(32)81- digest.doFinal(out, 0)82- return out81+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() }83102 }84103 85104 fun deriveRecoveryKey(wordMaterial: ByteArray, salt: ByteArray): SecretKeySpec {app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+25 −5
@@ -27,10 +27,19 @@2727 2828 /**2929 * 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).30+ * as a slot-A blob (GCM auth covers the AAD). Used by Android's whole-payload31+ * offline-restore escrow.3132 */3233 const val AAD_RECOVERY = "recovery_escrow_v1"3334 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+3443 private val secureRandom = SecureRandom()3544 private var _lastTimestamp = 0L3645 @@ -47,7 +56,18 @@4756 return hash4857 }4958 50- fun encrypt(plaintext: ByteArray, key: ByteArray, aad: String): ByteArray {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 {5171 val nonce = ByteArray(NONCE_SIZE).also(secureRandom::nextBytes)5272 val cipher = Cipher.getInstance("AES/GCM/NoPadding")5373 cipher.init(@@ -55,11 +75,11 @@5575 SecretKeySpec(key, "AES"),5676 GCMParameterSpec(TAG_LENGTH_BITS, nonce),5777 )58- cipher.updateAAD(aad.toByteArray(Charsets.UTF_8))78+ cipher.updateAAD(aad)5979 return nonce + cipher.doFinal(plaintext)6080 }6181 62- fun decrypt(data: ByteArray, key: ByteArray, aad: String): ByteArray {82+ fun decrypt(data: ByteArray, key: ByteArray, aad: ByteArray): ByteArray {6383 require(data.size >= NONCE_SIZE) { "Data too short" }6484 val nonce = data.copyOfRange(0, NONCE_SIZE)6585 val ciphertext = data.copyOfRange(NONCE_SIZE, data.size)@@ -69,7 +89,7 @@6989 SecretKeySpec(key, "AES"),7090 GCMParameterSpec(TAG_LENGTH_BITS, nonce),7191 )72- cipher.updateAAD(aad.toByteArray(Charsets.UTF_8))92+ cipher.updateAAD(aad)7393 return cipher.doFinal(ciphertext)7494 }7595 app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+129 −55
@@ -114,7 +114,7 @@114114 recoveryWordHash = null115115 recoveryWordsSet = false116116 decoyMode = false117- rootKey = VaultCrypto.generateRootKey()117+ rootKey = generateRecoverableRootKey()118118 val slotA = sealSlotA(key, salt)119119 if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")120120 writeMatchingNoiseSlotB(slotA)@@ -277,11 +277,16 @@277277 // The escrow seals the slot-A PLAINTEXT, which a password change does not278278 // alter — only the wrapping changes — so carry it forward; rebuilding the279279 // 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`).280284 val next = StoredVault(281285 version = slotA.version,282286 salt = b64(newSalt),283287 blob = blob,284288 recoveryEscrow = slotA.recoveryEscrow,289+ rootKeyEscrow = slotA.rootKeyEscrow,285290 )286291 if (!store.writeSlotA(next)) return false287292 writeMatchingNoiseSlotB(next)@@ -517,9 +522,13 @@517522 requireUnlocked()518523 recoveryWordHash = recoveryWordsHash(words)519524 recoveryWordsSet = true520- // Also seal a password-independent escrow so the forgot-password flow can521- // recover this vault without the master password.522- runCatching { persistSlotAWithEscrow(buildRecoveryEscrow(words)) }.getOrDefault(false)525+ // 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)523532 }524533 525534 /** Verify entered words against the stored recovery hash. */@@ -530,8 +539,9 @@530539 531540 // ---- Recovery escrow (forgot-password) --------------------------------532541 533- /** True at rest if this vault has a recovery escrow the recovery flow can use. */534- fun hasRecoveryEscrow(): Boolean = store.loadSlotA()?.recoveryEscrow != null542+ /** 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 } ?: false535545 536546 /**537547 * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of@@ -547,30 +557,50 @@547557 */548558 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {549559 val slotA = store.loadSlotA() ?: return false550- val escrow = slotA.recoveryEscrow ?: return false551560 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false552- val material = wordKeyMaterial(words)553- val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))554- val keyBytes = recoveryKey.encoded555- return try {556- val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)557- val payload = VaultCodec.decode(plaintext)561+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 false558594 decoyMode = false559- entryList = payload.entries.toMutableList()560- duressConfigured = payload.duressConfigured561- recoveryWordHash = payload.recoveryWordHash562- recoveryWordsSet = payload.recoveryWordsSet563- rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)564- else VaultCrypto.generateRootKey()595+ entryList = mutableListOf()596+ duressConfigured = false597+ recoveryWordHash = recoveryWordsHash(words)598+ recoveryWordsSet = true599+ rootKey = rk565600 _settings.value = store.loadSettings()566- VaultCrypto.zero(plaintext)567- true568- } catch (_: Exception) {569- false // AEADBadTagException (wrong words) or any decode failure570- } finally {571- VaultCrypto.zero(material)572- VaultCrypto.zero(keyBytes)601+ return true573602 }603+ return false574604 }575605 576606 /**@@ -593,29 +623,18 @@593623 val plaintext = VaultCodec.encode(currentPayload())594624 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))595625 val prior = store.loadSlotA()596- // Refresh the escrow against the (unchanged) payload so its salt rotates597- // with the password reset; fall back to the prior escrow if re-seal fails.598- val freshEscrow = if (words.size != 12 || findInvalidWords(words).isNotEmpty()) {599- prior?.recoveryEscrow600- } else {601- val material = wordKeyMaterial(words)602- val salt = VaultCrypto.generateSalt()603- val rk = deriveRecoveryKey(material, salt)604- val kb = rk.encoded605- try {606- RecoveryEscrow(607- salt = b64(salt),608- blob = b64(VaultCrypto.encrypt(plaintext, kb, VaultCrypto.AAD_RECOVERY)),609- )610- } finally {611- VaultCrypto.zero(material); VaultCrypto.zero(kb)612- }613- }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?.rootKeyEscrow614632 val next = StoredVault(615633 version = prior?.version ?: 1,616634 salt = b64(newSalt),617635 blob = blob,618- recoveryEscrow = freshEscrow,636+ recoveryEscrow = freshRecovery,637+ rootKeyEscrow = freshRootKey,619638 )620639 if (!store.writeSlotA(next)) return false621640 writeMatchingNoiseSlotB(next)@@ -633,12 +652,13 @@633652 634653 /**635654 * Seal the current slot-A plaintext under a key derived from the 12 BIP39636- * recovery [words], for password-independent recovery. Returns null if the637- * words are not a valid BIP39 phrase (checksum/unknown word).655+ * 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.638658 */639659 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {640660 if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null641- val material = wordKeyMaterial(words)661+ val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null642662 val salt = VaultCrypto.generateSalt()643663 val recoveryKey = deriveRecoveryKey(material, salt)644664 val keyBytes = recoveryKey.encoded@@ -654,19 +674,73 @@654674 }655675 656676 /**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+ /**657725 * Re-seal slot A from the current in-memory state under the live key, carrying658- * [escrow] onto the written record. Mirrors [persistSlotA]'s real-slot path but659- * adds the recovery escrow field. Never runs in decoy mode (recovery is never660- * offered for the decoy) and persists without a version bump, like the661- * recovery-words metadata write it replaces.726+ * 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.662729 */663- private fun persistSlotAWithEscrow(escrow: RecoveryEscrow?): Boolean {730+ private fun persistSlotAWithEscrows(731+ recoveryEscrow: RecoveryEscrow?,732+ rootKeyEscrow: RootKeyEscrow?,733+ ): Boolean {664734 val key = derivedKey ?: throw IllegalStateException("vault_locked")665735 if (decoyMode) return false666736 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")667737 val plaintext = VaultCodec.encode(currentPayload())668738 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))669- val next = prior.copy(blob = blob, recoveryEscrow = escrow ?: prior.recoveryEscrow)739+ val next = prior.copy(740+ blob = blob,741+ recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,742+ rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,743+ )670744 if (!store.writeSlotA(next)) return false671745 try {672746 writeMatchingNoiseSlotB(next)@@ -718,7 +792,7 @@718792 rootKey = unb64(payload.rootKeyB64)719793 return720794 }721- rootKey = VaultCrypto.generateRootKey()795+ rootKey = generateRecoverableRootKey()722796 runCatching { persistSlotA(bumpVersion = false) }723797 }724798 app/src/main/java/com/peachpasswords/vault/VaultStore.kt+22 −0
@@ -22,6 +22,28 @@2222 val salt: String,2323 val blob: String,2424 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,2547 )2648 2749 /**app/src/test/java/com/peachpasswords/vault/RecoveryEscrowTest.kt+101 −15
@@ -1,6 +1,7 @@11 package com.peachpasswords.vault22 33 import kotlinx.coroutines.runBlocking4+import org.junit.Assert.assertArrayEquals45 import org.junit.Assert.assertEquals56 import org.junit.Assert.assertFalse67 import org.junit.Assert.assertNotNull@@ -40,18 +41,21 @@4041 private fun login(title: String, password: String = "pw") =4142 VaultEntry(id = "", title = title, type = "login", password = password, createdAt = 0, modifiedAt = 0)4243 43- // 1 — setRecoveryWords stores a non-null RecoveryEscrow in StoredVault.44- @Test fun set_recovery_words_writes_escrow() = runBlocking {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 {4547 val storage = RecoveryFakeStorage()4648 val repo = VaultRepository(storage)4749 repo.createVault("pw")4850 assertNull(storage.slotA?.recoveryEscrow)51+ assertNull(storage.slotA?.rootKeyEscrow)4952 assertTrue(repo.setRecoveryWords(recoveryWordsOf(repo)))5053 assertNotNull(storage.slotA?.recoveryEscrow)54+ assertNotNull(storage.slotA?.rootKeyEscrow)5155 assertTrue(repo.hasRecoveryEscrow())5256 }5357 54- // 2 — unlockWithRecoveryWords with correct words succeeds.58+ // 2 — unlockWithRecoveryWords with correct words restores entries (offline escrow).5559 @Test fun unlock_with_correct_words_succeeds() = runBlocking {5660 val storage = RecoveryFakeStorage()5761 val repo = VaultRepository(storage)@@ -61,18 +65,16 @@6165 repo.setRecoveryWords(words)6266 repo.lock()6367 assertTrue(repo.unlockWithRecoveryWords(words))64- // Recovered session sees the entry that was sealed into the escrow.6568 assertTrue(repo.getEntries().any { it.title == "GitHub" })6669 }6770 68- // 3 — unlockWithRecoveryWords with wrong words fails.71+ // 3 — unlockWithRecoveryWords with wrong (still checksum-valid) words fails.6972 @Test fun unlock_with_wrong_words_fails() = runBlocking {7073 val storage = RecoveryFakeStorage()7174 val repo = VaultRepository(storage)7275 repo.createVault("pw")7376 repo.setRecoveryWords(recoveryWordsOf(repo))7477 repo.lock()75- // A different, still-checksum-valid phrase from an unrelated root key.7678 val wrong = rootKeyToWords(ByteArray(32) { (it + 7).toByte() })7779 assertFalse(repo.unlockWithRecoveryWords(wrong))7880 }@@ -103,27 +105,111 @@103105 assertTrue(repo.isUnlocked.value)104106 repo.lock()105107 106- // Old password no longer works; the new one does and the entry survived.107108 assertEquals(UnlockResult.WrongPassword, repo.unlock("old-pass"))108109 assertEquals(UnlockResult.Success, repo.unlock("brand-new-pass"))109110 assertTrue(repo.getEntries().any { it.title == "Bank" })110- // Escrow survived the password reset, so a second recovery still works.111111 assertTrue(repo.hasRecoveryEscrow())112112 }113113 114- // 6 — Round-trips for a phrase containing the duplicate "abandon" (WORD_LIST115- // index 0/1). Index-based entropy derivation can't invert these; the escrow116- // keys off the word strings, so seal+unlock stay consistent.117- @Test fun escrow_round_trips_for_phrase_with_duplicate_abandon() = runBlocking {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 {118120 val storage = RecoveryFakeStorage()119121 val repo = VaultRepository(storage)120122 repo.createVault("pw")121123 repo.addEntry(login("Mail"))122- val words = List(12) { "abandon" }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()!!123179 repo.setRecoveryWords(words)124- assertNotNull(storage.slotA?.recoveryEscrow)180+ // Simulate a browser-made vault: drop the Android-only whole-payload escrow.181+ storage.slotA = storage.slotA!!.copy(recoveryEscrow = null)125182 repo.lock()183+126184 assertTrue(repo.unlockWithRecoveryWords(words))127- assertTrue(repo.getEntries().any { it.title == "Mail" })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"))128214 }129215 }peach-android-audit-report.md+330 −0
@@ -0,0 +1,330 @@1+# Peach Android — Audit Report2+3+**Date:** 2026-06-094+**Base version (per brief):** v2.1.40 — note: `app/build.gradle` actually declares `versionName "2.2.0"` / `versionCode 202000`. The codebase audited is ahead of the brief's stated base. Findings below reference the code as it currently stands.5+**Method:** Read-only static comparison of `peach-android` against `peach-browser` (the reference implementation). No code was modified; no koh/git/gradle was run. Every claim cites `file:line`. Where a browser counterpart could not be found, that is stated rather than assumed.6+7+---8+9+## Executive Summary10+11+The cryptographic **primitives** are in good shape. Argon2id parameters, AES-256-GCM usage, nonce/tag handling, the per-entry sync HKDF envelope, sync-identity derivation, `computeVaultId`, the Noise NK/XX handshakes, SAS derivation, and the Codex RS/Aztec/deflate stack are all byte-for-byte (or parameter-for-parameter) equivalent to the browser. Key material is zeroed on lock and in transient paths, the biometric escrow is hardware-backed and correctly configured, and there is no secret-bearing logging. That is the good news, and it is substantial.12+13+The serious problems are not in the math — they are in **lifecycle and parity**:14+15+- **The vault never locks.** There is no auto-lock timer, no lock-on-background, and the manual lock function is dead code. The advertised auto-lock setting does nothing. Once unlocked, the vault key lives in memory and every entry is decryptable until the OS kills the process. For a password manager this is the most serious finding in the report. **(CF-1, CF-2)**16+- **Several cross-platform formats are silently incompatible**, any of which can cause recovery failure or data loss in a cross-device scenario: recovery words derive different keys on each platform, PeachScript is an entirely different container, the card `network` field is renamed (lost on sync), and non-BMP master passwords can fail to unlock across platforms. **(MF-1…MF-4)**17+- **Duress/plausible-deniability is materially weaker than the browser** (timing-distinguishable unlock, decoy keyed by a hardcoded sentinel, decoy existence detectable, slots not length-matched). For a feature whose entire purpose is deniability under coercion, these matter. **(MF-5, MF-6)**18+- **Autofill has no origin/app-trust validation and a loose substring domain matcher**, and the clipboard is never cleared and is not flagged sensitive on most copy paths. **(MF-7, MF-8)**19+20+Counts: **2 Critical, 8 Major, ~10 Minor.** A notable amount of the sync/pairing surface is **stubbed and throws at runtime**, so several sync-related risks are latent rather than live today (see MN-2). I would not ship this as a password manager until CF-1/CF-2 are fixed; the cross-platform parity breaks (MF-1…MF-4) should be resolved or explicitly documented as platform-local before any cross-device sync/recovery is advertised.21+22+---23+24+## Critical Findings25+26+### CF-1: Vault never auto-locks and does not lock on backgrounding27+**Severity:** Critical28+**Location:** `app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt` (no timer); `app/src/main/java/com/peachpasswords/vault/VaultRepository.kt:232` (`lock()`); `app/src/main/java/com/peachpasswords/vault/VaultSettings.kt:10` (`autoLockMinutes`); `app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt:164` (`setAutoLockMinutes`); `app/src/main/java/com/peachpasswords/PeachApplication.kt` (no lifecycle observer).29+**Description:** `autoLockMinutes` is written to settings and exposed in the UI (`SettingsCardBodies.kt:241-249`) but is read by nothing — there is no timer, no `postDelayed`, no `elapsedRealtime` tracking. There is also no lifecycle observer: grep for `ON_STOP`/`onStop`/`onPause`/`ProcessLifecycleOwner` finds no app-level hit. The vault key lives in the `@Singleton` `VaultRepository` and is cleared only by an explicit `lock()` call (which `lock()` does correctly — it zeroes `derivedKey` and `rootKey`, `VaultRepository.kt:232-244`).30+**Impact:** Once unlocked, the vault stays unlocked — key in memory, all entries decryptable, autofill/QS-tile/widget live — until the process is killed. Backgrounding the app, locking the device, and the configured auto-lock interval do nothing. The user-facing auto-lock setting is a false assurance. This is the single most damaging gap for a password manager.31+**Recommended fix:** Register a `DefaultLifecycleObserver` on `ProcessLifecycleOwner` that calls `vault.lock()` on `ON_STOP`, plus an idle timer honoring `autoLockMinutes`, reset on user interaction.32+33+### CF-2: No way to manually lock the vault from the UI (`lock()` is dead code)34+**Severity:** Critical35+**Location:** `app/src/main/java/com/peachpasswords/ui/vault/VaultListViewModel.kt:72` (`fun lock() = vault.lock()`, never invoked); `app/src/main/java/com/peachpasswords/ui/vault/VaultListScreen.kt:203` (TopBar exposes only Settings + Add).36+**Description:** `VaultListViewModel.lock()` is defined but never called anywhere in `app/src/main`. The vault-list top bar wires only `onSettings`/`onAdd`. There is no lock button anywhere.37+**Impact:** Combined with CF-1, the only events that ever lock the vault are `destroyVault()` (duress/panic) and process death. A user cannot deliberately lock their vault — e.g. before handing the phone to someone.38+**Recommended fix:** Wire a lock control into the top bar or settings calling `VaultListViewModel.lock()`.39+40+---41+42+## Major Findings43+44+### MF-1: Recovery words derive a different key on Android than the browser — escrow is not cross-platform recoverable45+**Severity:** Major46+**Location:** `vault/RecoveryWords.kt:76-91` (`wordKeyMaterial` = `BLAKE3(words.joinToString(" "))` → `deriveRecoveryKey`); browser `src/shared/recovery-words.ts:61-142` + `src/background/vault.ts:286,330` (`wordsToRootKeyMaterial` = reconstructed BIP39 entropy). Also: Android wraps the **entire slot-A payload** (`VaultRepository.kt:639-654`), the browser wraps **only the 32-byte root key** (`vault.ts:275-316`).47+**Description:** The HKDF salt and `info` label match (`"peach-recovery-v1"`), but the input keying material differs (BLAKE3 of the joined word strings vs. reconstructed BIP39 entropy) **and** the wrapped object differs (whole payload vs. root key). Two independent divergences, either of which breaks interop. On Android the root key is independently random (`VaultRepository.kt:117`) and unrelated to the displayed words, whereas in the browser the root key *is* the BIP39 entropy.48+**Impact:** Recovery words generated on Android cannot recover the vault in the browser and vice-versa. If a user is told "write these words down to recover on any device," that promise is false across platforms — a recovery-time data-loss risk. Within a single platform it works correctly.49+**Recommended fix:** If cross-platform recovery is a requirement, converge on the browser model (root key = BIP39 entropy; wrap only the root key; IKM = `wordsToRootKeyMaterial`). If Android recovery is intentionally platform-local, document it and never imply cross-device recovery.50+51+### MF-2: "PeachScript" is two completely different, incompatible formats52+**Severity:** Major53+**Location:** Browser `src/crypto/peachScript.ts` + `src/crypto/peachPayload.ts`; Android `ui/vault/PeachScriptExport.kt` / `PeachScriptImport.kt`.54+**Description:** Browser PeachScript = a binary envelope (magic `PCHS`, Argon2id, AES-256-GCM, **zstd** sections, BLAKE3 checksum, size-bucket padding, string-table entry packing) re-encoded into Private-Use-Area codepoints U+E000–U+E0FF. Android PeachScript = a JSON object `{"peachscript":1,"encrypted":true,"kdf":"argon2id","salt":…,"blob":…}` where `blob` = `nonce‖AES-256-GCM(plaintext-JSON entries)` under AAD `"peachscript_export_v1"`. They share no container, compression, checksum, entry packing, AAD, or encoding. The AAD `peachscript_export_v1` and the marker `"peachscript":1` **do not exist in the browser** (grep-confirmed). Android export also carries only 6 fields (title/username/password/url/notes/totp, `PeachScriptExport.kt:100-109`) — email folds into username; tags/card/passkey/breach/history/timestamps are dropped even within its own format.55+**Impact:** A browser-produced `.peach` backup cannot be imported on Android and vice-versa — a silent portability break for the format both products call "PeachScript." In a disaster-recovery scenario this is effective data loss. Each platform does round-trip with itself (`ExportRoundTripTest.kt:35-61`).56+**Recommended fix:** Pick one canonical PeachScript container. To match the browser, Android must implement the `peachPayload` binary envelope (PCHS, zstd, BLAKE3, string-table packing) plus PUA encode/decode. Until then, document the two formats as non-interoperable and rename one.57+58+### MF-3: Card `network` field renamed to `cardNetwork`; `last4` absent — silent card-data loss on sync59+**Severity:** Major60+**Location:** Browser `network` (`src/types/…` entry model; encoded at `peachPayload.ts:539` via `networkToByte(entry.network)`); Android `cardNetwork` (`vault/VaultEntry.kt:39`). Browser `last4` has no Android counterpart.61+**Description:** `kotlinx.serialization` keys on the Kotlin property name, so Android's `cardNetwork` will not map to the browser's `network` over any name-keyed sync/serialization channel. `last4` is simply missing on Android.62+**Impact:** Card network (and last4) are silently lost when a card entry round-trips browser↔Android.63+**Recommended fix:** Rename to `network` or add `@SerialName("network")`, and add `last4`.64+65+### MF-4: Non-BMP master passwords can derive different keys across platforms66+**Severity:** Major67+**Location:** Android `vault/VaultCrypto.kt:46` (`generator.generateBytes(password.toCharArray(), hash)`); browser `src/crypto/argon2.ts:12-21` (hash-wasm UTF-8 encodes the string).68+**Description:** All Argon2id parameters match exactly (m=65536, t=3, p=4, 32-byte out, 16-byte salt). The only divergence is input encoding: BouncyCastle's `char[]` path operates per-UTF-16 code unit, while hash-wasm UTF-8-encodes the full string. For BMP characters these agree; a password containing a non-BMP character (e.g. an emoji, a surrogate pair) can diverge.69+**Impact:** A vault created in the browser with a non-BMP master password may be unlockable only there (and vice-versa) — cross-platform unlock/restore failure for affected users. Same-platform use is unaffected. Rated Major (not Critical) because it was reasoned from BouncyCastle's documented behavior, not a runtime KAT.70+**Recommended fix:** Derive on explicit UTF-8 bytes on both sides (`password.toByteArray(Charsets.UTF_8)`), or document a master-password charset restriction. Add a shared cross-platform known-answer test vector.71+72+### MF-5: Duress vs. real unlock is timing-distinguishable on Android73+**Severity:** Major74+**Location:** `ui/lock/LockViewModel.kt:57-71`; `vault/DuressConfig.kt:105-119` (`verify`); `vault/VaultRepository.kt:132-160` (`unlock`).75+**Description:** On every unlock, `duress.verify(password)` runs first (one full Argon2id derivation against the duress salt); only on no-match does it fall through to `vault.unlock` (a second full Argon2id derivation against slot A). A real-password unlock therefore costs ~2× Argon2id; a duress-password unlock costs ~1× and returns immediately. The browser explicitly derives/decrypts both slots in parallel to keep wall-clock constant (`vault.ts:1067-1122`, comment "DUR-002").76+**Impact:** An observer who can time unlocks can distinguish "duress entered" from "real entered," partially defeating the deniability goal. Bounded by the noise of absolute Argon2id timing, but a real regression from the browser's stated threat model.77+**Recommended fix:** Derive both keys (and ideally attempt both decrypts) unconditionally and in parallel, then branch on results, so wall-clock time is password-independent.78+79+### MF-6: Duress/decoy architecture diverges from the browser and weakens deniability80+**Severity:** Major81+**Location:** `vault/VaultRepository.kt:21` (`DECOY_SENTINEL = "peach_decoy_v1"`), `:168-206` (`unlockDecoy`, no password, keyed by the sentinel), persisted to a distinctly-named `peach_vault_duress` pref (`VaultStore.kt:126-130,156`); browser stores the decoy as a real second slot (slot B) keyed by a user-chosen **duress passphrase**, tried in parallel at the same prompt (`vault.ts:993-1029, 1067-1169`).82+**Description:** The browser decoy is a genuine second vault keyed by a duress password, reached by typing that password at the normal prompt (constant-time, indistinguishable). Android's decoy is reached by an explicit no-secret `unlockDecoy()` path keyed by a hardcoded in-app constant, stored under a distinctly-named pref. There is no duress *passphrase*. The decoy key is independent of slot A (verified — it cannot derive or brute-force the real key), so the real vault is not endangered; the weakness is purely in deniability.83+**Impact:** (a) The `peach_vault_duress` pref's existence signals a decoy was configured. (b) The sentinel is a constant in the APK, so anyone can open the decoy without a secret. (c) No constant-time dual-slot unlock (compounds MF-5). A coerced user relying on plausible deniability gets materially less than the browser provides.84+**Recommended fix:** Port the browser's slot-B-under-duress-passphrase model (single prompt, parallel dual-slot decrypt, user-chosen decoy passphrase, length-matched slots). If a no-secret panic decoy is intentional product scope, document it and remove "plausible deniability"/"exact port" framing.85+86+### MF-7: Autofill performs no origin/app-trust validation and uses a loose substring domain matcher87+**Severity:** Major88+**Location:** `autofill/PeachAutofillService.kt:44-55`; `autofill/AutofillResponseBuilder.kt:27-47` (`matchEntries`); `autofill/AssistStructureParser.kt:47-49` (`webDomain` taken verbatim); browser reference `src/background/vault.ts:919-930,1927` (strict eTLD+1 bucket).89+**Description:** When unlocked, the service offers entries for any form: `matchEntries` partitions into hits/rest but returns `hits + rest` (then `.take(6)`), so non-matching entries are still surfaced; with a null/blank origin it returns **all** entries. The matcher itself is a substring test on a single host label (`coreLabel` → `hay.contains(core)`), looser and less correct than the browser's registrable-domain match — `core="github"` matches "GitHub Desktop" or any host containing "github". `webDomain` is trusted verbatim with no check that the providing package is a real browser and no Digital Asset Links validation for native apps.90+**Impact:** Wrong-site credentials surface in the picker; a malicious or spoofing app can elicit the picker for credentials it does not own (the classic Android autofill phishing vector). Mitigated by the fact that fill requires an explicit user tap (no silent fill), which is why this is Major rather than Critical.91+**Recommended fix:** Filter strictly to `extractDomain(entry.url) == extractDomain(origin)` (PSL already available via `DomainUtils`); when nothing matches, show only the picker. Validate `webDomain`-providing packages against a trusted-browser allowlist; verify native apps via Digital Asset Links.92+93+### MF-8: Clipboard is never cleared and is not flagged sensitive on in-app copy paths94+**Severity:** Major95+**Location:** Copy sites with no clear and no sensitive flag — `EntryDetailViewModel.kt:74-75`, `EntryEditViewModel.kt:144-145,154-155`, `VaultListViewModel.kt:129-130,144-145`, `RecoveryWordsScreen.kt:166-167`, `ExportScreen.kt:310-311`. Only `qs/PeachTileService.kt:67-74` sets `android.content.extra.IS_SENSITIVE`. The `CopyButton.kt:32-77` "drain" is a cosmetic animation only.96+**Description:** Passwords, TOTP codes, recovery words, and full vault-backup blobs are written via `ClipData.newPlainText(...)` with no auto-clear timer and (except the QS tile) without the Android-12+ `IS_SENSITIVE` flag.97+**Impact:** Secrets persist on the system clipboard indefinitely, readable by any clipboard-capable app and shown in the OS clipboard preview/history. A copied recovery phrase or backup blob is high value.98+**Recommended fix:** Set `IS_SENSITIVE` on every sensitive `ClipData`; schedule a clear/overwrite after a short timeout (mirror the browser's clipboard-clear behavior).99+100+---101+102+## Minor Findings103+104+### MN-1: Vault plaintext is not padded — slot-A ciphertext length leaks vault size105+**Severity:** Minor (Major in the duress threat model)106+**Location:** `VaultRepository.kt:729-766` (`sealSlotA`/`persistSlotA` encrypt with no padding); padding helpers exist but are unused — `VaultCrypto.kt:80-89` (`padToBucket`/`padToBlock`), `:78` (`generateNoise`); browser `vault.ts:51` (`PAD_BLOCK=1024`), `:647-654` (`padPlaintext`), `:67,1012` (`DURESS_SLOT_SIZE` ceiling).107+**Description:** The browser pads every slot-A plaintext to the next 1 KiB block, and to a fixed 256 KiB ceiling for both slots when duress is configured (so the slots are length-identical). Android applies no padding; slot A grows/shrinks with exact plaintext length. Slot B is roughly size-matched (`writeMatchingNoiseSlotB`, `:736`) but slot A is not bucketed.108+**Impact:** An attacker with at-rest access can estimate stored-secret count/size from ciphertext length; combined with MF-6 it further erodes duress indistinguishability. Not data loss, not a crypto break.109+**Recommended fix:** Apply `padToBlock` (and the duress ceiling when configured) in `sealSlotA`/`persistSlotA`, matching the browser.110+111+### MN-2: Acoustic pairing codec and pairing-UI entry points are stubs that throw at runtime112+**Severity:** Minor (but functionally significant)113+**Location:** `sync/Ggwave.kt:37-41` (`createChirpCodec` throws `UnsupportedOperationException`); `ui/pairing/ChirpPairViewModel.kt:115-118,128,130,132` (`completePairing` no-op, `getLocalSubnet` returns null, `openPairingTransport`/`openPairingServer` throw).114+**Description:** The Noise NK/XX handshakes, `ChirpSyncTransport`, `MdnsPairingServer`, and the per-entry sync envelope are fully implemented and unit-tested (see Clean Findings), but the **acoustic codec and the pairing view-model entry points are stubbed**. The user-facing pairing/sync flow therefore cannot complete at runtime today.115+**Impact:** Sync/pairing is non-functional in production. This is not a security hole (no half-built crypto path is reachable), and it means the sync-related data-loss and validation risks below are **latent**, not live. Worth surfacing prominently because the crypto audit otherwise reads as if sync ships.116+**Recommended fix:** Gate the pairing UI behind a feature flag until the native codec + transport land, or remove the entry points.117+118+### MN-3: Incoming sync entries are not validated/sanitized before persisting (latent — sync is stubbed)119+**Severity:** Minor (would be Major once sync is live)120+**Location:** `sync/VaultSyncAdapter.kt:64-77`; `vault/VaultRepository.kt:465-499` (`applyMergedRemoteEntries`); browser `vault.ts:1534,1855-1856` (`sanitizeRestoredEntry`), `chirp-sync-vault-adapter.ts:298-321`.121+**Description:** The browser runs every incoming remote entry through `sanitizeRestoredEntry` (rejects empty title, login lacking password, passkey missing `credentialId`; migrates legacy shapes) and validates `typeof id === "string"`. Android trusts whatever `kotlinx.serialization` decodes; the id-binding check (`entry.id == id`, `VaultSyncAdapter.kt:71`) protects routing but not content. A malicious paired device (already sharing the root key) could push malformed entries or an unbounded `passwordHistory` (no re-cap on merge).122+**Impact:** Divergent/garbage vault state from a trusted-but-compromised peer. Requires an already-paired device, and sync is currently stubbed, so latent.123+**Recommended fix:** Port `sanitizeRestoredEntry` checks and re-cap `passwordHistory` to `PASSWORD_HISTORY_MAX` on merge.124+125+### MN-4: No cross-platform byte-vector test pins the Noise handshake or key derivations126+**Severity:** Minor127+**Location:** `app/src/test/java/com/peachpasswords/sync/C7ChirpTransportTest.kt:93-177` (initiator/responder agree only with each other); browser `src/shared/noise-js.test.ts:42-51` (pins only the HMAC auth proof, which Android does not implement).128+**Description:** Neither side pins the actual Noise NK/XX transcript (message bytes, transport keys, `handshakeHash`), nor the derived X25519/Ed25519 public keys, against a fixed vector shared across platforms. A subtle divergence (HKDF info/salt, nonce endianness, BLAKE2s personalization, key-split order, stablelib-vs-BouncyCastle public-key derivation) would not be caught and would wedge all cross-platform pairing silently.129+**Recommended fix:** Add fixed-ephemeral-key and fixed-seed vector tests on both platforms; make `generateKeyPair()` injectable for the test (`NoiseNK.kt:64`, `NoiseXX.kt:66`).130+131+### MN-5: Hand-rolled JSON parser in pairing-frame decode can diverge from `JSON.parse`132+**Severity:** Minor133+**Location:** `sync/ChirpPairing.kt:530-628` (`decodePairingFrame`/`simpleJsonObject`); browser `src/shared/chirp-handshake.ts:67-85` (`JSON.parse`).134+**Description:** Android's custom parser does not unescape string escapes in values and assumes flat fields. Key-bearing fields are hex-regex-validated (`:544-551`), so no key confusion — but a browser peer whose `device_name` contains a quote/backslash/Unicode escape would parse incorrectly or throw on Android.135+**Recommended fix:** Use `kotlinx.serialization`'s JSON parser (already a dependency).136+137+### MN-6: FLAG_SECURE not applied per-screen on several secret-bearing screens; absent entirely in debug builds138+**Severity:** Minor139+**Location:** Activity-wide release-only flag at `MainActivity.kt:52-57` (`if (!BuildConfig.DEBUG)`); per-screen flags only on `EntryDetailScreen.kt:100-101` and `NotesModeScreen.kt:81-82`. No per-screen flag on `RecoveryWordsScreen.kt`, `RecoveryWordEntryScreen.kt`, `ExportScreen.kt`, `CodexGenerateScreen.kt`, `CodexRestoreScreen.kt`, `LockScreen.kt`, `VaultListScreen.kt`.140+**Description:** Release builds get window-wide FLAG_SECURE (covers all screens); debug builds skip it, leaving recovery words / export / codex backup screenshottable in QA builds and reliant on a single activity-wide flag.141+**Recommended fix:** Keep FLAG_SECURE on in debug too, or add per-screen `DisposableEffect` flags to the secret-bearing screens as defense-in-depth.142+143+### MN-7: Autofill picker activity is not FLAG_SECURE144+**Severity:** Minor145+**Location:** `MainActivity.kt:54-55` (main window secure); `autofill/AutofillEntryPickerActivity.kt` (referenced at `PeachAutofillService.kt:84`) sets no FLAG_SECURE.146+**Description:** The picker that lists/decrypts vault entries during autofill can be screenshotted/recorded.147+**Recommended fix:** Set FLAG_SECURE on the picker activity window.148+149+### MN-8: Settings stored in cleartext SharedPreferences (metadata only)150+**Severity:** Minor151+**Location:** `vault/VaultStore.kt:114,140-144` (`peach_vault_store` / `peach_settings`).152+**Description:** Vault slots are AES-GCM ciphertext (correct), but `VaultSettings` (theme, accent, `autoLockMinutes`, `trashRetentionDays`, duress-configured flag) is plaintext JSON. No secrets, but configuration metadata is readable on a rooted/backup-extracted device. `allowBackup="false"` limits exposure.153+**Recommended fix:** Optional — move settings into the encrypted payload or `EncryptedSharedPreferences` (the dependency is already present).154+155+### MN-9: Decoy session can surface recovery words / sync master key156+**Severity:** Minor157+**Location:** `VaultRepository.kt:178,196-197` (decoy mints/loads a root key); `ui/vault/RecoveryWordsScreen.kt:65-66` derives words from `syncMasterKey()`. Browser keeps `rootKey` null in decoy unlock and throws on recovery-word access (`vault.ts:533-536,1146-1157`).158+**Description:** In decoy mode the UI can still present recovery words for the decoy's throwaway root key. No key leak, but it could confuse the deniability story (a coerced user shown "your recovery words" for the decoy).159+**Recommended fix:** Gate recovery-word display and sync-master-key access on `!decoyMode`.160+161+### MN-10: Minor robustness / dead-code items162+**Severity:** Minor163+- `ui/lock/BiometricUnlockActivity.kt:6-11` — dead stub that `finish()`es in `onCreate`; remove or document.164+- `sync/MdnsPairingServer.kt:175,177` and `sync/PairingDiscoveryClient.kt:59,72` — mDNS registration/resolve failures swallowed as empty no-ops (silent failure on multicast-blocked networks; moot while transport stubbed).165+- `PeachAppNavHost.kt:113-117` — `SettingsProtection`/`SettingsVault`/`SettingsSync`/`SettingsAppearance`/`SettingsPro` route to `SimpleStub` placeholders (`PlaceholderScreens.kt:118-120`).166+- `feedback/FeedbackRepository.kt:36,58-61` — feedback endpoint is empty-string; `submit()` returns success without sending (intentional no-op, matches browser contract; blank message throws `message_empty`).167+- REPLACE import has no empty-set guard the browser has (`ImportScreen.kt:204` vs `vault.ts:1480-1482`); currently UI-unreachable. Import is also per-entry writes (N commits + N version bumps) rather than one batch.168+- Import MERGE does **no** deduplication (every row → new UUID); re-importing duplicates entries but **can never silently overwrite** an existing password — the audit's specific concern is a clean NO (`ImportScreen.kt:209-225`).169+170+---171+172+## Browser Parity Matrix173+174+| Feature | Browser | Android | Status | Notes |175+|---|---|---|---|---|176+| Entry core fields (id/title/username/email/password/url/additionalUrls/totp/notes/tags) | present | present, same names | ✅ | `VaultEntry.kt:9-26` |177+| `modifiedAt` / `deletedAt` / `breach` / `passwordChangedAt` | present | present | ✅ | `VaultEntry.kt:20-27` |178+| `passwordHistory` shape (`password`+`changedAt`) | present | present | ✅ | `VaultEntry.kt:23`, `PasswordHistoryItem.kt` |179+| Card `network` | `network` | `cardNetwork` | ❌ | Name mismatch → lost on sync (MF-3) |180+| Card `last4` | present | absent | ⚠ | Missing on Android (MF-3) |181+| Card month/year/cvc/holder/nickname | present | present | ✅ | `VaultEntry.kt:32-37` |182+| Passkey storage | nested `passkey` object | flat fields | ⚠ | Flat→nested mapping on export unverified (MN) |183+| `type` enum values | login/note/passkey/card | login/note/card (String) | ✅ | Values align |184+| `isWeak`/`isReused`/favicon | computed, not stored | computed, not stored | ✅ | Parity |185+| TOTP algorithm / hash / period / digits / time source | RFC 6238, SHA1/256/512, 30s, 6 | identical | ✅ | `TOTPGenerator.kt`; RFC vectors pass (`TOTPGeneratorTest.kt:13-15`) |186+| Autofill domain matching | strict eTLD+1 | loose substring on one label | ❌ | MF-7 |187+| Autofill TOTP freshness | n/a | code generated at fill time | ✅ | `AutofillResponseBuilder.kt:94` |188+| Autofill app/origin trust | registrable-domain bucket | none | ❌ | MF-7 |189+| PeachScript container | PCHS binary + zstd + BLAKE3 + PUA | JSON + AES-GCM | ❌ | Incompatible (MF-2) |190+| PeachScript AAD `peachscript_export_v1` | not present | present | ❌ | Browser uses no such AAD (MF-2) |191+| Codex GF(2⁸) poly / RS shard counts / deflate / Aztec ECL / 6×6 grid | reed-solomon WASM, pako L9, ZXing 25% | poly 0x11d, Deflater BEST, ZXing 25% | ✅ | `ReedSolomon.kt`, `CodexCodec.kt`, `CodexTypes.kt` |192+| Codex cross-platform paper restore | — | — | ⚠ | Structurally compatible; no cross-platform parity-byte fixture (MN-4 class) |193+| Noise NK/XX patterns, suite, hash, nonce, AAD, key-split | as spec | byte-equivalent | ✅ | `NoiseNK.kt`, `NoiseXX.kt` |194+| SAS derivation | first 4 bytes BE mod 1e6 pad6 | identical | ✅ | `SASDerivation.kt` (Android also user-gates it) |195+| `computeVaultId` / sync-identity / signing-key derivation | BLAKE3 + HKDF-SHA256 | identical inputs | ✅ | `SyncIdentity.kt:19-49` |196+| Chirp on-air payload (magic/offsets/CRC32) | defined | byte-identical | ✅ | `ChirpPayload.kt` |197+| Recovery escrow IKM + wrap target | entropy / root key | BLAKE3(words) / whole payload | ❌ | Not cross-recoverable (MF-1) |198+| Per-entry sync HKDF envelope | HKDF-SHA256, info `id+"sync-entry-v1"`, AAD `peach-sync-entry-v1` | identical | ✅ | `VaultSyncAdapter.kt:89-123` |199+| Conflict resolution | LWW by `modifiedAt`, tombstone-guarded | identical | ✅ | `VaultRepository.kt:474-491` |200+| Acoustic pairing / sync end-to-end | implemented | codec + UI stubbed (throws) | ❌ | Non-functional at runtime (MN-2) |201+202+---203+204+## Crypto Correctness Matrix205+206+| Operation | Parameter | Browser Value | Android Value | Match? |207+|---|---|---|---|---|208+| Vault KDF | Algorithm | Argon2id (`argon2.ts:12`) | Argon2id (`VaultCrypto.kt:38`) | ✅ |209+| Vault KDF | Memory | 65536 KiB | 65536 KiB (`VaultCrypto.kt:11`) | ✅ |210+| Vault KDF | Iterations | 3 | 3 (`VaultCrypto.kt:12`) | ✅ |211+| Vault KDF | Parallelism | 4 | 4 (`VaultCrypto.kt:13`) | ✅ |212+| Vault KDF | Output / salt length | 32 / 16 | 32 / 16 (`VaultCrypto.kt:14-15`) | ✅ |213+| Vault KDF | Password encoding | UTF-8 (hash-wasm) | `char[]`/UTF-16 (`VaultCrypto.kt:46`) | ⚠ BMP-only parity; non-BMP diverges (MF-4) |214+| Vault cipher | Algorithm / nonce / tag | AES-256-GCM / 12B CSPRNG / 128b | AES-256-GCM / 12B `SecureRandom` / 128b (`VaultCrypto.kt:51-59`) | ✅ |215+| Vault cipher | At-rest layout | nonce/ct/tag fields | `nonce‖ct‖tag` base64 | ⚠ equivalent bytes, different serialization (not a defect) |216+| Vault AAD | slot A | `slot_a_v1` | `slot_a_v1` (`VaultCrypto.kt:24`) | ✅ |217+| Vault AAD | slot B | `slot_b_v1` (`vault.ts:1013`) | decoy uses `slot_a_v1` (`VaultRepository.kt:182`) | ❌ architectural divergence (MF-6) |218+| Vault AAD | recovery escrow | `[1]` byte, wraps root key | `recovery_escrow_v1`, wraps payload | ❌ different AAD + wrapped object (MF-1) |219+| Plaintext padding | block / duress ceiling | 1024 / 262144 | none / none | ❌ (MN-1) |220+| Key zeroing | derived + root key on lock | zeroed | zeroed (`VaultRepository.kt:232-244`) | ✅ |221+| Recovery KDF | algorithm / info / salt | HKDF-SHA256 / `peach-recovery-v1` / 16B | identical (`RecoveryWords.kt:86-87`) | ✅ (IKM differs — MF-1) |222+| Sync envelope | KDF / salt / info / len / AAD / scope | HKDF-SHA256 / empty / `id+sync-entry-v1` / 32 / `peach-sync-entry-v1` / per-entry | identical (`VaultSyncAdapter.kt:89-123`) | ✅ |223+| Sync identity | X25519 / signing HKDF salts | `peach-sync-identity-v1` / `peach-sync-signing-v1` | identical (`SyncIdentity.kt:19-20`) | ✅ |224+| vault_id | BLAKE3(master‖"peach-vault-id") 64 hex | — | identical (`SyncIdentity.kt:32-40`) | ✅ |225+| Noise | suite / hash / nonce LE@offset4 / AAD=`h` | ChaCha20-Poly1305 / BLAKE2s / yes / yes | identical (`NoiseNK.kt`, `NoiseXX.kt`) | ✅ |226+| Pairing SAS | first 4 bytes BE mod 1e6 pad6 | — | identical (`SASDerivation.kt`) | ✅ |227+| Biometric escrow | HW key, auth-required, invalidate-on-enroll | n/a (platform) | yes (`BiometricKeyStore.kt:107-115`) | ✅ |228+| Duress hash | independent Argon2id salt, hash-only, constant-time compare | n/a | yes (`DuressConfig.kt:85-129`) | ✅ |229+230+---231+232+## Test Coverage Summary233+234+91 `@Test` methods across 14 files in `app/src/test`; no instrumented tests under `app/src/androidTest`. Tests use the real `VaultCrypto` (not mocked) plus a hand-rolled `FakeStorage`; sync tests use all-zero Noise keys (`ByteArray(32)`) — acceptable for protocol-shape tests, not real KATs.235+236+| Module | Tests | Coverage gaps |237+|---|---|---|238+| vault/VaultRepository | 23 | Solid: CRUD, LWW merge, duress decoy, rollback, retention. |239+| vault/RecoveryEscrow | 6 | Seal/recover round-trip incl. all-"abandon" phrase (genuine regression test, `RecoveryEscrowTest.kt:117-128`). |240+| vault/TOTPGenerator | 4 | Canonical RFC 6238 vectors. |241+| vault/PasswordGenerator | 4 | OK. |242+| **vault/VaultCrypto** | **0** | **No direct test** — Argon2id params, AES-GCM, AAD-mismatch rejection, nonce uniqueness, `zero()` exercised only indirectly. No KATs. |243+| **vault/VaultHealth** | **0** | Breach/reuse/aged/weak scoring untested. |244+| **ui/lock/BiometricKeyStore** | **0** | Wrap/unwrap + invalidation path untested (needs instrumented test). |245+| **vault/DuressConfig** | **0** | Duress verify/timing untested at unit level. |246+| codex/CodexCodec | 4 | Round-trip; RS/Aztec error-correction edges not separately tested; no cross-platform parity-byte fixture. |247+| autofill/AutofillMatch | 3 | Ranking only; no origin-trust/anti-phishing test. |248+| sync/* (5 files) | 24 | Protocol shape with fakes; real ggwave codec stubbed; no cross-platform byte vectors. |249+| ui/security/PasswordStrength | 11 | Good. |250+| ui/vault/ExportRoundTrip, ImportParsers | 13 | Same-platform round-trip + parsers. |251+252+Largest gaps: the core crypto primitive (`VaultCrypto`), `VaultHealth`, `BiometricKeyStore`, and duress verification have **no** direct tests; no cross-platform interop vectors exist anywhere.253+254+---255+256+## Dependency Inventory257+258+From `app/build.gradle` (Compose via BOM `2024.06.00`; no `libs.versions.toml`). All versions **pinned** (no floating ranges).259+260+| Library | Version | Purpose | Sensitive? | Pinned? |261+|---|---|---|---|---|262+| org.bouncycastle:bcprov-jdk18on | 1.78.1 | Argon2id KDF, X25519/Ed25519, ChaCha20-Poly1305 | **Yes** | Yes |263+| com.google.crypto.tink:tink-android | 1.13.0 | Crypto primitives (present; `VaultCrypto` uses JCE directly — possibly unused) | **Yes** | Yes |264+| androidx.security:security-crypto | 1.1.0-**alpha06** | EncryptedSharedPreferences | **Yes** | Yes (alpha — churn risk) |265+| androidx.biometric:biometric | 1.1.0 | BiometricPrompt | **Yes** | Yes |266+| androidx.credentials:credentials (+ play-services-auth) | 1.5.0 | Passkey/credential provider | **Yes** | Yes |267+| com.squareup.okhttp3:okhttp | 4.12.0 | Feedback HTTP (endpoint empty) | Indirect | Yes |268+| com.google.zxing:core | 3.5.3 | Codex/Aztec encode-decode | Indirect | Yes |269+| androidx.camera:camera-* | 1.3.4 | Codex restore camera | Indirect | Yes |270+| org.jetbrains.kotlinx:kotlinx-serialization-json | 1.7.1 | Vault payload / settings codec | Indirect | Yes |271+| org.jetbrains.kotlinx:kotlinx-coroutines-android | 1.8.1 | Concurrency | No | Yes |272+| com.google.dagger:hilt-android (+compiler) | 2.51.1 | DI | No | Yes |273+| androidx.glance:glance-appwidget / -material3 | 1.1.0 | Widgets | Indirect | Yes |274+| androidx.autofill:autofill | 1.1.0 | Inline autofill UI | Indirect | Yes |275+| androidx.navigation:navigation-compose | 2.8.0 | Navigation | No | Yes |276+| androidx.lifecycle:lifecycle-* | 2.8.4 | Lifecycle/VM | No | Yes |277+| androidx.activity:activity-compose | 1.9.2 | Compose host | No | Yes |278+| androidx.appcompat:appcompat / core-ktx / core-splashscreen | 1.7.0 / 1.13.1 / 1.0.1 | Compat/core | No | Yes |279+| com.google.android.material:material | 1.12.0 | Material views | No | Yes |280+| Compose (material3/ui/foundation/icons) | BOM 2024.06.00 | UI | No | Yes |281+282+Notes: `security-crypto` is an **alpha** in a security-critical role (deliberately pinned; alpha API can churn). `tink-android` appears unused (`VaultCrypto` uses JCE + BouncyCastle) — confirm and drop if dead weight. No SBOM/lockfile. The browser uses different libraries for equivalent functions (hash-wasm Argon2, stablelib Noise/X25519, pako deflate, reed-solomon-erasure WASM, otpauth) — equivalence is verified at the parameter level above, but the implementation mismatch is exactly why the cross-platform byte-vector tests in MN-4 are needed.283+284+---285+286+## Clean Findings (explicitly verified correct)287+288+**Cryptographic primitives**289+- Argon2id parameters identical across platforms: m=65536 KiB, t=3, p=4, 32-byte output, 16-byte CSPRNG salt (`VaultCrypto.kt:11-15,37-48`).290+- AES-256-GCM with fresh 96-bit `SecureRandom` nonce per encrypt and 128-bit tag, on both vault and sync envelopes (`VaultCrypto.kt:51`, `VaultSyncAdapter.kt:98`).291+- Distinct AAD constants per blob type (`AAD_SLOT_A`/`AAD_SLOT_B`/`AAD_ROOT_KEY`/`AAD_RECOVERY`, `VaultCrypto.kt:24-32`); a recovery-escrow blob cannot be presented as slot A (GCM-enforced).292+- Slot-A AAD (`slot_a_v1`) byte-identical to the browser.293+- Per-entry sync HKDF envelope is byte-for-byte parity (KDF, empty salt, info, 32-byte key, AAD, per-entry scope) **and** id-bound — a swapped envelope is rejected (`VaultSyncAdapter.kt:69-71`).294+- Sync-identity HKDF salts/info, `computeVaultId` BLAKE3 derivation, and SAS derivation all match exactly.295+- Noise NK and XX message patterns, cipher suite (ChaCha20-Poly1305), hash (BLAKE2s), HKDF (SHA-256), nonce encoding, AAD usage, and transport-key/role split are byte-equivalent to the browser; ephemeral keys are fresh per handshake (no static-key reuse). The C7 transport uses the real `noiseNKResponder`/`noiseXXInitiator`, not stubs. Android additionally wires the SAS into a user-confirmation gate (stronger than the browser, where SAS is documented as not-yet-surfaced).296+- Chirp on-air payload (magic `PEAC`, version, device-type range, 32B pubkey, 16B nonce, CRC32-IEEE) is byte-identical — cross-platform decodable.297+- Codex: GF(2⁸) poly 0x11d with Vandermonde-made-systematic matrix, RS shard counts, zlib deflate (mutually inflatable), ZXing Aztec at 25% ECC, 6×6=36 codes/page, and the envelope JSON schema all match.298+299+**Key-material lifecycle**300+- `lock()` zeroes both `derivedKey` and `rootKey` and nulls them (`VaultRepository.kt:232-244`) — the in-memory key *is* cleared when `lock()` is called (the problem is that it is rarely called — see CF-1/CF-2).301+- Sync/codex/recovery/change-password paths zero master/material/key copies in `finally` blocks; wrong-password paths zero the trial key (`VaultRepository.kt:142,566-573,611,650-651`).302+- `currentVaultKey()` returns a copy (`copyOf()`, `:263`), zeroed at its call sites.303+- Biometric escrow: hardware-backed AndroidKeyStore AES-256-GCM key, `setUserAuthenticationRequired(true)` with `AUTH_BIOMETRIC_STRONG`, `setInvalidatedByBiometricEnrollment(true)`; on `KeyPermanentlyInvalidatedException` the wrapped blob is cleared before password fallback (`BiometricKeyStore.kt:62-115`). Wrapped blob + IV in plain prefs is safe (ciphertext under a key that never leaves secure hardware).304+- No secret-bearing logging anywhere: the only `Log` call in the tree is a clock-skew timestamp (`ChirpSyncCoordinator.kt:275`); no `println`/`printStackTrace`. No empty catch blocks in `app/src/main`.305+- Vault slots in plain `SharedPreferences` is acceptable and matches the browser model — the blob is already AES-GCM-sealed; only the salt is cleartext. License and paired-device stores correctly use `EncryptedSharedPreferences`.306+307+**Data integrity**308+- Soft-delete is the only normal delete path; hard delete (`purgeEntry`/`purgeDeletedEntries`) is reachable only from Trash behind a confirm overlay (`TrashScreen.kt:148-163`).309+- Trash retention defaults to "Never" (`null`), **not** 30 days, matching the deliberate CONTINUITY decision; tested both ways (`VaultSettings.kt:14`, `VaultRepositoryTest.kt:239-249`).310+- Panic/`destroyVault` is guarded by 3 confirmations + a typed "DESTROY", wipes both slots, and preserves the Pro license (separate prefs file). Duress DESTROY and Panic converge on the same `destroyVault()` (`PanicScreen.kt`, `VaultRepository.kt:302-306`).311+- Password history captured **before** the new password is applied, newest-first, age-stamped, deduped on identical resave, capped at 50 (`VaultRepository.kt:340-355`); survives sync as a serialized field.312+- Vault write keeps the **real** vault readable on crash: slot A is committed first and fully and decrypts independently of slot B; `persistOrRollback` restores in-memory state on disk-write failure (`VaultRepository.kt:751-780`). (The two-slot write is non-atomic, but this matches the browser and only affects the decoy size-match — see MN-1.)313+- Schema migration is forward-compatible: `ignoreUnknownKeys = true`, decrypt does not gate on `version`, `recoveryEscrow` and `rootKeyB64` are nullable/back-filled, so a v2.0.x vault opens on v2.1.x+ and lazily gains a root key (`VaultStore.kt:73`, `VaultRepository.kt:716-723`).314+- Import never silently overwrites an existing entry's password — every imported row gets a fresh UUID (`ImportScreen.kt:212-224`).315+316+**Concurrency / network / surface**317+- `VaultRepository` serializes all mutating + unlock ops under a `Mutex` (`VaultRepository.kt:51`).318+- QS tile checks `isUnlocked` before copying; locked → launches app, never copies (`PeachTileService.kt:36-49`).319+- All exported manifest components are permission-gated: autofill (`BIND_AUTOFILL_SERVICE`), credential provider (`BIND_CREDENTIAL_PROVIDER_SERVICE`), QS tile (`BIND_QUICK_SETTINGS_TILE`); `BiometricUnlockActivity` and `AutofillEntryPickerActivity` are `exported="false"`; widget receivers use the standard system-only `APPWIDGET_UPDATE` pattern. `allowBackup="false"` + `fullBackupContent="false"`.320+- **No HIBP/online breach check exists** — `VaultHealth.isBreach` reads a pre-existing `entry.breach` field; SHA-256 is used only for *local* reuse detection; the only network call is the (empty) feedback endpoint. So the brief's k-anonymity concern is moot: **no password hash or plaintext is ever sent anywhere.** This is good for privacy, but note it also means the "breach" indicator is only as fresh as whatever populated the field (likely set during browser sync) — flagged as a feature-parity observation, not a defect.321+322+---323+324+## Residual Uncertainty (flagged honestly)325+326+- **MF-4 (non-BMP passwords)** was reasoned from BouncyCastle's documented `char[]`→UTF-8 behavior, not a runtime KAT. A shared test vector would settle it definitively; until then treat as Major-probable, not confirmed.327+- **MF-5 timing magnitudes** were derived from control flow (sequential two-derivation path), not measured. The structural finding is high-confidence; the exploitability depends on observable timing resolution.328+- **X25519/Ed25519 public-key determinism** across stablelib (browser) vs BouncyCastle (Android) is byte-identical by spec but is not pinned by any test (subsumed by MN-4).329+- **Passkey flat→nested mapping** on cross-platform export was not exercised; Android stores flat passkey fields while the browser's canonical shape is a nested `passkey` object — confirm before relying on cross-platform passkey portability.330+- The biometric key copy is **not** zeroed if the prompt is dismissed without firing any callback (e.g. process death mid-prompt) — minor, GC-reachable only, unverified whether the platform guarantees a callback.