Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / e2e / RcsE2E.kt
RcsE2E.kt642 lines · 28.4 KiBRaw
| 1 | package com.vayunmathur.communicate.data.rcs.e2e |
| 2 | |
| 3 | import android.annotation.SuppressLint |
| 4 | import android.content.Context |
| 5 | import android.telephony.SubscriptionManager |
| 6 | import com.vayunmathur.communicate.data.rcs.RcsDatabase |
| 7 | import com.vayunmathur.communicate.data.rcs.RcsFeature |
| 8 | import com.vayunmathur.communicate.data.rcs.RcsMlsGroup |
| 9 | import com.vayunmathur.communicate.data.rcs.RcsMlsIdentity |
| 10 | import com.vayunmathur.communicate.data.rcs.RcsSipTransport |
| 11 | import java.util.UUID |
| 12 | import kotlinx.coroutines.Dispatchers |
| 13 | import kotlinx.coroutines.sync.withLock |
| 14 | import kotlinx.coroutines.withContext |
| 15 | |
| 16 | /** |
| 17 | * Closed-loop MLS E2EE orchestration for the RCS line. |
| 18 | * |
| 19 | * MLS here follows GSMA Universal Profile 3.0 (standard MLS, RFC 9420) — the |
| 20 | * same profile Google Messages uses — so the crypto is interop-shaped: |
| 21 | * standard ciphersuite, `BasicCredential` identities, TLS framing. What stays |
| 22 | * closed-loop in v1 is *key discovery*: key packages ride our own RCS |
| 23 | * content-types rather than a federated directory. |
| 24 | * |
| 25 | * Flow: |
| 26 | * - Each local E.164 gets an Ed25519 identity (generated once, Room-held). |
| 27 | * - 1:1 E2EE: creator builds a group, adds the peer's key package (fetched |
| 28 | * over RCS via [RcsKeyDirectory], which exchanges key packages as opaque |
| 29 | * RCS payloads), sends Welcome + commit; joiner persists the group. |
| 30 | * - Group E2EE: same, with N key packages. |
| 31 | * - Sends encrypt to the group; receives decrypt by group id. Commits merge |
| 32 | * automatically inside the crate. |
| 33 | * |
| 34 | * Key packages are exchanged over the RCS transport itself (no side channel): |
| 35 | * an unencrypted `message/cpim` with content-type `application/x-rcs-keypackage` |
| 36 | * carries the TLS bytes; Welcomes ride `application/x-rcs-welcome`. |
| 37 | */ |
| 38 | object RcsE2E { |
| 39 | /** Content-Type marking a key-package publication message. */ |
| 40 | const val CT_KEY_PACKAGE = "application/x-rcs-keypackage" |
| 41 | |
| 42 | /** Content-Type marking a Welcome envelope message. */ |
| 43 | const val CT_WELCOME = "application/x-rcs-welcome" |
| 44 | |
| 45 | /** Content-Type marking an MLS commit message. */ |
| 46 | const val CT_COMMIT = "application/x-rcs-commit" |
| 47 | |
| 48 | /** Content-Type marking an MLS application (encrypted) message. */ |
| 49 | const val CT_MLS = "application/x-rcs-mls" |
| 50 | |
| 51 | /** Content-Type marking a key-package request (peer auto-answers). */ |
| 52 | const val CT_KEY_REQUEST = "application/x-rcs-keyrequest" |
| 53 | |
| 54 | /** |
| 55 | * Per-conversation commit locks (§5.3): concurrent commits from two |
| 56 | * members fork the epoch. Our own commits serialize per group so we |
| 57 | * never fork ourselves; inbound epoch mismatches get one re-sync attempt |
| 58 | * in [decryptFor] before the payload is dropped. |
| 59 | */ |
| 60 | internal val commitLocks = |
| 61 | java.util.concurrent.ConcurrentHashMap<String, kotlinx.coroutines.sync.Mutex>() |
| 62 | |
| 63 | /** |
| 64 | * Safety-number fingerprint for a conversation peer (§5.4): SHA-256 of |
| 65 | * the peer's latest cached key package, grouped `XXXX XXXX …`. |
| 66 | * |
| 67 | * Closed-loop comparable: both apps fingerprint the same package bytes |
| 68 | * (our latest publication ↔ their cached copy), so matching safety |
| 69 | * numbers mean no MITM on the key directory. Null when no package is |
| 70 | * cached yet. For our own side see [mySafetyFingerprint]. |
| 71 | */ |
| 72 | suspend fun safetyFingerprint(peerE164: String): String? = |
| 73 | withContext(Dispatchers.IO) { |
| 74 | if (!RcsFeature.enabled) return@withContext null |
| 75 | val pkg = RcsPeerKeys.get(peerE164) ?: return@withContext null |
| 76 | formatSafetyNumber(pkg) |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * Our own safety number: fingerprint of our latest published package |
| 81 | * ([RcsKeyDirectory.lastPublishedFor]), same grouping. Null before our |
| 82 | * first publication. |
| 83 | */ |
| 84 | suspend fun mySafetyFingerprint(localE164: String): String? = |
| 85 | withContext(Dispatchers.IO) { |
| 86 | if (!RcsFeature.enabled) return@withContext null |
| 87 | val pkg = RcsKeyDirectory.lastPublishedFor(localE164) ?: return@withContext null |
| 88 | formatSafetyNumber(pkg) |
| 89 | } |
| 90 | |
| 91 | internal val PAYLOAD_KINDS = 0..1 |
| 92 | private const val BYTE_MASK = 0xFF |
| 93 | internal const val HEX_RADIX = 16 |
| 94 | internal const val HEX_PAIR = 2 |
| 95 | private const val SAFETY_GROUP = 4 |
| 96 | internal const val MIN_FRAME_BYTES = 8 |
| 97 | |
| 98 | private fun formatSafetyNumber(bytes: ByteArray): String { |
| 99 | val digest = java.security.MessageDigest.getInstance("SHA-256").digest(bytes) |
| 100 | return digest.joinToString("") { "%02d".format(it.toInt() and BYTE_MASK) } |
| 101 | .chunked(SAFETY_GROUP).joinToString(" ") |
| 102 | } |
| 103 | |
| 104 | /** |
| 105 | * Whether [e164]'s identity is user-verified (§5.4). |
| 106 | */ |
| 107 | suspend fun isVerified(context: Context, e164: String): Boolean = |
| 108 | withContext(Dispatchers.IO) { |
| 109 | if (!RcsFeature.enabled) return@withContext false |
| 110 | RcsDatabase.getDatabase(context).mlsIdentityDao().get(e164)?.verified == true |
| 111 | } |
| 112 | |
| 113 | /** |
| 114 | * Mark [e164]'s identity verified/unverified (from the verify screen). |
| 115 | */ |
| 116 | suspend fun setVerified(context: Context, e164: String, verified: Boolean) { |
| 117 | withContext(Dispatchers.IO) { |
| 118 | if (!RcsFeature.enabled) return@withContext |
| 119 | val db = RcsDatabase.getDatabase(context) |
| 120 | db.mlsIdentityDao().get(e164)?.let { |
| 121 | db.mlsIdentityDao().upsert(it.copy(verified = verified)) |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /** |
| 127 | * Check a peer's key package against their verified identity (§5.4). |
| 128 | * Returns true when the peer was previously VERIFIED (via the verify |
| 129 | * screen) and this package differs from the one recorded at verify time |
| 130 | * — i.e. a possible re-install or MITM, exactly Signal's safety-number |
| 131 | * change warning. Verification is cleared so the user must re-verify. |
| 132 | * Unverified peers always return false (nothing to compare against). |
| 133 | */ |
| 134 | suspend fun checkPeerIdentityChange( |
| 135 | context: Context, |
| 136 | peerE164: String, |
| 137 | keyPackage: ByteArray, |
| 138 | ): Boolean = withContext(Dispatchers.IO) { |
| 139 | if (!RcsFeature.enabled || keyPackage.isEmpty()) return@withContext false |
| 140 | val db = RcsDatabase.getDatabase(context) |
| 141 | val record = db.mlsIdentityDao().get(peerE164) ?: return@withContext false |
| 142 | if (!record.verified) return@withContext false |
| 143 | val sketch = java.security.MessageDigest.getInstance("SHA-256").digest(keyPackage) |
| 144 | // The verified record stores the package sketch witnessed at verify |
| 145 | // time in its identity bytes (see setVerifiedWithPackage). |
| 146 | if (!record.identity.contentEquals(sketch)) { |
| 147 | db.mlsIdentityDao().upsert(record.copy(verified = false)) |
| 148 | return@withContext true |
| 149 | } |
| 150 | false |
| 151 | } |
| 152 | |
| 153 | /** |
| 154 | * Verify [peerE164] against the currently cached package sketch (from |
| 155 | * the verify screen after comparing safety numbers out-of-band). |
| 156 | */ |
| 157 | suspend fun setVerifiedWithPackage(context: Context, peerE164: String, keyPackage: ByteArray) { |
| 158 | withContext(Dispatchers.IO) { |
| 159 | if (!RcsFeature.enabled || keyPackage.isEmpty()) return@withContext |
| 160 | val db = RcsDatabase.getDatabase(context) |
| 161 | val sketch = java.security.MessageDigest.getInstance("SHA-256").digest(keyPackage) |
| 162 | db.mlsIdentityDao().upsert( |
| 163 | RcsMlsIdentity( |
| 164 | e164 = peerE164, |
| 165 | identity = sketch, |
| 166 | updatedAt = System.currentTimeMillis(), |
| 167 | verified = true, |
| 168 | ), |
| 169 | ) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /** |
| 174 | * Our identity bytes for [e164], generating + persisting on first use. |
| 175 | * Null when the gate is off or native is unavailable. |
| 176 | */ |
| 177 | suspend fun identityFor(context: Context, e164: String): ByteArray? = |
| 178 | withContext(Dispatchers.IO) { |
| 179 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || e164.isBlank()) return@withContext null |
| 180 | val db = RcsDatabase.getDatabase(context) |
| 181 | db.mlsIdentityDao().get(e164)?.identity ?: runCatching { |
| 182 | val out = RustMlsCrypto.generateIdentity(e164.toByteArray(Charsets.UTF_8)) |
| 183 | ?: return@runCatching null |
| 184 | val identity = out.getOrNull(1) ?: return@runCatching null |
| 185 | db.mlsIdentityDao().upsert( |
| 186 | RcsMlsIdentity(e164 = e164, identity = identity, updatedAt = System.currentTimeMillis()), |
| 187 | ) |
| 188 | identity |
| 189 | }.getOrNull() |
| 190 | } |
| 191 | |
| 192 | /** |
| 193 | * Fresh key package TLS for [e164] (publish to peers). Persists the |
| 194 | * evolved storage snapshot. Null on any failure. |
| 195 | */ |
| 196 | suspend fun freshKeyPackage(context: Context, e164: String): ByteArray? = |
| 197 | withContext(Dispatchers.IO) { |
| 198 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return@withContext null |
| 199 | val identity = identityFor(context, e164) ?: return@withContext null |
| 200 | val db = RcsDatabase.getDatabase(context) |
| 201 | val group = db.mlsGroupDao().getByConversation(e2eThreadFor(e164)) |
| 202 | val storage = group?.storage ?: ByteArray(0) |
| 203 | runCatching { |
| 204 | val out = RustMlsCrypto.buildKeyPackage(storage, identity) ?: return@runCatching null |
| 205 | val storageOut = out.getOrNull(0) ?: ByteArray(0) |
| 206 | val kp = out.getOrNull(1) ?: return@runCatching null |
| 207 | if (group != null) { |
| 208 | db.mlsGroupDao().upsert(group.copy(storage = storageOut, updatedAt = System.currentTimeMillis())) |
| 209 | } else { |
| 210 | // No group yet: stash the snapshot under the 1:1 pseudo-group row. |
| 211 | db.mlsGroupDao().upsert( |
| 212 | RcsMlsGroup( |
| 213 | groupIdHex = "pending:$e164", |
| 214 | conversationId = e2eThreadFor(e164), |
| 215 | storage = storageOut, |
| 216 | updatedAt = System.currentTimeMillis(), |
| 217 | ), |
| 218 | ) |
| 219 | } |
| 220 | kp |
| 221 | }.getOrNull() |
| 222 | } |
| 223 | |
| 224 | /** |
| 225 | * Remove members from [conversationId]'s MLS group by leaf index (see the |
| 226 | * `removeMembers` JNI contract: ASCII decimal CSV). Sends the commit to |
| 227 | * the group thread so remaining members ratchet forward — removed members |
| 228 | * can no longer decrypt. Persists the evolved snapshot + pruned member |
| 229 | * map. Serialized per group (§5.3). |
| 230 | * |
| 231 | * Prefer [removeMembersByE164]; use this only when indices are already |
| 232 | * known. Returns true when the commit was accepted by the transport. |
| 233 | */ |
| 234 | suspend fun removeMembers( |
| 235 | context: Context, |
| 236 | e164: String, |
| 237 | conversationId: String, |
| 238 | leafIndices: List<Int>, |
| 239 | ): Boolean = withContext(Dispatchers.IO) { |
| 240 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || leafIndices.isEmpty()) { |
| 241 | return@withContext false |
| 242 | } |
| 243 | commitLockFor(conversationId).withLock { |
| 244 | val identity = identityFor(context, e164) ?: return@withLock false |
| 245 | val db = RcsDatabase.getDatabase(context) |
| 246 | val group = db.mlsGroupDao().getByConversation(conversationId) ?: return@withLock false |
| 247 | if (group.groupIdHex.startsWith("pending:")) return@withLock false |
| 248 | val groupId = group.groupIdHex.chunked(HEX_PAIR).map { it.toInt(HEX_RADIX).toByte() }.toByteArray() |
| 249 | val csv = leafIndices.distinct().sorted().joinToString(",") |
| 250 | .toByteArray(Charsets.US_ASCII) |
| 251 | val out = runCatching { |
| 252 | RustMlsCrypto.removeMembers(group.storage, identity, groupId, csv) |
| 253 | }.getOrNull() ?: return@withLock false |
| 254 | val storageOut = out.getOrNull(0) ?: group.storage |
| 255 | val commit = out.getOrNull(1) ?: return@withLock false |
| 256 | val droppedIdx = leafIndices.toSet() |
| 257 | db.mlsGroupDao().upsert( |
| 258 | group.copy( |
| 259 | storage = storageOut, |
| 260 | updatedAt = System.currentTimeMillis(), |
| 261 | members = pruneMembers(group.members, droppedIdx), |
| 262 | ), |
| 263 | ) |
| 264 | RcsE2ETransport.sendMlsEnvelope(conversationId, commit, CT_COMMIT) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | /** |
| 269 | * Remove members by E.164 using the tracked leaf map (§5.2). Unknown |
| 270 | * E.164s (never added through this client) are ignored. Returns true |
| 271 | * when at least one member was removed and committed. |
| 272 | */ |
| 273 | suspend fun removeMembersByE164( |
| 274 | context: Context, |
| 275 | e164: String, |
| 276 | conversationId: String, |
| 277 | peers: List<String>, |
| 278 | ): Boolean { |
| 279 | if (!RcsFeature.enabled || peers.isEmpty()) return false |
| 280 | val db = RcsDatabase.getDatabase(context) |
| 281 | val group = db.mlsGroupDao().getByConversation(conversationId) ?: return false |
| 282 | val indexByMember = parseMembers(group.members) |
| 283 | val indices = peers.mapNotNull { indexByMember[it.trim()] } |
| 284 | if (indices.isEmpty()) return false |
| 285 | return removeMembers(context, e164, conversationId, indices) |
| 286 | } |
| 287 | |
| 288 | /** Leaf index of [peer] in [conversationId]'s group, or null. */ |
| 289 | suspend fun leafIndexFor(context: Context, conversationId: String, peer: String): Int? = |
| 290 | withContext(Dispatchers.IO) { |
| 291 | if (!RcsFeature.enabled) return@withContext null |
| 292 | val group = RcsDatabase.getDatabase(context).mlsGroupDao() |
| 293 | .getByConversation(conversationId) ?: return@withContext null |
| 294 | parseMembers(group.members)[peer.trim()] |
| 295 | } |
| 296 | |
| 297 | |
| 298 | /** |
| 299 | * Record added members' leaf indices. The crate assigns leaves in join |
| 300 | * order starting after our own leaf 0: for an N-member add to a group |
| 301 | * whose current max leaf is M, new leaves are M+1..M+N in package order. |
| 302 | * Best-effort (crate-internal, but stable for add-order tracking). |
| 303 | */ |
| 304 | fun trackAddedMembers( |
| 305 | csv: String, |
| 306 | peerE164s: List<String>, |
| 307 | ): String { |
| 308 | val current = parseMembers(csv).toMutableMap() |
| 309 | var next = (current.values.maxOrNull() ?: -1) + 1 |
| 310 | // Our own leaf is 0 when the map is empty (creator). |
| 311 | if (current.isEmpty()) next = 1 |
| 312 | for (peer in peerE164s) { |
| 313 | val member = peer.trim() |
| 314 | if (member.isNotEmpty() && member !in current) { |
| 315 | current[member] = next++ |
| 316 | } |
| 317 | } |
| 318 | return current.entries.joinToString(",") { "${it.key}=${it.value}" } |
| 319 | } |
| 320 | |
| 321 | /** |
| 322 | * Create an E2EE group for [conversationId] with our local identity, then |
| 323 | * add [peerKeyPackages]. Returns the commit + welcome payloads to send |
| 324 | * (commit → group thread, welcome → each joiner 1:1). Persists the group. |
| 325 | */ |
| 326 | suspend fun createEncryptedGroup( |
| 327 | context: Context, |
| 328 | e164: String, |
| 329 | conversationId: String, |
| 330 | peerKeyPackages: List<ByteArray>, |
| 331 | ): Pair<ByteArray, ByteArray>? = withContext(Dispatchers.IO) { |
| 332 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || peerKeyPackages.isEmpty()) return@withContext null |
| 333 | val identity = identityFor(context, e164) ?: return@withContext null |
| 334 | val db = RcsDatabase.getDatabase(context) |
| 335 | runCatching { |
| 336 | var storage = db.mlsGroupDao().getByConversation(conversationId)?.storage ?: ByteArray(0) |
| 337 | val created = RustMlsCrypto.createGroup(storage, identity) ?: return@runCatching null |
| 338 | storage = created.getOrNull(0) ?: storage |
| 339 | val groupId = created.getOrNull(1) ?: return@runCatching null |
| 340 | val added = RustMlsCrypto.addMembers(storage, identity, groupId, peerKeyPackages.toTypedArray()) |
| 341 | ?: return@runCatching null |
| 342 | val storageOut = added.getOrNull(0) ?: storage |
| 343 | val commit = added.getOrNull(1) ?: return@runCatching null |
| 344 | val welcome = added.getOrNull(2) ?: return@runCatching null |
| 345 | db.mlsGroupDao().upsert( |
| 346 | RcsMlsGroup( |
| 347 | groupIdHex = groupId.hex(), |
| 348 | conversationId = conversationId, |
| 349 | storage = storageOut, |
| 350 | updatedAt = System.currentTimeMillis(), |
| 351 | ), |
| 352 | ) |
| 353 | commit to welcome |
| 354 | }.getOrNull() |
| 355 | } |
| 356 | |
| 357 | /** |
| 358 | * Join from a Welcome envelope. Persists the group under [conversationId]. |
| 359 | * Returns the group id, or null. |
| 360 | */ |
| 361 | suspend fun joinEncryptedGroup( |
| 362 | context: Context, |
| 363 | conversationId: String, |
| 364 | welcome: ByteArray, |
| 365 | ): ByteArray? = withContext(Dispatchers.IO) { |
| 366 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return@withContext null |
| 367 | val db = RcsDatabase.getDatabase(context) |
| 368 | // The Welcome's key-package private key lives in the pending |
| 369 | // snapshot freshKeyPackage stashed under our own 1:1 thread, not |
| 370 | // under the (new) conversation's row: without it the native join |
| 371 | // has no key material and always fails for a first group. |
| 372 | val storage = db.mlsGroupDao().getByConversation(conversationId)?.storage |
| 373 | ?: db.mlsGroupDao().getPending()?.storage |
| 374 | ?: ByteArray(0) |
| 375 | runCatching { |
| 376 | val out = RustMlsCrypto.joinGroup(storage, welcome) ?: return@runCatching null |
| 377 | val storageOut = out.getOrNull(0) ?: storage |
| 378 | val groupId = out.getOrNull(1) ?: return@runCatching null |
| 379 | db.mlsGroupDao().upsert( |
| 380 | RcsMlsGroup( |
| 381 | groupIdHex = groupId.hex(), |
| 382 | conversationId = conversationId, |
| 383 | storage = storageOut, |
| 384 | updatedAt = System.currentTimeMillis(), |
| 385 | ), |
| 386 | ) |
| 387 | groupId |
| 388 | }.getOrNull() |
| 389 | } |
| 390 | |
| 391 | /** |
| 392 | * Encrypt [plaintext] for [conversationId]'s group. Returns the framed |
| 393 | * payload to send, or null. |
| 394 | */ |
| 395 | suspend fun encryptTo( |
| 396 | context: Context, |
| 397 | e164: String, |
| 398 | conversationId: String, |
| 399 | plaintext: ByteArray, |
| 400 | ): ByteArray? = withContext(Dispatchers.IO) { |
| 401 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return@withContext null |
| 402 | val identity = identityFor(context, e164) ?: return@withContext null |
| 403 | val db = RcsDatabase.getDatabase(context) |
| 404 | val group = db.mlsGroupDao().getByConversation(conversationId) ?: return@withContext null |
| 405 | if (group.groupIdHex.startsWith("pending:")) return@withContext null |
| 406 | runCatching { |
| 407 | val groupId = group.groupIdHex.chunked(HEX_PAIR).map { it.toInt(HEX_RADIX).toByte() }.toByteArray() |
| 408 | val out = RustMlsCrypto.encrypt(group.storage, identity, groupId, plaintext) |
| 409 | ?: return@runCatching null |
| 410 | val storageOut = out.getOrNull(0) ?: group.storage |
| 411 | val payload = out.getOrNull(1) ?: return@runCatching null |
| 412 | db.mlsGroupDao().upsert(group.copy(storage = storageOut, updatedAt = System.currentTimeMillis())) |
| 413 | payload |
| 414 | }.getOrNull() |
| 415 | } |
| 416 | |
| 417 | /** |
| 418 | * Decrypt [payload] for [conversationId]'s group. Returns |
| 419 | * `(plaintext, isApplication)` — commits merge silently with empty |
| 420 | * plaintext. Null on failure (caller keeps the opaque row / drops). |
| 421 | */ |
| 422 | suspend fun decryptFor( |
| 423 | context: Context, |
| 424 | conversationId: String, |
| 425 | payload: ByteArray, |
| 426 | ): Pair<ByteArray, Boolean>? = withContext(Dispatchers.IO) { |
| 427 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return@withContext null |
| 428 | val db = RcsDatabase.getDatabase(context) |
| 429 | val group = db.mlsGroupDao().getByConversation(conversationId) ?: return@withContext null |
| 430 | if (group.groupIdHex.startsWith("pending:")) return@withContext null |
| 431 | runCatching { |
| 432 | val groupId = group.groupIdHex.chunked(HEX_PAIR).map { it.toInt(HEX_RADIX).toByte() }.toByteArray() |
| 433 | val out = RustMlsCrypto.decrypt(group.storage, groupId, payload) |
| 434 | ?: return@runCatching null |
| 435 | val storageOut = out.getOrNull(0) ?: group.storage |
| 436 | val isApp = (out.getOrNull(1)?.firstOrNull() ?: 0) == 1.toByte() |
| 437 | val plaintext = out.getOrNull(2) ?: ByteArray(0) |
| 438 | db.mlsGroupDao().upsert(group.copy(storage = storageOut, updatedAt = System.currentTimeMillis())) |
| 439 | plaintext to isApp |
| 440 | }.getOrNull() |
| 441 | } |
| 442 | |
| 443 | /** |
| 444 | * Request the peer's key package (they auto-publish on receipt) and |
| 445 | * publish ours. Call when the user taps "Start encrypted chat". |
| 446 | */ |
| 447 | suspend fun requestEncryptedChat(context: Context, localE164: String, peerE164: String): Boolean { |
| 448 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false |
| 449 | // Ensure our identity exists first. |
| 450 | identityFor(context, localE164) ?: return false |
| 451 | // Publish ours alongside the request so one round trip suffices. |
| 452 | RcsKeyDirectory.publishTo(context, localE164, peerE164) |
| 453 | return RcsE2ETransport.sendKeyRequest(peerE164) |
| 454 | } |
| 455 | |
| 456 | |
| 457 | /** |
| 458 | * Request one peer's key package (public; the peer auto-publishes). |
| 459 | * Used for N-peer group setup when cached packages are missing. |
| 460 | */ |
| 461 | suspend fun requestKeyPackage(peerE164: String): Boolean { |
| 462 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false |
| 463 | return RcsE2ETransport.sendKeyRequest(peerE164) |
| 464 | } |
| 465 | |
| 466 | /** |
| 467 | * Create the E2EE group for N peers and fan out: one commit to the group |
| 468 | * thread ([CT_COMMIT]), one Welcome per peer 1:1 ([CT_WELCOME]). Persists |
| 469 | * the group under [conversationId]. Returns true when every leg was |
| 470 | * accepted by the transport. |
| 471 | */ |
| 472 | suspend fun setupEncryptedGroup( |
| 473 | context: Context, |
| 474 | localE164: String, |
| 475 | conversationId: String, |
| 476 | peerPackages: Map<String, ByteArray>, |
| 477 | ): Boolean { |
| 478 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || peerPackages.isEmpty()) return false |
| 479 | val (commit, welcome) = createEncryptedGroup( |
| 480 | context, localE164, conversationId, peerPackages.values.toList(), |
| 481 | ) ?: return false |
| 482 | // Track leaf indices for later removal (§5.2). |
| 483 | RcsE2ETransport.trackGroupMembers(context, conversationId, peerPackages.keys.toList()) |
| 484 | var ok = RcsE2ETransport.sendMlsEnvelope(conversationId, commit, CT_COMMIT) |
| 485 | for ((peer, _) in peerPackages) { |
| 486 | ok = RcsE2ETransport.sendMlsEnvelope(peer, welcome, CT_WELCOME) && ok |
| 487 | } |
| 488 | // Rotate our key package now that the previous one may be consumed. |
| 489 | freshKeyPackage(context, localE164) |
| 490 | // Replenish the published pool (§5.1). |
| 491 | RcsE2ETransport.replenishKeyPackages(context, peerPackages.keys.toList(), localE164) |
| 492 | return ok |
| 493 | } |
| 494 | |
| 495 | /** |
| 496 | * Create the E2EE group once the peer's key package is known and send the |
| 497 | * Welcome + commit. Called when a key package arrives for a conversation |
| 498 | * with no group yet, or explicitly from the setup UI. Returns true when |
| 499 | * the Welcome + commit were accepted by the transport. |
| 500 | */ |
| 501 | suspend fun setupGroupWithPeer( |
| 502 | context: Context, |
| 503 | localE164: String, |
| 504 | conversationId: String, |
| 505 | peerE164: String, |
| 506 | peerKeyPackage: ByteArray, |
| 507 | ): Boolean { |
| 508 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false |
| 509 | val (commit, welcome) = createEncryptedGroup(context, localE164, conversationId, listOf(peerKeyPackage)) |
| 510 | ?: return false |
| 511 | RcsE2ETransport.trackGroupMembers(context, conversationId, listOf(peerE164)) |
| 512 | // Commit → the (new) group thread; Welcome → the peer 1:1. |
| 513 | val commitOk = RcsE2ETransport.sendMlsEnvelope(conversationId, commit, CT_COMMIT) |
| 514 | val welcomeOk = RcsE2ETransport.sendMlsEnvelope(peerE164, welcome, CT_WELCOME) |
| 515 | // Rotate our key package now that the previous one may be consumed. |
| 516 | freshKeyPackage(context, localE164) |
| 517 | RcsE2ETransport.replenishKeyPackages(context, listOf(peerE164), localE164) |
| 518 | return commitOk && welcomeOk |
| 519 | } |
| 520 | |
| 521 | /** Group id for [conversationId], or null when no E2EE group exists. */ |
| 522 | suspend fun groupIdFor(context: Context, conversationId: String): ByteArray? = |
| 523 | withContext(Dispatchers.IO) { |
| 524 | if (!RcsFeature.enabled) return@withContext null |
| 525 | val group = RcsDatabase.getDatabase(context).mlsGroupDao().getByConversation(conversationId) |
| 526 | ?: return@withContext null |
| 527 | if (group.groupIdHex.startsWith("pending:")) return@withContext null |
| 528 | group.groupIdHex.chunked(HEX_PAIR).map { it.toInt(HEX_RADIX).toByte() }.toByteArray() |
| 529 | } |
| 530 | |
| 531 | /** |
| 532 | * True when [body] (CPIM text or raw) carries an MLS payload: magic |
| 533 | * prefixes after base64 decode, or the MLS content types. |
| 534 | */ |
| 535 | fun isMlsPayload(body: String): Boolean { |
| 536 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable) return false |
| 537 | if (body.contains(CT_MLS, ignoreCase = true) || |
| 538 | body.contains(CT_COMMIT, ignoreCase = true) || |
| 539 | body.contains(CT_WELCOME, ignoreCase = true) |
| 540 | ) { |
| 541 | return true |
| 542 | } |
| 543 | val b64 = if (body.contains("\r\n\r\n")) { |
| 544 | body.substringAfter("\r\n\r\n", "").trim() |
| 545 | } else { |
| 546 | body.trim() |
| 547 | }.takeIf { it.isNotEmpty() } ?: return false |
| 548 | val bytes = runCatching { |
| 549 | android.util.Base64.decode(b64, android.util.Base64.DEFAULT) |
| 550 | }.getOrNull() ?: return false |
| 551 | if (bytes.size < MIN_FRAME_BYTES) return false |
| 552 | return runCatching { RustMlsCrypto.payloadKind(bytes) in PAYLOAD_KINDS }.getOrDefault(false) |
| 553 | } |
| 554 | |
| 555 | /** Our own E.164 (default SMS subscription's number when readable). */ |
| 556 | // Own subscriber number for MLS/SIP addressing: the user's own line, not |
| 557 | // a device identifier, and end-to-end RCS cannot address us without it. |
| 558 | @SuppressLint("HardwareIds") |
| 559 | fun localE164(context: Context): String? { |
| 560 | if (!RcsFeature.enabled) return null |
| 561 | val tm = context.getSystemService(android.telephony.TelephonyManager::class.java) |
| 562 | ?: return null |
| 563 | return try { |
| 564 | tm.line1Number?.takeIf { it.isNotBlank() } |
| 565 | } catch (_: SecurityException) { |
| 566 | null |
| 567 | } catch (_: Exception) { |
| 568 | null |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | |
| 573 | |
| 574 | |
| 575 | } |
| 576 | |
| 577 | /** |
| 578 | * SIP transport legs for [RcsE2E]: key-package requests, MLS envelope fan-out, |
| 579 | * member tracking and key-package replenishment. |
| 580 | */ |
| 581 | internal object RcsE2ETransport { |
| 582 | suspend fun sendKeyRequest(peerE164: String): Boolean { |
| 583 | if (!RcsSipTransport.canSend()) return false |
| 584 | val body = "Content-Type: ${RcsE2E.CT_KEY_REQUEST}\r\n\r\nrequest" |
| 585 | val (startLine, headers, content) = RcsSipTransport.buildChatMessage( |
| 586 | fromUri = "sip:me@rcs", |
| 587 | toUri = "sip:$peerE164@rcs", |
| 588 | callId = "${UUID.randomUUID()}@rcs-kreq", |
| 589 | body = body, |
| 590 | ) |
| 591 | return runCatching { RcsSipTransport.sendSipMessage(startLine, headers, content) } |
| 592 | .getOrDefault(false) |
| 593 | } |
| 594 | /** |
| 595 | * Merge [peers] into the tracked member map for [conversationId]'s group |
| 596 | * (§5.2). Best-effort; never throws. |
| 597 | */ |
| 598 | suspend fun trackGroupMembers(context: Context, conversationId: String, peers: List<String>) { |
| 599 | if (!RcsFeature.enabled || peers.isEmpty()) return |
| 600 | runCatching { |
| 601 | val db = RcsDatabase.getDatabase(context) |
| 602 | val group = db.mlsGroupDao().getByConversation(conversationId) ?: return |
| 603 | db.mlsGroupDao().upsert( |
| 604 | group.copy( |
| 605 | members = RcsE2E.trackAddedMembers(group.members, peers), |
| 606 | updatedAt = System.currentTimeMillis(), |
| 607 | ), |
| 608 | ) |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | /** |
| 613 | * Key-package replenishment (§5.1): after consuming our published package |
| 614 | * in a setup, immediately publish a fresh one to the same peers so their |
| 615 | * cached pool stays warm and the next add doesn't stall on a round trip. |
| 616 | */ |
| 617 | suspend fun replenishKeyPackages(context: Context, peers: List<String>, localE164: String) { |
| 618 | if (!RcsFeature.enabled || !RustMlsCrypto.isAvailable || peers.isEmpty()) return |
| 619 | for (peer in peers) { |
| 620 | runCatching { RcsKeyDirectory.publishTo(context, localE164, peer) } |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | suspend fun sendMlsEnvelope( |
| 625 | recipient: String, |
| 626 | framed: ByteArray, |
| 627 | contentType: String, |
| 628 | ): Boolean { |
| 629 | if (!RcsSipTransport.canSend()) return false |
| 630 | val b64 = android.util.Base64.encodeToString(framed, android.util.Base64.NO_WRAP) |
| 631 | val body = "Content-Type: $contentType\r\n\r\n$b64" |
| 632 | val (startLine, headers, content) = RcsSipTransport.buildChatMessage( |
| 633 | fromUri = "sip:me@rcs", |
| 634 | toUri = "sip:$recipient@rcs", |
| 635 | callId = "${UUID.randomUUID()}@rcs-env", |
| 636 | body = body, |
| 637 | ) |
| 638 | val typedHeaders = headers.replace("Content-Type: message/cpim", "Content-Type: $contentType") |
| 639 | return runCatching { RcsSipTransport.sendSipMessage(startLine, typedHeaders, content) } |
| 640 | .getOrDefault(false) |
| 641 | } |
| 642 | } |