@vinzsocket/baileys 2.8.10 → 2.8.30

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