Modern Apps git

← Modern-Apps.git

communicate: RCS full UP core and MLS E2EE

Commit
d7980018ac3d9539506244b56abef4a9d8f48b98
Author
vayun-mathur <[email protected]>
When
2026-09-24 22:56 UTC (2 months ago)
Parents
6fc5fbb

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 2b5d75c0cf..b528fc849e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -285,6 +285,26 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]]+name = "bindgen"+version = "0.72.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"+dependencies = [+ "bitflags 2.13.2",+ "cexpr",+ "clang-sys",+ "itertools 0.13.0",+ "log",+ "prettyplease",+ "proc-macro2",+ "quote",+ "regex",+ "rustc-hash",+ "shlex 1.3.0",+ "syn 2.0.119",+]+ [[package]] name = "bitfield-struct" version = "0.12.1"@@ -484,7 +504,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4" dependencies = [  "find-msvc-tools",- "shlex",+ "shlex 2.0.1", ]  [[package]]@@ -493,6 +513,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" +[[package]]+name = "cexpr"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"+dependencies = [+ "nom 7.1.3",+]+ [[package]] name = "cfg-if" version = "1.0.5"@@ -519,6 +548,7 @@ dependencies = [  "cfg-if",  "cipher 0.5.2",  "cpufeatures 0.3.1",+ "rand_core 0.10.1", ]  [[package]]@@ -595,6 +625,17 @@ dependencies = [  "inout 0.2.2", ] +[[package]]+name = "clang-sys"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"+dependencies = [+ "glob",+ "libc",+ "libloading",+]+ [[package]] name = "clap" version = "4.6.7"@@ -666,18 +707,34 @@ dependencies = [  "memchr", ] +[[package]]+name = "communicate_mls"+version = "0.1.0"+dependencies = [+ "ed25519-dalek",+ "getrandom 0.2.17",+ "jni",+ "openmls",+ "openmls_basic_credential",+ "openmls_memory_storage",+ "openmls_rust_crypto",+ "openmls_traits",+ "rand_core 0.6.4",+ "tls_codec",+]+ [[package]] name = "communicate_signal" version = "0.1.0" dependencies = [  "aes 0.8.4",- "curve25519-dalek",+ "curve25519-dalek 4.1.3",  "hmac 0.13.0",  "jni",  "rand_core 0.6.4",  "sha2 0.11.0",  "subtle",- "x25519-dalek",+ "x25519-dalek 2.0.1", ]  [[package]]@@ -704,6 +761,17 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]]+name = "core-models"+version = "0.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee3344d349528f449816cfa85e558c439bdca5a6d8a738cfb21e69f0b2b1952f"+dependencies = [+ "hax-lib",+ "pastey",+ "rand 0.10.3",+]+ [[package]] name = "core_detect" version = "1.0.0"@@ -734,6 +802,17 @@ dependencies = [  "libc", ] +[[package]]+name = "crabgrind"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc7459e07732f6de74001fcf73a3fdfbb0f368e4fd8e2392f4a2206a065e6e95"+dependencies = [+ "bindgen",+ "cc",+ "pkg-config",+]+ [[package]] name = "crc32fast" version = "1.5.2"@@ -848,7 +927,9 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [+ "getrandom 0.4.3",  "hybrid-array",+ "rand_core 0.10.1", ]  [[package]]@@ -886,7 +967,7 @@ dependencies = [  "ctr",  "ed25519-dalek",  "hex",- "hkdf",+ "hkdf 0.12.4",  "hmac 0.12.1",  "p256",  "rand 0.8.8",@@ -895,7 +976,7 @@ dependencies = [  "sec1",  "sha2 0.11.0",  "subtle",- "x25519-dalek",+ "x25519-dalek 2.0.1", ]  [[package]]@@ -926,12 +1007,26 @@ dependencies = [  "cpufeatures 0.2.17",  "curve25519-dalek-derive",  "digest 0.10.7",- "fiat-crypto",+ "fiat-crypto 0.2.9",  "rustc_version",  "subtle",  "zeroize", ] +[[package]]+name = "curve25519-dalek"+version = "5.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.1",+ "curve25519-dalek-derive",+ "fiat-crypto 0.3.0",+ "rustc_version",+ "subtle",+]+ [[package]] name = "curve25519-dalek-derive" version = "0.1.1"@@ -960,6 +1055,16 @@ dependencies = [  "zeroize", ] +[[package]]+name = "der"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"+dependencies = [+ "const-oid 0.10.2",+ "zeroize",+]+ [[package]] name = "diff" version = "0.1.13"@@ -1021,7 +1126,7 @@ dependencies = [  "jni",  "rand_core 0.6.4",  "sha2 0.11.0",- "sha3",+ "sha3 0.10.9", ]  [[package]]@@ -1039,12 +1144,12 @@ version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [- "der",+ "der 0.7.10",  "digest 0.10.7",  "elliptic-curve",  "rfc6979",- "signature",- "spki",+ "signature 2.2.0",+ "spki 0.7.3", ]  [[package]]@@ -1053,8 +1158,8 @@ version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [- "pkcs8",- "signature",+ "pkcs8 0.10.2",+ "signature 2.2.0", ]  [[package]]@@ -1063,7 +1168,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [- "curve25519-dalek",+ "curve25519-dalek 4.1.3",  "ed25519",  "rand_core 0.6.4",  "serde",@@ -1090,9 +1195,9 @@ dependencies = [  "ff",  "generic-array",  "group",- "hkdf",+ "hkdf 0.12.4",  "pem-rfc7468",- "pkcs8",+ "pkcs8 0.10.2",  "rand_core 0.6.4",  "sec1",  "subtle",@@ -1203,6 +1308,12 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]]+name = "fiat-crypto"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"+ [[package]] name = "find-msvc-tools" version = "0.1.12"@@ -1216,7 +1327,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8bdb6454f692ca2a2b45cd554c6828c639d7f9c968cf83a678899ec4443a280" dependencies = [  "rand_core 0.6.4",- "sha3",+ "sha3 0.10.9",  "subtle",  "zeroize", ]@@ -1229,7 +1340,7 @@ checksum = "c9fb5a367b9846933e271a3c2a992930743f82ae5e8cb7faa780715a80fa0b15" dependencies = [  "rand_core 0.6.4",  "sha2 0.10.9",- "sha3",+ "sha3 0.10.9",  "zeroize", ] @@ -1346,6 +1457,7 @@ dependencies = [  "js-sys",  "libc",  "r-efi 6.0.0",+ "rand_core 0.10.1",  "wasm-bindgen", ] @@ -1376,6 +1488,12 @@ dependencies = [  "vello_common 0.0.9", ] +[[package]]+name = "glob"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"+ [[package]] name = "group" version = "0.13.0"@@ -1416,6 +1534,43 @@ dependencies = [  "foldhash", ] +[[package]]+name = "hax-lib"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01a33cb227f97ee5c419064c31d7c55a7d895f28d8019ccdadc311cc036500c4"+dependencies = [+ "hax-lib-macros",+ "num-bigint",+ "num-traits",+]++[[package]]+name = "hax-lib-macros"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28da835a5f153e9f3d0cc1f42ee605a1cfa9093c93348193793d60a1b0908b51"+dependencies = [+ "hax-lib-macros-types",+ "proc-macro-error2",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "hax-lib-macros-types"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eed327e9a28d6ee018a4a9ba842d4ee27e378c8a591d2beb6f42f32b24a02fcb"+dependencies = [+ "proc-macro2",+ "quote",+ "serde",+ "serde_json",+ "uuid",+]+ [[package]] name = "hayro" version = "0.7.1"@@ -1559,6 +1714,15 @@ dependencies = [  "hmac 0.12.1", ] +[[package]]+name = "hkdf"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"+dependencies = [+ "hmac 0.13.0",+]+ [[package]] name = "hmac" version = "0.12.1"@@ -1586,12 +1750,82 @@ dependencies = [  "windows-sys 0.61.2", ] +[[package]]+name = "hpke-rs"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812de62ab573b876c6c40d7553bae9402ae3bad95b64af06f964388eecb9b7b1"+dependencies = [+ "hpke-rs-crypto",+ "hpke-rs-libcrux",+ "hpke-rs-rust-crypto",+ "libcrux-sha3",+ "log",+ "serde",+ "subtle",+ "tls_codec",+ "zeroize",+]++[[package]]+name = "hpke-rs-crypto"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2c461da2e0c9c93d875b597f0c78214fb0d2d5c57834b2ef2a2fa057fa20e24"+dependencies = [+ "rand 0.10.3",+ "zeroize",+]++[[package]]+name = "hpke-rs-libcrux"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c1ace95ef11fbbd84527eada5fc1304f66720fc4c008db30d888d62d3c52613"+dependencies = [+ "hpke-rs-crypto",+ "libcrux-aead",+ "libcrux-ecdh",+ "libcrux-hkdf",+ "libcrux-kem",+ "libcrux-traits",+ "rand 0.10.3",+ "rand_chacha 0.10.0",+ "rand_core 0.10.1",+ "zeroize",+]++[[package]]+name = "hpke-rs-rust-crypto"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a606ac19851da841862ef5f39d26d6227bfcfb4047417801a66c1f6e6652d71"+dependencies = [+ "aes-gcm",+ "chacha20poly1305",+ "hkdf 0.13.0",+ "hpke-rs-crypto",+ "k256",+ "ml-kem",+ "p256",+ "p384",+ "rand 0.10.3",+ "rand_chacha 0.10.0",+ "rand_core 0.10.1",+ "sha2 0.11.0",+ "subtle",+ "x-wing",+ "x25519-dalek 2.0.1",+ "zeroize",+]+ [[package]] name = "hybrid-array" version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [+ "ctutils",  "typenum", ] @@ -1898,6 +2132,16 @@ dependencies = [  "wasm-bindgen", ] +[[package]]+name = "k256"+version = "0.13.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b"+dependencies = [+ "cfg-if",+ "elliptic-curve",+]+ [[package]] name = "keccak" version = "0.1.6"@@ -1907,6 +2151,16 @@ dependencies = [  "cpufeatures 0.2.17", ] +[[package]]+name = "keccak"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.1",+]+ [[package]] name = "keepass" version = "0.13.22"@@ -1941,6 +2195,16 @@ dependencies = [  "zeroize", ] +[[package]]+name = "kem"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd"+dependencies = [+ "crypto-common 0.2.2",+ "rand_core 0.10.1",+]+ [[package]] name = "kurbo" version = "0.13.1"@@ -2014,17 +2278,236 @@ dependencies = [ ]  [[package]]-name = "ldt_tbc"-version = "0.1.0"+name = "ldt_tbc"+version = "0.1.0"+dependencies = [+ "crypto_provider",+]++[[package]]+name = "libc"+version = "0.2.189"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"++[[package]]+name = "libcrux-aead"+version = "0.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22acbe68be84b7b41aaba6e39b87036fc4324dee628d94773750bf3d7e906d69"+dependencies = [+ "libcrux-aes",+ "libcrux-chacha20poly1305",+ "libcrux-secrets",+ "libcrux-traits",+]++[[package]]+name = "libcrux-aes"+version = "0.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57cc95b11dbc797b1e169467b1fc4205c4e6ee2ce516a035ad7342ce5f6ae971"+dependencies = [+ "libcrux-intrinsics",+ "libcrux-platform",+ "libcrux-secrets",+ "libcrux-traits",+]++[[package]]+name = "libcrux-chacha20poly1305"+version = "0.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "537e6eee5cdc9a980014d058784b0be09614f0596df789b114f7833aa9f35d75"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-poly1305",+ "libcrux-secrets",+ "libcrux-traits",+]++[[package]]+name = "libcrux-curve25519"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4f3cfd5e31cb9745e290ee061222c380ec42884654b09fc7d12a5b0ed63e028"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-secrets",+ "libcrux-traits",+]++[[package]]+name = "libcrux-ecdh"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a227590b89ff55ce7cd97b5a7468c82d231db8f3b890bb4d4fb6d271e7524d7"+dependencies = [+ "libcrux-curve25519",+ "libcrux-p256",+ "rand 0.10.3",+ "tls_codec",+]++[[package]]+name = "libcrux-hacl-rs"+version = "0.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66106db376ae249af86911aee048cf73ea1f394d6653026fc988dd22cf2a4ace"+dependencies = [+ "libcrux-macros",+]++[[package]]+name = "libcrux-hkdf"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc94e651dca4d47edbcdd88bb2428ce16a2bd86b7a4e7170da87b505478f9839"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-hmac",+ "libcrux-secrets",+]++[[package]]+name = "libcrux-hmac"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "500ad9b32c715161b594172ca1fb11503a1c033b393ff4c0c33505ce51c1943c"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-sha2",+ "libcrux-traits",+]++[[package]]+name = "libcrux-intrinsics"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98a0c574d4eb81d0814bc2b91e4a433d7e0b35851b1d62eb5dd95c064f1f76d0"+dependencies = [+ "core-models",+ "hax-lib",+]++[[package]]+name = "libcrux-kem"+version = "0.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "541a7377fb35060892e0620982e224e47419f10da8c212453bf642dafe529691"+dependencies = [+ "libcrux-curve25519",+ "libcrux-ecdh",+ "libcrux-ml-kem",+ "libcrux-p256",+ "libcrux-sha3",+ "libcrux-traits",+ "rand 0.10.3",+]++[[package]]+name = "libcrux-macros"+version = "0.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ffd6aa2dcd5be681662001b81d493f1569c6d49a32361f470b0c955465cd0338"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "libcrux-ml-kem"+version = "0.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d8160f7d64fd2716b4fd05cc886a042f8dcda18d9206c0d506e2c67bdf97daa"+dependencies = [+ "hax-lib",+ "libcrux-intrinsics",+ "libcrux-platform",+ "libcrux-secrets",+ "libcrux-sha3",+ "libcrux-traits",+ "rand 0.10.3",+ "tls_codec",+]++[[package]]+name = "libcrux-p256"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3400732702d578be622257b98cec85e9b0cd34a67f1f06d3ebe9ae34963cdf02"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-secrets",+ "libcrux-sha2",+ "libcrux-traits",+]++[[package]]+name = "libcrux-platform"+version = "0.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d9e21d7ed31a92ac539bd69a8c970b183ee883872d2d19ce27036e24cb8ecc4"+dependencies = [+ "libc",+]++[[package]]+name = "libcrux-poly1305"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a9144949845813a0b8787d08cbba47baabe59c83f3043e558e6e92385c40cc"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-macros",+]++[[package]]+name = "libcrux-secrets"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "79054fc9037cb70d6a546cf094cea7d7df06af5e49d230ba24103d27ccc886f1"+dependencies = [+ "crabgrind",+ "hax-lib",+]++[[package]]+name = "libcrux-sha2"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "960e46e1be0b77098cc6ce82137864936ecad3a1b9fd4303dd51202ca140dd1e" dependencies = [- "crypto_provider",+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-traits", ]  [[package]]-name = "libc"-version = "0.2.189"+name = "libcrux-sha3"+version = "0.0.10" source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"+checksum = "c09f5c39afae0528e1f70a3c1e3c6ee649ec1f19dda26fc9b6ea91108fb879ef"+dependencies = [+ "hax-lib",+ "libcrux-intrinsics",+ "libcrux-platform",+ "libcrux-traits",+]++[[package]]+name = "libcrux-traits"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3fa7a21e8c2e8baa8b40f0b176740f2ca4baadd79d1b00e48d6b1e363c42085a"+dependencies = [+ "libcrux-secrets",+ "rand 0.10.3",+]  [[package]] name = "libloading"@@ -2186,6 +2669,35 @@ dependencies = [  "simd-adler32", ] +[[package]]+name = "ml-dsa"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "add6b9d92e496f16f4526d68ff29da1483aba4b119baeab8bed3b9e3544a6f3d"+dependencies = [+ "const-oid 0.10.2",+ "crypto-common 0.2.2",+ "ctutils",+ "hybrid-array",+ "module-lattice",+ "pkcs8 0.11.0",+ "shake",+ "signature 3.0.0",+]++[[package]]+name = "ml-kem"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e15f3e5b957493873e396a66914e83e616b6afe335cdef7efe5c6e1216aba66"+dependencies = [+ "hybrid-array",+ "kem",+ "module-lattice",+ "rand_core 0.10.1",+ "sha3 0.11.0",+]+ [[package]] name = "modelrunner" version = "0.1.0"@@ -2194,6 +2706,17 @@ dependencies = [  "jni", ] +[[package]]+name = "module-lattice"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c61b87c9683ab7cb1c6871d261ad5479b6b10ceb52c4352aaca3b5d35a8febe"+dependencies = [+ "ctutils",+ "hybrid-array",+ "num-traits",+]+ [[package]] name = "moxcms" version = "0.8.1"@@ -2416,6 +2939,102 @@ dependencies = [  "sprintf", ] +[[package]]+name = "openmls"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6b08d90fc020cb5354d5f08ca17711b84c82e2bcc7331753fd94f000d99a8c8"+dependencies = [+ "log",+ "openmls_serialization_helpers",+ "openmls_traits",+ "rayon",+ "serde",+ "serde_bytes",+ "thiserror 2.0.20",+ "tls_codec",+ "zeroize",+]++[[package]]+name = "openmls_basic_credential"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dbd3f0c3422e7c7a8496f042b547b0c28d0793f8ba97feb401966e58196a1e40"+dependencies = [+ "ed25519-dalek",+ "ml-dsa",+ "openmls_traits",+ "p256",+ "p384",+ "rand_core 0.6.4",+ "serde",+ "tls_codec",+ "zeroize",+]++[[package]]+name = "openmls_memory_storage"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce927945a16eaa19302ed5ccef052f01ba68f2ba7ae67e4ac4ff2fc661445364"+dependencies = [+ "log",+ "openmls_traits",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+]++[[package]]+name = "openmls_rust_crypto"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "36bf3fe824ead6e81d22f49a9cd7feffca3494979fac14c1248e19516e3625f1"+dependencies = [+ "aes-gcm",+ "chacha20poly1305",+ "ed25519-dalek",+ "hkdf 0.13.0",+ "hmac 0.13.0",+ "hpke-rs",+ "hpke-rs-crypto",+ "hpke-rs-rust-crypto",+ "ml-dsa",+ "openmls_memory_storage",+ "openmls_traits",+ "p256",+ "p384",+ "rand_chacha 0.3.1",+ "rand_core 0.10.1",+ "rand_core 0.6.4",+ "sha2 0.11.0",+ "thiserror 2.0.20",+ "tls_codec",+]++[[package]]+name = "openmls_serialization_helpers"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e2cf2193541e83ce1a89aaa44c2fd4783abd54853823075a32b60ef032284c0"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "thiserror 2.0.20",+]++[[package]]+name = "openmls_traits"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac13edad8698eb1917cbc1dab99591fa1594d84320904fe3fc5121854f95831c"+dependencies = [+ "serde",+ "tls_codec",+]+ [[package]] name = "owned_ttf_parser" version = "0.25.1"@@ -2437,6 +3056,18 @@ dependencies = [  "sha2 0.10.9", ] +[[package]]+name = "p384"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"+dependencies = [+ "ecdsa",+ "elliptic-curve",+ "primeorder",+ "sha2 0.10.9",+]+ [[package]] name = "parking_lot" version = "0.12.5"@@ -2470,12 +3101,18 @@ dependencies = [  "serde", ] +[[package]]+name = "pastey"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"+ [[package]] name = "pdf_render" version = "0.1.0" dependencies = [  "aes 0.8.4",- "der",+ "der 0.7.10",  "fax",  "flate2",  "getrandom 0.2.17",@@ -2591,10 +3228,26 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [- "der",- "spki",+ "der 0.7.10",+ "spki 0.7.3",+]++[[package]]+name = "pkcs8"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"+dependencies = [+ "der 0.8.2",+ "spki 0.8.0", ] +[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"+ [[package]] name = "plotters" version = "0.3.7"@@ -2692,6 +3345,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" +[[package]]+name = "prettyplease"+version = "0.2.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"+dependencies = [+ "proc-macro2",+ "syn 2.0.119",+]+ [[package]] name = "primeorder" version = "0.13.6"@@ -2701,6 +3364,28 @@ dependencies = [  "elliptic-curve", ] +[[package]]+name = "proc-macro-error-attr2"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"+dependencies = [+ "proc-macro2",+ "quote",+]++[[package]]+name = "proc-macro-error2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"+dependencies = [+ "proc-macro-error-attr2",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+ [[package]] name = "proc-macro2" version = "1.0.107"@@ -2878,6 +3563,17 @@ dependencies = [  "rand_core 0.9.5", ] +[[package]]+name = "rand"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"+dependencies = [+ "chacha20 0.10.2",+ "getrandom 0.4.3",+ "rand_core 0.10.1",+]+ [[package]] name = "rand_chacha" version = "0.3.1"@@ -2898,6 +3594,16 @@ dependencies = [  "rand_core 0.9.5", ] +[[package]]+name = "rand_chacha"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e6af7f3e25ded52c41df4e0b1af2d047e45896c2f3281792ed68a1c243daedb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.10.1",+]+ [[package]] name = "rand_core" version = "0.6.4"@@ -2916,6 +3622,12 @@ dependencies = [  "getrandom 0.3.4", ] +[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"+ [[package]] name = "rand_ext" version = "0.1.0"@@ -3125,9 +3837,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [  "base16ct",- "der",+ "der 0.7.10",  "generic-array",- "pkcs8",+ "pkcs8 0.10.2",  "subtle",  "zeroize", ]@@ -3157,6 +3869,16 @@ dependencies = [  "serde_derive", ] +[[package]]+name = "serde_bytes"+version = "0.11.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"+dependencies = [+ "serde",+ "serde_core",+]+ [[package]] name = "serde_core" version = "1.0.229"@@ -3219,7 +3941,39 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874" dependencies = [  "digest 0.10.7",- "keccak",+ "keccak 0.1.6",+]++[[package]]+name = "sha3"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be176f1a57ce4e3d31c1a166222d9768de5954f811601fb7ca06fc8203905ce1"+dependencies = [+ "digest 0.11.3",+ "keccak 0.2.2",+]++[[package]]+name = "sha3"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759"+dependencies = [+ "digest 0.11.3",+ "keccak 0.2.2",+ "sponge-cursor",+]++[[package]]+name = "shake"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a"+dependencies = [+ "digest 0.11.3",+ "keccak 0.2.2",+ "sponge-cursor", ]  [[package]]@@ -3232,7 +3986,7 @@ dependencies = [  "cipher 0.4.4",  "crypto_provider_default",  "getrandom 0.2.17",- "hkdf",+ "hkdf 0.12.4",  "hmac 0.12.1",  "jni",  "np_adv",@@ -3243,6 +3997,12 @@ dependencies = [  "ukey2_connections", ] +[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+ [[package]] name = "shlex" version = "2.0.1"@@ -3259,6 +4019,16 @@ dependencies = [  "rand_core 0.6.4", ] +[[package]]+name = "signature"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"+dependencies = [+ "digest 0.11.3",+ "rand_core 0.10.1",+]+ [[package]] name = "simd-adler32" version = "0.3.10"@@ -3319,9 +4089,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [  "base64ct",- "der",+ "der 0.7.10",+]++[[package]]+name = "spki"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f"+dependencies = [+ "base64ct",+ "der 0.8.2", ] +[[package]]+name = "sponge-cursor"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"+ [[package]] name = "sprintf" version = "0.1.4"@@ -3517,6 +4303,29 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]]+name = "tls_codec"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18cc98286004cea38f717e2b03d990fc774fbfd38a82720de40e5c94365067c8"+dependencies = [+ "serde",+ "serde_bytes",+ "tls_codec_derive",+ "zeroize",+]++[[package]]+name = "tls_codec_derive"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "674f41dd95f76cdeb005c83f9444e20cf43daebef37cde9e49a9ca6f4e87b423"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+ [[package]] name = "tracing" version = "0.1.44"@@ -3783,7 +4592,7 @@ dependencies = [  "thiserror 2.0.20",  "tracing",  "typed-builder",- "x25519-dalek",+ "x25519-dalek 2.0.1",  "zerocopy", ] @@ -4142,18 +4951,41 @@ dependencies = [  "serde_json", ] +[[package]]+name = "x-wing"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b51507b887016c3925c84591108dadb8c099f776eb04fec6a60ae3519fee856f"+dependencies = [+ "kem",+ "ml-kem",+ "sha3 0.12.0",+ "shake",+ "x25519-dalek 3.0.0",+]+ [[package]] name = "x25519-dalek" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" dependencies = [- "curve25519-dalek",+ "curve25519-dalek 4.1.3",  "rand_core 0.6.4",  "serde",  "zeroize", ] +[[package]]+name = "x25519-dalek"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"+dependencies = [+ "curve25519-dalek 5.0.0",+ "rand_core 0.10.1",+]+ [[package]] name = "xts-mode" version = "0.5.1"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 5453120dd3..7176c69491 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -19,6 +19,7 @@ members = [   "library/vision/src/main/rust",   "measure/src/main/rust",   "communicate/src/main/rust",+  "communicate/src/main/rust-mls",   "youpipe/src/main/rust",   "web/src/main/rust",   "share/src/main/rust",@@ -140,6 +141,13 @@ md-5 = "0.11.0" keepass = { version = "=0.13.22", default-features = false, features = ["save_kdbx4"] } # Classic Signal protocol (WhatsApp bridge) – X25519/XEdDSA + AES-CBC + HMAC. curve25519-dalek = { version = "4.1.3", default-features = false, features = ["alloc", "precomputed-tables", "zeroize"] }+# MLS (RFC 9420) for the RCS line — OpenMLS + RustCrypto provider + memory storage.+openmls = { version = "0.9.0", default-features = false }+openmls_rust_crypto = "0.6.0"+openmls_memory_storage = "0.6.0"+openmls_basic_credential = "0.6.0"+openmls_traits = "0.6.0"+tls_codec = "0.5.0" x25519-dalek = { version = "2.0.1", default-features = false, features = ["static_secrets"] } hmac = "0.12.1" subtle = "2.6.1"
build-logic/src/main/kotlin/RustNative.kt
diff --git a/build-logic/src/main/kotlin/RustNative.kt b/build-logic/src/main/kotlin/RustNative.ktindex 1b92a64097..2a9a1ef816 100644--- a/build-logic/src/main/kotlin/RustNative.kt+++ b/build-logic/src/main/kotlin/RustNative.kt@@ -69,6 +69,9 @@ private val KNOWN_RUST_ABIS = listOf(  * @param crate      cargo package lib name → produces `lib<crate>.so`  * @param remapLabel `--remap-path-prefix` label baked in for reproducible builds  *                   (defaults to [crate]).+ * @param srcDir     crate directory relative to the module (defaults to+ *                   `src/main/rust`). Namespaces the per-ABI task names by+ *                   [crate] so a module can build several crates.  * @param extraAbis  ABIs to build in addition to [ABI_ARM64]. Opt-in per module so only  *                   the modules that need a second ABI pay for the extra cargo build;  *                   pass [ABI_ARMV7] for libraries consumed by an app that sets@@ -83,6 +86,7 @@ fun Project.rustNativeLib(     remapLabel: String = crate,     extraAbis: List<String> = emptyList(),     features: List<String> = emptyList(),+    srcDir: String = "src/main/rust", ) {     // Serialize cargoBuild across all Rust modules to avoid concurrent rustup installs.     val rustLock = gradle.sharedServices.registerIfAbsent(@@ -129,10 +133,10 @@ fun Project.rustNativeLib(      val perAbi = rustAbis.map { abi ->         val (abiDir, triple) = abi-        tasks.register<Exec>("cargoBuild_${abiDir.replace('-', '_')}") {+        tasks.register<Exec>("cargoBuild_${crate}_${abiDir.replace('-', '_')}") {             usesService(rustLock)             description = "Cross-compiles lib$crate for $abiDir."-            workingDir = file("src/main/rust")+            workingDir = file(srcDir)              // Windows hosts use the .cmd clang wrappers and .exe tool suffixes; Unix hosts none.             val isWindows = OperatingSystem.current().isWindows@@ -143,12 +147,12 @@ fun Project.rustNativeLib(             val linkerVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_LINKER"             // Per-crate target (may exist from older isolated builds) and workspace root target             // (current scheme since Cargo.toml workspace unified to root).-            val perCrateSoOut = file("src/main/rust/target/$triple/release/lib$crate.so")+            val perCrateSoOut = file("$srcDir/target/$triple/release/lib$crate.so")             val workspaceSoOut = rootProject.file("target/$triple/release/lib$crate.so")             val destSo = layout.buildDirectory.file("rustJniLibs/$abiDir/lib$crate.so").get().asFile -            inputs.dir("src/main/rust/src")-            inputs.file("src/main/rust/Cargo.toml")+            inputs.dir("$srcDir/src")+            inputs.file("$srcDir/Cargo.toml")             // The crate's own build script and whatever it generates from. `:library:ml`'s             // build.rs compiles `shaders/*.comp` to SPIR-V and `include_bytes!`s the result, so             // a shader edit changes the .so - but without these two the task stays up to date,@@ -156,13 +160,13 @@ fun Project.rustNativeLib(             // makes shader A/B measurements read as "no effect".             //             // Optional because not every Rust module here has either.-            file("src/main/rust/build.rs").takeIf { it.isFile }?.let { inputs.file(it) }-            file("src/main/rust/shaders").takeIf { it.isDirectory }?.let { inputs.dir(it) }+            file("$srcDir/build.rs").takeIf { it.isFile }?.let { inputs.file(it) }+            file("$srcDir/shaders").takeIf { it.isDirectory }?.let { inputs.dir(it) }             // `:library:ml`'s build.rs also compiles `schema/maml2.fbs` to Rust via             // flatc and `include!`s the result, so a schema edit changes the .so too.             // Same staleness hazard as shaders above: without this the task stays up             // to date and the old bindings ship.-            file("src/main/rust/schema").takeIf { it.isDirectory }?.let { inputs.dir(it) }+            file("$srcDir/schema").takeIf { it.isDirectory }?.let { inputs.dir(it) }             // Whole-crate safety net: track every source under src/main/rust so ANY             // rust change invalidates cargoBuild - crucially vendored dependency             // crates under vendor/, which@@ -172,7 +176,7 @@ fun Project.rustNativeLib(             // output back in as an input means the task can never be up to date. The             // FileTree is a FileCollection resolved at configuration time, so only the             // file set (never the Project) crosses into the task action.-            inputs.files(fileTree("src/main/rust") { exclude("target/**") })+            inputs.files(fileTree(srcDir) { exclude("target/**") })                 .withPropertyName("rustCrateTree")             // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml)             inputs.file(rootProject.file("Cargo.toml"))@@ -189,7 +193,7 @@ fun Project.rustNativeLib(             outputs.file(destSo)              val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"-            val rustSrc = file("src/main/rust").absolutePath+            val rustSrc = file(srcDir).absolutePath              val pathSep = if (isWindows) ";" else ":"             environment("PATH", "$cargoBin$pathSep${System.getenv("PATH")}")@@ -253,17 +257,26 @@ fun Project.rustNativeLib(         }     } -    val cargoNdkBuild = tasks.register("cargoNdkBuild") {+    val cargoNdkBuild = tasks.register("cargoNdkBuild_$crate") {         description = "Builds lib$crate.so for all Android ABIs."         dependsOn(perAbi)     }+    // Keep the historic aggregate name for the default crate dir so existing+    // invocations (`./gradlew :mod:cargoNdkBuild`) keep working.+    if (srcDir == "src/main/rust") {+        tasks.register("cargoNdkBuild") {+            description = "Builds lib$crate.so for all Android ABIs."+            dependsOn(cargoNdkBuild)+        }+    }     // Rust file-length gate: fails the build on any *.rs over     // RUST_FILE_LENGTH_LIMIT lines, like the Kotlin FileLength rule (which     // cannot see Rust). Configuration-cache compatible: plain path strings     // cross the configuration boundary, never the Project object.-    val rustSrcPath: String = file("src/main/rust/src").absolutePath+    val rustSrcPath: String = file("$srcDir/src").absolutePath     val rustProjPath: String = projectDir.absolutePath-    val rustFileLength = tasks.register("rustFileLength") {+    val lengthTaskName = if (srcDir == "src/main/rust") "rustFileLength" else "rustFileLength_$crate"+    val rustFileLength = tasks.register(lengthTaskName) {         description = "Fails on Rust files over $RUST_FILE_LENGTH_LIMIT lines."         inputs.dir(rustSrcPath)         doLast {
communicate/build.gradle.kts
diff --git a/communicate/build.gradle.kts b/communicate/build.gradle.ktsindex 1c746f595e..9bc36b01a1 100644--- a/communicate/build.gradle.kts+++ b/communicate/build.gradle.kts@@ -153,6 +153,10 @@ androidComponents { // messages' whatsapp_signal. rustNativeLib("communicate_signal", "communicate_signal") +// MLS (RFC 9420, OpenMLS) for the RCS line's closed-loop E2EE — separate crate+// (own dependency tree) with its own JNI lib.+rustNativeLib("communicate_mls", "communicate_mls", srcDir = "src/main/rust-mls")+ dependencies {     // Google Voice virtual line: protojson RPCs + SIP-over-WSS transport go through     // the repo's own Android-only HTTP/WebSocket stack (no OkHttp/Ktor).
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.ktindex 9c27dcb81d..24cf15281b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepositoryRcs.kt@@ -7,6 +7,10 @@ import com.vayunmathur.communicate.data.rcs.RcsCapabilityExchange import com.vayunmathur.communicate.data.rcs.RcsConversation import com.vayunmathur.communicate.data.rcs.RcsDatabase import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsFileTransfer+import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp+import com.vayunmathur.communicate.data.rcs.RcsMsrp+import com.vayunmathur.communicate.data.rcs.RcsSessionManager import com.vayunmathur.communicate.data.rcs.RcsSipTransport import com.vayunmathur.library.util.AppMessages import java.util.UUID@@ -117,22 +121,65 @@ suspend fun CommunicateRepository.sendRcsMessage(     }.getOrDefault(false)     if (!capable) return@withContext RcsSendResult.FallbackSms     if (!RcsSipTransport.canSend()) return@withContext RcsSendResult.FallbackSms+    val repository = this@sendRcsMessage     runCatching {-        val (startLine, headers, content) = if (attachments.isEmpty()) {-            RcsSipTransport.buildChatMessage(+        // E2EE first: when the conversation has an MLS group, encrypt and send+        // the framed payload as an MLS content message. Falls through to the+        // plaintext paths when no group exists or encryption fails.+        val e2ePayload = encryptForE2E(context, recipient, body)+        if (e2ePayload != null) {+            val (startLine, headers, content) = RcsSipTransport.buildChatMessage(                 fromUri = "sip:me@rcs",                 toUri = "sip:$recipient@rcs",-                body = body,+                callId = "${UUID.randomUUID()}@rcs-mls",+                body = android.util.Base64.encodeToString(+                    e2ePayload,+                    android.util.Base64.NO_WRAP,+                ),             )-        } else {-            // v1: attachments ride as a plain-text placeholder + FT metadata row;-            // full MSRP/FT flows land in RcsFileTransfer.-            RcsSipTransport.buildChatMessage(-                fromUri = "sip:me@rcs",-                toUri = "sip:$recipient@rcs",-                body = body.ifBlank { "[attachment]" },+            // Re-wrap as the MLS content type (buildChatMessage defaults CPIM).+            val mlsHeaders = headers.replace(+                "Content-Type: message/cpim",+                "Content-Type: ${com.vayunmathur.communicate.data.rcs.e2e.RcsE2E.CT_MLS}",             )+            val ok = RcsSipTransport.sendSipMessage(startLine, mlsHeaders, content)+            if (!ok) return@withContext RcsSendResult.FallbackSms+            if (body.isNotBlank()) {+                cacheOutgoingRcs(context, recipient, body, "local-${UUID.randomUUID()}")+            }+            return@withContext RcsSendResult.Sent         }+        // Prefer an established session (MSRP) when one exists; else pager-mode CPIM.+        val session = RcsSessionManager.sessionFor(recipient)+        if (session?.msrpRemotePath != null && attachments.isEmpty()) {+            val cpim = RcsSipTransport.buildCpimBody(body).toByteArray(Charsets.UTF_8)+            if (RcsMsrp.send(session, cpim)) {+                if (body.isNotBlank()) {+                    cacheOutgoingRcs(context, recipient, body, "local-${UUID.randomUUID()}")+                }+                return@withContext RcsSendResult.Sent+            }+        }+        if (attachments.isNotEmpty()) {+            // FT-over-HTTP when the content server is known, else the v1 envelope.+            val ftOk = if (RcsFileTransferHttp.contentServerUri != null) {+                var oneOk = false+                for (attachment in attachments) {+                    if (RcsFileTransferHttp.sendFile(context, repository, recipient, attachment, body)) {+                        oneOk = true+                    }+                }+                oneOk+            } else {+                RcsFileTransfer.sendFiles(context, repository, recipient, body, attachments)+            }+            return@withContext if (ftOk) RcsSendResult.Sent else RcsSendResult.FallbackSms+        }+        val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+            fromUri = "sip:me@rcs",+            toUri = "sip:$recipient@rcs",+            body = body,+        )         val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)         if (!ok) return@withContext RcsSendResult.FallbackSms         if (body.isNotBlank()) {@@ -281,3 +328,24 @@ suspend fun CommunicateRepository.markRcsRead( fun CommunicateRepository.notifyRcsFallback(context: Context) {     AppMessages.show(context.getString(com.vayunmathur.communicate.R.string.rcs_fallback_sms)) }++/**+ * Encrypt [body] for [recipient]'s E2EE group when one exists. Returns the+ * framed MLS payload, or null when the conversation is plaintext (no group)+ * or encryption failed (caller falls through to plaintext paths).+ */+internal suspend fun CommunicateRepository.encryptForE2E(+    context: Context,+    recipient: String,+    body: String,+): ByteArray? {+    if (!com.vayunmathur.communicate.data.rcs.RcsFeature.enabled || body.isBlank()) return null+    // Group threads address by remoteId; 1:1 threads by E.164 recipient.+    val conversationId = recipient+    val hasGroup = com.vayunmathur.communicate.data.rcs.e2e.RcsE2E.groupIdFor(context, conversationId) != null+    if (!hasGroup) return null+    val local = com.vayunmathur.communicate.data.rcs.e2e.RcsE2E.localE164(context) ?: return null+    return com.vayunmathur.communicate.data.rcs.e2e.RcsE2E.encryptTo(+        context, local, conversationId, body.toByteArray(Charsets.UTF_8),+    )+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.ktindex 7efe4cf196..dd58e59431 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsDatabase.kt@@ -11,6 +11,8 @@ import androidx.room3.OnConflictStrategy import androidx.room3.PrimaryKey import androidx.room3.Query import androidx.room3.RoomDatabase+import androidx.sqlite.SQLiteConnection+import androidx.sqlite.execSQL import com.vayunmathur.library.room.RoomRepository import com.vayunmathur.library.util.DatabaseMigrations @@ -24,17 +26,42 @@ import com.vayunmathur.library.util.DatabaseMigrations     entities = [         RcsConversation::class,         RcsCachedMessage::class,+        RcsMlsIdentity::class,+        RcsMlsGroup::class,     ],-    version = 1,+    version = 2,     exportSchema = false, ) @ColumnTypeConverters(RcsTypeConverters::class) abstract class RcsDatabase : RoomDatabase() {     abstract fun conversationDao(): RcsConversationDao     abstract fun cachedMessageDao(): RcsCachedMessageDao+    abstract fun mlsIdentityDao(): RcsMlsIdentityDao+    abstract fun mlsGroupDao(): RcsMlsGroupDao      companion object : DatabaseMigrations {-        override val migrations = emptyList<androidx.room3.migration.Migration>()+        /**+         * v1 → v2: MLS E2EE tables (identity + group state). New tables only,+         * nothing to backfill.+         */+        private val MIGRATION_1_2 = object : androidx.room3.migration.Migration(1, 2) {+            override suspend fun migrate(connection: androidx.sqlite.SQLiteConnection) {+                connection.execSQL(+                    "CREATE TABLE IF NOT EXISTS `rcs_mls_identity` (" ++                        "`e164` TEXT NOT NULL, `identity` BLOB NOT NULL, " ++                        "`updatedAt` INTEGER NOT NULL, " ++                        "PRIMARY KEY(`e164`))",+                )+                connection.execSQL(+                    "CREATE TABLE IF NOT EXISTS `rcs_mls_group` (" ++                        "`groupIdHex` TEXT NOT NULL, `conversationId` TEXT NOT NULL, " ++                        "`storage` BLOB NOT NULL, `updatedAt` INTEGER NOT NULL, " ++                        "PRIMARY KEY(`groupIdHex`))",+                )+            }+        }++        override val migrations = listOf(MIGRATION_1_2)          fun getDatabase(context: Context): RcsDatabase =             RcsRepository.get(context).database()@@ -107,7 +134,6 @@ interface RcsConversationDao { }  // -- Cached messages --- @Entity(tableName = "rcs_cached_message") data class RcsCachedMessage(     @PrimaryKey val messageId: String,@@ -160,3 +186,60 @@ interface RcsCachedMessageDao {     @Query("DELETE FROM rcs_cached_message")     suspend fun deleteAll() }++// -- MLS E2EE (closed-loop, our-app-to-our-app) --++/**+ * Our MLS identity for one local E.164: serialized `IdentityState`+ * (Ed25519 keypair + identity string) from the `communicate_mls` crate.+ */+@Entity(tableName = "rcs_mls_identity")+data class RcsMlsIdentity(+    @PrimaryKey val e164: String,+    val identity: ByteArray,+    val updatedAt: Long = 0L,+)++/**+ * One MLS group, keyed by hex-encoded MLS group id bytes. [storage] is the+ * opaque provider snapshot the crate needs on every call; [conversationId]+ * maps back to the RCS thread.+ */+@Entity(tableName = "rcs_mls_group")+data class RcsMlsGroup(+    /** Hex of the MLS group id (BLOB PKs are unreliable in Room). */+    @PrimaryKey val groupIdHex: String,+    val conversationId: String,+    val storage: ByteArray,+    val updatedAt: Long = 0L,+)++@Dao+interface RcsMlsIdentityDao {+    @Query("SELECT * FROM rcs_mls_identity WHERE e164 = :e164 LIMIT 1")+    suspend fun get(e164: String): RcsMlsIdentity?++    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun upsert(identity: RcsMlsIdentity)++    @Query("DELETE FROM rcs_mls_identity WHERE e164 = :e164")+    suspend fun delete(e164: String)+}++@Dao+interface RcsMlsGroupDao {+    @Query("SELECT * FROM rcs_mls_group WHERE groupIdHex = :groupIdHex LIMIT 1")+    suspend fun get(groupIdHex: String): RcsMlsGroup?++    @Query("SELECT * FROM rcs_mls_group WHERE conversationId = :conversationId LIMIT 1")+    suspend fun getByConversation(conversationId: String): RcsMlsGroup?++    @Insert(onConflict = OnConflictStrategy.REPLACE)+    suspend fun upsert(group: RcsMlsGroup)++    @Query("DELETE FROM rcs_mls_group WHERE groupIdHex = :groupIdHex")+    suspend fun delete(groupIdHex: String)++    @Query("DELETE FROM rcs_mls_group WHERE conversationId = :conversationId")+    suspend fun deleteByConversation(conversationId: String)+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.ktnew file mode 100644index 0000000000..f88ee7e818--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsFileTransferHttp.kt@@ -0,0 +1,234 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.net.Uri+import android.util.Log+import androidx.core.net.toUri+import com.vayunmathur.communicate.data.CommunicateAttachment+import com.vayunmathur.communicate.data.CommunicateRepository+import com.vayunmathur.communicate.data.cacheOutgoingRcsFile+import com.vayunmathur.library.network.NetworkClient+import java.io.File+import java.util.UUID+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * FT-over-HTTP (RCC.07 Annex: file transfer via the carrier content server).+ *+ * Upload flow mirrors TestRcsApp's `FileUploadController`, rebuilt on this+ * repo's `NetworkClient` (no Apache HttpClient / Guava): empty POST →+ * 401 digest challenge → authenticated multipart POST (`tid` + `File` parts)+ * → server returns the download URL. The URL + metadata ride a CPIM+ * file-transfer message so the far end can fetch; inbound FT messages expose+ * [RcsFtInfo] for the attachment renderer + a [download] helper.+ *+ * The content-server URI comes from provisioning (RCS config XML+ * `ftHTTPCSURI`); without it, FT degrades to the v1 envelope path.+ */+object RcsFileTransferHttp {+    private const val TAG = "RcsFtHttp"++    /** Parsed inbound file-transfer descriptor. */+    data class RcsFtInfo(+        val url: String,+        val mime: String,+        val fileName: String?,+        val fileSize: Long?,+    )++    /** Content-server base URI from provisioning, or null when unknown. */+    @Volatile+    var contentServerUri: String? = null++    /**+     * Upload [attachment] bytes to the content server. Returns the download+     * URL on success, null otherwise. Never throws.+     */+    suspend fun upload(+        context: Context,+        attachment: CommunicateAttachment,+    ): String? = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled) return@withContext null+        val server = contentServerUri?.takeIf { it.isNotBlank() } ?: return@withContext null+        runCatching {+            val bytes = context.contentResolver.openInputStream(attachment.contentUri.toUri())+                ?.use { it.readBytes() } ?: return@runCatching null+            // 1. Empty POST to harvest the digest challenge.+            val probe = NetworkClient.performRequest(server, "POST", useSystemTrust = true)+            val challenge = probe.headers.entries+                .firstOrNull { it.key.equals("WWW-Authenticate", ignoreCase = true) }+                ?.value?.firstOrNull()+                ?: return@runCatching null+            // 2. Authenticated multipart POST (tid + File).+            val boundary = "rcsft${UUID.randomUUID().toString().replace("-", "").take(16)}"+            val tid = UUID.randomUUID().toString()+            val multipart = buildMultipart(+                boundary = boundary,+                tid = tid,+                fileName = attachment.fileName ?: "file",+                mime = attachment.mimeType,+                bytes = bytes,+            )+            val auth = digestAuthHeader(+                challenge = challenge,+                method = "POST",+                uri = server,+                username = "rcs",+            )+            val response = NetworkClient.performRequest(+                url = server,+                method = "POST",+                headers = mapOf(+                    "Content-Type" to "multipart/form-data; boundary=$boundary",+                    "Authorization" to auth,+                    "User-Agent" to "Communicate-RCS/1.0",+                ),+                body = multipart,+                useSystemTrust = true,+            )+            if (!response.isSuccess) return@runCatching null+            // Server answers with the file URL (plain or XML-wrapped).+            Regex("https?://[^\\s\"'<>]+").find(response.body)?.value+        }.getOrElse {+            Log.w(TAG, "FT upload failed", it)+            null+        }+    }++    /**+     * Download [url] to the app cache and return the file. Never throws.+     */+    suspend fun download(context: Context, url: String): File? = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled || url.isBlank()) return@withContext null+        runCatching {+            val (status, bytes) = NetworkClient.performRequestBytes(url, useSystemTrust = true)+            if (status !in 200..299 || bytes.isEmpty()) return@runCatching null+            val dir = File(context.cacheDir, "rcs-ft").apply { mkdirs() }+            val file = File(dir, "dl-${UUID.randomUUID()}")+            file.writeBytes(bytes)+            file+        }.getOrElse {+            Log.w(TAG, "FT download failed", it)+            null+        }+    }++    /**+     * Send a file to [recipient]: upload, then a CPIM FT message carrying the+     * URL + metadata, then cache the outgoing row. Returns true when the SIP+     * leg was accepted.+     */+    suspend fun sendFile(+        context: Context,+        repository: CommunicateRepository,+        recipient: String,+        attachment: CommunicateAttachment,+        caption: String = "",+    ): Boolean = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return@withContext false+        val url = upload(context, attachment) ?: return@withContext false+        val ftCpim = buildString {+            append("File-URL: $url\r\n")+            append("File-MIME: ${attachment.mimeType}\r\n")+            attachment.fileName?.let { append("File-Name: $it\r\n") }+            if (caption.isNotBlank()) append("\r\n$caption")+        }+        val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+            fromUri = "sip:me@rcs",+            toUri = "sip:$recipient@rcs",+            callId = "${UUID.randomUUID()}@rcs-ft",+            body = ftCpim,+        )+        val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)+        if (ok) {+            repository.cacheOutgoingRcsFile(+                context = context,+                conversationId = recipient,+                body = caption.ifBlank { attachment.fileName ?: "[file]" },+                messageId = "local-ft-${UUID.randomUUID()}",+                ftUrl = url,+                ftMime = attachment.mimeType,+            )+        }+        ok+    }++    /** Parse an inbound FT CPIM body into [RcsFtInfo], or null. */+    fun parseFtBody(body: String): RcsFtInfo? {+        val url = Regex("File-URL:\\s*(\\S+)", RegexOption.IGNORE_CASE).find(body)+            ?.groupValues?.getOrNull(1)?.trim() ?: return null+        val mime = Regex("File-MIME:\\s*(\\S+)", RegexOption.IGNORE_CASE).find(body)+            ?.groupValues?.getOrNull(1)?.trim() ?: "application/octet-stream"+        val name = Regex("File-Name:\\s*(.+)", RegexOption.IGNORE_CASE).find(body)+            ?.groupValues?.getOrNull(1)?.trim()?.takeIf { it.isNotEmpty() }+        val size = Regex("File-Size:\\s*(\\d+)", RegexOption.IGNORE_CASE).find(body)+            ?.groupValues?.getOrNull(1)?.toLongOrNull()+        return RcsFtInfo(url = url, mime = mime, fileName = name, fileSize = size)+    }++    private fun buildMultipart(+        boundary: String,+        tid: String,+        fileName: String,+        mime: String,+        bytes: ByteArray,+    ): ByteArray {+        val out = java.io.ByteArrayOutputStream()+        fun part(headers: String, content: ByteArray) {+            out.write("--$boundary\r\n".toByteArray(Charsets.UTF_8))+            out.write(headers.toByteArray(Charsets.UTF_8))+            out.write("\r\n".toByteArray(Charsets.UTF_8))+            out.write(content)+            out.write("\r\n".toByteArray(Charsets.UTF_8))+        }+        part(+            "Content-Disposition: form-data; name=\"tid\"\r\nContent-Type: text/plain",+            tid.toByteArray(Charsets.UTF_8),+        )+        part(+            "Content-Disposition: form-data; name=\"File\"; filename=\"$fileName\"\r\nContent-Type: $mime",+            bytes,+        )+        out.write("--$boundary--\r\n".toByteArray(Charsets.UTF_8))+        return out.toByteArray()+    }++    /**+     * Minimal digest Authorization header from a WWW-Authenticate challenge.+     * GBA bootstrapping (TestRcsApp GbaRequestExecutor) is out of scope —+     * this covers plain digest; AKA/GBA challenges return an empty header and+     * the upload degrades gracefully.+     */+    private fun digestAuthHeader(challenge: String, method: String, uri: String, username: String): String {+        if (!challenge.contains("Digest", ignoreCase = true)) return ""+        fun param(name: String): String =+            Regex("$name=\"([^\"]+)\"", RegexOption.IGNORE_CASE).find(challenge)+                ?.groupValues?.getOrNull(1).orEmpty()+        val realm = param("realm")+        val nonce = param("nonce")+        if (realm.isBlank() || nonce.isBlank()) return ""+        val cnonce = UUID.randomUUID().toString().replace("-", "").take(16)+        fun h(s: String): String {+            val md = java.security.MessageDigest.getInstance("MD5")+            return md.digest(s.toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }+        }+        // Empty password: GBA-derived keys are unavailable outside the telephony stack.+        val ha1 = h("$username:$realm:")+        val ha2 = h("$method:$uri")+        val response = h("$ha1:$nonce:00000001:$cnonce:auth:$ha2")+        return "Digest username=\"$username\", realm=\"$realm\", nonce=\"$nonce\", uri=\"$uri\", " ++            "response=\"$response\", qop=auth, nc=00000001, cnonce=\"$cnonce\""+    }++    /** Pull the FT content-server URI out of RCS config XML (ftHTTPCSURI). */+    fun parseContentServer(configXml: ByteArray): String? {+        val xml = configXml.toString(Charsets.UTF_8)+        return Regex("<ftHTTPCSURI>([^<]+)</ftHTTPCSURI>", RegexOption.IGNORE_CASE).find(xml)+            ?.groupValues?.getOrNull(1)?.trim()?.takeIf { it.isNotEmpty() }+    }++    /** Expose the uploader URI type for tests without leaking Uri internals. */+    @Suppress("unused")+    private fun uriOf(s: String): Uri = s.toUri()+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImdn.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImdn.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImdn.ktnew file mode 100644index 0000000000..1b5187be1f--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsImdn.kt@@ -0,0 +1,27 @@+package com.vayunmathur.communicate.data.rcs++import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * IMDN delivery/display receipt tracker (RFC 5438).+ *+ * Outgoing CPIM carries `imdn.Message-ID`; the far end answers with+ * `message/imdn+xml` reporting `positive-delivery` / `display` / `failed`.+ * Reports arrive via [RcsSessionManager.onSipRequest] → [onReportReceived].+ * Statuses feed the `SmsMessage.status` ticks through the repository layer.+ */+object RcsImdn {+    /** message-id → latest disposition. */+    private val _reports = MutableStateFlow<Map<String, ImdnDisposition>>(emptyMap())+    val reports: StateFlow<Map<String, ImdnDisposition>> = _reports.asStateFlow()++    fun onReportReceived(body: String) {+        if (!RcsFeature.enabled) return+        val (id, disposition) = parseImdnBody(body) ?: return+        _reports.value = _reports.value + (id to disposition)+    }++    fun statusFor(messageId: String): ImdnDisposition? = _reports.value[messageId]+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.ktnew file mode 100644index 0000000000..0950db9d00--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt@@ -0,0 +1,86 @@+package com.vayunmathur.communicate.data.rcs++import android.util.Log+import java.util.UUID+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Minimal MSRP (RFC 4975) over the negotiated session socket.+ *+ * TestRcsApp's `MsrpManager`/`MsrpSession` ride a raw TCP socket to the+ * negotiated `a=path`; chunks are `MSRP <txid> SEND` with To-Path/From-Path,+ * Byte-Range, Message-ID and Content-Type headers. This port covers the+ * SEND + 200-response subset needed for CPM chat payloads (CPIM text and+ * IMDN reports travel inside sessions once established; pager-mode remains+ * the pre-session path).+ *+ * Sockets open on Dispatchers.IO; every failure returns null/false so callers+ * fall back to pager-mode. No Guava — plain suspend functions.+ */+object RcsMsrp {+    private const val TAG = "RcsMsrp"++    /**+     * Send [payload] (CPIM bytes) over an MSRP session bound to [session].+     * Opens a TCP socket to the remote path when needed. Returns true on a+     * 200 response to our SEND.+     */+    suspend fun send(+        session: RcsSession,+        payload: ByteArray,+        contentType: String = "message/cpim",+    ): Boolean = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled) return@withContext false+        val remotePath = session.msrpRemotePath ?: return@withContext false+        val localPath = session.msrpLocalPath ?: "msrp://local.invalid/${UUID.randomUUID()};tcp"+        runCatching {+            val (host, port) = parseMsrpPath(remotePath) ?: return@runCatching false+            val txid = UUID.randomUUID().toString().replace("-", "").take(12)+            val messageId = UUID.randomUUID().toString()+            val chunk = buildString {+                append("MSRP $txid SEND\r\n")+                append("To-Path: $remotePath\r\n")+                append("From-Path: $localPath\r\n")+                append("Message-ID: $messageId\r\n")+                append("Byte-Range: 1-${payload.size}/${payload.size}\r\n")+                append("Failure-Report: yes\r\n")+                append("Success-Report: no\r\n")+                append("Content-Type: $contentType\r\n")+            }+            val socket = runCatching {+                val s = java.net.Socket()+                s.connect(java.net.InetSocketAddress(host, port), 10_000)+                s.soTimeout = 10_000+                s+            }.getOrNull() ?: return@runCatching false+            socket.use { s ->+                val out = s.getOutputStream()+                out.write(chunk.toByteArray(Charsets.UTF_8))+                out.write("\r\n".toByteArray(Charsets.UTF_8))+                out.write(payload)+                out.write("\r\n-------$txid\$\r\n".toByteArray(Charsets.UTF_8))+                out.flush()+                val reply = s.getInputStream().bufferedReader(Charsets.UTF_8).readLine()+                    .orEmpty()+                reply.contains(" 200 ")+            }+        }.getOrElse {+            Log.w(TAG, "MSRP send failed", it)+            false+        }+    }++    /**+     * Parse an `msrp://host[:port]/...` path into (host, port). Default MSRP+     * port 2855 when absent.+     */+    fun parseMsrpPath(path: String): Pair<String, Int>? {+        return runCatching {+            val uri = android.net.Uri.parse(path)+            val host = uri.host ?: return null+            val port = if (uri.port > 0) uri.port else 2855+            host to port+        }.getOrNull()+    }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.ktnew file mode 100644index 0000000000..fb8618a1fc--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt@@ -0,0 +1,91 @@+package com.vayunmathur.communicate.data.rcs++/**+ * RCS Universal Profile session + messaging primitives.+ *+ * Covers the TestRcsApp gap analysis:+ * - TestRcsApp HAS: INVITE/MSRP 1:1 sessions (SimpleChatSession), CPIM+ *   envelopes (CpimUtils), FT-over-HTTP upload (FileUploadController),+ *   provisioning flow (ProvisioningController), UCE (UceActivity).+ * - TestRcsApp LACKS (built here from the UP spec): IMDN delivery/display+ *   receipts (RFC 5438), is-typing notifications (RFC 3994), group+ *   conference INVITE semantics, FT-over-HTTP receiver side.+ *+ * All SIP construction uses the `SipDelegateConfiguration` captured by+ * [RcsSipTransport] (public user identity, home domain, local address).+ * Pager-mode CPIM remains the v1 send path; sessions upgrade a conversation+ * to INVITE/MSRP when both ends support it.+ */++/** A live CPM session dialog (INVITE/200/ACK completed, MSRP bound). */+data class RcsSession(+    /** SIP dialog id (Call-ID + tags); routes in-dialog traffic. */+    val dialogId: String,+    val callId: String,+    val localTag: String,+    val remoteTag: String,+    val remoteUri: String,+    val conversationId: String,+    val isGroup: Boolean = false,+    /** MSRP path negotiated via SDP (`a=path`). Null until bound. */+    val msrpLocalPath: String? = null,+    val msrpRemotePath: String? = null,+    val createdAt: Long = System.currentTimeMillis(),+)++/** IMDN disposition (RFC 5438) for delivery/display receipts. */+enum class ImdnDisposition(val token: String) {+    Delivered("positive-delivery"),+    Displayed("display"),+    Failed("failed"),+}++/**+ * Build an IMDN `message/imdn+xml` body reporting [disposition] for+ * [originalMessageId] (the `imdn.Message-ID` from the received CPIM).+ */+fun buildImdnBody(originalMessageId: String, disposition: ImdnDisposition): String = buildString {+    append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")+    append("<imdn xmlns=\"urn:ietf:params:xml:ns:imdn\">\n")+    append("  <message-id>$originalMessageId</message-id>\n")+    append("  <datetime>${java.time.Instant.now()}</datetime>\n")+    append("  <status><${disposition.token}/></status>\n")+    append("</imdn>")+}++/** Parse an IMDN report body into (message-id, disposition), or null. */+fun parseImdnBody(body: String): Pair<String, ImdnDisposition>? {+    if (!body.contains("<imdn", ignoreCase = true)) return null+    val id = Regex("<message-id>([^<]+)</message-id>").find(body)?.groupValues?.getOrNull(1)+        ?: return null+    val disposition = ImdnDisposition.entries.firstOrNull { body.contains("<${it.token}", ignoreCase = true) }+        ?: return null+    return id.trim() to disposition+}++/** Extract the `imdn.Message-ID` from a CPIM envelope, or null. */+fun extractImdnMessageId(cpim: String): String? =+    Regex("imdn\\.Message-ID:\\s*(\\S+)", RegexOption.IGNORE_CASE).find(cpim)+        ?.groupValues?.getOrNull(1)?.trim()++/**+ * Build an `application/im-iscomposing+xml` body (RFC 3994): [active] true+ * while the user is typing, false + `lastactive` on idle.+ */+fun buildIsComposingBody(active: Boolean): String = buildString {+    append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")+    append("<isComposing xmlns=\"urn:ietf:params:xml:ns:im-composing\">\n")+    append("  <state>${if (active) "active" else "idle"}</state>\n")+    if (!active) append("  <lastactive>${java.time.Instant.now()}</lastactive>\n")+    append("</isComposing>")+}++/** True when [body] is an is-composing notification; returns active flag or null. */+fun parseIsComposingBody(body: String): Boolean? {+    if (!body.contains("im-composing", ignoreCase = true)) return null+    return when {+        body.contains("<state>active</state>", ignoreCase = true) -> true+        body.contains("<state>idle</state>", ignoreCase = true) -> false+        else -> null+    }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.ktnew file mode 100644index 0000000000..550aedd8a4--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt@@ -0,0 +1,252 @@+package com.vayunmathur.communicate.data.rcs++import android.util.Log+import java.util.UUID+import java.util.concurrent.ConcurrentHashMap+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * CPM session manager: INVITE/MSRP 1:1 dialogs + group conference dialogs.+ *+ * Mirrors TestRcsApp's `MinimalCpmChatService` (transaction → session routing,+ * dialog cache for in-dialog requests) without the jain-sip/Guava stack:+ * SIP construction is string-based from the delegate configuration, sends go+ * through [RcsSipTransport.sendSipMessage].+ *+ * v1 scope: outgoing 1:1 INVITE with SDP-for-MSRP offer, incoming INVITE auto+ * handling (200 OK + local SDP or 488), BYE teardown, and group conference+ * INVITE to the focus URI. MSRP media itself rides the negotiated socket+ * (see [RcsMsrp]); text falls back to pager-mode CPIM until the session is+ * established, exactly like ChatManager's session-init gate.+ */+object RcsSessionManager {+    private const val TAG = "RcsSession"++    private val _sessions = MutableStateFlow<Map<String, RcsSession>>(emptyMap())+    val sessions: StateFlow<Map<String, RcsSession>> = _sessions.asStateFlow()++    /** Transaction id (Via branch) → session, for response routing. */+    private val transactions = ConcurrentHashMap<String, String>()++    /** Typing state per conversation: conversationId → (active, updatedAt). */+    private val _typing = MutableStateFlow<Map<String, Boolean>>(emptyMap())+    val typing: StateFlow<Map<String, Boolean>> = _typing.asStateFlow()++    /** Active session for [conversationId], or null. */+    fun sessionFor(conversationId: String): RcsSession? = _sessions.value[conversationId]++    /**+     * Start an outgoing 1:1 CPM session: INVITE with SDP-for-MSRP offer to the+     * `tel:` URI. Returns the dialog id on accept-tracked send, null when the+     * transport is unavailable. The 200 OK/ACK/MSRP bind completes+     * asynchronously via [onSipResponse]/[onSipRequest].+     */+    suspend fun startSession(remoteTelUri: String, conversationId: String): String? {+        if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return null+        val callId = "${UUID.randomUUID()}@rcs"+        val localTag = UUID.randomUUID().toString().take(8)+        val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"+        val (startLine, headers, content) = buildInvite(remoteTelUri, callId, localTag, branch, conversationId)+        val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)+        if (!ok) return null+        val dialogId = "$callId:$localTag"+        transactions[branch] = dialogId+        _sessions.value = _sessions.value + (conversationId to RcsSession(+            dialogId = dialogId,+            callId = callId,+            localTag = localTag,+            remoteTag = "",+            remoteUri = remoteTelUri,+            conversationId = conversationId,+        ))+        return dialogId+    }++    /**+     * Start a group conference session: INVITE to the conference focus URI+     * with `Conversation-ID` + subject. Members join via the focus; per-UP the+     * focus own the participant list (no re-INVITE fan-out from us).+     */+    suspend fun startGroupSession(+        focusUri: String,+        subject: String,+        conversationId: String,+    ): String? {+        if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return null+        val callId = "${UUID.randomUUID()}@rcs"+        val localTag = UUID.randomUUID().toString().take(8)+        val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"+        val (startLine, headers, content) = buildInvite(focusUri, callId, localTag, branch, conversationId, subject)+        val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)+        if (!ok) return null+        val dialogId = "$callId:$localTag"+        transactions[branch] = dialogId+        _sessions.value = _sessions.value + (conversationId to RcsSession(+            dialogId = dialogId,+            callId = callId,+            localTag = localTag,+            remoteTag = "",+            remoteUri = focusUri,+            conversationId = conversationId,+            isGroup = true,+        ))+        return dialogId+    }++    /** Tear down the session for [conversationId] with BYE. */+    suspend fun terminateSession(conversationId: String): Boolean {+        val session = _sessions.value[conversationId] ?: return true+        val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"+        val startLine = "BYE sip:${session.remoteUri} SIP/2.0"+        val headers = buildString {+            append("Via: SIP/2.0/TCP local;branch=$branch\r\n")+            append("Call-ID: ${session.callId}\r\n")+            append("CSeq: 2 BYE\r\n")+            append("Content-Length: 0\r\n")+        }+        val ok = RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0))+        transactions.remove(branch)+        _sessions.value = _sessions.value - conversationId+        return ok+    }++    /**+     * Route an inbound SIP response (from the delegate message callback) to+     * its session: 200 OK to INVITE completes the dialog (remote tag + SDP+     * answer), other finals tear the pending session down.+     */+    fun onSipResponse(statusCode: Int, callId: String, remoteTag: String?, sdpAnswer: String?) {+        val entry = _sessions.value.entries.firstOrNull { it.value.callId == callId } ?: return+        val session = entry.value+        if (statusCode in 200..299 && !remoteTag.isNullOrBlank()) {+            val (localPath, remotePath) = parseSdpPaths(sdpAnswer)+            _sessions.value = _sessions.value + (entry.key to session.copy(+                remoteTag = remoteTag,+                msrpLocalPath = localPath,+                msrpRemotePath = remotePath,+            ))+            Log.i(TAG, "Session established ${session.dialogId}")+        } else if (statusCode >= 300) {+            Log.w(TAG, "Session failed $callId code=$statusCode")+            transactions.entries.removeIf { it.value == session.dialogId }+            _sessions.value = _sessions.value - entry.key+        }+    }++    /**+     * Route an inbound SIP request: INVITE starts an incoming session entry+     * (caller answers via [acceptIncoming]), BYE tears down, MESSAGE with+     * `message/imdn+xml` updates receipts, `im-iscomposing` updates typing.+     */+    fun onSipRequest(+        method: String,+        callId: String,+        fromUri: String,+        contentType: String?,+        body: String,+    ): RcsSession? {+        return when (method.uppercase()) {+            "INVITE" -> {+                val conversationId = fromUri.substringAfter("sip:").substringBefore("@")+                    .takeIf { it.isNotBlank() } ?: fromUri+                val session = RcsSession(+                    dialogId = "$callId:in",+                    callId = callId,+                    localTag = UUID.randomUUID().toString().take(8),+                    remoteTag = "",+                    remoteUri = fromUri,+                    conversationId = conversationId,+                )+                _sessions.value = _sessions.value + (conversationId to session)+                session+            }+            "BYE" -> {+                val entry = _sessions.value.entries.firstOrNull { it.value.callId == callId }+                if (entry != null) _sessions.value = _sessions.value - entry.key+                null+            }+            "MESSAGE" -> {+                val conversationId = fromUri.substringAfter("sip:").substringBefore("@")+                if (contentType?.contains("imdn", ignoreCase = true) == true) {+                    RcsImdn.onReportReceived(body)+                } else if (contentType?.contains("im-composing", ignoreCase = true) == true ||+                    parseIsComposingBody(body) != null+                ) {+                    val active = parseIsComposingBody(body) ?: false+                    _typing.value = _typing.value + (conversationId to active)+                }+                null+            }+            else -> null+        }+    }++    /**+     * Build an INVITE with SDP-for-MSRP offer (TestRcsApp SipUtils.buildInvite+     * header set, string-built): From (P-Preferred-Identity), To, Via,+     * Max-Forwards, Call-ID, CSeq, Contact (+sip.instance + CPM tag),+     * Conversation-ID, Contribution-ID, Accept-Contact (CPM session),+     * P-Preferred-Service (CPM URN), Route (Service-Route), User-Agent,+     * P-Access-Network-Info when configured.+     */+    fun buildInvite(+        targetUri: String,+        callId: String,+        localTag: String,+        branch: String,+        conversationId: String,+        subject: String? = null,+    ): Triple<String, String, ByteArray> {+        val cfg = RcsSipTransport.lastConfigSnapshot()+        val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"+        val sdp = buildSdpOffer(cfg?.msrpLocalIp)+        val bytes = sdp.toByteArray(Charsets.UTF_8)+        val startLine = "INVITE $targetUri SIP/2.0"+        val headers = buildString {+            append("Via: SIP/2.0/TCP local;branch=$branch\r\n")+            append("Max-Forwards: 70\r\n")+            append("From: <$from>;tag=$localTag\r\n")+            append("To: <$targetUri>\r\n")+            append("Call-ID: $callId\r\n")+            append("CSeq: 1 INVITE\r\n")+            append("Contact: <$from>;+sip.instance=\"<urn:gsma:imei:${cfg?.imei ?: "unknown"}>\";+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"\r\n")+            append("Conversation-ID: $conversationId\r\n")+            append("Contribution-ID: ${UUID.randomUUID()}\r\n")+            append("Accept-Contact: *;+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"\r\n")+            append("P-Preferred-Identity: <$from>\r\n")+            append("P-Preferred-Service: urn:urn-7:3gpp-service.ims.icsi.oma.cpm.session\r\n")+            if (subject != null) append("Subject: $subject\r\n")+            cfg?.serviceRoute?.takeIf { it.isNotBlank() }?.let { append("Route: <$it>\r\n") }+            cfg?.pani?.takeIf { it.isNotBlank() }?.let { append("P-Access-Network-Info: $it\r\n") }+            append("User-Agent: ${cfg?.userAgent ?: "Communicate-RCS/1.0"}\r\n")+            append("Content-Type: application/sdp\r\n")+            append("Content-Length: ${bytes.size}\r\n")+        }+        return Triple(startLine, headers, bytes)+    }++    private fun buildSdpOffer(localIp: String?): String {+        val ip = localIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0"+        val path = "msrp://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp"+        return buildString {+            append("v=0\r\n")+            append("o=- ${System.currentTimeMillis()} ${System.currentTimeMillis()} IN IP4 $ip\r\n")+            append("s=-\r\n")+            append("c=IN IP4 $ip\r\n")+            append("t=0 0\r\n")+            append("m=message 2855 TCP/MSRP *\r\n")+            append("a=path:$path\r\n")+            append("a=accept-types:message/cpim text/plain\r\n")+            append("a=setup:active\r\n")+        }+    }++    private fun parseSdpPaths(sdp: String?): Pair<String?, String?> {+        if (sdp.isNullOrBlank()) return null to null+        val path = Regex("a=path:(\\S+)", RegexOption.IGNORE_CASE).find(sdp)+            ?.groupValues?.getOrNull(1)?.trim()+        return null to path+    }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.ktindex 38dc105657..c0a65b10f6 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSipTransport.kt@@ -66,6 +66,37 @@ object RcsSipTransport {     /** Last IMS configuration (identity, server, route headers for sends). */     @Volatile private var lastConfig: SipDelegateConfiguration? = null +    /**+     * Snapshot of the fields SIP construction needs, decoupled from the hidden+     * config class so callers never touch framework types.+     */+    data class ConfigSnapshot(+        val version: Long,+        val publicUserId: String?,+        val homeDomain: String?,+        val msrpLocalIp: String?,+        val serviceRoute: String?,+        val pani: String?,+        val userAgent: String?,+        val imei: String?,+    )++    fun lastConfigSnapshot(): ConfigSnapshot? {+        val cfg = lastConfig ?: return null+        return runCatching {+            ConfigSnapshot(+                version = cfg.getVersion(),+                publicUserId = cfg.getPublicUserIdentifier(),+                homeDomain = cfg.getHomeDomain(),+                msrpLocalIp = null,+                serviceRoute = cfg.getSipServiceRouteHeader(),+                pani = cfg.getSipPaniHeader(),+                userAgent = cfg.getSipUserAgentHeader(),+                imei = cfg.getImei(),+            )+        }.getOrNull()+    }+     /** Inbound SIP MESSAGE listener (sync service writes to Room + notifies). */     @Volatile     var onInboundMessage: ((SipMessage) -> Unit)? = null
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.ktnew file mode 100644index 0000000000..c92ea9c924--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsE2E.kt@@ -0,0 +1,330 @@+package com.vayunmathur.communicate.data.rcs.e2e++import android.content.Context+import android.telephony.SubscriptionManager+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsMlsGroup+import com.vayunmathur.communicate.data.rcs.RcsMlsIdentity+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import java.util.UUID+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Closed-loop MLS E2EE orchestration for the RCS line (our-app-to-our-app).+ *+ * Flow:+ * - Each local E.164 gets an Ed25519 identity (generated once, Room-held).+ * - 1:1 E2EE: creator builds a group, adds the peer's key package (fetched+ *   over RCS via [RcsKeyDirectory], which exchanges key packages as opaque+ *   RCS payloads), sends Welcome + commit; joiner persists the group.+ * - Group E2EE: same, with N key packages.+ * - Sends encrypt to the group; receives decrypt by group id. Commits merge+ *   automatically inside the crate.+ *+ * Key packages are exchanged over the RCS transport itself (no side channel):+ * an unencrypted `message/cpim` with content-type `application/x-rcs-keypackage`+ * carries the TLS bytes; Welcomes ride `application/x-rcs-welcome`.+ */+object RcsE2E {+    /** Content-Type marking a key-package publication message. */+    const val CT_KEY_PACKAGE = "application/x-rcs-keypackage"++    /** Content-Type marking a Welcome envelope message. */+    const val CT_WELCOME = "application/x-rcs-welcome"++    /** Content-Type marking an MLS commit message. */+    const val CT_COMMIT = "application/x-rcs-commit"++    /** Content-Type marking an MLS application (encrypted) message. */+    const val CT_MLS = "application/x-rcs-mls"++    /** Content-Type marking a key-package request (peer auto-answers). */+    const val CT_KEY_REQUEST = "application/x-rcs-keyrequest"++    private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) }++    /**+     * Our identity bytes for [e164], generating + persisting on first use.+     * Null when the gate is off or native is unavailable.+     */+    suspend fun identityFor(context: Context, e164: String): ByteArray? =+        withContext(Dispatchers.IO) {+            if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || e164.isBlank()) return@withContext null+            val db = RcsDatabase.getDatabase(context)+            db.mlsIdentityDao().get(e164)?.identity ?: runCatching {+                val out = RustMlsCrypto.generateIdentity(e164.toByteArray(Charsets.UTF_8))+                    ?: return@runCatching null+                val identity = out.getOrNull(1) ?: return@runCatching null+                db.mlsIdentityDao().upsert(+                    RcsMlsIdentity(e164 = e164, identity = identity, updatedAt = System.currentTimeMillis()),+                )+                identity+            }.getOrNull()+        }++    /**+     * Fresh key package TLS for [e164] (publish to peers). Persists the+     * evolved storage snapshot. Null on any failure.+     */+    suspend fun freshKeyPackage(context: Context, e164: String): ByteArray? =+        withContext(Dispatchers.IO) {+            if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return@withContext null+            val identity = identityFor(context, e164) ?: return@withContext null+            val db = RcsDatabase.getDatabase(context)+            val group = db.mlsGroupDao().getByConversation(e2eThreadFor(e164))+            val storage = group?.storage ?: ByteArray(0)+            runCatching {+                val out = RustMlsCrypto.buildKeyPackage(storage, identity) ?: return@runCatching null+                val storageOut = out.getOrNull(0) ?: ByteArray(0)+                val kp = out.getOrNull(1) ?: return@runCatching null+                if (group != null) {+                    db.mlsGroupDao().upsert(group.copy(storage = storageOut, updatedAt = System.currentTimeMillis()))+                } else {+                    // No group yet: stash the snapshot under the 1:1 pseudo-group row.+                    db.mlsGroupDao().upsert(+                        RcsMlsGroup(+                            groupIdHex = "pending:$e164",+                            conversationId = e2eThreadFor(e164),+                            storage = storageOut,+                            updatedAt = System.currentTimeMillis(),+                        ),+                    )+                }+                kp+            }.getOrNull()+        }++    /**+     * Create an E2EE group for [conversationId] with our local identity, then+     * add [peerKeyPackages]. Returns the commit + welcome payloads to send+     * (commit → group thread, welcome → each joiner 1:1). Persists the group.+     */+    suspend fun createEncryptedGroup(+        context: Context,+        e164: String,+        conversationId: String,+        peerKeyPackages: List<ByteArray>,+    ): Pair<ByteArray, ByteArray>? = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || peerKeyPackages.isEmpty()) return@withContext null+        val identity = identityFor(context, e164) ?: return@withContext null+        val db = RcsDatabase.getDatabase(context)+        runCatching {+            var storage = db.mlsGroupDao().getByConversation(conversationId)?.storage ?: ByteArray(0)+            val created = RustMlsCrypto.createGroup(storage, identity) ?: return@runCatching null+            storage = created.getOrNull(0) ?: storage+            val groupId = created.getOrNull(1) ?: return@runCatching null+            val added = RustMlsCrypto.addMembers(storage, identity, groupId, peerKeyPackages.toTypedArray())+                ?: return@runCatching null+            val storageOut = added.getOrNull(0) ?: storage+            val commit = added.getOrNull(1) ?: return@runCatching null+            val welcome = added.getOrNull(2) ?: return@runCatching null+            db.mlsGroupDao().upsert(+                RcsMlsGroup(+                    groupIdHex = groupId.hex(),+                    conversationId = conversationId,+                    storage = storageOut,+                    updatedAt = System.currentTimeMillis(),+                ),+            )+            commit to welcome+        }.getOrNull()+    }++    /**+     * Join from a Welcome envelope. Persists the group under [conversationId].+     * Returns the group id, or null.+     */+    suspend fun joinEncryptedGroup(+        context: Context,+        conversationId: String,+        welcome: ByteArray,+    ): ByteArray? = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return@withContext null+        val db = RcsDatabase.getDatabase(context)+        val storage = db.mlsGroupDao().getByConversation(conversationId)?.storage ?: ByteArray(0)+        runCatching {+            val out = RustMlsCrypto.joinGroup(storage, welcome) ?: return@runCatching null+            val storageOut = out.getOrNull(0) ?: storage+            val groupId = out.getOrNull(1) ?: return@runCatching null+            db.mlsGroupDao().upsert(+                RcsMlsGroup(+                    groupIdHex = groupId.hex(),+                    conversationId = conversationId,+                    storage = storageOut,+                    updatedAt = System.currentTimeMillis(),+                ),+            )+            groupId+        }.getOrNull()+    }++    /**+     * Encrypt [plaintext] for [conversationId]'s group. Returns the framed+     * payload to send, or null.+     */+    suspend fun encryptTo(+        context: Context,+        e164: String,+        conversationId: String,+        plaintext: ByteArray,+    ): ByteArray? = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return@withContext null+        val identity = identityFor(context, e164) ?: return@withContext null+        val db = RcsDatabase.getDatabase(context)+        val group = db.mlsGroupDao().getByConversation(conversationId) ?: return@withContext null+        if (group.groupIdHex.startsWith("pending:")) return@withContext null+        runCatching {+            val groupId = group.groupIdHex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()+            val out = RustMlsCrypto.encrypt(group.storage, identity, groupId, plaintext)+                ?: return@runCatching null+            val storageOut = out.getOrNull(0) ?: group.storage+            val payload = out.getOrNull(1) ?: return@runCatching null+            db.mlsGroupDao().upsert(group.copy(storage = storageOut, updatedAt = System.currentTimeMillis()))+            payload+        }.getOrNull()+    }++    /**+     * Decrypt [payload] for [conversationId]'s group. Returns+     * `(plaintext, isApplication)` — commits merge silently with empty+     * plaintext. Null on failure (caller keeps the opaque row / drops).+     */+    suspend fun decryptFor(+        context: Context,+        conversationId: String,+        payload: ByteArray,+    ): Pair<ByteArray, Boolean>? = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return@withContext null+        val db = RcsDatabase.getDatabase(context)+        val group = db.mlsGroupDao().getByConversation(conversationId) ?: return@withContext null+        if (group.groupIdHex.startsWith("pending:")) return@withContext null+        runCatching {+            val groupId = group.groupIdHex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()+            val out = RustMlsCrypto.decrypt(group.storage, groupId, payload)+                ?: return@runCatching null+            val storageOut = out.getOrNull(0) ?: group.storage+            val isApp = (out.getOrNull(1)?.firstOrNull() ?: 0) == 1.toByte()+            val plaintext = out.getOrNull(2) ?: ByteArray(0)+            db.mlsGroupDao().upsert(group.copy(storage = storageOut, updatedAt = System.currentTimeMillis()))+            plaintext to isApp+        }.getOrNull()+    }++    /**+     * Request the peer's key package (they auto-publish on receipt) and+     * publish ours. Call when the user taps "Start encrypted chat".+     */+    suspend fun requestEncryptedChat(context: Context, localE164: String, peerE164: String): Boolean {+        if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false+        // Ensure our identity exists first.+        identityFor(context, localE164) ?: return false+        // Publish ours alongside the request so one round trip suffices.+        RcsKeyDirectory.publishTo(context, localE164, peerE164)+        return sendKeyRequest(context, peerE164)+    }++    private suspend fun sendKeyRequest(context: Context, peerE164: String): Boolean {+        if (!RcsSipTransport.canSend()) return false+        val body = "Content-Type: $CT_KEY_REQUEST\r\n\r\nrequest"+        val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+            fromUri = "sip:me@rcs",+            toUri = "sip:$peerE164@rcs",+            callId = "${UUID.randomUUID()}@rcs-kreq",+            body = body,+        )+        return runCatching { RcsSipTransport.sendSipMessage(startLine, headers, content) }+            .getOrDefault(false)+    }++    /**+     * Create the E2EE group once the peer's key package is known and send the+     * Welcome + commit. Called when a key package arrives for a conversation+     * with no group yet, or explicitly from the setup UI. Returns true when+     * the Welcome + commit were accepted by the transport.+     */+    suspend fun setupGroupWithPeer(+        context: Context,+        localE164: String,+        conversationId: String,+        peerE164: String,+        peerKeyPackage: ByteArray,+    ): Boolean {+        if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false+        val (commit, welcome) = createEncryptedGroup(context, localE164, conversationId, listOf(peerKeyPackage))+            ?: return false+        // Commit → the (new) group thread; Welcome → the peer 1:1.+        val commitOk = sendMlsEnvelope(context, conversationId, commit, CT_COMMIT)+        val welcomeOk = sendMlsEnvelope(context, peerE164, welcome, CT_WELCOME)+        // Rotate our key package now that the previous one may be consumed.+        freshKeyPackage(context, localE164)+        return commitOk && welcomeOk+    }++    private suspend fun sendMlsEnvelope(+        context: Context,+        recipient: String,+        framed: ByteArray,+        contentType: String,+    ): Boolean {+        if (!RcsSipTransport.canSend()) return false+        val b64 = android.util.Base64.encodeToString(framed, android.util.Base64.NO_WRAP)+        val body = "Content-Type: $contentType\r\n\r\n$b64"+        val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+            fromUri = "sip:me@rcs",+            toUri = "sip:$recipient@rcs",+            callId = "${UUID.randomUUID()}@rcs-env",+            body = body,+        )+        val typedHeaders = headers.replace("Content-Type: message/cpim", "Content-Type: $contentType")+        return runCatching { RcsSipTransport.sendSipMessage(startLine, typedHeaders, content) }+            .getOrDefault(false)+    }++    /** Group id for [conversationId], or null when no E2EE group exists. */+    suspend fun groupIdFor(context: Context, conversationId: String): ByteArray? =+        withContext(Dispatchers.IO) {+            if (!RcsFeature.enabled) return@withContext null+            val group = RcsDatabase.getDatabase(context).mlsGroupDao().getByConversation(conversationId)+                ?: return@withContext null+            if (group.groupIdHex.startsWith("pending:")) return@withContext null+            group.groupIdHex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()+        }++    /**+     * True when [body] (CPIM text or raw) carries an MLS payload: magic+     * prefixes after base64 decode, or the MLS content types.+     */+    fun isMlsPayload(body: String): Boolean {+        if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false+        if (body.contains(CT_MLS, ignoreCase = true) ||+            body.contains(CT_COMMIT, ignoreCase = true) ||+            body.contains(CT_WELCOME, ignoreCase = true)+        ) {+            return true+        }+        val b64 = if (body.contains("\r\n\r\n")) {+            body.substringAfter("\r\n\r\n", "").trim()+        } else {+            body.trim()+        }.takeIf { it.isNotEmpty() } ?: return false+        val bytes = runCatching {+            android.util.Base64.decode(b64, android.util.Base64.DEFAULT)+        }.getOrNull() ?: return false+        if (bytes.size < 8) return false+        return runCatching { RustMlsCrypto.payloadKind(bytes) in 0..1 }.getOrDefault(false)+    }++    /** Our own E.164 (default SMS subscription's number when readable). */+    fun localE164(context: Context): String? {+        if (!RcsFeature.enabled) return null+        return runCatching {+            val tm = context.getSystemService(android.telephony.TelephonyManager::class.java)+                ?: return null+            tm.line1Number?.takeIf { it.isNotBlank() }+        }.getOrNull()+    }++    private fun e2eThreadFor(e164: String): String = "e2e:$e164"+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsKeyDirectory.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsKeyDirectory.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsKeyDirectory.ktnew file mode 100644index 0000000000..da0879c84b--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsKeyDirectory.kt@@ -0,0 +1,57 @@+package com.vayunmathur.communicate.data.rcs.e2e++import android.content.Context+import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import java.util.UUID+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Key-package directory over the RCS transport itself (no side channel).+ *+ * Publication: our fresh key package rides an unencrypted `message/cpim`+ * with content-type [RcsE2E.CT_KEY_PACKAGE] to the peer's 1:1 thread. Peers+ * cache the latest package per sender; group creation consumes them.+ *+ * Rotation: a new package is published whenever the previous one is consumed+ * (post-Welcome) — single-use init keys mean reuse fails closed at the+ * crate layer, so rotation-on-publish keeps adds working.+ */+object RcsKeyDirectory {+    /**+     * Publish our fresh key package to [recipientE164]'s 1:1 thread+     * (unencrypted pager-mode CPIM). Returns true when the SIP leg accepted.+     */+    suspend fun publishTo(context: Context, localE164: String, recipientE164: String): Boolean =+        withContext(Dispatchers.IO) {+            if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return@withContext false+            val kp = RcsE2E.freshKeyPackage(context, localE164) ?: return@withContext false+            // Key package bytes are binary — base64 the payload into the CPIM text.+            val b64 = android.util.Base64.encodeToString(kp, android.util.Base64.NO_WRAP)+            val body = "Content-Type: ${RcsE2E.CT_KEY_PACKAGE}\r\n\r\n$b64"+            val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+                fromUri = "sip:me@rcs",+                toUri = "sip:$recipientE164@rcs",+                callId = "${UUID.randomUUID()}@rcs-kp",+                body = body,+            )+            runCatching { RcsSipTransport.sendSipMessage(startLine, headers, content) }+                .getOrDefault(false)+        }++    /**+     * Extract a key package from an inbound key-package message body, or null.+     * The CPIM text carries `Content-Type: application/x-rcs-keypackage`+     * followed by base64 TLS bytes.+     */+    fun parsePublished(body: String): ByteArray? {+        if (!body.contains(RcsE2E.CT_KEY_PACKAGE, ignoreCase = true)) return null+        val b64 = body.substringAfter("\r\n\r\n", "").ifBlank {+            body.substringAfter("\n\n", "")+        }.trim().takeIf { it.isNotEmpty() } ?: return null+        return runCatching {+            android.util.Base64.decode(b64, android.util.Base64.DEFAULT)+        }.getOrNull()?.takeIf { it.isNotEmpty() }+    }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsPeerKeys.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsPeerKeys.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsPeerKeys.ktnew file mode 100644index 0000000000..6a4093838d--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RcsPeerKeys.kt@@ -0,0 +1,41 @@+package com.vayunmathur.communicate.data.rcs.e2e++import android.content.Context+import com.vayunmathur.communicate.data.rcs.RcsDatabase+import com.vayunmathur.communicate.data.rcs.RcsFeature+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Peer key-package cache for E2EE group creation.+ *+ * Key packages arrive as unencrypted publications on 1:1 threads+ * ([RcsKeyDirectory]). The latest package per peer E.164 is kept in memory+ * (backed by nothing — packages are single-use and republished on demand, so+ * staleness fails closed at the crate layer and the creator simply requests a+ * fresh one by sending a key-package request message).+ *+ * v1 scope: in-memory only. A Room table lands with the key-rotation pass.+ */+object RcsPeerKeys {+    private val cache = java.util.concurrent.ConcurrentHashMap<String, ByteArray>()++    fun store(context: Context, peerE164: String, keyPackage: ByteArray) {+        if (!RcsFeature.enabled || peerE164.isBlank() || keyPackage.isEmpty()) return+        cache[peerE164] = keyPackage+    }++    fun get(peerE164: String): ByteArray? {+        if (!RcsFeature.enabled) return null+        return cache[peerE164]+    }++    fun consume(peerE164: String): ByteArray? {+        if (!RcsFeature.enabled) return null+        return cache.remove(peerE164)+    }++    fun clear() {+        cache.clear()+    }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RustMlsCrypto.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RustMlsCrypto.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RustMlsCrypto.ktnew file mode 100644index 0000000000..738dd2dfa8--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/e2e/RustMlsCrypto.kt@@ -0,0 +1,100 @@+package com.vayunmathur.communicate.data.rcs.e2e++import android.util.Log++/**+ * JNI bridge to the `communicate_mls` Rust crate (OpenMLS, RFC 9420).+ *+ * Flat byte protocol: every call takes opaque blobs in and returns+ * `Array<ByteArray>` (`[storage_out, result…]`) or null on error. Kotlin+ * persists `storage_out` (provider snapshot) in Room alongside conversation+ * rows; identity bytes live in the MLS identity table. The crate holds no+ * state across calls.+ *+ * Closed-loop only: our-app-to-our-app over RCS as the wire. There is no+ * interop with proprietary key distribution (e.g. Google Messages).+ */+object RustMlsCrypto {++    private const val TAG = "RustMlsCrypto"++    val isAvailable: Boolean = try {+        System.loadLibrary("communicate_mls")+        Log.i(TAG, "libcommunicate_mls loaded")+        true+    } catch (t: Throwable) {+        if (t.message?.contains("already loaded", ignoreCase = true) == true) {+            Log.i(TAG, "libcommunicate_mls already loaded")+            true+        } else {+            Log.e(TAG, "System.loadLibrary(communicate_mls) failed", t)+            false+        }+    }++    /** Generate an identity for `e164` UTF-8 bytes. Returns `[empty, identity]`. */+    @JvmStatic external fun generateIdentity(e164: ByteArray): Array<ByteArray>?++    /** Build a key package. `(storage, identity)` → `[storage_out, key_package_tls]`. */+    @JvmStatic external fun buildKeyPackage(storage: ByteArray, identity: ByteArray): Array<ByteArray>?++    /** Create a group. `(storage, identity)` → `[storage_out, group_id]`. */+    @JvmStatic external fun createGroup(storage: ByteArray, identity: ByteArray): Array<ByteArray>?++    /**+     * Add members. `(storage, identity, group_id, key_packages)` →+     * `[storage_out, commit_tls, welcome_framed]`. Send commit to the group,+     * welcome to the joiners (both over RCS).+     */+    @JvmStatic external fun addMembers(+        storage: ByteArray,+        identity: ByteArray,+        groupId: ByteArray,+        keyPackages: Array<ByteArray>,+    ): Array<ByteArray>?++    /**+     * Join from a Welcome envelope. `(storage, welcome_framed)` →+     * `[storage_out, group_id]`.+     */+    @JvmStatic external fun joinGroup(storage: ByteArray, welcome: ByteArray): Array<ByteArray>?++    /**+     * Encrypt. `(storage, identity, group_id, plaintext)` →+     * `[storage_out, framed_payload]`. Send the payload over RCS.+     */+    @JvmStatic external fun encrypt(+        storage: ByteArray,+        identity: ByteArray,+        groupId: ByteArray,+        plaintext: ByteArray,+    ): Array<ByteArray>?++    /**+     * Decrypt. `(storage, group_id, framed_payload)` →+     * `[storage_out, is_application(1B), plaintext]`.+     */+    @JvmStatic external fun decrypt(+        storage: ByteArray,+        groupId: ByteArray,+        payload: ByteArray,+    ): Array<ByteArray>?++    /**+     * Remove members by leaf index. `(storage, identity, group_id, indices_csv)` →+     * `[storage_out, commit_tls]`. Indices are ASCII decimal, comma-separated.+     */+    @JvmStatic external fun removeMembers(+        storage: ByteArray,+        identity: ByteArray,+        groupId: ByteArray,+        indicesCsv: ByteArray,+    ): Array<ByteArray>?++    /** Framing probe: 0=welcome, 1=message, 2=unknown. */+    @JvmStatic external fun payloadKind(payload: ByteArray): Int++    /** Magic prefixes for Kotlin-side routing without a JNI round trip. */+    @JvmStatic external fun welcomeMagic(): ByteArray?+    @JvmStatic external fun messageMagic(): ByteArray?+}
communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.ktindex 846111a397..8e1ddd84fa 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/telephony/RcsSyncService.kt@@ -18,9 +18,21 @@ import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.CommunicateLine import com.vayunmathur.communicate.data.CommunicateRepository import com.vayunmathur.communicate.data.cacheInboundRcs+import com.vayunmathur.communicate.data.rcs.ImdnDisposition import com.vayunmathur.communicate.data.rcs.RcsFeature+import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp+import com.vayunmathur.communicate.data.rcs.RcsImdn import com.vayunmathur.communicate.data.rcs.RcsRegistrationState+import com.vayunmathur.communicate.data.rcs.RcsSessionManager import com.vayunmathur.communicate.data.rcs.RcsSipTransport+import com.vayunmathur.communicate.data.rcs.buildImdnBody+import com.vayunmathur.communicate.data.rcs.e2e.RcsE2E+import com.vayunmathur.communicate.data.rcs.e2e.RcsKeyDirectory+import com.vayunmathur.communicate.data.rcs.e2e.RcsPeerKeys+import com.vayunmathur.communicate.data.rcs.e2e.RustMlsCrypto+import com.vayunmathur.communicate.data.rcs.extractImdnMessageId+import com.vayunmathur.communicate.data.rcs.parseImdnBody+import com.vayunmathur.communicate.data.rcs.parseIsComposingBody import com.vayunmathur.communicate.notifications.ConversationSpace import com.vayunmathur.communicate.notifications.ConversationTarget import com.vayunmathur.library.util.ensureNotificationChannel@@ -94,18 +106,75 @@ class RcsSyncService : Service() {     }      private suspend fun handleInbound(message: SipMessage) {-        val parsed = parseInbound(message) ?: return-        CommunicateRepository.cacheInboundRcs(-            context = this,-            conversationId = parsed.conversationId,-            body = parsed.body,-            senderId = parsed.senderId,-            messageId = parsed.messageId,-        )-        showIncomingNotification(parsed)+        val envelope = parseEnvelope(message) ?: return+        // E2EE control + data payloads route before plaintext handling.+        handleE2EEInbound(envelope)?.let { e2ee ->+            when (e2ee.kind) {+                InboundKind.Text -> {+                    CommunicateRepository.cacheInboundRcs(+                        context = this,+                        conversationId = e2ee.conversationId,+                        body = e2ee.body,+                        senderId = e2ee.senderId,+                        messageId = e2ee.messageId,+                        ftUrl = e2ee.ftUrl,+                        ftMime = e2ee.ftMime,+                    )+                    showIncomingNotification(e2ee)+                }+                InboundKind.Receipt, InboundKind.Typing -> Unit+            }+            return+        }+        val parsed = parseInbound(envelope) ?: return+        when (parsed.kind) {+            InboundKind.Text -> {+                CommunicateRepository.cacheInboundRcs(+                    context = this,+                    conversationId = parsed.conversationId,+                    body = parsed.body,+                    senderId = parsed.senderId,+                    messageId = parsed.messageId,+                    ftUrl = parsed.ftUrl,+                    ftMime = parsed.ftMime,+                )+                // IMDN positive-delivery: the message reached us, so tell the sender.+                sendImdnReport(parsed)+                showIncomingNotification(parsed)+            }+            InboundKind.Receipt, InboundKind.Typing -> {+                // Routed to RcsImdn / RcsSessionManager.typing by parseInbound already.+                Unit+            }+        }+    }++    private suspend fun sendImdnReport(parsed: InboundRcs) {+        val originalId = parsed.imdnMessageId ?: return+        runCatching {+            val report = buildImdnBody(originalId, ImdnDisposition.Delivered)+            val (startLine, headers, content) = RcsSipTransport.buildChatMessage(+                fromUri = "sip:me@rcs",+                toUri = "sip:${parsed.conversationId}@rcs",+                callId = "${java.util.UUID.randomUUID()}@rcs-imdn",+                body = report,+            )+            RcsSipTransport.sendSipMessage(startLine, headers, content)+        }     } -    private fun parseInbound(message: SipMessage): InboundRcs? {+    private enum class InboundKind { Text, Receipt, Typing }++    /** Raw envelope: repaired headers + sender + content type + body + ids. */+    private data class Envelope(+        val from: String,+        val contentType: String?,+        val raw: String,+        val callId: String,+        val viaBranch: String,+    )++    private fun parseEnvelope(message: SipMessage): Envelope? {         return runCatching {             // Modem quirk (TestRcsApp RegistrationControllerImpl.repairHeaderSection):             // some modems emit "ia:" instead of "Via:".@@ -117,18 +186,160 @@ class RcsSyncService : Service() {             val from = headerValue(headers, "From:")?.substringAfter("<")?.substringBefore(">")                 ?.substringAfter("sip:")?.substringBefore("@")                 ?.takeIf { it.isNotBlank() } ?: return null-            val body = extractTextBody(message.getContent()) ?: return null+            val contentType = headerValue(headers, "Content-Type:")+            val raw = message.getContent().toString(Charsets.UTF_8)+            if (raw.isBlank()) return null+            Envelope(+                from = from,+                contentType = contentType,+                raw = raw,+                callId = message.getCallIdParameter() ?: raw.hashCode().toString(),+                viaBranch = message.getViaBranchParameter(),+            )+        }.getOrNull()+    }++    private fun parseInbound(envelope: Envelope): InboundRcs? {+        return runCatching {+            val from = envelope.from+            val contentType = envelope.contentType+            val raw = envelope.raw+            // IMDN reports and is-composing route to their trackers, not the inbox.+            if (contentType?.contains("imdn", ignoreCase = true) == true ||+                parseImdnBody(raw) != null+            ) {+                RcsImdn.onReportReceived(raw)+                return InboundRcs(+                    conversationId = from,+                    body = "",+                    senderId = from,+                    messageId = "in-${envelope.callId}",+                    kind = InboundKind.Receipt,+                )+            }+            if (contentType?.contains("im-composing", ignoreCase = true) == true ||+                parseIsComposingBody(raw) != null+            ) {+                RcsSessionManager.onSipRequest("MESSAGE", envelope.callId, from, contentType, raw)+                return InboundRcs(+                    conversationId = from,+                    body = "",+                    senderId = from,+                    messageId = "in-${envelope.callId}",+                    kind = InboundKind.Typing,+                )+            }+            val body = extractTextBody(envelope.raw.toByteArray(Charsets.UTF_8)) ?: return null             if (body.isBlank()) return null-            val callId = message.getCallIdParameter() ?: body.hashCode().toString()+            // FT-over-HTTP descriptors expose URL + mime for the renderer.+            val ft = RcsFileTransferHttp.parseFtBody(body)             InboundRcs(                 conversationId = from,-                body = body,+                body = ft?.let { body.substringAfter("\r\n").ifBlank { "[file]" } } ?: body,                 senderId = from,-                messageId = "in-$callId-${message.getViaBranchParameter()}",+                messageId = "in-${envelope.callId}-${envelope.viaBranch}",+                kind = InboundKind.Text,+                ftUrl = ft?.url,+                ftMime = ft?.mime,+                imdnMessageId = extractImdnMessageId(raw),             )         }.getOrNull()     } +    /**+     * Route E2EE payloads: key-package publications (cache for group creation),+     * Welcome envelopes (join + persist), MLS commits/application (decrypt;+     * application text becomes an inbox row). Returns an [InboundRcs] when the+     * payload produces a visible row, null when fully absorbed (key packages,+     * commits, typing-like control).+     */+    private suspend fun handleE2EEInbound(envelope: Envelope): InboundRcs? {+        if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return null+        val from = envelope.from+        val contentType = envelope.contentType+        val raw = envelope.raw+        val body = extractTextBody(raw.toByteArray(Charsets.UTF_8)) ?: raw+        // Key-request → auto-publish our key package (one round trip setup).+        if (contentType?.contains(RcsE2E.CT_KEY_REQUEST, ignoreCase = true) == true ||+            body.contains(RcsE2E.CT_KEY_REQUEST, ignoreCase = true)+        ) {+            RcsE2E.localE164(this)?.let { local ->+                RcsKeyDirectory.publishTo(this, local, from)+            }+            return InboundRcs(from, "", from, "in-kreq-${System.currentTimeMillis()}", InboundKind.Typing)+        }+        // Key package publication → stash, and create the group if none exists yet.+        if (contentType?.contains(RcsE2E.CT_KEY_PACKAGE, ignoreCase = true) == true ||+            body.contains(RcsE2E.CT_KEY_PACKAGE, ignoreCase = true)+        ) {+            RcsKeyDirectory.parsePublished(body)?.let { kp ->+                RcsPeerKeys.store(this, from, kp)+                // Auto-setup: first key package for a conversation with no group+                // creates it and sends Welcome. Closed-loop peers opt in by+                // running this code; no group forms with non-participants.+                val conversationId = from+                if (RcsE2E.groupIdFor(this, conversationId) == null) {+                    RcsE2E.localE164(this)?.let { local ->+                        RcsE2E.setupGroupWithPeer(this, local, conversationId, from, kp)+                    }+                }+            }+            return InboundRcs(from, "", from, "in-kp-${System.currentTimeMillis()}", InboundKind.Typing)+        }+        // Welcome envelope → join the group, then announce with a notice row.+        if (contentType?.contains(RcsE2E.CT_WELCOME, ignoreCase = true) == true ||+            body.contains(RcsE2E.CT_WELCOME, ignoreCase = true) == true+        ) {+            val welcomeBytes = decodePayloadBody(body) ?: return null+            val conversationId = from+            val groupId = RcsE2E.joinEncryptedGroup(this, conversationId, welcomeBytes)+            if (groupId != null) {+                // Rotate: publish a fresh key package so future adds work.+                RcsE2E.localE164(this)?.let { local ->+                    RcsE2E.freshKeyPackage(this, local)+                }+                return InboundRcs(+                    conversationId, "🔒 Encrypted chat started", from,+                    "in-welcome-${System.currentTimeMillis()}",+                )+            }+            return null+        }+        // MLS data (commit or application) → decrypt against the conversation group.+        val isMls = contentType?.contains(RcsE2E.CT_MLS, ignoreCase = true) == true ||+            contentType?.contains(RcsE2E.CT_COMMIT, ignoreCase = true) == true ||+            RcsE2E.isMlsPayload(body)+        if (!isMls) return null+        val payload = decodePayloadBody(body) ?: return null+        val (plaintext, isApp) = RcsE2E.decryptFor(this, from, payload) ?: return null+        if (!isApp) return null+        val text = plaintext.toString(Charsets.UTF_8)+        if (text.isBlank()) return null+        val callId = text.hashCode().toString()+        return InboundRcs(+            conversationId = from,+            body = text,+            senderId = from,+            messageId = "in-mls-$callId-${System.currentTimeMillis()}",+            ftUrl = null,+            ftMime = null,+            imdnMessageId = extractImdnMessageId(text),+        )+    }++    /** Base64-decode a CPIM-wrapped binary payload body. */+    private fun decodePayloadBody(body: String): ByteArray? {+        val b64 = if (body.contains("\r\n\r\n")) {+            body.substringAfter("\r\n\r\n", "").trim()+        } else if (body.contains("\n\n")) {+            body.substringAfter("\n\n", "").trim()+        } else {+            body.trim()+        }.takeIf { it.isNotEmpty() } ?: return null+        return runCatching {+            android.util.Base64.decode(b64, android.util.Base64.DEFAULT)+        }.getOrNull()+    }     /**      * Extract display text from a message body. Pager-mode RCS arrives as      * `message/cpim` (TestRcsApp CpimUtils); plain `text/plain` passes through.@@ -153,6 +364,10 @@ class RcsSyncService : Service() {         val body: String,         val senderId: String,         val messageId: String,+        val kind: InboundKind = InboundKind.Text,+        val ftUrl: String? = null,+        val ftMime: String? = null,+        val imdnMessageId: String? = null,     )      private fun showIncomingNotification(parsed: InboundRcs) {
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationTopBar.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationTopBar.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationTopBar.ktindex 9ebab323a4..6a5c1a8a2e 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationTopBar.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationTopBar.kt@@ -186,6 +186,40 @@ internal fun ConversationActions(                 onClick = { ContactIntents.addToExisting(context, address) },             )         }+        // Closed-loop MLS encryption for 1:1 RCS threads (our-app-to-our-app).+        if (!isGroup && line == CommunicateLine.Rcs &&+            com.vayunmathur.communicate.data.rcs.RcsFeature.enabled+        ) {+            Item(+                text = stringResource(R.string.rcs_start_encrypted),+                leadingIcon = { com.vayunmathur.library.ui.IconLock() },+                onClick = {+                    scope.launch {+                        val ok = withContext(Dispatchers.IO) {+                            val local = com.vayunmathur.communicate.data.rcs.e2e.RcsE2E.localE164(context)+                                ?: return@withContext false+                            val peer = remoteId?.takeIf { it.isNotBlank() } ?: address+                            // Fast path: cached key package → create group immediately.+                            val cached = com.vayunmathur.communicate.data.rcs.e2e.RcsPeerKeys.consume(peer)+                            if (cached != null) {+                                com.vayunmathur.communicate.data.rcs.e2e.RcsE2E.setupGroupWithPeer(+                                    context, local, peer, peer, cached,+                                )+                            } else {+                                com.vayunmathur.communicate.data.rcs.e2e.RcsE2E.requestEncryptedChat(+                                    context, local, peer,+                                )+                            }+                        }+                        AppMessages.show(+                            context.getString(+                                if (ok) R.string.rcs_encrypted_started else R.string.rcs_encrypted_failed,+                            ),+                        )+                    }+                },+            )+        }         Item(             text = stringResource(com.vayunmathur.library.ui.R.string.delete),             leadingIcon = { com.vayunmathur.library.ui.IconDelete() },
communicate/src/main/res/values/strings.xml
diff --git a/communicate/src/main/res/values/strings.xml b/communicate/src/main/res/values/strings.xmlindex 6b91d9f4ca..d57c1cd8ea 100644--- a/communicate/src/main/res/values/strings.xml+++ b/communicate/src/main/res/values/strings.xml@@ -171,6 +171,9 @@     <string name="rcs_status_title">RCS status</string>     <string name="rcs_retry">Retry</string>     <string name="rcs_probe">Run availability check</string>+    <string name="rcs_start_encrypted">Start encrypted chat</string>+    <string name="rcs_encrypted_started">Encrypted chat requested — messages lock once the peer joins</string>+    <string name="rcs_encrypted_failed">Couldn\'t start encrypted chat</string>     <string name="inapp_ongoing_call">Ongoing call</string>     <string name="inapp_call_channel_name">Calls</string>     <string name="inapp_incoming_call_channel_name">Incoming calls</string>
communicate/src/main/rust-mls/Cargo.toml
diff --git a/communicate/src/main/rust-mls/Cargo.toml b/communicate/src/main/rust-mls/Cargo.tomlnew file mode 100644index 0000000000..2e9e3b1bc5--- /dev/null+++ b/communicate/src/main/rust-mls/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "communicate_mls"+version = "0.1.0"+edition = "2021"+description = "MLS (RFC 9420) via OpenMLS for the RCS line in communicate, exposed to Kotlin over JNI. Kotlin owns persistence (Room) and passes group/key-package state as opaque bytes; the crate never calls back into Kotlin."+license = "GPL-2.0-only"++[lib]+name = "communicate_mls"+crate-type = ["cdylib", "rlib"]++[dependencies]+openmls.workspace = true+openmls_rust_crypto.workspace = true+openmls_memory_storage.workspace = true+openmls_basic_credential.workspace = true+openmls_traits.workspace = true+tls_codec.workspace = true+ed25519-dalek.workspace = true+rand_core.workspace = true+getrandom.workspace = true+jni.workspace = true++[lints]+workspace = true
communicate/src/main/rust-mls/src/group.rs
diff --git a/communicate/src/main/rust-mls/src/group.rs b/communicate/src/main/rust-mls/src/group.rsnew file mode 100644index 0000000000..7f8e3e41af--- /dev/null+++ b/communicate/src/main/rust-mls/src/group.rs@@ -0,0 +1,386 @@+//! Closed-loop MLS groups: create, add/remove, encrypt/decrypt.+//!+//! Every function takes the Kotlin-persisted blobs in and returns updated+//! blobs out — no globals, no callbacks:+//!+//! - `storage`: opaque provider snapshot ([`crate::store`])+//! - `identity`: serialized [`crate::keys::IdentityState`]+//! - groups are addressed by their MLS `GroupId` bytes; Kotlin maps+//!   conversation ⇔ group id.+//!+//! Wire payloads are TLS-serialized `MlsMessageIn/Out` bytes, sent over RCS+//! (SIP MESSAGE / MSRP) as opaque application payloads. Welcome delivery uses+//! a small framed envelope (see [`WELCOME_MAGIC`]) carrying Welcome ++//! ratchet tree so joiners never need a side channel.++use openmls::group::{MlsGroup, MlsGroupCreateConfig, MlsGroupJoinConfig};+use openmls::key_packages::{KeyPackage, KeyPackageIn};+use openmls::prelude::{+    GroupId, KeyPackageBundle, MlsMessageBodyIn, MlsMessageIn, MlsMessageOut,+    ProcessedMessageContent, ProtocolMessage, ProtocolVersion, StagedWelcome,+};+use openmls_traits::OpenMlsProvider as _;+use tls_codec::{Deserialize as _, Serialize as _};++use crate::keys::{self};+use crate::store::SnapshotProvider;++/// Errors from group operations. Variants carry strings only so the JNI+/// boundary stays a flat byte protocol.+#[derive(Debug)]+pub enum GroupError {+    /// Caller input failed validation (bad identity, bad framing, …).+    InvalidInput(&'static str),+    /// Identity bytes failed to parse.+    BadIdentity,+    /// Storage snapshot failed to parse.+    BadSnapshot,+    /// An OpenMLS operation failed.+    Mls(String),+}++impl core::fmt::Display for GroupError {+    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {+        match self {+            GroupError::InvalidInput(m) => write!(f, "invalid input: {m}"),+            GroupError::BadIdentity => write!(f, "bad identity"),+            GroupError::BadSnapshot => write!(f, "bad snapshot"),+            GroupError::Mls(m) => write!(f, "mls error: {m}"),+        }+    }+}++/// Magic prefix for the Welcome envelope: `b"RCSMLS1W"`.+pub const WELCOME_MAGIC: &[u8; 8] = b"RCSMLS1W";++/// Magic prefix for encrypted application payloads: `b"RCSMLS1M"`.+pub const MESSAGE_MAGIC: &[u8; 8] = b"RCSMLS1M";++/// Result of creating a group: updated storage + group id.+pub struct GroupCreated {+    /// Updated provider snapshot for Kotlin to persist.+    pub storage: Vec<u8>,+    /// MLS group id bytes (conversation ⇔ group mapping key).+    pub group_id: Vec<u8>,+}++/// Result of adding members: updated storage + commit + welcome envelope.+pub struct MembersAdded {+    /// Updated provider snapshot for Kotlin to persist.+    pub storage: Vec<u8>,+    /// TLS-serialized commit (`MlsMessageOut`) to send the group.+    pub commit: Vec<u8>,+    /// [`WELCOME_MAGIC`]-framed Welcome + ratchet tree for the joiners.+    pub welcome: Vec<u8>,+}++/// Result of encrypting: updated storage + framed payload.+pub struct Encrypted {+    /// Updated provider snapshot for Kotlin to persist.+    pub storage: Vec<u8>,+    /// [`MESSAGE_MAGIC`]-framed TLS `MlsMessageOut`.+    pub payload: Vec<u8>,+}+

Diff truncated.