Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalContactSync.kt

SignalContactSync.kt202 lines · 8.7 KiBRaw
1package com.vayunmathur.communicate.data.signal
2
3import androidx.core.content.edit
4import android.Manifest
5import android.content.Context
6import android.content.pm.PackageManager
7import android.provider.ContactsContract
8import android.telephony.TelephonyManager
9import android.util.Base64 as AndroidBase64
10import com.vayunmathur.library.log.Log
11import com.google.i18n.phonenumbers.PhoneNumberUtil
12import com.vayunmathur.communicate.data.ContactPlatformRows
13import com.vayunmathur.communicate.data.signal.transport.SignalCdsi
14import com.vayunmathur.communicate.data.signal.transport.SignalTrust
15import com.vayunmathur.library.network.NetworkClient
16import org.json.JSONArray
17import org.json.JSONObject
18import java.nio.ByteBuffer
19
20/**
21 * Device address-book → Signal contact sync via CDSI.
22 *
23 * This is what makes a phone number usable as a message destination: Signal addresses by ACI, and
24 * modern envelopes carry no E164, so an address-book number is unaddressable until discovery maps it.
25 *
26 * The enclave interaction — SGX remote attestation and the Noise handshake — is delegated to libsignal
27 * through [SignalCdsi]; the enclave will not answer without it.
28 */
29object SignalContactSync {
30 private const val TAG = "SignalContactSync"
31 private const val LONG_BYTES = 8
32
33 /** The outcome of a Signal contact sync: how many numbers were checked and discovered. */
34 data class SyncResult(
35 val deviceCount: Int,
36 val e164Count: Int,
37 val onSignalCount: Int,
38 val transportError: String? = null,
39 )
40
41 fun normalizeE164(raw: String, region: String): String? = runCatching {
42 val util = PhoneNumberUtil.getInstance()
43 val parsed = util.parse(raw, region)
44 if (!util.isValidNumber(parsed)) return null
45 util.format(parsed, PhoneNumberUtil.PhoneNumberFormat.E164)
46 }.getOrNull()
47
48 fun defaultRegion(context: Context): String = runCatching {
49 val tm = context.getSystemService(TelephonyManager::class.java)
50 (tm?.simCountryIso?.takeIf { it.isNotBlank() } ?: tm?.networkCountryIso)?.uppercase()
51 }.getOrNull()?.takeIf { it.isNotBlank() }
52 ?: context.resources.configuration.locales[0].country.ifEmpty { "US" }
53
54 fun readDeviceContacts(context: Context): List<Pair<String, String>> {
55 if (context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
56 return emptyList()
57 }
58 val projection = arrayOf(
59 ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
60 ContactsContract.CommonDataKinds.Phone.NUMBER,
61 )
62 return runCatching {
63 context.contentResolver.query(
64 ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null,
65 )?.use { cursor ->
66 buildList {
67 val nameIdx =
68 cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY)
69 val numIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)
70 while (cursor.moveToNext()) {
71 val number = cursor.getString(numIdx).orEmpty().trim()
72 if (number.isEmpty()) continue
73 add(cursor.getString(nameIdx).orEmpty() to number)
74 }
75 }
76 }.orEmpty()
77 }.getOrDefault(emptyList())
78 }
79
80 /** Encode E.164 string as 8-byte BE uint64 (digits only, no '+'). Matches cds2.proto new_e164s encoding. */
81 fun e164ToUint64Bytes(e164: String): ByteArray {
82 val digits = e164.filter { it.isDigit() }
83 val num = digits.toLongOrNull() ?: 0L
84 return ByteBuffer.allocate(LONG_BYTES).putLong(num).array()
85 }
86
87 fun uint64ToE164(value: Long): String = "+$value"
88
89 /** Parse stored CDSI token continuation if present; persisted as base64 opaque bytes. */
90 private fun loadCdsiToken(context: Context): ByteArray? = try {
91 val prefs = context.getSharedPreferences("communicate_signal_cdsi", Context.MODE_PRIVATE)
92 val b64 = prefs.getString("cdsi_token", null) ?: return null
93 AndroidBase64.decode(b64, AndroidBase64.NO_WRAP)
94 } catch (_: Exception) { null }
95
96 private fun saveCdsiToken(context: Context, token: ByteArray?) {
97 try {
98 val prefs = context.getSharedPreferences("communicate_signal_cdsi", Context.MODE_PRIVATE)
99 if (token == null || token.isEmpty()) {
100 prefs.edit { remove("cdsi_token") }
101 } else {
102 prefs.edit { putString("cdsi_token", AndroidBase64.encodeToString(token, AndroidBase64.NO_WRAP)) }
103 }
104 } catch (_: Exception) {}
105 }
106
107 /** CDSI lookup bundle with the partition it was built from. */
108 private data class CdsiLookup(
109 val result: SignalCdsi.LookupResult,
110 val previous: Set<String>,
111 val new: Set<String>,
112 )
113
114 /** Fetch credentials + run the CDSI lookup; null on failure. */
115 private suspend fun fetchLookup(
116 context: Context,
117 byE164: Map<String, String>,
118 ): CdsiLookup? {
119 val db = SignalDatabase.getDatabase(context)
120 val auth = SignalAuthData.load(context) ?: return null
121
122 val credentials = SignalCdsi.fetchCredentials(
123 authHeader = SignalGroups.basicAuth(auth),
124 sslSocketFactory = SignalTrust.sslSocketFactory(context),
125 ) ?: return null
126
127 // Numbers we have already asked about pair with the stored token for a cheaper incremental
128 // lookup; anything else is new. A stale token is handled inside lookup().
129 val known = try {
130 db.contactDao().getAll().mapNotNull { it.phoneE164.takeIf { p -> p.isNotEmpty() } }.toSet()
131 } catch (_: Exception) {
132 emptySet()
133 }
134 val previous = byE164.keys.intersect(known)
135 val new = byE164.keys - previous
136
137 val result = SignalCdsi.lookup(
138 credentials = credentials,
139 previousE164s = previous,
140 newE164s = new,
141 token = loadCdsiToken(context),
142 ) ?: return null
143
144 saveCdsiToken(context, result.token)
145 return CdsiLookup(result, previous, new)
146 }
147
148 suspend fun sync(context: Context): SyncResult {
149 if (!SignalFeature.enabled) return SyncResult(0, 0, 0, "disabled")
150 val region = defaultRegion(context)
151 val device = readDeviceContacts(context)
152 val byE164 = LinkedHashMap<String, String>()
153 for ((name, number) in device) {
154 val e164 = normalizeE164(number, region) ?: continue
155 byE164.putIfAbsent(e164, name)
156 }
157 if (byE164.isEmpty()) return SyncResult(device.size, 0, 0)
158
159 val lookup = fetchLookup(context, byE164)
160 ?: return SyncResult(device.size, byE164.size, 0, "CDSI lookup failed")
161 val now = System.currentTimeMillis()
162 val db = SignalDatabase.getDatabase(context)
163 val discoveredByE164 = lookup.result.discovered.associateBy { entry -> entry.e164 }
164 var onSignal = 0
165 val toUpsert = byE164.map { (e164, name) ->
166 val hit = discoveredByE164[e164]
167 // Registered means discovery returned an identity at all. The ACI is usually absent — CDSI
168 // only returns one when we already hold the contact's profile key — so the PNI is what makes
169 // a contact addressable.
170 val registered = hit != null && (hit.aci != null || hit.pni != null)
171 if (registered) onSignal++
172 SignalContact(
173 aci = hit?.aci ?: e164,
174 phoneE164 = e164,
175 displayName = name,
176 onSignal = registered,
177 updatedAt = now,
178 pni = hit?.pni ?: "",
179 )
180 }
181 db.contactDao().upsertAll(toUpsert)
182 Log.status(
183 TAG,
184 "CDSI sync: device=${device.size} e164=${byE164.size} previous=${lookup.previous.size} " +
185 "new=${lookup.new.size} registered=$onSignal " +
186 "withAci=${lookup.result.discovered.count { it.aci != null }}",
187 )
188 // Publish reachability into the contacts provider, so the contacts app can offer "message on Signal"
189 // for these numbers using the vendor's own mimetypes.
190 try {
191 ContactPlatformRows.publish(
192 context,
193 toUpsert.filter { it.onSignal }.map {
194 ContactPlatformRows.Reachability(e164 = it.phoneE164, whatsApp = false, signal = true)
195 },
196 )
197 } catch (expected: Throwable) {
198 Log.status(TAG, "could not publish Signal reachability to contacts", expected)
199 }
200 return SyncResult(device.size, byE164.size, onSignal)
201 }
202}