@vinzsocket/baileys 2.1.0 → 2.8.9

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 (35) hide show
  1. package/lib/Signal/Group/group_cipher.d.ts +1 -0
  2. package/lib/Signal/Group/group_cipher.js +38 -28
  3. package/lib/Signal/Group/queue-job.d.ts +2 -0
  4. package/lib/Signal/Group/queue-job.js +57 -0
  5. package/lib/Socket/groups.js +2 -0
  6. package/lib/Socket/messages-send.js +450 -496
  7. package/lib/Store/index.d.ts +4 -0
  8. package/lib/Store/index.js +4 -0
  9. package/lib/Store/make-cache-manager-store.d.ts +17 -0
  10. package/lib/Store/make-cache-manager-store.js +102 -0
  11. package/lib/Store/make-in-memory-store.d.ts +118 -0
  12. package/lib/Store/make-in-memory-store.js +427 -0
  13. package/lib/Store/make-ordered-dictionary.d.ts +14 -0
  14. package/lib/Store/make-ordered-dictionary.js +79 -0
  15. package/lib/Store/object-repository.d.ts +10 -0
  16. package/lib/Store/object-repository.js +23 -0
  17. package/lib/Types/Message.d.ts +12 -42
  18. package/lib/Utils/extended-messages.d.ts +73 -0
  19. package/lib/Utils/extended-messages.js +231 -0
  20. package/lib/Utils/index.d.ts +3 -0
  21. package/lib/Utils/index.js +3 -0
  22. package/lib/Utils/lid-resolver.d.ts +17 -0
  23. package/lib/Utils/lid-resolver.js +67 -0
  24. package/lib/Utils/mention.d.ts +27 -0
  25. package/lib/Utils/mention.js +134 -0
  26. package/lib/Utils/messages.js +44 -143
  27. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +8 -0
  28. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  29. package/lib/WAUSync/Protocols/index.d.ts +1 -0
  30. package/lib/WAUSync/Protocols/index.js +1 -0
  31. package/lib/WAUSync/USyncQuery.d.ts +1 -0
  32. package/lib/WAUSync/USyncQuery.js +5 -0
  33. package/lib/index.d.ts +1 -0
  34. package/lib/index.js +1 -0
  35. package/package.json +8 -7
@@ -2,39 +2,28 @@ import NodeCache from '@cacheable/node-cache';
2
2
  import { Boom } from '@hapi/boom';
3
3
  import { proto } from '../../WAProto/index.js';
4
4
  import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
- import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
5
+ import { WAMessageAddressingMode } from '../Types/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageID, generateMessageIDV2, generateWAMessage, generateWAMessageContent, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { detectExtendedMessageType, makeExtendedMessageHandlers } from '../Utils/extended-messages.js';
6
8
  import { getUrlInfo } from '../Utils/link-preview.js';
7
- import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
8
- import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
9
- import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
10
- import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
9
+ import { makeKeyedMutex } from '../Utils/make-mutex.js';
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
13
  export const makeMessagesSocket = (config) => {
14
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
14
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
15
15
  const sock = makeNewsletterSocket(config);
16
- const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
17
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
18
- /**
19
- * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
20
- * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
21
- * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
22
- */
23
- const inFlightTcTokenIssuance = new Set();
16
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
24
17
  const userDevicesCache = config.userDevicesCache ||
25
18
  new NodeCache({
26
19
  stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
27
20
  useClones: false
28
21
  });
29
- /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
30
- const devicesMutex = makeMutex();
31
22
  // Initialize message retry manager if enabled
32
23
  const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
33
24
  // Prevent race conditions in Signal session encryption by user
34
25
  const encryptionMutex = makeKeyedMutex();
35
26
  let mediaConn;
36
- /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
37
- let mediaHost = DEF_MEDIA_HOST;
38
27
  const refreshMediaConn = async (forceGet = false) => {
39
28
  const media = await mediaConn;
40
29
  if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
@@ -49,7 +38,6 @@ export const makeMessagesSocket = (config) => {
49
38
  content: [{ tag: 'media_conn', attrs: {} }]
50
39
  });
51
40
  const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
52
- // TODO: explore full length of data that whatsapp provides
53
41
  const node = {
54
42
  hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
55
43
  hostname: attrs.hostname,
@@ -60,9 +48,6 @@ export const makeMessagesSocket = (config) => {
60
48
  fetchDate: new Date()
61
49
  };
62
50
  logger.debug('fetched media conn');
63
- if (node.hosts[0]) {
64
- mediaHost = node.hosts[0].hostname;
65
- }
66
51
  return node;
67
52
  })();
68
53
  }
