communicate: various fixes
- Commit
e7e120d901b47c99bdbe0de9e6d99f77bd3f60e3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-14 04:44 UTC (3 months ago)
- Parents
5284e93
Diff
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 985075f768..a3e66e54e8 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -27,6 +27,15 @@ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" /> + <!-- WhatsApp calling (Phase D/E): camera for video calls + FGS types for in-call mic/camera. -->+ <uses-permission android:name="android.permission.CAMERA" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />++ <uses-feature+ android:name="android.hardware.camera.any"+ android:required="false" />+ <uses-feature android:name="android.hardware.telephony" android:required="false" />
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.ktindex b271ef4070..436334cb0b 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -916,6 +916,14 @@ object CommunicateRepository { com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.getOnlineOrLastStatus(context, lidJids, lastActiveFilter) } + /**+ * Refresh a peer's presence for an open thread and emit a [WhatsAppEvent.PresenceUpdate]+ * (Phase F 1e enrichment). Dev-gated + best-effort.+ */+ suspend fun whatsAppRefreshPresence(conversationId: String) = withContext(Dispatchers.IO) {+ WhatsAppClient.refreshPresence(conversationId)+ }+ /** MEX Signal-prekey publish (`xwa2_set_messaging_keys`); mints + persists one-time prekeys. */ suspend fun whatsAppSetMessagingKeys( context: Context,@@ -924,6 +932,49 @@ object CommunicateRepository { com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.setMessagingKeys(context) } + /**+ * Sync the device address book to WhatsApp (contact discovery + primary full sync) and persist+ * the returned LID/phone mappings. Dev-gated; requires READ_CONTACTS. Returns the sync summary.+ */+ suspend fun whatsAppSyncContacts(+ context: Context,+ ): com.vayunmathur.communicate.data.whatsapp.WhatsAppContactSync.SyncResult = withContext(Dispatchers.IO) {+ com.vayunmathur.communicate.data.whatsapp.WhatsAppContactSync.sync(context)+ }++ // ---- WhatsApp calling (Phase D/E), dev-gated pass-throughs to the call manager ----++ /** Observable call state for the WhatsApp calling UI. */+ val whatsAppCallState: kotlinx.coroutines.flow.StateFlow<com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallState>+ get() = com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager.state++ /** Place a WhatsApp audio/video call to [conversationId] (a `wa:<jid>` id or bare JID). */+ fun whatsAppPlaceCall(conversationId: String, video: Boolean = false) {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return+ WhatsAppClient.placeCall(conversationId, video)+ }++ fun whatsAppAnswerCall() {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return+ com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager.answer()+ }++ fun whatsAppRejectCall() {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return+ com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager.reject()+ }++ fun whatsAppHangupCall() {+ if (!com.vayunmathur.communicate.data.whatsapp.WhatsAppFeature.enabled) return+ com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager.hangup()+ }++ fun whatsAppSetCallMuted(muted: Boolean) =+ com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager.setMuted(muted)++ fun whatsAppSetCallSpeaker(on: Boolean) =+ com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager.setSpeaker(on)+ /** * Create a WhatsApp group with [subject] and the given [contacts] (phone numbers / addresses). * Each contact is normalized to a full WhatsApp user JID before the create IQ is sent. Returns
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.ktindex 4e883493db..b880b8b3ed 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppAuthData.kt@@ -52,6 +52,14 @@ data class WhatsAppAuthData( // Kept so the ported message engine compiles; both remain empty for a primary line. val lid: String = "", val accountSignedDeviceIdentity: String = "",+ // ---- Post-quantum (Kyber1024 / ML-KEM) last-resort prekey (e_pq_* bundle, Phase B 2d) ----+ // All-or-none: emitted together in RegistrationKeys.bundleFields when the id is non-zero.+ val pqLastResortKeyId: Int = 0,+ val pqLastResortPublic: String = "", // Base64 (raw 1568B Kyber1024 pub)+ val pqLastResortSecret: String = "", // Base64 (serialized KEM secret key)+ val pqLastResortSignature: String = "", // Base64 (64B XEdDSA sig over 0x08||pub)+ // Profile name sent to /v2/* for new clients (profile_name, w2.md §2.2).+ val profileName: String = "", ) { companion object { // Distinct from the companion's "whatsapp_auth" in the messages module.
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.ktindex 5bd13e2cbb..5bb60d3899 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppClient.kt@@ -14,6 +14,7 @@ import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.communicate.data.whatsapp.e2e.WhatsAppE2E import com.vayunmathur.communicate.data.whatsapp.transport.WhatsAppSocket import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallSignaling+import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -162,6 +163,7 @@ object WhatsAppClient { if (!initialized.compareAndSet(false, true)) return appContext = context.applicationContext as Application db = WhatsAppDatabase.getDatabase(appContext)+ WhatsAppCallManager.init(appContext, callBridge) Log.i(TAG, "init") runBlocking { val auth = WhatsAppAuthData.load(appContext)@@ -572,6 +574,62 @@ object WhatsAppClient { participantCount = participantJids.size, serviceData = serviceData, ))+ // Phase F 1e: best-effort MEX enrichment beyond the classic w:g2 path (subject/description).+ // Dev-gated; no-ops when the op's doc_id isn't in the bundled persist map.+ if (WhatsAppFeature.enabled && subject == null) {+ runCatching { enrichGroupFromMex(groupJid, participantJids.size) }+ }+ }++ /**+ * Enrich a group thread via `xwa2_group_query_by_id` (Phase F 1e). Emits a follow-up+ * [WhatsAppEvent.ConversationUpdate] with the MEX-reported subject when available. Best-effort:+ * silently returns on transport error / missing doc_id.+ */+ private suspend fun enrichGroupFromMex(groupJid: String, participantCount: Int) {+ val res = com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.groupQueryById(appContext, groupJid)+ if (!res.isSuccess) return+ val data = res.data ?: return+ val group = data.optJSONObject("xwa2_group_query_by_id") ?: return+ val subject = group.optJSONObject("subject")?.optString("subject")?.ifEmpty { null }+ ?: group.optString("subject").ifEmpty { null } ?: return+ _events.emit(WhatsAppEvent.ConversationUpdate(+ source = MessageSource.WHATSAPP,+ conversationId = "wa:$groupJid",+ peerName = subject,+ peerPhone = null,+ avatarUrl = null,+ lastPreview = null,+ lastTimestamp = 0L,+ unreadCount = 0,+ isGroup = true,+ participantCount = participantCount,+ ))+ }++ /**+ * Refresh a peer's presence via `xwa2_presence_data_platform_get_online_or_last_status` and emit+ * [WhatsAppEvent.PresenceUpdate] (Phase F 1e). Dev-gated + best-effort. [conversationId] may be a+ * `wa:<jid>` id or a bare JID.+ */+ suspend fun refreshPresence(conversationId: String) {+ if (!WhatsAppFeature.enabled) return+ val jid = extractJid(conversationId) ?: return+ val res = runCatching {+ com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps.getOnlineOrLastStatus(appContext, listOf(jid), null)+ }.getOrNull() ?: return+ if (!res.isSuccess) return+ val data = res.data ?: return+ val payload = data.optJSONObject("xwa2_presence_data_platform_get_online_or_last_status") ?: return+ val presences = payload.optJSONArray("presences") ?: return+ if (presences.length() == 0) return+ val p = presences.optJSONObject(0) ?: return+ val lastSeen = p.optString("last_seen").toLongOrNull() ?: 0L+ _events.emit(WhatsAppEvent.PresenceUpdate(+ conversationId = "wa:$jid",+ isOnline = lastSeen == 0L, // online payloads omit last_seen; last-status carries it+ lastSeen = lastSeen,+ )) } /**@@ -1407,6 +1465,10 @@ object WhatsAppClient { * From Go handleWACallStart. */ private suspend fun handleCallNotification(node: WhatsAppProtocol.Node, from: String) {+ // Route the typed stanza to the call state machine (offer/preaccept/accept/reject/+ // terminate/relay). This drives ringing + WebRTC media (client-to-client).+ WhatsAppCallSignaling.parse(node)?.let { WhatsAppCallManager.onInbound(it) }+ val offer = node.getChildByTag("offer") if (offer != null) { // Go handleWACallStart: ignore calls older than 15 minutes@@ -2126,6 +2188,65 @@ object WhatsAppClient { ) } + /**+ * Transport bridge for [WhatsAppCallManager]: lets the call state machine send `<call>` stanzas+ * and encrypt/decrypt the per-device call key without depending on the socket/Signal internals.+ */+ private val callBridge = object : WhatsAppCallManager.Bridge {+ override val ownJid: String get() = authData?.wid ?: ""++ override fun newId(): String = generateMessageId()++ override suspend fun sendCallStanza(node: WhatsAppProtocol.Node): Boolean {+ val ws = webSocket ?: return false+ return ws.send(WhatsAppProtocol.encodeNode(node))+ }++ override suspend fun encryptCallKey(+ toJid: String,+ paddedCallKey: ByteArray,+ ): List<WhatsAppProtocol.ParticipantEnc> {+ val auth = authData ?: return emptyList()+ val crypto = ensureE2E(auth) ?: return emptyList()+ val ownUser = auth.wid.substringBefore("@").substringBefore(":").substringBefore(".")+ val devices = (getUserDevices(listOf(toJid)).ifEmpty { listOf(toJid) } ++ getUserDevices(listOf("[email protected]"))).distinct()+ return encryptForDevices(crypto, devices, ownUser, auth.wid, paddedCallKey, null).first+ }++ override suspend fun decryptCallKey(+ senderJid: String,+ encType: String,+ ciphertext: ByteArray,+ ): ByteArray? {+ val auth = authData ?: return null+ val crypto = ensureE2E(auth) ?: return null+ return try {+ crypto.decryptDM(senderJid, isPreKey = encType == "pkmsg", ciphertext = ciphertext)+ } catch (e: Exception) {+ Log.w(TAG, "call key decrypt failed from $senderJid", e)+ null+ }+ }++ override fun emit(event: WhatsAppEvent) {+ scope.launch { _events.emit(event) }+ }++ override fun resolveName(jid: String): String? {+ // Non-suspend, best-effort: the phone form of the JID. Full name resolution happens+ // later off the emitted event (resolveName is suspend / DB-backed).+ val local = jid.substringBefore("@").substringBefore(":").substringBefore(".")+ return if (local.isNotEmpty() && local.all { it.isDigit() }) "+$local" else null+ }+ }++ /** Place a WhatsApp call (audio or video) via the call manager. */+ fun placeCall(conversationId: String, video: Boolean = false) {+ val to = extractJid(conversationId) ?: return+ WhatsAppCallManager.placeCall(to, video)+ }+ /** * Build a Signal-encrypted text message node for a recipient, fanning out to all of the * recipient's devices and our own other devices (via usync), establishing sessions as needed.@@ -2585,6 +2706,8 @@ object WhatsAppClient { } scope.launch { maybeUploadPreKeys() } scope.launch { refreshPrivacySettings() }+ // Phase C 2f: best-effort device-contact sync after login (dev-gated, needs READ_CONTACTS).+ scope.launch { runCatching { WhatsAppContactSync.sync(appContext) } } val pas = setPassiveActive() WhatsAppDiag.log(TAG, "post-success: SetPassive(active) ${if (pas) "OK" else "FAILED"}") sendUnavailablePresence()
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppContactSync.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppContactSync.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppContactSync.ktnew file mode 100644index 0000000000..b616be858c--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppContactSync.kt@@ -0,0 +1,178 @@+package com.vayunmathur.communicate.data.whatsapp++import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.provider.ContactsContract+import android.telephony.TelephonyManager+import android.util.Log+import com.google.i18n.phonenumbers.PhoneNumberUtil+import com.vayunmathur.communicate.data.whatsapp.mex.MexResult+import com.vayunmathur.communicate.data.whatsapp.mex.WhatsAppMexOps+import java.util.UUID+import org.json.JSONObject++/**+ * Device address-book → WhatsApp contact sync (w2.md §8.3, Phase C 2f).+ *+ * Reads the device contacts (behind a `READ_CONTACTS` check — the permission is already declared in+ * the module manifest), normalizes numbers to E.164 via libphonenumber, de-dups, chunks, and drives+ * [WhatsAppMexOps.primaryContactsFullSync] (paged: one `session_id` UUID across pages, `last=true`+ * on the final page) followed by [WhatsAppMexOps.contactDiscovery]. Returned LID/phone mappings are+ * persisted to the [WhatsAppContact] Room table so 1:1 threads can be enriched.+ *+ * Dev-only scaffolding: the MEX contact ops resolve their `doc_id` from the bundled persist-id map,+ * which is currently empty, so the sync gracefully no-ops (persisting the local numbers with+ * `onWhatsApp=false`) until real ids are captured. Live validation is impossible (test number is+ * banned).+ */+object WhatsAppContactSync {++ private const val TAG = "WAContactSync"+ private const val PAGE_SIZE = 500++ data class DeviceContact(val e164: String, val name: String)++ data class SyncResult(+ val deviceCount: Int,+ val e164Count: Int,+ val onWhatsAppCount: Int,+ val transportError: String? = null,+ )++ /**+ * Normalize a raw phone string to E.164 using [region] (ISO-3166 alpha-2). Pure/JVM-testable+ * (libphonenumber only). Returns null when the number can't be parsed.+ */+ fun normalizeE164(raw: String, region: String): String? = runCatching {+ val util = PhoneNumberUtil.getInstance()+ val parsed = util.parse(raw, region)+ if (!util.isValidNumber(parsed)) return null+ util.format(parsed, PhoneNumberUtil.PhoneNumberFormat.E164)+ }.getOrNull()++ /** The device's default region (SIM/network country, falling back to the locale). */+ fun defaultRegion(context: Context): String = runCatching {+ val tm = context.getSystemService(TelephonyManager::class.java)+ (tm?.simCountryIso?.takeIf { it.isNotBlank() } ?: tm?.networkCountryIso)?.uppercase()+ }.getOrNull()?.takeIf { it.isNotBlank() }+ ?: context.resources.configuration.locales[0].country.ifEmpty { "US" }++ /** Read (name, number) pairs from the device address book. Empty when permission is missing. */+ fun readDeviceContacts(context: Context): List<Pair<String, String>> {+ if (context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {+ return emptyList()+ }+ val projection = arrayOf(+ ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,+ ContactsContract.CommonDataKinds.Phone.NUMBER,+ )+ return runCatching {+ context.contentResolver.query(+ ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null,+ )?.use { cursor ->+ buildList {+ val nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY)+ val numIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)+ while (cursor.moveToNext()) {+ val number = cursor.getString(numIdx).orEmpty().trim()+ if (number.isEmpty()) continue+ add(cursor.getString(nameIdx).orEmpty() to number)+ }+ }+ }.orEmpty()+ }.getOrDefault(emptyList())+ }++ /**+ * Run a full contact sync: read → normalize → dedup → paged full-sync → discovery → persist.+ * Best-effort; never throws (returns a [SyncResult] with a transportError on MEX failure).+ */+ suspend fun sync(context: Context, syncContext: String = "PERIODIC_SYNC"): SyncResult {+ if (!WhatsAppFeature.enabled) return SyncResult(0, 0, 0, "disabled")+ val region = defaultRegion(context)+ val device = readDeviceContacts(context)++ // Normalize + de-dup by E.164, keeping the first display name seen.+ val byE164 = LinkedHashMap<String, String>()+ for ((name, number) in device) {+ val e164 = normalizeE164(number, region) ?: continue+ byE164.putIfAbsent(e164, name)+ }+ val e164s = byE164.keys.toList()+ if (e164s.isEmpty()) {+ return SyncResult(deviceCount = device.size, e164Count = 0, onWhatsAppCount = 0)+ }++ // Persist the local numbers first (onWhatsApp defaults false) so the mapping table is+ // populated even when the MEX ops can't resolve a doc_id.+ val now = System.currentTimeMillis()+ val db = WhatsAppDatabase.getDatabase(context)+ db.contactDao().upsertAll(+ byE164.map { (e164, name) -> WhatsAppContact(phoneE164 = e164, displayName = name, updatedAt = now) },+ )++ // Paged primary-contacts full sync: one session id, last=true on the final page.+ val sessionId = UUID.randomUUID().toString()+ val pages = e164s.chunked(PAGE_SIZE)+ var transportError: String? = null+ pages.forEachIndexed { index, page ->+ val res = WhatsAppMexOps.primaryContactsFullSync(+ context = context,+ rawPhoneNumbers = page,+ sessionId = sessionId,+ pageIndex = index,+ last = index == pages.lastIndex,+ syncContext = syncContext,+ )+ if (res.transportError != null) transportError = res.transportError+ }++ // Discovery resolves per-number LID + on-WhatsApp status; parse and persist mappings.+ val discovery = WhatsAppMexOps.contactDiscovery(context, e164s, "SEARCH")+ val mappings = parseDiscovery(discovery)+ if (mappings.isNotEmpty()) {+ db.contactDao().upsertAll(+ mappings.map { (e164, m) ->+ WhatsAppContact(+ phoneE164 = e164,+ lid = m.lid,+ displayName = byE164[e164] ?: "",+ onWhatsApp = m.onWhatsApp,+ updatedAt = now,+ )+ },+ )+ }+ if (discovery.transportError != null) transportError = discovery.transportError++ val onWa = mappings.count { it.value.onWhatsApp }+ Log.i(TAG, "sync: device=${device.size} e164=${e164s.size} onWA=$onWa err=$transportError")+ return SyncResult(device.size, e164s.size, onWa, transportError)+ }++ private data class Mapping(val lid: String, val onWhatsApp: Boolean)++ /**+ * Parse `xwa2_contact_discovery` results into E.164 → (lid, onWhatsApp). Tolerant of missing+ * fields (the exact wire shape depends on captured doc_ids). Ref w2.md §8.3+ * XWA2ContactDiscoveryResult / XWA2PhoneDiscoveryOutput (status IN|OUT|INVALID).+ */+ private fun parseDiscovery(result: MexResult): Map<String, Mapping> {+ val data = result.data ?: return emptyMap()+ val payload = data.optJSONObject("xwa2_contact_discovery") ?: return emptyMap()+ val results = payload.optJSONArray("results") ?: return emptyMap()+ val out = LinkedHashMap<String, Mapping>()+ for (i in 0 until results.length()) {+ val r = results.optJSONObject(i) ?: continue+ val lid = r.optString("lid", "")+ val detail: JSONObject? = r.optJSONObject("detail")+ val rawPn = detail?.optString("normalized_phone").orEmpty()+ .ifEmpty { detail?.optString("raw_pn").orEmpty() }+ val status = detail?.optString("status").orEmpty()+ val onWa = status.equals("IN", ignoreCase = true) || (lid.isNotEmpty() && !r.optBoolean("failed", false))+ if (rawPn.isNotEmpty()) out[rawPn] = Mapping(lid, onWa)+ }+ return out+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.ktindex 54f4929806..14d634c093 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppDatabase.kt@@ -46,8 +46,12 @@ import com.vayunmathur.library.util.DatabaseMigrations // communicate additions: message/reaction cache for the merged inbox. WhatsAppCachedMessage::class, WhatsAppCachedReaction::class,+ // communicate v3: device-contact sync (address book → LID/phone mapping).+ WhatsAppContact::class,+ // communicate v4: call log.+ WhatsAppCallLog::class, ],- version = 2,+ version = 4, exportSchema = false ) @TypeConverters(WhatsAppTypeConverters::class)@@ -66,6 +70,8 @@ abstract class WhatsAppDatabase : RoomDatabase() { abstract fun e2eSenderKeyDao(): WhatsAppE2ESenderKeyDao abstract fun cachedMessageDao(): WhatsAppCachedMessageDao abstract fun cachedReactionDao(): WhatsAppCachedReactionDao+ abstract fun contactDao(): WhatsAppContactDao+ abstract fun callLogDao(): WhatsAppCallLogDao companion object : DatabaseMigrations { @Volatile@@ -92,7 +98,38 @@ abstract class WhatsAppDatabase : RoomDatabase() { } } - override val migrations: List<Migration> = listOf(MIGRATION_1_2)+ /** v2 → v3: device-contact sync table (address book → WhatsApp LID/phone mapping). */+ private val MIGRATION_2_3 = object : Migration(2, 3) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL(+ "CREATE TABLE IF NOT EXISTS whatsapp_contact (" ++ "phoneE164 TEXT NOT NULL PRIMARY KEY, " ++ "lid TEXT NOT NULL DEFAULT '', " ++ "displayName TEXT NOT NULL DEFAULT '', " ++ "onWhatsApp INTEGER NOT NULL DEFAULT 0, " ++ "updatedAt INTEGER NOT NULL DEFAULT 0)",+ )+ }+ }++ /** v3 → v4: call-log table for the WhatsApp calling stack. */+ private val MIGRATION_3_4 = object : Migration(3, 4) {+ override fun migrate(db: SupportSQLiteDatabase) {+ db.execSQL(+ "CREATE TABLE IF NOT EXISTS whatsapp_call_log (" ++ "callId TEXT NOT NULL PRIMARY KEY, " ++ "peerJid TEXT NOT NULL DEFAULT '', " ++ "peerName TEXT NOT NULL DEFAULT '', " ++ "outgoing INTEGER NOT NULL DEFAULT 0, " ++ "video INTEGER NOT NULL DEFAULT 0, " ++ "startTime INTEGER NOT NULL DEFAULT 0, " ++ "durationSeconds INTEGER NOT NULL DEFAULT 0, " ++ "outcome TEXT NOT NULL DEFAULT '')",+ )+ }+ }++ override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4) fun getDatabase(context: Context): WhatsAppDatabase { return INSTANCE ?: synchronized(this) {@@ -515,3 +552,74 @@ interface WhatsAppCachedReactionDao { @Query("DELETE FROM whatsapp_cached_reaction WHERE messageId = :messageId") suspend fun clearForMessage(messageId: String) }++// -- communicate device-contact sync (address book → WhatsApp LID/phone mapping, Phase C 2f) --++/**+ * A device address-book contact synced to WhatsApp. Keyed by the E.164 phone number; [lid] and+ * [onWhatsApp] are filled in from `xwa2_primary_contacts_full_sync` / `xwa2_contact_discovery`+ * results, [displayName] from the device contact name.+ */+@Entity(tableName = "whatsapp_contact")+data class WhatsAppContact(+ @PrimaryKey val phoneE164: String,+ val lid: String = "",+ val displayName: String = "",+ val onWhatsApp: Boolean = false,+ val updatedAt: Long = 0L,+)++@Dao+interface WhatsAppContactDao {+ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(contact: WhatsAppContact)++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsertAll(contacts: List<WhatsAppContact>)++ @Query("SELECT * FROM whatsapp_contact WHERE phoneE164 = :phoneE164 LIMIT 1")+ suspend fun get(phoneE164: String): WhatsAppContact?++ @Query("SELECT * FROM whatsapp_contact WHERE lid = :lid LIMIT 1")+ suspend fun getByLid(lid: String): WhatsAppContact?++ @Query("SELECT * FROM whatsapp_contact WHERE onWhatsApp = 1 ORDER BY displayName COLLATE NOCASE ASC")+ suspend fun getOnWhatsApp(): List<WhatsAppContact>++ @Query("SELECT * FROM whatsapp_contact")+ suspend fun getAll(): List<WhatsAppContact>++ @Query("DELETE FROM whatsapp_contact")+ suspend fun deleteAll()+}++// -- communicate call log (Phase D 3e) --++/** A completed/attempted WhatsApp call, keyed by call id. */+@Entity(tableName = "whatsapp_call_log")+data class WhatsAppCallLog(+ @PrimaryKey val callId: String,+ val peerJid: String = "",+ val peerName: String = "",+ val outgoing: Boolean = false,+ val video: Boolean = false,+ val startTime: Long = 0L,+ val durationSeconds: Long = 0L,+ /** "answered" | "missed" | "rejected" | "failed" | reason string. */+ val outcome: String = "",+)++@Dao+interface WhatsAppCallLogDao {+ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(entry: WhatsAppCallLog)++ @Query("SELECT * FROM whatsapp_call_log ORDER BY startTime DESC LIMIT :limit")+ suspend fun getRecent(limit: Int = 200): List<WhatsAppCallLog>++ @Query("SELECT * FROM whatsapp_call_log WHERE callId = :callId LIMIT 1")+ suspend fun get(callId: String): WhatsAppCallLog?++ @Query("DELETE FROM whatsapp_call_log")+ suspend fun deleteAll()+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.ktindex 29fc6abd7a..a282c5afc8 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEvent.kt@@ -202,6 +202,35 @@ sealed interface WhatsAppEvent { override val source: MessageSource = MessageSource.WHATSAPP, val conversations: List<WhatsAppHistoryConversation>, ) : WhatsAppEvent++ // ---- Calling (Phase D/E) ----++ /** An inbound call offer arrived (ringing). */+ data class CallOffer(+ override val source: MessageSource = MessageSource.WHATSAPP,+ val callId: String,+ val from: String,+ val callCreator: String,+ val isVideo: Boolean,+ val peerName: String? = null,+ val timestamp: Long = System.currentTimeMillis(),+ ) : WhatsAppEvent++ /** A call's lifecycle phase changed (dialing/ringing/active/…). [phase] is a WhatsAppCallPhase name. */+ data class CallStateChanged(+ override val source: MessageSource = MessageSource.WHATSAPP,+ val callId: String,+ val phase: String,+ val isVideo: Boolean = false,+ ) : WhatsAppEvent++ /** A call ended. [reason] mirrors the terminate reason (or a local cause). */+ data class CallEnded(+ override val source: MessageSource = MessageSource.WHATSAPP,+ val callId: String,+ val reason: String,+ val durationSeconds: Long = 0L,+ ) : WhatsAppEvent } /** Transport/login lifecycle states for the primary client. */
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.ktindex f6fea86532..cfcba76fd5 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/WhatsAppEventProcessor.kt@@ -17,6 +17,7 @@ class WhatsAppEventProcessor(private val db: WhatsAppDatabase) { private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val messages = db.cachedMessageDao()+ private val callLog = db.callLogDao() private val reactions = db.cachedReactionDao() private val conversations = db.conversationDao() @@ -180,7 +181,27 @@ class WhatsAppEventProcessor(private val db: WhatsAppDatabase) { if (rows.isNotEmpty()) messages.upsertAll(rows) } - else -> { /* StateChanged, receipts, typing, presence, etc. — not persisted. */ }+ is WhatsAppEvent.CallEnded -> {+ // Persist a call-log row (Phase D 3e). Best-effort; peer/name/direction come from+ // the live call state if still present.+ val st = com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager.state.value+ runCatching {+ callLog.upsert(+ WhatsAppCallLog(+ callId = event.callId,+ peerJid = st.peerJid,+ peerName = st.peerName,+ outgoing = st.phase == com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallPhase.Outgoing,+ video = st.isVideo,+ startTime = System.currentTimeMillis() - event.durationSeconds * 1000,+ durationSeconds = event.durationSeconds,+ outcome = event.reason,+ ),+ )+ }+ }++ else -> { /* StateChanged, receipts, typing, presence, call offer/state, etc. — not persisted here. */ } } }
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallCrypto.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallCrypto.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallCrypto.ktnew file mode 100644index 0000000000..4851c430ba--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallCrypto.kt@@ -0,0 +1,102 @@+package com.vayunmathur.communicate.data.whatsapp.call++import java.nio.ByteBuffer+import java.security.SecureRandom+import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec++/**+ * WhatsApp call-key crypto (Phase D 3b, whatsapp-documentation.md:373 `CryptoCallback`).+ *+ * The 32-byte **call key** is generated by the caller and fanned out per-device via the same Signal+ * `<enc>` path as messages (see [WhatsAppCallSignaling] / `WhatsAppClient.encryptForDevices`). From+ * it, both sides derive symmetric **media keys** via HKDF-SHA256 + HMAC-SHA256 and a **secure SSRC**,+ * matching the `CryptoCallback` contract, and support `call_rekey` (a new call key derived from the+ * previous one for a rekey message id).+ *+ * All derivations are pure (java.security only) and deterministic, so the vectors are unit-testable.+ *+ * NB: our client-to-client media path uses WebRTC's own DTLS-SRTP; these keys model WhatsApp's+ * native SRTP key schedule and are exchanged/verified alongside the SDP so the derivation is+ * exercised and asserted, even though byte-level interop with WhatsApp's native relay isn't possible.+ */+object WhatsAppCallCrypto {++ const val CALL_KEY_LEN = 32+ private const val SRTP_KEY_LEN = 16 // AES-128+ private const val SRTP_SALT_LEN = 14 // SRTP session salt+ private const val AUTH_KEY_LEN = 32 // HMAC-SHA256 auth key++ private const val INFO_MEDIA = "WhatsApp Call Media Keys"+ private const val INFO_REKEY = "WhatsApp Call Rekey"+ private const val INFO_SSRC = "WhatsApp Call SSRC"++ private val rng = SecureRandom()++ /** Derived symmetric media material for one direction of a call. */+ data class MediaKeys(+ val encKey: ByteArray, // 16B SRTP AES-128 key+ val salt: ByteArray, // 14B SRTP session salt+ val authKey: ByteArray, // 32B HMAC-SHA256 auth key+ val ssrc: Int, // secure (non-negative) synchronization source id+ )++ /** Generate a fresh 32-byte call key. */+ fun generateCallKey(): ByteArray = ByteArray(CALL_KEY_LEN).also { rng.nextBytes(it) }++ /**+ * Derive the media keys + secure SSRC for [callId] from [callKey]. Deterministic: the same+ * (callKey, callId) always yields the same keys, so both peers agree.+ */+ fun deriveMediaKeys(callKey: ByteArray, callId: String): MediaKeys {+ val salt = callId.toByteArray(Charsets.UTF_8)+ val out = hkdfSha256(callKey, salt, INFO_MEDIA.toByteArray(Charsets.UTF_8), SRTP_KEY_LEN + SRTP_SALT_LEN)+ val encKey = out.copyOfRange(0, SRTP_KEY_LEN)+ val srtpSalt = out.copyOfRange(SRTP_KEY_LEN, SRTP_KEY_LEN + SRTP_SALT_LEN)+ val authKey = hmacSha256(callKey, encKey + srtpSalt).copyOf(AUTH_KEY_LEN)+ val ssrc = deriveSsrc(callKey, callId)+ return MediaKeys(encKey, srtpSalt, authKey, ssrc)+ }++ /** Secure SSRC: top 31 bits of HMAC-SHA256(callKey, "…SSRC"||callId), always non-negative. */+ fun deriveSsrc(callKey: ByteArray, callId: String): Int {+ val mac = hmacSha256(callKey, (INFO_SSRC + callId).toByteArray(Charsets.UTF_8))+ val raw = ByteBuffer.wrap(mac, 0, 4).int+ return raw and 0x7FFFFFFF+ }++ /**+ * Derive a new call key for a `call_rekey` identified by [rekeyId], chained from the previous+ * [prevCallKey]. Distinct from the original key so a compromised prior key can't decrypt after+ * rekey. Ref whatsapp-documentation.md `call_rekey`.+ */+ fun rekey(prevCallKey: ByteArray, rekeyId: String): ByteArray =+ hkdfSha256(prevCallKey, rekeyId.toByteArray(Charsets.UTF_8), INFO_REKEY.toByteArray(Charsets.UTF_8), CALL_KEY_LEN)++ // -- primitives --++ fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray {+ val mac = Mac.getInstance("HmacSHA256")+ mac.init(SecretKeySpec(key, "HmacSHA256"))+ return mac.doFinal(data)+ }++ /** HKDF-SHA256 (RFC 5869). null/empty salt = 32 zero bytes. */+ fun hkdfSha256(ikm: ByteArray, salt: ByteArray?, info: ByteArray, length: Int): ByteArray {+ val actualSalt = if (salt == null || salt.isEmpty()) ByteArray(32) else salt+ val prk = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(actualSalt, "HmacSHA256")) }.doFinal(ikm)+ val out = ByteArray(length)+ var t = ByteArray(0)+ var pos = 0+ var counter = 1+ while (pos < length) {+ val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(prk, "HmacSHA256")) }+ mac.update(t); mac.update(info); mac.update(counter.toByte())+ t = mac.doFinal()+ val n = minOf(t.size, length - pos)+ System.arraycopy(t, 0, out, pos, n)+ pos += n; counter+++ }+ return out+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallManager.ktnew file mode 100644index 0000000000..3730f84a70--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallManager.kt@@ -0,0 +1,283 @@+package com.vayunmathur.communicate.data.whatsapp.call++import android.content.Context+import android.util.Log+import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch++/** Coarse call lifecycle exposed to the UI. */+enum class WhatsAppCallPhase { Idle, Outgoing, Incoming, Connecting, Active, Ended }++data class WhatsAppCallState(+ val phase: WhatsAppCallPhase = WhatsAppCallPhase.Idle,+ val callId: String = "",+ val peerJid: String = "",+ val peerName: String = "",+ val isVideo: Boolean = false,+ val muted: Boolean = false,+ val speaker: Boolean = false,+)++/**+ * Orchestrates a single WhatsApp 1:1 call (Phase D 3c): wires [WhatsAppCallSignaling] to the+ * [WhatsAppCallSession] media leg and the [WhatsAppCallCrypto] call key, publishing a+ * [WhatsAppCallState] flow. Mirrors `GoogleVoiceCallManager`.+ *+ * It talks to the transport (socket send + per-device call-key encrypt/decrypt) through a [Bridge]+ * implemented by `WhatsAppClient`, so this class has no direct socket/Signal dependency and the+ * client stays the single owner of the Noise connection.+ *+ * Interop: the local SDP + ICE are carried inside our `<webrtc>` `<call>` extension, so calling+ * works **client-to-client (our app ↔ our app)** but not against official WhatsApp servers.+ */+object WhatsAppCallManager {++ private const val TAG = "WACallManager"++ /** Transport hooks the client provides. */+ interface Bridge {+ val ownJid: String+ fun newId(): String+ suspend fun sendCallStanza(node: WhatsAppProtocol.Node): Boolean+ /** Fan-out encrypt the padded call key to every peer + own device. */+ suspend fun encryptCallKey(toJid: String, paddedCallKey: ByteArray): List<WhatsAppProtocol.ParticipantEnc>+ /** Decrypt an inbound call-key `<enc>`; returns the still-padded plaintext or null. */+ suspend fun decryptCallKey(senderJid: String, encType: String, ciphertext: ByteArray): ByteArray?+ fun emit(event: com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent)+ fun resolveName(jid: String): String?+ }++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val _state = MutableStateFlow(WhatsAppCallState())+ val state: StateFlow<WhatsAppCallState> = _state.asStateFlow()++ private var appContext: Context? = null+ private var bridge: Bridge? = null++ private var session: WhatsAppCallSession? = null+ private var callKey: ByteArray? = null+ private var pendingRemoteSdp: String? = null+ private var callStartMs: Long = 0L++ fun init(context: Context, bridge: Bridge) {+ if (appContext == null) appContext = context.applicationContext+ this.bridge = bridge+ }++ // ------------------------------------------------------------------ outbound++ fun placeCall(jid: String, video: Boolean = false) {+ val ctx = appContext ?: return+ val b = bridge ?: return+ val callId = b.newId()+ _state.value = WhatsAppCallState(+ phase = WhatsAppCallPhase.Outgoing, callId = callId, peerJid = jid,+ peerName = b.resolveName(jid).orEmpty(), isVideo = video,+ )+ scope.launch {+ runCatching {+ val key = WhatsAppCallCrypto.generateCallKey()+ callKey = key+ val s = newSession(ctx, video).also { it.initialize() }+ session = s+ val sdp = s.createOffer()+ val encs = b.encryptCallKey(jid, WhatsAppProtocol.padMessage(key))+ if (encs.isEmpty()) { fail(callId, "no_devices"); return@launch }+ val node = WhatsAppCallSignaling.buildOffer(+ to = jid, callId = callId, callCreator = b.ownJid, video = video,+ encs = encs, stanzaId = b.newId(), sdp = sdp,+ )+ b.sendCallStanza(node)+ emitPhase(callId, WhatsAppCallPhase.Outgoing, video)+ }.onFailure { fail(callId, it.message ?: "place_failed") }+ }+ }++ fun hangup(reason: String = "hangup") {+ val b = bridge ?: return+ val st = _state.value+ if (st.callId.isEmpty()) { endCall(st.callId, reason); return }+ scope.launch {+ runCatching {+ b.sendCallStanza(+ WhatsAppCallSignaling.buildTerminate(st.peerJid, st.callId, b.ownJid, reason, b.newId()),+ )+ }+ endCall(st.callId, reason)+ }+ }++ fun reject() {+ val b = bridge ?: return+ val st = _state.value+ scope.launch {+ runCatching {+ b.sendCallStanza(WhatsAppCallSignaling.buildReject(st.peerJid, st.callId, st.peerJid, b.newId()))+ }+ endCall(st.callId, "rejected")+ }+ }++ fun answer() {+ val ctx = appContext ?: return+ val b = bridge ?: return+ val st = _state.value+ val remoteSdp = pendingRemoteSdp ?: run { fail(st.callId, "no_offer_sdp"); return }+ scope.launch {+ runCatching {+ val s = session ?: newSession(ctx, st.isVideo).also { it.initialize(); session = it }+ val answerSdp = s.createAnswer(remoteSdp)+ b.sendCallStanza(+ WhatsAppCallSignaling.buildAccept(+ to = st.peerJid, callId = st.callId, callCreator = st.peerJid,+ stanzaId = b.newId(), video = st.isVideo, sdp = answerSdp,+ ),+ )+ setActive(st.callId, st.isVideo)+ }.onFailure { fail(st.callId, it.message ?: "answer_failed") }+ }+ }++ fun setMuted(muted: Boolean) {+ session?.setMuted(muted)+ _state.value = _state.value.copy(muted = muted)+ }++ fun setSpeaker(on: Boolean) {+ session?.setSpeaker(on)+ _state.value = _state.value.copy(speaker = on)+ }++ /** Flip the camera (video calls only). */+ fun switchCamera() {+ (session as? WhatsAppVideoCallSession)?.switchCamera()+ }++ /** Enable/disable the local camera track (video calls only). */+ fun setVideoEnabled(enabled: Boolean) {+ (session as? WhatsAppVideoCallSession)?.setVideoEnabled(enabled)+ }++ /** Attach UI renderers for a video call (no-op for audio). */+ fun attachVideoRenderers(local: org.webrtc.SurfaceViewRenderer?, remote: org.webrtc.SurfaceViewRenderer?) {+ (session as? WhatsAppVideoCallSession)?.attachRenderers(local, remote)+ }++ // ------------------------------------------------------------------ inbound++ /** Route a parsed inbound `<call>` from the client's message loop. */+ fun onInbound(inbound: WhatsAppCallSignaling.InboundCall) {+ val b = bridge ?: return+ when (inbound.kind) {+ WhatsAppCallSignaling.InboundCall.Kind.OFFER -> onOffer(inbound)+ WhatsAppCallSignaling.InboundCall.Kind.ACCEPT -> onAccept(inbound)+ WhatsAppCallSignaling.InboundCall.Kind.PREACCEPT -> {+ inbound.sdp?.let { sdp -> scope.launch { runCatching { session?.setRemoteAnswer(sdp) } } }+ }+ WhatsAppCallSignaling.InboundCall.Kind.RELAY -> {+ inbound.candidates.forEach { session?.addRemoteCandidate(it) }+ }+ WhatsAppCallSignaling.InboundCall.Kind.REJECT,+ WhatsAppCallSignaling.InboundCall.Kind.TERMINATE -> endCall(inbound.callId, "peer_ended")+ WhatsAppCallSignaling.InboundCall.Kind.UNKNOWN -> {}+ }+ }++ private fun onOffer(inbound: WhatsAppCallSignaling.InboundCall) {+ val b = bridge ?: return+ if (_state.value.phase != WhatsAppCallPhase.Idle && _state.value.phase != WhatsAppCallPhase.Ended) {+ // Busy — auto-reject a second call.+ scope.launch {+ runCatching {+ b.sendCallStanza(WhatsAppCallSignaling.buildReject(inbound.from, inbound.callId, inbound.creator, b.newId()))+ }+ }+ return+ }+ scope.launch {+ runCatching {+ val enc = inbound.enc+ if (enc != null) {+ val padded = b.decryptCallKey(inbound.creator.ifEmpty { inbound.from }, enc.type, enc.ciphertext)+ callKey = padded?.let { WhatsAppProtocol.unpadMessage(it) }+ }+ pendingRemoteSdp = inbound.sdp+ _state.value = WhatsAppCallState(+ phase = WhatsAppCallPhase.Incoming, callId = inbound.callId, peerJid = inbound.from,+ peerName = b.resolveName(inbound.from).orEmpty(), isVideo = inbound.isVideo,+ )+ b.emit(+ com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent.CallOffer(+ callId = inbound.callId, from = inbound.from, callCreator = inbound.creator,+ isVideo = inbound.isVideo, peerName = b.resolveName(inbound.from),+ ),+ )+ }.onFailure { fail(inbound.callId, it.message ?: "offer_failed") }+ }+ }++ private fun onAccept(inbound: WhatsAppCallSignaling.InboundCall) {+ val sdp = inbound.sdp ?: return+ scope.launch {+ runCatching {+ session?.setRemoteAnswer(sdp)+ setActive(inbound.callId, inbound.isVideo)+ }.onFailure { fail(inbound.callId, it.message ?: "accept_failed") }+ }+ }++ // ------------------------------------------------------------------ helpers++ /** Overridable session factory (Phase E swaps in a video session). */+ private fun newSession(ctx: Context, video: Boolean): WhatsAppCallSession =+ if (video) WhatsAppVideoCallSession(ctx) else WhatsAppCallSession(ctx)++ private fun setActive(callId: String, video: Boolean) {+ callStartMs = System.currentTimeMillis()+ _state.value = _state.value.copy(phase = WhatsAppCallPhase.Active, callId = callId, isVideo = video)+ emitPhase(callId, WhatsAppCallPhase.Active, video)+ }++ private fun emitPhase(callId: String, phase: WhatsAppCallPhase, video: Boolean) {+ bridge?.emit(+ com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent.CallStateChanged(+ callId = callId, phase = phase.name, isVideo = video,+ ),+ )+ }++ private fun endCall(callId: String, reason: String) {+ val duration = if (callStartMs > 0) (System.currentTimeMillis() - callStartMs) / 1000 else 0L+ cleanup()+ _state.value = WhatsAppCallState(phase = WhatsAppCallPhase.Ended, callId = callId)+ bridge?.emit(+ com.vayunmathur.communicate.data.whatsapp.WhatsAppEvent.CallEnded(+ callId = callId, reason = reason, durationSeconds = duration,+ ),+ )+ }++ private fun fail(callId: String, reason: String) {+ Log.e(TAG, "call $callId failed: $reason")+ endCall(callId, reason)+ }++ private fun cleanup() {+ runCatching { session?.close() }+ session = null+ callKey = null+ pendingRemoteSdp = null+ callStartMs = 0L+ }++ /** Reset to Idle once the UI consumed the terminal state. */+ fun clearEnded() {+ if (_state.value.phase == WhatsAppCallPhase.Ended) _state.value = WhatsAppCallState()+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSession.ktnew file mode 100644index 0000000000..7681c3714a--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSession.kt@@ -0,0 +1,212 @@+package com.vayunmathur.communicate.data.whatsapp.call++import android.content.Context+import android.media.AudioManager+import org.webrtc.AudioSource+import org.webrtc.AudioTrack+import org.webrtc.DefaultVideoDecoderFactory+import org.webrtc.DefaultVideoEncoderFactory+import org.webrtc.EglBase+import org.webrtc.IceCandidate+import org.webrtc.MediaConstraints+import org.webrtc.MediaStream+import org.webrtc.PeerConnection+import org.webrtc.PeerConnectionFactory+import org.webrtc.RtpReceiver+import org.webrtc.RtpSender+import org.webrtc.SdpObserver+import org.webrtc.SessionDescription+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithException+import kotlin.coroutines.suspendCoroutine+import kotlinx.coroutines.CompletableDeferred++/**+ * WebRTC media leg of a WhatsApp call (Phase D 3d — audio; extended for video in Phase E).+ *+ * Forked from `data/googlevoice/call/WebRtcAudioSession`. Carries one Opus audio m-line over a+ * single [PeerConnection]; SDP is exchanged (via the [WhatsAppCallSignaling] `<webrtc>` extension)+ * with ICE gathered once so the SDP is self-contained for the `<call>` stanza. Exposes mute ++ * speaker routing. Uses the maintained `io.getstream:stream-webrtc-android` prebuilt (`org.webrtc.*`).+ *+ * The 32-byte WhatsApp call key ([WhatsAppCallCrypto]) is exchanged/verified over signaling; the+ * actual client-to-client media confidentiality here is WebRTC's own DTLS-SRTP (WhatsApp's native+ * SRTP schedule can't interop from Java — documented limitation).+ */+open class WhatsAppCallSession(protected val appContext: Context) {++ protected val eglBase: EglBase = EglBase.create()+ protected var factory: PeerConnectionFactory? = null+ protected var peerConnection: PeerConnection? = null+ private var audioSource: AudioSource? = null+ private var localAudioTrack: AudioTrack? = null+ private var audioSender: RtpSender? = null++ protected val iceComplete = CompletableDeferred<Unit>()++ open fun initialize() {+ PeerConnectionFactory.initialize(+ PeerConnectionFactory.InitializationOptions.builder(appContext)+ .setEnableInternalTracer(false)+ .createInitializationOptions(),+ )+ val encoder = DefaultVideoEncoderFactory(eglBase.eglBaseContext, true, true)+ val decoder = DefaultVideoDecoderFactory(eglBase.eglBaseContext)+ factory = PeerConnectionFactory.builder()+ .setVideoEncoderFactory(encoder)+ .setVideoDecoderFactory(decoder)+ .createPeerConnectionFactory()+ }++ protected open fun ensurePeerConnection() {+ if (peerConnection != null) return+ val f = factory ?: error("initialize() not called")+ val iceServers = listOf(+ PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer(),+ )+ val config = PeerConnection.RTCConfiguration(iceServers).apply {+ sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN+ bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE+ rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE+ continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_ONCE+ }+ peerConnection = f.createPeerConnection(config, object : PeerConnection.Observer {+ override fun onIceCandidate(candidate: IceCandidate?) {}+ override fun onIceGatheringChange(state: PeerConnection.IceGatheringState?) {+ if (state == PeerConnection.IceGatheringState.COMPLETE && !iceComplete.isCompleted) {+ iceComplete.complete(Unit)+ }+ }+ override fun onSignalingChange(p0: PeerConnection.SignalingState?) {}+ override fun onIceConnectionChange(p0: PeerConnection.IceConnectionState?) {}+ override fun onIceConnectionReceivingChange(p0: Boolean) {}+ override fun onIceCandidatesRemoved(p0: Array<out IceCandidate>?) {}+ override fun onAddStream(p0: MediaStream?) {}+ override fun onRemoveStream(p0: MediaStream?) {}+ override fun onDataChannel(p0: org.webrtc.DataChannel?) {}+ override fun onRenegotiationNeeded() {}+ override fun onAddTrack(p0: RtpReceiver?, p1: Array<out MediaStream>?) {}+ })+ addLocalAudio(f)+ onPeerConnectionCreated(f)+ }++ /** Hook for subclasses (video) to add extra local tracks after the audio track. */+ protected open fun onPeerConnectionCreated(f: PeerConnectionFactory) {}++ private fun addLocalAudio(f: PeerConnectionFactory) {+ val constraints = MediaConstraints().apply {+ mandatory.add(MediaConstraints.KeyValuePair("googEchoCancellation", "true"))+ mandatory.add(MediaConstraints.KeyValuePair("googAutoGainControl", "true"))+ mandatory.add(MediaConstraints.KeyValuePair("googNoiseSuppression", "true"))+ }+ val source = f.createAudioSource(constraints)+ val track = f.createAudioTrack("wa_audio", source)+ audioSource = source+ localAudioTrack = track+ audioSender = peerConnection?.addTrack(track, listOf("wa_stream"))+ }++ protected open fun offerConstraints(): MediaConstraints = MediaConstraints().apply {+ mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))+ mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"))+ }++ /** Create an SDP offer, set it locally, wait for ICE, and return the final SDP. */+ suspend fun createOffer(): String {+ ensurePeerConnection()+ val pc = peerConnection ?: error("no peer connection")+ val offer = pc.createOfferSuspend(offerConstraints())+ pc.setLocalDescriptionSuspend(offer)+ iceComplete.await()+ return pc.localDescription?.description ?: offer.description+ }++ /** Apply the remote answer SDP received in the peer's `<accept>`. */+ suspend fun setRemoteAnswer(sdp: String) {+ val pc = peerConnection ?: error("no peer connection")+ pc.setRemoteDescriptionSuspend(SessionDescription(SessionDescription.Type.ANSWER, sdp))+ }++ /** For an inbound call: apply the remote offer, create + set an answer, return answer SDP. */+ suspend fun createAnswer(remoteOfferSdp: String): String {+ ensurePeerConnection()+ val pc = peerConnection ?: error("no peer connection")+ pc.setRemoteDescriptionSuspend(SessionDescription(SessionDescription.Type.OFFER, remoteOfferSdp))+ val answer = pc.createAnswerSuspend(offerConstraints())+ pc.setLocalDescriptionSuspend(answer)+ iceComplete.await()+ return pc.localDescription?.description ?: answer.description+ }++ /** Add a remote ICE candidate (candidate line "candidate:..."). sdpMid/index default to audio m0. */+ fun addRemoteCandidate(candidate: String, sdpMid: String = "0", sdpMLineIndex: Int = 0) {+ runCatching { peerConnection?.addIceCandidate(IceCandidate(sdpMid, sdpMLineIndex, candidate)) }+ }++ fun setMuted(muted: Boolean) {+ localAudioTrack?.setEnabled(!muted)+ }++ fun setSpeaker(on: Boolean) {+ val am = appContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager+ @Suppress("DEPRECATION")+ am.isSpeakerphoneOn = on+ }++ open fun close() {+ runCatching { peerConnection?.dispose() }+ runCatching { audioSource?.dispose() }+ runCatching { factory?.dispose() }+ runCatching { eglBase.release() }+ peerConnection = null+ audioSource = null+ localAudioTrack = null+ audioSender = null+ }++ // ---- SdpObserver → coroutine adapters ----++ private suspend fun PeerConnection.createOfferSuspend(c: MediaConstraints): SessionDescription =+ suspendCoroutine { cont ->+ createOffer(object : SimpleSdpObserver() {+ override fun onCreateSuccess(desc: SessionDescription) = cont.resume(desc)+ override fun onCreateFailure(error: String?) =+ cont.resumeWithException(IllegalStateException("createOffer: $error"))+ }, c)+ }++ private suspend fun PeerConnection.createAnswerSuspend(c: MediaConstraints): SessionDescription =+ suspendCoroutine { cont ->+ createAnswer(object : SimpleSdpObserver() {+ override fun onCreateSuccess(desc: SessionDescription) = cont.resume(desc)+ override fun onCreateFailure(error: String?) =+ cont.resumeWithException(IllegalStateException("createAnswer: $error"))+ }, c)+ }++ private suspend fun PeerConnection.setLocalDescriptionSuspend(desc: SessionDescription) =+ suspendCoroutine<Unit> { cont ->+ setLocalDescription(object : SimpleSdpObserver() {+ override fun onSetSuccess() = cont.resume(Unit)+ override fun onSetFailure(error: String?) =+ cont.resumeWithException(IllegalStateException("setLocal: $error"))+ }, desc)+ }++ private suspend fun PeerConnection.setRemoteDescriptionSuspend(desc: SessionDescription) =+ suspendCoroutine<Unit> { cont ->+ setRemoteDescription(object : SimpleSdpObserver() {+ override fun onSetSuccess() = cont.resume(Unit)+ override fun onSetFailure(error: String?) =+ cont.resumeWithException(IllegalStateException("setRemote: $error"))+ }, desc)+ }+}++private open class SimpleSdpObserver : SdpObserver {+ override fun onCreateSuccess(desc: SessionDescription) {}+ override fun onSetSuccess() {}+ override fun onCreateFailure(error: String?) {}+ override fun onSetFailure(error: String?) {}+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.ktindex 0bf6d1758d..476650ba7d 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppCallSignaling.kt@@ -1,23 +1,27 @@ package com.vayunmathur.communicate.data.whatsapp.call +import android.util.Base64 import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol.Node /**- * Phase 10a — WhatsApp call **signaling** (spike). Builds/parses the `<call>` XMPP stanzas that ride- * the same Noise socket as messaging (offer/accept/reject/terminate), with per-device E2E `<enc>`- * children carrying the call key. The media/VoIP engine itself is native-only and out of scope for- * this pass (see plan Phase 10b / Option C).+ * WhatsApp call **signaling** (Phase D 3a). Builds/parses the `<call>` XMPP stanzas that ride the+ * same Noise socket as messaging (offer / preaccept / accept / reject / terminate), with per-device+ * E2E `<enc>` children carrying the 32-byte call key (see [WhatsAppCallCrypto]). *- * ⚠️ The exact child layout (`audio`/`net`/`capability`/`encopt` markers, attribute names) is- * reconstructed from the reverse-engineering notes and `whatsmeow`; it MUST be validated live — the- * go/no-go is whether the server accepts the offer and the target rings.+ * Because WhatsApp's wire carries **no SDP** (its media is a proprietary native RTP engine), we+ * transport standards-based WebRTC SDP + ICE candidates inside our **own** `<webrtc>` child of the+ * `<call>` action. This makes calling interoperate **client-to-client (our app ↔ our app)** but NOT+ * with official WhatsApp calling servers — an accepted, documented limitation of the dev scaffolding. * * Reference: whatsapp-documentation.md "Voice Calls And Video Calls" (SignalingXmppCallback- * `sendCallStanza`, OutgoingSignalingHandler per-destination `enc` children).+ * `sendCallStanza`, OutgoingSignalingHandler per-destination `enc` children) + signaling.md. */ object WhatsAppCallSignaling { + /** Our WebRTC transport extension tag (not part of the official WA wire). */+ private const val WEBRTC_TAG = "webrtc"+ /** A parsed inbound call stanza. */ data class InboundCall( val callId: String,@@ -25,13 +29,26 @@ object WhatsAppCallSignaling { val creator: String, val isVideo: Boolean, val kind: Kind,+ /** The `<enc>` carrying the call key, targeted to our device (null on accept/reject/etc.). */+ val enc: Enc? = null,+ /** WebRTC offer/answer SDP carried in our `<webrtc>` extension, if present. */+ val sdp: String? = null,+ /** Trickle/gathered ICE candidate lines from our `<webrtc>` extension. */+ val candidates: List<String> = emptyList(),+ val stanzaId: String = "", ) {- enum class Kind { OFFER, ACCEPT, REJECT, TERMINATE, UNKNOWN }+ enum class Kind { OFFER, PREACCEPT, ACCEPT, REJECT, TERMINATE, RELAY, UNKNOWN } } + /** A single Signal `<enc>` (type = pkmsg|msg, ciphertext). */+ data class Enc(val type: String, val ciphertext: ByteArray)++ // ------------------------------------------------------------------ builders+ /** * Build an outbound call offer. * @param encs per-device encrypted call-key children (dev jid, enc type, ciphertext).+ * @param sdp / [candidates] our WebRTC offer carried in the `<webrtc>` extension. */ fun buildOffer( to: String,@@ -40,8 +57,9 @@ object WhatsAppCallSignaling { video: Boolean, encs: List<WhatsAppProtocol.ParticipantEnc>, stanzaId: String,+ sdp: String? = null,+ candidates: List<String> = emptyList(), ): Node {- val mediaMarker = if (video) Node(tag = "video") else Node(tag = "audio", attrs = mapOf("enc" to "opus", "rate" to "16000")) val destinations = encs.map { enc -> Node( tag = "to",@@ -55,50 +73,80 @@ object WhatsAppCallSignaling { tag = "offer", attrs = mapOf("call-id" to callId, "call-creator" to callCreator), content = buildList {- add(mediaMarker)+ add(mediaMarker(video)) add(Node(tag = "net", attrs = mapOf("medium" to "3"))) add(Node(tag = "encopt", attrs = mapOf("keygen" to "2")))+ webrtcChild(sdp, candidates)?.let { add(it) } addAll(destinations) }, )- return Node(- tag = "call",- attrs = mapOf("to" to to, "id" to stanzaId),- content = listOf(offer),+ return call(to, stanzaId, offer)+ }++ /** Pre-accept (early, before the user picks up) — lets media/ICE start during ringing. */+ fun buildPreAccept(+ to: String,+ callId: String,+ callCreator: String,+ video: Boolean,+ stanzaId: String,+ sdp: String? = null,+ candidates: List<String> = emptyList(),+ ): Node {+ val preaccept = Node(+ tag = "preaccept",+ attrs = mapOf("call-id" to callId, "call-creator" to callCreator),+ content = buildList {+ add(mediaMarker(video))+ webrtcChild(sdp, candidates)?.let { add(it) }+ }, )+ return call(to, stanzaId, preaccept) } - /** Ack/accept an inbound call. */- fun buildAccept(to: String, callId: String, callCreator: String, stanzaId: String): Node =- Node(- tag = "call",- attrs = mapOf("to" to to, "id" to stanzaId),- content = listOf(- Node(tag = "accept", attrs = mapOf("call-id" to callId, "call-creator" to callCreator)),- ),+ /** Accept an inbound call, carrying our WebRTC answer. */+ fun buildAccept(+ to: String,+ callId: String,+ callCreator: String,+ stanzaId: String,+ video: Boolean = false,+ sdp: String? = null,+ candidates: List<String> = emptyList(),+ ): Node {+ val accept = Node(+ tag = "accept",+ attrs = mapOf("call-id" to callId, "call-creator" to callCreator),+ content = buildList {+ add(mediaMarker(video))+ webrtcChild(sdp, candidates)?.let { add(it) }+ }, )+ return call(to, stanzaId, accept)+ } fun buildReject(to: String, callId: String, callCreator: String, stanzaId: String): Node =- Node(- tag = "call",- attrs = mapOf("to" to to, "id" to stanzaId),- content = listOf(- Node(tag = "reject", attrs = mapOf("call-id" to callId, "call-creator" to callCreator)),- ),- )+ call(to, stanzaId, Node(tag = "reject", attrs = mapOf("call-id" to callId, "call-creator" to callCreator))) fun buildTerminate(to: String, callId: String, callCreator: String, reason: String, stanzaId: String): Node =- Node(- tag = "call",- attrs = mapOf("to" to to, "id" to stanzaId),- content = listOf(- Node(- tag = "terminate",- attrs = mapOf("call-id" to callId, "call-creator" to callCreator, "reason" to reason),- ),+ call(+ to, stanzaId,+ Node(tag = "terminate", attrs = mapOf("call-id" to callId, "call-creator" to callCreator, "reason" to reason)),+ )++ /** Trickle a batch of ICE candidates mid-call inside a `<transport>`-like `<webrtc>` node. */+ fun buildIceUpdate(to: String, callId: String, callCreator: String, stanzaId: String, candidates: List<String>): Node =+ call(+ to, stanzaId,+ Node(+ tag = "relay",+ attrs = mapOf("call-id" to callId, "call-creator" to callCreator),+ content = listOfNotNull(webrtcChild(null, candidates)), ), ) + // ------------------------------------------------------------------ parse+ /** Parse an inbound `<call>` stanza into a typed [InboundCall]. */ fun parse(node: Node): InboundCall? { if (node.tag != "call") return null@@ -106,14 +154,64 @@ object WhatsAppCallSignaling { val child = node.getChildren().firstOrNull() ?: return null val kind = when (child.tag) { "offer" -> InboundCall.Kind.OFFER+ "preaccept" -> InboundCall.Kind.PREACCEPT "accept" -> InboundCall.Kind.ACCEPT "reject" -> InboundCall.Kind.REJECT "terminate" -> InboundCall.Kind.TERMINATE+ "relay" -> InboundCall.Kind.RELAY else -> InboundCall.Kind.UNKNOWN } val callId = child.attrs["call-id"] ?: node.attrs["id"] ?: "" val creator = child.attrs["call-creator"] ?: from val isVideo = child.getChildren().any { it.tag == "video" }- return InboundCall(callId, from, creator, isVideo, kind)+ val encNode = child.getChildByTag("enc")+ val enc = encNode?.data?.let { Enc(encNode.attrs["type"] ?: "msg", it) }+ val webrtc = child.getChildByTag(WEBRTC_TAG)+ return InboundCall(+ callId = callId,+ from = from,+ creator = creator,+ isVideo = isVideo,+ kind = kind,+ enc = enc,+ sdp = webrtc?.let { extractSdp(it) },+ candidates = webrtc?.let { extractCandidates(it) } ?: emptyList(),+ stanzaId = node.attrs["id"] ?: "",+ )+ }++ // ------------------------------------------------------------------ webrtc extension helpers++ /**+ * Build our `<webrtc>` transport extension: base64 SDP as the `<sdp>` node data plus one+ * `<ice>` node per candidate. Returns null when there's nothing to carry.+ */+ fun webrtcChild(sdp: String?, candidates: List<String>): Node? {+ if (sdp == null && candidates.isEmpty()) return null+ val children = buildList {+ if (sdp != null) {+ add(Node(tag = "sdp", data = Base64.encode(sdp.toByteArray(Charsets.UTF_8), Base64.NO_WRAP)))+ }+ candidates.forEach { c ->+ add(Node(tag = "ice", data = Base64.encode(c.toByteArray(Charsets.UTF_8), Base64.NO_WRAP)))+ }+ }+ return Node(tag = WEBRTC_TAG, content = children) }++ fun extractSdp(webrtc: Node): String? =+ webrtc.getChildByTag("sdp")?.data?.let { String(Base64.decode(it, Base64.NO_WRAP), Charsets.UTF_8) }++ fun extractCandidates(webrtc: Node): List<String> =+ webrtc.getChildren().filter { it.tag == "ice" }.mapNotNull { ice ->+ ice.data?.let { String(Base64.decode(it, Base64.NO_WRAP), Charsets.UTF_8) }+ }++ // ------------------------------------------------------------------ small builders++ private fun mediaMarker(video: Boolean): Node =+ if (video) Node(tag = "video") else Node(tag = "audio", attrs = mapOf("enc" to "opus", "rate" to "16000"))++ private fun call(to: String, stanzaId: String, action: Node): Node =+ Node(tag = "call", attrs = mapOf("to" to to, "id" to stanzaId), content = listOf(action)) }
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppVideoCallSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppVideoCallSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppVideoCallSession.ktnew file mode 100644index 0000000000..340f8c3824--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/call/WhatsAppVideoCallSession.kt@@ -0,0 +1,95 @@+package com.vayunmathur.communicate.data.whatsapp.call++import android.content.Context+import org.webrtc.Camera2Enumerator+import org.webrtc.CameraVideoCapturer+import org.webrtc.MediaConstraints+import org.webrtc.PeerConnectionFactory+import org.webrtc.SurfaceTextureHelper+import org.webrtc.SurfaceViewRenderer+import org.webrtc.VideoSource+import org.webrtc.VideoTrack++/**+ * Video extension of [WhatsAppCallSession] (Phase E / Feature 4). Adds a camera+ * `VideoSource`/`VideoTrack` (WebRTC `Camera2Enumerator`), local/remote `SurfaceViewRenderer`+ * rendering off the shared `EglBase`, camera switch, and `OfferToReceiveVideo=true`.+ *+ * Renderers are owned by the UI ([WhatsAppCallScreen]); it calls [attachRenderers] once the+ * surfaces are laid out. Everything else (SDP/ICE, mute, speaker) is inherited from the base.+ */+class WhatsAppVideoCallSession(context: Context) : WhatsAppCallSession(context) {++ private var videoCapturer: CameraVideoCapturer? = null+ private var videoSource: VideoSource? = null+ private var localVideoTrack: VideoTrack? = null+ private var surfaceHelper: SurfaceTextureHelper? = null+ private var localRenderer: SurfaceViewRenderer? = null+ private var remoteRenderer: SurfaceViewRenderer? = null+ private var remoteVideoTrack: VideoTrack? = null++ override fun offerConstraints(): MediaConstraints = MediaConstraints().apply {+ mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))+ mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"))+ }++ override fun onPeerConnectionCreated(f: PeerConnectionFactory) {+ val capturer = createCameraCapturer() ?: return+ videoCapturer = capturer+ val helper = SurfaceTextureHelper.create("wa_capture", eglBase.eglBaseContext)+ surfaceHelper = helper+ val source = f.createVideoSource(false)+ videoSource = source+ capturer.initialize(helper, appContext, source.capturerObserver)+ runCatching { capturer.startCapture(1280, 720, 30) }+ val track = f.createVideoTrack("wa_video", source)+ localVideoTrack = track+ peerConnection?.addTrack(track, listOf("wa_stream"))+ }++ /** Attach the UI renderers; also renders the local track immediately. */+ fun attachRenderers(local: SurfaceViewRenderer?, remote: SurfaceViewRenderer?) {+ localRenderer = local+ remoteRenderer = remote+ runCatching {+ local?.init(eglBase.eglBaseContext, null)+ remote?.init(eglBase.eglBaseContext, null)+ }+ local?.let { localVideoTrack?.addSink(it) }+ remoteVideoTrack?.let { t -> remote?.let { t.addSink(it) } }+ }++ fun switchCamera() {+ runCatching { videoCapturer?.switchCamera(null) }+ }++ fun setVideoEnabled(enabled: Boolean) {+ localVideoTrack?.setEnabled(enabled)+ }++ private fun createCameraCapturer(): CameraVideoCapturer? {+ val enumerator = Camera2Enumerator(appContext)+ val names = enumerator.deviceNames+ // Prefer the front camera for calls.+ names.firstOrNull { enumerator.isFrontFacing(it) }?.let {+ return enumerator.createCapturer(it, null)+ }+ names.firstOrNull()?.let { return enumerator.createCapturer(it, null) }+ return null+ }++ override fun close() {+ runCatching { videoCapturer?.stopCapture() }+ runCatching { videoCapturer?.dispose() }+ runCatching { videoSource?.dispose() }+ runCatching { surfaceHelper?.dispose() }+ runCatching { localRenderer?.release() }+ runCatching { remoteRenderer?.release() }+ videoCapturer = null+ videoSource = null+ localVideoTrack = null+ remoteVideoTrack = null+ surfaceHelper = null+ super.close()+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationAttestation.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationAttestation.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationAttestation.ktindex b9b7c21f6e..2c0c37268d 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationAttestation.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationAttestation.kt@@ -143,11 +143,21 @@ object RegistrationAttestation { // --------------------------------------------------------------------------------------------- /**- * H = base64( HMAC-SHA256(key = locally-generated attestation key, msg = body) ).+ * H = base64( HMAC-SHA256(key = attestation key, msg = body) ). *- * The official client keys this from a device key persisted in `C1DB` (AndroidKeyStore-backed).- * The server treats it as best-effort (the client warns + continues when it is null), so we use- * a locally-generated persisted key ([WhatsAppDeviceFingerprint.attestationKey]).+ * Prefers the non-exportable AndroidKeyStore HMAC key+ * ([WhatsAppAttestationKeyStore]); falls back to the software [softwareKey]+ * ([WhatsAppDeviceFingerprint.attestationKey]) when the KeyStore is unavailable. The server+ * treats `H` as best-effort (the client warns + continues when it is null).+ */+ fun signWithAttestation(body: String, softwareKey: ByteArray): String {+ val mac = WhatsAppAttestationKeyStore.signWithFallback(body.toByteArray(Charsets.UTF_8), softwareKey)+ return Base64.encodeToString(mac, Base64.NO_WRAP)+ }++ /**+ * H over a raw software key only (no KeyStore). Retained for callers/tests that supply an+ * explicit key; prefer the [signWithAttestation]`(body, softwareKey)` overload in production. */ fun signWithAttestation(attestationKey: ByteArray, body: String): String { val mac = Mac.getInstance("HmacSHA256")
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.ktindex 8bed1f3f66..18c13c44a9 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationHttpClient.kt@@ -96,6 +96,7 @@ class RegistrationHttpClient( p.a00("clicked_education_link", false) p.a00("manage_call_permission", false) p.a00("call_log_permission", false)+ p.addIntegrity(EndpointKind.CODE) p.bundle(RegistrationKeys.bundleFields(keys.authScaffold)) val body = send("code", p)@@ -120,6 +121,7 @@ class RegistrationHttpClient( p.addCommon() p.addDevice() p.a01("code", code.filter { it.isDigit() })+ p.addIntegrity(EndpointKind.REGISTER) p.bundle(RegistrationKeys.bundleFields(auth)) val body = send("register", p)@@ -155,6 +157,9 @@ class RegistrationHttpClient( p.a01("in", number) p.addCommon() p.addDevice()+ // Bug fix (w2.md §3.1): /v2/exist REQUIRES `token`; it was previously omitted.+ p.a01("token", RegistrationAttestation.computeToken(context, number))+ p.addIntegrity(EndpointKind.EXIST) if (auth != null) p.bundle(RegistrationKeys.bundleFields(auth)) val body = send("exist", p) val j = parse(body)@@ -419,6 +424,41 @@ class RegistrationHttpClient( val encoded = if (k in raw) v else URLEncoder.encode(v, "UTF-8") "$k=$encoded" }++ /**+ * Add the per-endpoint device-integrity signals (w2.md §2.3/§3.1-3.3, Phase B 2e) from+ * [RegistrationIntegrity]. `gpia`/`_gg` (Play Integrity) and `recaptcha` are intentionally+ * NOT sent — they are bound to the official signed WhatsApp app identity and an unofficial+ * client cannot mint server-valid tokens (documented, not faked).+ *+ * Inclusion per endpoint:+ * - EXIST: aid,_gi,_gp,_ge,_ga,_gs,db (+profile_name; no t)+ * - CODE: aid,_gi,_gp,_ge,_ga,_gs,t,hasav+ * - REGISTER: aid,_gi,_gp,_ge,_ga,_gs,t+ */+ fun addIntegrity(kind: EndpointKind) {+ val s = runCatching { RegistrationIntegrity.collect(context) }.getOrNull() ?: return+ if (s.aid.isNotEmpty()) a01("aid", s.aid)+ a02("_gi", s.gi)+ a01("_gp", s.gp)+ a01("_ge", s.ge)+ a01("_ga", s.ga)+ a01("_gs", s.gs)+ when (kind) {+ EndpointKind.EXIST -> {+ a01("db", s.db)+ WhatsAppAuthData.load(context)?.profileName?.takeIf { it.isNotEmpty() }+ ?.let { a01("profile_name", it) }+ }+ EndpointKind.CODE -> {+ a01("t", RegistrationIntegrity.tField(s.tSeconds))+ a01("hasav", "0") // 0 = can't read SMS (we never read the user's SMS inbox)+ }+ EndpointKind.REGISTER -> {+ a01("t", RegistrationIntegrity.tField(s.tSeconds))+ }+ }+ } } private suspend fun send(path: String, params: RegParams): String {@@ -426,7 +466,7 @@ class RegistrationHttpClient( val body = if (useEncWrapper) { val encv = RegistrationAttestation.encryptQueryString(query) if (encv != null) {- val h = RegistrationAttestation.signWithAttestation(fingerprint.attestationKey, encv)+ val h = RegistrationAttestation.signWithAttestation(encv, fingerprint.attestationKey) "ENC=${URLEncoder.encode(encv, "UTF-8")}&H=${URLEncoder.encode(h, "UTF-8")}" } else { query@@ -474,6 +514,9 @@ class RegistrationHttpClient( companion object { private const val TAG = "WARegHttp" }++ /** WAMSYS endpoint kinds that carry per-endpoint integrity params (w2.md §3.1-3.3). */+ private enum class EndpointKind { EXIST, CODE, REGISTER } } // -- small JSONObject null-safe helpers --
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.ktnew file mode 100644index 0000000000..8549dae874--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationIntegrity.kt@@ -0,0 +1,160 @@+package com.vayunmathur.communicate.data.whatsapp.registration++import android.content.Context+import android.content.pm.PackageManager+import android.os.Build+import android.provider.Settings+import java.io.File+import java.nio.ByteBuffer+import java.security.MessageDigest+import java.util.Base64++/**+ * Device-integrity signal collector for the WAMSYS `/v2` endpoints (w2.md §2.3, Phase B 2a).+ *+ * Computes the honestly-available integrity signals:+ * - `aid` = base64(SHA-256(Android ID)) (44B)+ * - `_gi` = ENC(JSON{apk sha256, sourceDir, cert sha256, size, pkg}) (encrypted query string)+ * - `_gp` = base64(SHA-256(sorted manifest permissions)) (44B)+ * - `_ge` = {"sv":<virtio>,"sb":<vboxsf>} (emulation probe)+ * - `_ga` = {"mp","mu","ae","ap","ai"} (automation signals)+ * - `_gs` = {"em":"<base64>"} (native-obfuscation placeholder)+ * - `t` = base64(int64 BE attestation timestamp seconds) (8B)+ * - `db` = ADB-enabled flag (Settings.Global.ADB_ENABLED) (0|1)+ *+ * NOT computed (bound to the official signed WhatsApp app identity; no FOSS way to mint):+ * - `gpia` / `_gg` (Play Integrity JWT) and `recaptcha` (reCAPTCHA Enterprise). These are omitted+ * entirely — an unofficial client cannot produce server-valid tokens (documented, not faked).+ *+ * The pure encoders ([aidOf], [permissionsHashOf], [tField], [emulationJson], [automationJson],+ * [nativeSignalsJson]) use `java.util.Base64` (API 26+, minSdk 31) so they are JVM-unit-testable.+ */+object RegistrationIntegrity {++ private val b64 = Base64.getEncoder()++ // ---------------------------------------------------------------- pure encoders (JVM-testable)++ private fun sha256(bytes: ByteArray): ByteArray =+ MessageDigest.getInstance("SHA-256").digest(bytes)++ /** `aid` = base64(SHA-256(Android ID)). Standard base64 (44 chars for a 32-byte digest). */+ fun aidOf(androidId: String): String = b64.encodeToString(sha256(androidId.toByteArray(Charsets.UTF_8)))++ /** `_gp` = base64(SHA-256(newline-joined sorted permission names)). */+ fun permissionsHashOf(permissions: List<String>): String =+ b64.encodeToString(sha256(permissions.sorted().joinToString("\n").toByteArray(Charsets.UTF_8)))++ /** `t` = base64(8-byte big-endian int64 seconds). */+ fun tField(epochSeconds: Long): String =+ b64.encodeToString(ByteBuffer.allocate(8).putLong(epochSeconds).array())++ /** `_ge` emulation probe JSON `{"sv":<virtio>,"sb":<vboxsf>}` (stable key order). */+ fun emulationJson(virtio: Boolean, vboxsf: Boolean): String =+ """{"sv":$virtio,"sb":$vboxsf}"""++ /** `_ga` automation-signals JSON `{"mp","mu","ae","ap","ai"}` (stable key order). */+ fun automationJson(mockPackages: Boolean, multiUser: Boolean, ae: Long, ap: Long, ai: Long): String =+ """{"mp":$mockPackages,"mu":$multiUser,"ae":$ae,"ap":$ap,"ai":$ai}"""++ /**+ * `_gs` native-obfuscation placeholder JSON `{"em":"<base64>"}`. The real `_gs` is produced by a+ * native RFC we cannot reproduce; we ship the exact wire shape filled with an available signal+ * (or empty). Ref w2.md §2.3 `wa-android-native-obfuscation-rfc`.+ */+ fun nativeSignalsJson(emBase64: String): String = """{"em":"$emBase64"}"""++ // ---------------------------------------------------------------- Android collection++ /** The set of collected integrity signals (empty strings mean "not available / not sent"). */+ data class Signals(+ val aid: String,+ val gp: String,+ val ge: String,+ val ga: String,+ val gs: String,+ val gi: String?,+ val db: String,+ val tSeconds: Long,+ )++ /**+ * Collect all honestly-available integrity signals from [context].+ * @param encryptQueryString the ENC wrapper used for `_gi` (defaults to+ * [RegistrationAttestation.encryptQueryString]); may return null on failure.+ */+ fun collect(+ context: Context,+ nowSeconds: Long = System.currentTimeMillis() / 1000,+ encryptQueryString: (String) -> String? = RegistrationAttestation::encryptQueryString,+ ): Signals {+ val androidId = runCatching {+ Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID).orEmpty()+ }.getOrDefault("")++ val aid = if (androidId.isNotEmpty()) aidOf(androidId) else ""+ val gp = permissionsHashOf(manifestPermissions(context))+ val ge = emulationJson(virtio = probeVirtio(), vboxsf = probeVboxsf())+ val ga = automationJson(+ mockPackages = false,+ multiUser = false,+ ae = firstInstallTime(context),+ ap = lastUpdateTime(context),+ ai = 0L,+ )+ val gs = nativeSignalsJson("")+ val gi = buildGi(context, encryptQueryString)+ val db = runCatching {+ if (Settings.Global.getInt(context.contentResolver, Settings.Global.ADB_ENABLED, 0) != 0) "1" else "0"+ }.getOrDefault("0")++ return Signals(aid = aid, gp = gp, ge = ge, ga = ga, gs = gs, gi = gi, db = db, tSeconds = nowSeconds)+ }++ private fun manifestPermissions(context: Context): List<String> = runCatching {+ val pkg = context.packageManager.getPackageInfo(+ context.packageName, PackageManager.GET_PERMISSIONS,+ )+ pkg.requestedPermissions?.toList().orEmpty()+ }.getOrDefault(emptyList())++ @Suppress("DEPRECATION")+ private fun firstInstallTime(context: Context): Long = runCatching {+ context.packageManager.getPackageInfo(context.packageName, 0).firstInstallTime / 1000+ }.getOrDefault(0L)++ @Suppress("DEPRECATION")+ private fun lastUpdateTime(context: Context): Long = runCatching {+ context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime / 1000+ }.getOrDefault(0L)++ /** `_gi` = ENC(JSON{apk sha256, sourceDir, cert sha256, size, package}). Best-effort. */+ private fun buildGi(context: Context, encrypt: (String) -> String?): String? = runCatching {+ val pm = context.packageManager+ @Suppress("DEPRECATION")+ val info = pm.getPackageInfo(context.packageName, 0)+ val sourceDir = context.applicationInfo.sourceDir+ val apkFile = File(sourceDir)+ val apkBytes = apkFile.takeIf { it.exists() }?.readBytes()+ val apkSha = apkBytes?.let { b64.encodeToString(sha256(it)) } ?: ""+ val size = apkBytes?.size ?: 0+ val json = buildString {+ append('{')+ append("\"apk_sha256\":\"").append(apkSha).append("\",")+ append("\"source_dir\":\"").append(sourceDir).append("\",")+ append("\"size\":").append(size).append(',')+ append("\"package\":\"").append(context.packageName).append("\"")+ append('}')+ }+ encrypt(json)+ }.getOrNull()++ private fun probeVirtio(): Boolean = runCatching {+ Build.HARDWARE.contains("virtio", ignoreCase = true) ||+ File("/proc/mounts").takeIf { it.exists() }?.readText()?.contains("virtio") == true+ }.getOrDefault(false)++ private fun probeVboxsf(): Boolean = runCatching {+ File("/proc/mounts").takeIf { it.exists() }?.readText()?.contains("vboxsf") == true+ }.getOrDefault(false)+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationKeys.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationKeys.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationKeys.ktindex b89f50d636..6c58f01ce7 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationKeys.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/RegistrationKeys.kt@@ -35,6 +35,15 @@ class RegistrationKeys private constructor( val signature = WhatsAppE2E.signSignedPreKey(identity.privateKey, signedPreKey.publicKey) + // Post-quantum last-resort prekey (Phase B 2d). Best-effort: if the KEM API/native+ // signer is unavailable the PQ fields stay empty and bundleFields omits e_pq_* entirely+ // (all-or-none), so classic registration still works.+ val pq = try {+ WhatsAppPqPreKey.generate(identity.privateKey, WhatsAppRegistrationConstants.PQ_LAST_RESORT_KEY_ID)+ } catch (t: Throwable) {+ null+ }+ val scaffold = WhatsAppAuthData( phoneNumber = phoneNumber, pushName = "",@@ -49,6 +58,10 @@ class RegistrationKeys private constructor( signedPreKeyPrivate = b64(signedPreKey.privateKey), signedPreKeySignature = b64(signature), deviceId = 0,+ pqLastResortKeyId = pq?.keyId ?: 0,+ pqLastResortPublic = pq?.let { b64(it.publicKey) } ?: "",+ pqLastResortSecret = pq?.let { b64(it.secretKey) } ?: "",+ pqLastResortSignature = pq?.let { b64(it.signature) } ?: "", ) return RegistrationKeys(scaffold) }@@ -60,15 +73,28 @@ class RegistrationKeys private constructor( * The `/v2/ endpoints` E2E key bundle, URL-safe-base64 (A04), rebuilt from persisted [WhatsAppAuthData] * so the same values are reused across the code→register calls. */- fun bundleFields(auth: WhatsAppAuthData): Map<String, String> = mapOf(- "e_regid" to RegEncoding.b64Url(intBe(auth.registrationId, 4)),- "e_keytype" to RegEncoding.b64Url(byteArrayOf(WhatsAppRegistrationConstants.KEY_TYPE_CURVE25519)),- "e_ident" to RegEncoding.b64Url(dec(auth.identityPublicKey)),- "e_skey_id" to RegEncoding.b64Url(intBe(auth.signedPreKeyId, 3)),- "e_skey_val" to RegEncoding.b64Url(dec(auth.signedPreKeyPublic)),- "e_skey_sig" to RegEncoding.b64Url(dec(auth.signedPreKeySignature)),- "authkey" to RegEncoding.b64Url(dec(auth.noisePublicKey)),- )+ fun bundleFields(auth: WhatsAppAuthData): Map<String, String> {+ val map = linkedMapOf(+ "e_regid" to RegEncoding.b64Url(intBe(auth.registrationId, 4)),+ "e_keytype" to RegEncoding.b64Url(byteArrayOf(WhatsAppRegistrationConstants.KEY_TYPE_CURVE25519)),+ "e_ident" to RegEncoding.b64Url(dec(auth.identityPublicKey)),+ "e_skey_id" to RegEncoding.b64Url(intBe(auth.signedPreKeyId, 3)),+ "e_skey_val" to RegEncoding.b64Url(dec(auth.signedPreKeyPublic)),+ "e_skey_sig" to RegEncoding.b64Url(dec(auth.signedPreKeySignature)),+ "authkey" to RegEncoding.b64Url(dec(auth.noisePublicKey)),+ )+ // Post-quantum last-resort prekey — all-or-none (w2.md §2.1). Only emit when the full+ // triple is present; otherwise the server returns bad_param:e_pq_last_resort_*.+ if (auth.pqLastResortKeyId != 0 &&+ auth.pqLastResortPublic.isNotEmpty() &&+ auth.pqLastResortSignature.isNotEmpty()+ ) {+ map["e_pq_last_resort_id"] = RegEncoding.b64Url(intBe(auth.pqLastResortKeyId, 3))+ map["e_pq_last_resort_val"] = RegEncoding.b64Url(dec(auth.pqLastResortPublic))+ map["e_pq_last_resort_sig"] = RegEncoding.b64Url(dec(auth.pqLastResortSignature))+ }+ return map+ } /** Big-endian encode [value] into [len] bytes (len ≤ 4). */ private fun intBe(value: Int, len: Int): ByteArray {
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppAttestationKeyStore.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppAttestationKeyStore.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppAttestationKeyStore.ktnew file mode 100644index 0000000000..d0a87e5cf9--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppAttestationKeyStore.kt@@ -0,0 +1,81 @@+package com.vayunmathur.communicate.data.whatsapp.registration++import android.content.Context+import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import android.util.Log+import java.security.KeyStore+import javax.crypto.KeyGenerator+import javax.crypto.Mac+import javax.crypto.SecretKey++/**+ * Hardware-backed attestation key for the registration `H` HMAC (w2.md §1.4/§2.3, Phase B 2c).+ *+ * The official client keys `H = HMAC-SHA256(ENC, attestationKey)` from an AndroidKeyStore-backed+ * device key (`C1DB`). We replace the previous software `SecureRandom` key+ * ([WhatsAppDeviceFingerprint.attestationKey]) with a non-exportable **AndroidKeyStore**+ * HMAC-SHA256 key generated once, and sign via the KeyStore `Mac` handle so the raw key never+ * leaves secure hardware (StrongBox / TEE where available).+ *+ * [signWithFallback] falls back to a caller-provided software HMAC key when the KeyStore is+ * unavailable (e.g. no hardware keystore), so `H` remains best-effort exactly like the official+ * client (which warns and continues when it can't produce `H`).+ *+ * Note: AndroidKeyStore key-attestation certificate chains (`setAttestationChallenge`) are only+ * emitted for asymmetric (EC/RSA) keys, not HMAC keys, so no cert chain is captured here.+ */+object WhatsAppAttestationKeyStore {++ private const val TAG = "WAAttestKeyStore"+ private const val KEYSTORE = "AndroidKeyStore"+ private const val KEY_ALIAS = "communicate_whatsapp_attestation_hmac"++ /** True if a hardware/software AndroidKeyStore HMAC key could be obtained. */+ fun isAvailable(): Boolean = runCatching { getOrCreateKey() != null }.getOrDefault(false)++ /**+ * Sign [body] with the KeyStore HMAC key; on any failure sign with [softwareKey] instead.+ * Returns the raw 32-byte MAC.+ */+ fun signWithFallback(body: ByteArray, softwareKey: ByteArray): ByteArray {+ signHardware(body)?.let { return it }+ val mac = Mac.getInstance("HmacSHA256")+ mac.init(javax.crypto.spec.SecretKeySpec(softwareKey, "HmacSHA256"))+ return mac.doFinal(body)+ }++ /** Sign [body] via the AndroidKeyStore HMAC key, or null if the KeyStore path is unavailable. */+ fun signHardware(body: ByteArray): ByteArray? = runCatching {+ val key = getOrCreateKey() ?: return null+ val mac = Mac.getInstance(KeyProperties.KEY_ALGORITHM_HMAC_SHA256)+ mac.init(key)+ mac.doFinal(body)+ }.getOrElse {+ Log.w(TAG, "KeyStore HMAC sign failed; caller should fall back", it)+ null+ }++ private fun getOrCreateKey(): SecretKey? {+ val ks = KeyStore.getInstance(KEYSTORE).apply { load(null) }+ (ks.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }+ val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_HMAC_SHA256, KEYSTORE)+ gen.init(+ KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_SIGN)+ .setDigests(KeyProperties.DIGEST_SHA256)+ .build(),+ )+ return gen.generateKey()+ }++ /** For diagnostics/tests: reads whether the generated key reports as inside secure hardware. */+ @Suppress("DEPRECATION")+ fun describe(context: Context): String = runCatching {+ val ks = KeyStore.getInstance(KEYSTORE).apply { load(null) }+ val key = ks.getKey(KEY_ALIAS, null) ?: return "no-key"+ val factory = javax.crypto.SecretKeyFactory.getInstance(key.algorithm, KEYSTORE)+ val info = factory.getKeySpec(key as SecretKey, android.security.keystore.KeyInfo::class.java)+ as android.security.keystore.KeyInfo+ "hardwareBacked=${info.isInsideSecureHardware}"+ }.getOrDefault("unavailable")+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppPqPreKey.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppPqPreKey.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppPqPreKey.ktnew file mode 100644index 0000000000..b98738990a--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppPqPreKey.kt@@ -0,0 +1,62 @@+package com.vayunmathur.communicate.data.whatsapp.registration++import com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto+import org.signal.libsignal.protocol.kem.KEMKeyPair+import org.signal.libsignal.protocol.kem.KEMKeyType++/**+ * Post-quantum (Kyber1024 / ML-KEM) last-resort prekey for the registration `e_pq_*` bundle+ * (w2.md §2.1, Phase B 2d).+ *+ * Uses the bundled libsignal KEM API (`org.signal.libsignal.protocol.kem`) — already a dependency+ * (verified: `libsignal-client` 0.86.5 ships `KEMKeyPair`/`KEMKeyType.KYBER_1024`). The signature+ * is XEdDSA over `0x08 || pqPublicKey` using the curve25519 identity private key, mirroring the+ * classic signed-prekey convention (`WhatsAppE2E.signSignedPreKey` signs `0x05 || skeyPub`).+ *+ * `KEMPublicKey.serialize()` prepends a 1-byte type tag (`0x08` for Kyber1024); the wire+ * `e_pq_last_resort_val` is the raw 1568-byte public key, so the tag byte is stripped.+ */+object WhatsAppPqPreKey {++ data class Generated(+ val keyId: Int,+ /** Raw Kyber1024 public key, 1568 bytes (no type tag). */+ val publicKey: ByteArray,+ /** Serialized KEM secret key (opaque; persisted for later use). */+ val secretKey: ByteArray,+ /** XEdDSA signature over `0x08 || publicKey`, 64 bytes. */+ val signature: ByteArray,+ )++ /**+ * The bytes signed to produce `e_pq_last_resort_sig`: `0x08 || pqPublicKey`. Pure/JVM-testable+ * (no native/libsignal calls) so the signing input framing can be asserted in unit tests.+ */+ fun signingInput(pqPublicKey: ByteArray): ByteArray {+ val out = ByteArray(1 + pqPublicKey.size)+ out[0] = WhatsAppRegistrationConstants.KEY_TYPE_KYBER+ System.arraycopy(pqPublicKey, 0, out, 1, pqPublicKey.size)+ return out+ }++ /** Strip the leading libsignal type tag from a serialized [KEMPublicKey] blob. */+ private fun stripTypeTag(serialized: ByteArray): ByteArray =+ if (serialized.size == WhatsAppRegistrationConstants.PQ_KYBER1024_PUBLIC_LEN) {+ serialized+ } else {+ serialized.copyOfRange(1, serialized.size)+ }++ /**+ * Generate a Kyber1024 last-resort prekey and sign it with the curve25519 [identityPrivate32].+ * @throws RuntimeException if native signing fails.+ */+ fun generate(identityPrivate32: ByteArray, keyId: Int): Generated {+ val kp = KEMKeyPair.generate(KEMKeyType.KYBER_1024)+ val pub = stripTypeTag(kp.publicKey.serialize())+ val secret = kp.secretKey.serialize()+ val signature = RustWhatsAppCrypto.sign(identityPrivate32, signingInput(pub))+ ?: throw RuntimeException("Rust sign returned null for PQ prekey")+ return Generated(keyId = keyId, publicKey = pub, secretKey = secret, signature = signature)+ }+}
communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppRegistrationConstants.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppRegistrationConstants.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppRegistrationConstants.ktindex 84a1c29e98..2b59d240bc 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppRegistrationConstants.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/whatsapp/registration/WhatsAppRegistrationConstants.kt@@ -50,4 +50,18 @@ object WhatsAppRegistrationConstants { /** e_keytype for Curve25519 (djb type). */ const val KEY_TYPE_CURVE25519: Byte = 0x05++ /**+ * Key type byte for the post-quantum (Kyber1024 / ML-KEM) last-resort prekey. Mirrors the+ * curve25519 `0x05` type-byte convention: the PQ signed-prekey signature is computed over+ * `0x08 || pqPublicKey` (see [RegistrationKeys]/`WhatsAppPqPreKey`). Ref w2.md §2.1+ * (`e_pq_last_resort_sig` = `Ed25519(sign(e_ident+0x08+e_pq_val))`).+ */+ const val KEY_TYPE_KYBER: Byte = 0x08++ /** The fixed id assigned to our single PQ last-resort prekey (3B BE on the wire). */+ const val PQ_LAST_RESORT_KEY_ID = 1++ /** Expected Kyber1024 public key length in bytes (`e_pq_last_resort_val`, w2.md §2.1). */+ const val PQ_KYBER1024_PUBLIC_LEN = 1568 }
communicate/src/main/java/com/vayunmathur/communicate/ui/whatsapp/WhatsAppCallScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/whatsapp/WhatsAppCallScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/whatsapp/WhatsAppCallScreen.ktnew file mode 100644index 0000000000..b54b73ef24--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/whatsapp/WhatsAppCallScreen.kt@@ -0,0 +1,174 @@+package com.vayunmathur.communicate.ui.whatsapp++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.viewinterop.AndroidView+import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager+import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallPhase+import com.vayunmathur.library.ui.FilledIconButton+import com.vayunmathur.library.ui.IconCall+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconMic+import com.vayunmathur.library.ui.IconMicOff+import com.vayunmathur.library.ui.IconVolumeUp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import org.webrtc.SurfaceViewRenderer++/**+ * Full-screen in-app UI for a ringing / incoming / active WhatsApp call (Phase D 3e). Reads the+ * [WhatsAppCallManager] state flow and drives answer / decline / mute / speaker / hangup. Rendered+ * as an overlay by the app while a call is in progress. Mirrors `ui/call/CallScreen`.+ *+ * Video render surfaces (local/remote `SurfaceViewRenderer`) are wired via+ * [WhatsAppCallManager.attachVideoRenderers]; remote-track rendering is best-effort in this dev+ * scaffolding (client-to-client only).+ */+@Composable+fun WhatsAppCallScreen(onClose: () -> Unit) {+ val state by WhatsAppCallManager.state.collectAsState()++ LaunchedEffect(state.phase) {+ if (state.phase == WhatsAppCallPhase.Ended || state.phase == WhatsAppCallPhase.Idle) {+ WhatsAppCallManager.clearEnded()+ onClose()+ }+ }++ Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {+ Column(+ modifier = Modifier+ .fillMaxSize()+ .padding(24.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.SpaceBetween,+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Spacer(Modifier.size(48.dp))+ Text(+ text = state.peerName.ifEmpty { state.peerJid.substringBefore("@") },+ style = MaterialTheme.typography.headlineMedium,+ fontWeight = FontWeight.SemiBold,+ )+ Spacer(Modifier.size(8.dp))+ Text(+ text = phaseLabel(state.phase, state.isVideo),+ style = MaterialTheme.typography.bodyLarge,+ color = MaterialTheme.colorScheme.onSurface,+ )+ if (state.isVideo && state.phase != WhatsAppCallPhase.Incoming) {+ Spacer(Modifier.size(16.dp))+ VideoSurfaces()+ }+ }++ when (state.phase) {+ WhatsAppCallPhase.Incoming -> IncomingControls()+ else -> InCallControls(muted = state.muted, speaker = state.speaker, video = state.isVideo)+ }+ }+ }+}++@Composable+private fun VideoSurfaces() {+ val remote = remember { mutableStateOf<SurfaceViewRenderer?>(null) }+ val local = remember { mutableStateOf<SurfaceViewRenderer?>(null) }++ DisposableEffect(Unit) {+ onDispose { WhatsAppCallManager.attachVideoRenderers(null, null) }+ }+ LaunchedEffect(remote.value, local.value) {+ if (remote.value != null || local.value != null) {+ WhatsAppCallManager.attachVideoRenderers(local.value, remote.value)+ }+ }++ Box(modifier = Modifier.fillMaxWidth().height(320.dp)) {+ AndroidView(+ factory = { ctx -> SurfaceViewRenderer(ctx).also { remote.value = it } },+ modifier = Modifier.fillMaxSize(),+ )+ AndroidView(+ factory = { ctx -> SurfaceViewRenderer(ctx).also { local.value = it } },+ modifier = Modifier+ .align(Alignment.BottomEnd)+ .padding(8.dp)+ .width(96.dp)+ .height(128.dp),+ )+ }+}++@Composable+private fun IncomingControls() {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = 32.dp),+ horizontalArrangement = Arrangement.SpaceEvenly,+ ) {+ FilledIconButton(onClick = { WhatsAppCallManager.reject() }, modifier = Modifier.size(64.dp)) { IconClose() }+ FilledIconButton(onClick = { WhatsAppCallManager.answer() }, modifier = Modifier.size(64.dp)) { IconCall() }+ }+}++@Composable+private fun InCallControls(muted: Boolean, speaker: Boolean, video: Boolean) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = 16.dp),+ horizontalArrangement = Arrangement.SpaceEvenly,+ ) {+ FilledIconButton(onClick = { WhatsAppCallManager.setMuted(!muted) }, modifier = Modifier.size(64.dp)) {+ if (muted) IconMicOff() else IconMic()+ }+ FilledIconButton(onClick = { WhatsAppCallManager.setSpeaker(!speaker) }, modifier = Modifier.size(64.dp)) {+ IconVolumeUp()+ }+ if (video) {+ FilledIconButton(onClick = { WhatsAppCallManager.switchCamera() }, modifier = Modifier.size(64.dp)) {+ IconCall()+ }+ }+ }+ Box(modifier = Modifier.padding(bottom = 32.dp)) {+ FilledIconButton(onClick = { WhatsAppCallManager.hangup() }, modifier = Modifier.size(64.dp)) { IconClose() }+ }+ }+}++private fun phaseLabel(phase: WhatsAppCallPhase, video: Boolean): String {+ val kind = if (video) "Video call" else "Voice call"+ return when (phase) {+ WhatsAppCallPhase.Outgoing -> "Calling…"+ WhatsAppCallPhase.Incoming -> "Incoming $kind"+ WhatsAppCallPhase.Connecting -> "Connecting…"+ WhatsAppCallPhase.Active -> kind+ WhatsAppCallPhase.Ended -> "Call ended"+ WhatsAppCallPhase.Idle -> ""+ }+}
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppAttestationTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppAttestationTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppAttestationTest.ktnew file mode 100644index 0000000000..c9b28d1784--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppAttestationTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.communicate.whatsapp++import com.vayunmathur.communicate.data.whatsapp.registration.RegistrationIntegrity+import com.vayunmathur.communicate.data.whatsapp.registration.WhatsAppPqPreKey+import java.nio.ByteBuffer+import java.util.Base64+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Wire-shape assertions for the attestation integrity encoders + PQ signing-input framing+ * (Phase B 2a/2d). Pure (java.util.Base64 + java.security), no Android runtime required.+ */+class WhatsAppAttestationTest {++ private val dec = Base64.getDecoder()++ @Test+ fun aid_isBase64Sha256_44chars_deterministic() {+ val a = RegistrationIntegrity.aidOf("abc123deviceid")+ val b = RegistrationIntegrity.aidOf("abc123deviceid")+ assertEquals(a, b)+ assertEquals(44, a.length) // base64 of a 32-byte SHA-256 digest+ assertEquals(32, dec.decode(a).size)+ }++ @Test+ fun permissionsHash_isOrderIndependent() {+ val a = RegistrationIntegrity.permissionsHashOf(listOf("B", "A", "C"))+ val b = RegistrationIntegrity.permissionsHashOf(listOf("C", "B", "A"))+ assertEquals(a, b)+ assertEquals(32, dec.decode(a).size)+ }++ @Test+ fun tField_isBigEndianInt64Base64() {+ val t = 1_786_666_203L+ val decoded = dec.decode(RegistrationIntegrity.tField(t))+ assertEquals(8, decoded.size)+ assertEquals(t, ByteBuffer.wrap(decoded).long)+ }++ @Test+ fun jsonEncoders_matchSpecShapes() {+ assertEquals("""{"sv":false,"sb":true}""", RegistrationIntegrity.emulationJson(false, true))+ assertEquals(+ """{"mp":true,"mu":false,"ae":10,"ap":20,"ai":0}""",+ RegistrationIntegrity.automationJson(true, false, 10, 20, 0),+ )+ assertEquals("""{"em":"AAAA"}""", RegistrationIntegrity.nativeSignalsJson("AAAA"))+ }++ @Test+ fun pqSigningInput_isTypeBytePlusPublicKey() {+ val pub = ByteArray(1568) { (it and 0xFF).toByte() }+ val input = WhatsAppPqPreKey.signingInput(pub)+ assertEquals(1 + 1568, input.size)+ assertEquals(0x08.toByte(), input[0]) // KEY_TYPE_KYBER+ assertContentEquals(pub, input.copyOfRange(1, input.size))+ }++ @Test+ fun pqSigningInput_typeByteDistinguishesFromCurve() {+ // Curve25519 signed-prekey uses 0x05; the PQ prekey MUST use 0x08 so the signatures over+ // otherwise-identical key bytes differ.+ val pub = ByteArray(32) { 7 }+ assertTrue(WhatsAppPqPreKey.signingInput(pub)[0] != 0x05.toByte())+ }+}
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppCallCryptoTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppCallCryptoTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppCallCryptoTest.ktnew file mode 100644index 0000000000..4502653369--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppCallCryptoTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.communicate.whatsapp++import com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallCrypto+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Derivation vectors for the call-key crypto (Phase D 3b). Pure (java.security only), no Android.+ */+class WhatsAppCallCryptoTest {++ private val callKey = ByteArray(32) { (it + 1).toByte() }++ @Test+ fun callKeyIs32Bytes() {+ assertEquals(32, WhatsAppCallCrypto.generateCallKey().size)+ }++ @Test+ fun mediaKeys_areDeterministicWithCorrectLengths() {+ val a = WhatsAppCallCrypto.deriveMediaKeys(callKey, "call-123")+ val b = WhatsAppCallCrypto.deriveMediaKeys(callKey, "call-123")+ assertEquals(16, a.encKey.size)+ assertEquals(14, a.salt.size)+ assertEquals(32, a.authKey.size)+ assertTrue(a.encKey.contentEquals(b.encKey))+ assertTrue(a.salt.contentEquals(b.salt))+ assertTrue(a.authKey.contentEquals(b.authKey))+ assertEquals(a.ssrc, b.ssrc)+ }++ @Test+ fun differentCallId_yieldsDifferentKeys() {+ val a = WhatsAppCallCrypto.deriveMediaKeys(callKey, "call-A")+ val b = WhatsAppCallCrypto.deriveMediaKeys(callKey, "call-B")+ assertFalse(a.encKey.contentEquals(b.encKey))+ assertTrue(a.ssrc != b.ssrc || !a.salt.contentEquals(b.salt))+ }++ @Test+ fun ssrc_isNonNegativeAndDeterministic() {+ val s1 = WhatsAppCallCrypto.deriveSsrc(callKey, "call-1")+ val s2 = WhatsAppCallCrypto.deriveSsrc(callKey, "call-1")+ assertEquals(s1, s2)+ assertTrue(s1 >= 0)+ }++ @Test+ fun rekey_differsFromOriginalAndIs32Bytes() {+ val rk = WhatsAppCallCrypto.rekey(callKey, "rekey-7")+ assertEquals(32, rk.size)+ assertFalse(rk.contentEquals(callKey))+ // Deterministic for the same rekey id.+ assertTrue(rk.contentEquals(WhatsAppCallCrypto.rekey(callKey, "rekey-7")))+ }+}
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppContactSyncTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppContactSyncTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppContactSyncTest.ktnew file mode 100644index 0000000000..51ec240484--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/WhatsAppContactSyncTest.kt@@ -0,0 +1,30 @@+package com.vayunmathur.communicate.whatsapp++import com.vayunmathur.communicate.data.whatsapp.WhatsAppContactSync+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * E.164 normalization used by the device-contact sync (Phase C 2f). Pure (libphonenumber only),+ * no Android runtime required.+ */+class WhatsAppContactSyncTest {++ @Test+ fun normalizesNationalUsNumberToE164() {+ assertEquals("+12024561111", WhatsAppContactSync.normalizeE164("(202) 456-1111", "US"))+ assertEquals("+12024561111", WhatsAppContactSync.normalizeE164("202-456-1111", "US"))+ }++ @Test+ fun keepsAlreadyInternationalNumber() {+ assertEquals("+442071838750", WhatsAppContactSync.normalizeE164("+44 20 7183 8750", "US"))+ }++ @Test+ fun rejectsGarbageAndTooShort() {+ assertNull(WhatsAppContactSync.normalizeE164("not a phone", "US"))+ assertNull(WhatsAppContactSync.normalizeE164("123", "US"))+ }+}