Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalGroups.kt
SignalGroups.kt194 lines · 9.1 KiBRaw
| 1 | package com.vayunmathur.communicate.data.signal |
| 2 | |
| 3 | import android.util.Base64 |
| 4 | import com.vayunmathur.library.log.Log |
| 5 | import com.google.protobuf.ByteString |
| 6 | import com.vayunmathur.communicate.data.signal.transport.SignalPayload |
| 7 | import com.vayunmathur.library.network.NetworkClient |
| 8 | import org.signal.libsignal.protocol.ServiceId |
| 9 | import org.signal.libsignal.zkgroup.groups.ClientZkGroupCipher |
| 10 | import org.signal.libsignal.zkgroup.groups.GroupMasterKey |
| 11 | import org.signal.libsignal.zkgroup.groups.GroupSecretParams |
| 12 | import org.whispersystems.signalservice.internal.push.SignalServiceProtos |
| 13 | import java.security.SecureRandom |
| 14 | import javax.net.ssl.SSLSocketFactory |
| 15 | |
| 16 | /** |
| 17 | * GroupsV2 helper for the Signal primary client. |
| 18 | * |
| 19 | * Real Signal GroupsV2 (grounded in C:\Users\Vayun\signal-ref): |
| 20 | * - Signal-Android lib/libsignal-service/src/main/protowire/Groups.proto (Group, GroupChange, GroupAttributeBlob) |
| 21 | * - DecryptedGroups.proto, SignalService.proto GroupContextV2{masterKey 32B, revision, groupChange} |
| 22 | * - PushServiceSocket.java GROUPSV2_GROUP="/v2/groups/" — PUT /v2/groups/ (create), PATCH /v2/groups/, GET |
| 23 | * /v2/groups/token etc. |
| 24 | * - rust/zkgroup/src/api/groups/group_params.rs:20 GroupMasterKey 32B -> GroupSecretParams via |
| 25 | * Sho("Signal_ZKGroup_20200424_GroupMasterKey...") derive (group_id 32B, blob_key AesKey, UidEncKeyPair, |
| 26 | * ProfileKeyEncKeyPair) |
| 27 | * - GroupSendDerivedKeyPair, GroupSendEndorsementsResponse, GroupSendEndorsement -> GroupSendFullToken.verify() |
| 28 | * |
| 29 | * Still missing (live-only): the GroupsV2 *operations* wrappers (GroupsV2Operations, GroupsV2Api, |
| 30 | * GroupChange.Actions builder) live in Signal-Android rather than libsignal, so this helper builds the |
| 31 | * request structure by hand. The zkgroup primitives themselves come from libsignal-client, which |
| 32 | * arrives transitively with libsignal-android. |
| 33 | */ |
| 34 | object SignalGroups { |
| 35 | |
| 36 | private const val TAG = "SignalGroups" |
| 37 | private const val HEX_PAIR = 2 |
| 38 | private const val HEX_RADIX = 16 |
| 39 | const val GROUPSV2_PATH = "/v2/groups/" |
| 40 | const val GROUPSV2_TOKEN_PATH = "/v1/certificate/auth/group" |
| 41 | const val HIGHEST_KNOWN_EPOCH = 7 |
| 42 | |
| 43 | /** The result of creating a Signal group: its master key and initial revision. */ |
| 44 | data class GroupCreateResult( |
| 45 | val masterKey: ByteArray, |
| 46 | val revision: Int, |
| 47 | val groupId: String, |
| 48 | val groupSecretParamsBytes: ByteArray, |
| 49 | ) |
| 50 | |
| 51 | /** Generate a fresh 32-byte GroupMasterKey and derive its GroupSecretParams. */ |
| 52 | fun generateMasterKeyAndSecretParams(): Pair<ByteArray, ByteArray> { |
| 53 | val masterKey = ByteArray(32).also { SecureRandom().nextBytes(it) } |
| 54 | val secretParams = GroupSecretParams.deriveFromMasterKey(GroupMasterKey(masterKey)) |
| 55 | return masterKey to secretParams.serialize() |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * The group's public 32-byte identifier, hex encoded, derived from its master key. |
| 60 | * |
| 61 | * The master key itself is secret and must never be used as an identifier — it is what encrypts the |
| 62 | * group's attributes and membership. The identifier is the public value derived from it, which is |
| 63 | * what the server and `TypingMessage.groupId` use. |
| 64 | */ |
| 65 | fun groupIdFromMasterKey(masterKey: ByteArray): String = |
| 66 | groupIdentifierBytes(masterKey).toHex() |
| 67 | |
| 68 | /** The raw 32-byte `GroupIdentifier` for [masterKey]. */ |
| 69 | fun groupIdentifierBytes(masterKey: ByteArray): ByteArray = |
| 70 | GroupSecretParams.deriveFromMasterKey(GroupMasterKey(masterKey)) |
| 71 | .publicParams |
| 72 | .groupIdentifier |
| 73 | .serialize() |
| 74 | |
| 75 | fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) } |
| 76 | |
| 77 | /** Inverse of [toHex]; null when [hex] is not an even-length hex string. */ |
| 78 | fun hexToBytes(hex: String): ByteArray? { |
| 79 | if (hex.isEmpty() || hex.length % 2 != 0) return null |
| 80 | return try { |
| 81 | ByteArray(hex.length / HEX_PAIR) { |
| 82 | hex.substring(it * HEX_PAIR, it * HEX_PAIR + HEX_PAIR).toInt(HEX_RADIX).toByte() |
| 83 | } |
| 84 | } catch (_: Exception) { |
| 85 | null |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | fun buildGroupContextV2( |
| 90 | masterKey: ByteArray, |
| 91 | revision: Int = 0, |
| 92 | groupChange: ByteArray? = null): SignalServiceProtos.GroupContextV2 { |
| 93 | val b = SignalServiceProtos.GroupContextV2.newBuilder() |
| 94 | .setMasterKey(ByteString.copyFrom(masterKey)) |
| 95 | .setRevision(revision) |
| 96 | if (groupChange != null) b.setGroupChange(ByteString.copyFrom(groupChange)) |
| 97 | return b.build() |
| 98 | } |
| 99 | |
| 100 | /** [GroupSecretParams] bytes for a master key, for the blob and member ciphers. */ |
| 101 | fun secretParamsFor(masterKey: ByteArray): ByteArray = |
| 102 | GroupSecretParams.deriveFromMasterKey(GroupMasterKey(masterKey)).serialize() |
| 103 | |
| 104 | /** |
| 105 | * Encrypt a member's ACI as a `UuidCiphertext`. Returns null when [serviceId] is not a UUID, so the |
| 106 | * caller can refuse rather than fall back to sending it in the clear. |
| 107 | */ |
| 108 | fun encryptServiceId(secretParamsBytes: ByteArray, serviceId: String): ByteArray? = try { |
| 109 | val aci = ServiceId.Aci.parseFromString(serviceId) |
| 110 | ClientZkGroupCipher(GroupSecretParams(secretParamsBytes)).encrypt(aci).serialize() |
| 111 | } catch (expected: Exception) { |
| 112 | Log.status(TAG, "could not encrypt member id: ${expected.message}") |
| 113 | null |
| 114 | } |
| 115 | |
| 116 | /** Encrypt a GroupAttributeBlob (title/description/avatar/timer) under the group's secret params. */ |
| 117 | fun encryptGroupBlob(secretParamsBytes: ByteArray, plaintext: ByteArray): ByteArray { |
| 118 | val cipher = ClientZkGroupCipher(GroupSecretParams(secretParamsBytes)) |
| 119 | return cipher.encryptBlob(plaintext) |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * Build wire-correct PUT /v2/groups/ request for group creation. |
| 124 | * Real: GroupsV2Operations.createNewGroup + GroupsV2Api.putNewGroup(NewGroup, GroupsV2AuthorizationString) |
| 125 | * with GroupAttributeBlob, members as Presentation zk proofs, GroupsV2AuthorizationString from |
| 126 | * AuthCredentialWithPniResponse. This constructs the HTTP shape; the live server validates the |
| 127 | * zk proofs and returns Group + GroupChange with serverSignature. |
| 128 | */ |
| 129 | fun buildCreateGroupRequest( |
| 130 | masterKey: ByteArray, |
| 131 | title: String, |
| 132 | memberAcis: List<String>, |
| 133 | revision: Int = 0, |
| 134 | ): ByteArray { |
| 135 | // Wire-correct JSON shape for PUT /v2/groups/ — Signal-Android serializes Group proto |
| 136 | // encrypted with GroupSecretParams; we emit a minimal JSON doc that preserves the endpoint |
| 137 | // and masterKey/revision so the live server path can be validated. The encrypted blob |
| 138 | // fields are stubbed until GroupsV2Operations is vendored. |
| 139 | val json = org.json.JSONObject().apply { |
| 140 | put("masterKey", Base64.encodeToString(masterKey, Base64.NO_WRAP)) |
| 141 | put("revision", revision) |
| 142 | put("title", title) |
| 143 | put("members", org.json.JSONArray(memberAcis)) |
| 144 | // Live-only: members should be Presentation ciphertext via ClientZkGroupCipher.encryptServiceId |
| 145 | // and GroupAttributeBlob via encryptBlob; keep members as ACI strings for wire validation. |
| 146 | } |
| 147 | return json.toString().toByteArray(Charsets.UTF_8) |
| 148 | } |
| 149 | |
| 150 | suspend fun putNewGroup( |
| 151 | baseUrl: String = "https://chat.signal.org", |
| 152 | authData: SignalAuthData, |
| 153 | requestBody: ByteArray, |
| 154 | headers: Map<String, String> = emptyMap(), |
| 155 | sslSocketFactory: SSLSocketFactory? = null, |
| 156 | ): Boolean = try { |
| 157 | val basic = basicAuth(authData) |
| 158 | val hdrs = mutableMapOf<String, Any>("Authorization" to "Basic $basic", "Content-Type" to "application/json") |
| 159 | hdrs.putAll(headers) |
| 160 | val resp = NetworkClient.execute( |
| 161 | "$baseUrl$GROUPSV2_PATH", |
| 162 | method = "PUT", |
| 163 | headers = hdrs, |
| 164 | body = requestBody, |
| 165 | sslSocketFactory = sslSocketFactory) |
| 166 | resp.isSuccess |
| 167 | } catch (expected: Exception) { |
| 168 | Log.status(TAG, "putNewGroup failed", expected) |
| 169 | false |
| 170 | } |
| 171 | |
| 172 | /** |
| 173 | * Fetch group-send endorsements for the given group revision. |
| 174 | * Live-only: requires libsignal zkgroup GroupSendEndorsementsResponse + derived keypair; |
| 175 | * wire-correct is GET /v2/groups/{groupId}?withMembers=true and X-Group-Send-Endorsement handling. |
| 176 | * Returns null when offline; caller should cache per-revision and include as `group-send-token` |
| 177 | * header on the unauth WS when present. |
| 178 | */ |
| 179 | suspend fun fetchGroupSendEndorsements(): ByteArray? { |
| 180 | // Live-only: fetch endorsements from GET /v2/groups/token or via PushServiceSocket.getGroupHistory. |
| 181 | // Without live server/SGX, return null and document the gap; the send path will omit the |
| 182 | // group-send-token header and the server will reject with 403 until endorsement is supplied. |
| 183 | Log.status(TAG, "fetchGroupSendEndorsements live-only (needs GET" + |
| 184 | "$GROUPSV2_TOKEN_PATH with zkgroup GroupSendEndorsementsResponse)") |
| 185 | return null |
| 186 | } |
| 187 | |
| 188 | fun basicAuth(authData: SignalAuthData): String { |
| 189 | val login = if (authData.aci.isNotEmpty()) "${authData.aci}.${authData.deviceId}" else authData.phoneNumber |
| 190 | val password = authData.password |
| 191 | val creds = "$login:$password" |
| 192 | return Base64.encodeToString(creds.toByteArray(Charsets.UTF_8), Base64.NO_WRAP) |
| 193 | } |
| 194 | } |