@@ -86,7 +71,7 @@ export const makeMessagesSocket = (config) => {
86
71
  if (isReadReceipt) {
87
72
  node.attrs.t = unixTimestampSeconds().toString();
88
73
  }
89
- if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
74
+ if (type === 'sender' && isPnUser(jid)) {
90
75
  node.attrs.recipient = jid;
91
76
  node.attrs.to = participant;
92
77
  }
@@ -129,6 +114,34 @@ export const makeMessagesSocket = (config) => {
129
114
  const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
130
115
  await sendReceipts(keys, readType);
131
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
+ };
132
145
  /** Fetch all the devices we've to send a message to */
133
146
  const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
134
147
  const deviceResults = [];
@@ -136,39 +149,33 @@ export const makeMessagesSocket = (config) => {
136
149
  logger.debug('not using cache for devices');
137
150
  }
138
151
  const toFetch = [];
139
- const jidsWithUser = jids
140
- .map(jid => {
152
+ // Deduplicate and normalize JIDs
153
+ jids = deduplicateLidPnJids(Array.from(new Set(jids)));
154
+ for (let jid of jids) {
141
155
  const decoded = jidDecode(jid);
142
156
  const user = decoded?.user;
143
157
  const device = decoded?.device;
144
158
  const isExplicitDevice = typeof device === 'number' && device >= 0;
159
+ // Handle explicit device JIDs directly
145
160
  if (isExplicitDevice && user) {
146
161
  deviceResults.push({
147
162
  user,
148
163
  device,
149
- jid
164
+ wireJid: jid // Preserve exact JID format for wire protocol
150
165
  });
151
- return null;
166
+ continue;
152
167
  }
168
+ // For user JIDs, normalize and prepare for device enumeration
153
169
  jid = jidNormalizedUser(jid);
154
- return { jid, user };
155
- })
156
- .filter(jid => jid !== null);
157
- let mgetDevices;
158
- if (useCache && userDevicesCache.mget) {
159
- const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
160
- mgetDevices = await userDevicesCache.mget(usersToFetch);
161
- }
162
- for (const { jid, user } of jidsWithUser) {
163
170
  if (useCache) {
164
- const devices = mgetDevices?.[user] ||
165
- (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
171
+ const devices = userDevicesCache.get(user);
166
172
  if (devices) {
167
- const devicesWithJid = devices.map(d => ({
173
+ const isLidJid = jid.includes('@lid');
174
+ const devicesWithWire = devices.map(d => ({
168
175
  ...d,
169
- jid: jidEncode(d.user, d.server, d.device)
176
+ wireJid: isLidJid ? jidEncode(d.user, 'lid', d.device) : jidEncode(d.user, 's.whatsapp.net', d.device)
170
177
  }));
171
- deviceResults.push(...devicesWithJid);
178
+ deviceResults.push(...devicesWithWire);
172
179
  logger.trace({ user }, 'using cache for devices');
173
180
  }
174
181
  else {
@@ -184,35 +191,19 @@ export const makeMessagesSocket = (config) => {
184
191
  }
185
192
  const requestedLidUsers = new Set();
186
193
  for (const jid of toFetch) {
187
- if (isLidUser(jid) || isHostedLidUser(jid)) {
194
+ if (jid.includes('@lid')) {
188
195
  const user = jidDecode(jid)?.user;
189
196
  if (user)
190
197
  requestedLidUsers.add(user);
191
198
  }
192
199
  }
193
- const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
200
+ const query = new USyncQuery().withContext('message').withDeviceProtocol();
194
201
  for (const jid of toFetch) {
195
- 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
202
+ query.withUser(new USyncUser().withId(jid));
196
203
  }
197
204
  const result = await sock.executeUSyncQuery(query);
198
205
  if (result) {
199
- // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
200
- const lidResults = result.list.filter(a => !!a.lid);
201
- if (lidResults.length > 0) {
202
- logger.trace('Storing LID maps from device call');
203
- await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
204
- // Force-refresh sessions for newly mapped LIDs to align identity addressing
205
- try {
206
- const lids = lidResults.map(a => a.lid);
207
- if (lids.length) {
208
- await assertSessions(lids, true);
209
- }
210
- }
211
- catch (e) {
212
- logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
213
- }
214
- }
215
- const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
206
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, ignoreZeroDevices);
216
207
  const deviceMap = {};
217
208
  for (const item of extracted) {
218
209
  deviceMap[item.user] = deviceMap[item.user] || [];
@@ -223,97 +214,197 @@ export const makeMessagesSocket = (config) => {
223
214
  const isLidUser = requestedLidUsers.has(user);
224
215
  // Process all devices for this user
225
216
  for (const item of userDevices) {
226
- const finalJid = isLidUser
227
- ? jidEncode(user, item.server, item.device)
228
- : jidEncode(item.user, item.server, item.device);
217
+ const finalWireJid = isLidUser
218
+ ? jidEncode(user, 'lid', item.device)
219
+ : jidEncode(item.user, 's.whatsapp.net', item.device);
229
220
  deviceResults.push({
230
221
  ...item,
231
- jid: finalJid
222
+ wireJid: finalWireJid
232
223
  });
233
224
  logger.debug({
234
225
  user: item.user,
235
226
  device: item.device,
236
- finalJid,
227
+ finalWireJid,
237
228
  usedLid: isLidUser
238
229
  }, 'Processed device with LID priority');
239
230
  }
240
231
  }
241
- await devicesMutex.mutex(async () => {
242
- if (userDevicesCache.mset) {
243
- // if the cache supports mset, we can set all devices in one go
244
- await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
232
+ for (const key in deviceMap) {
233
+ userDevicesCache.set(key, deviceMap[key]);
234
+ }
235
+ }
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
+ }
245
269
  }
246
- else {
247
- for (const key in deviceMap) {
248
- if (deviceMap[key])
249
- await userDevicesCache.set(key, deviceMap[key]);
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');
250
274
  }
275
+ jidsRequiringFetch.push(jid);
251
276
  }
252
- });
253
- const userDeviceUpdates = {};
254
- for (const [userId, devices] of Object.entries(deviceMap)) {
255
- if (devices && devices.length > 0) {
256
- userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
277
+ };
278
+ // Process all JIDs
279
+ for (const jid of jids) {
280
+ await checkJidSession(jid);
281
+ }
282
+ }
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, []);
257
293
  }
294
+ userGroups.get(user).push(jid);
258
295
  }
259
- if (Object.keys(userDeviceUpdates).length > 0) {
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
+ }
260
301
  try {
261
- await authState.keys.set({ 'device-list': userDeviceUpdates });
262
- logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
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
+ }
263
307
  }
264
308
  catch (error) {
265
- logger.warn({ error }, 'failed to store user device lists');
309
+ logger.debug({ user, error }, 'Failed to check LID mapping for user');
266
310
  }
267
- }
268
- }
269
- return deviceResults;
270
- };
271
- /**
272
- * Update Member Label
273
- */
274
- const updateMemberLabel = (jid, memberLabel) => {
275
- return relayMessage(jid, {
276
- protocolMessage: {
277
- type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
278
- memberLabel: {
279
- label: memberLabel?.slice(0, 30),
280
- labelTimestamp: unixTimestampSeconds()
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
+ }
281
329
  }
282
- }
283
- }, {
284
- additionalNodes: [
285
- {
286
- tag: 'meta',
287
- attrs: {
288
- tag_reason: 'user_update',
289
- appdata: 'member_tag'
290
- },
291
- content: undefined
330
+ catch (migrationError) {
331
+ logger.warn({ jid, error: migrationError }, 'Failed to migrate device session');
292
332
  }
293
- ]
294
- });
295
- };
296
- const assertSessions = async (jids, force) => {
297
- let didFetchNewSession = false;
298
- const uniqueJids = [...new Set(jids)];
299
- const jidsRequiringFetch = [];
300
- logger.debug({ jids }, 'assertSessions call with jids');
301
- for (const jid of uniqueJids) {
302
- if (!force) {
303
- const sessionValidation = await signalRepository.validateSession(jid);
304
- if (sessionValidation.exists) {
305
- continue;
333
+ };
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);
306
380
  }
307
381
  }
308
- jidsRequiringFetch.push(jid);
309
382
  }
310
383
  if (jidsRequiringFetch.length) {
311
- // LID if mapped, otherwise original
312
- const wireJids = [
313
- ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
314
- ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
315
- ];
316
- logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
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
+ }
317
408
  const result = await query({
318
409
  tag: 'iq',
319
410
  attrs: {
@@ -325,12 +416,10 @@ export const makeMessagesSocket = (config) => {
325
416
  {
326
417
  tag: 'key',
327
418
  attrs: {},
328
- content: wireJids.map(jid => {
329
- const attrs = { jid };
330
- if (force)
331
- attrs.reason = 'identity';
332
- return { tag: 'user', attrs };
333
- })
419
+ content: jidsRequiringFetch.map(jid => ({
420
+ tag: 'user',
421
+ attrs: { jid }
422
+ }))
334
423
  }
335
424
  ]
336
425
  });
@@ -355,97 +444,161 @@ export const makeMessagesSocket = (config) => {
355
444
  additionalAttributes: {
356
445
  category: 'peer',
357
446
  push_priority: 'high_force'
358
- },
359
- additionalNodes: [
360
- {
361
- tag: 'meta',
362
- attrs: { appdata: 'default' }
363
- }
364
- ]
447
+ }
365
448
  });
