@skycodee/baileys 8.0.4 → 8.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/WAProto.proto +352 -520
  3. package/WAProto/index.js +558 -4154
  4. package/lib/Defaults/index.js +123 -0
  5. package/lib/Defaults/index.js.bak +123 -0
  6. package/lib/KeyDB/BinarySearch.js +20 -0
  7. package/lib/KeyDB/KeyedDB.js +167 -0
  8. package/lib/KeyDB/index.js +4 -0
  9. package/lib/Signal/Group/ciphertext-message.js +13 -0
  10. package/lib/Signal/Group/group-session-builder.js +32 -0
  11. package/lib/Signal/Group/group_cipher.js +84 -0
  12. package/lib/Signal/Group/index.js +13 -0
  13. package/lib/Signal/Group/keyhelper.js +20 -0
  14. package/lib/Signal/Group/sender-chain-key.js +28 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-message.js +68 -0
  17. package/lib/Signal/Group/sender-key-name.js +52 -0
  18. package/lib/Signal/Group/sender-key-record.js +43 -0
  19. package/lib/Signal/Group/sender-key-state.js +86 -0
  20. package/lib/Signal/Group/sender-message-key.js +28 -0
  21. package/lib/Signal/libsignal.js +324 -0
  22. package/lib/Signal/lid-mapping.js +155 -0
  23. package/lib/Socket/Client/index.js +4 -0
  24. package/lib/Socket/Client/types.js +13 -0
  25. package/lib/Socket/Client/websocket.js +52 -0
  26. package/lib/Socket/Client/websocket.js.bak +53 -0
  27. package/lib/Socket/business.js +377 -0
  28. package/lib/Socket/chats.js +885 -0
  29. package/lib/Socket/communities.js +413 -0
  30. package/lib/Socket/groups.js +312 -0
  31. package/lib/Socket/index.js +16 -0
  32. package/lib/Socket/messages-recv.js +1163 -0
  33. package/lib/Socket/messages-send.js +1100 -0
  34. package/lib/Socket/mex.js +45 -0
  35. package/lib/Socket/newsletter.js +247 -0
  36. package/lib/Socket/socket.js +820 -0
  37. package/lib/Store/index.js +6 -0
  38. package/lib/Store/make-cache-manager-store.js +75 -0
  39. package/lib/Store/make-in-memory-store.js +290 -0
  40. package/lib/Store/make-ordered-dictionary.js +79 -0
  41. package/lib/Store/object-repository.js +25 -0
  42. package/lib/Types/Auth.js +3 -0
  43. package/lib/Types/Bussines.js +3 -0
  44. package/lib/Types/Call.js +3 -0
  45. package/lib/Types/Chat.js +9 -0
  46. package/lib/Types/Contact.js +3 -0
  47. package/lib/Types/Events.js +3 -0
  48. package/lib/Types/GroupMetadata.js +3 -0
  49. package/lib/Types/Label.js +25 -0
  50. package/lib/Types/LabelAssociation.js +7 -0
  51. package/lib/Types/Message.js +12 -0
  52. package/lib/Types/Newsletter.js +33 -0
  53. package/lib/Types/Newsletter.js.bak +33 -0
  54. package/lib/Types/Product.js +3 -0
  55. package/lib/Types/Signal.js +3 -0
  56. package/lib/Types/Socket.js +4 -0
  57. package/lib/Types/State.js +11 -0
  58. package/lib/Types/USync.js +3 -0
  59. package/lib/Types/index.js +28 -0
  60. package/lib/Utils/auth-utils.js +219 -0
  61. package/lib/Utils/baileys-event-stream.js +44 -0
  62. package/lib/Utils/browser-utils.js +25 -0
  63. package/lib/Utils/business.js +233 -0
  64. package/lib/Utils/chat-utils.js +752 -0
  65. package/lib/Utils/crypto.js +130 -0
  66. package/lib/Utils/decode-wa-message.js +267 -0
  67. package/lib/Utils/event-buffer.js +528 -0
  68. package/lib/Utils/generics.js +355 -0
  69. package/lib/Utils/history.js +87 -0
  70. package/lib/Utils/index.js +21 -0
  71. package/lib/Utils/link-preview.js +81 -0
  72. package/lib/Utils/logger.js +5 -0
  73. package/lib/Utils/lt-hash.js +45 -0
  74. package/lib/Utils/make-mutex.js +36 -0
  75. package/lib/Utils/message-retry-manager.js +113 -0
  76. package/lib/Utils/messages-media.js +627 -0
  77. package/lib/Utils/messages.js +909 -0
  78. package/lib/Utils/noise-handler.js +144 -0
  79. package/lib/Utils/pre-key-manager.js +85 -0
  80. package/lib/Utils/process-message.js +341 -0
  81. package/lib/Utils/signal.js +161 -0
  82. package/lib/Utils/use-multi-file-auth-state.js +111 -0
  83. package/lib/Utils/validate-connection.js +200 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +240 -0
  86. package/lib/WABinary/encode.js +218 -0
  87. package/lib/WABinary/generic-utils.js +189 -0
  88. package/lib/WABinary/index.js +7 -0
  89. package/lib/WABinary/jid-utils.js +93 -0
  90. package/lib/WABinary/types.js +3 -0
  91. package/lib/WAM/BinaryInfo.js +11 -0
  92. package/lib/WAM/constants.js +22853 -0
  93. package/lib/WAM/encode.js +154 -0
  94. package/lib/WAM/index.js +5 -0
  95. package/lib/WAUSync/Protocols/USyncContactProtocol.js +30 -0
  96. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  97. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -0
  98. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  99. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  100. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/index.js +6 -0
  102. package/lib/WAUSync/USyncQuery.js +90 -0
  103. package/lib/WAUSync/USyncUser.js +24 -0
  104. package/lib/WAUSync/index.js +5 -0
  105. package/lib/index.js +21 -0
  106. package/package.json +84 -57
  107. package/README.md +0 -1312
  108. package/WAProto/GenerateStatics.sh +0 -3
  109. package/WAProto/fix-imports.js +0 -81
  110. package/WAProto/index.d.ts +0 -14017
  111. package/engine-requirements.js +0 -10
  112. package/src/Defaults/baileys-version.json +0 -1
  113. package/src/Defaults/index.ts +0 -149
  114. package/src/Signal/Group/ciphertext-message.ts +0 -9
  115. package/src/Signal/Group/group-session-builder.ts +0 -56
  116. package/src/Signal/Group/group_cipher.ts +0 -117
  117. package/src/Signal/Group/index.ts +0 -11
  118. package/src/Signal/Group/keyhelper.ts +0 -28
  119. package/src/Signal/Group/sender-chain-key.ts +0 -34
  120. package/src/Signal/Group/sender-key-distribution-message.ts +0 -95
  121. package/src/Signal/Group/sender-key-message.ts +0 -96
  122. package/src/Signal/Group/sender-key-name.ts +0 -66
  123. package/src/Signal/Group/sender-key-record.ts +0 -69
  124. package/src/Signal/Group/sender-key-state.ts +0 -134
  125. package/src/Signal/Group/sender-message-key.ts +0 -36
  126. package/src/Signal/libsignal.ts +0 -521
  127. package/src/Signal/lid-mapping.ts +0 -328
  128. package/src/Socket/Client/index.ts +0 -2
  129. package/src/Socket/Client/types.ts +0 -22
  130. package/src/Socket/Client/websocket.ts +0 -63
  131. package/src/Socket/business.ts +0 -424
  132. package/src/Socket/chats.ts +0 -1272
  133. package/src/Socket/communities.ts +0 -477
  134. package/src/Socket/groups.ts +0 -361
  135. package/src/Socket/index.ts +0 -15
  136. package/src/Socket/messages-recv.ts +0 -1668
  137. package/src/Socket/messages-send.ts +0 -1296
  138. package/src/Socket/mex.ts +0 -58
  139. package/src/Socket/newsletter.ts +0 -229
  140. package/src/Socket/socket.ts +0 -1184
  141. package/src/Types/Auth.ts +0 -116
  142. package/src/Types/Bussines.ts +0 -20
  143. package/src/Types/Call.ts +0 -15
  144. package/src/Types/Chat.ts +0 -138
  145. package/src/Types/Contact.ts +0 -24
  146. package/src/Types/Events.ts +0 -159
  147. package/src/Types/GroupMetadata.ts +0 -70
  148. package/src/Types/Label.ts +0 -48
  149. package/src/Types/LabelAssociation.ts +0 -35
  150. package/src/Types/Message.ts +0 -380
  151. package/src/Types/Newsletter.ts +0 -98
  152. package/src/Types/Product.ts +0 -85
  153. package/src/Types/Signal.ts +0 -76
  154. package/src/Types/Socket.ts +0 -150
  155. package/src/Types/State.ts +0 -43
  156. package/src/Types/USync.ts +0 -27
  157. package/src/Types/globals.d.ts +0 -8
  158. package/src/Types/index.ts +0 -67
  159. package/src/Utils/auth-utils.ts +0 -368
  160. package/src/Utils/browser-utils.ts +0 -31
  161. package/src/Utils/business.ts +0 -286
  162. package/src/Utils/chat-utils.ts +0 -974
  163. package/src/Utils/crypto.ts +0 -147
  164. package/src/Utils/decode-wa-message.ts +0 -355
  165. package/src/Utils/event-buffer.ts +0 -692
  166. package/src/Utils/generics.ts +0 -474
  167. package/src/Utils/history.ts +0 -161
  168. package/src/Utils/identity-change-handler.ts +0 -83
  169. package/src/Utils/index.ts +0 -19
  170. package/src/Utils/link-preview.ts +0 -111
  171. package/src/Utils/logger.ts +0 -13
  172. package/src/Utils/lt-hash.ts +0 -8
  173. package/src/Utils/make-mutex.ts +0 -42
  174. package/src/Utils/message-retry-manager.ts +0 -295
  175. package/src/Utils/messages-media.ts +0 -984
  176. package/src/Utils/messages.ts +0 -1097
  177. package/src/Utils/noise-handler.ts +0 -268
  178. package/src/Utils/pre-key-manager.ts +0 -126
  179. package/src/Utils/process-message.ts +0 -670
  180. package/src/Utils/reporting-utils.ts +0 -344
  181. package/src/Utils/signal.ts +0 -214
  182. package/src/Utils/sync-action-utils.ts +0 -74
  183. package/src/Utils/tc-token-utils.ts +0 -34
  184. package/src/Utils/use-multi-file-auth-state.ts +0 -136
  185. package/src/Utils/validate-connection.ts +0 -253
  186. package/src/WABinary/constants.ts +0 -1305
  187. package/src/WABinary/decode.ts +0 -308
  188. package/src/WABinary/encode.ts +0 -258
  189. package/src/WABinary/generic-utils.ts +0 -141
  190. package/src/WABinary/index.ts +0 -5
  191. package/src/WABinary/jid-utils.ts +0 -128
  192. package/src/WABinary/types.ts +0 -17
  193. package/src/WAM/BinaryInfo.ts +0 -12
  194. package/src/WAM/constants.ts +0 -22889
  195. package/src/WAM/encode.ts +0 -169
  196. package/src/WAM/index.ts +0 -3
  197. package/src/WAUSync/Protocols/USyncContactProtocol.ts +0 -32
  198. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +0 -78
  199. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +0 -35
  200. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +0 -44
  201. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +0 -76
  202. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +0 -33
  203. package/src/WAUSync/Protocols/index.ts +0 -4
  204. package/src/WAUSync/USyncQuery.ts +0 -133
  205. package/src/WAUSync/USyncUser.ts +0 -32
  206. package/src/WAUSync/index.ts +0 -3
  207. package/src/__tests__/Signal/Group/sender-key-state-regression.test.ts +0 -22
  208. package/src/__tests__/Signal/lid-mapping.test.ts +0 -47
  209. package/src/__tests__/Socket/identity-change-handling.test.ts +0 -207
  210. package/src/__tests__/TestUtils/session.ts +0 -47
  211. package/src/__tests__/Utils/generics.test.ts +0 -70
  212. package/src/__tests__/Utils/history.test.ts +0 -362
  213. package/src/__tests__/Utils/messages-media.test.ts +0 -405
  214. package/src/__tests__/Utils/noise-handler.test.ts +0 -339
  215. package/src/__tests__/Utils/process-message.test.ts +0 -138
  216. package/src/__tests__/Utils/process-sync-action.test.ts +0 -359
  217. package/src/__tests__/Utils/reporting-utils.test.ts +0 -160
  218. package/src/__tests__/Utils/signal.test.ts +0 -69
  219. package/src/__tests__/Utils/sync-action-utils.test.ts +0 -183
  220. package/src/__tests__/binary/connection-deadlock.test.ts +0 -54
  221. package/src/__tests__/e2e/fetch-wa-web-version.test-e2e.ts +0 -60
  222. package/src/__tests__/e2e/send-receive-message.test-e2e.ts +0 -644
  223. package/src/__tests__/proto-tojson-long.test.ts +0 -31
  224. package/src/index.ts +0 -13
