Modern Apps git

← Modern-Apps.git

messages: various fixes

Commit
477f5d2a53ea70fbb3a4e66cdff852df962b0daa
Author
Vayun Mathur <[email protected]>
When
2026-06-10 22:06 UTC (5 months ago)
Parents
b08b701

Diff

.idea/idealens/idealens.xml
diff --git a/.idea/idealens/idealens.xml b/.idea/idealens/idealens.xmlnew file mode 100644index 0000000000..e5580d9638--- /dev/null+++ b/.idea/idealens/idealens.xml@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="UTF-8"?>+<project version="4">+  <component name="IdeaLensProjectSettingsComponent">+    <option name="lensTypeEnabled">+      <map>+        <entry key="Class Load" value="true" />+        <entry key="CodeBits" value="true" />+        <entry key="Dead Items" value="false" />+        <entry key="Gatekeeper" value="true" />+        <entry key="Launcher" value="true" />+        <entry key="MobileConfig" value="true" />+        <entry key="PrivacyDecision" value="true" />+        <entry key="QuickPerformanceLogger (QPL)" value="true" />+        <entry key="TestDetails" value="true" />+        <entry key="Thread Safe" value="true" />+      </map>+    </option>+  </component>+</project>\ No newline at end of file
contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.kt b/contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.ktindex b2aff9fef9..64967c916b 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.kt@@ -1,7 +1,6 @@ package com.vayunmathur.contacts.intents -import com.vayunmathur.contacts.R-import com.vayunmathur.contacts.data.Contact+import android.provider.ContactsContract import com.vayunmathur.library.intents.contacts.ContactData import com.vayunmathur.library.util.AssistantIntent import kotlinx.serialization.InternalSerializationApi@@ -11,11 +10,25 @@ import kotlinx.serialization.serializer class GetIntent: AssistantIntent<Unit, List<ContactData>>(serializer<Unit>(), serializer<List<ContactData>>()) {      override suspend fun performCalculation(input: Unit): List<ContactData> {-        return Contact.getAllContacts(this).map { contact ->-            ContactData(-                name = getString(R.string.full_name_format, contact.name.firstName, contact.name.lastName),-                phoneNumber = contact.details.phoneNumbers.firstOrNull()?.number ?: ""-            )+        val contacts = mutableListOf<ContactData>()+        contentResolver.query(+            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,+            arrayOf(+                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,+                ContactsContract.CommonDataKinds.Phone.NUMBER+            ),+            null, null,+            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"+        )?.use { cursor ->+            val nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)+            val numberIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)+            while (cursor.moveToNext()) {+                contacts.add(ContactData(+                    name = cursor.getString(nameIdx) ?: "",+                    phoneNumber = cursor.getString(numberIdx) ?: ""+                ))+            }         }+        return contacts     } }
messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.ktindex 8bd7f01c22..cfda655e01 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/AuthData.kt@@ -68,7 +68,7 @@ data class AuthData(     val webEncryptionKeyB64: String? = null, ) { -    fun isPaired(): Boolean = !tachyonAuthTokenB64.isNullOrBlank() && mobileDeviceB64 != null+    fun isPaired(): Boolean = !tachyonAuthTokenB64.isNullOrBlank() && browserDeviceB64 != null      fun isGoogleAccount(): Boolean = !destRegId.isNullOrBlank() 
messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.ktindex 5698585397..b3c6ec4a26 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/GMessagesClient.kt@@ -544,7 +544,7 @@ object GMessagesClient {             }             updates.hasBrowserPresenceCheckEvent() -> {                 Log.d(TAG, "GET_UPDATES: browser presence check, sending ack")-                ackBrowserPresence()+                scope.launch { ackBrowserPresence() }             }             updates.hasAccountChange() -> {                 Log.d(TAG, "GET_UPDATES: account change event")@@ -566,12 +566,11 @@ object GMessagesClient {             for (i in recentUpdatesPtr + recentUpdates.size - 1 downTo recentUpdatesPtr) {                 val item = recentUpdates[i % recentUpdates.size] ?: continue                 if (item.id == id) {-                    return if (item.hash.contentEquals(hash)) {+                    if (item.hash.contentEquals(hash)) {                         Log.d(TAG, "dedup: ignoring duplicate update id=$id")-                        true-                    } else {-                        false+                        return true                     }+                    break                 }             }             recentUpdates[recentUpdatesPtr] = UpdateDedupItem(id, hash)@@ -609,6 +608,18 @@ object GMessagesClient {      */     private suspend fun postConnect() {         kotlinx.coroutines.delay(2_000)+        // If old messages haven't drained yet, wait up to 3 more seconds+        // (port of Go's skipCount check in postConnect)+        if (longPoll.skipCount > 0) {+            Log.w(TAG, "skipCount is non-zero (${longPoll.skipCount}) in postConnect, waiting longer")+            repeat(3) {+                if (longPoll.skipCount <= 0) return@repeat+                kotlinx.coroutines.delay(1_000)+            }+            if (longPoll.skipCount > 0) {+                Log.w(TAG, "skipCount is still non-zero (${longPoll.skipCount})")+            }+        }         // Send acks before set active session (matches Go's postConnect)         sessionHandler.sendAckRequest()         kotlinx.coroutines.delay(1_000)
messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.ktindex 5d8e757e68..ecb6b93821 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/LongPoll.kt@@ -272,7 +272,7 @@ class LongPoll(             unencryptedData = if (msg.unencryptedData.size() > 0) msg.unencryptedData.toByteArray() else null,         )         val reqId = msg.sessionID-        if (reqId.isNotEmpty()) sessionHandler.deliverResponse(reqId, incoming)+        if (reqId.isNotEmpty() && sessionHandler.deliverResponse(reqId, incoming)) return         onEvent(LongPollEvent.Data(incoming))     } @@ -288,12 +288,6 @@ class LongPoll(             "data event: action=${msg.action} sessionID=${msg.sessionID} encrypted=${msg.encryptedData.size()}B",         ) -        // Track old messages via skipCount-        val isOld = if (skipCount > 0) {-            skipCount---            true-        } else false-         var decrypted: ByteArray? = null         if (msg.encryptedData.size() > 0) {             decrypted = try {@@ -313,16 +307,36 @@ class LongPoll(          val unencrypted = if (msg.unencryptedData.size() > 0) msg.unencryptedData.toByteArray() else null +        // Try to deliver to a waiter first (port of Go's receiveResponse+        // check in HandleRPCMsg). If consumed, return early — don't+        // process as an update event and don't decrement skipCount.+        val reqId = msg.sessionID+        if (reqId.isNotEmpty()) {+            val incoming = IncomingRpc(+                responseId = data.responseID,+                requestId = reqId,+                action = msg.action,+                decryptedData = decrypted,+                unencryptedData = unencrypted,+            )+            if (sessionHandler.deliverResponse(reqId, incoming)) return+        }++        // Only track old messages via skipCount for non-waiter messages+        // (matches Go where skipCount is checked after receiveResponse).+        val isOld = if (skipCount > 0) {+            skipCount--+            true+        } else false+         val incoming = IncomingRpc(             responseId = data.responseID,-            requestId = msg.sessionID.takeIf { it.isNotEmpty() },+            requestId = reqId.takeIf { it.isNotEmpty() },             action = msg.action,             decryptedData = decrypted,             unencryptedData = unencrypted,             isOld = isOld,         )-        val reqId = msg.sessionID-        if (reqId.isNotEmpty()) sessionHandler.deliverResponse(reqId, incoming)         onEvent(LongPollEvent.Data(incoming))     } 
messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt b/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.ktindex 7861356a49..725f995d2d 100644--- a/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gmessages/SessionHandler.kt@@ -252,8 +252,10 @@ class SessionHandler(         ))     } -    /** Called by the long-poll dispatcher when a response arrives. */-    fun deliverResponse(requestId: String, msg: IncomingRpc) {+    /** Called by the long-poll dispatcher when a response arrives.+     *  Returns true if the response was consumed by a waiter (matching+     *  Go's `receiveResponse` return semantics). */+    fun deliverResponse(requestId: String, msg: IncomingRpc): Boolean {         val auth = authProvider()         if (auth.hasCookies()) {             when (msg.action) {@@ -261,7 +263,7 @@ class SessionHandler(                 ActionType.CREATE_GAIA_PAIRING_CLIENT_FINISHED -> { /* allow */ }                 else -> {                     if (msg.unencryptedData != null && msg.decryptedData == null) {-                        return+                        return false                     }                 }             }@@ -269,10 +271,11 @@ class SessionHandler(         val waiter = waiters.remove(requestId)         if (waiter == null) {             Log.d(TAG, "no waiter for requestID=$requestId (action=${msg.action})")-            return+            return false         }         Log.i(TAG, "delivering response for requestID=$requestId action=${msg.action}")         waiter.complete(msg)+        return true     }      /** Drop everything (called on stop / reset). */
messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.ktindex 170f46de86..2a8c75334d 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt@@ -290,10 +290,10 @@ object GVoiceClient {      private fun mimeToVoiceMediaType(mime: String): Requests.ReqSendSMS.Media.Type? =         when (mime.lowercase()) {-            "image/jpeg", "image/jpg" -> Requests.ReqSendSMS.Media.Type.JPEG             "image/png" -> Requests.ReqSendSMS.Media.Type.PNG+            "image/jpeg" -> Requests.ReqSendSMS.Media.Type.JPEG             "image/gif" -> Requests.ReqSendSMS.Media.Type.GIF-            "image/bmp", "image/x-ms-bmp" -> Requests.ReqSendSMS.Media.Type.BMP+            "image/bmp" -> Requests.ReqSendSMS.Media.Type.BMP             "image/tiff" -> Requests.ReqSendSMS.Media.Type.TIFF             "image/webp" -> Requests.ReqSendSMS.Media.Type.WEBP             else -> null@@ -811,6 +811,13 @@ object GVoiceClient {             }         } +        // If no text and no MMS, this is an unknown message type+        // (matches Go's convertMessage fallback: `logUnknownGVMessage` ++        // `convertUnknownGVMessage` which returns "Unknown message type").+        if (m.text.isEmpty() && !m.hasMMS()) {+            return "Unknown message type, please view it on the Google Voice app"+        }+         // MMS messages         if (m.hasMMS()) {             val mms = m.getMMS()
messages/src/main/java/com/vayunmathur/messages/meta/MetaAuthData.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/meta/MetaAuthData.kt b/messages/src/main/java/com/vayunmathur/messages/meta/MetaAuthData.ktindex 6f4344a153..05d7794e18 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaAuthData.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaAuthData.kt@@ -75,7 +75,9 @@ data class MetaAuthData(             Platform.INSTAGRAM -> {                 cookies.containsKey("sessionid") &&                 cookies.containsKey("csrftoken") &&-                cookies.containsKey("ds_user_id")+                cookies.containsKey("ds_user_id") &&+                cookies.containsKey("mid") &&+                cookies.containsKey("ig_did")             }         }     }
messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt b/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.ktindex 6c1902b515..f8831d54c3 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaMqttClient.kt@@ -166,11 +166,6 @@ class MetaMqttClient(     }      private suspend fun sendConnectPacket() {-        val connectionType = when (authData.platform) {-            MetaAuthData.Platform.INSTAGRAM -> "cookie_auth"-            MetaAuthData.Platform.MESSENGER -> "websocket"-        }-         val connectJsonStr = MetaProtocol.buildConnectJson(             accountId = authData.userId,             sessionId = sessionId,@@ -243,19 +238,23 @@ class MetaMqttClient(         sendSubscribePacket(MetaProtocol.TOPIC_LS_FOREGROUND_STATE, MqttPackets.QOS_LEVEL_0)         sendSubscribePacket(MetaProtocol.TOPIC_LS_RESP, MqttPackets.QOS_LEVEL_0) -        previouslyConnected = true         _connectionState.emit(ConnectionState.Connected)         startPing()          // Fetch threads for SyncGroup 1 and SyncGroup 95 (from messagix/events.go)         if (versionId > 0) {-            syncDatabase(1)-            syncDatabase(95)+            val fetchPayloadSG1 = MetaProtocol.buildFetchThreadsPayload(versionId)+            makeLSRequest(fetchPayloadSG1, MetaProtocol.LS_REQUEST_TYPE_TASK)++            val fetchPayloadSG95 = MetaProtocol.buildFetchThreadsPayload(versionId, syncGroup = 95)+            makeLSRequest(fetchPayloadSG95, MetaProtocol.LS_REQUEST_TYPE_TASK)              // Report app state as FOREGROUND (from messagix/events.go)             val reportPayload = MetaProtocol.buildReportAppStatePayload(versionId)             makeLSRequest(reportPayload, MetaProtocol.LS_REQUEST_TYPE_TASK)         }++        previouslyConnected = true     }      private suspend fun syncDatabase(databaseId: Long, cursor: String? = null) {@@ -281,11 +280,12 @@ class MetaMqttClient(     }      private fun handlePublishMessage(publish: MqttFraming.MqttResponse.PublishMessage) {-        // Send PUBACK if QoS > 0-        if (publish.qos > 0 && publish.packetId > 0) {+        if (publish.qos == MqttPackets.QOS_LEVEL_1.toInt() && publish.packetId > 0) {             scope.launch {                 sendData(MqttFraming.buildPubAckPacket(publish.packetId))             }+        } else if (publish.qos == MqttPackets.QOS_LEVEL_2.toInt()) {+            Log.e(TAG, "Got packet with QoS level 2")         }          val mqttMessage = MetaProtocol.MqttMessage(@@ -379,7 +379,7 @@ class MetaMqttClient(         }          // PUBLISH type doesn't expect a response-        if (type == MetaProtocol.LS_REQUEST_TYPE_PUBLISH) {+        if (type == MetaProtocol.LS_REQUEST_TYPE_STATELESS) {             requestChannels.remove(packetId)             return null         }
messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt b/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.ktindex 568b880991..a97c45634c 100644--- a/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt+++ b/messages/src/main/java/com/vayunmathur/messages/meta/MetaProtocol.kt@@ -52,7 +52,7 @@ object MetaProtocol {     const val LS_REQUEST_TYPE_DB_QUERY = 1     const val LS_REQUEST_TYPE_DB_QUERY_CURSOR = 2     const val LS_REQUEST_TYPE_TASK = 3-    const val LS_REQUEST_TYPE_PUBLISH = 4+    const val LS_REQUEST_TYPE_STATELESS = 4      private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true } @@ -187,12 +187,36 @@ object MetaProtocol {         @SerialName("otid") val otid: String,         val source: Int = 0,         @SerialName("send_type") val sendType: Int = 1,+        @SerialName("attachment_fbids") val attachmentFbIds: List<Long>? = null,         @SerialName("sync_group") val syncGroup: Long = 1,+        @SerialName("reply_metadata") val replyMetadata: ReplyMetaData? = null,+        @SerialName("mention_data") val mentionData: MentionData? = null,         val text: String = "",+        @SerialName("hot_emoji_size") val hotEmojiSize: Int = 0,+        @SerialName("sticker_id") val stickerId: Long = 0,         @SerialName("initiating_source") val initiatingSource: Int = 0,         @SerialName("skip_url_preview_gen") val skipUrlPreviewGen: Int = 0,         @SerialName("text_has_links") val textHasLinks: Int = 0,+        @SerialName("strip_forwarded_msg_caption") val stripForwardedMsgCaption: Int = 0,+        @SerialName("forwarded_msg_id") val forwardedMsgId: String = "",         @SerialName("multitab_env") val multitabEnv: Int = 0,+        val url: String = "",+        @SerialName("attribution_app_id") val attributionAppId: Long = 0,+    )++    @Serializable+    data class ReplyMetaData(+        @SerialName("reply_source_id") val replySourceId: String,+        @SerialName("reply_source_type") val replySourceType: Long = 1,+        @SerialName("reply_type") val replyType: Long = 0,+    )++    @Serializable+    data class MentionData(+        @SerialName("mention_ids") val mentionIds: String,+        @SerialName("mention_offsets") val mentionOffsets: String,+        @SerialName("mention_lengths") val mentionLengths: String,+        @SerialName("mention_types") val mentionTypes: String,     )      @Serializable@@ -473,14 +497,20 @@ object MetaProtocol {         @SerialName("message_id") val messageId: String,     ) +    @Serializable+    data class DeleteMessageMeOnlyTask(+        @SerialName("thread_key") val threadKey: Long = 0,+        @SerialName("message_id") val messageId: String,+    )+     @Serializable     data class EditMessageTask(         @SerialName("message_id") val messageId: String,         val text: String,     ) -    fun buildFetchThreadsPayload(versionId: Long): String {-        val task = FetchThreadsTask()+    fun buildFetchThreadsPayload(versionId: Long, syncGroup: Int = 1): String {+        val task = FetchThreadsTask(syncGroup = syncGroup)         val taskJson = json.encodeToString(task)         return buildTaskPayload(             label = TASK_LABELS["FetchThreadsTask"] ?: "145",@@ -512,7 +542,7 @@ object MetaProtocol {      fun buildReportAppStatePayload(versionId: Long): String {         val task = ReportAppStateTask(-            requestId = generateEpochId().toString(),+            requestId = java.util.UUID.randomUUID().toString(),         )         val taskJson = json.encodeToString(task)         return buildTaskPayload(@@ -539,6 +569,24 @@ object MetaProtocol {         )     } +    fun buildDeleteMessageMeOnlyPayload(+        threadKey: Long,+        messageId: String,+        versionId: Long,+    ): String {+        val task = DeleteMessageMeOnlyTask(+            threadKey = threadKey,+            messageId = messageId,+        )+        val taskJson = json.encodeToString(task)+        return buildTaskPayload(+            label = TASK_LABELS["DeleteMessageMeOnlyTask"] ?: "155",+            taskPayloadJson = taskJson,+            queueName = "155",+            versionId = versionId,+        )+    }+     fun buildEditMessagePayload(         messageId: String,         text: String,@@ -557,6 +605,72 @@ object MetaProtocol {         )     } +    @Serializable+    data class DeleteThreadTask(+        @SerialName("thread_key") val threadKey: Long,+        @SerialName("remove_type") val removeType: Long = 0,+        @SerialName("sync_group") val syncGroup: Long = 1,+    )++    fun buildDeleteThreadPayload(+        threadKey: Long,+        versionId: Long,+    ): String {+        val task = DeleteThreadTask(threadKey = threadKey)+        val taskJson = json.encodeToString(task)+        return buildTaskPayload(+            label = TASK_LABELS["DeleteThreadTask"] ?: "146",+            taskPayloadJson = taskJson,+            queueName = threadKey.toString(),+            versionId = versionId,+        )+    }++    @Serializable+    data class MuteThreadTask(+        @SerialName("thread_key") val threadKey: Long,+        @SerialName("mailbox_type") val mailboxType: Long = 0,+        @SerialName("mute_expire_time_ms") val muteExpireTimeMs: Long,+        @SerialName("sync_group") val syncGroup: Long = 1,+    )++    fun buildMuteThreadPayload(+        threadKey: Long,+        muteExpireTimeMs: Long,+        versionId: Long,+    ): String {+        val task = MuteThreadTask(threadKey = threadKey, muteExpireTimeMs = muteExpireTimeMs)+        val taskJson = json.encodeToString(task)+        return buildTaskPayload(+            label = TASK_LABELS["MuteThreadTask"] ?: "144",+            taskPayloadJson = taskJson,+            queueName = threadKey.toString(),+            versionId = versionId,+        )+    }++    @Serializable+    data class RenameThreadTask(+        @SerialName("thread_key") val threadKey: Long,+        @SerialName("thread_name") val threadName: String,+        @SerialName("sync_group") val syncGroup: Long = 1,+    )++    fun buildRenameThreadPayload(+        threadKey: Long,+        threadName: String,+        versionId: Long,+    ): String {+        val task = RenameThreadTask(threadKey = threadKey, threadName = threadName)+        val taskJson = json.encodeToString(task)+        return buildTaskPayload(+            label = TASK_LABELS["RenameThreadTask"] ?: "32",+            taskPayloadJson = taskJson,+            queueName = threadKey.toString(),+            versionId = versionId,+        )+    }+     fun buildAppSettingsJson(versionId: Long): String {         return json.encodeToString(AppSettingsPublish(schemaVersion = versionId.toString()))     }
messages/src/main/java/com/vayunmathur/messages/signal/SignalAuthData.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/SignalAuthData.kt b/messages/src/main/java/com/vayunmathur/messages/signal/SignalAuthData.ktindex ac5d66256d..edcdce97a5 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/SignalAuthData.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/SignalAuthData.kt@@ -16,12 +16,22 @@ data class SignalAuthData(     val pniIdentityKeyPair: String,     val aciRegistrationId: Int,     val pniRegistrationId: Int,-    val profileKey: String? = null,     val masterKey: String? = null,     val accountEntropyPool: String? = null,     val ephemeralBackupKey: String? = null,     val mediaRootBackupKey: String? = null,+    val accountRecord: ByteArray? = null, ) {+    private val nilUuid = "00000000-0000-0000-0000-000000000000"++    fun isDeviceLoggedIn(): Boolean {+        return aci.isNotEmpty() && aci != nilUuid && deviceId != 0 && password.isNotEmpty()+    }++    fun basicAuthCreds(): Pair<String, String> {+        return Pair("$aci.$deviceId", password)+    }+     suspend fun save(context: Context) {         DataStoreUtils.getInstance(context).setString(             DATA_STORE_KEY,
messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt b/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.ktindex fabaa1ed41..b046d053c5 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt@@ -48,9 +48,12 @@ import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch+import org.json.JSONObject import org.signal.libsignal.protocol.IdentityKeyPair import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock  object SignalClient { @@ -79,8 +82,10 @@ object SignalClient {     private lateinit var appContext: Context     private var authData: SignalAuthData? = null     private var webSocket: SignalWebSocket? = null+    private var unauthedWebSocket: SignalWebSocket? = null     private var backfillJob: Job? = null     private var provisioningJob: Job? = null+    private var keyCheckJob: Job? = null      private var db: SignalDatabase? = null     private var sessionStore: SignalSessionStore? = null@@ -92,9 +97,31 @@ object SignalClient {     private var profileManager: ProfileManager? = null     private var groupManager: GroupManager? = null     private var contactDiscovery: ContactDiscovery? = null+    var syncContactsOnConnect: Boolean = false+    private var lastContactRequestTime: Long = 0L+    val encryptionLock = Mutex()      private val nameCache = ConcurrentHashMap<String, String>() +    fun isConnected(): Boolean {+        return webSocket?.isConnected() == true && unauthedWebSocket?.isConnected() == true+    }++    fun isLoggedIn(): Boolean {+        return authData?.isDeviceLoggedIn() == true+    }++    suspend fun getRemoteConfig(): String? {+        val ws = webSocket ?: return null+        return try {+            val response = ws.sendRequest("GET", "/v2/config")+            if (response.status in 200..299) response.body.toStringUtf8() else null+        } catch (e: Exception) {+            Log.w(TAG, "Failed to get remote config: ${e.message}")+            null+        }+    }+     fun init(context: Context) {         if (!initialized.compareAndSet(false, true)) return         appContext = context.applicationContext@@ -123,17 +150,26 @@ object SignalClient {         }     } -    fun stop() {-        Log.i(TAG, "stop — clearing Signal session")+    fun disconnect() {+        Log.i(TAG, "disconnect — stopping Signal websockets")         backfillJob?.cancel()-        provisioningJob?.cancel()+        keyCheckJob?.cancel()+        keyCheckJob = null         webSocket?.disconnect()         webSocket = null+        unauthedWebSocket?.disconnect()+        unauthedWebSocket = null         messageSender = null         contactManager = null         contactDiscovery = null         profileManager = null         groupManager = null+        _state.value = State.Disconnected("Disconnected")+    }++    fun stop() {+        Log.i(TAG, "stop — clearing Signal session")+        disconnect()         nameCache.clear()         scope.launch { SignalAuthData.clear(appContext) }         _state.value = State.NeedsSetup@@ -161,7 +197,10 @@ object SignalClient {                                 pniIdentityKeyPair = data.pniIdentityKeyPair,                                 aciRegistrationId = data.aciRegistrationId,                                 pniRegistrationId = data.pniRegistrationId,-                                profileKey = data.profileKey,+                                masterKey = data.masterKey,+                                accountEntropyPool = data.accountEntropyPool,+                                ephemeralBackupKey = data.ephemeralBackupKey,+                                mediaRootBackupKey = data.mediaRootBackupKey,                             )                             auth.save(appContext)                             authData = auth@@ -316,6 +355,16 @@ object SignalClient {             senderKeyStore = skStore              val basicAuth = "${auth.aci}.${auth.deviceId}:${auth.password}"++            if (webSocket != null) {+                webSocket?.disconnect()+                webSocket = null+            }+            if (unauthedWebSocket != null) {+                unauthedWebSocket?.disconnect()+                unauthedWebSocket = null+            }+             val ws = SignalWebSocket(                 appContext,                 android.util.Base64.encodeToString(@@ -323,11 +372,12 @@ object SignalClient {                     android.util.Base64.NO_WRAP,                 ),             )-            ws.connect("wss://chat.signal.org/v1/websocket/?login=${auth.aci}.${auth.deviceId}")+            ws.connect("wss://chat.signal.org/v1/websocket/")             webSocket = ws              val unauthedWs = SignalWebSocket(appContext)             unauthedWs.connect("wss://chat.signal.org/v1/websocket/")+            unauthedWebSocket = unauthedWs              val devManager = DeviceManager(ws, sessStore, idStore, pkStore, pkStore, pkStore, skStore)             val recipientStore = SignalRecipientStore(database)@@ -335,7 +385,7 @@ object SignalClient {             messageSender = sender             contactManager = ContactManager(recipientStore)             contactDiscovery = ContactDiscovery(recipientStore, auth.aci, auth.deviceId, auth.password, appContext)-            profileManager = ProfileManager(ws, recipientStore)+            profileManager = ProfileManager(unauthedWs, recipientStore)             groupManager = GroupManager(ws, SignalGroupStore(database), auth.aci, auth.pni, auth.password)              ws.incomingRequestHandler = { request ->@@ -350,11 +400,7 @@ object SignalClient {                     ws.sendRequest(                         "PUT",                         "/v1/devices/capabilities",-                        org.json.JSONObject().apply {-                            put("attachmentBackfill", true)-                            put("spqr", true)-                        }.toString().toByteArray(),-                        mapOf("Content-Type" to "application/json"),+                        Provisioning.signalCapabilities.toString().toByteArray(),                     )                     Log.d(TAG, "Successfully registered capabilities")                 } catch (t: Throwable) {@@ -372,7 +418,26 @@ object SignalClient {                 }             } -            kickoffBackfill()+            keyCheckJob?.cancel()+            keyCheckJob = scope.launch {+                try {+                    val aciKeyPair = IdentityKeyPair(Base64.decode(auth.aciIdentityKeyPair, Base64.NO_WRAP))+                    val pniKeyPair = IdentityKeyPair(Base64.decode(auth.pniIdentityKeyPair, Base64.NO_WRAP))+                    PreKeyManager.keyCheckLoop(ws, pkStore, aciKeyPair, pniKeyPair)+                } catch (e: CancellationException) {+                    throw e+                } catch (t: Throwable) {+                    Log.e(TAG, "Key check loop terminated: ${t.message}")+                    if (t.message?.contains("422") == true) {+                        _state.value = State.Disconnected("Logged out")+                        stop()+                    }+                }+            }++            if (syncContactsOnConnect) {+                kickoffBackfill()+            }              if (auth.masterKey == null) {                 scope.launch {@@ -437,6 +502,7 @@ object SignalClient {                     val decrypted = ContentDispatcher.dispatch(                         result.senderAci, result.senderDeviceId,                         result.content, result.timestamp, result.serverTimestamp,+                        selfAci = auth.aci,                     )                     handleDecryptedMessage(decrypted) 
messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.ktindex de381c51ac..5f175b8021 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/auth/PreKeyManager.kt@@ -9,19 +9,58 @@ import org.json.JSONObject import org.signal.libsignal.protocol.IdentityKeyPair import org.signal.libsignal.protocol.ecc.ECKeyPair import org.signal.libsignal.protocol.ecc.ECPublicKey-import org.signal.libsignal.protocol.ecc.ECPrivateKey import org.signal.libsignal.protocol.kem.KEMKeyPair import org.signal.libsignal.protocol.kem.KEMKeyType import org.signal.libsignal.protocol.state.KyberPreKeyRecord import org.signal.libsignal.protocol.state.PreKeyRecord+import org.signal.libsignal.protocol.state.PreKeyBundle import org.signal.libsignal.protocol.state.SignedPreKeyRecord+import org.signal.libsignal.protocol.SignalProtocolAddress+import org.signal.libsignal.protocol.SessionBuilder import java.io.IOException import java.security.SecureRandom+import kotlinx.coroutines.delay  object PreKeyManager {     private const val TAG = "PreKeyManager"     private const val BATCH_SIZE = 100     private const val MIN_KEY_COUNT = BATCH_SIZE / 2+    private const val ACI_KEYS_PATH = "/v2/keys?identity=aci"+    private const val PNI_KEYS_PATH = "/v2/keys?identity=pni"++    private data class PreKeyCountResult(val ecCount: Int, val pqCount: Int)++    private data class PreKeyResponse(+        val identityKey: String,+        val devices: List<PreKeyDevice>,+    )++    private data class PreKeyDevice(+        val deviceId: Int,+        val registrationId: Int,+        val signedPreKey: PreKeyDetail,+        val preKey: PreKeyDetail?,+        val pqPreKey: PreKeyDetail?,+    )++    private data class PreKeyDetail(+        val keyId: Int,+        val publicKey: String,+        val signature: String?,+    )++    private fun keysPath(identity: String): String {+        return if (identity == "pni") PNI_KEYS_PATH else ACI_KEYS_PATH+    }++    private fun addBase64PaddingAndDecode(data: String): ByteArray {+        var padded = data+        val padding = padded.length % 4+        if (padding > 0) {+            padded += "=".repeat(4 - padding)+        }+        return Base64.decode(padded, Base64.NO_WRAP)+    }      suspend fun generateAndUploadPreKeys(         ws: SignalWebSocket,@@ -40,23 +79,77 @@ object PreKeyManager {         aciIdentityKeyPair: IdentityKeyPair,         pniIdentityKeyPair: IdentityKeyPair,     ) {-        val aciCount = getPreKeyCount(ws, "aci")-        val pniCount = getPreKeyCount(ws, "pni")-        Log.d(TAG, "Pre-key counts: aci=$aciCount, pni=$pniCount")+        val aciCounts = getPreKeyCount(ws, "aci")+        val pniCounts = getPreKeyCount(ws, "pni")+        Log.d(TAG, "Pre-key counts: aci=(ec=${aciCounts.ecCount}, pq=${aciCounts.pqCount}), pni=(ec=${pniCounts.ecCount}, pq=${pniCounts.pqCount})")++        var aciNeedsUpload = false+        var pniNeedsUpload = false++        if (aciCounts.ecCount < MIN_KEY_COUNT || aciCounts.pqCount < MIN_KEY_COUNT) {+            aciNeedsUpload = true+        }+        if (pniCounts.ecCount < MIN_KEY_COUNT || pniCounts.pqCount < MIN_KEY_COUNT) {+            pniNeedsUpload = true+        } -        if (aciCount < MIN_KEY_COUNT) {+        if (aciNeedsUpload) {             uploadKeysForIdentity(ws, preKeyStore, "aci", aciIdentityKeyPair)         }-        if (pniCount < MIN_KEY_COUNT) {+        if (pniNeedsUpload) {             uploadKeysForIdentity(ws, preKeyStore, "pni", pniIdentityKeyPair)         }     } -    private suspend fun getPreKeyCount(ws: SignalWebSocket, identity: String): Int {-        val response = ws.sendRequest("GET", "/v2/keys?identity=$identity")-        if (response.status != 200) return 0+    suspend fun keyCheckLoop(+        ws: SignalWebSocket,+        preKeyStore: SignalPreKeyStore,+        aciIdentityKeyPair: IdentityKeyPair,+        pniIdentityKeyPair: IdentityKeyPair,+    ) {+        var windowStartMinutes = 0+        var windowSizeMinutes = 1+        var firstRun = true+        while (true) {+            val waitMinutes = if (firstRun) {+                firstRun = false+                0+            } else {+                val random = SecureRandom()+                random.nextInt(windowSizeMinutes) + windowStartMinutes+            }+            if (waitMinutes > 0) {+                Log.d(TAG, "Waiting $waitMinutes minutes before next key check")+                delay(waitMinutes * 60_000L)+            }+            try {+                checkAndRefreshIfNeeded(ws, preKeyStore, aciIdentityKeyPair, pniIdentityKeyPair)+                // After success, check again in 36–60 hours+                windowStartMinutes = 36 * 60+                windowSizeMinutes = 24 * 60+            } catch (e: IOException) {+                if (e.message?.contains("422") == true) {+                    Log.e(TAG, "Got 422 on PNI prekey upload, session invalid")+                    throw e+                }+                Log.w(TAG, "Key check failed, retrying in 5-30 minutes: ${e.message}")+                windowStartMinutes = 5+                windowSizeMinutes = 25+            } catch (e: Exception) {+                Log.w(TAG, "Key check failed, retrying in 5-30 minutes: ${e.message}")+                windowStartMinutes = 5+                windowSizeMinutes = 25+            }+        }+    }++    private suspend fun getPreKeyCount(ws: SignalWebSocket, identity: String): PreKeyCountResult {+        val response = ws.sendRequest("GET", keysPath(identity))+        if (response.status < 200 || response.status >= 300) {+            throw IOException("Fetching prekey counts failed: ${response.status}")+        }         val json = JSONObject(response.body.toStringUtf8())-        return minOf(json.optInt("count", 0), json.optInt("pqCount", 0))+        return PreKeyCountResult(json.optInt("count", 0), json.optInt("pqCount", 0))     }      private suspend fun uploadKeysForIdentity(@@ -82,17 +175,6 @@ object PreKeyManager {             }         } -        val spkId = random.nextInt(Int.MAX_VALUE)-        val spkKeyPair = ECKeyPair.generate()-        val spkSignature = identityKeyPair.privateKey.calculateSignature(spkKeyPair.publicKey.serialize())-        val spkRecord = SignedPreKeyRecord(spkId, System.currentTimeMillis(), spkKeyPair, spkSignature)-        preKeyStore.storeSignedPreKey(spkId, spkRecord)-        val signedPreKey = JSONObject().apply {-            put("keyId", spkId)-            put("publicKey", Base64.encodeToString(spkKeyPair.publicKey.serialize(), Base64.NO_WRAP))-            put("signature", Base64.encodeToString(spkSignature, Base64.NO_WRAP))-        }-         val pqPreKeys = JSONArray().apply {             for (i in 0 until BATCH_SIZE) {                 val kemKp = KEMKeyPair.generate(KEMKeyType.KYBER_1024)@@ -110,16 +192,14 @@ object PreKeyManager {          val payload = JSONObject().apply {             put("preKeys", preKeys)-            put("signedPreKey", signedPreKey)             put("pqPreKeys", pqPreKeys)             put("identityKey", Base64.encodeToString(identityKeyPair.publicKey.serialize(), Base64.NO_WRAP))         }          val response = ws.sendRequest(             method = "PUT",-            path = "/v2/keys?identity=$identity",+            path = keysPath(identity),             body = payload.toString().toByteArray(),-            headers = mapOf("Content-Type" to "application/json"),         )         if (response.status == 422 && identity == "pni") {             Log.e(TAG, "Got 422 on PNI prekey upload - account may be logged out")@@ -130,4 +210,84 @@ object PreKeyManager {         }         Log.d(TAG, "Uploaded $identity pre-keys")     }++    suspend fun fetchAndProcessPreKey(+        ws: SignalWebSocket,+        theirServiceId: String,+        specificDeviceId: Int = -1,+        sessionStore: com.vayunmathur.messages.signal.store.SignalSessionStore,+        identityKeyStore: com.vayunmathur.messages.signal.store.SignalIdentityKeyStore,+        preKeyStore: SignalPreKeyStore,+    ) {+        val deviceIdPath = if (specificDeviceId >= 0) "/$specificDeviceId" else "/*"+        val path = "/v2/keys/$theirServiceId$deviceIdPath?pq=true"+        val response = ws.sendRequest("GET", path)+        if (response.status == 404) {+            throw IOException("User $theirServiceId is unregistered (404)")+        }+        if (response.status !in 200..299) {+            throw IOException("Failed to fetch pre-keys for $theirServiceId: ${response.status}")+        }+        val json = JSONObject(response.body.toStringUtf8())+        val identityKeyBytes = addBase64PaddingAndDecode(json.getString("identityKey"))+        val identityKey = org.signal.libsignal.protocol.IdentityKey(identityKeyBytes)++        val devices = json.getJSONArray("devices")+        for (i in 0 until devices.length()) {+            val d = devices.getJSONObject(i)+            val deviceId = d.getInt("deviceId")+            val registrationId = d.getInt("registrationId")++            val signedPreKeyObj = d.getJSONObject("signedPreKey")+            val signedPreKeyId = signedPreKeyObj.getInt("keyId")+            val signedPublicKeyBytes = addBase64PaddingAndDecode(signedPreKeyObj.getString("publicKey"))+            val signedPublicKey = ECPublicKey(signedPublicKeyBytes)+            val signatureBytes = addBase64PaddingAndDecode(signedPreKeyObj.getString("signature"))++            var preKeyId = 0+            var preKeyPublic: ECPublicKey? = null+            if (d.has("preKey") && !d.isNull("preKey")) {+                val preKeyObj = d.getJSONObject("preKey")+                preKeyId = preKeyObj.getInt("keyId")+                preKeyPublic = ECPublicKey(addBase64PaddingAndDecode(preKeyObj.getString("publicKey")))+            }++            val pqPreKeyObj = d.optJSONObject("pqPreKey")+            val bundle = if (pqPreKeyObj != null) {+                try {+                    val kyberPreKeyId = pqPreKeyObj.getInt("keyId")+                    val kyberPreKeyPublic = org.signal.libsignal.protocol.kem.KEMPublicKey(+                        addBase64PaddingAndDecode(pqPreKeyObj.getString("publicKey"))+                    )+                    val kyberPreKeySignature = addBase64PaddingAndDecode(pqPreKeyObj.getString("signature"))+                    PreKeyBundle(+                        registrationId, deviceId,+                        preKeyId, preKeyPublic,+                        signedPreKeyId, signedPublicKey, signatureBytes,+                        identityKey,+                        kyberPreKeyId, kyberPreKeyPublic, kyberPreKeySignature,+                    )+                } catch (e: Exception) {+                    Log.w(TAG, "Failed to parse Kyber pre-key, falling back to non-PQ bundle", e)+                    PreKeyBundle(+                        registrationId, deviceId,+                        preKeyId, preKeyPublic,+                        signedPreKeyId, signedPublicKey, signatureBytes,+                        identityKey,+                    )+                }+            } else {+                PreKeyBundle(+                    registrationId, deviceId,+                    preKeyId, preKeyPublic,+                    signedPreKeyId, signedPublicKey, signatureBytes,+                    identityKey,+                )+            }+            val address = SignalProtocolAddress(theirServiceId, deviceId)+            val builder = SessionBuilder(sessionStore, preKeyStore, preKeyStore, identityKeyStore, address)+            builder.process(bundle)+        }+        Log.d(TAG, "Processed pre-key bundle for $theirServiceId")+    } }
messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt b/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.ktindex f1eaf10673..2760e74061 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/auth/Provisioning.kt@@ -43,7 +43,12 @@ object Provisioning {         data class Error(val message: String) : ProvisioningEvent     } -    fun startProvisioning(context: Context): Flow<ProvisioningEvent> = channelFlow {+    val signalCapabilities = JSONObject().apply {+        put("attachmentBackfill", true)+        put("spqr", true)+    }++    fun startProvisioning(context: Context, allowBackup: Boolean = true, deviceName: String = "Android"): Flow<ProvisioningEvent> = channelFlow {         try {             val cipher = ProvisioningCipher()             val ws = SignalWebSocket(context)@@ -54,11 +59,9 @@ object Provisioning {             ws.connectionEvents.first { it is SignalWebSocket.ConnectionEvent.Connected }              // Step 1: Receive provisioning UUID via PUT /v1/address-            var addressReq = requests.receive()-            while (addressReq.verb != "PUT" || addressReq.path != "/v1/address") {-                Log.d(TAG, "Skipping non-address request: ${addressReq.verb} ${addressReq.path} (${addressReq.body.size()} bytes)")-                ws.sendResponse(addressReq.id, 200)-                addressReq = requests.receive()+            val addressReq = requests.receive()+            if (addressReq.verb != "PUT" || addressReq.path != "/v1/address") {+                throw IOException("Expected PUT /v1/address, got ${addressReq.verb} ${addressReq.path}")             }             val provAddress = ProvisioningProtos.ProvisioningAddress.parseFrom(addressReq.body)             ws.sendResponse(addressReq.id, 200)@@ -66,16 +69,15 @@ object Provisioning {              // Step 2: Emit QR code URL             val pubKeyBase64 = Base64.encodeToString(cipher.getPublicKey().serialize(), Base64.NO_WRAP)-            val qrUrl = "sgnl://linkdevice?uuid=${Uri.encode(provAddress.address)}&pub_key=${Uri.encode(pubKeyBase64)}&capabilities=${Uri.encode("backup4,backup5")}"+            val capabilitiesPart = if (allowBackup) "&capabilities=${Uri.encode("backup4,backup5")}" else ""+            val qrUrl = "sgnl://linkdevice?uuid=${Uri.encode(provAddress.address)}&pub_key=${Uri.encode(pubKeyBase64)}$capabilitiesPart"             send(ProvisioningEvent.QrUrl(qrUrl))             Log.d(TAG, "QR URL generated")              // Step 3: Receive encrypted provisioning message via PUT /v1/message-            var msgReq = requests.receive()-            while (msgReq.verb != "PUT" || msgReq.path != "/v1/message") {-                Log.d(TAG, "Skipping non-message request: ${msgReq.verb} ${msgReq.path} (${msgReq.body.size()} bytes)")-                ws.sendResponse(msgReq.id, 200)-                msgReq = requests.receive()+            val msgReq = requests.receive()+            if (msgReq.verb != "PUT" || msgReq.path != "/v1/message") {+                throw IOException("Expected PUT /v1/message, got ${msgReq.verb} ${msgReq.path}")             }             Log.d(TAG, "Got provision envelope: ${msgReq.body.size()} bytes")             val envelope = ProvisioningProtos.ProvisionEnvelope.parseFrom(msgReq.body)@@ -127,7 +129,7 @@ object Provisioning {             preKeyStore.storeLastResortKyberPreKey(pniPqLastResort.id, pniPqLastResort)              // Step 8: Encrypt device name-            val encryptedName = encryptDeviceName("Android", aciIdentityKeyPair.publicKey.publicKey)+            val encryptedName = encryptDeviceName(deviceName, aciIdentityKeyPair.publicKey.publicKey)              // Step 9: Build and send device confirmation             val payload = JSONObject().apply {@@ -137,10 +139,7 @@ object Provisioning {                     put("name", encryptedName)                     put("registrationId", aciRegistrationId)                     put("pniRegistrationId", pniRegistrationId)-                    put("capabilities", JSONObject().apply {-                        put("attachmentBackfill", true)-                        put("spqr", true)-                    })+                    put("capabilities", signalCapabilities)                 })                 put("aciSignedPreKey", signedPreKeyToJson(aciSignedPreKey))                 put("pniSignedPreKey", signedPreKeyToJson(pniSignedPreKey))@@ -161,8 +160,9 @@ object Provisioning {              val respJson = JSONObject(response.body?.string() ?: throw IOException("Empty response"))             val aci = respJson.getString("uuid")-            val pni = respJson.getString("pni")-            val deviceId = respJson.optInt("deviceId", 1)+            val pni = respJson.optString("pni", "")+            val rawDeviceId = respJson.optInt("deviceId", 0)+            val deviceId = if (rawDeviceId != 0) rawDeviceId else 1              // Store identity keys             val identityKeyStore = com.vayunmathur.messages.signal.store.SignalIdentityKeyStore(@@ -171,26 +171,34 @@ object Provisioning {                 aciRegistrationId,             )             identityKeyStore.saveIdentity(-                SignalProtocolAddress(aci, 1),+                SignalProtocolAddress(aci, deviceId),                 aciIdentityKeyPair.publicKey,             )             identityKeyStore.saveIdentity(-                SignalProtocolAddress(pni, 1),+                SignalProtocolAddress(pni, deviceId),                 pniIdentityKeyPair.publicKey,             ) -            // Store own profile key as recipient-            if (provMsg.profileKey != null) {-                val recipientStore = com.vayunmathur.messages.signal.store.SignalRecipientStore(database)-                recipientStore.storeRecipient(com.vayunmathur.messages.signal.store.SignalRecipientEntity(-                    aci = aci,-                    profileKey = provMsg.profileKey.toByteArray(),-                ))-            }+            // Store own profile key as recipient (with PNI and E164, matching Go reference)+            val recipientStore = com.vayunmathur.messages.signal.store.SignalRecipientStore(database)+            recipientStore.storeRecipient(com.vayunmathur.messages.signal.store.SignalRecipientEntity(+                aci = aci,+                pni = pni,+                e164 = number,+                profileKey = provMsg.profileKey?.toByteArray(),+            ))              // Step 10: Build and emit device data             val accountEntropyPool = if (provMsg.hasAccountEntropyPool()) provMsg.accountEntropyPool else null +            // Extract backup keys from provisioning message (matches Go reference)+            val ephemeralBackupKey = if (provMsg.hasEphemeralBackupKey() && provMsg.ephemeralBackupKey.size() > 0)+                Base64.encodeToString(provMsg.ephemeralBackupKey.toByteArray(), Base64.NO_WRAP)+            else null+            val mediaRootBackupKey = if (provMsg.hasMediaRootBackupKey() && provMsg.mediaRootBackupKey.size() > 0)+                Base64.encodeToString(provMsg.mediaRootBackupKey.toByteArray(), Base64.NO_WRAP)+            else null+             // Derive master key from account entropy pool (matches Go reference)             val derivedMasterKey = if (accountEntropyPool != null) {                 try {@@ -214,9 +222,10 @@ object Provisioning {                 pniIdentityKeyPair = Base64.encodeToString(pniIdentityKeyPair.serialize(), Base64.NO_WRAP),                 aciRegistrationId = aciRegistrationId,                 pniRegistrationId = pniRegistrationId,-                profileKey = provMsg.profileKey?.let { Base64.encodeToString(it.toByteArray(), Base64.NO_WRAP) },                 accountEntropyPool = accountEntropyPool,                 masterKey = derivedMasterKey?.let { Base64.encodeToString(it, Base64.NO_WRAP) },+                ephemeralBackupKey = ephemeralBackupKey,+                mediaRootBackupKey = mediaRootBackupKey,             )             send(ProvisioningEvent.Success(deviceData))             Log.d(TAG, "Provisioning complete, deviceId=$deviceId")@@ -259,6 +268,17 @@ object Provisioning {         }     } +    suspend fun unlink(ws: SignalWebSocket, deviceId: Int) {+        val response = ws.sendRequest("DELETE", "/v1/devices/$deviceId")+        if (response.status < 200 || response.status >= 300) {+            throw IOException("Failed to unlink device: status=${response.status}")+        }+    }++    private val scope = kotlinx.coroutines.CoroutineScope(+        kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO+    )+     private fun encryptDeviceName(name: String, identityPublicKey: ECPublicKey): String {         val ephemeral = ECKeyPair.generate()         val masterSecret = ephemeral.privateKey.calculateAgreement(identityPublicKey)
messages/src/main/java/com/vayunmathur/messages/signal/auth/ProvisioningCipher.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/auth/ProvisioningCipher.kt b/messages/src/main/java/com/vayunmathur/messages/signal/auth/ProvisioningCipher.ktindex 95c554f8fd..6e71c7cc77 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/auth/ProvisioningCipher.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/auth/ProvisioningCipher.kt@@ -13,6 +13,17 @@ import javax.crypto.spec.SecretKeySpec class ProvisioningCipher {     private var keyPair: ECKeyPair? = null +    companion object {+        const val SUPPORTED_VERSION: Byte = 1+        const val CIPHER_KEY_SIZE = 32+        const val MAC_SIZE = 32+        const val VERSION_OFFSET = 0+        const val VERSION_LENGTH = 1+        const val IV_OFFSET = VERSION_OFFSET + VERSION_LENGTH+        const val IV_LENGTH = 16+        const val CIPHERTEXT_OFFSET = IV_OFFSET + IV_LENGTH+    }+     fun getPublicKey(): ECPublicKey {         if (keyPair == null) {             keyPair = ECKeyPair.generate()@@ -22,32 +33,49 @@ class ProvisioningCipher {      fun decrypt(envelope: ProvisionEnvelope): ProvisionMessage {         val kp = keyPair ?: throw IllegalStateException("Key pair not initialized")+        require(envelope.hasPublicKey() && envelope.publicKey.size() > 0) { "Envelope missing public key" }+        require(envelope.hasBody() && envelope.body.size() > 0) { "Envelope missing body" }         val masterEphemeral = ECPublicKey(envelope.publicKey.toByteArray())         val body = envelope.body.toByteArray()-        require(body[0].toInt() == 1) { "Unsupported ProvisionMessage version: ${body[0]}" }+        require(body[VERSION_OFFSET] == SUPPORTED_VERSION) { "Unsupported ProvisionMessage version: ${body[0]}" } -        val iv = body.copyOfRange(1, 17)-        val mac = body.copyOfRange(body.size - 32, body.size)-        val cipherText = body.copyOfRange(17, body.size - 32)-        val ivAndCipherText = body.copyOfRange(0, body.size - 32)+        val bodyLen = body.size+        val iv = body.copyOfRange(IV_OFFSET, IV_OFFSET + IV_LENGTH)+        val mac = body.copyOfRange(bodyLen - MAC_SIZE, bodyLen)+        require(iv.size == IV_LENGTH) { "Invalid IV size: ${iv.size}" }+        require(mac.size == MAC_SIZE) { "Invalid MAC size: ${mac.size}" }+        val cipherText = body.copyOfRange(CIPHERTEXT_OFFSET, bodyLen - CIPHER_KEY_SIZE)+        val ivAndCipherText = body.copyOfRange(0, bodyLen - CIPHER_KEY_SIZE)          val agreement = kp.privateKey.calculateAgreement(masterEphemeral)          val sharedSecrets = hkdfDeriveSecrets(agreement, "TextSecure Provisioning Message".toByteArray(), 64) -        val cipherKey = sharedSecrets.copyOfRange(0, 32)-        val macKey = sharedSecrets.copyOfRange(32, 64)+        val cipherKey = sharedSecrets.copyOfRange(0, CIPHER_KEY_SIZE)+        val macKey = sharedSecrets.copyOfRange(CIPHER_KEY_SIZE, 64)          val hmac = Mac.getInstance("HmacSHA256")         hmac.init(SecretKeySpec(macKey, "HmacSHA256"))         val ourMac = hmac.doFinal(ivAndCipherText)-        require(ourMac.copyOfRange(0, 32).contentEquals(mac)) { "Invalid MAC" }+        require(ourMac.size == mac.size) { "Invalid MAC length: ourMac=${ourMac.size} mac=${mac.size}" }+        require(java.security.MessageDigest.isEqual(ourMac.copyOfRange(0, MAC_SIZE), mac)) { "Invalid MAC" } -        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")+        val cipher = Cipher.getInstance("AES/CBC/NoPadding")         cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(cipherKey, "AES"), IvParameterSpec(iv))         val decrypted = cipher.doFinal(cipherText) -        return ProvisionMessage.parseFrom(decrypted)+        val unpadded = unpadPKCS7(decrypted)+        return ProvisionMessage.parseFrom(unpadded)+    }++    private fun unpadPKCS7(data: ByteArray): ByteArray {+        require(data.isNotEmpty()) { "data is empty" }+        val paddingLen = data.last().toInt() and 0xFF+        require(paddingLen in 1..data.size) { "invalid padding" }+        for (i in 0 until paddingLen) {+            require(data[data.size - 1 - i] == paddingLen.toByte()) { "invalid padding" }+        }+        return data.copyOfRange(0, data.size - paddingLen)     }      private fun hkdfDeriveSecrets(input: ByteArray, info: ByteArray, outputLength: Int): ByteArray {
messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactDiscovery.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactDiscovery.kt b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactDiscovery.ktindex 86a9b7edf4..cc44bd2ed9 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactDiscovery.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactDiscovery.kt@@ -25,20 +25,33 @@ import java.util.UUID import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit -/**- * Contact Discovery Service (CDSI) implementation matching Go signalmeow.- * Uses manual WebSocket + CDS2 handshake to support return_acis_without_uaks flag.- */+class ContactDiscoveryRateLimitError(val retryAfterSeconds: Long) : Exception(+    "contact discovery rate limited for ${retryAfterSeconds}s"+)++data class CDSResponseEntry(val aci: UUID, val pni: UUID)+ class ContactDiscovery(     private val recipientStore: SignalRecipientStore,-    private val selfAci: String,-    private val selfDeviceId: Int,-    private val selfPassword: String,+    private val ws: com.vayunmathur.messages.signal.web.SignalWebSocket,     private val context: android.content.Context, ) {     private var cachedCdsiUsername: String? = null     private var cachedCdsiPassword: String? = null     private var cdsiAuthExpiry: Long = 0L+    private var cdsiToken: ByteArray? = null++    suspend fun lookupPhones(vararg e164s: Long): Map<Long, CDSResponseEntry>? {+        if (e164s.isEmpty()) return null+        val requestData = ByteBuffer.allocate(e164s.size * 8)+        for (e164 in e164s) requestData.putLong(e164)+        val (cdsiUsername, cdsiPassword) = getCdsiAuth() ?: return null+        val (resp, token) = performCdsiLookup(requestData.array(), cdsiUsername, cdsiPassword)+            ?: return null+        if (token != null) cdsiToken = token+        return resp+    }+     suspend fun resolveE164(e164: String): String? {         val cached = recipientStore.getByE164(e164)         if (cached != null) {@@ -51,30 +64,30 @@ class ContactDiscovery(             Log.d(TAG, "Resolved $e164 from local store: $aci")             return aci         }-        return lookupViaCdsi(e164)?.let { result ->-            val aci = result.aci-            val pni = result.pni-            if (aci != null) {-                recipientStore.storeRecipient(-                    SignalRecipientEntity(aci = aci, e164 = e164, profileName = null)-                )-                Log.d(TAG, "CDSI resolved $e164 -> ACI $aci")-                aci-            } else if (pni != null) {-                val pniWithPrefix = "PNI:$pni"-                recipientStore.storeRecipient(-                    SignalRecipientEntity(aci = pniWithPrefix, e164 = e164, profileName = null)-                )-                Log.d(TAG, "CDSI resolved $e164 -> PNI $pni (no ACI)")-                pniWithPrefix-            } else {-                null-            }+        val e164Num = e164.removePrefix("+").toLong()+        val results = try {+            lookupPhones(e164Num)+        } catch (e: Exception) {+            Log.e(TAG, "CDSI lookup failed for $e164", e)+            null+        } ?: return null+        val entry = results[e164Num] ?: return null+        val nilUUID = UUID(0, 0)+        val aci = entry.aci.takeIf { it != nilUUID }?.toString()+        val pni = entry.pni.takeIf { it != nilUUID }?.toString()+        if (aci != null) {+            recipientStore.storeRecipient(SignalRecipientEntity(aci = aci, e164 = e164))+            Log.d(TAG, "CDSI resolved $e164 -> ACI $aci")+            return aci+        } else if (pni != null) {+            val pniWithPrefix = "PNI:$pni"+            recipientStore.storeRecipient(SignalRecipientEntity(aci = pniWithPrefix, e164 = e164))+            Log.d(TAG, "CDSI resolved $e164 -> PNI $pni (no ACI)")+            return pniWithPrefix         }+        return null     } -    private data class CdsResult(val aci: String?, val pni: String?)-     private suspend fun getCdsiAuth(): Pair<String, String>? {         val now = System.currentTimeMillis()         val username = cachedCdsiUsername@@ -82,17 +95,15 @@ class ContactDiscovery(         if (username != null && password != null && now < cdsiAuthExpiry) {             return username to password         }-        val authResponse = SignalHttpClient.request(-            method = "GET",-            path = "/v2/directory/auth",-            username = "$selfAci.$selfDeviceId",-            password = selfPassword,+        val authResponse = ws.sendRequest(+            "GET",+            "/v2/directory/auth",         )-        if (!authResponse.isSuccessful) {-            Log.e(TAG, "Directory auth failed: ${authResponse.code}")+        if (authResponse.status !in 200..299) {+            Log.e(TAG, "Directory auth failed: ${authResponse.status}")             return null         }-        val authJson = JSONObject(authResponse.body?.string() ?: return null)+        val authJson = JSONObject(authResponse.body.toStringUtf8())         val newUsername = authJson.getString("username")         val newPassword = authJson.getString("password")         cachedCdsiUsername = newUsername@@ -101,23 +112,12 @@ class ContactDiscovery(         return newUsername to newPassword     } -    private suspend fun lookupViaCdsi(e164: String): CdsResult? {-        return try {-            val (cdsiUsername, cdsiPassword) = getCdsiAuth() ?: return null-            Log.d(TAG, "Got CDSI auth credentials")-            performCdsiLookup(e164, cdsiUsername, cdsiPassword)-        } catch (e: Exception) {-            Log.e(TAG, "CDSI lookup failed for $e164", e)-            null-        }-    }-     private suspend fun performCdsiLookup(-        e164: String,+        newE164sData: ByteArray,         cdsiUsername: String,         cdsiPassword: String,-    ): CdsResult? {-        val url = "wss://cdsi.signal.org/v1/$MRENCLAVE/discovery"+    ): Pair<Map<Long, CDSResponseEntry>, ByteArray?>? {+        val url = "wss://$CDSI_HOST/v1/$MRENCLAVE/discovery"         val (sslSocketFactory, trustManager) = CertPinning.createSslSocketFactory(context)         val client = OkHttpClient.Builder()             .sslSocketFactory(sslSocketFactory, trustManager)@@ -140,6 +140,14 @@ class ContactDiscovery(             override fun onMessage(webSocket: WebSocket, bytes: ByteString) {                 messages.put(bytes.toByteArray())             }+            override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {+                if (code == RATE_LIMIT_CLOSE_CODE) {+                    val retryAfter = try {+                        JSONObject(reason).optLong("retry_after", 0)+                    } catch (_: Exception) { 0L }+                    connected.completeExceptionally(ContactDiscoveryRateLimitError(retryAfter))+                }+            }             override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {                 Log.e(TAG, "CDSI WebSocket failure", t)                 connected.completeExceptionally(t)@@ -159,58 +167,34 @@ class ContactDiscovery(                     ?: throw IllegalStateException("No handshake finish")                 cds2Client.completeHandshake(handshakeFinish) -                val e164Num = e164.removePrefix("+").toLong()-                val e164Bytes = ByteBuffer.allocate(8).putLong(e164Num).array()                 val cdsiRequest = CDSClientRequest.newBuilder()-                    .setNewE164S(com.google.protobuf.ByteString.copyFrom(e164Bytes))+                    .setNewE164S(com.google.protobuf.ByteString.copyFrom(newE164sData))                     .build()-                val encryptedRequest = cds2Client.establishedSend(cdsiRequest.toByteArray())-                socket.send(encryptedRequest.toByteString())--                val encryptedResponse = messages.poll(10, TimeUnit.SECONDS)-                    ?: throw IllegalStateException("No CDSI response")-                val decryptedResponse = cds2Client.establishedRecv(encryptedResponse)-                val cdsiResponse = CDSClientResponse.parseFrom(decryptedResponse)--                if (cdsiResponse.hasToken()) {-                    val tokenAck = CDSClientRequest.newBuilder().setTokenAck(true).build()-                    val encryptedAck = cds2Client.establishedSend(tokenAck.toByteArray())-                    socket.send(encryptedAck.toByteString())-                }--                var responseData = cdsiResponse-                if (responseData.hasToken() && responseData.e164PniAciTriples.isEmpty) {-                    val nextMsg = messages.poll(10, TimeUnit.SECONDS)-                    if (nextMsg != null) {-                        responseData = CDSClientResponse.parseFrom(cds2Client.establishedRecv(nextMsg))+                val encryptedReq = cds2Client.establishedSend(cdsiRequest.toByteArray())+                socket.send(encryptedReq.toByteString())++                // Response loop matching Go's ReadResponse+                var token: ByteArray? = null+                var response: Map<Long, CDSResponseEntry>? = null+                while (response == null) {+                    val msg = messages.poll(10, TimeUnit.SECONDS)+                        ?: throw IllegalStateException("No CDSI response")+                    val decrypted = cds2Client.establishedRecv(msg)+                    val cdsiResp = CDSClientResponse.parseFrom(decrypted)++                    if (cdsiResp.hasToken()) {+                        token = cdsiResp.token.toByteArray()+                        val tokenAck = CDSClientRequest.newBuilder()+                            .setTokenAck(true).build()+                        val encAck = cds2Client.establishedSend(tokenAck.toByteArray())+                        socket.send(encAck.toByteString())                     }-                } -                val triples = responseData.e164PniAciTriples.toByteArray()-                if (triples.size < 40 || triples.size % 40 != 0) return@withTimeout null--                var result: CdsResult? = null-                var offset = 0-                while (offset + 40 <= triples.size) {-                    val e164Chunk = ByteBuffer.wrap(triples, offset, 8).long-                    if (e164Chunk == 0L) { offset += 40; continue }-                    val pniBytes = triples.copyOfRange(offset + 8, offset + 24)-                    val aciBytes = triples.copyOfRange(offset + 24, offset + 40)-                    val pni = if (pniBytes.any { it != 0.toByte() }) {-                        val buf = ByteBuffer.wrap(pniBytes)-                        UUID(buf.long, buf.long).toString()-                    } else null-                    val aci = if (aciBytes.any { it != 0.toByte() }) {-                        val buf = ByteBuffer.wrap(aciBytes)-                        UUID(buf.long, buf.long).toString()-                    } else null-                    if (aci != null || pni != null) {-                        result = CdsResult(aci, pni)-                        break+                    if (!cdsiResp.e164PniAciTriples.isEmpty) {+                        response = parseTriples(cdsiResp.e164PniAciTriples.toByteArray())                     }-                    offset += 40                 }-                result+                Pair(response, token)             }         } finally {             socket?.close(3000, "Normal")@@ -218,9 +202,31 @@ class ContactDiscovery(         }     } +    private fun parseTriples(triples: ByteArray): Map<Long, CDSResponseEntry> {+        val tripleSize = 8 + 16 + 16+        val pairCount = triples.size / tripleSize+        if (pairCount * tripleSize != triples.size) {+            throw IllegalStateException("Invalid response size ${triples.size} (not divisible by $tripleSize)")+        }+        val result = mutableMapOf<Long, CDSResponseEntry>()+        for (i in 0 until pairCount) {+            val offset = i * tripleSize+            val e164 = ByteBuffer.wrap(triples, offset, 8).long+            if (e164 == 0L) continue+            val pniBuf = ByteBuffer.wrap(triples, offset + 8, 16)+            val pni = UUID(pniBuf.long, pniBuf.long)+            val aciBuf = ByteBuffer.wrap(triples, offset + 24, 16)+            val aci = UUID(aciBuf.long, aciBuf.long)+            result[e164] = CDSResponseEntry(aci = aci, pni = pni)+        }+        return result+    }+     companion object {         private const val TAG = "ContactDiscovery"+        private const val CDSI_HOST = "cdsi.signal.org"         private const val MRENCLAVE = "15637fa1e54fe655176d3df1a9f94b87c01ed377acaa570682dc5d72c95ef07b"-        private const val CDSI_AUTH_TTL_MS = 23 * 60 * 60 * 1000L // 23 hours, matching Go+        private const val CDSI_AUTH_TTL_MS = 23 * 60 * 60 * 1000L+        private const val RATE_LIMIT_CLOSE_CODE = 4008     } }
messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.ktindex e9022bd588..0b898321eb 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ContactManager.kt@@ -6,38 +6,96 @@ import com.vayunmathur.messages.signal.proto.SignalServiceProtos import com.vayunmathur.messages.signal.store.SignalRecipientEntity import com.vayunmathur.messages.signal.store.SignalRecipientStore import com.vayunmathur.messages.util.ContactSuggestion+import java.nio.ByteBuffer+import java.security.MessageDigest  class ContactManager(     private val recipientStore: SignalRecipientStore,+    private val profileManager: ProfileManager? = null, ) {-    suspend fun handleContactSync(contacts: List<SignalServiceProtos.ContactDetails>) {-        for (contact in contacts) {-            val entity = SignalRecipientEntity(-                aci = contact.aci,-                e164 = contact.number,-                profileName = contact.name,-            )-            recipientStore.storeRecipient(entity)+    suspend fun storeContactDetailsAsContact(+        contactDetails: SignalServiceProtos.ContactDetails,+        avatar: ByteArray? = null,+    ) {+        val aci = contactDetails.aci.takeIf { it.isNotBlank() } ?: return+        val existing = recipientStore.getRecipient(aci)+        val e164 = contactDetails.number.takeIf { it.isNotBlank() } ?: existing?.e164+        val contactName = contactDetails.name+        var avatarHash = existing?.contactAvatarHash+        if (avatar != null && avatar.isNotEmpty()) {+            val rawHash = MessageDigest.getInstance("SHA-256").digest(avatar)+            avatarHash = rawHash.joinToString("") { "%02x".format(it) }+        }+        recipientStore.storeRecipient(SignalRecipientEntity(+            aci = aci,+            e164 = e164,+            contactName = contactName,+            contactAvatarHash = avatarHash,+            profileKey = existing?.profileKey,+            profileName = existing?.profileName,+            profileAvatarPath = existing?.profileAvatarPath,+        ))+    }++    suspend fun handleContactSync(+        contacts: List<SignalServiceProtos.ContactDetails>,+        avatars: List<ByteArray?> = emptyList(),+    ) {+        for ((index, contact) in contacts.withIndex()) {+            val avatar = avatars.getOrNull(index)+            storeContactDetailsAsContact(contact, avatar)         }         Log.d(TAG, "Synced ${contacts.size} contacts")     } +    suspend fun contactByACI(aci: String): SignalRecipientEntity? {+        return contactByACIWithRefreshAfter(aci, ProfileManager.DEFAULT_PROFILE_REFRESH_AFTER_MS)+    }++    suspend fun contactByACIWithRefreshAfter(aci: String, refreshAfter: Long): SignalRecipientEntity? {+        val existing = recipientStore.getRecipient(aci)+        if (profileManager != null && existing != null) {+            val profile = profileManager.retrieveProfileByID(aci, existing.profileKey, refreshAfter)+            if (profile != null) {+                val updated = existing.copy(+                    profileName = profile.name ?: existing.profileName,+                    profileAbout = profile.about ?: existing.profileAbout,+                    profileAboutEmoji = profile.aboutEmoji ?: existing.profileAboutEmoji,+                    profileAvatarPath = profile.avatarPath ?: existing.profileAvatarPath,+                    profileFetchedAt = profile.fetchedAt,+                )+                recipientStore.storeRecipient(updated)+                return updated+            }+        }+        return existing+    }++    suspend fun contactByE164(e164: String): SignalRecipientEntity? {+        val contact = recipientStore.getByE164(e164) ?: return null+        if (contact.aci.isNotBlank()) {+            return contactByACI(contact.aci)+        }+        return contact+    }+     suspend fun getDisplayName(aci: String): String? {         val recipient = recipientStore.getRecipient(aci) ?: return null-        return recipient.profileName ?: recipient.e164+        return recipient.contactName ?: recipient.profileName ?: recipient.e164     }      suspend fun searchContacts(query: String): List<ContactSuggestion> {         val lowerQuery = query.lowercase()         val all = recipientStore.getAllRecipients()         return all.filter { recipient ->-            recipient.profileName?.lowercase()?.contains(lowerQuery) == true ||+            recipient.contactName?.lowercase()?.contains(lowerQuery) == true ||+                recipient.profileName?.lowercase()?.contains(lowerQuery) == true ||                 recipient.e164?.contains(lowerQuery) == true         }.map { recipient ->             ContactSuggestion(-                displayName = recipient.profileName ?: recipient.e164 ?: recipient.aci,+                displayName = recipient.contactName ?: recipient.profileName ?: recipient.e164 ?: recipient.aci,                 phoneE164 = recipient.e164,-                avatarUrl = recipient.profileAvatar,+                avatarUrl = recipient.profileAvatarPath,                 source = MessageSource.SIGNAL,             )         }@@ -45,5 +103,44 @@ class ContactManager(      companion object {         private const val TAG = "ContactManager"++        fun unmarshalContactDetailsMessages(+            byteStream: ByteArray,+        ): Pair<List<SignalServiceProtos.ContactDetails>, List<ByteArray?>> {+            val contactDetailsList = mutableListOf<SignalServiceProtos.ContactDetails>()+            val avatarList = mutableListOf<ByteArray?>()+            val buf = ByteBuffer.wrap(byteStream)+            while (buf.hasRemaining()) {+                val msgLen = readUvarint(buf) ?: break+                if (!buf.hasRemaining()) break+                val msgBytes = ByteArray(msgLen.toInt())+                buf.get(msgBytes)+                val contactDetails = SignalServiceProtos.ContactDetails.parseFrom(msgBytes)+                contactDetailsList.add(contactDetails)+                if (contactDetails.hasAvatar() && contactDetails.avatar.hasLength()+                    && contactDetails.avatar.length > 0+                ) {+                    val avatarBytes = ByteArray(contactDetails.avatar.length)+                    buf.get(avatarBytes)+                    avatarList.add(avatarBytes.copyOf())+                } else {+                    avatarList.add(null)+                }+            }+            return Pair(contactDetailsList, avatarList)+        }++        private fun readUvarint(buf: ByteBuffer): Long? {+            var result = 0L+            var shift = 0+            while (buf.hasRemaining()) {+                val b = buf.get().toLong() and 0xFF+                result = result or ((b and 0x7F) shl shift)+                if (b and 0x80 == 0L) return result+                shift += 7+                if (shift >= 64) return null+            }+            return null+        }     } }
messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.ktindex b6c49aac68..9a6ff96de6 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/ProfileManager.kt@@ -2,48 +2,149 @@ package com.vayunmathur.messages.signal.contacts  import android.util.Log import com.vayunmathur.messages.signal.store.SignalRecipientStore+import com.vayunmathur.messages.signal.web.SignalHttpClient import com.vayunmathur.messages.signal.web.SignalWebSocket import org.json.JSONObject+import java.util.concurrent.ConcurrentHashMap import javax.crypto.Cipher import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.SecretKeySpec +class ProfileUnauthorizedException : Exception("profile get returned 401")+class ProfileNotFoundException : Exception("profile get returned 404")+class ProfileInternalErrorException(status: Int) : Exception("profile get returned $status")+ class ProfileManager(     private val ws: SignalWebSocket,     private val recipientStore: SignalRecipientStore, ) {-    data class Profile(val name: String?, val about: String?, val avatarPath: String?)+    data class Profile(+        val name: String?,+        val about: String?,+        val aboutEmoji: String?,+        val avatarPath: String?,+        val credential: ByteArray? = null,+        val fetchedAt: Long = System.currentTimeMillis(),+    )++    private val profileCache = ConcurrentHashMap<String, Profile>()+    private val errorCache = ConcurrentHashMap<String, Exception>()+    private val lastFetched = ConcurrentHashMap<String, Long>() -    suspend fun fetchProfile(aci: String, profileKey: ByteArray?): Profile? {+    suspend fun retrieveProfileByID(+        aci: String,+        profileKey: ByteArray?,+        refreshAfter: Long = DEFAULT_PROFILE_REFRESH_AFTER_MS,+    ): Profile? {+        val fetchTime = lastFetched[aci]+        if (fetchTime != null && System.currentTimeMillis() - fetchTime < refreshAfter) {+            profileCache[aci]?.let { return it }+            errorCache[aci]?.let {+                Log.d(TAG, "Returning cached error for $aci: ${it.message}")+                return null+            }+        }+        val profile = fetchProfile(aci, profileKey)+        if (profile != null) {+            profileCache[aci] = profile+            errorCache.remove(aci)+            lastFetched[aci] = System.currentTimeMillis()+        }+        return profile+    }++    suspend fun fetchProfile(aci: String, profileKey: ByteArray?, credentialRequest: String? = null): Profile? {         return try {-            val response = ws.sendRequest("GET", "/v1/profile/$aci",-                headers = mapOf("Accept-Language" to "en-US"))-            if (response.status !in 200..299) return null+            val headers = mutableMapOf<String, String>()+            val profileKeyHex = profileKey?.let { pk ->+                try {+                    val profileKeyObj = org.signal.libsignal.zkgroup.profiles.ProfileKey(pk)+                    val version = profileKeyObj.getProfileKeyVersion(+                        org.signal.libsignal.protocol.ServiceId.Aci(java.util.UUID.fromString(aci))+                    )+                    val accessKey = profileKeyObj.deriveAccessKey()+                    headers["Unidentified-Access-Key"] = android.util.Base64.encodeToString(accessKey, android.util.Base64.NO_WRAP)+                    headers["Accept-Language"] = "en-US"+                    version.serialize().joinToString("") { "%02x".format(it) }+                } catch (e: Exception) {+                    Log.w(TAG, "Could not derive profile key version", e)+                    null+                }+            }++            var path = "/v1/profile/$aci"+            if (profileKeyHex != null) {+                path += "/$profileKeyHex"+            }+            if (credentialRequest != null) {+                path += "/$credentialRequest"+                path += "?credentialType=expiringProfileKey"+            }++            val response = ws.sendRequest("GET", path,+                headers = headers)++            val status = response.status+            if (status == 401) {+                cacheError(aci, ProfileUnauthorizedException())+                return null+            }+            if (status == 404) {+                cacheError(aci, ProfileNotFoundException())+                throw ProfileNotFoundException()+            }+            if (status in 500..599) {+                cacheError(aci, ProfileInternalErrorException(status))+                return null+            }+            if (status !in 200..299) {+                Log.e(TAG, "Unexpected status code $status fetching profile for $aci")+                return null+            }              val json = JSONObject(String(response.body.toByteArray()))             val encryptedName = json.optString("name", null)             val encryptedAbout = json.optString("about", null)-            val avatarPath = json.optString("avatar", null)+            val encryptedAboutEmoji = json.optString("aboutEmoji", null)+            val rawAvatar = json.optString("avatar", null)+            val credentialBase64 = json.optString("credential", null)+            val credential = credentialBase64?.takeIf { it.isNotEmpty() }?.let {+                android.util.Base64.decode(it, android.util.Base64.NO_WRAP)+            }              val name = if (encryptedName != null && profileKey != null) {-                decryptProfileField(android.util.Base64.decode(encryptedName, android.util.Base64.DEFAULT), profileKey)-            } else {-                null-            }+                decryptProfileString(profileKey,+                    android.util.Base64.decode(encryptedName, android.util.Base64.NO_WRAP)+                )?.replace('\u0000', ' ')+            } else null              val about = if (encryptedAbout != null && profileKey != null) {-                decryptProfileField(android.util.Base64.decode(encryptedAbout, android.util.Base64.DEFAULT), profileKey)-            } else {-                null-            }+                decryptProfileString(profileKey,+                    android.util.Base64.decode(encryptedAbout, android.util.Base64.NO_WRAP))+            } else null -            val profile = Profile(name = name, about = about, avatarPath = avatarPath)+            val aboutEmoji = if (encryptedAboutEmoji != null && profileKey != null) {+                decryptProfileString(profileKey,+                    android.util.Base64.decode(encryptedAboutEmoji, android.util.Base64.NO_WRAP))+            } else null -            if (name != null) {-                val existing = recipientStore.getRecipient(aci)-                if (existing != null) {-                    recipientStore.storeRecipient(existing.copy(profileName = name, profileAvatar = avatarPath))-                }+            val avatarPath = if (rawAvatar.isNullOrEmpty()) "clear" else rawAvatar+            val fetchedAt = System.currentTimeMillis()++            val profile = Profile(+                name = name, about = about, aboutEmoji = aboutEmoji,+                avatarPath = avatarPath, credential = credential, fetchedAt = fetchedAt,+            )++            val existing = recipientStore.getRecipient(aci)+            if (existing != null) {+                recipientStore.storeRecipient(existing.copy(+                    profileName = name ?: existing.profileName,+                    profileAbout = about ?: existing.profileAbout,+                    profileAboutEmoji = aboutEmoji ?: existing.profileAboutEmoji,+                    profileAvatarPath = avatarPath,+                    profileFetchedAt = fetchedAt,+                ))             }              profile@@ -53,24 +154,79 @@ class ProfileManager(         }     } -    private fun decryptProfileField(encryptedData: ByteArray, profileKey: ByteArray): String? {+    suspend fun downloadUserAvatar(+        avatarPath: String,+        profileKey: ByteArray,+        username: String? = null,+        password: String? = null,+    ): ByteArray? {         return try {-            if (encryptedData.size < 29) return null // NONCE(12) + TAG(16) + at least 1 byte-            val nonce = encryptedData.copyOfRange(0, 12)-            val ciphertext = encryptedData.copyOfRange(12, encryptedData.size)+            val resp = SignalHttpClient.request(+                host = SignalHttpClient.CDN1_HOST,+                method = "GET",+                path = avatarPath,+                username = username,+                password = password,+            )+            if (resp.code !in 200..299) {+                Log.e(TAG, "Unexpected response status ${resp.code} downloading avatar")+                return null+            }+            val encryptedAvatar = resp.body?.bytes() ?: return null+            decryptBytes(profileKey, encryptedAvatar)+        } catch (e: Exception) {+            Log.e(TAG, "Failed to download user avatar", e)+            null+        }+    }++    private fun cacheError(aci: String, err: Exception) {+        Log.e(TAG, err.message ?: "Profile error for $aci")+        errorCache[aci] = err+        lastFetched[aci] = System.currentTimeMillis()+    }++    private fun decryptBytes(profileKey: ByteArray, encryptedData: ByteArray): ByteArray? {+        return try {+            if (encryptedData.size < NONCE_LENGTH + TAG_LENGTH_BYTES + 1) return null+            val nonce = encryptedData.copyOfRange(0, NONCE_LENGTH)+            val ciphertext = encryptedData.copyOfRange(NONCE_LENGTH, encryptedData.size)             val cipher = Cipher.getInstance("AES/GCM/NoPadding")             val keySpec = SecretKeySpec(profileKey, "AES")-            val gcmSpec = GCMParameterSpec(128, nonce)+            val gcmSpec = GCMParameterSpec(TAG_LENGTH_BYTES * 8, nonce)             cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec)-            val decrypted = cipher.doFinal(ciphertext)-            String(decrypted).trimEnd('\u0000').replace('\u0000', ' ')+            cipher.doFinal(ciphertext)+        } catch (e: Exception) {+            Log.e(TAG, "Failed to decrypt", e)+            null+        }+    }++    private fun decryptProfileString(profileKey: ByteArray, encryptedData: ByteArray): String? {+        val data = decryptBytes(profileKey, encryptedData) ?: return null+        var end = data.size+        while (end > 0 && data[end - 1] == 0.toByte()) end--+        return String(data, 0, end)+    }++    fun encryptString(profileKey: ByteArray, plaintext: String, paddedLength: Int): ByteArray? {+        if (plaintext.length > paddedLength) return null+        val padded = plaintext.toByteArray() + ByteArray(paddedLength - plaintext.length)+        val nonce = ByteArray(NONCE_LENGTH).also { java.security.SecureRandom().nextBytes(it) }+        return try {+            val cipher = Cipher.getInstance("AES/GCM/NoPadding")+            cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(profileKey, "AES"), GCMParameterSpec(TAG_LENGTH_BYTES * 8, nonce))+            nonce + cipher.doFinal(padded)         } catch (e: Exception) {-            Log.e(TAG, "Failed to decrypt profile name", e)+            Log.e(TAG, "Failed to encrypt string", e)             null         }     }      companion object {         private const val TAG = "ProfileManager"+        private const val NONCE_LENGTH = 12+        private const val TAG_LENGTH_BYTES = 16+        const val DEFAULT_PROFILE_REFRESH_AFTER_MS = 60 * 60 * 1000L     } }
messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.ktindex bea7d4c37f..ddf1e780bf 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/contacts/StorageServiceManager.kt@@ -14,18 +14,38 @@ import com.vayunmathur.messages.signal.store.SignalGroupStore import com.vayunmathur.messages.signal.store.SignalRecipientEntity import com.vayunmathur.messages.signal.store.SignalRecipientStore import com.vayunmathur.messages.signal.web.SignalHttpClient+import java.io.ByteArrayOutputStream import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec  class StorageServiceManager(     private val recipientStore: SignalRecipientStore,     private val groupStore: SignalGroupStore,-    private val selfAci: String,-    private val password: String,+    private val ws: com.vayunmathur.messages.signal.web.SignalWebSocket, ) {     companion object {         private const val TAG = "StorageService"         private const val MAX_READ_STORAGE_RECORDS = 2500+        private const val STORAGE_AUTH_TTL_MS = 23L * 60 * 60 * 1000+        private const val STORAGE_SERVICE_ITEM_KEY_INFO_PREFIX = "20240801_SIGNAL_STORAGE_SERVICE_ITEM_"+        private const val STORAGE_SERVICE_ITEM_KEY_LEN = 32+    }++    private var storageAuth: Pair<String, String>? = null+    private var storageAuthTimestamp = 0L++    private suspend fun getStorageCredentials(): Pair<String, String> {+        val cached = storageAuth+        if (cached != null && System.currentTimeMillis() - storageAuthTimestamp < STORAGE_AUTH_TTL_MS) {+            return cached+        }+        val resp = ws.sendRequest("GET", "/v1/storage/auth")+        if (resp.status !in 200..299) throw java.io.IOException("Storage auth failed: ${resp.status}")+        val json = org.json.JSONObject(resp.body.toStringUtf8())+        val creds = Pair(json.getString("username"), json.getString("password"))+        storageAuth = creds+        storageAuthTimestamp = System.currentTimeMillis()+        return creds     }      suspend fun syncStorage(masterKey: ByteArray) {@@ -39,14 +59,20 @@ class StorageServiceManager(         }     } -    private suspend fun fetchManifest(storageKey: ByteArray): ManifestRecord? {+    private suspend fun fetchManifest(storageKey: ByteArray, greaterThanVersion: Long = 0): ManifestRecord? {+        val creds = getStorageCredentials()+        var path = "/v1/storage/manifest"+        if (greaterThanVersion > 0) {+            path += "/version/$greaterThanVersion"+        }         val resp = SignalHttpClient.request(             host = SignalHttpClient.STORAGE_HOST, method = "GET",-            path = "/v1/storage/manifest",-            username = selfAci, password = password,+            path = path,+            username = creds.first, password = creds.second,             contentType = "application/x-protobuf",         )-        if (resp.code == 204 || !resp.isSuccessful) return null+        if (resp.code == 204) return null+        if (resp.code != 200) throw java.io.IOException("Storage manifest fetch failed: ${resp.code}")         val body = resp.body?.bytes() ?: return null         val enc = StorageManifest.parseFrom(body)         val mKey = deriveManifestKey(storageKey, enc.version)@@ -58,24 +84,27 @@ class StorageServiceManager(         storageKey: ByteArray,         manifest: ManifestRecord,     ): List<StorageRecord> {+        val recordIkm = manifest.recordIkm?.takeIf { !it.isEmpty }?.toByteArray()         val allKeys = manifest.identifiersList.map { it.raw.toByteArray() }         val results = mutableListOf<StorageRecord>()         for (chunk in allKeys.chunked(MAX_READ_STORAGE_RECORDS)) {             val readOp = ReadOperation.newBuilder()             chunk.forEach { readOp.addReadKey(com.google.protobuf.ByteString.copyFrom(it)) }+            val creds = getStorageCredentials()             val resp = SignalHttpClient.request(                 host = SignalHttpClient.STORAGE_HOST, method = "PUT",                 path = "/v1/storage/read",                 body = readOp.build().toByteArray(),-                username = selfAci, password = password,+                username = creds.first, password = creds.second,                 contentType = "application/x-protobuf",             )-            if (!resp.isSuccessful) continue+            if (!resp.isSuccessful) throw java.io.IOException("Storage read failed: ${resp.code}")             val items = StorageItems.parseFrom(resp.body?.bytes() ?: continue)             items.itemsList.mapNotNull { item ->                 try {-                    val b64 = Base64.encodeToString(item.key.toByteArray(), Base64.NO_WRAP)-                    val iKey = deriveItemKey(storageKey, b64)+                    val rawKey = item.key.toByteArray()+                    val b64 = Base64.encodeToString(rawKey, Base64.NO_WRAP)+                    val iKey = deriveItemKey(storageKey, recordIkm, rawKey, b64)                     StorageRecord.parseFrom(decryptAESGCM(iKey, item.value.toByteArray()))                 } catch (e: Exception) { null }             }.let { results.addAll(it) }@@ -88,6 +117,7 @@ class StorageServiceManager(             try {                 if (r.hasContact()) processContact(r.contact)                 else if (r.hasGroupV2()) processGroup(r.groupV2)+                else if (r.hasAccount()) Log.d(TAG, "Found account record")             } catch (e: Exception) {                 Log.w(TAG, "Failed to process record", e)             }@@ -95,24 +125,50 @@ class StorageServiceManager(     }      private suspend fun processContact(c: ContactRecord) {-        val aci = c.aci.takeIf { it.isNotBlank() } ?: return-        val pni = if (c.hasPni() && c.pni.isNotBlank()) c.pni else null-        val name = listOf(c.givenName, c.familyName)-            .filter { it.isNotBlank() }.joinToString(" ")-            .ifBlank {-                listOf(c.systemGivenName, c.systemFamilyName)-                    .filter { it.isNotBlank() }.joinToString(" ")-            }-        val existing = recipientStore.getRecipient(aci)+        val aci = c.aci.takeIf { it.isNotBlank() }+        val pni = c.pni.takeIf { it.isNotBlank() }+        if (aci == null && pni == null) {+            Log.w(TAG, "Storage service has contact record with no ACI or PNI")+            return+        }+        val entityAci = aci ?: "PNI:$pni"+        val existing = recipientStore.getRecipient(entityAci)+         val pk = if (c.profileKey.size() == 32)             c.profileKey.toByteArray()         else existing?.profileKey++        // Profile name from given/family name - only set if currently empty (matching Go)+        val profileName = if (existing?.profileName.isNullOrBlank()) {+            listOf(c.givenName, c.familyName)+                .filter { it.isNotBlank() }.joinToString(" ")+                .takeIf { it.isNotBlank() }+        } else existing?.profileName++        // Contact name from system given/family name (always update when present)+        val contactName = listOf(c.systemGivenName, c.systemFamilyName)+            .filter { it.isNotBlank() }.joinToString(" ")+            .takeIf { it.isNotBlank() } ?: existing?.contactName++        // Nickname handling+        val nickname = if (c.hasNickname() && (c.nickname.given.isNotBlank() || c.nickname.family.isNotBlank())) {+            listOf(c.nickname.given, c.nickname.family)+                .filter { it.isNotBlank() }.joinToString(" ")+                .takeIf { it.isNotBlank() }+        } else {+            null+        }+         recipientStore.storeRecipient(SignalRecipientEntity(-            aci = aci,+            aci = entityAci,             pni = pni ?: existing?.pni,             e164 = c.e164.takeIf { it.isNotBlank() } ?: existing?.e164,-            profileName = name.takeIf { it.isNotBlank() } ?: existing?.profileName,+            contactName = contactName,+            nickname = nickname,+            profileName = profileName ?: existing?.profileName,             profileKey = pk,+            blocked = c.blocked,+            whitelisted = if (existing?.whitelisted == true) true else c.whitelisted,         ))     } @@ -134,13 +190,24 @@ class StorageServiceManager(         return mac.doFinal("Manifest_$version".toByteArray())     } -    private fun deriveItemKey(storageKey: ByteArray, b64ItemId: String): ByteArray {-        val mac = Mac.getInstance("HmacSHA256")-        mac.init(SecretKeySpec(storageKey, "HmacSHA256"))-        return mac.doFinal("Item_$b64ItemId".toByteArray())+    private fun deriveItemKey(+        storageKey: ByteArray,+        recordIkm: ByteArray?,+        rawItemId: ByteArray,+        b64ItemId: String,+    ): ByteArray {+        if (recordIkm == null) {+            val mac = Mac.getInstance("HmacSHA256")+            mac.init(SecretKeySpec(storageKey, "HmacSHA256"))+            return mac.doFinal("Item_$b64ItemId".toByteArray())+        } else {+            val info = STORAGE_SERVICE_ITEM_KEY_INFO_PREFIX.toByteArray() + rawItemId+            return hkdfSha256(recordIkm, ByteArray(0), info, STORAGE_SERVICE_ITEM_KEY_LEN)+        }     }      private fun decryptAESGCM(key: ByteArray, data: ByteArray): ByteArray {+        if (data.size < 12 + 16 + 1) throw IllegalArgumentException("Invalid encrypted data length")         val nonce = data.copyOfRange(0, 12)         val ciphertext = data.copyOfRange(12, data.size)         val cipher = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding")@@ -149,4 +216,23 @@ class StorageServiceManager(             javax.crypto.spec.GCMParameterSpec(128, nonce))         return cipher.doFinal(ciphertext)     }++    private fun hkdfSha256(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray {+        val effectiveSalt = if (salt.isEmpty()) ByteArray(32) else salt+        val mac = Mac.getInstance("HmacSHA256")+        mac.init(SecretKeySpec(effectiveSalt, "HmacSHA256"))+        val prk = mac.doFinal(ikm)+        val n = (length + 31) / 32+        var t = ByteArray(0)+        val okm = ByteArrayOutputStream()+        for (i in 1..n) {+            mac.init(SecretKeySpec(prk, "HmacSHA256"))+            mac.update(t)+            mac.update(info)+            mac.update(byteArrayOf(i.toByte()))+            t = mac.doFinal()+            okm.write(t)+        }+        return okm.toByteArray().copyOfRange(0, length)+    } }\ No newline at end of file
messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.ktindex 7c12b971d3..756a5b7ea2 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/groups/GroupManager.kt@@ -3,6 +3,7 @@ package com.vayunmathur.messages.signal.groups import android.util.Base64 import android.util.Log import com.vayunmathur.messages.signal.proto.Group+import com.vayunmathur.messages.signal.proto.GroupAttributeBlob import com.vayunmathur.messages.signal.store.SignalGroupEntity import com.vayunmathur.messages.signal.store.SignalGroupStore import com.vayunmathur.messages.signal.web.SignalHttpClient@@ -17,6 +18,7 @@ import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse import org.signal.libsignal.zkgroup.auth.ClientZkAuthOperations import org.signal.libsignal.zkgroup.groups.GroupMasterKey import org.signal.libsignal.zkgroup.groups.GroupSecretParams+import org.signal.libsignal.protocol.ServiceId  class GroupManager(     private val ws: SignalWebSocket,@@ -33,19 +35,151 @@ class GroupManager(         UNKNOWN(0), DEFAULT(1), ADMINISTRATOR(2)     } +    data class GroupMember(+        val aci: UUID,+        val role: MemberRole = MemberRole.UNKNOWN,+        val profileKey: ByteArray = ByteArray(0),+        val joinedAtRevision: Int = 0,+    )++    data class GroupAccessControl(+        val members: AccessControl,+        val addFromInviteLink: AccessControl,+        val attributes: AccessControl,+    )++    data class PendingMember(+        val serviceId: String,+        val role: MemberRole,+        val addedByUserId: UUID,+        val timestamp: Long,+    )++    data class RequestingMember(+        val aci: UUID,+        val profileKey: ByteArray,+        val timestamp: Long,+    )++    data class BannedMember(+        val serviceId: String,+        val timestamp: Long,+    )+     data class SignalGroup(         val groupId: String,         val title: String,-        val memberAcis: List<String>,-        val avatarUrl: String?,+        val members: List<GroupMember>,+        val avatarPath: String?,         val revision: Int,         val description: String? = null,-        val disappearingMessagesTimer: Int = 0,+        val disappearingMessagesDuration: Int = 0,         val announcementsOnly: Boolean = false,+        val accessControl: GroupAccessControl? = null,+        val pendingMembers: List<PendingMember> = emptyList(),+        val requestingMembers: List<RequestingMember> = emptyList(),+        val bannedMembers: List<BannedMember> = emptyList(),+        val inviteLinkPassword: String? = null,+    ) {+        val memberAcis: List<String> get() = members.map { it.aci.toString() }++        fun findMemberOrEmpty(aci: UUID): GroupMember {+            return members.find { it.aci == aci } ?: GroupMember(aci)+        }+    }++    data class GroupChange(+        var groupMasterKey: ByteArray,+        val sourceServiceId: String? = null,+        var revision: Int = 0,+        val addMembers: MutableList<GroupMember> = mutableListOf(),+        val deleteMembers: MutableList<UUID> = mutableListOf(),+        val modifyMemberRoles: MutableList<Pair<UUID, MemberRole>> = mutableListOf(),+        val modifyMemberProfileKeys: MutableList<Pair<UUID, ByteArray>> = mutableListOf(),+        val addPendingMembers: MutableList<PendingMember> = mutableListOf(),+        val deletePendingMembers: MutableList<String> = mutableListOf(),+        val promotePendingMembers: MutableList<Pair<UUID, ByteArray>> = mutableListOf(),+        var modifyTitle: String? = null,+        var modifyAvatar: String? = null,+        var modifyDisappearingMessagesDuration: Int? = null,+        var modifyAttributesAccess: AccessControl? = null,+        var modifyMemberAccess: AccessControl? = null,+        var modifyAddFromInviteLinkAccess: AccessControl? = null,+        val addRequestingMembers: MutableList<RequestingMember> = mutableListOf(),+        val deleteRequestingMembers: MutableList<UUID> = mutableListOf(),+        val promoteRequestingMembers: MutableList<Pair<UUID, MemberRole>> = mutableListOf(),+        var modifyDescription: String? = null,+        var modifyAnnouncementsOnly: Boolean? = null,+        val addBannedMembers: MutableList<BannedMember> = mutableListOf(),+        val deleteBannedMembers: MutableList<String> = mutableListOf(),+        val promotePendingPniAciMembers: MutableList<Triple<UUID, ByteArray, UUID>> = mutableListOf(),+        var modifyInviteLinkPassword: String? = null,+    ) {+        fun isEmpty(): Boolean {+            return addMembers.isEmpty() && deleteMembers.isEmpty() &&+                modifyMemberRoles.isEmpty() && modifyMemberProfileKeys.isEmpty() &&+                addPendingMembers.isEmpty() &&+                promotePendingMembers.isEmpty() && modifyTitle == null &&+                modifyAvatar == null && modifyDisappearingMessagesDuration == null &&+                modifyAttributesAccess == null && modifyMemberAccess == null &&+                modifyAddFromInviteLinkAccess == null && addRequestingMembers.isEmpty() &&+                deleteRequestingMembers.isEmpty() && promoteRequestingMembers.isEmpty() &&+                modifyDescription == null && modifyAnnouncementsOnly == null &&+                addBannedMembers.isEmpty()+        }++        fun resolveConflict(group: SignalGroup) {+            if (modifyTitle != null && modifyTitle == group.title) modifyTitle = null+            if (modifyDescription != null && modifyDescription == group.description) modifyDescription = null+            if (modifyAvatar != null && modifyAvatar == group.avatarPath) modifyAvatar = null+            if (modifyDisappearingMessagesDuration != null &&+                modifyDisappearingMessagesDuration == group.disappearingMessagesDuration+            ) modifyDisappearingMessagesDuration = null+            if (modifyAttributesAccess != null && modifyAttributesAccess == group.accessControl?.attributes) {+                modifyAttributesAccess = null+            }+            if (modifyMemberAccess != null && modifyMemberAccess == group.accessControl?.members) {+                modifyAttributesAccess = null+            }+            if (modifyAddFromInviteLinkAccess != null &&+                modifyAddFromInviteLinkAccess == group.accessControl?.addFromInviteLink+            ) modifyAddFromInviteLinkAccess = null+            if (modifyAnnouncementsOnly != null && modifyAnnouncementsOnly == group.announcementsOnly) {+                modifyAnnouncementsOnly = null+            }+            val memberMap = group.members.associate { it.aci to it.role }+            val pendingSet = group.pendingMembers.map { it.serviceId }.toSet()+            val requestingSet = group.requestingMembers.map { it.aci }.toSet()+            addMembers.removeAll { memberMap.containsKey(it.aci) }+            promotePendingMembers.removeAll { memberMap.containsKey(it.first) }+            promoteRequestingMembers.removeAll { memberMap.containsKey(it.first) }+            addPendingMembers.removeAll { pendingSet.contains(it.serviceId) }+            addRequestingMembers.removeAll { requestingSet.contains(it.aci) }+            deletePendingMembers.removeAll { !pendingSet.contains(it) }+            deleteRequestingMembers.removeAll { !requestingSet.contains(it) }+            deleteMembers.removeAll { !memberMap.containsKey(it) }+            modifyMemberRoles.removeAll { memberMap[it.first] == it.second }+        }+    }++    data class GroupChangeState(+        val groupState: SignalGroup?,+        val groupChange: GroupChange?,     )      private val cache = ConcurrentHashMap<String, SignalGroup>()     private val credentialCache = ConcurrentHashMap<Long, ByteArray>()+    private val activeCalls = ConcurrentHashMap<String, String>()++    fun updateActiveCall(groupId: String, callId: String): Boolean {+        val currentCallId = activeCalls[groupId]+        if (currentCallId != null && currentCallId == callId) {+            activeCalls.remove(groupId)+            return false+        }+        activeCalls[groupId] = callId+        return true+    }      suspend fun fetchGroup(groupId: String, masterKey: ByteArray): SignalGroup? {         return try {@@ -59,18 +193,38 @@ class GroupManager(                 username = auth.username,                 password = auth.password,             )-            if (response.code !in 200..299) return null+            if (response.code != 200) return null              val groupProto = Group.parseFrom(response.body?.bytes())+            val members = groupProto.membersList.map { member ->+                val bb = ByteBuffer.wrap(member.userId.toByteArray())+                GroupMember(+                    aci = UUID(bb.getLong(), bb.getLong()),+                    role = MemberRole.entries.find { it.value == member.role.number } ?: MemberRole.UNKNOWN,+                    profileKey = member.profileKey.toByteArray(),+                    joinedAtRevision = member.joinedAtVersion,+                )+            }             val group = SignalGroup(                 groupId = groupId,-                title = groupProto.title.toStringUtf8(),-                memberAcis = groupProto.membersList.map {-                    val bb = ByteBuffer.wrap(it.userId.toByteArray())-                    UUID(bb.getLong(), bb.getLong()).toString()-                },-                avatarUrl = groupProto.avatarUrl.ifEmpty { null },+                title = cleanupStringProperty(groupProto.title.toStringUtf8()),+                members = members,+                avatarPath = groupProto.avatarUrl.ifEmpty { null },                 revision = groupProto.version,+                description = runCatching {+                    cleanupStringProperty(groupProto.description.toStringUtf8())+                }.getOrNull(),+                announcementsOnly = groupProto.announcementsOnly,+                accessControl = groupProto.accessControl?.let {+                    GroupAccessControl(+                        members = AccessControl.entries.find { ac -> ac.value == it.members.number } ?: AccessControl.UNKNOWN,+                        addFromInviteLink = AccessControl.entries.find { ac -> ac.value == it.addFromInviteLink.number } ?: AccessControl.UNKNOWN,+                        attributes = AccessControl.entries.find { ac -> ac.value == it.attributes.number } ?: AccessControl.UNKNOWN,+                    )+                },+                inviteLinkPassword = groupProto.inviteLinkPassword?.let {+                    if (it.isEmpty) null else Base64.encodeToString(it.toByteArray(), Base64.NO_WRAP)+                },             )              cache[groupId] = group@@ -79,7 +233,7 @@ class GroupManager(                     groupId = groupId,                     masterKey = masterKey,                     title = group.title,-                    avatarUrl = group.avatarUrl,+                    avatarUrl = group.avatarPath,                     revision = group.revision,                 )             )@@ -90,6 +244,14 @@ class GroupManager(         }     } +    suspend fun retrieveGroupByID(groupId: String, masterKey: ByteArray, revision: Int = 0): SignalGroup? {+        val cached = cache[groupId]+        if (cached != null && cached.revision >= revision) {+            return cached+        }+        return fetchGroup(groupId, masterKey)+    }+     suspend fun getOrFetchGroup(groupId: String, masterKey: ByteArray): SignalGroup? {         cache[groupId]?.let { return it }         return fetchGroup(groupId, masterKey)@@ -97,6 +259,10 @@ class GroupManager(      fun getCachedGroup(groupId: String): SignalGroup? = cache[groupId] +    fun invalidateCachedGroup(groupId: String) {+        cache.remove(groupId)+    }+     fun deriveGroupId(masterKey: ByteArray): String {         val groupMasterKey = GroupMasterKey(masterKey)         val groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey)@@ -104,6 +270,42 @@ class GroupManager(         return Base64.encodeToString(groupId, Base64.NO_WRAP)     } +    suspend fun storeMasterKey(groupId: String, masterKey: ByteArray) {+        groupStore.storeGroup(+            SignalGroupEntity(+                groupId = groupId,+                masterKey = masterKey,+                title = "",+                avatarUrl = null,+                revision = 0,+            )+        )+    }++    suspend fun downloadGroupAvatar(avatarPath: String, masterKey: ByteArray): ByteArray? {+        return try {+            val response = SignalHttpClient.request(+                host = SignalHttpClient.CDN1_HOST,+                method = "GET",+                path = avatarPath,+            )+            if (response.code !in 200..299) return null+            val encryptedAvatar = response.body?.bytes() ?: return null+            decryptGroupAvatar(encryptedAvatar, masterKey)+        } catch (e: Exception) {+            Log.e(TAG, "Failed to download group avatar", e)+            null+        }+    }++    private fun decryptGroupAvatar(encryptedAvatar: ByteArray, masterKey: ByteArray): ByteArray {+        val groupMasterKey = GroupMasterKey(masterKey)+        val groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey)+        val decryptedBlob = groupSecretParams.decryptBlobWithPadding(encryptedAvatar)+        val blob = GroupAttributeBlob.parseFrom(decryptedBlob)+        return blob.avatar.toByteArray()+    }+     private data class GroupAuthResult(val username: String, val password: String)      private suspend fun getGroupAuth(masterKey: ByteArray): GroupAuthResult? {@@ -120,8 +322,8 @@ class GroupManager(              val authCredResponse = AuthCredentialWithPniResponse(credential)             val authCred = clientZkAuth.receiveAuthCredentialWithPniAsServiceId(-                java.util.UUID.fromString(aci),-                java.util.UUID.fromString(pni),+                ServiceId.Aci(java.util.UUID.fromString(aci)),+                ServiceId.Pni(java.util.UUID.fromString(pni)),                 todaySeconds,                 authCredResponse,             )@@ -147,9 +349,14 @@ class GroupManager(             val sevenDays = todaySeconds + 7 * 86400             val path = "/v1/certificate/auth/group?redemptionStartSeconds=$todaySeconds&redemptionEndSeconds=$sevenDays&pniAsServiceId=true"             val response = ws.sendRequest("GET", path)-            if (response.status !in 200..299) return null+            if (response.status != 200) return null -            val json = JSONObject(response.body)+            val json = JSONObject(response.body.toStringUtf8())+            val pniFromResponse = json.optString("pni", "")+            if (pniFromResponse.isNotEmpty() && pniFromResponse != pni) {+                Log.e(TAG, "Mismatching PNI in group credentials: $pniFromResponse != $pni")+                return null+            }             val credentials = json.getJSONArray("credentials")             for (i in 0 until credentials.length()) {                 val cred = credentials.getJSONObject(i)@@ -175,5 +382,19 @@ class GroupManager(         private fun hexEncode(bytes: ByteArray): String {             return bytes.joinToString("") { "%02x".format(it) }         }++        fun cleanupStringProperty(property: String): String {+            val cleaned = property.filter { ch ->+                val type = Character.getType(ch)+                type != Character.CONTROL.toInt() &&+                    type != Character.FORMAT.toInt() &&+                    type != Character.SURROGATE.toInt() &&+                    type != Character.UNASSIGNED.toInt() &&+                    type != Character.PRIVATE_USE.toInt() &&+                    type != Character.LINE_SEPARATOR.toInt() &&+                    type != Character.PARAGRAPH_SEPARATOR.toInt()+            }+            return cleaned.trim()+        }     } }
messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.ktindex 3566a22bf9..dba64fadab 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/groups/SenderKeyManager.kt@@ -52,4 +52,50 @@ class SenderKeyManager(         distributionCreatedAt.remove(groupId)         Log.d(TAG, "Reset sender key distribution for group $groupId")     }++    fun processDistributionMessage(+        groupId: String,+        senderAci: String,+        senderDeviceId: Int,+        distributionMessage: SenderKeyDistributionMessage,+    ) {+        try {+            val senderAddress = SignalProtocolAddress(senderAci, senderDeviceId)+            val builder = GroupSessionBuilder(senderKeyStore)+            builder.process(senderAddress, distributionMessage)+            Log.d(TAG, "Processed sender key distribution message from $senderAci for group $groupId")+        } catch (e: Exception) {+            Log.e(TAG, "Failed to process sender key distribution message", e)+        }+    }++    fun encryptForGroup(+        groupId: String,+        plaintext: ByteArray,+    ): ByteArray? {+        val distributionId = distributionIds[groupId] ?: return null+        val selfAddress = SignalProtocolAddress(selfAci, selfDeviceId)+        return try {+            val cipher = GroupCipher(senderKeyStore, selfAddress)+            cipher.encrypt(distributionId, plaintext)+        } catch (e: Exception) {+            Log.e(TAG, "Failed to encrypt for group $groupId", e)+            null+        }+    }++    fun decryptFromGroup(+        senderAci: String,+        senderDeviceId: Int,+        ciphertext: ByteArray,+    ): ByteArray? {+        val senderAddress = SignalProtocolAddress(senderAci, senderDeviceId)+        return try {+            val cipher = GroupCipher(senderKeyStore, senderAddress)+            cipher.decrypt(ciphertext)+        } catch (e: Exception) {+            Log.e(TAG, "Failed to decrypt from group", e)+            null+        }+    } }
messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.ktindex 6bc6268b1f..732ebc2230 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/media/AttachmentManager.kt@@ -14,8 +14,82 @@ import javax.crypto.spec.SecretKeySpec object AttachmentManager {      private const val TAG = "AttachmentManager"+    private const val MAC_LENGTH = 32+    private const val IV_LENGTH = 16++    class InvalidMACException : Exception("Invalid MAC for attachment")+    class InvalidDigestException(msg: String = "Invalid digest for attachment") : Exception(msg)+    class AttachmentNotFoundException : Exception("Attachment not found on server")++    suspend fun download(+        cdnId: Long,+        cdnKey: String,+        cdnNumber: Int,+        key: ByteArray,+        digest: ByteArray?,+        plaintextDigest: Boolean = false,+        size: Int,+    ): ByteArray? {+        return try {+            val path = if (cdnId != 0L) "/attachments/$cdnId" else "/attachments/$cdnKey"+            val host = SignalHttpClient.cdnHost(cdnNumber)+            val response = SignalHttpClient.request(+                host = host,+                method = "GET",+                path = path,+            )+            if (response.code == 404) throw AttachmentNotFoundException()+            if (response.code !in 200..299) return null+            val body = response.body?.bytes() ?: return null++            if (digest != null && !plaintextDigest) {+                val hash = MessageDigest.getInstance("SHA-256").digest(body)+                if (!MessageDigest.isEqual(hash, digest)) {+                    throw InvalidDigestException()+                }+            }++            val decrypted = macAndAESDecrypt(body, key)+            if (decrypted.size < size) {+                throw Exception("Decrypted attachment length ${decrypted.size} < expected $size")+            }+            val result = decrypted.copyOfRange(0, size)+            if (digest != null && plaintextDigest) {+                val hash = MessageDigest.getInstance("SHA-256").digest(result)+                if (!MessageDigest.isEqual(hash, digest)) {+                    throw InvalidDigestException("Invalid digest for attachment (plaintext hash)")+                }+            }+            result+        } catch (e: Exception) {+            Log.e(TAG, "Failed to download attachment", e)+            null+        }+    }++    suspend fun downloadWithPointer(+        pointer: SignalServiceProtos.AttachmentPointer,+        plaintextHash: ByteArray? = null,+    ): ByteArray? {+        var digest = if (pointer.hasDigest()) pointer.digest.toByteArray() else null+        var isPlaintextDigest = false+        if (digest == null && plaintextHash != null) {+            digest = plaintextHash+            isPlaintextDigest = true+        }+        return download(+            cdnId = pointer.cdnId,+            cdnKey = pointer.cdnKey,+            cdnNumber = pointer.cdnNumber,+            key = pointer.key.toByteArray(),+            digest = digest,+            plaintextDigest = isPlaintextDigest,+            size = pointer.size,+        )+    }      suspend fun upload(+        ws: com.vayunmathur.messages.signal.web.SignalWebSocket,         data: ByteArray,         contentType: String,         fileName: String?,@@ -33,25 +107,23 @@ object AttachmentManager {             val encrypted = encryptAttachment(paddedData, aesKey, macKey, iv)             val digest = MessageDigest.getInstance("SHA-256").digest(encrypted) -            val formResponse = SignalHttpClient.request(-                method = "GET",-                path = "/v4/attachments/form/upload",+            val formResponse = ws.sendRequest(+                "GET",+                "/v4/attachments/form/upload",             )-            if (!formResponse.isSuccessful) return null+            if (formResponse.status !in 200..299) return null -            val formJson = JSONObject(formResponse.body!!.string())+            val formJson = JSONObject(formResponse.body.toStringUtf8())             val uploadUrl = formJson.getString("signedUploadLocation")-            val cdnNumber = formJson.optInt("cdn", 2)+            val cdnNumber = formJson.optInt("cdn", 0)             val cdnKey = formJson.optString("key", "")+            val headers = formJson.optJSONObject("headers") -            val uploadResponse = SignalHttpClient.request(-                host = uploadUrl.substringAfter("://").substringBefore("/"),-                method = "PUT",-                path = "/" + uploadUrl.substringAfter("://").substringAfter("/"),-                body = encrypted,-                contentType = contentType,-            )-            if (!uploadResponse.isSuccessful) return null+            if (cdnNumber == 3) {+                uploadAttachmentTUS(uploadUrl, cdnKey, encrypted, headers)+            } else {+                uploadAttachmentLegacy(uploadUrl, encrypted, contentType, headers)+            }              SignalServiceProtos.AttachmentPointer.newBuilder()                 .setCdnKey(cdnKey)@@ -84,10 +156,86 @@ object AttachmentManager {         return iv + ciphertext + hmac     } +    fun macAndAESDecrypt(body: ByteArray, key: ByteArray): ByteArray {+        val l = body.size - MAC_LENGTH+        val macKey = key.copyOfRange(MAC_LENGTH, key.size)+        val aesKey = key.copyOfRange(0, MAC_LENGTH)++        val mac = Mac.getInstance("HmacSHA256")+        mac.init(SecretKeySpec(macKey, "HmacSHA256"))+        mac.update(body, 0, l)+        val computedMac = mac.doFinal()+        val expectedMac = body.copyOfRange(l, body.size)+        if (!MessageDigest.isEqual(computedMac, expectedMac)) {+            throw InvalidMACException()+        }++        val iv = body.copyOfRange(0, IV_LENGTH)+        val ciphertext = body.copyOfRange(IV_LENGTH, l)+        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")+        cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(aesKey, "AES"), IvParameterSpec(iv))+        return cipher.doFinal(ciphertext)+    }++    private suspend fun uploadAttachmentLegacy(+        uploadUrl: String,+        encrypted: ByteArray,+        contentType: String,+        headers: JSONObject?,+    ) {+        val headerMap = mutableMapOf<String, String>()+        headers?.keys()?.forEach { k -> headerMap[k] = headers.getString(k) }+        val allocResponse = SignalHttpClient.request(+            method = "POST",+            path = "",+            overrideUrl = uploadUrl,+            contentType = "application/octet-stream",+            headers = headerMap,+        )+        if (!allocResponse.isSuccessful) throw Exception("Allocate request returned ${allocResponse.code}")+        val location = allocResponse.header("Location") ?: throw Exception("No Location header in allocate response")++        val uploadResponse = SignalHttpClient.request(+            method = "PUT",+            path = "",+            overrideUrl = location,+            body = encrypted,+            contentType = "application/octet-stream",+        )+        if (!uploadResponse.isSuccessful) throw Exception("Upload request returned ${uploadResponse.code}")+    }++    private suspend fun uploadAttachmentTUS(+        uploadUrl: String,+        key: String,+        encrypted: ByteArray,+        headers: JSONObject?,+    ) {+        val tusHeaders = mutableMapOf<String, String>()+        headers?.keys()?.forEach { k -> tusHeaders[k] = headers.getString(k) }+        tusHeaders["Tus-Resumable"] = "1.0.0"+        tusHeaders["Upload-Length"] = encrypted.size.toString()+        tusHeaders["Upload-Metadata"] = "filename " + android.util.Base64.encodeToString(key.toByteArray(), android.util.Base64.NO_WRAP)++        val uploadResponse = SignalHttpClient.request(+            method = "POST",+            path = "",+            overrideUrl = uploadUrl,+            body = encrypted,+            contentType = "application/offset+octet-stream",+            headers = tusHeaders,+        )+        if (!uploadResponse.isSuccessful) throw Exception("TUS upload request returned ${uploadResponse.code}")+    }+     private fun padAttachmentSize(size: Int): Int {         if (size <= 541) return 541         val logSize = Math.log(size.toDouble()) / Math.log(1.05)         val rounded = Math.ceil(logSize)-        return Math.floor(Math.pow(1.05, rounded)).toInt().coerceAtLeast(size)+        val padded = Math.floor(Math.pow(1.05, rounded)).toInt()+        if (padded < size) {+            throw IllegalStateException("Math error: padded length $padded is less than body length $size")+        }+        return padded     } }
messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.kt b/messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.ktindex 626bc34c30..25f9545b2f 100644--- a/messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.kt+++ b/messages/src/main/java/com/vayunmathur/messages/signal/media/BackupManager.kt@@ -20,45 +20,60 @@ class BackupManager(     companion object {         private const val TAG = "BackupManager"         private const val BACKUP_VERSION = 1+        private const val TRANSFER_ARCHIVE_FETCH_TIMEOUT_MS = 60L * 60 * 1000 // 1 hour+        private const val REQUEST_TIMEOUT_SECONDS = 300L // 5 minutes+        const val TRANSFER_ERROR_RELINK_REQUESTED = "RELINK_REQUESTED"+        const val TRANSFER_ERROR_CONTINUE_WITHOUT_UPLOAD = "CONTINUE_WITHOUT_UPLOAD"     }      data class TransferArchiveMetadata(         val cdn: Int,         val key: String,-        val error: String?,+        val error: String = "",     )      suspend fun waitForTransfer(         ephemeralBackupKey: ByteArray?,     ): TransferArchiveMetadata? {         if (ephemeralBackupKey == null) {-            Log.w(TAG, "No ephemeral backup key")-            return null+            throw IllegalStateException("No ephemeral backup key")         }-        return try {-            val resp = ws.sendRequest(-                "GET",-                "/v1/devices/transfer_archive?timeout=300",-                null,-            )-            when (resp.status) {-                204 -> null-                200 -> {-                    val json = JSONObject(resp.body.toStringUtf8())-                    TransferArchiveMetadata(-                        cdn = json.optInt("cdn", 0),-                        key = json.optString("key", ""),-                        error = json.optString("error", null),-                    )-                }-                else -> {-                    Log.w(TAG, "Transfer archive request failed: ${resp.status}")-                    null-                }+        val deadline = System.currentTimeMillis() + TRANSFER_ARCHIVE_FETCH_TIMEOUT_MS+        while (true) {+            val remainingMs = deadline - System.currentTimeMillis()+            if (remainingMs <= 0) {+                throw Exception("Timed out waiting for transfer archive")             }-        } catch (e: Exception) {-            Log.e(TAG, "Failed to wait for transfer", e)-            null+            val reqTimeoutSeconds = minOf(remainingMs / 1000, REQUEST_TIMEOUT_SECONDS)+            val reqStart = S

Diff truncated.