366
449
  return msgId;
367
450
  };
368
- const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
369
- if (!recipientJids.length) {
370
- return { nodes: [], shouldIncludeDeviceIdentity: false };
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];
371
455
  }
372
- const patched = await patchMessageBeforeSending(message, recipientJids);
373
- const patchedMessages = Array.isArray(patched)
374
- ? patched
375
- : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
376
456
  let shouldIncludeDeviceIdentity = false;
377
457
  const meId = authState.creds.me.id;
378
458
  const meLid = authState.creds.me?.lid;
379
459
  const meLidUser = meLid ? jidDecode(meLid)?.user : null;
380
- const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
381
- try {
382
- if (!jid)
383
- return null;
384
- let msgToEncrypt = patchedMessage;
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 });
474
+ }
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;
385
524
  if (dsmMessage) {
386
- const { user: targetUser } = jidDecode(jid);
525
+ const { user: targetUser } = jidDecode(wireJid);
387
526
  const { user: ownPnUser } = jidDecode(meId);
388
527
  const ownLidUser = meLidUser;
528
+ // Check if this is our device (same user, different device)
389
529
  const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
390
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
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);
391
532
  if (isOwnUser && !isExactSenderDevice) {
392
- msgToEncrypt = dsmMessage;
393
- logger.debug({ jid, targetUser }, 'Using DSM for own device');
533
+ messageToEncrypt = dsmMessage;
534
+ logger.debug({ wireJid, targetUser }, 'Using DSM for own device');
394
535
  }