@@ -1,1296 +0,0 @@
1
- import NodeCache from '@cacheable/node-cache'
2
- import { Boom } from '@hapi/boom'
3
- import { proto } from '../../WAProto/index.js'
4
- import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults'
5
- import type {
6
- AnyMessageContent,
7
- MediaConnInfo,
8
- MessageReceiptType,
9
- MessageRelayOptions,
10
- MiscMessageGenerationOptions,
11
- SocketConfig,
12
- WAMessage,
13
- WAMessageKey
14
- } from '../Types'
15
- import {
16
- aggregateMessageKeysNotFromMe,
17
- assertMediaContent,
18
- bindWaitForEvent,
19
- decryptMediaRetryData,
20
- encodeNewsletterMessage,
21
- encodeSignedDeviceIdentity,
22
- encodeWAMessage,
23
- encryptMediaRetryRequest,
24
- extractDeviceJids,
25
- generateMessageIDV2,
26
- generateParticipantHashV2,
27
- generateWAMessage,
28
- getStatusCodeForMediaRetry,
29
- getUrlFromDirectPath,
30
- getWAUploadToServer,
31
- MessageRetryManager,
32
- normalizeMessageContent,
33
- parseAndInjectE2ESessions,
34
- unixTimestampSeconds
35
- } from '../Utils'
36
- import { getUrlInfo } from '../Utils/link-preview'
37
- import { makeKeyedMutex } from '../Utils/make-mutex'
38
- import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils'
39
- import {
40
- areJidsSameUser,
41
- type BinaryNode,
42
- type BinaryNodeAttributes,
43
- type FullJid,
44
- getBinaryNodeChild,
45
- getBinaryNodeChildren,
46
- isHostedLidUser,
47
- isHostedPnUser,
48
- isJidGroup,
49
- isLidUser,
50
- isPnUser,
51
- jidDecode,
52
- jidEncode,
53
- jidNormalizedUser,
54
- type JidWithDevice,
55
- S_WHATSAPP_NET
56
- } from '../WABinary'
57
- import { USyncQuery, USyncUser } from '../WAUSync'
58
- import { makeNewsletterSocket } from './newsletter'
59
-
60
- export const makeMessagesSocket = (config: SocketConfig) => {
61
- const {
62
- logger,
63
- linkPreviewImageThumbnailWidth,
64
- generateHighQualityLinkPreview,
65
- options: httpRequestOptions,
66
- patchMessageBeforeSending,
67
- cachedGroupMetadata,
68
- enableRecentMessageCache,
69
- maxMsgRetryCount
70
- } = config
71
- const sock = makeNewsletterSocket(config)
72
- const {
73
- ev,
74
- authState,
75
- messageMutex,
76
- signalRepository,
77
- upsertMessage,
78
- query,
79
- fetchPrivacySettings,
80
- sendNode,
81
- groupMetadata,
82
- groupToggleEphemeral
83
- } = sock
84
-
85
- const userDevicesCache =
86
- config.userDevicesCache ||
87
- new NodeCache<JidWithDevice[]>({
88
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
89
- useClones: false
90
- })
91
-
92
- const peerSessionsCache = new NodeCache<boolean>({
93
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
94
- useClones: false
95
- })
96
-
97
- // Initialize message retry manager if enabled
98
- const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null
99
-
100
- // Prevent race conditions in Signal session encryption by user
101
- const encryptionMutex = makeKeyedMutex()
102
-
103
- let mediaConn: Promise<MediaConnInfo>
104
- const refreshMediaConn = async (forceGet = false) => {
105
- const media = await mediaConn
106
- if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
107
- mediaConn = (async () => {
108
- const result = await query({
109
- tag: 'iq',
110
- attrs: {
111
- type: 'set',
112
- xmlns: 'w:m',
113
- to: S_WHATSAPP_NET
114
- },
115
- content: [{ tag: 'media_conn', attrs: {} }]
116
- })
117
- const mediaConnNode = getBinaryNodeChild(result, 'media_conn')!
118
- // TODO: explore full length of data that whatsapp provides
119
- const node: MediaConnInfo = {
120
- hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
121
- hostname: attrs.hostname!,
122
- maxContentLengthBytes: +attrs.maxContentLengthBytes!
123
- })),
124
- auth: mediaConnNode.attrs.auth!,
125
- ttl: +mediaConnNode.attrs.ttl!,
126
- fetchDate: new Date()
127
- }
128
- logger.debug('fetched media conn')
129
- return node
130
- })()
131
- }
132
-
133
- return mediaConn
134
- }
135
-
136
- /**
137
- * generic send receipt function
138
- * used for receipts of phone call, read, delivery etc.
139
- * */
140
- const sendReceipt = async (
141
- jid: string,
142
- participant: string | undefined,
143
- messageIds: string[],
144
- type: MessageReceiptType
145
- ) => {
146
- if (!messageIds || messageIds.length === 0) {
147
- throw new Boom('missing ids in receipt')
148
- }
149
-
150
- const node: BinaryNode = {
151
- tag: 'receipt',
152
- attrs: {
153
- id: messageIds[0]!
154
- }
155
- }
156
- const isReadReceipt = type === 'read' || type === 'read-self'
157
- if (isReadReceipt) {
158
- node.attrs.t = unixTimestampSeconds().toString()
159
- }
160
-
161
- if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
162
- node.attrs.recipient = jid
163
- node.attrs.to = participant!
164
- } else {
165
- node.attrs.to = jid
166
- if (participant) {
167
- node.attrs.participant = participant
168
- }
169
- }
170
-
171
- if (type) {
172
- node.attrs.type = type
173
- }
174
-
175
- const remainingMessageIds = messageIds.slice(1)
176
- if (remainingMessageIds.length) {
177
- node.content = [
178
- {
179
- tag: 'list',
180
- attrs: {},
181
- content: remainingMessageIds.map(id => ({
182
- tag: 'item',
183
- attrs: { id }
184
- }))
185
- }
186
- ]
187
- }
188
-
189
- logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages')
190
- await sendNode(node)
191
- }
192
-
193
- /** Correctly bulk send receipts to multiple chats, participants */
194
- const sendReceipts = async (keys: WAMessageKey[], type: MessageReceiptType) => {
195
- const recps = aggregateMessageKeysNotFromMe(keys)
196
- for (const { jid, participant, messageIds } of recps) {
197
- await sendReceipt(jid, participant, messageIds, type)
198
- }
199
- }
200
-
201
- /** Bulk read messages. Keys can be from different chats & participants */
202
- const readMessages = async (keys: WAMessageKey[]) => {
203
- const privacySettings = await fetchPrivacySettings()
204
- // based on privacy settings, we have to change the read type
205
- const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self'
206
- await sendReceipts(keys, readType)
207
- }
208
-
209
- /** Device info with wire JID */
210
- type DeviceWithJid = JidWithDevice & {
211
- jid: string
212
- }
213
-
214
- /** Fetch all the devices we've to send a message to */
215
- const getUSyncDevices = async (
216
- jids: string[],
217
- useCache: boolean,
218
- ignoreZeroDevices: boolean
219
- ): Promise<DeviceWithJid[]> => {
220
- const deviceResults: DeviceWithJid[] = []
221
-
222
- if (!useCache) {
223
- logger.debug('not using cache for devices')
224
- }
225
-
226
- const toFetch: string[] = []
227
-
228
- const jidsWithUser = jids
229
- .map(jid => {
230
- const decoded = jidDecode(jid)
231
- const user = decoded?.user
232
- const device = decoded?.device
233
- const isExplicitDevice = typeof device === 'number' && device >= 0
234
-
235
- if (isExplicitDevice && user) {
236
- deviceResults.push({
237
- user,
238
- device,
239
- jid
240
- })
241
- return null
242
- }
243
-
244
- jid = jidNormalizedUser(jid)
245
- return { jid, user }
246
- })
247
- .filter(jid => jid !== null)
248
-
249
- let mgetDevices: undefined | Record<string, FullJid[] | undefined>
250
-
251
- if (useCache && userDevicesCache.mget) {
252
- const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean) as string[]
253
- mgetDevices = await userDevicesCache.mget(usersToFetch)
254
- }
255
-
256
- for (const { jid, user } of jidsWithUser) {
257
- if (useCache) {
258
- const devices =
259
- mgetDevices?.[user!] ||
260
- (userDevicesCache.mget ? undefined : ((await userDevicesCache.get(user!)) as FullJid[]))
261
- if (devices) {
262
- const devicesWithJid = devices.map(d => ({
263
- ...d,
264
- jid: jidEncode(d.user, d.server, d.device)
265
- }))
266
- deviceResults.push(...devicesWithJid)
267
-
268
- logger.trace({ user }, 'using cache for devices')
269
- } else {
270
- toFetch.push(jid)
271
- }
272
- } else {
273
- toFetch.push(jid)
274
- }
275
- }
276
-
277
- if (!toFetch.length) {
278
- return deviceResults
279
- }
280
-
281
- const requestedLidUsers = new Set<string>()
282
- for (const jid of toFetch) {
283
- if (isLidUser(jid) || isHostedLidUser(jid)) {
284
- const user = jidDecode(jid)?.user
285
- if (user) requestedLidUsers.add(user)
286
- }
287
- }
288
-
289
- const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol()
290
-
291
- for (const jid of toFetch) {
292
- query.withUser(new USyncUser().withId(jid)) // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
293
- }
294
-
295
- const result = await sock.executeUSyncQuery(query)
296
-
297
- if (result) {
298
- // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
299
- const lidResults = result.list.filter(a => !!a.lid)
300
- if (lidResults.length > 0) {
301
- logger.trace('Storing LID maps from device call')
302
- await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid as string, pn: a.id })))
303
-
304
- // Force-refresh sessions for newly mapped LIDs to align identity addressing
305
- try {
306
- const lids = lidResults.map(a => a.lid as string)
307
- if (lids.length) {
308
- await assertSessions(lids, true)
309
- }
310
- } catch (e) {
311
- logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs')
312
- }
313
- }
314
-
315
- const extracted = extractDeviceJids(
316
- result?.list,
317
- authState.creds.me!.id,
318
- authState.creds.me!.lid!,
319
- ignoreZeroDevices
320
- )
321
- const deviceMap: { [_: string]: FullJid[] } = {}
322
-
323
- for (const item of extracted) {
324
- deviceMap[item.user] = deviceMap[item.user] || []
325
- deviceMap[item.user]?.push(item)
326
- }
327
-
328
- // Process each user's devices as a group for bulk LID migration
329
- for (const [user, userDevices] of Object.entries(deviceMap)) {
330
- const isLidUser = requestedLidUsers.has(user)
331
-
332
- // Process all devices for this user
333
- for (const item of userDevices) {
334
- const finalJid = isLidUser
335
- ? jidEncode(user, item.server, item.device)
336
- : jidEncode(item.user, item.server, item.device)
337
-
338
- deviceResults.push({
339
- ...item,
340
- jid: finalJid
341
- })
342
-
343
- logger.debug(
344
- {
345
- user: item.user,
346
- device: item.device,
347
- finalJid,
348
- usedLid: isLidUser
349
- },
350
- 'Processed device with LID priority'
351
- )
352
- }
353
- }
354
-
355
- if (userDevicesCache.mset) {
356
- // if the cache supports mset, we can set all devices in one go
357
- await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })))
358
- } else {
359
- for (const key in deviceMap) {
360
- if (deviceMap[key]) await userDevicesCache.set(key, deviceMap[key])
361
- }
362
- }
363
-
364
- const userDeviceUpdates: { [userId: string]: string[] } = {}
365
- for (const [userId, devices] of Object.entries(deviceMap)) {
366
- if (devices && devices.length > 0) {
367
- userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0')
368
- }
369
- }
370
-
371
- if (Object.keys(userDeviceUpdates).length > 0) {
372
- try {
373
- await authState.keys.set({ 'device-list': userDeviceUpdates })
374
- logger.debug(
375
- { userCount: Object.keys(userDeviceUpdates).length },
376
- 'stored user device lists for bulk migration'
377
- )
378
- } catch (error) {
379
- logger.warn({ error }, 'failed to store user device lists')
380
- }
381
- }
382
- }
383
-
384
- return deviceResults
385
- }
386
-
387
- /**
388
- * Update Member Label
389
- */
390
- const updateMemberLabel = (jid: string, memberLabel: string) => {
391
- return relayMessage(
392
- jid,
393
- {
394
- protocolMessage: {
395
- type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
396
- memberLabel: {
397
- label: memberLabel?.slice(0, 30),
398
- labelTimestamp: unixTimestampSeconds()
399
- }
400
- }
401
- },
402
- {
403
- additionalNodes: [
404
- {
405
- tag: 'meta',
406
- attrs: {
407
- tag_reason: 'user_update',
408
- appdata: 'member_tag'
409
- },
410
- content: undefined
411
- }
412
- ]
413
- }
414
- )
415
- }
416
-
417
- const assertSessions = async (jids: string[], force?: boolean) => {
418
- let didFetchNewSession = false
419
- const uniqueJids = [...new Set(jids)] // Deduplicate JIDs
420
- const jidsRequiringFetch: string[] = []
421
-
422
- logger.debug({ jids }, 'assertSessions call with jids')
423
-
424
- // Check peerSessionsCache and validate sessions using libsignal loadSession
425
- for (const jid of uniqueJids) {
426
- const signalId = signalRepository.jidToSignalProtocolAddress(jid)
427
- const cachedSession = peerSessionsCache.get(signalId)
428
- if (cachedSession !== undefined) {
429
- if (cachedSession && !force) {
430
- continue // Session exists in cache
431
- }
432
- } else {
433
- const sessionValidation = await signalRepository.validateSession(jid)
434
- const hasSession = sessionValidation.exists
435
- peerSessionsCache.set(signalId, hasSession)
436
- if (hasSession && !force) {
437
- continue
438
- }
439
- }
440
-
441
- jidsRequiringFetch.push(jid)
442
- }
443
-
444
- if (jidsRequiringFetch.length) {
445
- // LID if mapped, otherwise original
446
- const wireJids = [
447
- ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
448
- ...(
449
- (await signalRepository.lidMapping.getLIDsForPNs(
450
- jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid))
451
- )) || []
452
- ).map(a => a.lid)
453
- ]
454
-
455
- logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions')
456
- const result = await query({
457
- tag: 'iq',
458
- attrs: {
459
- xmlns: 'encrypt',
460
- type: 'get',
461
- to: S_WHATSAPP_NET
462
- },
463
- content: [
464
- {
465
- tag: 'key',
466
- attrs: {},
467
- content: wireJids.map(jid => {
468
- const attrs: { [key: string]: string } = { jid }
469
- if (force) attrs.reason = 'identity'
470
- return { tag: 'user', attrs }
471
- })
472
- }
473
- ]
474
- })
475
- await parseAndInjectE2ESessions(result, signalRepository)
476
- didFetchNewSession = true
477
-
478
- // Cache fetched sessions using wire JIDs
479
- for (const wireJid of wireJids) {
480
- const signalId = signalRepository.jidToSignalProtocolAddress(wireJid)
481
- peerSessionsCache.set(signalId, true)
482
- }
483
- }
484
-
485
- return didFetchNewSession
486
- }
487
-
488
- const sendPeerDataOperationMessage = async (
489
- pdoMessage: proto.Message.IPeerDataOperationRequestMessage
490
- ): Promise<string> => {
491
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
492
- if (!authState.creds.me?.id) {
493
- throw new Boom('Not authenticated')
494
- }
495
-
496
- const protocolMessage: proto.IMessage = {
497
- protocolMessage: {
498
- peerDataOperationRequestMessage: pdoMessage,
499
- type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
500
- }
501
- }
502
-
503
- const meJid = jidNormalizedUser(authState.creds.me.id)
504
-
505
- const msgId = await relayMessage(meJid, protocolMessage, {
506
- additionalAttributes: {
507
- category: 'peer',
508
-
509
- push_priority: 'high_force'
510
- },
511
- additionalNodes: [
512
- {
513
- tag: 'meta',
514
- attrs: { appdata: 'default' }
515
- }
516
- ]
517
- })
518
-
519
- return msgId
520
- }
521
-
522
- const createParticipantNodes = async (
523
- recipientJids: string[],
524
- message: proto.IMessage,
525
- extraAttrs?: BinaryNode['attrs'],
526
- dsmMessage?: proto.IMessage
527
- ) => {
528
- if (!recipientJids.length) {
529
- return { nodes: [] as BinaryNode[], shouldIncludeDeviceIdentity: false }
530
- }
531
-
532
- const patched = await patchMessageBeforeSending(message, recipientJids)
533
- const patchedMessages = Array.isArray(patched)
534
- ? patched
535
- : recipientJids.map(jid => ({ recipientJid: jid, message: patched }))
536
-
537
- let shouldIncludeDeviceIdentity = false
538
- const meId = authState.creds.me!.id
539
- const meLid = authState.creds.me?.lid
540
- const meLidUser = meLid ? jidDecode(meLid)?.user : null
541
-
542
- const encryptionPromises = (patchedMessages as any).map(
543
- async ({ recipientJid: jid, message: patchedMessage }: any) => {
544
- try {
545
- if (!jid) return null
546
-
547
- let msgToEncrypt = patchedMessage
548
-
549
- if (dsmMessage) {
550
- const { user: targetUser } = jidDecode(jid)!
551
- const { user: ownPnUser } = jidDecode(meId)!
552
- const ownLidUser = meLidUser
553
-
554
- const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser)
555
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
556
-
557
- if (isOwnUser && !isExactSenderDevice) {
558
- msgToEncrypt = dsmMessage
559
- logger.debug({ jid, targetUser }, 'Using DSM for own device')
560
- }
561
- }
562
-
563
- const bytes = encodeWAMessage(msgToEncrypt)
564
- const mutexKey = jid
565
-
566
- const node = await encryptionMutex.mutex(mutexKey, async () => {
567
- const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes })
568
-
569
- if (type === 'pkmsg') {
570
- shouldIncludeDeviceIdentity = true
571
- }
572
-
573
- return {
574
- tag: 'to',
575
- attrs: { jid },
576
- content: [
577
- {
578
- tag: 'enc',
579
- attrs: { v: '2', type, ...(extraAttrs || {}) },
580
- content: ciphertext
581
- }
582
- ]
583
- }
584
- })
585
-
586
- return node
587
- } catch (err) {
588
- logger.error({ jid, err }, 'Failed to encrypt for recipient')
589
- return null
590
- }
591
- }
592
- )
593
-
594
- const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null) as BinaryNode[]
595
-
596
- if (recipientJids.length > 0 && nodes.length === 0) {
597
- throw new Boom('All encryptions failed', { statusCode: 500 })
598
- }
599
-
600
- return { nodes, shouldIncludeDeviceIdentity }
601
- }
602
-
603
- const relayMessage = async (
604
- jid: string,
605
- message: proto.IMessage,
606
- {
607
- messageId: msgId,
608
- participant,
609
- additionalAttributes,
610
- additionalNodes,
611
- useUserDevicesCache,
612
- useCachedGroupMetadata,
613
- statusJidList
614
- }: MessageRelayOptions
615
- ) => {
616
- const meId = authState.creds.me!.id
617
- const meLid = authState.creds.me?.lid
618
- const isRetryResend = Boolean(participant?.jid)
619
- let shouldIncludeDeviceIdentity = isRetryResend
620
- const statusJid = 'status@broadcast'
621
-
622
- const { user, server } = jidDecode(jid)!
623
- const isGroup = server === 'g.us'
624
- const isStatus = jid === statusJid
625
- const isLid = server === 'lid'
626
- const isNewsletter = server === 'newsletter'
627
- const isGroupOrStatus = isGroup || isStatus
628
- const finalJid = jid
629
-
630
- msgId = msgId || generateMessageIDV2(meId)
631
- useUserDevicesCache = useUserDevicesCache !== false
632
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus
633
-
634
- const participants: BinaryNode[] = []
635
- const destinationJid = !isStatus ? finalJid : statusJid
636
- const binaryNodeContent: BinaryNode[] = []
637
- const devices: DeviceWithJid[] = []
638
- let reportingMessage: proto.IMessage | undefined
639
-
640
- const meMsg: proto.IMessage = {
641
- deviceSentMessage: {
642
- destinationJid,
643
- message
644
- },
645
- messageContextInfo: message.messageContextInfo
646
- }
647
-
648
- const extraAttrs: BinaryNodeAttributes = {}
649
-
650
- if (participant) {
651
- if (!isGroup && !isStatus) {
652
- additionalAttributes = { ...additionalAttributes, device_fanout: 'false' }
653
- }
654
-
655
- const { user, device } = jidDecode(participant.jid)!
656
- devices.push({
657
- user,
658
- device,
659
- jid: participant.jid
660
- })
661
- }
662
-
663
- await authState.keys.transaction(async () => {
664
- const mediaType = getMediaType(message)
665
- if (mediaType) {
666
- extraAttrs['mediatype'] = mediaType
667
- }
668
-
669
- if (isNewsletter) {
670
- const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message
671
- const bytes = encodeNewsletterMessage(patched as proto.IMessage)
672
- binaryNodeContent.push({
673
- tag: 'plaintext',
674
- attrs: {},
675
- content: bytes
676
- })
677
- const stanza: BinaryNode = {
678
- tag: 'message',
679
- attrs: {
680
- to: jid,
681
- id: msgId,
682
- type: getMessageType(message),
683
- ...(additionalAttributes || {})
684
- },
685
- content: binaryNodeContent
686
- }
687
- logger.debug({ msgId }, `sending newsletter message to ${jid}`)
688
- await sendNode(stanza)
689
- return
690
- }
691
-
692
- if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
693
- extraAttrs['decrypt-fail'] = 'hide' // todo: expand for reactions and other types
694
- }
695
-
696
- if (isGroupOrStatus && !isRetryResend) {
697
- const [groupData, senderKeyMap] = await Promise.all([
698
- (async () => {
699
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
700
- if (groupData && Array.isArray(groupData?.participants)) {
701
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
702
- } else if (!isStatus) {
703
- groupData = await groupMetadata(jid) // TODO: start storing group participant list + addr mode in Signal & stop relying on this
704
- }
705
-
706
- return groupData
707
- })(),
708
- (async () => {
709
- if (!participant && !isStatus) {
710
- // what if sender memory is less accurate than the cached metadata
711
- // on participant change in group, we should do sender memory manipulation
712
- const result = await authState.keys.get('sender-key-memory', [jid]) // TODO: check out what if the sender key memory doesn't include the LID stuff now?
713
- return result[jid] || {}
714
- }
715
-
716
- return {}
717
- })()
718
- ])
719
-
720
- const participantsList = groupData ? groupData.participants.map(p => p.id) : []
721
-
722
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
723
- additionalAttributes = {
724
- ...additionalAttributes,
725
- expiration: groupData.ephemeralDuration.toString()
726
- }
727
- }
728
-
729
- if (isStatus && statusJidList) {
730
- participantsList.push(...statusJidList)
731
- }
732
-
733
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false)
734
- devices.push(...additionalDevices)
735
-
736
- if (isGroup) {
737
- additionalAttributes = {
738
- ...additionalAttributes,
739
- addressing_mode: groupData?.addressingMode || 'lid'
740
- }
741
- }
742
-
743
- const patched = await patchMessageBeforeSending(message)
744
- if (Array.isArray(patched)) {
745
- throw new Boom('Per-jid patching is not supported in groups')
746
- }
747
-
748
- const bytes = encodeWAMessage(patched)
749
- reportingMessage = patched
750
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid'
751
- const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId
752
-
753
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
754
- group: destinationJid,
755
- data: bytes,
756
- meId: groupSenderIdentity
757
- })
758
-
759
- const senderKeyRecipients: string[] = []
760
- for (const device of devices) {
761
- const deviceJid = device.jid
762
- const hasKey = !!senderKeyMap[deviceJid]
763
- if (
764
- (!hasKey || !!participant) &&
765
- !isHostedLidUser(deviceJid) &&
766
- !isHostedPnUser(deviceJid) &&
767
- device.device !== 99
768
- ) {
769
- //todo: revamp all this logic
770
- // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
771
- senderKeyRecipients.push(deviceJid)
772
- senderKeyMap[deviceJid] = true
773
- }
774
- }
775
-
776
- if (senderKeyRecipients.length) {
777
- logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key')
778
-
779
- const senderKeyMsg: proto.IMessage = {
780
- senderKeyDistributionMessage: {
781
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
782
- groupId: destinationJid
783
- }
784
- }
785
-
786
- const senderKeySessionTargets = senderKeyRecipients
787
- await assertSessions(senderKeySessionTargets)
788
-
789
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs)
790
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
791
-
792
- participants.push(...result.nodes)
793
- }
794
-
795
- binaryNodeContent.push({
796
- tag: 'enc',
797
- attrs: { v: '2', type: 'skmsg', ...extraAttrs },
798
- content: ciphertext
799
- })
800
-
801
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
802
- } else {
803
- // ADDRESSING CONSISTENCY: Match own identity to conversation context
804
- // TODO: investigate if this is true
805
- let ownId = meId
806
- if (isLid && meLid) {
807
- ownId = meLid
808
- logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation')
809
- } else {
810
- logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation')
811
- }
812
-
813
- const { user: ownUser } = jidDecode(ownId)!
814
- if (!participant) {
815
- const patchedForReporting = await patchMessageBeforeSending(message, [jid])
816
- reportingMessage = Array.isArray(patchedForReporting)
817
- ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
818
- : patchedForReporting
819
- }
820
-
821
- if (!isRetryResend) {
822
- const targetUserServer = isLid ? 'lid' : 's.whatsapp.net'
823
- devices.push({
824
- user,
825
- device: 0,
826
- jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
827
- })
828
-
829
- if (user !== ownUser) {
830
- const ownUserServer = isLid ? 'lid' : 's.whatsapp.net'
831
- const ownUserForAddressing = isLid && meLid ? jidDecode(meLid)!.user : jidDecode(meId)!.user
832
-
833
- devices.push({
834
- user: ownUserForAddressing,
835
- device: 0,
836
- jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
837
- })
838
- }
839
-
840
- if (additionalAttributes?.['category'] !== 'peer') {
841
- // Clear placeholders and enumerate actual devices
842
- devices.length = 0
843
-
844
- // Use conversation-appropriate sender identity
845
- const senderIdentity =
846
- isLid && meLid
847
- ? jidEncode(jidDecode(meLid)?.user!, 'lid', undefined)
848
- : jidEncode(jidDecode(meId)?.user!, 's.whatsapp.net', undefined)
849
-
850
- // Enumerate devices for sender and target with consistent addressing
851
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false)
852
- devices.push(...sessionDevices)
853
-
854
- logger.debug(
855
- {
856
- deviceCount: devices.length,
857
- devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
858
- },
859
- 'Device enumeration complete with unified addressing'
860
- )
861
- }
862
- }
863
-
864
- const allRecipients: string[] = []
865
- const meRecipients: string[] = []
866
- const otherRecipients: string[] = []
867
- const { user: mePnUser } = jidDecode(meId)!
868
- const { user: meLidUser } = meLid ? jidDecode(meLid)! : { user: null }
869
-
870
- for (const { user, jid } of devices) {
871
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
872
- if (isExactSenderDevice) {
873
- logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)')
874
- continue
875
- }
876
-
877
- // Check if this is our device (could match either PN or LID user)
878
- const isMe = user === mePnUser || user === meLidUser
879
-
880
- if (isMe) {
881
- meRecipients.push(jid)
882
- } else {
883
- otherRecipients.push(jid)
884
- }
885
-
886
- allRecipients.push(jid)
887
- }
888
-
889
- await assertSessions(allRecipients)
890
-
891
- const [
892
- { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
893
- { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
894
- ] = await Promise.all([
895
- // For own devices: use DSM if available (1:1 chats only)
896
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
897
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
898
- ])
899
- participants.push(...meNodes)
900
- participants.push(...otherNodes)
901
-
902
- if (meRecipients.length > 0 || otherRecipients.length > 0) {
903
- extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients])
904
- }
905
-
906
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
907
- }
908
-
909
- if (isRetryResend) {
910
- const isParticipantLid = isLidUser(participant!.jid)
911
- const isMe = areJidsSameUser(participant!.jid, isParticipantLid ? meLid : meId)
912
-
913
- const encodedMessageToSend = isMe
914
- ? encodeWAMessage({
915
- deviceSentMessage: {
916
- destinationJid,
917
- message
918
- }
919
- })
920
- : encodeWAMessage(message)
921
-
922
- const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
923
- data: encodedMessageToSend,
924
- jid: participant!.jid
925
- })
926
-
927
- binaryNodeContent.push({
928
- tag: 'enc',
929
- attrs: {
930
- v: '2',
931
- type,
932
- count: participant!.count.toString()
933
- },
934
- content: encryptedContent
935
- })
936
- }
937
-
938
- if (participants.length) {
939
- if (additionalAttributes?.['category'] === 'peer') {
940
- const peerNode = participants[0]?.content?.[0] as BinaryNode
941
- if (peerNode) {
942
- binaryNodeContent.push(peerNode) // push only enc
943
- }
944
- } else {
945
- binaryNodeContent.push({
946
- tag: 'participants',
947
- attrs: {},
948
-
949
- content: participants
950
- })
951
- }
952
- }
953
-
954
- const stanza: BinaryNode = {
955
- tag: 'message',
956
- attrs: {
957
- id: msgId,
958
- to: destinationJid,
959
- type: getMessageType(message),
960
- ...(additionalAttributes || {})
961
- },
962
- content: binaryNodeContent
963
- }
964
-
965
- // if the participant to send to is explicitly specified (generally retry recp)
966
- // ensure the message is only sent to that person
967
- // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
968
- if (participant) {
969
- if (isJidGroup(destinationJid)) {
970
- stanza.attrs.to = destinationJid
971
- stanza.attrs.participant = participant.jid
972
- } else if (areJidsSameUser(participant.jid, meId)) {
973
- stanza.attrs.to = participant.jid
974
- stanza.attrs.recipient = destinationJid
975
- } else {
976
- stanza.attrs.to = participant.jid
977
- }
978
- } else {
979
- stanza.attrs.to = destinationJid
980
- }
981
-
982
- if (shouldIncludeDeviceIdentity) {
983
- ;(stanza.content as BinaryNode[]).push({
984
- tag: 'device-identity',
985
- attrs: {},
986
- content: encodeSignedDeviceIdentity(authState.creds.account!, true)
987
- })
988
-
989
- logger.debug({ jid }, 'adding device identity')
990
- }
991
-
992
- if (
993
- !isNewsletter &&
994
- !isRetryResend &&
995
- reportingMessage?.messageContextInfo?.messageSecret &&
996
- shouldIncludeReportingToken(reportingMessage)
997
- ) {
998
- try {
999
- const encoded = encodeWAMessage(reportingMessage)
1000
- const reportingKey: WAMessageKey = {
1001
- id: msgId,
1002
- fromMe: true,
1003
- remoteJid: destinationJid,
1004
- participant: participant?.jid
1005
- }
1006
- const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey)
1007
- if (reportingNode) {
1008
- ;(stanza.content as BinaryNode[]).push(reportingNode)
1009
- logger.trace({ jid }, 'added reporting token to message')
1010
- }
1011
- } catch (error: any) {
1012
- logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token')
1013
- }
1014
- }
1015
-
1016
- const contactTcTokenData =
1017
- !isGroup && !isRetryResend && !isStatus ? await authState.keys.get('tctoken', [destinationJid]) : {}
1018
-
1019
- const tcTokenBuffer = contactTcTokenData[destinationJid]?.token
1020
-
1021
- if (tcTokenBuffer) {
1022
- ;(stanza.content as BinaryNode[]).push({
1023
- tag: 'tctoken',
1024
- attrs: {},
1025
- content: tcTokenBuffer
1026
- })
1027
- }
1028
-
1029
- if (additionalNodes && additionalNodes.length > 0) {
1030
- ;(stanza.content as BinaryNode[]).push(...additionalNodes)
1031
- }
1032
-
1033
- logger.debug({ msgId }, `sending message to ${participants.length} devices`)
1034
-
1035
- await sendNode(stanza)
1036
-
1037
- // Add message to retry cache if enabled
1038
- if (messageRetryManager && !participant) {
1039
- messageRetryManager.addRecentMessage(destinationJid, msgId, message)
1040
- }
1041
- }, meId)
1042
-
1043
- return msgId
1044
- }
1045
-
1046
- const getMessageType = (message: proto.IMessage) => {
1047
- const normalizedMessage = normalizeMessageContent(message)
1048
- if (!normalizedMessage) return 'text'
1049
-
1050
- if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
1051
- return 'reaction'
1052
- }
1053
-
1054
- if (
1055
- normalizedMessage.pollCreationMessage ||
1056
- normalizedMessage.pollCreationMessageV2 ||
1057
- normalizedMessage.pollCreationMessageV3 ||
1058
- normalizedMessage.pollUpdateMessage
1059
- ) {
1060
- return 'poll'
1061
- }
1062
-
1063
- if (normalizedMessage.eventMessage) {
1064
- return 'event'
1065
- }
1066
-
1067
- if (getMediaType(normalizedMessage) !== '') {
1068
- return 'media'
1069
- }
1070
-
1071
- return 'text'
1072
- }
1073
-
1074
- const getMediaType = (message: proto.IMessage) => {
1075
- if (message.imageMessage) {
1076
- return 'image'
1077
- } else if (message.videoMessage) {
1078
- return message.videoMessage.gifPlayback ? 'gif' : 'video'
1079
- } else if (message.audioMessage) {
1080
- return message.audioMessage.ptt ? 'ptt' : 'audio'
1081
- } else if (message.contactMessage) {
1082
- return 'vcard'
1083
- } else if (message.documentMessage) {
1084
- return 'document'
1085
- } else if (message.contactsArrayMessage) {
1086
- return 'contact_array'
1087
- } else if (message.liveLocationMessage) {
1088
- return 'livelocation'
1089
- } else if (message.stickerMessage) {
1090
- return 'sticker'
1091
- } else if (message.listMessage) {
1092
- return 'list'
1093
- } else if (message.listResponseMessage) {
1094
- return 'list_response'
1095
- } else if (message.buttonsResponseMessage) {
1096
- return 'buttons_response'
1097
- } else if (message.orderMessage) {
1098
- return 'order'
1099
- } else if (message.productMessage) {
1100
- return 'product'
1101
- } else if (message.interactiveResponseMessage) {
1102
- return 'native_flow_response'
1103
- } else if (message.groupInviteMessage) {
1104
- return 'url'
1105
- }
1106
-
1107
- return ''
1108
- }
1109
-
1110
- const getPrivacyTokens = async (jids: string[]) => {
1111
- const t = unixTimestampSeconds().toString()
1112
- const result = await query({
1113
- tag: 'iq',
1114
- attrs: {
1115
- to: S_WHATSAPP_NET,
1116
- type: 'set',
1117
- xmlns: 'privacy'
1118
- },
1119
- content: [
1120
- {
1121
- tag: 'tokens',
1122
- attrs: {},
1123
- content: jids.map(jid => ({
1124
- tag: 'token',
1125
- attrs: {
1126
- jid: jidNormalizedUser(jid),
1127
- t,
1128
- type: 'trusted_contact'
1129
- }
1130
- }))
1131
- }
1132
- ]
1133
- })
1134
-
1135
- return result
1136
- }
1137
-
1138
- const waUploadToServer = getWAUploadToServer(config, refreshMediaConn)
1139
-
1140
- const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update')
1141
-
1142
- return {
1143
- ...sock,
1144
- getPrivacyTokens,
1145
- assertSessions,
1146
- relayMessage,
1147
- sendReceipt,
1148
- sendReceipts,
1149
- readMessages,
1150
- refreshMediaConn,
1151
- waUploadToServer,
1152
- fetchPrivacySettings,
1153
- sendPeerDataOperationMessage,
1154
- createParticipantNodes,
1155
- getUSyncDevices,
1156
- messageRetryManager,
1157
- updateMemberLabel,
1158
- updateMediaMessage: async (message: WAMessage) => {
1159
- const content = assertMediaContent(message.message)
1160
- const mediaKey = content.mediaKey!
1161
- const meId = authState.creds.me!.id
1162
- const node = encryptMediaRetryRequest(message.key, mediaKey, meId)
1163
-
1164
- let error: Error | undefined = undefined
1165
- await Promise.all([
1166
- sendNode(node),
1167
- waitForMsgMediaUpdate(async update => {
1168
- const result = update.find(c => c.key.id === message.key.id)
1169
- if (result) {
1170
- if (result.error) {
1171
- error = result.error
1172
- } else {
1173
- try {
1174
- const media = decryptMediaRetryData(result.media!, mediaKey, result.key.id!)
1175
- if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1176
- const resultStr = proto.MediaRetryNotification.ResultType[media.result!]
1177
- throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1178
- data: media,
1179
- statusCode: getStatusCodeForMediaRetry(media.result!) || 404
1180
- })
1181
- }
1182
-
1183
- content.directPath = media.directPath
1184
- content.url = getUrlFromDirectPath(content.directPath!)
1185
-
1186
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
1187
- } catch (err: any) {
1188
- error = err
1189
- }
1190
- }
1191
-
1192
- return true
1193
- }
1194
- })
1195
- ])
1196
-
1197
- if (error) {
1198
- throw error
1199
- }
1200
-
1201
- ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }])
1202
-
1203
- return message
1204
- },
1205
- sendMessage: async (jid: string, content: AnyMessageContent, options: MiscMessageGenerationOptions = {}) => {
1206
- const userJid = authState.creds.me!.id
1207
- if (
1208
- typeof content === 'object' &&
1209
- 'disappearingMessagesInChat' in content &&
1210
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1211
- isJidGroup(jid)
1212
- ) {
1213
- const { disappearingMessagesInChat } = content
1214
- const value =
1215
- typeof disappearingMessagesInChat === 'boolean'
1216
- ? disappearingMessagesInChat
1217
- ? WA_DEFAULT_EPHEMERAL
1218
- : 0
1219
- : disappearingMessagesInChat
1220
- await groupToggleEphemeral(jid, value)
1221
- } else {
1222
- const fullMsg = await generateWAMessage(jid, content, {
1223
- logger,
1224
- userJid,
1225
- getUrlInfo: text =>
1226
- getUrlInfo(text, {
1227
- thumbnailWidth: linkPreviewImageThumbnailWidth,
1228
- fetchOpts: {
1229
- timeout: 3_000,
1230
- ...(httpRequestOptions || {})
1231
- },
1232
- logger,
1233
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1234
- }),
1235
- //TODO: CACHE
1236
- getProfilePicUrl: sock.profilePictureUrl,
1237
- getCallLink: sock.createCallLink,
1238
- upload: waUploadToServer,
1239
- mediaCache: config.mediaCache,
1240
- options: config.options,
1241
- messageId: generateMessageIDV2(sock.user?.id),
1242
- ...options
1243
- })
1244
- const isEventMsg = 'event' in content && !!content.event
1245
- const isDeleteMsg = 'delete' in content && !!content.delete
1246
- const isEditMsg = 'edit' in content && !!content.edit
1247
- const isPinMsg = 'pin' in content && !!content.pin
1248
- const isPollMessage = 'poll' in content && !!content.poll
1249
- const additionalAttributes: BinaryNodeAttributes = {}
1250
- const additionalNodes: BinaryNode[] = []
1251
- // required for delete
1252
- if (isDeleteMsg) {
1253
- // if the chat is a group, and I am not the author, then delete the message as an admin
1254
- if (isJidGroup(content.delete?.remoteJid as string) && !content.delete?.fromMe) {
1255
- additionalAttributes.edit = '8'
1256
- } else {
1257
- additionalAttributes.edit = '7'
1258
- }
1259
- } else if (isEditMsg) {
1260
- additionalAttributes.edit = '1'
1261
- } else if (isPinMsg) {
1262
- additionalAttributes.edit = '2'
1263
- } else if (isPollMessage) {
1264
- additionalNodes.push({
1265
- tag: 'meta',
1266
- attrs: {
1267
- polltype: 'creation'
1268
- }
1269
- } as BinaryNode)
1270
- } else if (isEventMsg) {
1271
- additionalNodes.push({
1272
- tag: 'meta',
1273
- attrs: {
1274
- event_type: 'creation'
1275
- }
1276
- } as BinaryNode)
1277
- }
1278
-
1279
- await relayMessage(jid, fullMsg.message!, {
1280
- messageId: fullMsg.key.id!,
1281
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1282
- additionalAttributes,
1283
- statusJidList: options.statusJidList,
1284
- additionalNodes
1285
- })
1286
- if (config.emitOwnEvents) {
1287
- process.nextTick(async () => {
1288
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'))
1289
- })
1290
- }
1291
-
1292
- return fullMsg
1293
- }
1294
- }
1295
- }
1296
- }