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

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

SignalIdentity.kt203 lines · 8.4 KiBRaw
1package com.vayunmathur.communicate.data.signal
2
3import com.vayunmathur.library.log.Log
4import com.vayunmathur.communicate.data.signal.e2e.acceptIdentity
5import com.vayunmathur.communicate.data.signal.e2e.storedIdentityKey
6import kotlinx.coroutines.Dispatchers
7import kotlinx.coroutines.launch
8import kotlinx.coroutines.withContext
9import org.signal.libsignal.protocol.IdentityKey
10import org.whispersystems.signalservice.internal.push.SignalServiceProtos
11
12/**
13 * SignalClient identity + contact resolution (split from SignalClient.kt for file length).
14 *
15 * Extension functions on [SignalClient]; behavior identical, call sites unchanged.
16 */
17
18/** A profile key can arrive on any DataMessage, including the one wrapped inside an edit. */
19fun SignalClient.profileKeyFrom(parsed: SignalProtocol.ParsedContent): ByteArray? {
20 val dm = when (parsed) {
21 is SignalProtocol.ParsedContent.Data -> parsed.dataMessage
22 is SignalProtocol.ParsedContent.Edit ->
23 if (parsed.editMessage.hasDataMessage()) parsed.editMessage.dataMessage else null
24 else -> null
25 } ?: return null
26 return if (dm.hasProfileKey()) dm.profileKey.toByteArray() else null
27}
28
29/**
30 * A peer's identity key changed. Reported rather than absorbed: this is either a reinstall or a key
31 * substitution, and only the user comparing safety numbers can tell the difference.
32 */
33fun SignalClient.reportIdentityChange(peerAci: String, newIdentityKey: ByteArray) {
34 val hex = SignalGroups.run { newIdentityKey.toHex() }
35 pendingIdentityChanges[peerAci] = newIdentityKey
36 Log.status(TAG, "identity key changed for $peerAci")
37 scope.launch {
38 eventsMutable.emit(
39 SignalEvent.IdentityKeyChanged(
40 conversationId = SignalProtocol.toConversationId(peerAci, null as ByteArray?),
41 peerAci = peerAci,
42 newIdentityKeyHex = hex,
43 timestamp = System.currentTimeMillis(),
44 ),
45 )
46 }
47}
48
49/** The unaccepted identity key a peer is presenting, if any. */
50fun SignalClient.pendingIdentityChange(peerAci: String): ByteArray? = pendingIdentityChanges[peerAci]
51
52/**
53 * The safety number to show for [peerAci] — for the key they are currently presenting when that
54 * differs from the one on record, otherwise for the accepted one. Null when it cannot be computed.
55 */
56suspend fun SignalClient.safetyNumber(peerAci: String): String? = withContext(Dispatchers.IO) {
57 // protocolStore hits Room via runBlocking inside, so self-guard on IO:
58 // callers may invoke this from any dispatcher (incl. Main-adjacent scopes).
59 val e = e2e ?: return@withContext null
60 val localAci = authData?.aci?.takeIf { it.isNotEmpty() } ?: return@withContext null
61 val remoteKey = pendingIdentityChanges[peerAci] ?: e.storedIdentityKey(peerAci) ?: return@withContext null
62 SignalSafetyNumber.compute(
63 localAci = localAci,
64 localIdentityKey = e.ownIdentityPublicKeySerialized,
65 remoteAci = peerAci,
66 remoteIdentityKey = remoteKey,
67 )
68}
69
70/**
71 * Accept the identity key [peerAci] is presenting, after the user has compared safety numbers.
72 *
73 * [expectedKeyHex] must match the key currently pending, so accepting can only ever apply to the key
74 * whose safety number was actually shown — otherwise a key swapped in between display and tap would
75 * be trusted instead. Existing sessions are archived so the next send builds against the new key.
76 */
77suspend fun SignalClient.acceptIdentityChange(peerAci: String, expectedKeyHex: String): Boolean =
78 withContext(Dispatchers.IO) {
79 // protocolStore hits Room via runBlocking inside, so self-guard on IO
80 // (see safetyNumber); double-shifting an already-IO caller is harmless.
81 val e = e2e ?: return@withContext false
82 val pending = pendingIdentityChanges[peerAci] ?: run {
83 Log.status(TAG, "no pending identity change for $peerAci")
84 return@withContext false
85 }
86 if (!SignalGroups.run { pending.toHex() }.equals(expectedKeyHex, ignoreCase = true)) {
87 Log.status(TAG, "refusing to accept a different key than the one shown for $peerAci")
88 return@withContext false
89 }
90 val accepted = e.acceptIdentity(peerAci, pending)
91 if (accepted) {
92 pendingIdentityChanges.remove(peerAci)
93 Log.status(TAG, "accepted the new identity key for $peerAci")
94 }
95 accepted
96 }
97
98/**
99 * Associate a sender's ACI with the PNI we already knew them by, when they prove the link.
100 *
101 * `PniSignatureMessage` carries their PNI plus a signature *by* the PNI identity key *of* the ACI
102 * identity key, so the two can be merged without trusting the server. Until they are merged, a reply
103 * arrives under the ACI while everything we sent went to the PNI — which shows up as a second
104 * conversation with a UUID for a name.
105 */
106internal suspend fun SignalClient.linkPniToAci(
107 senderAci: String,
108 pniSignature: SignalServiceProtos.PniSignatureMessage,
109) {
110 val e = e2e ?: return
111 val database = db ?: return
112 val pniRaw = try {
113 SignalProtocol.bytesToUuidString(pniSignature.pni.toByteArray())
114 } catch (_: Exception) {
115 null
116 }
117 if (pniRaw.isNullOrEmpty()) return
118 val pniServiceId = "$PNI_PREFIX$pniRaw"
119
120 val aciIdentity = e.storedIdentityKey(senderAci)
121 val pniIdentity = e.storedIdentityKey(pniServiceId)
122 if (aciIdentity == null || pniIdentity == null) {
123 Log.status(TAG, "cannot verify the PNI signature for $senderAci: missing an identity key")
124 return
125 }
126 if (!verifyPniSignature(senderAci, pniServiceId, aciIdentity, pniIdentity, pniSignature)) return
127 mergePniContact(database, senderAci, pniServiceId, pniRaw)
128}
129
130/** Merge the PNI contact row into the ACI after verification. */
131private suspend fun SignalClient.mergePniContact(
132 database: SignalDatabase,
133 senderAci: String,
134 pniServiceId: String,
135 pniRaw: String,
136) {
137 val contact = try {
138 database.contactDao().getByPni(pniServiceId) ?: database.contactDao().getByPni(pniRaw)
139 } catch (_: Exception) {
140 null
141 }
142 if (contact == null) {
143 Log.status(TAG, "verified PNI signature from $senderAci but no contact holds $pniServiceId")
144 return
145 }
146 if (contact.aci == senderAci) return
147 try {
148 // The row is keyed by aci, so replace it rather than update in place.
149 database.contactDao().deleteByPhone(contact.phoneE164)
150 database.contactDao().upsert(contact.copy(aci = senderAci))
151 Log.status(TAG, "associated $senderAci with ${contact.phoneE164} via a verified PNI signature")
152 } catch (expected: Throwable) {
153 Log.status(TAG, "could not associate $senderAci with ${contact.phoneE164}", expected)
154 }
155}
156
157/** Verify a PNI alternate-identity signature, logging failures. */
158private suspend fun SignalClient.verifyPniSignature(
159 senderAci: String,
160 pniServiceId: String,
161 aciIdentity: ByteArray,
162 pniIdentity: ByteArray,
163 pniSignature: SignalServiceProtos.PniSignatureMessage,
164): Boolean {
165 val verified = try {
166 IdentityKey(pniIdentity).verifyAlternateIdentity(
167 IdentityKey(aciIdentity),
168 pniSignature.signature.toByteArray(),
169 )
170 } catch (expected: Throwable) {
171 Log.status(TAG, "PNI signature verification failed for $senderAci", expected)
172 false
173 }
174 if (!verified) {
175 Log.status(TAG, "invalid PNI signature from $senderAci; not associating it with $pniServiceId")
176 return false
177 }
178 return true
179}
180
181/** The contact behind a service id, matched on ACI or PNI. */
182private suspend fun SignalClient.contactFor(serviceId: String): SignalContact? = try {
183 db?.contactDao()?.let { dao ->
184 dao.get(serviceId) ?: dao.getByPni(serviceId) ?: dao.getByPni(serviceId.removePrefix(PNI_PREFIX))
185 }
186} catch (_: Exception) {
187 null
188}
189
190/** A human name for a sender, falling back through phone number to the raw id. */
191suspend fun SignalClient.displayNameFor(serviceId: String): String {
192 val contact = contactFor(serviceId) ?: return serviceId
193 return contact.displayName.takeIf { it.isNotBlank() }
194 ?: contact.phoneE164.takeIf { it.isNotBlank() }
195 ?: serviceId
196}
197
198/**
199 * The conversation a sender belongs to. Anchored on the contact's phone number when we know it, so a
200 * reply from an ACI lands in the same thread as everything we sent to their PNI.
201 */
202suspend fun SignalClient.conversationIdFor(serviceId: String): String =
203 contactFor(serviceId)?.phoneE164?.takeIf { it.isNotBlank() } ?: serviceId