395
536
  }
396
- const bytes = encodeWAMessage(msgToEncrypt);
397
- const mutexKey = jid;
398
- const node = await encryptionMutex.mutex(mutexKey, async () => {
399
- const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
400
- if (type === 'pkmsg') {
401
- shouldIncludeDeviceIdentity = true;
402
- }
403
- return {
404
- tag: 'to',
405
- attrs: { jid },
406
- content: [
407
- {
408
- tag: 'enc',
409
- attrs: { v: '2', type, ...(extraAttrs || {}) },
410
- content: ciphertext
411
- }
412
- ]
413
- };
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
414
544
  });
415
- return node;
416
- }
417
- catch (err) {
418
- logger.error({ jid, err }, 'Failed to encrypt for recipient');
419
- return null;
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);
420
564
  }
421
- });
422
- const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
423
- if (recipientJids.length > 0 && nodes.length === 0) {
424
- throw new Boom('All encryptions failed', { statusCode: 500 });
425
- }
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();
426
571
  return { nodes, shouldIncludeDeviceIdentity };
427
572
  };
428
573
  const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
429
- const meId = assertMeId(authState.creds);
574
+ const meId = authState.creds.me.id;
430
575
  const meLid = authState.creds.me?.lid;
431
- const isRetryResend = Boolean(participant?.jid);
432
- let shouldIncludeDeviceIdentity = isRetryResend;
433
- const statusJid = 'status@broadcast';
576
+ // ADDRESSING CONSISTENCY: Keep envelope addressing as user provided, handle LID migration in encryption
577
+ let shouldIncludeDeviceIdentity = false;
434
578
  const { user, server } = jidDecode(jid);
579
+ const statusJid = 'status@broadcast';
435
580
  const isGroup = server === 'g.us';
436
581
  const isStatus = jid === statusJid;
437
582
  const isLid = server === 'lid';
438
583
  const isNewsletter = server === 'newsletter';
439
- const isGroupOrStatus = isGroup || isStatus;
584
+ // Keep user's original JID choice for envelope addressing
440
585
  const finalJid = jid;
441
- msgId = msgId || generateMessageIDV2(meId);
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');
591
+ }
592
+ else {
593
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
594
+ }
595
+ msgId = msgId || generateMessageIDV2(sock.user?.id);
442
596
  useUserDevicesCache = useUserDevicesCache !== false;
443
597
  useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
444
598
  const participants = [];
445
599
  const destinationJid = !isStatus ? finalJid : statusJid;
446
600
  const binaryNodeContent = [];
447
601
  const devices = [];
