Modern Apps git

← Modern-Apps.git

securemail: websocket-first PGP mail app + native OpenPGP in e2ee-p2p

Commit
f26a9ffa0193ce237202fe56fc6a588e8b73fc2e
Author
vayun-mathur <[email protected]>
When
2026-10-23 19:35 UTC (1 month ago)
Parents
8a73008

Diff

.github/ISSUE_TEMPLATE/bug_report.yml
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 06a81f5b85..22ced00fbf 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -56,6 +56,7 @@ body:         - screentime         - setupwizard         - share+        - securemail         - solitaire         - speech         - sudoku
.github/ISSUE_TEMPLATE/feature_request.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 29ea123f3c..799d591177 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -56,6 +56,7 @@ body:         - screentime         - setupwizard         - share+        - securemail         - solitaire         - speech         - sudoku
.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex 8b4e771136..0650bac276 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs:              if (match && match[1]) {               const selectedApp = match[1].trim().toLowerCase();-              const validApps = ['appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'emergency', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'kart', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'todo', 'translate', 'travel', 'tuner', 'unblockjam', 'uniflix', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+              const validApps = ['appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'emergency', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'kart', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'securemail', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'todo', 'translate', 'travel', 'tuner', 'unblockjam', 'uniflix', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];                if (validApps.includes(selectedApp)) {                 await github.rest.issues.addLabels({
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 5431000ae3..4f79951be2 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -65,6 +65,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [+ "bytes",  "crypto-common 0.1.7",  "generic-array", ]@@ -144,6 +145,15 @@ dependencies = [  "polyval 0.7.3", ] +[[package]]+name = "aes-kw"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69fa2b352dcefb5f7f3a5fb840e02665d311d878955380515e4fd50095dd3d8c"+dependencies = [+ "aes 0.8.4",+]+ [[package]] name = "ahash" version = "0.8.12"@@ -284,6 +294,19 @@ dependencies = [  "derive_arbitrary", ] +[[package]]+name = "argon2"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"+dependencies = [+ "base64ct",+ "blake2 0.10.6",+ "cpufeatures 0.2.17",+ "password-hash",+ "zeroize",+]+ [[package]] name = "array_ref" version = "0.1.0"@@ -387,6 +410,27 @@ dependencies = [  "syn 2.0.119", ] +[[package]]+name = "bitfields"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef6e59298da389bc0649c7463856b34c6e17fe542f88939426ede4436c6b1195"+dependencies = [+ "bitfields-impl",+]++[[package]]+name = "bitfields-impl"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2c044f98f86f15414668d6c8187c7e4fadab1ad2b31680f648703e0fe07c555"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "thiserror 2.0.21",+]+ [[package]] name = "bitflags" version = "1.3.2"@@ -402,6 +446,27 @@ dependencies = [  "serde_core", ] +[[package]]+name = "bitvec"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"+dependencies = [+ "funty",+ "radium",+ "tap",+ "wyz",+]++[[package]]+name = "blake2"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"+dependencies = [+ "digest 0.10.7",+]+ [[package]] name = "blake2" version = "0.11.0"@@ -445,6 +510,15 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e2211b0817f061502a8dd9f11a37e879e79763e3c698d2418cf824d8cb2f21e" +[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array",+]+ [[package]] name = "block-padding" version = "0.4.2"@@ -454,6 +528,16 @@ dependencies = [  "hybrid-array", ] +[[package]]+name = "blowfish"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7"+dependencies = [+ "byteorder",+ "cipher 0.4.4",+]+ [[package]] name = "brotli" version = "8.0.4"@@ -475,6 +559,15 @@ dependencies = [  "alloc-stdlib", ] +[[package]]+name = "buffer-redux"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "431a9cc8d7efa49bc326729264537f5e60affce816c66edf434350778c9f4f54"+dependencies = [+ "memchr",+]+ [[package]] name = "bumpalo" version = "3.20.3"@@ -519,6 +612,25 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]]+name = "bzip2"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"+dependencies = [+ "libbz2-rs-sys",+]++[[package]]+name = "camellia"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3264e2574e9ef2b53ce6f536dea83a69ac0bc600b762d1523ff83fe07230ce30"+dependencies = [+ "byteorder",+ "cipher 0.4.4",+]+ [[package]] name = "camera_stitch" version = "0.1.0"@@ -535,6 +647,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" +[[package]]+name = "cast5"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26b07d673db1ccf000e90f54b819db9e75a8348d6eb056e9b8ab53231b7a9911"+dependencies = [+ "cipher 0.4.4",+]+ [[package]] name = "cbc" version = "0.2.1"@@ -564,6 +685,15 @@ dependencies = [  "nom 7.1.3", ] +[[package]]+name = "cfb-mode"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "738b8d467867f80a71351933f70461f5b56f24d5c93e0cf216e59229c968d330"+dependencies = [+ "cipher 0.4.4",+]+ [[package]] name = "cfg-if" version = "1.0.5"@@ -730,6 +860,17 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]]+name = "cmac"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8543454e3c3f5126effff9cd44d562af4e31fb8ce1cc0d3dcd8f084515dbc1aa"+dependencies = [+ "cipher 0.4.4",+ "dbl",+ "digest 0.10.7",+]+ [[package]] name = "cmov" version = "0.5.4"@@ -791,7 +932,7 @@ dependencies = [  "openmls_memory_storage",  "openmls_rust_crypto",  "openmls_traits",- "rand",+ "rand 0.10.3",  "rand_core 0.10.1",  "tls_codec", ]@@ -804,7 +945,7 @@ dependencies = [  "curve25519-dalek 5.0.0",  "hmac 0.13.0",  "jni",- "rand",+ "rand 0.10.3",  "rand_core 0.10.1",  "sha2 0.11.1",  "subtle",@@ -838,6 +979,15 @@ dependencies = [  "rustversion", ] +[[package]]+name = "convert_case"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"+dependencies = [+ "unicode-segmentation",+]+ [[package]] name = "core-foundation-sys" version = "0.8.7"@@ -852,7 +1002,7 @@ checksum = "ee3344d349528f449816cfa85e558c439bdca5a6d8a738cfb21e69f0b2b1952f" dependencies = [  "hax-lib",  "pastey",- "rand",+ "rand 0.10.3", ]  [[package]]@@ -896,6 +1046,12 @@ dependencies = [  "pkg-config", ] +[[package]]+name = "crc24"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd121741cf3eb82c08dd3023eb55bf2665e5f60ec20f89760cf836ae4562e6a0"+ [[package]] name = "crc32fast" version = "1.5.3"@@ -1036,7 +1192,7 @@ dependencies = [  "criterion",  "crypto_provider_default",  "hex-literal",- "rand",+ "rand 0.10.3",  "rand_ext",  "tinyvec", ]@@ -1067,7 +1223,7 @@ dependencies = [  "hkdf 0.13.0",  "hmac 0.13.0",  "p256 0.14.0",- "rand",+ "rand 0.10.3",  "rand_chacha 0.10.0",  "rand_core 0.10.1",  "sec1 0.8.1",@@ -1148,12 +1304,73 @@ dependencies = [  "syn 2.0.119", ] +[[package]]+name = "cx448"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4c0cf476284b03eb6c10e78787b21c7abb7d7d43cb2f02532ba6b831ed892fa"+dependencies = [+ "crypto-bigint 0.5.5",+ "elliptic-curve 0.13.8",+ "pkcs8 0.10.2",+ "rand_core 0.6.4",+ "serdect 0.3.0",+ "sha3 0.10.9",+ "signature 2.2.0",+ "subtle",+ "zeroize",+]++[[package]]+name = "darling"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"+dependencies = [+ "fnv",+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 2.0.119",+]++[[package]]+name = "darling_macro"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"+dependencies = [+ "darling_core",+ "quote",+ "syn 2.0.119",+]+ [[package]] name = "data-encoding" version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]]+name = "dbl"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd2735a791158376708f9347fe8faba9667589d82427ef3aed6794a8981de3d9"+dependencies = [+ "generic-array",+]+ [[package]] name = "dem_ingest" version = "0.1.0"@@ -1195,6 +1412,37 @@ dependencies = [  "syn 3.0.9", ] +[[package]]+name = "derive_builder"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"+dependencies = [+ "derive_builder_macro",+]++[[package]]+name = "derive_builder_core"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "derive_builder_macro"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"+dependencies = [+ "derive_builder_core",+ "syn 2.0.119",+]+ [[package]] name = "derive_fuzztest" version = "0.1.4"@@ -1218,6 +1466,38 @@ dependencies = [  "syn 2.0.119", ] +[[package]]+name = "derive_more"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"+dependencies = [+ "derive_more-impl",+]++[[package]]+name = "derive_more-impl"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"+dependencies = [+ "convert_case",+ "proc-macro2",+ "quote",+ "rustc_version",+ "syn 2.0.119",+ "unicode-xid",+]++[[package]]+name = "des"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"+dependencies = [+ "cipher 0.4.4",+]+ [[package]] name = "diff" version = "0.1.13"@@ -1259,6 +1539,22 @@ dependencies = [  "syn 3.0.9", ] +[[package]]+name = "dsa"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "48bc224a9084ad760195584ce5abb3c2c34a225fa312a128ad245a6b412b7689"+dependencies = [+ "digest 0.10.7",+ "num-bigint-dig",+ "num-traits",+ "pkcs8 0.10.2",+ "rfc6979 0.4.0",+ "sha2 0.10.9",+ "signature 2.2.0",+ "zeroize",+]+ [[package]] name = "duplicate" version = "2.0.1"@@ -1274,14 +1570,31 @@ dependencies = [ name = "e2ee_pqc" version = "0.1.0" dependencies = [+ "base64 0.23.1",  "fips203",  "fips204",  "jni",- "rand",+ "pgp",+ "rand 0.10.3",+ "rand 0.8.6",  "rand_core 0.10.1",  "sha2 0.11.1",  "sha3 0.12.0",  "shake",+ "smallvec",+]++[[package]]+name = "eax"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9954fabd903b82b9d7a68f65f97dc96dd9ad368e40ccc907a7c19d53e6bfac28"+dependencies = [+ "aead 0.5.2",+ "cipher 0.4.4",+ "cmac",+ "ctr 0.9.2",+ "subtle", ]  [[package]]@@ -1383,6 +1696,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [  "base16ct 0.2.0",+ "base64ct",  "crypto-bigint 0.5.5",  "digest 0.10.7",  "ff 0.13.1",@@ -1393,7 +1707,10 @@ dependencies = [  "pkcs8 0.10.2",  "rand_core 0.6.4",  "sec1 0.7.3",+ "serde_json",+ "serdect 0.2.0",  "subtle",+ "tap",  "zeroize", ] @@ -1537,6 +1854,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [+ "bitvec",  "rand_core 0.6.4",  "subtle", ]@@ -1608,6 +1926,12 @@ dependencies = [  "zlib-rs", ] +[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"+ [[package]] name = "foldhash" version = "0.2.0"@@ -1632,6 +1956,12 @@ dependencies = [  "percent-encoding", ] +[[package]]+name = "funty"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"+ [[package]] name = "futures-core" version = "0.3.34"@@ -2099,7 +2429,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2c461da2e0c9c93d875b597f0c78214fb0d2d5c57834b2ef2a2fa057fa20e24" dependencies = [- "rand",+ "rand 0.10.3",  "zeroize", ] @@ -2115,7 +2445,7 @@ dependencies = [  "libcrux-hkdf",  "libcrux-kem",  "libcrux-traits",- "rand",+ "rand 0.10.3",  "rand_chacha 0.10.0",  "rand_core 0.10.1",  "zeroize",@@ -2135,7 +2465,7 @@ dependencies = [  "ml-kem",  "p256 0.13.2",  "p384",- "rand",+ "rand 0.10.3",  "rand_chacha 0.10.0",  "rand_core 0.10.1",  "sha2 0.11.1",@@ -2280,6 +2610,21 @@ dependencies = [  "zerovec", ] +[[package]]+name = "idea"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "075557004419d7f2031b8bb7f44bb43e55a83ca7b63076a8fb8fe75753836477"+dependencies = [+ "cipher 0.4.4",+]++[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"+ [[package]] name = "idna" version = "1.1.0"@@ -2355,7 +2700,7 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f" dependencies = [- "block-padding",+ "block-padding 0.4.2",  "hybrid-array", ] @@ -2494,7 +2839,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" dependencies = [  "cfg-if",+ "ecdsa 0.16.9",  "elliptic-curve 0.13.8",+ "once_cell",+ "sha2 0.10.9",+ "signature 2.2.0", ]  [[package]]@@ -2558,7 +2907,7 @@ dependencies = [  "serde",  "sha2 0.11.1",  "thiserror 2.0.21",- "twofish",+ "twofish 0.8.0",  "uuid",  "zeroize", ]@@ -2611,7 +2960,7 @@ dependencies = [  "aes 0.9.3",  "anyhow",  "base64 0.23.1",- "blake2",+ "blake2 0.11.0",  "clap",  "criterion",  "crypto_provider",@@ -2621,7 +2970,7 @@ dependencies = [  "hdrhistogram",  "hex",  "ldt_tbc",- "rand",+ "rand 0.10.3",  "rand_ext",  "rand_pcg",  "serde_json",@@ -2672,7 +3021,7 @@ dependencies = [  "ldt",  "ldt_tbc",  "np_hkdf",- "rand",+ "rand 0.10.3",  "rand_ext",  "rand_pcg",  "serde_json",@@ -2688,6 +3037,12 @@ dependencies = [  "crypto_provider", ] +[[package]]+name = "libbz2-rs-sys"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"+ [[package]] name = "libc" version = "0.2.191"@@ -2751,7 +3106,7 @@ checksum = "4a227590b89ff55ce7cd97b5a7468c82d231db8f3b890bb4d4fb6d271e7524d7" dependencies = [  "libcrux-curve25519",  "libcrux-p256",- "rand",+ "rand 0.10.3",  "tls_codec", ] @@ -2809,7 +3164,7 @@ dependencies = [  "libcrux-p256",  "libcrux-sha3",  "libcrux-traits",- "rand",+ "rand 0.10.3", ]  [[package]]@@ -2834,7 +3189,7 @@ dependencies = [  "libcrux-secrets",  "libcrux-sha3",  "libcrux-traits",- "rand",+ "rand 0.10.3",  "tls_codec", ] @@ -2910,7 +3265,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fa7a21e8c2e8baa8b40f0b176740f2ca4baadd79d1b00e48d6b1e363c42085a" dependencies = [  "libcrux-secrets",- "rand",+ "rand 0.10.3", ]  [[package]]@@ -2933,6 +3288,12 @@ dependencies = [  "windows-link", ] +[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+ [[package]] name = "libmimalloc-sys" version = "0.1.47"@@ -2998,9 +3359,9 @@ dependencies = [  "indexmap",  "itoa",  "log",- "md-5",+ "md-5 0.11.0",  "nom 8.0.0",- "rand",+ "rand 0.10.3",  "rangemap",  "serde",  "sha2 0.11.1",@@ -3035,6 +3396,16 @@ dependencies = [  "tilecodec", ] +[[package]]+name = "md-5"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"+dependencies = [+ "cfg-if",+ "digest 0.10.7",+]+ [[package]] name = "md-5" version = "0.11.0"@@ -3176,7 +3547,7 @@ dependencies = [  "jni",  "libc",  "log",- "rand",+ "rand 0.10.3",  "ruzstd", ] @@ -3216,7 +3587,7 @@ dependencies = [  "ldt_np_adv",  "nom 8.0.0",  "np_hkdf",- "rand",+ "rand 0.10.3",  "rand_ext",  "serde",  "serde_json",@@ -3252,7 +3623,7 @@ dependencies = [  "crypto_provider_default",  "hex",  "ldt",- "rand",+ "rand 0.10.3",  "rand_ext",  "serde_json",  "test_helper",@@ -3280,6 +3651,23 @@ dependencies = [  "num-traits", ] +[[package]]+name = "num-bigint-dig"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"+dependencies = [+ "lazy_static",+ "libm",+ "num-integer",+ "num-iter",+ "num-traits",+ "rand 0.8.6",+ "serde",+ "smallvec",+ "zeroize",+]+ [[package]] name = "num-integer" version = "0.1.47"@@ -3289,6 +3677,16 @@ dependencies = [  "num-traits", ] +[[package]]+name = "num-iter"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"+dependencies = [+ "num-integer",+ "num-traits",+]+ [[package]] name = "num-traits" version = "0.2.19"@@ -3296,6 +3694,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [  "autocfg",+ "libm",+]++[[package]]+name = "num_enum"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"+dependencies = [+ "num_enum_derive",+ "rustversion",+]++[[package]]+name = "num_enum_derive"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "ocb3"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c196e0276c471c843dd5777e7543a36a298a4be942a2a688d8111cd43390dedb"+dependencies = [+ "aead 0.5.2",+ "cipher 0.4.4",+ "ctr 0.9.2",+ "subtle", ]  [[package]]@@ -3517,6 +3949,20 @@ dependencies = [  "sha2 0.10.9", ] +[[package]]+name = "p521"+version = "0.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fc9e2161f1f215afdfce23677034ae137bbd45016a880c2eb3ba8eb95f085b2"+dependencies = [+ "base16ct 0.2.0",+ "ecdsa 0.16.9",+ "elliptic-curve 0.13.8",+ "primeorder 0.13.6",+ "rand_core 0.6.4",+ "sha2 0.10.9",+]+ [[package]] name = "page_size" version = "0.6.0"@@ -3550,6 +3996,17 @@ dependencies = [  "windows-link", ] +[[package]]+name = "password-hash"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"+dependencies = [+ "base64ct",+ "rand_core 0.6.4",+ "subtle",+]+ [[package]] name = "passwords_kdbx" version = "0.1.0"@@ -3581,9 +4038,9 @@ dependencies = [  "jni",  "jpeg-decoder",  "lopdf",- "md-5",+ "md-5 0.11.0",  "openjp2",- "rand",+ "rand 0.10.3",  "rand_core 0.10.1",  "sha2 0.11.1",  "ttf-parser",@@ -3617,6 +4074,76 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]]+name = "pgp"+version = "0.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae70f4d9325a391db30d115d6191a7bb67cec856aa0bba131290f0c4e09a532a"+dependencies = [+ "aead 0.5.2",+ "aes 0.8.4",+ "aes-gcm 0.10.3",+ "aes-kw",+ "argon2",+ "base64 0.22.1",+ "bitfields",+ "block-padding 0.3.3",+ "blowfish",+ "buffer-redux",+ "byteorder",+ "bytes",+ "bzip2",+ "camellia",+ "cast5",+ "cfb-mode",+ "cipher 0.4.4",+ "const-oid 0.9.6",+ "crc24",+ "curve25519-dalek 4.1.3",+ "cx448",+ "derive_builder",+ "derive_more",+ "des",+ "digest 0.10.7",+ "dsa",+ "eax",+ "ecdsa 0.16.9",+ "ed25519-dalek 2.2.0",+ "elliptic-curve 0.13.8",+ "flate2",+ "generic-array",+ "hex",+ "hkdf 0.12.4",+ "idea",+ "k256",+ "log",+ "md-5 0.10.6",+ "memchr",+ "nom 8.0.0",+ "num-bigint-dig",+ "num-traits",+ "num_enum",+ "ocb3",+ "p256 0.13.2",+ "p384",+ "p521",+ "rand 0.8.6",+ "replace_with",+ "ripemd",+ "rsa",+ "sha1",+ "sha1-checked",+ "sha2 0.10.9",+ "sha3 0.10.9",+ "signature 2.2.0",+ "smallvec",+ "snafu",+ "subtle",+ "twofish 0.7.1",+ "x25519-dalek 2.0.1",+ "zeroize",+]+ [[package]] name = "phf" version = "0.13.1"@@ -3682,6 +4209,17 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]]+name = "pkcs1"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"+dependencies = [+ "der 0.7.10",+ "pkcs8 0.10.2",+ "spki 0.7.3",+]+ [[package]] name = "pkcs8" version = "0.10.2"@@ -4026,7 +4564,7 @@ checksum = "95c589f335db0f6aaa168a7cd27b1fc6920f5e1470c804f814d9cd6e62a0f70b" dependencies = [  "env_logger",  "log",- "rand",+ "rand 0.10.3", ]  [[package]]@@ -4044,6 +4582,23 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]]+name = "radium"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"++[[package]]+name = "rand"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"+dependencies = [+ "libc",+ "rand_chacha 0.3.1",+ "rand_core 0.6.4",+]+ [[package]] name = "rand" version = "0.10.3"@@ -4096,7 +4651,7 @@ version = "0.1.0" dependencies = [  "crypto_provider",  "log",- "rand",+ "rand 0.10.3",  "rand_pcg", ] @@ -4195,6 +4750,12 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]]+name = "replace_with"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51743d3e274e2b18df81c4dc6caf8a5b8e15dbe799e0dca05c7617380094e884"+ [[package]] name = "rfc6979" version = "0.4.0"@@ -4229,6 +4790,35 @@ dependencies = [  "windows-sys 0.52.0", ] +[[package]]+name = "ripemd"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f"+dependencies = [+ "digest 0.10.7",+]++[[package]]+name = "rsa"+version = "0.9.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"+dependencies = [+ "const-oid 0.9.6",+ "digest 0.10.7",+ "num-bigint-dig",+ "num-integer",+ "num-traits",+ "pkcs1",+ "pkcs8 0.10.2",+ "rand_core 0.6.4",+ "signature 2.2.0",+ "spki 0.7.3",+ "subtle",+ "zeroize",+]+ [[package]] name = "rust-argon2" version = "3.0.0"@@ -4373,6 +4963,7 @@ dependencies = [  "der 0.7.10",  "generic-array",  "pkcs8 0.10.2",+ "serdect 0.2.0",  "subtle",  "zeroize", ]@@ -4459,6 +5050,48 @@ dependencies = [  "zmij", ] +[[package]]+name = "serdect"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a84f14a19e9a014bb9f4512488d9829a68e04ecabffb0f9904cd1ace94598177"+dependencies = [+ "base16ct 0.2.0",+ "serde",+]++[[package]]+name = "serdect"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f42f67da2385b51a5f9652db9c93d78aeaf7610bf5ec366080b6de810604af53"+dependencies = [+ "base16ct 0.2.0",+ "serde",+]++[[package]]+name = "sha1"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest 0.10.7",+]++[[package]]+name = "sha1-checked"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "89f599ac0c323ebb1c6082821a54962b839832b03984598375bff3975b804423"+dependencies = [+ "digest 0.10.7",+ "sha1",+ "zeroize",+]+ [[package]] name = "sha2" version = "0.10.9"@@ -4636,6 +5269,27 @@ version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +[[package]]+name = "snafu"+version = "0.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e45cb604038abb7b926b679887b3226d8d0f23874b66623625a0454be425a4b7"+dependencies = [+ "snafu-derive",+]++[[package]]+name = "snafu-derive"+version = "0.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "287f59010008f0d7cf5e3b03196d666c1acc46c8d3e9cf34c28a1a7157601e72"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+ [[package]] name = "spin" version = "0.9.9"@@ -4754,6 +5408,12 @@ dependencies = [  "syn 3.0.9", ] +[[package]]+name = "tap"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"+ [[package]] name = "tempfile" version = "3.27.0"@@ -5038,6 +5698,15 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +[[package]]+name = "twofish"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a78e83a30223c757c3947cd144a31014ff04298d8719ae10d03c31c0448c8013"+dependencies = [+ "cipher 0.4.4",+]+ [[package]] name = "twofish" version = "0.8.0"@@ -5089,7 +5758,7 @@ dependencies = [  "crypto_provider_default",  "crypto_provider_rustcrypto",  "nom 8.0.0",- "rand",+ "rand 0.10.3",  "thiserror 2.0.21",  "ukey2_proto",  "ukey2_rs",@@ -5125,7 +5794,7 @@ dependencies = [  "crypto_provider_default",  "log",  "num-bigint 0.5.1",- "rand",+ "rand 0.10.3",  "sha2 0.11.1",  "ukey2_proto", ]@@ -5157,6 +5826,18 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" +[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "unicode-xid"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"+ [[package]] name = "universal-hash" version = "0.5.1"@@ -5320,7 +6001,7 @@ dependencies = [  "aead 0.6.1",  "base64 0.23.1",  "bitfield-struct",- "blake2",+ "blake2 0.11.0",  "bytes",  "chacha20poly1305 0.11.0",  "constant_time_eq 0.6.1",@@ -5333,7 +6014,7 @@ dependencies = [  "jni",  "libc",  "parking_lot",- "rand",+ "rand 0.10.3",  "rand_core 0.10.1",  "thiserror 2.0.21",  "tracing",@@ -5689,6 +6370,15 @@ dependencies = [  "serde_json", ] +[[package]]+name = "wyz"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"+dependencies = [+ "tap",+]+ [[package]] name = "x-wing" version = "0.1.1"@@ -5759,7 +6449,7 @@ dependencies = [  "crypto_provider_default",  "hex",  "ldt_tbc",- "rand",+ "rand 0.10.3",  "rand_ext",  "rand_pcg",  "regex",
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 6123db8427..20bb730a14 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -182,8 +182,14 @@ hmac = "0.13.0" subtle = "2.6.1" fips203 = "0.4.3" fips204 = "0.4.6"+# OpenPGP (RFC 9580) for SecureMail via :library:e2ee-p2p — replaces BouncyCastle.+# rPGP: pure-Rust packet armor/keyring/encrypt/decrypt. BouncyCastle stays removed.+pgp = { version = "0.21.0" } rand_core = { version = "0.10.1" } rand = { version = "0.10.3", default-features = true }+# rand 0.8 for rPGP (`pgp` 0.21 uses rand 0.8 / rand_core 0.6; workspace default+# is rand 0.10). Same alias pattern as `aes09` for keepass.+rand08 = { package = "rand", version = "=0.8.6" } getrandom = "0.4.3" # x509-cert / cms / spki / rsa removed with the PDF signature-creation feature. der = { version = "0.8.2", features = ["alloc", "oid"] }
README.md
diff --git a/README.md b/README.mdindex 28475a8fbc..b9fc57fd63 100644--- a/README.md+++ b/README.md@@ -83,6 +83,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **PDF Reader** | MA-1 | [Homepage](https://maproj.org/apps/pdf) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.pdf) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=PDF&packageName=com.vayunmathur.pdf&apk=pdf-release.apk) | | **Photos** | MA-1 | [Homepage](https://maproj.org/apps/photos) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.photos) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=Photos&packageName=com.vayunmathur.photos&apk=photos-release.apk) | | **Share** | MA-2 | [Homepage](https://maproj.org/apps/share) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.share/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=Share&packageName=com.vayunmathur.share&apk=share-release.apk) |+| **SecureMail** | MA-1 | [Homepage](https://maproj.org/apps/securemail) | In Progress | In Progress | | **Speech Recognizer** | MA-2 | [Homepage](https://maproj.org/apps/speech) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.speech/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=Speech%20Recognizer&packageName=com.vayunmathur.speech&apk=speech-release.apk) | | **Taxi (US and Canada only)** | MA-E | [Homepage](https://maproj.org/apps/taxi) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.taxi/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=Taxi&packageName=com.vayunmathur.taxi&apk=taxi-release.apk) | | **Things** | MA-3 | [Homepage](https://maproj.org/apps/things) | In Progress | In Progress |
library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pgp.kt
diff --git a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pgp.kt b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pgp.ktnew file mode 100644index 0000000000..73be54a739--- /dev/null+++ b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/Pgp.kt@@ -0,0 +1,75 @@+package com.vayunmathur.e2ee++/**+ * OpenPGP (RFC 9580) primitives for SecureMail, backed by native Rust (rPGP)+ * instead of BouncyCastle.+ *+ * Suite: Ed25519 signing primary + X25519 encryption subkey, AES-256 session+ * keys, SHA-512 digests — interoperable with ProtonMail and any OpenPGP+ * client. All key handling speaks ASCII armor; the relay wire carries raw+ * bytes and converts at the boundary only, mirroring the FindFamily relay+ * contract.+ */+object Pgp {++    /** A generated identity: armored secret ring (passphrase-wrapped) + armored public ring. */+    data class Identity(+        val armoredSecret: String,+        val armoredPublic: String,+        val fingerprintHex: String,+    )++    private fun String.toUtf8(): ByteArray = toByteArray(Charsets.UTF_8)+    private fun ByteArray.toUtf8String(): String = toString(Charsets.UTF_8)++    /**+     * Generates an Ed25519 primary + X25519 encryption subkey for [userId]+     * (e.g. "alice <[email protected]>"). The secret key material is wrapped+     * with [passphrase] via S2K so the stored blob alone is useless.+     */+    fun generateIdentity(userId: String, passphrase: String): Identity {+        val parts = PgpNative.nativePgpGenerate(userId.toUtf8(), passphrase.toUtf8())+            ?: error("OpenPGP key generation failed")+        require(parts.size == 3) { "OpenPGP key generation returned ${parts.size} parts" }+        return Identity(+            armoredSecret = parts[0].toUtf8String(),+            armoredPublic = parts[1].toUtf8String(),+            fingerprintHex = parts[2].toUtf8String(),+        )+    }++    /** Fingerprint hex (uppercase, no spaces) of an armored public key. */+    fun fingerprintHex(armoredPublic: String): String =+        PgpNative.nativePgpFingerprint(armoredPublic.toUtf8())?.toUtf8String()+            ?: error("Invalid OpenPGP public key")++    /**+     * Normalizes a WKD record (binary key or armor) to canonical armor text.+     * Throws when the input is not a parseable OpenPGP public key.+     */+    fun normalizeKey(record: ByteArray): String =+        PgpNative.nativePgpNormalizeKey(record)?.toUtf8String()+            ?: error("Invalid OpenPGP public key")++    /**+     * Encrypts [plaintext] (raw message bytes, e.g. a PGP/MIME body) to the+     * holder of [armoredPublic]. Returns raw (unarmored) PGP bytes for the+     * relay wire; armor via [armorMessage] for SMTP federation.+     */+    fun encrypt(armoredPublic: String, plaintext: ByteArray): ByteArray =+        PgpNative.nativePgpEncrypt(armoredPublic.toUtf8(), plaintext)+            ?: error("OpenPGP encryption failed")++    /**+     * Decrypts raw PGP bytes with [armoredSecret] + [passphrase]. Returns the+     * literal payload.+     */+    fun decrypt(armoredSecret: String, passphrase: String, ciphertext: ByteArray): ByteArray =+        PgpNative.nativePgpDecrypt(armoredSecret.toUtf8(), passphrase.toUtf8(), ciphertext)+            ?: error("OpenPGP decryption failed")++    /** Armors raw PGP bytes as a `PGP MESSAGE` block (for SMTP federation). */+    fun armorMessage(raw: ByteArray): String =+        PgpNative.nativePgpArmorMessage(raw)?.toUtf8String()+            ?: error("OpenPGP armor failed")+}
library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PgpNative.kt
diff --git a/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PgpNative.kt b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PgpNative.ktnew file mode 100644index 0000000000..33bff6ae8c--- /dev/null+++ b/library/e2ee-p2p/src/main/java/com/vayunmathur/e2ee/PgpNative.kt@@ -0,0 +1,28 @@+package com.vayunmathur.e2ee++// PACKAGE STRUCTURE EXCEPTION (JNI)++/**+ * JNI surface for the native Rust OpenPGP module (libe2ee_pqc.so, `pgp.rs` via+ * rPGP): Ed25519 primary + X25519 subkey generation, armor, encrypt, decrypt.+ *+ * Keys cross as ASCII armor (UTF-8 bytes); ciphertext crosses as raw PGP bytes+ * (armored only for SMTP federation via [nativePgpArmorMessage]). Null on any+ * failure — callers in [Pgp] map null to errors.+ */+internal object PgpNative {+    external fun nativePgpGenerate(userId: ByteArray, passphrase: ByteArray): Array<ByteArray>?+    external fun nativePgpFingerprint(armoredPublic: ByteArray): ByteArray?+    external fun nativePgpNormalizeKey(input: ByteArray): ByteArray?+    external fun nativePgpEncrypt(armoredPublic: ByteArray, plaintext: ByteArray): ByteArray?+    external fun nativePgpDecrypt(+        armoredSecret: ByteArray,+        passphrase: ByteArray,+        ciphertext: ByteArray,+    ): ByteArray?+    external fun nativePgpArmorMessage(raw: ByteArray): ByteArray?++    init {+        System.loadLibrary("e2ee_pqc")+    }+}
library/e2ee-p2p/src/main/rust/Cargo.toml
diff --git a/library/e2ee-p2p/src/main/rust/Cargo.toml b/library/e2ee-p2p/src/main/rust/Cargo.tomlindex ac8582573c..5e1ecffc92 100644--- a/library/e2ee-p2p/src/main/rust/Cargo.toml+++ b/library/e2ee-p2p/src/main/rust/Cargo.toml@@ -18,3 +18,13 @@ shake.workspace = true jni.workspace = true rand.workspace = true rand_core.workspace = true+# rand 0.8 for rPGP keygen/encrypt RNG (workspace default is 0.10; see root).+rand08.workspace = true+# OpenPGP packet engine for SecureMail (generate/armor/encrypt/decrypt).+# Same crate as the relay server would use; the JNI surface below exposes only+# what the app needs (no WKD/SMTP — those stay in Kotlin via library:network).+pgp.workspace = true+# Base64 framing for PGP/MIME armor output (workspace pin, betocore line).+base64.workspace = true+# smallvec! for rPGP key-preference lists (workspace pin, betocore line).+smallvec.workspace = true
library/e2ee-p2p/src/main/rust/src/lib.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/lib.rs b/library/e2ee-p2p/src/main/rust/src/lib.rsindex 07424141b1..2a1208b73c 100644--- a/library/e2ee-p2p/src/main/rust/src/lib.rs+++ b/library/e2ee-p2p/src/main/rust/src/lib.rs@@ -239,6 +239,10 @@ pub fn mldsa_verify_der(pub_der: &[u8], msg: &[u8], sig: &[u8]) -> bool {  mod jni_bridge; mod c_bridge;+pub mod pgp;  #[cfg(test)] mod tests;++#[cfg(test)]+mod pgp_tests;
library/e2ee-p2p/src/main/rust/src/pgp.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/pgp.rs b/library/e2ee-p2p/src/main/rust/src/pgp.rsnew file mode 100644index 0000000000..1401b85518--- /dev/null+++ b/library/e2ee-p2p/src/main/rust/src/pgp.rs@@ -0,0 +1,331 @@+//! OpenPGP (RFC 9580) for SecureMail, via rPGP.+//!+//! Suite: Ed25519 signing primary + X25519 encryption subkey (the same suite+//! the app previously generated with BouncyCastle), AES-256 session keys,+//! SHA-512 digests. Keys cross the JNI boundary as ASCII armor; ciphertext+//! crosses as raw PGP/MIME bytes (armored only for SMTP federation, which the+//! app does with [`to_armored_message`]).+//!+//! The relay server never sees plaintext or private keys — it routes opaque+//! blobs by recipient address, exactly like the FindFamily relay routes opaque+//! ciphertext by userid.++use pgp::armor::Dearmor;+use pgp::composed::{+    ArmorOptions, Deserializable, EncryptionCaps, KeyType, Message, MessageBuilder,+    SecretKeyParamsBuilder, SignedPublicKey, SignedSecretKey, SubkeyParamsBuilder,+};+use pgp::crypto::hash::HashAlgorithm;+use pgp::crypto::sym::SymmetricKeyAlgorithm;+use pgp::types::{KeyDetails, Password};+use rand08::rngs::OsRng;++/// Generate an Ed25519 primary + X25519 encryption subkey for `user_id`.+/// Returns (armoredSecret, armoredPublic, fingerprintHex).+pub fn pgp_generate(user_id: &str, passphrase: &str) -> Option<(String, String, String)> {+    let mut rng = OsRng;+    let mut params = SecretKeyParamsBuilder::default();+    params+        .key_type(KeyType::Ed25519)+        .can_certify(false)+        .can_sign(true)+        .primary_user_id(user_id.to_string())+        .passphrase(Some(passphrase.to_string()))+        .preferred_symmetric_algorithms(smallvec::smallvec![+            SymmetricKeyAlgorithm::AES256,+        ])+        .preferred_hash_algorithms(smallvec::smallvec![HashAlgorithm::Sha512])+        .preferred_compression_algorithms(smallvec::smallvec![])+        .subkeys(vec![SubkeyParamsBuilder::default()+            .key_type(KeyType::X25519)+            .can_encrypt(EncryptionCaps::All)+            .passphrase(Some(passphrase.to_string()))+            .build()+            .ok()?]);+    let secret = params.build().ok()?.generate(&mut rng).ok()?;+    let public = secret.to_public_key();+    let fingerprint = hex_upper(&secret.fingerprint().as_bytes());+    Some((+        secret.to_armored_string(ArmorOptions::default()).ok()?,+        public.to_armored_string(ArmorOptions::default()).ok()?,+        fingerprint,+    ))+}++/// Fingerprint (uppercase hex, no spaces) of an armored public key.+pub fn pgp_fingerprint(armored_public: &str) -> Option<String> {+    let (key, _) = SignedPublicKey::from_string(armored_public).ok()?;+    Some(hex_upper(&key.fingerprint().as_bytes()))+}++/// Normalize a public key (binary WKD record or armor) to canonical armor.+/// Returns None when the input is not a parseable OpenPGP public key.+pub fn pgp_normalize_key(input: &[u8]) -> Option<String> {+    use pgp::composed::Deserializable as _;+    let key = if is_probably_armor(input) {+        let text = std::str::from_utf8(input).ok()?;+        let (key, _) = SignedPublicKey::from_string(text).ok()?;+        key+    } else {+        SignedPublicKey::from_bytes(input).ok()?+    };+    key.to_armored_string(ArmorOptions::default()).ok()+}++fn is_probably_armor(input: &[u8]) -> bool {+    input.starts_with(b"-----BEGIN PGP")+}++/// Encrypt `plaintext` to one recipient's armored public key. Returns raw+/// (unarmored) PGP bytes for the relay wire.+pub fn pgp_encrypt(armored_public: &str, plaintext: &[u8]) -> Option<Vec<u8>> {+    let mut rng = OsRng;+    let (public, _) = SignedPublicKey::from_string(armored_public).ok()?;+    // Encrypt to the first subkey (our keys always carry the X25519+    // encryption subkey; a foreign key without one cannot be encrypted to).+    // Matches the documented `encrypt_to_key(&rng, &public_subkeys[0])` shape.+    let subkey = public.public_subkeys.first()?;+    let mut builder = MessageBuilder::from_bytes("message.txt", plaintext.to_vec())+        .seipd_v1(&mut rng, SymmetricKeyAlgorithm::AES256);+    builder.encrypt_to_key(&mut rng, subkey).ok()?;+    builder.to_vec(&mut rng).ok()+}++/// Decrypt raw PGP bytes with an armored secret key + passphrase. Returns the+/// literal payload. Signature verification is a separate pass (see below).+pub fn pgp_decrypt(+    armored_secret: &str,+    passphrase: &str,+    ciphertext: &[u8],+) -> Option<Vec<u8>> {+    let (secret, _) = SignedSecretKey::from_string(armored_secret).ok()?;+    let msg = Message::from_bytes(ciphertext).ok()?;+    let mut decrypted = msg+        .decrypt(&Password::from(passphrase), &secret)+        .ok()?;+    decrypted.as_data_vec().ok()+}++/// Armor raw PGP bytes as a `PGP MESSAGE` block (for SMTP federation).+pub fn to_armored_message(raw: &[u8]) -> Option<String> {+    use base64::Engine;+    // RFC 9580 §6 armor framing: header, base64 body at 64-col, CRC24 footer.+    let mut out = String::from("-----BEGIN PGP MESSAGE-----\n\n");+    let b64 = base64::engine::general_purpose::STANDARD.encode(raw);+    for chunk in b64.as_bytes().chunks(64) {+        out.push_str(std::str::from_utf8(chunk).ok()?);+        out.push('\n');+    }+    out.push('=');+    out.push_str(&base64::engine::general_purpose::STANDARD.encode(crc24(raw)));+    out.push_str("\n-----END PGP MESSAGE-----\n");+    Some(out)+}++/// OpenPGP CRC24 (RFC 9580 §6.1): polynomial 0x1864CFB, init 0xB704CE.+fn crc24(data: &[u8]) -> [u8; 3] {+    let mut crc: u32 = 0xB704CE;+    for &b in data {+        crc ^= (b as u32) << 16;+        for _ in 0..8 {+            crc <<= 1;+            if crc & 0x1000000 != 0 {+                crc ^= 0x1864CFB;+            }+        }+    }+    [(crc >> 16) as u8, (crc >> 8) as u8, crc as u8]+}++/// Dearmor any ASCII-armored input to raw bytes (key or message).+pub fn dearmor_any(armored: &str) -> Option<Vec<u8>> {+    use std::io::Read;+    let mut dearmor = Dearmor::new(armored.as_bytes());+    let mut bytes = Vec::new();+    dearmor.read_to_end(&mut bytes).ok()?;+    Some(bytes)+}++fn hex_upper(bytes: &[u8]) -> String {+    const HEX: &[u8; 16] = b"0123456789ABCDEF";+    let mut out = String::with_capacity(bytes.len() * 2);+    for b in bytes {+        out.push(HEX[(b >> 4) as usize] as char);+        out.push(HEX[(b & 0x0f) as usize] as char);+    }+    out+}++// ---------------------------------------------------------------------------+// JNI surface for `com.vayunmathur.e2ee.PgpNative`.+// Armor crosses as UTF-8 bytes; ciphertext crosses as raw bytes.+// ---------------------------------------------------------------------------++use jni::objects::{JByteArray, JClass};+use jni::sys::{jbyteArray, jobjectArray};+use jni::{Env, EnvUnowned};++fn jbytes_in(env: &Env, arr: &JByteArray) -> Option<Vec<u8>> {+    env.convert_byte_array(arr).ok()+}++fn jbytes_out(env: &mut Env, data: &[u8]) -> jbyteArray {+    match env.byte_array_from_slice(data) {+        Ok(a) => a.into_raw(),+        Err(_) => std::ptr::null_mut(),+    }+}++fn jstring_in(env: &mut Env, arr: &JByteArray) -> Option<String> {+    let bytes = jbytes_in(env, arr)?;+    String::from_utf8(bytes).ok()+}++fn jstring_out(env: &mut Env, s: &str) -> jbyteArray {+    jbytes_out(env, s.as_bytes())+}++/// Return a Java `byte[][]` of exactly three elements (secret, public,+/// fingerprint), or null.+fn triple_out(env: &mut Env, a: &str, b: &str, c: &str) -> jobjectArray {+    let arr = match env.new_object_type_array::<JByteArray>(3, JByteArray::null()) {+        Ok(a) => a,+        Err(_) => return std::ptr::null_mut(),+    };+    let items = [a.as_bytes(), b.as_bytes(), c.as_bytes()];+    for (i, data) in items.iter().enumerate() {+        let element = match env.byte_array_from_slice(data) {+            Ok(x) => x,+            Err(_) => return std::ptr::null_mut(),+        };+        if arr.set_element(env, i, &element).is_err() {+            return std::ptr::null_mut();+        }+    }+    arr.into_raw()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpGenerate<'l>(+    mut env: EnvUnowned<'l>,+    _class: JClass<'l>,+    user_id: JByteArray<'l>,+    passphrase: JByteArray<'l>,+) -> jobjectArray {+    env.with_env(|env| -> jni::errors::Result<jobjectArray> {+        let (uid, pw) = match (jstring_in(env, &user_id), jstring_in(env, &passphrase)) {+            (Some(a), Some(b)) => (a, b),+            _ => return Ok(std::ptr::null_mut()),+        };+        match pgp_generate(&uid, &pw) {+            Some((secret, public, fp)) => Ok(triple_out(env, &secret, &public, &fp)),+            None => Ok(std::ptr::null_mut()),+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpFingerprint<'l>(+    mut env: EnvUnowned<'l>,+    _class: JClass<'l>,+    armored_public: JByteArray<'l>,+) -> jbyteArray {+    env.with_env(|env| -> jni::errors::Result<jbyteArray> {+        let armor = match jstring_in(env, &armored_public) {+            Some(a) => a,+            None => return Ok(std::ptr::null_mut()),+        };+        match pgp_fingerprint(&armor) {+            Some(fp) => Ok(jstring_out(env, &fp)),+            None => Ok(std::ptr::null_mut()),+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpNormalizeKey<'l>(+    mut env: EnvUnowned<'l>,+    _class: JClass<'l>,+    input: JByteArray<'l>,+) -> jbyteArray {+    env.with_env(|env| -> jni::errors::Result<jbyteArray> {+        let bytes = match jbytes_in(env, &input) {+            Some(b) => b,+            None => return Ok(std::ptr::null_mut()),+        };+        match pgp_normalize_key(&bytes) {+            Some(armor) => Ok(jstring_out(env, &armor)),+            None => Ok(std::ptr::null_mut()),+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpEncrypt<'l>(+    mut env: EnvUnowned<'l>,+    _class: JClass<'l>,+    armored_public: JByteArray<'l>,+    plaintext: JByteArray<'l>,+) -> jbyteArray {+    env.with_env(|env| -> jni::errors::Result<jbyteArray> {+        let (armor, plain) = match (+            jstring_in(env, &armored_public),+            jbytes_in(env, &plaintext),+        ) {+            (Some(a), Some(b)) => (a, b),+            _ => return Ok(std::ptr::null_mut()),+        };+        match pgp_encrypt(&armor, &plain) {+            Some(raw) => Ok(jbytes_out(env, &raw)),+            None => Ok(std::ptr::null_mut()),+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpDecrypt<'l>(+    mut env: EnvUnowned<'l>,+    _class: JClass<'l>,+    armored_secret: JByteArray<'l>,+    passphrase: JByteArray<'l>,+    ciphertext: JByteArray<'l>,+) -> jbyteArray {+    env.with_env(|env| -> jni::errors::Result<jbyteArray> {+        let (armor, pw, ct) = match (+            jstring_in(env, &armored_secret),+            jstring_in(env, &passphrase),+            jbytes_in(env, &ciphertext),+        ) {+            (Some(a), Some(b), Some(c)) => (a, b, c),+            _ => return Ok(std::ptr::null_mut()),+        };+        match pgp_decrypt(&armor, &pw, &ct) {+            Some(plain) => Ok(jbytes_out(env, &plain)),+            None => Ok(std::ptr::null_mut()),+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_e2ee_PgpNative_nativePgpArmorMessage<'l>(+    mut env: EnvUnowned<'l>,+    _class: JClass<'l>,+    raw: JByteArray<'l>,+) -> jbyteArray {+    env.with_env(|env| -> jni::errors::Result<jbyteArray> {+        let bytes = match jbytes_in(env, &raw) {+            Some(b) => b,+            None => return Ok(std::ptr::null_mut()),+        };+        match to_armored_message(&bytes) {+            Some(armor) => Ok(jstring_out(env, &armor)),+            None => Ok(std::ptr::null_mut()),+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}
library/e2ee-p2p/src/main/rust/src/pgp_tests.rs
diff --git a/library/e2ee-p2p/src/main/rust/src/pgp_tests.rs b/library/e2ee-p2p/src/main/rust/src/pgp_tests.rsnew file mode 100644index 0000000000..c5c54a1b49--- /dev/null+++ b/library/e2ee-p2p/src/main/rust/src/pgp_tests.rs@@ -0,0 +1,105 @@+//! OpenPGP round-trip tests: generate → armor → encrypt → decrypt.+//! No external vectors: keys are randomized per run (keygen uses OS entropy),+//! so these prove self-consistency of the rPGP pipeline the app ships.++use super::pgp::*;++#[test]+fn generate_emits_armor_and_fingerprint() {+    let (secret, public, fp) = pgp_generate("alice <[email protected]>", "correct horse")+        .expect("keygen");+    assert!(secret.contains("-----BEGIN PGP PRIVATE KEY BLOCK-----"), "secret armor");+    assert!(public.contains("-----BEGIN PGP PUBLIC KEY BLOCK-----"), "public armor");+    assert_eq!(fp.len(), 40, "v4 fingerprint is 20 bytes hex");+    assert!(fp.bytes().all(|b| b.is_ascii_hexdigit()), "fingerprint hex");+    assert_eq!(fp, fp.to_uppercase(), "fingerprint uppercase");+}++#[test]+fn fingerprint_is_stable_and_address_independent() {+    let (_, public_a, fp_a) = pgp_generate("alice <[email protected]>", "pw12345678")+        .expect("keygen a");+    assert_eq!(Some(fp_a.clone()), pgp_fingerprint(&public_a));+    let (_, public_b, fp_b) = pgp_generate("bob <[email protected]>", "pw12345678")+        .expect("keygen b");+    assert_ne!(fp_a, fp_b, "distinct keys have distinct fingerprints");+    assert!(pgp_fingerprint(&public_b).is_some());+}++#[test]+fn encrypt_decrypt_roundtrip() {+    let (secret, public, _) = pgp_generate("alice <[email protected]>", "pw12345678")+        .expect("keygen");+    let plaintext = b"Hello from SecureMail";+    let raw = pgp_encrypt(&public, plaintext).expect("encrypt");+    assert!(!raw.is_empty(), "ciphertext non-empty");+    assert_ne!(raw.as_slice(), plaintext.as_slice(), "ciphertext differs");+    let back = pgp_decrypt(&secret, "pw12345678", &raw).expect("decrypt");+    assert_eq!(back, plaintext, "round-trip plaintext");+}++#[test]+fn wrong_passphrase_fails_decrypt() {+    let (secret, public, _) = pgp_generate("alice <[email protected]>", "pw12345678")+        .expect("keygen");+    let raw = pgp_encrypt(&public, b"secret").expect("encrypt");+    assert!(+        pgp_decrypt(&secret, "wrong passphrase", &raw).is_none(),+        "wrong passphrase must fail"+    );+}++#[test]+fn malformed_inputs_fail_cleanly() {+    assert!(pgp_fingerprint("not armor at all").is_none());+    assert!(pgp_encrypt("not armor at all", b"x").is_none());+    assert!(pgp_decrypt("not armor at all", "pw", b"x").is_none());+}++#[test]+fn armor_message_roundtrip() {+    let (_, public, _) = pgp_generate("alice <[email protected]>", "pw12345678")+        .expect("keygen");+    let raw = pgp_encrypt(&public, b"federation body").expect("encrypt");+    let armored = to_armored_message(&raw).expect("armor");+    assert!(+        armored.starts_with("-----BEGIN PGP MESSAGE-----"),+        "message armor header"+    );+    assert!(armored.contains("-----END PGP MESSAGE-----"), "message armor footer");+    let back = dearmor_any(&armored).expect("dearmor");+    assert_eq!(back, raw, "armor round-trips raw bytes");+}++#[test]+fn normalize_accepts_binary_and_armor() {+    use pgp::composed::{Deserializable, SignedPublicKey};+    let (_, public, fp) = pgp_generate("alice <[email protected]>", "pw12345678")+        .expect("keygen");+    // Armor in → canonical armor out with the same fingerprint.+    let normalized = pgp_normalize_key(public.as_bytes()).expect("normalize armor");+    assert!(normalized.contains("-----BEGIN PGP PUBLIC KEY BLOCK-----"));+    let (reparsed, _) = SignedPublicKey::from_string(&normalized).expect("reparse");+    assert_eq!(fingerprint_of(&reparsed), fp);+    // Binary (WKD-style record) in → armor out.+    let binary = dearmor_any(&public).expect("dearmor for binary form");+    assert!(!binary.starts_with(b"-----BEGIN"));+    let normalized_bin = pgp_normalize_key(&binary).expect("normalize binary");+    assert!(normalized_bin.contains("-----BEGIN PGP PUBLIC KEY BLOCK-----"));+    // Garbage fails cleanly.+    assert!(pgp_normalize_key(b"not a key").is_none());+    assert!(pgp_normalize_key(b"-----BEGIN PGP MESSAGE-----\n\nAAAA\n=ABCD\n-----END PGP MESSAGE-----\n").is_none());+}++fn fingerprint_of(_key: &pgp::composed::SignedPublicKey) -> String {+    use pgp::types::KeyDetails;+    let fp = _key.fingerprint();+    let bytes = fp.as_bytes();+    const HEX: &[u8; 16] = b"0123456789ABCDEF";+    let mut out = String::with_capacity(bytes.len() * 2);+    for b in bytes {+        out.push(HEX[(b >> 4) as usize] as char);+        out.push(HEX[(b & 0x0f) as usize] as char);+    }+    out+}
library/e2ee-p2p/test/java/com/vayunmathur/e2ee/PgpTest.kt
diff --git a/library/e2ee-p2p/test/java/com/vayunmathur/e2ee/PgpTest.kt b/library/e2ee-p2p/test/java/com/vayunmathur/e2ee/PgpTest.ktnew file mode 100644index 0000000000..f5a3863eaa--- /dev/null+++ b/library/e2ee-p2p/test/java/com/vayunmathur/e2ee/PgpTest.kt@@ -0,0 +1,48 @@+package com.vayunmathur.e2ee++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.test.assertFailsWith++class PgpTest {++    @Test+    fun generateEncryptDecryptRoundtrip() {+        val identity = Pgp.generateIdentity("alice <[email protected]>", "correct horse battery")+        assertTrue(identity.armoredSecret.contains("PGP PRIVATE KEY BLOCK"))+        assertTrue(identity.armoredPublic.contains("PGP PUBLIC KEY BLOCK"))+        assertEquals(40, identity.fingerprintHex.length)++        val plaintext = "Hello from SecureMail".toByteArray(Charsets.UTF_8)+        val raw = Pgp.encrypt(identity.armoredPublic, plaintext)+        assertTrue(raw.isNotEmpty())++        val back = Pgp.decrypt(identity.armoredSecret, "correct horse battery", raw)+        assertEquals(plaintext.toList(), back.toList())+    }++    @Test+    fun wrongPassphraseFails() {+        val identity = Pgp.generateIdentity("alice <[email protected]>", "correct horse battery")+        val raw = Pgp.encrypt(identity.armoredPublic, "secret".toByteArray(Charsets.UTF_8))+        assertFailsWith<IllegalStateException> {+            Pgp.decrypt(identity.armoredSecret, "wrong passphrase", raw)+        }+    }++    @Test+    fun fingerprintStable() {+        val identity = Pgp.generateIdentity("alice <[email protected]>", "correct horse battery")+        assertEquals(identity.fingerprintHex, Pgp.fingerprintHex(identity.armoredPublic))+    }++    @Test+    fun armorMessageRoundtrip() {+        val identity = Pgp.generateIdentity("alice <[email protected]>", "correct horse battery")+        val raw = Pgp.encrypt(identity.armoredPublic, "federation".toByteArray(Charsets.UTF_8))+        val armored = Pgp.armorMessage(raw)+        assertTrue(armored.startsWith("-----BEGIN PGP MESSAGE-----"))+        assertTrue(armored.contains("-----END PGP MESSAGE-----"))+    }+}
metadata_data/securemail.md
diff --git a/metadata_data/securemail.md b/metadata_data/securemail.mdnew file mode 100644index 0000000000..1690d950a6--- /dev/null+++ b/metadata_data/securemail.md@@ -0,0 +1,10 @@+End-to-end encrypted mail with PGP, over a live relay++Features:+- Claim an @maemail.org address with an on-device PGP key (Ed25519 + X25519)+- Live relay socket: mail arrives instantly, queued when offline+- Per-recipient encryption with explicit unencrypted opt-in fallback+- Interoperates with ProtonMail and any OpenPGP client via standard PGP/MIME+- Biometric-gated private key; server sees ciphertext only++Internet only used for: relay socket, key directory, and external mail delivery
securemail/build.gradle.kts
diff --git a/securemail/build.gradle.kts b/securemail/build.gradle.ktsnew file mode 100644index 0000000000..fcae4ac396--- /dev/null+++ b/securemail/build.gradle.kts@@ -0,0 +1,42 @@+plugins {+    id("common-conventions-app")+    // Store-listing screenshots come from Compose previews (src/screenshotTest).+    id("common-conventions-preview-metadata")+}++launcherIcon {+    symbol = "lock"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.securemail"+    }++    buildFeatures {+        buildConfig = true+    }++    packaging {+        resources {+            excludes += "/META-INF/{AL2.0,LGPL2.1}"+            excludes += "META-INF/NOTICE.md"+            excludes += "META-INF/LICENSE.md"+        }+    }+}++dependencies {+    // Custom REST + WebSocket relay to mail.maemail.org (dynamic host → SYSTEM trust).+    implementation(project(":library:network"))+    // Biometric gate before the Keystore-wrapped PGP private key is unwrapped.+    implementation(project(":library:biometric"))+    // Periodic inbox poll as a backstop behind the live socket.+    implementation(project(":library:work"))+    implementation(project(":library:room"))+    implementRoom(libs)+    // Address token + onboarded flag.+    implementation(libs.androidx.datastore.preferences)+    // OpenPGP via the native Rust core (rPGP in libe2ee_pqc.so). No BouncyCastle.+    implementation(project(":library:e2ee-p2p"))+}
securemail/src/main/AndroidManifest.xml
diff --git a/securemail/src/main/AndroidManifest.xml b/securemail/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..b21476966c--- /dev/null+++ b/securemail/src/main/AndroidManifest.xml@@ -0,0 +1,72 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+    xmlns:tools="http://schemas.android.com/tools">++    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:networkSecurityConfig="@xml/network_security_config"+        android:theme="@style/Theme.General"+        tools:replace="android:networkSecurityConfig">+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:theme="@style/Theme.General"+            android:launchMode="singleTask">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>++            <intent-filter>+                <action android:name="android.intent.action.SEND" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="text/plain" />+            </intent-filter>++            <intent-filter>+                <action android:name="android.intent.action.SENDTO" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:scheme="mailto" />+            </intent-filter>+        </activity>++        <service+            android:name=".service.MailSocketService"+            android:exported="false"+            android:foregroundServiceType="dataSync" />++        <receiver+            android:name=".platform.BootReceiver"+            android:exported="true"+            android:enabled="true">+            <intent-filter>+                <action android:name="android.intent.action.BOOT_COMPLETED" />+                <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+                <action android:name="android.intent.action.QUICKBOOT_POWERON" />+            </intent-filter>+        </receiver>++        <provider+            android:name="androidx.core.content.FileProvider"+            android:authorities="com.vayunmathur.securemail.fileprovider"+            android:exported="false"+            android:grantUriPermissions="true">+            <meta-data+                android:name="android.support.FILE_PROVIDER_PATHS"+                android:resource="@xml/file_paths" />+        </provider>+    </application>++</manifest>
securemail/src/main/java/com/vayunmathur/securemail/MainActivity.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/MainActivity.kt b/securemail/src/main/java/com/vayunmathur/securemail/MainActivity.ktnew file mode 100644index 0000000000..e8ec1c0108--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/MainActivity.kt@@ -0,0 +1,71 @@+package com.vayunmathur.securemail++import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import com.vayunmathur.library.ui.MaFragmentActivity+import com.vayunmathur.securemail.platform.MailViewModel+import com.vayunmathur.securemail.service.MailSocketService++/**+ * SecureMail entry point. A [MaFragmentActivity] (not plain MaActivity) because+ * unlocking the PGP private key needs a fragment host for the biometric prompt.+ * Composition is deferred until the key gate succeeds.+ */+class MainActivity : MaFragmentActivity() {++    override val autoSetContent: Boolean = false++    private val viewModel: MailViewModel by viewModels()++    override fun onCreateBeforeContent() {+        // mail.maemail.org is a pinned first-party host; WKD/VKS lookups for+        // arbitrary external domains ride the platform trust store instead.+        NetworkClient.init(this, TrustBundle.FIRST_PARTY)+        handleIntent(intent)+        viewModel.unlockIfReady(+            activity = this,+            onUnlocked = {+                MailSocketService.start(this)+                showContent()+            },+            onLocked = {+                // Stay on the lock screen: composition waits for the key gate.+                showContent()+            },+        )+    }++    @Composable+    override fun Content() {+        val route = IntentState.navigationRoute+        LaunchedEffect(route) { IntentState.navigationRoute = null }+        Navigation(viewModel, initialRoute = route)+    }++    override fun onNewIntent(intent: android.content.Intent) {+        super.onNewIntent(intent)+        handleIntent(intent)+    }++    private fun handleIntent(intent: android.content.Intent?) {+        if (intent == null) return+        val shared = intent.getStringExtra(android.content.Intent.EXTRA_TEXT)+        val to = if (intent.action == android.content.Intent.ACTION_SENDTO) {+            intent.data?.schemeSpecificPart ?: ""+        } else {+            ""+        }+        if (intent.action == android.content.Intent.ACTION_SEND ||+            intent.action == android.content.Intent.ACTION_SENDTO+        ) {+            IntentState.navigationRoute = Route.Composer(+                to = to,+                subject = intent.getStringExtra(android.content.Intent.EXTRA_SUBJECT) ?: "",+                body = shared ?: "",+            )+        }+    }+}
securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt b/securemail/src/main/java/com/vayunmathur/securemail/Navigation.ktnew file mode 100644index 0000000000..c187e469b6--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/Navigation.kt@@ -0,0 +1,138 @@+package com.vayunmathur.securemail++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import androidx.fragment.app.FragmentActivity+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.securemail.platform.MailViewModel+import com.vayunmathur.securemail.service.PendingInbox+import com.vayunmathur.securemail.ui.ComposeScreen+import com.vayunmathur.securemail.ui.InboxScreen+import com.vayunmathur.securemail.ui.LockScreen+import com.vayunmathur.securemail.ui.OnboardingScreen+import com.vayunmathur.securemail.ui.OutboxScreen+import com.vayunmathur.securemail.ui.ReaderScreen+import com.vayunmathur.securemail.ui.SettingsScreen++@Composable+fun Navigation(viewModel: MailViewModel, initialRoute: Route? = null) {+    val state = viewModel.state+    val context = LocalContext.current+    val messages by viewModel.messages.collectAsState(emptyList())+    val outbox by viewModel.outboxCount.collectAsState(0)+    // The stack follows the account flag, not navigation events: once an address+    // is claimed there is no going back to onboarding, and a locked key gates+    // everything. reset() rather than add() for the same reason as backup/.+    val start = when {+        !state.onboarded -> Route.Onboarding+        state.locked -> Route.Lock+        else -> Route.Inbox+    }+    val backStack = rememberNavBackStack<Route>(start)++    LaunchedEffect(state.onboarded, state.locked) {+        val target = when {+            !state.onboarded -> Route.Onboarding+            state.locked -> Route.Lock+            backStack.last() == Route.Onboarding || backStack.last() == Route.Lock -> Route.Inbox+            else -> return@LaunchedEffect+        }+        if (backStack.last() != target) backStack.reset(target)+    }++    LaunchedEffect(initialRoute) {+        if (initialRoute != null) backStack.add(initialRoute)+    }++    MainNavigation(backStack) {+        entry<Route.Onboarding> {+            OnboardingScreen(+                state = state,+                onClaim = viewModel::claimAddress,+                onDismissMessages = viewModel::dismissMessages,+            )+        }+        entry<Route.Lock> {+            LockScreen(+                state = state,+                onUnlock = {+                    (context as? FragmentActivity)?.let { viewModel.unlock(it) }+                },+                onDismissMessages = viewModel::dismissMessages,+                onPassphrase = viewModel::providePassphrase,+            )+        }+        entry<Route.Inbox> {+            // Drain frames that arrived while no UI was alive.+            LaunchedEffect(Unit) {+                for (p in PendingInbox.drain()) {+                    viewModel.onInboundMessage(p.id, p.unencrypted, p.raw)+                }+            }+            InboxScreen(+                state = state,+                onOpen = { backStack.add(Route.Reader(it)) },+                onCompose = { backStack.add(Route.Composer()) },+                onOutbox = { backStack.add(Route.Outbox) },+                onSettings = { backStack.add(Route.Settings) },+                onRefresh = viewModel::refresh,+                messages = messages,+                outbox = outbox,+            )+        }+        entry<Route.Composer> { route ->+            ComposeScreen(+                state = state,+                initialTo = route.to,+                initialSubject = route.subject,+                initialBody = route.body,+                onSend = viewModel::send,+                onBack = { backStack.pop() },+            )+        }+        entry<Route.Reader> { route ->+            val msg = remember(route.messageId, messages) {+                messages.firstOrNull { it.id == route.messageId }+            }+            LaunchedEffect(route.messageId) {+                viewModel.decryptStored(route.messageId)+                viewModel.markRead(route.messageId)+            }+            ReaderScreen(+                state = state,+                messageId = route.messageId,+                onReply = { m ->+                    backStack.add(+                        Route.Composer(+                            to = m.from,+                            subject = "Re: ${m.decryptedSubject ?: ""}",+                            inReplyTo = m.id,+                        ),+                    )+                },+                onBack = { backStack.pop() },+                message = msg,+            )+        }+        entry<Route.Outbox> {+            OutboxScreen(+                state = state,+                onRetry = viewModel::retryOutbox,+                onBack = { backStack.pop() },+            )+        }+        entry<Route.Settings> {+            SettingsScreen(+                state = state,+                onExportPublicKey = viewModel::exportPublicKey,+                onForget = viewModel::forgetIdentity,+                onBack = { backStack.pop() },+            )+        }+    }+}
securemail/src/main/java/com/vayunmathur/securemail/Route.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/Route.kt b/securemail/src/main/java/com/vayunmathur/securemail/Route.ktnew file mode 100644index 0000000000..9767280064--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/Route.kt@@ -0,0 +1,38 @@+package com.vayunmathur.securemail++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++/** Holds a pending deep-link/share route until Navigation consumes it. */+object IntentState {+    var navigationRoute: Route? = null+}++@Serializable+sealed interface Route : NavKey {+    @Serializable+    data object Onboarding : Route++    @Serializable+    data object Lock : Route++    @Serializable+    data object Inbox : Route++    @Serializable+    data class Composer(+        val to: String = "",+        val subject: String = "",+        val body: String = "",+        val inReplyTo: String? = null,+    ) : Route++    @Serializable+    data class Reader(val messageId: String) : Route++    @Serializable+    data object Outbox : Route++    @Serializable+    data object Settings : Route+}
securemail/src/main/java/com/vayunmathur/securemail/data/MailConfig.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailConfig.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailConfig.ktnew file mode 100644index 0000000000..dfdbeba265--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailConfig.kt@@ -0,0 +1,56 @@+package com.vayunmathur.securemail.data++import android.content.Context+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++/** Immutable snapshot of the SecureMail account state. */+data class MailSettings(+    val address: String = "",+    val publicArmor: String = "",+    val fingerprintHex: String = "",+    val lastSyncMillis: Long = 0L,+) {+    val isConfigured: Boolean get() = address.isNotBlank()+}++private val Context.mailDataStore by preferencesDataStore(name = "securemail_config")++/** DataStore-backed persistence for [MailSettings] (non-secret fields only). */+class MailConfig(private val context: Context) {+    val settings: Flow<MailSettings> = context.mailDataStore.data.map { p ->+        MailSettings(+            address = p[KEY_ADDRESS] ?: "",+            publicArmor = p[KEY_PUBLIC] ?: "",+            fingerprintHex = p[KEY_FINGERPRINT] ?: "",+            lastSyncMillis = p[KEY_LAST_SYNC] ?: 0L,+        )+    }++    suspend fun setIdentity(address: String, publicArmor: String, fingerprintHex: String) {+        context.mailDataStore.edit {+            it[KEY_ADDRESS] = address+            it[KEY_PUBLIC] = publicArmor+            it[KEY_FINGERPRINT] = fingerprintHex+        }+    }++    suspend fun setLastSync(epochMillis: Long) {+        context.mailDataStore.edit { it[KEY_LAST_SYNC] = epochMillis }+    }++    suspend fun clear() {+        context.mailDataStore.edit { it.clear() }+    }++    companion object {+        private val KEY_ADDRESS = stringPreferencesKey("address")+        private val KEY_PUBLIC = stringPreferencesKey("public_armor")+        private val KEY_FINGERPRINT = stringPreferencesKey("fingerprint_hex")+        private val KEY_LAST_SYNC = longPreferencesKey("last_sync")+    }+}
securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.ktnew file mode 100644index 0000000000..8301f313e7--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt@@ -0,0 +1,127 @@+package com.vayunmathur.securemail.data++import androidx.room3.ColumnInfo+import androidx.room3.Dao+import androidx.room3.Database+import androidx.room3.Entity+import androidx.room3.Insert+import androidx.room3.OnConflictStrategy+import androidx.room3.PrimaryKey+import androidx.room3.Query+import androidx.room3.RoomDatabase+import androidx.room3.migration.Migration+import androidx.sqlite.execSQL+import com.vayunmathur.library.util.DatabaseMigrations+import kotlinx.coroutines.flow.Flow++/**+ * One stored message: envelope metadata plus the opaque PGP/MIME blob exactly+ * as it arrived over the socket (raw bytes, base64 in the DB). The server never+ * sees plaintext; neither does this table — decryption happens in memory only.+ */+@Entity+data class StoredMessage(+    @PrimaryKey val id: String,+    val from: String,+    val toJson: String,+    val dateMillis: Long,+    val messageId: String,+    /** Base64 of the raw PGP/MIME blob (wire format is raw binary). */+    val blobBase64: String,+    /** Decrypted body cached only after an in-memory decrypt (nullable). */+    val decryptedBody: String? = null,+    val decryptedSubject: String? = null,+    val verifiedSigner: String? = null,+    val unencrypted: Boolean = false,+    val isRead: Boolean = false,+)++/** Cached public key for a recipient (own directory, WKD, or VKS result). */+@Entity+data class CachedKey(+    @PrimaryKey val address: String,+    val armoredPublic: String,+    val fingerprintHex: String,+    val source: String,+    val updatedMillis: Long,+)++/** Queued outbound message awaiting socket reconnect or SMTP federation. */+@Entity+data class OutboxMessage(+    @PrimaryKey(autoGenerate = true) val rowId: Long = 0,+    val toJson: String,+    val subject: String,+    val body: String,+    val inReplyTo: String? = null,+    val sendUnencrypted: Boolean = false,+    val createdMillis: Long,+    val lastError: String? = null,+    val attemptCount: Int = 0,+)++@Dao+interface MessageDao {+    @Query("SELECT * FROM StoredMessage ORDER BY dateMillis DESC")+    fun observeAll(): Flow<List<StoredMessage>>++    @Query("SELECT * FROM StoredMessage WHERE id = :id LIMIT 1")+    suspend fun get(id: String): StoredMessage?++    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun upsert(msg: StoredMessage)++    @Query("UPDATE StoredMessage SET isRead = 1 WHERE id = :id")+    suspend fun markRead(id: String)++    @Query(+        "UPDATE StoredMessage SET decryptedBody = :body, decryptedSubject = :subject, " ++            "verifiedSigner = :verified WHERE id = :id",+    )+    suspend fun storeDecrypted(id: String, body: String, subject: String, verified: String?)++    @Query("DELETE FROM StoredMessage WHERE id = :id")+    suspend fun delete(id: String)+}++@Dao+interface KeyDao {+    @Query("SELECT * FROM CachedKey WHERE address = :address LIMIT 1")+    suspend fun get(address: String): CachedKey?++    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun upsert(key: CachedKey)+}++@Dao+interface OutboxDao {+    @Query("SELECT * FROM OutboxMessage ORDER BY createdMillis ASC")+    suspend fun all(): List<OutboxMessage>++    @Query("SELECT COUNT(*) FROM OutboxMessage")+    fun observeCount(): Flow<Int>++    @Insert+    suspend fun insert(entry: OutboxMessage): Long++    @Query("DELETE FROM OutboxMessage WHERE rowId = :rowId")+    suspend fun delete(rowId: Long)++    @Query("UPDATE OutboxMessage SET lastError = :error, attemptCount = attemptCount + 1 WHERE rowId = :rowId")+    suspend fun noteAttempt(rowId: Long, error: String)+}++@Database(+    entities = [StoredMessage::class, CachedKey::class, OutboxMessage::class],+    version = 1,+    exportSchema = false,+)+abstract class MailDatabase : RoomDatabase() {+    abstract fun messageDao(): MessageDao+    abstract fun keyDao(): KeyDao+    abstract fun outboxDao(): OutboxDao++    companion object : DatabaseMigrations {+        override val migrations: List<Migration> = emptyList()+    }+}
securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.ktnew file mode 100644index 0000000000..18601e0132--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailRepository.kt@@ -0,0 +1,24 @@+package com.vayunmathur.securemail.data++import android.content.Context+import com.vayunmathur.library.room.RoomRepository++/**+ * Process-wide mail database holder. Concern logic lives in the ViewModel and+ * the socket layer; this class only owns the singleton and exposes DAO access.+ */+class MailRepository private constructor(context: Context) :+    RoomRepository<MailDatabase>(context, MailDatabase::class, "securemail-db") {++    fun messageDao(): MessageDao = db.messageDao()+    fun keyDao(): KeyDao = db.keyDao()+    fun outboxDao(): OutboxDao = db.outboxDao()++    companion object {+        @Volatile private var instance: MailRepository? = null+        fun get(context: Context): MailRepository =+            instance ?: synchronized(this) {+                instance ?: MailRepository(context).also { instance = it }+            }+    }+}
securemail/src/main/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicy.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicy.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicy.ktnew file mode 100644index 0000000000..ce46aaf31d--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicy.kt@@ -0,0 +1,108 @@+package com.vayunmathur.securemail.domain.mail++/**+ * Pure recipient-key lookup + fallback decision (no Android imports, fully+ * unit-testable).+ *+ * Key discovery is Web Key Directory only (RFC 7929):+ *   1. own relay directory over the live socket for `@maemail.org` (which the+ *      server also serves as WKD at+ *      `https://mail.maemail.org/.well-known/openpgpkey/...`, so external+ *      clients discover us the same way), plus the local vault cache;+ *   2. WKD (advanced then direct method) for every external address —+ *      Proton serves it on `proton.me`, Gmail and others on their own domains;+ *   3. unencrypted fallback with explicit per-message opt-in when WKD has no key.+ *+ * Never silently downgrade: an address that previously had a key requires an+ * explicit key-change acknowledgement before sending to a new key.+ */+object KeyLookupPolicy {++    /** Where a recipient's usable public key came from, or why there is none. */+    sealed interface KeySource {+        data object OwnDirectory : KeySource+        data object Wkd : KeySource+        data object Cached : KeySource+        data object None : KeySource+    }++    /** Trust state of one recipient for the compose screen. */+    data class RecipientTrust(+        val address: String,+        val hasKey: Boolean,+        val source: KeySource,+        val fingerprintHex: String? = null,+        /** True when the cached fingerprint differs from the directory's. */+        val keyChanged: Boolean = false,+        /** True when a previous key existed but none is found now. */+        val keyLost: Boolean = false,+    )++    /** Send-gate decision for the current recipient set. */+    sealed interface SendDecision {+        /** Every recipient has a usable key — send encrypted. */+        data object Encrypted : SendDecision+        /**+         * Some recipients lack keys. [missing] lists them; the caller must+         * obtain explicit per-message opt-in before sending unencrypted.+         */+        data class NeedsUnencryptedOptIn(val missing: List<String>) : SendDecision+        /** A known key changed — the user must acknowledge before sending. */+        data class NeedsKeyChangeAck(val changed: List<RecipientTrust>) : SendDecision+    }++    fun decide(recipients: List<RecipientTrust>): SendDecision {+        val changed = recipients.filter { it.keyChanged || it.keyLost }+        if (changed.isNotEmpty()) return SendDecision.NeedsKeyChangeAck(changed)+        val missing = recipients.filter { !it.hasKey }.map { it.address }+        return if (missing.isEmpty()) SendDecision.Encrypted+        else SendDecision.NeedsUnencryptedOptIn(missing)+    }++    /**+     * WKD lookup URLs for [address] (RFC 7929): the advanced method+     * (`openpgpkey.<domain>`) first, then the direct method (`<domain>`).+     * The local part is lowercased, SHA-1 hashed, and z-base-32 encoded.+     * Proton serves WKD on `proton.me` for `@proton.me` / `@protonmail.com`.+     */+    fun wkdUrls(address: String): List<String> {+        val at = address.lastIndexOf('@')+        if (at <= 0) return emptyList()+        val local = address.substring(0, at).lowercase()+        val domain = address.substring(at + 1).lowercase()+        if (local.isEmpty() || domain.isEmpty()) return emptyList()+        val hash = wkdHash(local)+        return listOf(+            "https://openpgpkey.$domain/.well-known/openpgpkey/$domain/hu/$hash",+            "https://$domain/.well-known/openpgpkey/hu/$hash",+        )+    }++    /** Single (direct-method) WKD URL, for callers that try only one. */+    fun wkdUrl(address: String): String? = wkdUrls(address).lastOrNull()++    internal fun wkdHash(local: String): String {+        val sha1 = java.security.MessageDigest.getInstance("SHA-1")+        val digest = sha1.digest(local.toByteArray(Charsets.UTF_8))+        return zBase32(digest)+    }++    // RFC 7929 z-base-32 alphabet.+    private const val ZBASE32 = "ybndrfg8ejkmcpqxot1uwisza345h769"++    internal fun zBase32(bytes: ByteArray): String {+        val out = StringBuilder()+        var buffer = 0+        var bits = 0+        for (b in bytes) {+            buffer = (buffer shl 8) or (b.toInt() and 0xFF)+            bits += 8+            while (bits >= 5) {+                bits -= 5+                out.append(ZBASE32[(buffer shr bits) and 31])+            }+        }+        if (bits > 0) out.append(ZBASE32[(buffer shl (5 - bits)) and 31])+        return out.toString()+    }+}
securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MailPolicy.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MailPolicy.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MailPolicy.ktnew file mode 100644index 0000000000..9f80a25021--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MailPolicy.kt@@ -0,0 +1,65 @@+package com.vayunmathur.securemail.domain.mail++import kotlinx.serialization.Serializable++/**+ * Pure address + envelope validation (no Android imports). Own-domain addresses+ * end in @maemail.org; external addresses federate via SMTP with an encryption+ * fallback decided by [KeyLookupPolicy].+ */+object AddressValidator {++    const val OWN_DOMAIN = "maemail.org"++    private val LOCAL_PART = Regex("^[a-z0-9][a-z0-9._-]{1,62}[a-z0-9]$")+    private val EMAIL = Regex("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$")++    /** True for a claimable own-domain local part (lowercased, 3–64 chars). */+    fun isClaimableLocalPart(local: String): Boolean =+        local.length in 3..64 && LOCAL_PART.matches(local.lowercase())++    /** Canonical own-domain address for a local part, or null when invalid. */+    fun canonicalAddress(local: String): String? {+        val clean = local.trim().lowercase()+        return if (isClaimableLocalPart(clean)) "$clean@$OWN_DOMAIN" else null+    }++    /** True for any syntactically valid email address (own or external). */+    fun isValidAddress(address: String): Boolean =+        EMAIL.matches(address.trim()) && address.trim().length <= 254++    /** True when [address] belongs to this relay's domain. */+    fun isOwnDomain(address: String): Boolean =+        address.trim().substringAfterLast('@', "").lowercase() == OWN_DOMAIN++    /** Splits a comma/semicolon recipient line into trimmed non-empty addresses. */+    fun parseRecipients(line: String): List<String> =+        line.split(',', ';', '\n').map { it.trim() }.filter { it.isNotEmpty() }+}++/**+ * Envelope metadata for one message. The server stores the envelope + opaque+ * PGP/MIME blob only — never plaintext subject/body. See the Phase 0 wire spec.+ */+@Serializable+data class MessageEnvelope(+    val id: String,+    val from: String,+    val to: List<String>,+    val dateMillis: Long,+    val messageId: String,+    /** Present only for own messages composed unencrypted (fallback opt-in). */+    val unencrypted: Boolean = false,+    val sizeBytes: Long = 0,+    val fetched: Boolean = false,+)++/** Per-recipient send outcome returned by the relay. */+@Serializable+data class SendStatus(+    val recipient: String,+    val queued: Boolean,+    /** "relay" (own-domain live/queued), "federated" (SMTP out), "held". */+    val path: String,+    val detail: String = "",+)
securemail/src/main/java/com/vayunmathur/securemail/domain/pgp/PgpCrypto.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/pgp/PgpCrypto.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/pgp/PgpCrypto.ktnew file mode 100644index 0000000000..c18c4494f2--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/pgp/PgpCrypto.kt@@ -0,0 +1,58 @@+package com.vayunmathur.securemail.domain.pgp++import com.vayunmathur.e2ee.Pgp++/**+ * OpenPGP facade for SecureMail. All crypto runs in the native Rust core+ * ([Pgp] in `:library:e2ee-p2p`, rPGP) — no BouncyCastle anywhere.+ *+ * Suite: Ed25519 signing primary + X25519 encryption subkey, AES-256 session+ * keys, SHA-512 digests. Keys cross as ASCII armor; the relay wire carries raw+ * bytes and converts at the boundary only, mirroring the FindFamily relay+ * contract.+ */+object PgpCrypto {++    /** A generated identity: armored secret ring (passphrase-wrapped) + armored public ring. */+    data class Identity(+        val armoredSecret: String,+        val armoredPublic: String,+        val fingerprintHex: String,+    )++    /**+     * Generates an Ed25519 primary + X25519 encryption subkey for [userId]+     * (e.g. "alice <[email protected]>"). The secret key material is wrapped+     * with [passphrase] via S2K so the stored blob alone is useless.+     */+    fun generateIdentity(userId: String, passphrase: String): Identity {+        val native = Pgp.generateIdentity(userId, passphrase)+        return Identity(+            armoredSecret = native.armoredSecret,+            armoredPublic = native.armoredPublic,+            fingerprintHex = native.fingerprintHex,+        )+    }++    /** Fingerprint hex (uppercase, no spaces) of an armored public key. */+    fun fingerprintHex(armoredPublic: String): String =+        Pgp.fingerprintHex(armoredPublic)++    /**+     * Encrypts [plaintext] (raw message bytes, e.g. a PGP/MIME body) to the+     * holder of [armoredPublic]. Returns raw (unarmored) PGP bytes for the+     * relay wire; armor for SMTP federation.+     */+    fun encrypt(plaintext: ByteArray, armoredPublic: String): ByteArray =+        Pgp.encrypt(armoredPublic, plaintext)++    /**+     * Decrypts raw PGP bytes with [armoredSecret] + [passphrase]. Returns the+     * literal payload.+     */+    fun decrypt(ciphertext: ByteArray, armoredSecret: String, passphrase: String): ByteArray =+        Pgp.decrypt(armoredSecret, passphrase, ciphertext)++    /** Armors raw PGP bytes as a `PGP MESSAGE` block (for SMTP federation). */+    fun armorMessage(raw: ByteArray): String = Pgp.armorMessage(raw)+}
securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt b/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.ktnew file mode 100644index 0000000000..8909512f4b--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/network/MailSocket.kt@@ -0,0 +1,380 @@+package com.vayunmathur.securemail.network++import com.vayunmathur.library.log.Log+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.WebSocketClient+import com.vayunmathur.library.network.WsSession+import com.vayunmathur.library.network.webSocket+import java.util.concurrent.ConcurrentHashMap+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import kotlinx.coroutines.withTimeoutOrNull+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Live-socket mail relay, mirroring FindFamily's binary wire design:+ *+ * ```+ * client→server SUB     : [0x01][u16 addrLen][address UTF-8][armored public key…]+ * client→server PUB     : [0x02][flags][u16 rcptLen][recipient UTF-8][raw PGP/MIME…]+ * client→server GETKEY  : [0x04][u16 addrLen][address UTF-8]+ * client→server FETCH   : [0x06][u16 idLen][message id UTF-8]+ * server→client MSG     : [0x03][flags][u32 blobLen][message id UTF-8][raw PGP/MIME…]+ * server→client KEYRESP : [0x05][status][u16 addrLen][address UTF-8][armored public key…]+ * server→client FETCHED : [0x07][u16 idLen][message id UTF-8][u32 blobLen][raw PGP/MIME…]+ * ```+ *+ * flags bit0: 0 = encrypted PGP/MIME, 1 = unencrypted fallback (explicit opt-in only).+ * KEYRESP status: 0 = none, 1 = found (key follows).+ *+ * SUB doubles as registration (address claim + public-key publish), exactly like+ * FindFamily's SUB-carries-bundle: a socket-only client never needs separate+ * HTTP register/getkey endpoints. The server fans out to live subscribers and+ * durably queues for offline recipients; each SUB drains the recipient's backlog.+ *+ * Everything on the wire is framed binary — no JSON, no base64 — converted only+ * at the HTTP-federation boundary server-side and the DB boundary client-side.+ */+object MailSocket {++    const val WS_URL = "wss://mail.maemail.org/mail/ws"++    const val OP_SUB: Byte = 0x01+    const val OP_PUB: Byte = 0x02+    const val OP_MSG: Byte = 0x03+    const val OP_GETKEY_REQ: Byte = 0x04+    const val OP_GETKEY_RESP: Byte = 0x05+    const val OP_FETCH_REQ: Byte = 0x06+    const val OP_FETCH_RESP: Byte = 0x07++    const val FLAG_PLAIN: Byte = 0x01++    const val KEY_NONE = 0+    const val KEY_FOUND = 1++    const val GETKEY_TIMEOUT_MS = 8_000L+    const val FETCH_TIMEOUT_MS = 15_000L+    const val PING_INTERVAL_MS = 30_000L+    const val LIVENESS_TIMEOUT_MS = 75_000L++    private const val BACKOFF_INITIAL_MS = 1_000L+    private const val BACKOFF_MAX_MS = 30_000L++    private const val TAG = "MailSocket"++    val json: Json = Json { ignoreUnknownKeys = true }++    /** In-flight key lookups keyed by lowercase address, completed on KEYRESP. */+    internal val pendingKeys = ConcurrentHashMap<String, CompletableDeferred<KeyResult?>>()++    /** In-flight fetches keyed by message id, completed on FETCHED. */+    internal val pendingFetches = ConcurrentHashMap<String, CompletableDeferred<ByteArray?>>()++    @Volatile internal var session: WsSession? = null+    private var loop: Job? = null++    val connected: Boolean get() = session != null++    data class KeyResult(val address: String, val armoredPublic: String?)++    /**+     * Start (no-op if running) the persistent relay loop. [identity] supplies the+     * address + public key for every (re)SUB so registration self-heals.+     * [onMessage] receives each inbound MSG frame's (id, flags, raw blob);+     * [onBump] fires on any inbound frame to refresh UI/sync state.+     */+    @Synchronized+    fun start(+        scope: CoroutineScope,+        identity: suspend () -> IdentitySnapshot?,+        onMessage: suspend (id: String, unencrypted: Boolean, raw: ByteArray) -> Unit,+        onBump: () -> Unit = {},+    ) {+        if (loop?.isActive == true) return+        stop()+        loop = scope.launch(Dispatchers.IO) {+            val outer = this+            var backoff = BACKOFF_INITIAL_MS+            while (isActive) {+                val conn = CoroutineScope(Dispatchers.IO + Job())+                runCatching {+                    // mail.maemail.org is a pinned first-party host → platform trust is+                    // wrong here; the app inits NetworkClient with FIRST_PARTY.+                    webSocket(WS_URL) {+                        session = this+                        val id = identity()+                        if (id == null) {+                            Log.status(TAG, "no identity; waiting for onboarding")+                            delay(BACKOFF_MAX_MS)+                            return@webSocket+                        }+                        send(subFrame(id.address, id.armoredPublic))+                        backoff = BACKOFF_INITIAL_MS+                        supervise(conn, outer, onMessage, onBump)+                    }+                }.onFailure { Log.status(TAG, "relay loop error", it) }+                conn.cancel()+                session = null+                pendingKeys.values.forEach { it.complete(null) }+                pendingKeys.clear()+                pendingFetches.values.forEach { it.complete(null) }+                pendingFetches.clear()+                if (!isActive) break+                delay(backoff)+                backoff = (backoff * 2).coerceAtMost(BACKOFF_MAX_MS)+            }+        }+    }++    @Synchronized+    fun stop() {+        loop?.cancel(); loop = null; session = null+        pendingKeys.values.forEach { it.complete(null) }+        pendingKeys.clear()+        pendingFetches.values.forEach { it.complete(null) }+        pendingFetches.clear()+    }++    /** Publish an already-encrypted PGP/MIME blob to [recipient]. False when offline. */+    suspend fun publish(recipient: String, raw: ByteArray, unencrypted: Boolean = false): Boolean {+        val s = session ?: return false+        return runCatching {+            s.send(pubFrame(recipient, raw, unencrypted))+            true+        }.onFailure { Log.status(TAG, "publish failed", it) }.getOrDefault(false)+    }++    /** Directory lookup over the socket (request/response with timeout). */+    suspend fun getKey(address: String): KeyResult? {+        val s = session ?: return null+        val key = address.lowercase()+        val deferred = CompletableDeferred<KeyResult?>()+        pendingKeys[key] = deferred+        return try {+            s.send(getKeyFrame(address))+            withTimeoutOrNull(GETKEY_TIMEOUT_MS) { deferred.await() }+        } catch (e: Exception) {+            Log.status(TAG, "getKey failed for $address", e)+            null+        } finally {+            pendingKeys.remove(key)+        }+    }++    /** Fetch one backlog message's blob by id (for missed fan-outs / fresh devices). */+    suspend fun fetch(id: String): ByteArray? {+        val s = session ?: return null+        val deferred = CompletableDeferred<ByteArray?>()+        pendingFetches[id] = deferred+        return try {+            s.send(fetchFrame(id))+            withTimeoutOrNull(FETCH_TIMEOUT_MS) { deferred.await() }+        } catch (e: Exception) {+            Log.status(TAG, "fetch failed for $id", e)+            null+        } finally {+            pendingFetches.remove(id)+        }+    }++    // ------------------------------------------------------------------+    // Session internals+    // ------------------------------------------------------------------++    data class IdentitySnapshot(val address: String, val armoredPublic: String)++    private suspend fun WsSession.supervise(+        conn: CoroutineScope,+        outer: CoroutineScope,+        onMessage: suspend (id: String, unencrypted: Boolean, raw: ByteArray) -> Unit,+        onBump: () -> Unit,+    ) {+        var lastInbound = System.currentTimeMillis()+        conn.launch {+            runCatching {+                incoming.collect { frame ->+                    lastInbound = System.currentTimeMillis()+                    if (frame is WebSocketClient.WsFrame.Binary) {+                        dispatch(frame.bytes, onMessage)+                    }+                    runCatching { onBump() }+                }+            }+        }+        try {+            while (outer.isActive) {+                conn.launch { runCatching { ping() } }+                delay(PING_INTERVAL_MS)+                if (System.currentTimeMillis() - lastInbound > LIVENESS_TIMEOUT_MS) {+                    Log.status(TAG, "socket half-open, reconnecting")+                    break+                }+            }+        } finally {+            runCatching { abort() }+            conn.cancel()+        }+    }++    internal suspend fun dispatch(+        buf: ByteArray,+        onMessage: suspend (id: String, unencrypted: Boolean, raw: ByteArray) -> Unit,+    ) {+        when (buf.firstOrNull()) {+            OP_MSG -> {+                val parsed = parseMsg(buf) ?: return+                onMessage(parsed.first, parsed.second, parsed.third)+            }+            OP_GETKEY_RESP -> parseKeyResp(buf)?.let { (addr, key) ->+                pendingKeys.remove(addr.lowercase())?.complete(KeyResult(addr, key))+            }+            OP_FETCH_RESP -> parseFetched(buf)?.let { (id, raw) ->+                pendingFetches.remove(id)?.complete(raw)+            }+            else -> Unit+        }+    }++    // ------------------------------------------------------------------+    // Framing+    // ------------------------------------------------------------------++    internal fun subFrame(address: String, armoredPublic: String): ByteArray {+        val addr = address.lowercase().toByteArray(Charsets.UTF_8)+        val key = armoredPublic.toByteArray(Charsets.UTF_8)+        val out = ByteArray(1 + 2 + addr.size + key.size)+        out[0] = OP_SUB+        putU16(out, 1, addr.size)+        addr.copyInto(out, 3)+        key.copyInto(out, 3 + addr.size)+        return out+    }++    internal fun pubFrame(recipient: String, raw: ByteArray, unencrypted: Boolean): ByteArray {+        val rcpt = recipient.lowercase().toByteArray(Charsets.UTF_8)+        val out = ByteArray(1 + 1 + 2 + rcpt.size + raw.size)+        out[0] = OP_PUB+        out[1] = if (unencrypted) FLAG_PLAIN else 0+        putU16(out, 2, rcpt.size)+        rcpt.copyInto(out, 4)+        raw.copyInto(out, 4 + rcpt.size)+        return out+    }++    internal fun getKeyFrame(address: String): ByteArray {+        val addr = address.lowercase().toByteArray(Charsets.UTF_8)+        val out = ByteArray(1 + 2 + addr.size)+        out[0] = OP_GETKEY_REQ+        putU16(out, 1, addr.size)+        addr.copyInto(out, 3)+        return out+    }++    internal fun fetchFrame(id: String): ByteArray {+        val raw = id.toByteArray(Charsets.UTF_8)+        val out = ByteArray(1 + 2 + raw.size)+        out[0] = OP_FETCH_REQ+        putU16(out, 1, raw.size)+        raw.copyInto(out, 3)+        return out+    }++    /** MSG: [0x03][flags][u32 blobLen][id UTF-8][raw…] → (id, unencrypted, raw). */+    internal fun parseMsg(buf: ByteArray): Triple<String, Boolean, ByteArray>? {+        if (buf.size < 1 + 1 + 4 + 2) return null+        val unencrypted = (buf[1].toInt() and 0xFF) != 0+        val idLen = readU32(buf, 2)+        if (idLen < 0 || buf.size < 6 + idLen) return null+        val id = buf.copyOfRange(6, 6 + idLen).toString(Charsets.UTF_8)+        val raw = buf.copyOfRange(6 + idLen, buf.size)+        return Triple(id, unencrypted, raw)+    }++    /** KEYRESP: [0x05][status][u16 addrLen][address][key…] → (address, key?). */+    internal fun parseKeyResp(buf: ByteArray): Pair<String, String?>? {+        if (buf.size < 1 + 1 + 2) return null+        val status = buf[1].toInt()+        val addrLen = readU16(buf, 2)+        if (buf.size < 4 + addrLen) return null+        val addr = buf.copyOfRange(4, 4 + addrLen).toString(Charsets.UTF_8)+        val key = if (status == KEY_FOUND && buf.size > 4 + addrLen) {+            buf.copyOfRange(4 + addrLen, buf.size).toString(Charsets.UTF_8)+        } else {+            null+        }+        return addr to key+    }++    /** FETCHED: [0x07][u16 idLen][id][raw…] → (id, raw). */+    internal fun parseFetched(buf: ByteArray): Pair<String, ByteArray>? {+        if (buf.size < 1 + 2) return null+        val idLen = readU16(buf, 1)+        if (buf.size < 3 + idLen) return null+        val id = buf.copyOfRange(3, 3 + idLen).toString(Charsets.UTF_8)+        return id to buf.copyOfRange(3 + idLen, buf.size)+    }++    internal fun putU16(dst: ByteArray, off: Int, v: Int) {+        dst[off] = (v shr 8).toByte()+        dst[off + 1] = v.toByte()+    }++    internal fun readU16(src: ByteArray, off: Int): Int =+        ((src[off].toInt() and 0xFF) shl 8) or (src[off + 1].toInt() and 0xFF)++    internal fun readU32(src: ByteArray, off: Int): Int =+        ((src[off].toInt() and 0xFF) shl 24) or+            ((src[off + 1].toInt() and 0xFF) shl 16) or+            ((src[off + 2].toInt() and 0xFF) shl 8) or+            (src[off + 3].toInt() and 0xFF)+}++/** Minimal REST surface: WKD runs over plain HTTPS, not the relay socket. */+object KeyLookupHttp {+    suspend fun fetchText(url: String, useSystemTrust: Boolean): String? {+        return try {+            val r = NetworkClient.performRequest(+                url = url,+                useSystemTrust = useSystemTrust,+            )+            if (r.isSuccess) r.body else null+        } catch (_: Exception) {+            null+        }+    }++    /**+     * Fetches a WKD key record (binary OpenPGP key, possibly armored) and+     * returns it as canonical armor text via the native normalizer. WKD+     * responses are the raw key bytes, not JSON.+     */+    suspend fun fetchWkdKey(url: String): String? {+        return try {+            val r = NetworkClient.execute(+                url = url,+                useSystemTrust = true,+            )+            if (!r.isSuccess || r.bytes.isEmpty()) return null+            runCatching { com.vayunmathur.e2ee.Pgp.normalizeKey(r.bytes) }.getOrNull()+        } catch (_: Exception) {+            null+        }+    }+}++/** Federation DTOs shared with the server's /mail/v1 HTTP surface (Phase 2 SMTP). */+@Serializable+data class FederatedSendRequest(+    val from: String,+    val toExternal: List<String>,+    /** Armored PGP/MIME for key-known externals; null entries send clear. */+    val armoredBodies: List<String?>,+    val subject: String,+)
securemail/src/main/java/com/vayunmathur/securemail/platform/BootReceiver.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/BootReceiver.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/BootReceiver.ktnew file mode 100644index 0000000000..fd60fbea43--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/BootReceiver.kt@@ -0,0 +1,21 @@+package com.vayunmathur.securemail.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.securemail.data.MailConfig+import com.vayunmathur.securemail.service.MailSocketService+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch++/** Restarts the relay socket after boot/package-replace when an identity exists. */+class BootReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        CoroutineScope(Dispatchers.IO).launch {+            val settings = MailConfig(context).settings.first()+            if (settings.address.isNotBlank()) MailSocketService.start(context)+        }+    }+}
securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.ktnew file mode 100644index 0000000000..3e299628cc--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailSyncWorker.kt@@ -0,0 +1,74 @@+package com.vayunmathur.securemail.platform++import android.content.Context+import androidx.work.CoroutineWorker+import androidx.work.WorkerParameters+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.work.startRepeatedTask+import com.vayunmathur.securemail.data.MailConfig+import com.vayunmathur.securemail.data.MailRepository+import com.vayunmathur.securemail.network.MailSocket+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.first+import kotlin.time.Duration.Companion.minutes++/**+ * Periodic backstop behind the live socket: while the app is backgrounded+ * without the foreground service, this worker opens a short socket session to+ * drain backlog (SUB → MSG drain → close). No-ops without an identity.+ */+class MailSyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {++    override suspend fun doWork(): Result {+        val settings = MailConfig(applicationContext).settings.first()+        if (settings.address.isBlank()) return Result.success()+        if (MailSocket.connected) return Result.success()+        return try {+            var drained = 0+            // A dedicated scope for the short drain session (the worker's own+            // coroutine must stay free to enforce the delay/stop below).+            val drainScope = CoroutineScope(Dispatchers.IO + SupervisorJob())+            MailSocket.start(+                scope = drainScope,+                identity = {+                    MailSocket.IdentitySnapshot(settings.address, settings.publicArmor)+                },+                onMessage = { id, unencrypted, raw ->+                    val repo = MailRepository.get(applicationContext)+                    repo.messageDao().upsert(+                        com.vayunmathur.securemail.data.StoredMessage(+                            id = id,+                            from = "",+                            toJson = "[\"${settings.address}\"]",+                            dateMillis = System.currentTimeMillis(),+                            messageId = id,+                            blobBase64 = android.util.Base64.encodeToString(raw, android.util.Base64.NO_WRAP),+                            unencrypted = unencrypted,+                        ),+                    )+                    drained+++                },+            )+            kotlinx.coroutines.delay(20_000)+            MailSocket.stop()+            drainScope.cancel()+            Log.dev(TAG, "sync worker drained $drained")+            Result.success()+        } catch (e: Exception) {+            Log.status(TAG, "sync worker failed", e)+            Result.retry()+        }+    }++    companion object {+        private const val TAG = "MailSyncWorker"+        private const val WORK_NAME = "securemail_sync"++        fun schedule(context: Context) {+            startRepeatedTask<MailSyncWorker>(context, WORK_NAME, 15.minutes)+        }+    }+}
securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.ktnew file mode 100644index 0000000000..dbf6fa6e07--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt@@ -0,0 +1,538 @@+package com.vayunmathur.securemail.platform++import android.app.Application+import android.util.Base64+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.fragment.app.FragmentActivity+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.biometric.unlockDatabaseWithBiometrics+import com.vayunmathur.library.log.Log+import com.vayunmathur.securemail.data.CachedKey+import com.vayunmathur.securemail.data.MailConfig+import com.vayunmathur.securemail.data.MailRepository+import com.vayunmathur.securemail.data.OutboxMessage+import com.vayunmathur.securemail.data.StoredMessage+import com.vayunmathur.securemail.domain.mail.AddressValidator+import com.vayunmathur.securemail.domain.mail.KeyLookupPolicy+import com.vayunmathur.securemail.domain.mail.MessageEnvelope+import com.vayunmathur.securemail.domain.pgp.PgpCrypto+import com.vayunmathur.securemail.network.KeyLookupHttp+import com.vayunmathur.securemail.network.MailSocket+import com.vayunmathur.securemail.platform.crypto.KeyManager+import com.vayunmathur.securemail.service.MailSocketService+import java.util.UUID+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.launchIn+import kotlinx.coroutines.flow.onEach+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/** Aggregate UI state for SecureMail. */+data class MailUiState(+    val onboarded: Boolean = false,+    val locked: Boolean = true,+    val address: String = "",+    val fingerprintHex: String = "",+    val socketConnected: Boolean = false,+    val message: String? = null,+    val error: String? = null,+    val busy: Boolean = false,+    /** Exported public key awaiting user copy/share (Settings). */+    val exportArmor: String? = null,+    /** True when the in-memory key passphrase was lost (process restart). */+    val needsPassphrase: Boolean = false,+)++private const val TAG = "MailViewModel"++/**+ * Owns identity, decryption, send gating, and the socket lifecycle.+ * Decrypt + private-key reads happen on Dispatchers.IO and only while unlocked.+ */+class MailViewModel(app: Application) : AndroidViewModel(app) {++    private val config = MailConfig(app)+    private val keyManager = KeyManager(app)+    private val repo: MailRepository = MailRepository.get(app)++    var state by mutableStateOf(+        MailUiState(+            onboarded = keyManager.hasIdentity(),+            locked = keyManager.hasIdentity(),+        ),+    )+        private set++    val messages = repo.messageDao().observeAll()+    val outboxCount = repo.outboxDao().observeCount()++    /**+     * In-memory S2K passphrase for the PGP secret ring. Set at claim time and+     * re-entered on the Lock screen after process death; never persisted — the+     * Keystore holds only the S2K-wrapped blob, so a DB dump alone is useless.+     */+    private var passphraseCache: String? = null++    init {+        config.settings+            .onEach { s ->+                state = state.copy(+                    address = s.address,+                    fingerprintHex = s.fingerprintHex,+                    onboarded = s.isConfigured,+                    locked = if (!s.isConfigured) false else state.locked,+                )+            }+            .launchIn(viewModelScope)+    }++    // ------------------------------------------------------------------+    // Identity: claim + unlock+    // ------------------------------------------------------------------++    /** Generates the PGP identity, claims the address over the socket, persists. */+    fun claimAddress(localPart: String, passphrase: String) {+        val address = AddressValidator.canonicalAddress(localPart)+        if (address == null) {+            state = state.copy(error = "Use 3–64 lowercase letters, digits, dots or dashes.")+            return+        }+        if (passphrase.length < 8) {+            state = state.copy(error = "Use a passphrase of at least 8 characters.")+            return+        }+        state = state.copy(busy = true, error = null, message = "Generating your key…")+        viewModelScope.launch {+            val outcome = withContext(Dispatchers.IO) {+                runCatching {+                    val identity = PgpCrypto.generateIdentity(+                        "$address <$address>",+                        passphrase,+                    )+                    keyManager.storeSecretArmor(identity.armoredSecret)+                    keyManager.storeOwnAddress(address)+                    config.setIdentity(address, identity.armoredPublic, identity.fingerprintHex)+                    passphraseCache = passphrase+                    // Registration rides the first SUB; the service connects now.+                    MailSocketService.start(getApplication())+                    address+                }+            }+            state = outcome.fold(+                onSuccess = {+                    state.copy(+                        busy = false, locked = false, onboarded = true,+                        message = "Address $it claimed. Share your public key from Settings.",+                    )+                },+                onFailure = {+                    Log.status(TAG, "claim failed", it)+                    state.copy(busy = false, error = it.message ?: "Key generation failed.")+                },+            )+        }+    }++    /**+     * First unlock attempt from MainActivity: if no identity exists there is+     * nothing to gate; otherwise prompt biometrics before composition starts.+     */+    fun unlockIfReady(+        activity: FragmentActivity,+        onUnlocked: () -> Unit,+        onLocked: () -> Unit,+    ) {+        if (!keyManager.hasIdentity()) {+            state = state.copy(locked = false, onboarded = false)+            onUnlocked()+            return+        }+        unlockDatabaseWithBiometrics(+            activity,+            onSuccess = {+                state = state.copy(locked = false)+                onUnlocked()+            },+            onFailure = { message ->+                state = state.copy(+                    locked = true,+                    error = message ?: "Unlock to read your mail.",+                )+                onLocked()+            },+        )+    }++    /** Manual unlock from the Lock screen. */+    fun unlock(activity: FragmentActivity) {+        unlockDatabaseWithBiometrics(+            activity,+            onSuccess = { state = state.copy(locked = false, error = null) },+            onFailure = { message ->+                state = state.copy(error = message ?: "Unlock to read your mail.")+            },+        )+    }++    fun exportPublicKey() {+        viewModelScope.launch {+            // The public half was persisted in the clear at claim time (MailConfig) —+            // it is public by design, so no key unwrapping needed.+            val armor = withContext(Dispatchers.IO) {+                runCatching {+                    config.settings.first().publicArmor.ifBlank { null }+                }.getOrNull()+            }+            state = state.copy(exportArmor = armor, error = armor?.let { null } ?: "Unlock first.")+        }+    }++    fun forgetIdentity() {+        viewModelScope.launch {+            MailSocket.stop()+            keyManager.clear()+            config.clear()+            state = MailUiState()+        }+    }++    // ------------------------------------------------------------------+    // Inbound: store + decrypt+    // ------------------------------------------------------------------++    /** Called by the socket layer for every MSG frame (already in Dispatchers.IO). */+    suspend fun onInboundMessage(id: String, unencrypted: Boolean, raw: ByteArray) {+        // Sender/from is inside the encrypted payload; store now, label on decrypt.+        repo.messageDao().upsert(+            StoredMessage(+                id = id,+                from = "",+                toJson = "[\"${state.address}\"]",+                dateMillis = System.currentTimeMillis(),+                messageId = id,+                blobBase64 = Base64.encodeToString(raw, Base64.NO_WRAP),+                unencrypted = unencrypted,+            ),+        )+        decryptStored(id)+    }++    /** Decrypts one stored message in memory; never writes plaintext to the server. */+    fun decryptStored(id: String) {+        viewModelScope.launch {+            withContext(Dispatchers.IO) {+                runCatching {+                    val stored = repo.messageDao().get(id) ?: return@runCatching+                    if (stored.decryptedBody != null || stored.unencrypted) return@runCatching+                    val passphrase = passphraseCache+                    if (passphrase == null) {+                        state = state.copy(needsPassphrase = true)+                        Log.status(TAG, "decrypt deferred: passphrase cache empty")+                        return@runCatching+                    }+                    val raw = Base64.decode(stored.blobBase64, Base64.NO_WRAP)+                    val mime = PgpCrypto.decrypt(raw, keyManager.getSecretArmor(), passphrase)+                        .toString(Charsets.UTF_8)+                    val (subject, body, from) = parseMime(mime)+                    repo.messageDao().storeDecrypted(id, body, subject, verified = null)+                    if (from.isNotBlank()) {+                        repo.messageDao().upsert(stored.copy(from = from))+                    }+                }.onFailure { Log.status(TAG, "decryptStored failed", it) }+            }+        }+    }++    /**+     * Re-enters the S2K passphrase after process death (Lock screen). Verified+     * by a trial decrypt of nothing — it is checked lazily on next decrypt,+     * which fails closed and re-asks.+     */+    fun providePassphrase(passphrase: String) {+        passphraseCache = passphrase+        state = state.copy(needsPassphrase = false, error = null)+    }++    /** Plaintext fallback path: stores the body with the unencrypted flag set. */+    suspend fun onInboundPlaintext(id: String, from: String, subject: String, body: String) {+        repo.messageDao().upsert(+            StoredMessage(+                id = id,+                from = from,+                toJson = "[\"${state.address}\"]",+                dateMillis = System.currentTimeMillis(),+                messageId = id,+                blobBase64 = "",+                decryptedBody = body,+                decryptedSubject = subject,+                unencrypted = true,+            ),+        )+    }++    // ------------------------------------------------------------------+    // Outbound: trust gate + publish+    // ------------------------------------------------------------------++    /**+     * Resolves trust for every recipient: vault cache → live socket directory+     * (own domain) → WKD advanced/direct (external). No other discovery.+     */+    suspend fun resolveTrust(addresses: List<String>): List<KeyLookupPolicy.RecipientTrust> =+        withContext(Dispatchers.IO) {+            addresses.map { address ->+                val clean = address.trim().lowercase()+                val cached = repo.keyDao().get(clean)+                if (cached != null) {+                    return@map KeyLookupPolicy.RecipientTrust(+                        address = clean,+                        hasKey = true,+                        source = KeyLookupPolicy.KeySource.Cached,+                        fingerprintHex = cached.fingerprintHex,+                    )+                }+                // Own-domain directory over the live socket (the server also+                // serves this same key over WKD, so external clients agree).+                if (AddressValidator.isOwnDomain(clean)) {+                    val socketHit = runCatching { MailSocket.getKey(clean) }.getOrNull()+                    if (socketHit?.armoredPublic != null) {+                        cacheKey(clean, socketHit.armoredPublic, KeyLookupPolicy.KeySource.OwnDirectory)+                        return@map KeyLookupPolicy.RecipientTrust(+                            address = clean,+                            hasKey = true,+                            source = KeyLookupPolicy.KeySource.OwnDirectory,+                            fingerprintHex = runCatching {+                                PgpCrypto.fingerprintHex(socketHit.armoredPublic)+                            }.getOrNull(),+                        )+                    }+                }+                // External: WKD advanced then direct, over HTTPS with system trust.+                for (url in KeyLookupPolicy.wkdUrls(clean)) {+                    val wkd = KeyLookupHttp.fetchWkdKey(url)+                    if (wkd != null) {+                        cacheKey(clean, wkd, KeyLookupPolicy.KeySource.Wkd)+                        return@map KeyLookupPolicy.RecipientTrust(+                            address = clean,+                            hasKey = true,+                            source = KeyLookupPolicy.KeySource.Wkd,+                            fingerprintHex = runCatching { PgpCrypto.fingerprintHex(wkd) }.getOrNull(),+                        )+                    }+                }+                KeyLookupPolicy.RecipientTrust(clean, hasKey = false, source = KeyLookupPolicy.KeySource.None)+            }+        }++    private suspend fun cacheKey(address: String, armor: String, source: KeyLookupPolicy.KeySource) {+        val fingerprint = runCatching { PgpCrypto.fingerprintHex(armor) }.getOrNull() ?: return+        repo.keyDao().upsert(+            CachedKey(+                address = address,+                armoredPublic = armor,+                fingerprintHex = fingerprint,+                source = source.toString(),+                updatedMillis = System.currentTimeMillis(),+            ),+        )+    }++    /**+     * Sends a message: encrypts per-recipient on device, publishes over the live+     * socket when up, else queues to the outbox worker. Unencrypted send requires+     * [allowUnencrypted] (explicit per-message opt-in from Compose).+     */+    fun send(+        to: List<String>,+        subject: String,+        body: String,+        allowUnencrypted: Boolean,+        inReplyTo: String? = null,+    ) {+        state = state.copy(busy = true, error = null)+        viewModelScope.launch {+            val outcome = withContext(Dispatchers.IO) {+                runCatching {+                    val trust = resolveTrust(to)+                    when (val decision = KeyLookupPolicy.decide(trust)) {+                        is KeyLookupPolicy.SendDecision.NeedsKeyChangeAck ->+                            error("Key changed for ${decision.changed.first().address}. Review in Settings first.")+                        is KeyLookupPolicy.SendDecision.NeedsUnencryptedOptIn ->+            

Diff truncated.