448
- let reportingMessage;
449
602
  const meMsg = {
450
603
  deviceSentMessage: {
451
604
  destinationJid,
@@ -455,6 +608,9 @@ export const makeMessagesSocket = (config) => {
455
608
  };
456
609
  const extraAttrs = {};
457
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
458
614
  if (!isGroup && !isStatus) {
459
615
  additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
460
616
  }
@@ -462,7 +618,7 @@ export const makeMessagesSocket = (config) => {
462
618
  devices.push({
463
619
  user,
464
620
  device,
465
- jid: participant.jid
621
+ wireJid: participant.jid // Use the participant JID as wire JID
466
622
  });
467
623
  }
468
624
  await authState.keys.transaction(async () => {
@@ -470,8 +626,8 @@ export const makeMessagesSocket = (config) => {
470
626
  if (mediaType) {
471
627
  extraAttrs['mediatype'] = mediaType;
472
628
  }
473
- const buttonType = getButtonType(message);
474
629
  if (isNewsletter) {
630
+ // Patch message if needed, then encode as plaintext
475
631
  const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
476
632
  const bytes = encodeNewsletterMessage(patched);
477
633
  binaryNodeContent.push({
@@ -493,129 +649,108 @@ export const makeMessagesSocket = (config) => {
493
649
  await sendNode(stanza);
494
650
  return;
495
651
  }
496
- if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
497
- extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
652
+ if (normalizeMessageContent(message)?.pinInChatMessage) {
653
+ extraAttrs['decrypt-fail'] = 'hide';
498
654
  }
499
- if (isGroupOrStatus && !isRetryResend) {
655
+ if (isGroup || isStatus) {
500
656
  const [groupData, senderKeyMap] = await Promise.all([
501
657
  (async () => {
502
- 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?
658
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
503
659
  if (groupData && Array.isArray(groupData?.participants)) {
504
660
  logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
505
661
  }
506
662
  else if (!isStatus) {
507
- groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
663
+ groupData = await groupMetadata(jid);
508
664
  }
509
665
  return groupData;
510
666
  })(),
511
667
  (async () => {
512
668
  if (!participant && !isStatus) {
513
- // what if sender memory is less accurate than the cached metadata
514
- // on participant change in group, we should do sender memory manipulation
515
- 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?
669
+ const result = await authState.keys.get('sender-key-memory', [jid]);
516
670
  return result[jid] || {};
517
671
  }
518
672
  return {};
519
673
  })()
520
674
  ]);
521
- const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
522
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
523
- additionalAttributes = {
524
- ...additionalAttributes,
525
- expiration: groupData.ephemeralDuration.toString()
526
- };
527
- }
528
- if (isStatus && statusJidList) {
529
- participantsList.push(...statusJidList);
530
- }
531
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
532
- devices.push(...additionalDevices);
533
- if (isGroup) {
534
- additionalAttributes = {
535
- ...additionalAttributes,
536
- addressing_mode: groupData?.addressingMode || 'lid'
537
- };
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);
538
689
  }
539
690
  const patched = await patchMessageBeforeSending(message);
540
691
  if (Array.isArray(patched)) {
541
692
  throw new Boom('Per-jid patching is not supported in groups');
542
693
  }
543
694
  const bytes = encodeWAMessage(patched);
544
- reportingMessage = patched;
545
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
695
+ // This should match the group's addressing mode and conversation context
696
+ const groupAddressingMode = groupData?.addressingMode || (isLid ? 'lid' : 'pn');
546
697
  const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
547
698
  const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
548
699
  group: destinationJid,
549
700
  data: bytes,
550
701
  meId: groupSenderIdentity
551
702
  });
552
- const senderKeyRecipients = [];
703
+ const senderKeyJids = [];
704
+ // ensure a connection is established with every device
553
705
  for (const device of devices) {
554
- const deviceJid = device.jid;
706
+ // This preserves the LID migration results from getUSyncDevices
707
+ const deviceJid = device.wireJid;
555
708
  const hasKey = !!senderKeyMap[deviceJid];
556
- if ((!hasKey || !!participant) &&
557
- !isHostedLidUser(deviceJid) &&
558
- !isHostedPnUser(deviceJid) &&
559
- device.device !== 99) {
560
- //todo: revamp all this logic
561
- // 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
562
- senderKeyRecipients.push(deviceJid);
709
+ if (!hasKey || !!participant) {
710
+ senderKeyJids.push(deviceJid);
711
+ // store that this person has had the sender keys sent to them
563
712
  senderKeyMap[deviceJid] = true;
564
713
  }
565
714
  }
566
- if (senderKeyRecipients.length) {
567
- logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
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');
568
719
  const senderKeyMsg = {
569
720
  senderKeyDistributionMessage: {
570
721
  axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
571
722
  groupId: destinationJid
572
723
  }
573
724
  };
574
- const senderKeySessionTargets = senderKeyRecipients;
575
- await assertSessions(senderKeySessionTargets);
576
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
725
+ await assertSessions(senderKeyJids, false);
726
+ const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, extraAttrs);
577
727
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
578
728
  participants.push(...result.nodes);
579
729
  }
580
730
  binaryNodeContent.push({
581
731
  tag: 'enc',
582
- attrs: { v: '2', type: 'skmsg', ...extraAttrs },
732
+ attrs: { v: '2', type: 'skmsg' },
583
733
  content: ciphertext
584
734
  });
585
735
  await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
586
736
  }
587
737
  else {
588
- // ADDRESSING CONSISTENCY: Match own identity to conversation context
589
- // TODO: investigate if this is true
590
- let ownId = meId;
591
- if (isLid && meLid) {
592
- ownId = meLid;
593
- logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
594
- }
595
- else {
596
- logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
597
- }
598
738
  const { user: ownUser } = jidDecode(ownId);
599
739
  if (!participant) {
600
- const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
601
- reportingMessage = Array.isArray(patchedForReporting)
602
- ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
603
- : patchedForReporting;
604
- }
605
- if (!isRetryResend) {
606
740
  const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
607
741
  devices.push({
608
742
  user,
609
743
  device: 0,
610
- jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
744
+ wireJid: jidEncode(user, targetUserServer, 0)
611
745
  });
746
+ // Own user matches conversation addressing mode
612
747
  if (user !== ownUser) {
613
748
  const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
614
749
  const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
615
750
  devices.push({
616
751
  user: ownUserForAddressing,
617
752
  device: 0,
618
- jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
753
+ wireJid: jidEncode(ownUserForAddressing, ownUserServer, 0)
619
754
  });
620
755
  }
621
756
  if (additionalAttributes?.['category'] !== 'peer') {
@@ -626,101 +761,46 @@ export const makeMessagesSocket = (config) => {
626
761
  ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
627
762
  : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
628
763
  // Enumerate devices for sender and target with consistent addressing
629
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
764
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], false, false);
630
765
  devices.push(...sessionDevices);
631
766
  logger.debug({
632
767
  deviceCount: devices.length,
633
- devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
768
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.wireJid)?.server}`)
634
769
  }, 'Device enumeration complete with unified addressing');
635
770
  }
636
771
  }
637
- const allRecipients = [];
638
- const meRecipients = [];
639
- const otherRecipients = [];
772
+ const allJids = [];
773
+ const meJids = [];
774
+ const otherJids = [];
640
775
  const { user: mePnUser } = jidDecode(meId);
641
776
  const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
642
- for (const { user, jid } of devices) {
643
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
777
+ for (const { user, wireJid } of devices) {
778
+ const isExactSenderDevice = wireJid === meId || (meLid && wireJid === meLid);
644
779
  if (isExactSenderDevice) {
645
- logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
780
+ logger.debug({ wireJid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
646
781
  continue;
647
782
  }
648
783
  // Check if this is our device (could match either PN or LID user)
649
- const isMe = user === mePnUser || user === meLidUser;
784
+ const isMe = user === mePnUser || (meLidUser && user === meLidUser);
785
+ const jid = wireJid;
650
786
  if (isMe) {
651
- meRecipients.push(jid);
787
+ meJids.push(jid);
652
788
  }
653
789
  else {
654
- otherRecipients.push(jid);
790
+ otherJids.push(jid);
655
791
  }
656
- allRecipients.push(jid);
792
+ allJids.push(jid);
657
793
  }
658
- await assertSessions(allRecipients);
794
+ await assertSessions([...otherJids, ...meJids], false);
659
795
  const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
660
796
  // For own devices: use DSM if available (1:1 chats only)
661
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
662
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
797
+ createParticipantNodes(meJids, meMsg || message, extraAttrs),
798
+ createParticipantNodes(otherJids, message, extraAttrs, meMsg)
663
799
  ]);
664
800
  participants.push(...meNodes);
665
801
  participants.push(...otherNodes);
666
- if (meRecipients.length > 0 || otherRecipients.length > 0) {
667
- extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
668
- }
669
802
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
670
803
  }
671
- if (isRetryResend) {
672
- const isParticipantLid = isLidUser(participant.jid);
673
- const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
674
- let messageToSend = message;
675
- if (isGroupOrStatus) {
676
- let groupSenderIdentity;
677
- if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
678
- groupSenderIdentity = meLid;
679
- }
680
- else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
681
- groupSenderIdentity = meId;
682
- }
683
- if (groupSenderIdentity) {
684
- try {
685
- const skdm = await signalRepository.getSenderKeyDistributionMessage({
686
- group: destinationJid,
687
- meId: groupSenderIdentity
688
- });
689
- messageToSend = {
690
- ...message,
691
- senderKeyDistributionMessage: {
692
- groupId: destinationJid,
693
- axolotlSenderKeyDistributionMessage: skdm
694
- }
695
- };
696
- }
697
- catch (err) {
698
- logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
699
- }
700
- }
701
- }
702
- const encodedMessageToSend = isMe
703
- ? encodeWAMessage({
704
- deviceSentMessage: {
705
- destinationJid,
706
- message: messageToSend
707
- }
708
- })
709
- : encodeWAMessage(messageToSend);
710
- const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
711
- data: encodedMessageToSend,
712
- jid: participant.jid
713
- });
714
- binaryNodeContent.push({
715
- tag: 'enc',
716
- attrs: {
717
- v: '2',
718
- type,
719
- count: participant.count.toString()
720
- },
721
- content: encryptedContent
722
- });
723
- }
724
804
  if (participants.length) {
725
805
  if (additionalAttributes?.['category'] === 'peer') {
726
806
  const peerNode = participants[0]?.content?.[0];
@@ -774,113 +854,12 @@ export const makeMessagesSocket = (config) => {
774
854
  });
775
855
  logger.debug({ jid }, 'adding device identity');
776
856
  }
777
- if (!isNewsletter &&
778
- !isRetryResend &&
779
- reportingMessage?.messageContextInfo?.messageSecret &&
780
- shouldIncludeReportingToken(reportingMessage)) {
781
- try {
782
- const encoded = encodeWAMessage(reportingMessage);
783
- const reportingKey = {
784
- id: msgId,
785
- fromMe: true,
786
- remoteJid: destinationJid,
787
- participant: participant?.jid
788
- };
789
- const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
790
- if (reportingNode) {
791
- ;
792
- stanza.content.push(reportingNode);
793
- logger.trace({ jid }, 'added reporting token to message');
794
- }
795
- }
796
- catch (error) {
797
- logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
798
- }
799
- }
800
- // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
801
- const isPeerMessage = additionalAttributes?.['category'] === 'peer';
802
- const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
803
- // Resolve destination to LID for tctoken storage — matches Signal session key pattern
804
- const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
805
- const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
806
- const existingTokenEntry = contactTcTokenData[tcTokenJid];
807
- let tcTokenBuffer = existingTokenEntry?.token;
808
- // Treat expired tokens the same as missing — clear from cache
809
- if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
810
- logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
811
- tcTokenBuffer = undefined;
812
- // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
813
- const cleared = existingTokenEntry?.senderTimestamp !== undefined
814
- ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
815
- : null;
816
- try {
817
- await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
818
- }
819
- catch (err) {
820
- logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
821
- }
822
- }
823
- if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
824
- ;
825
- stanza.content.push({
826
- tag: 'tctoken',
827
- attrs: {},
828
- content: tcTokenBuffer
829
- });
830
- }
831
- const hasManualBizNode = Array.isArray(additionalNodes) && additionalNodes.some(n => n?.tag === 'biz');
832
- if (!isNewsletter && buttonType && !isStatus && !hasManualBizNode) {
833
- stanza.content.push(...getAdditionalNode(buttonType));
834
- logger.debug({ msgId, buttonType }, 'adding business node for native list message');
835
- }
836
857
  if (additionalNodes && additionalNodes.length > 0) {
837
858
  ;
838
859
  stanza.content.push(...additionalNodes);
839
860
  }
840
861
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
841
862
  await sendNode(stanza);
842
- // Fire-and-forget: issue our token to the contact AFTER message send.
843
- // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
844
- const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
845
- const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
846
- if (is1on1Send &&
847
- !isProtocolMsg &&
848
- !isBotOrPSA &&
849
- shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
850
- !inFlightTcTokenIssuance.has(tcTokenJid)) {
851
- inFlightTcTokenIssuance.add(tcTokenJid);
852
- const issueTimestamp = unixTimestampSeconds();
853
- const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
854
- resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
855
- .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
856
- .then(async (result) => {
857
- await storeTcTokensFromIqResult({
858
- result,
859
- fallbackJid: tcTokenJid,
860
- keys: authState.keys,
861
- getLIDForPN
862
- });
863
- const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
864
- const currentEntry = currentData[tcTokenJid];
865
- const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
866
- await authState.keys.set({
867
- tctoken: {
868
- [tcTokenJid]: {
869
- token: Buffer.alloc(0),
870
- ...currentEntry,
871
- senderTimestamp: issueTimestamp
872
- },
873
- ...indexWrite
874
- }
875
- });
876
- })
877
- .catch(err => {
878
- logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
879
- })
880
- .finally(() => {
881
- inFlightTcTokenIssuance.delete(tcTokenJid);
882
- });
883
- }
884
863
  // Add message to retry cache if enabled
885
864
  if (messageRetryManager && !participant) {
886
865
  messageRetryManager.addRecentMessage(destinationJid, msgId, message);
@@ -889,24 +868,12 @@ export const makeMessagesSocket = (config) => {
889
868
  return msgId;
890
869
  };
891
870
  const getMessageType = (message) => {
892
- const normalizedMessage = normalizeMessageContent(message);
893
- if (!normalizedMessage)
894
- return 'text';
895
- if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
896
- return 'reaction';
897
- }
898
- if (normalizedMessage.pollCreationMessage ||
899
- normalizedMessage.pollCreationMessageV2 ||
900
- normalizedMessage.pollCreationMessageV3 ||
901
- normalizedMessage.pollUpdateMessage) {
871
+ if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
902
872
  return 'poll';
903
873
  }
904
- if (normalizedMessage.eventMessage) {
874
+ if (message.eventMessage) {
905
875
  return 'event';
906
876
  }
907
- if (getMediaType(normalizedMessage) !== '') {
908
- return 'media';
909
- }
910
877
  return 'text';
911
878
  };
912
879
  const getMediaType = (message) => {
@@ -955,43 +922,9 @@ export const makeMessagesSocket = (config) => {
955
922
  else if (message.groupInviteMessage) {
956
923
  return 'url';
957
924
  }
958
- return '';
959
925
  };
960
- /** Detects WA message types that require an extra `<biz>` engagement node to render natively (e.g. native list messages) */
961
- const getButtonType = (message) => {
962
- if (message?.listMessage) {
963
- return 'list';
964
- }
965
- return undefined;
966
- };
967
- /** Builds the `<biz>` node WhatsApp expects alongside native list/button messages so they render correctly instead of falling back to "unsupported message" */
968
- const getAdditionalNode = (name) => {
969
- if (!name) {
970
- return [];
971
- }
972
- const ts = unixTimestampSeconds() - 77980457;
973
- return [
974
- {
975
- tag: 'biz',
976
- attrs: {
977
- actual_actors: '2',
978
- host_storage: '2',
979
- privacy_mode_ts: `${ts}`
980
- },
981
- content: [
982
- {
983
- tag: 'engagement',
984
- attrs: {
985
- customer_service_state: 'open',
986
- conversation_state: 'open'
987
- }
988
- }
989
- ]
990
- }
991
- ];
992
- };
993
- const issuePrivacyTokens = async (jids, timestamp) => {
994
- const t = (timestamp ?? unixTimestampSeconds()).toString();
926
+ const getPrivacyTokens = async (jids) => {
927
+ const t = unixTimestampSeconds().toString();
995
928
  const result = await query({
996
929
  tag: 'iq',
997
930
  attrs: {
@@ -1017,41 +950,36 @@ export const makeMessagesSocket = (config) => {
1017
950
  return result;
1018
951
  };
1019
952
  const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1020
- const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1021
- registerSocketEndHandler(() => {
1022
- if (!config.userDevicesCache && userDevicesCache.close) {
1023
- userDevicesCache.close();
1024
- }
1025
- mediaConn = undefined;
1026
- if (messageRetryManager) {
1027
- messageRetryManager.clear();
1028
- }
953
+ const extendedMessages = makeExtendedMessageHandlers({
954
+ generateWAMessage,
955
+ generateWAMessageContent,
956
+ generateWAMessageFromContent,
957
+ generateMessageID,
958
+ prepareWAMessageMedia,
959
+ waUploadToServer,
960
+ relayMessage
1029
961
  });
962
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1030
963
  return {
1031
964
  ...sock,
1032
- userDevicesCache,
1033
- devicesMutex,
1034
- issuePrivacyTokens,
965
+ getPrivacyTokens,
1035
966
  assertSessions,
1036
967
  relayMessage,
1037
968
  sendReceipt,
1038
969
  sendReceipts,
1039
970
  readMessages,
1040
971
  refreshMediaConn,
1041
- // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1042
- getMediaHost: () => mediaHost,
1043
972
  waUploadToServer,
1044
973
  fetchPrivacySettings,
1045
974
  sendPeerDataOperationMessage,
1046
975
  createParticipantNodes,
1047
976
  getUSyncDevices,
1048
977
  messageRetryManager,
1049
- updateMemberLabel,
1050
978
  updateMediaMessage: async (message) => {
1051
979
  const content = assertMediaContent(message.message);
1052
980
  const mediaKey = content.mediaKey;
1053
981
  const meId = authState.creds.me.id;
1054
- const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
982
+ const node = await encryptMediaRetryRequest(message.key, mediaKey, meId);
1055
983
  let error = undefined;
1056
984
  await Promise.all([
1057
985
  sendNode(node),
@@ -1063,7 +991,7 @@ export const makeMessagesSocket = (config) => {
1063
991
  }
1064
992
  else {
1065
993
  try {
1066
- const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
994
+ const media = await decryptMediaRetryData(result.media, mediaKey, result.key.id);
1067
995
  if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1068
996
  const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1069
997
  throw new Boom(`Media re-upload failed by device (${resultStr})`, {
@@ -1072,7 +1000,7 @@ export const makeMessagesSocket = (config) => {
1072
1000
  });
1073
1001
  }
1074
1002
  content.directPath = media.directPath;
1075
- content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1003
+ content.url = getUrlFromDirectPath(content.directPath);
1076
1004
  logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1077
1005
  }
1078
1006
  catch (err) {
@@ -1091,6 +1019,29 @@ export const makeMessagesSocket = (config) => {
1091
1019
  },
1092
1020
  sendMessage: async (jid, content, options = {}) => {
1093
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
+ }
1094
1045
  if (typeof content === 'object' &&
1095
1046
  'disappearingMessagesInChat' in content &&
1096
1047
  typeof content['disappearingMessagesInChat'] !== 'undefined' &&
@@ -1111,7 +1062,7 @@ export const makeMessagesSocket = (config) => {
1111
1062
  thumbnailWidth: linkPreviewImageThumbnailWidth,
1112
1063
  fetchOpts: {
1113
1064
  timeout: 3000,
1114
- ...(httpRequestOptions || {})
1065
+ ...(axiosOptions || {})
1115
1066
  },
1116
1067
  logger,
1117
1068
  uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
@@ -1164,6 +1115,9 @@ export const makeMessagesSocket = (config) => {
1164
1115
  }
1165
1116
  });
1166
1117
  }
1118
+ if ('cachedGroupMetadata' in options) {
1119
+ console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
1120
+ }
1167
1121
  await relayMessage(jid, fullMsg.message, {
1168
1122
  messageId: fullMsg.key.id,
1169
1123
  useCachedGroupMetadata: options.useCachedGroupMetadata,
@@ -1172,8 +1126,8 @@ export const makeMessagesSocket = (config) => {
1172
1126
  additionalNodes
1173
1127
  });
1174
1128
  if (config.emitOwnEvents) {
1175
- process.nextTick(async () => {
1176
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1129
+ process.nextTick(() => {
1130
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1177
1131
  });
1178
1132
  }
1179
1133
  return fullMsg;