@rakku-kun/baileys 2.0.15 → 2.0.17

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 (175) hide show
  1. package/WAProto/fix-imports.js +22 -18
  2. package/WAProto/index.js +22 -18
  3. package/lib/Defaults/index.d.ts +8 -7
  4. package/lib/Defaults/index.d.ts.map +1 -1
  5. package/lib/Defaults/index.js +11 -17
  6. package/lib/Defaults/index.js.map +1 -1
  7. package/lib/Signal/libsignal.d.ts.map +1 -1
  8. package/lib/Signal/libsignal.js +52 -59
  9. package/lib/Signal/libsignal.js.map +1 -1
  10. package/lib/Signal/lid-mapping.d.ts.map +1 -1
  11. package/lib/Signal/lid-mapping.js.map +1 -1
  12. package/lib/Socket/business.d.ts +18 -3
  13. package/lib/Socket/business.d.ts.map +1 -1
  14. package/lib/Socket/chats.d.ts +16 -2
  15. package/lib/Socket/chats.d.ts.map +1 -1
  16. package/lib/Socket/chats.js +238 -173
  17. package/lib/Socket/chats.js.map +1 -1
  18. package/lib/Socket/communities.d.ts +18 -3
  19. package/lib/Socket/communities.d.ts.map +1 -1
  20. package/lib/Socket/groups.d.ts +13 -2
  21. package/lib/Socket/groups.d.ts.map +1 -1
  22. package/lib/Socket/groups.js +26 -138
  23. package/lib/Socket/groups.js.map +1 -1
  24. package/lib/Socket/index.d.ts +18 -3
  25. package/lib/Socket/index.d.ts.map +1 -1
  26. package/lib/Socket/messages-recv.d.ts +22 -6
  27. package/lib/Socket/messages-recv.d.ts.map +1 -1
  28. package/lib/Socket/messages-recv.js +736 -647
  29. package/lib/Socket/messages-recv.js.map +1 -1
  30. package/lib/Socket/messages-send.d.ts +18 -2
  31. package/lib/Socket/messages-send.d.ts.map +1 -1
  32. package/lib/Socket/messages-send.js +152 -642
  33. package/lib/Socket/messages-send.js.map +1 -1
  34. package/lib/Socket/newsletter.d.ts +11 -1
  35. package/lib/Socket/newsletter.d.ts.map +1 -1
  36. package/lib/Socket/newsletter.js +3 -92
  37. package/lib/Socket/newsletter.js.map +1 -1
  38. package/lib/Socket/socket.d.ts +6 -2
  39. package/lib/Socket/socket.d.ts.map +1 -1
  40. package/lib/Socket/socket.js +61 -35
  41. package/lib/Socket/socket.js.map +1 -1
  42. package/lib/Types/Auth.d.ts +1 -0
  43. package/lib/Types/Auth.d.ts.map +1 -1
  44. package/lib/Types/Call.d.ts +1 -1
  45. package/lib/Types/Call.d.ts.map +1 -1
  46. package/lib/Types/Chat.d.ts +1 -0
  47. package/lib/Types/Chat.d.ts.map +1 -1
  48. package/lib/Types/Contact.d.ts +2 -0
  49. package/lib/Types/Contact.d.ts.map +1 -1
  50. package/lib/Types/Events.d.ts +20 -1
  51. package/lib/Types/Events.d.ts.map +1 -1
  52. package/lib/Types/GroupMetadata.d.ts +4 -0
  53. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  54. package/lib/Types/Message.d.ts +25 -200
  55. package/lib/Types/Message.d.ts.map +1 -1
  56. package/lib/Types/Message.js.map +1 -1
  57. package/lib/Types/Mex.d.ts +141 -0
  58. package/lib/Types/Mex.d.ts.map +1 -0
  59. package/lib/Types/Mex.js +37 -0
  60. package/lib/Types/Mex.js.map +1 -0
  61. package/lib/Types/Signal.d.ts +12 -1
  62. package/lib/Types/Signal.d.ts.map +1 -1
  63. package/lib/Types/Socket.d.ts +3 -0
  64. package/lib/Types/Socket.d.ts.map +1 -1
  65. package/lib/Types/State.d.ts +58 -0
  66. package/lib/Types/State.d.ts.map +1 -1
  67. package/lib/Types/State.js +43 -0
  68. package/lib/Types/State.js.map +1 -1
  69. package/lib/Types/index.d.ts +2 -1
  70. package/lib/Types/index.d.ts.map +1 -1
  71. package/lib/Types/index.js +1 -2
  72. package/lib/Types/index.js.map +1 -1
  73. package/lib/Utils/auth-utils.d.ts +5 -0
  74. package/lib/Utils/auth-utils.d.ts.map +1 -1
  75. package/lib/Utils/auth-utils.js +12 -0
  76. package/lib/Utils/auth-utils.js.map +1 -1
  77. package/lib/Utils/browser-utils.d.ts.map +1 -1
  78. package/lib/Utils/browser-utils.js +21 -33
  79. package/lib/Utils/browser-utils.js.map +1 -1
  80. package/lib/Utils/chat-utils.d.ts +31 -1
  81. package/lib/Utils/chat-utils.d.ts.map +1 -1
  82. package/lib/Utils/chat-utils.js +80 -20
  83. package/lib/Utils/chat-utils.js.map +1 -1
  84. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  85. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  86. package/lib/Utils/companion-reg-client-utils.js +35 -0
  87. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  88. package/lib/Utils/decode-wa-message.d.ts +18 -0
  89. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  90. package/lib/Utils/decode-wa-message.js +34 -0
  91. package/lib/Utils/decode-wa-message.js.map +1 -1
  92. package/lib/Utils/event-buffer.d.ts +2 -0
  93. package/lib/Utils/event-buffer.d.ts.map +1 -1
  94. package/lib/Utils/event-buffer.js +49 -1
  95. package/lib/Utils/event-buffer.js.map +1 -1
  96. package/lib/Utils/generics.d.ts +1 -0
  97. package/lib/Utils/generics.d.ts.map +1 -1
  98. package/lib/Utils/generics.js +10 -28
  99. package/lib/Utils/generics.js.map +1 -1
  100. package/lib/Utils/history.d.ts +2 -0
  101. package/lib/Utils/history.d.ts.map +1 -1
  102. package/lib/Utils/history.js +12 -9
  103. package/lib/Utils/history.js.map +1 -1
  104. package/lib/Utils/identity-change-handler.d.ts +7 -0
  105. package/lib/Utils/identity-change-handler.d.ts.map +1 -1
  106. package/lib/Utils/identity-change-handler.js +1 -0
  107. package/lib/Utils/identity-change-handler.js.map +1 -1
  108. package/lib/Utils/index.d.ts +2 -2
  109. package/lib/Utils/index.d.ts.map +1 -1
  110. package/lib/Utils/index.js +2 -7
  111. package/lib/Utils/index.js.map +1 -1
  112. package/lib/Utils/link-preview.js +2 -2
  113. package/lib/Utils/link-preview.js.map +1 -1
  114. package/lib/Utils/message-retry-manager.d.ts +5 -0
  115. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  116. package/lib/Utils/message-retry-manager.js +40 -0
  117. package/lib/Utils/message-retry-manager.js.map +1 -1
  118. package/lib/Utils/messages-media.d.ts +4 -1
  119. package/lib/Utils/messages-media.d.ts.map +1 -1
  120. package/lib/Utils/messages-media.js +131 -173
  121. package/lib/Utils/messages-media.js.map +1 -1
  122. package/lib/Utils/messages.d.ts +0 -1
  123. package/lib/Utils/messages.d.ts.map +1 -1
  124. package/lib/Utils/messages.js +100 -906
  125. package/lib/Utils/messages.js.map +1 -1
  126. package/lib/Utils/offline-node-processor.d.ts +17 -0
  127. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  128. package/lib/Utils/offline-node-processor.js +40 -0
  129. package/lib/Utils/offline-node-processor.js.map +1 -0
  130. package/lib/Utils/process-message.d.ts.map +1 -1
  131. package/lib/Utils/process-message.js +103 -1
  132. package/lib/Utils/process-message.js.map +1 -1
  133. package/lib/Utils/signal.d.ts +13 -0
  134. package/lib/Utils/signal.d.ts.map +1 -1
  135. package/lib/Utils/signal.js +42 -0
  136. package/lib/Utils/signal.js.map +1 -1
  137. package/lib/Utils/stanza-ack.d.ts +11 -0
  138. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  139. package/lib/Utils/stanza-ack.js +38 -0
  140. package/lib/Utils/stanza-ack.js.map +1 -0
  141. package/lib/Utils/sync-action-utils.d.ts.map +1 -1
  142. package/lib/Utils/sync-action-utils.js +1 -0
  143. package/lib/Utils/sync-action-utils.js.map +1 -1
  144. package/lib/Utils/tc-token-utils.d.ts +26 -1
  145. package/lib/Utils/tc-token-utils.d.ts.map +1 -1
  146. package/lib/Utils/tc-token-utils.js +151 -5
  147. package/lib/Utils/tc-token-utils.js.map +1 -1
  148. package/lib/Utils/validate-connection.d.ts.map +1 -1
  149. package/lib/Utils/validate-connection.js +12 -2
  150. package/lib/Utils/validate-connection.js.map +1 -1
  151. package/lib/WABinary/generic-utils.js +0 -15
  152. package/lib/WABinary/index.js +0 -1
  153. package/lib/WABinary/jid-utils.js +0 -2
  154. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  155. package/lib/WAUSync/Protocols/USyncContactProtocol.js +26 -3
  156. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  157. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  158. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  159. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  160. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  161. package/lib/WAUSync/Protocols/index.d.ts +1 -0
  162. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  163. package/lib/WAUSync/Protocols/index.js +2 -2
  164. package/lib/WAUSync/Protocols/index.js.map +1 -1
  165. package/lib/WAUSync/USyncQuery.d.ts +1 -0
  166. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  167. package/lib/WAUSync/USyncQuery.js +6 -2
  168. package/lib/WAUSync/USyncQuery.js.map +1 -1
  169. package/lib/WAUSync/USyncUser.d.ts +4 -0
  170. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  171. package/lib/WAUSync/USyncUser.js +8 -0
  172. package/lib/WAUSync/USyncUser.js.map +1 -1
  173. package/lib/index.d.ts +1 -1
  174. package/lib/index.js +10 -24
  175. package/package.json +1 -1
@@ -1,22 +1,38 @@
1
1
  import NodeCache from '@cacheable/node-cache';
2
2
  import { Boom } from '@hapi/boom';
3
3
  import { proto } from '../../WAProto/index.js';
4
- import { DEFAULT_CACHE_TTLS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
4
+ import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
5
  import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
6
  import { SyncState } from '../Types/State.js';
7
- import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, extractSyncdPatches, generateProfilePicture, getHistoryMsg, newLTHashState, processSyncAction } from '../Utils/index.js';
7
+ import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
8
8
  import { makeMutex } from '../Utils/make-mutex.js';
9
9
  import processMessage from '../Utils/process-message.js';
10
10
  import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
11
- import { getBinaryNodeChild, getBinaryNodeChildren, jidDecode, jidEncode, jidNormalizedUser, isLidUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
12
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
13
  import { makeSocket } from './socket.js';
14
- const MAX_SYNC_ATTEMPTS = 2;
14
+ export const buildProfilePictureQueryContent = (type, tcTokenContent) => {
15
+ const picture = { tag: 'picture', attrs: { type, query: 'url' } };
16
+ if (tcTokenContent?.length) {
17
+ picture.content = tcTokenContent;
18
+ }
19
+ return [picture];
20
+ };
15
21
  export const makeChatsSocket = (config) => {
16
22
  const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
17
23
  const sock = makeSocket(config);
18
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession } = sock;
24
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
25
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
19
26
  let privacySettings;
27
+ /** Server-assigned AB props for protocol behavior. */
28
+ const serverProps = {
29
+ /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
30
+ privacyTokenOn1to1: true,
31
+ /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
32
+ profilePicPrivacyToken: true,
33
+ /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
34
+ lidTrustedTokenIssueToLid: false
35
+ };
20
36
  let syncState = SyncState.Connecting;
21
37
  /** this mutex ensures that messages are processed in order */
22
38
  const messageMutex = makeMutex();
@@ -28,14 +44,20 @@ export const makeChatsSocket = (config) => {
28
44
  const notificationMutex = makeMutex();
29
45
  // Timeout for AwaitingInitialSync state
30
46
  let awaitingSyncTimeout;
47
+ // In-memory history sync completion tracking (resets on reconnection)
48
+ const historySyncStatus = {
49
+ initialBootstrapComplete: false,
50
+ recentSyncComplete: false
51
+ };
52
+ let historySyncPausedTimeout;
53
+ // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
54
+ // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
55
+ const blockedCollections = new Set();
31
56
  const placeholderResendCache = config.placeholderResendCache ||
32
57
  new NodeCache({
33
58
  stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
59
  useClones: false
35
60
  });
36
- if (!config.placeholderResendCache) {
37
- config.placeholderResendCache = placeholderResendCache;
38
- }
39
61
  /** helper function to fetch the given app state sync key */
40
62
  const getAppStateSyncKey = async (keyId) => {
41
63
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
@@ -152,23 +174,6 @@ export const makeChatsSocket = (config) => {
152
174
  }
153
175
  return botList;
154
176
  };
155
- const getLidUser = async (jid) => {
156
- if (!jid) throw new Boom('Please input a jid user');
157
- if (!jid.endsWith('@s.whatsapp.net') && !jid.endsWith('@lid')) {
158
- throw new Boom('Invalid JID: Not a user JID!');
159
- }
160
- const targetJid = jid.includes('@') ? jid : `${jid}@s.whatsapp.net`;
161
- const usyncQuery = new USyncQuery();
162
- usyncQuery.protocols.push({
163
- name: 'lid',
164
- getQueryElement: () => ({ tag: 'lid', attrs: {}, content: undefined }),
165
- getUserElement: () => null,
166
- parser: (node) => node.attrs.val
167
- });
168
- usyncQuery.users.push({ id: targetJid });
169
- const result = await sock.executeUSyncQuery(usyncQuery);
170
- if (result) return result.list;
171
- };
172
177
  const fetchStatus = async (...jids) => {
173
178
  const usyncQuery = new USyncQuery().withStatusProtocol();
174
179
  for (const jid of jids) {
@@ -275,23 +280,41 @@ export const makeChatsSocket = (config) => {
275
280
  return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
276
281
  };
277
282
  const updateBlockStatus = async (jid, action) => {
278
- jid = jidNormalizedUser(jid);
279
- // Jika input adalah LID, resolve ke PN dulu
280
- if (jid.endsWith('@lid')) {
281
- try {
282
- const pn = await signalRepository?.lidMapping?.getPNForLID?.(jid).catch(() => null);
283
- if (pn) jid = jidNormalizedUser(pn);
284
- } catch {}
283
+ const normalizedJid = jidNormalizedUser(jid);
284
+ let lid;
285
+ let pn_jid;
286
+ if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
287
+ lid = normalizedJid;
288
+ if (action === 'block') {
289
+ const pn = await signalRepository.lidMapping.getPNForLID(normalizedJid);
290
+ if (!pn) {
291
+ throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
292
+ }
293
+ pn_jid = jidNormalizedUser(pn);
294
+ }
295
+ }
296
+ else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
297
+ const mapped = await signalRepository.lidMapping.getLIDForPN(normalizedJid);
298
+ if (!mapped) {
299
+ throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
300
+ }
301
+ lid = mapped;
302
+ if (action === 'block') {
303
+ pn_jid = jidNormalizedUser(normalizedJid);
304
+ }
305
+ }
306
+ else {
307
+ throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
285
308
  }
286
- const dhash = String(Date.now());
287
309
  const itemAttrs = {
288
- dhash,
289
310
  action,
290
- jid, // selalu PN
311
+ jid: lid
291
312
  };
292
- // Block: tambah pn_jid juga
293
313
  if (action === 'block') {
294
- itemAttrs.pn_jid = jid;
314
+ if (!pn_jid) {
315
+ throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
316
+ }
317
+ itemAttrs.pn_jid = pn_jid;
295
318
  }
296
319
  await query({
297
320
  tag: 'iq',
@@ -402,6 +425,9 @@ export const makeChatsSocket = (config) => {
402
425
  const collectionsToHandle = new Set(collections);
403
426
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
404
427
  const attemptsMap = {};
428
+ // collections that failed and need a full snapshot on retry
429
+ // mirrors WA Web's ErrorFatal -> force snapshot behavior
430
+ const forceSnapshotCollections = new Set();
405
431
  // keep executing till all collections are done
406
432
  // sometimes a single patch request will not return all the patches (God knows why)
407
433
  // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
@@ -412,6 +438,7 @@ export const makeChatsSocket = (config) => {
412
438
  const result = await authState.keys.get('app-state-sync-version', [name]);
413
439
  let state = result[name];
414
440
  if (state) {
441
+ state = ensureLTHashStateVersion(state);
415
442
  if (typeof initialVersionMap[name] === 'undefined') {
416
443
  initialVersionMap[name] = state.version;
417
444
  }
@@ -420,14 +447,18 @@ export const makeChatsSocket = (config) => {
420
447
  state = newLTHashState();
421
448
  }
422
449
  states[name] = state;
423
- logger.info(`resyncing ${name} from v${state.version}`);
450
+ const shouldForceSnapshot = forceSnapshotCollections.has(name);
451
+ if (shouldForceSnapshot) {
452
+ forceSnapshotCollections.delete(name);
453
+ }
454
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
424
455
  nodes.push({
425
456
  tag: 'collection',
426
457
  attrs: {
427
458
  name,
428
459
  version: state.version.toString(),
429
- // return snapshot if being synced from scratch
430
- return_snapshot: (!state.version).toString()
460
+ // return snapshot if syncing from scratch or forcing after a failed attempt
461
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
431
462
  }
432
463
  });
433
464
  }
@@ -453,7 +484,7 @@ export const makeChatsSocket = (config) => {
453
484
  const { patches, hasMorePatches, snapshot } = decoded[name];
454
485
  try {
455
486
  if (snapshot) {
456
- const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
487
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
457
488
  states[name] = newState;
458
489
  Object.assign(globalMutationMap, mutationMap);
459
490
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
@@ -476,19 +507,37 @@ export const makeChatsSocket = (config) => {
476
507
  }
477
508
  }
478
509
  catch (error) {
479
- // if retry attempts overshoot
480
- // or key not found
481
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
482
- error.output?.statusCode === 404 ||
483
- error.name === 'TypeError';
484
- logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
485
- await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
486
- // increment number of retries
487
510
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
488
- if (isIrrecoverableError) {
489
- // stop retrying
511
+ const logData = {
512
+ name,
513
+ attempt: attemptsMap[name],
514
+ version: states[name].version,
515
+ statusCode: error.output?.statusCode,
516
+ errorType: error.name,
517
+ error: error.stack
518
+ };
519
+ if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
520
+ // WA Web treats missing keys as "Blocked" — park the collection
521
+ // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
522
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
523
+ blockedCollections.add(name);
490
524
  collectionsToHandle.delete(name);
491
525
  }
526
+ else if (isMissingKeyError(error)) {
527
+ // Retry with a snapshot which may use a different key.
528
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
529
+ forceSnapshotCollections.add(name);
530
+ }
531
+ else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
532
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
533
+ collectionsToHandle.delete(name);
534
+ }
535
+ else {
536
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
537
+ // force a full snapshot on retry to recover from
538
+ // corrupted local state (e.g. LTHash MAC mismatch)
539
+ forceSnapshotCollections.add(name);
540
+ }
492
541
  }
493
542
  }
494
543
  }
@@ -504,8 +553,21 @@ export const makeChatsSocket = (config) => {
504
553
  * type = "image for the high res picture"
505
554
  */
506
555
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
507
- const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
508
- const tcTokenContent = await buildTcTokenFromJid({ authState, jid, baseContent });
556
+ // WA Web only includes tctoken for user JIDs (not groups/newsletters)
557
+ // and never for own profile pic (Chat model for self has no tcToken).
558
+ // Including tctoken for own JID causes the server to never respond.
559
+ const normalizedJid = jidNormalizedUser(jid);
560
+ const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
561
+ const me = authState.creds.me;
562
+ const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
563
+ let tcTokenContent;
564
+ if (serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
565
+ tcTokenContent = await buildTcTokenFromJid({
566
+ authState,
567
+ jid: normalizedJid,
568
+ getLIDForPN
569
+ });
570
+ }
509
571
  jid = jidNormalizedUser(jid);
510
572
  const result = await query({
511
573
  tag: 'iq',
@@ -515,7 +577,7 @@ export const makeChatsSocket = (config) => {
515
577
  type: 'get',
516
578
  xmlns: 'w:profile:picture'
517
579
  },
518
- content: tcTokenContent
580
+ content: buildProfilePictureQueryContent(type, tcTokenContent)
519
581
  }, timeoutMs);
520
582
  const child = getBinaryNodeChild(result, 'picture');
521
583
  return child?.attrs?.url;
@@ -581,7 +643,12 @@ export const makeChatsSocket = (config) => {
581
643
  * @param tcToken token for subscription, use if present
582
644
  */
583
645
  const presenceSubscribe = async (toJid) => {
584
- const tcTokenContent = await buildTcTokenFromJid({ authState, jid: toJid });
646
+ // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
647
+ const normalizedToJid = jidNormalizedUser(toJid);
648
+ const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid);
649
+ const tcTokenContent = isUserJid
650
+ ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN })
651
+ : undefined;
585
652
  return sendNode({
586
653
  tag: 'presence',
587
654
  attrs: {
@@ -602,7 +669,8 @@ export const makeChatsSocket = (config) => {
602
669
  if (tag === 'presence') {
603
670
  presence = {
604
671
  lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
605
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
672
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
673
+ groupOnlineCount: attrs.count ? +attrs.count : undefined
606
674
  };
607
675
  }
608
676
  else if (Array.isArray(content)) {
@@ -636,7 +704,7 @@ export const makeChatsSocket = (config) => {
636
704
  logger.debug({ patch: patchCreate }, 'applying app patch');
637
705
  await resyncAppState([name], false);
638
706
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
639
- initial = currentSyncVersion || newLTHashState();
707
+ initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
640
708
  encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
641
709
  const { patch, state } = encodeResult;
642
710
  const node = {
@@ -682,22 +750,21 @@ export const makeChatsSocket = (config) => {
682
750
  }
683
751
  }
684
752
  };
685
- /** sending non-abt props may fix QR scan fail if server expects */
753
+ /** fetch AB props */
686
754
  const fetchProps = async () => {
687
- //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
688
755
  const resultNode = await query({
689
756
  tag: 'iq',
690
757
  attrs: {
691
758
  to: S_WHATSAPP_NET,
692
- xmlns: 'w',
759
+ xmlns: 'abt',
693
760
  type: 'get'
694
761
  },
695
762
  content: [
696
763
  {
697
764
  tag: 'props',
698
765
  attrs: {
699
- protocol: '2',
700
- hash: authState?.creds?.lastPropHash || ''
766
+ protocol: '1',
767
+ ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
701
768
  }
702
769
  }
703
770
  ]
@@ -712,7 +779,20 @@ export const makeChatsSocket = (config) => {
712
779
  }
713
780
  props = reduceBinaryNodeToDictionary(propsNode, 'prop');
714
781
  }
715
- logger.debug('fetched props');
782
+ // Extract protocol-relevant AB props (only the ones we need)
783
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
784
+ if (privacyTokenProp !== undefined) {
785
+ serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
786
+ }
787
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
788
+ if (profilePicProp !== undefined) {
789
+ serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
790
+ }
791
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
792
+ if (lidIssueProp !== undefined) {
793
+ serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
794
+ }
795
+ logger.debug({ serverProps }, 'fetched props');
716
796
  return props;
717
797
  };
718
798
  /**
@@ -835,60 +915,6 @@ export const makeChatsSocket = (config) => {
835
915
  await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
836
916
  };
837
917
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
838
- // ── Auto-inject isAdmin, isBotAdmin, metadata ─────────────────────────
839
- try {
840
- const remoteJid = msg.key?.remoteJid || '';
841
- const isGroup = remoteJid.endsWith('@g.us');
842
- if (isGroup) {
843
- const _normalizeJid = (jid) => {
844
- if (!jid) return null;
845
- try { return jidNormalizedUser(jid).split('@')[0]; }
846
- catch { return String(jid).split('@')[0]; }
847
- };
848
- // Fetch metadata (pakai cache jika tersedia)
849
- let meta = null;
850
- try { meta = await sock.groupMetadata(remoteJid); } catch {}
851
- if (meta && Array.isArray(meta.participants)) {
852
- msg.metadata = meta;
853
- const botJid = authState.creds?.me?.id;
854
- const senderJid = msg.key.fromMe
855
- ? authState.creds?.me?.id
856
- : (msg.key.participant || remoteJid);
857
- const senderNorm = _normalizeJid(senderJid);
858
- const botNorm = _normalizeJid(botJid);
859
- // isAdmin
860
- msg.isAdmin = meta.participants.some(p => {
861
- const pid = _normalizeJid(p.jid || p.id || p.lid);
862
- return pid === senderNorm && (p.admin === 'admin' || p.admin === 'superadmin');
863
- });
864
- // isBotAdmin: via m.isBotAdmin jika sudah di-set
865
- let isBotAdmin = typeof msg.isBotAdmin === 'boolean' ? msg.isBotAdmin : false;
866
- // fallback via owner
867
- if (!isBotAdmin) {
868
- const owners = [meta.owner, meta.subjectOwner, meta.ownerPn]
869
- .filter(Boolean).map(_normalizeJid);
870
- if (owners.includes(botNorm)) isBotAdmin = true;
871
- }
872
- // fallback via participants
873
- if (!isBotAdmin) {
874
- isBotAdmin = meta.participants.some(p => {
875
- const pid = _normalizeJid(p.jid || p.id || p.lid);
876
- return pid === botNorm && (p.admin === 'admin' || p.admin === 'superadmin');
877
- });
878
- }
879
- msg.isBotAdmin = isBotAdmin;
880
- } else {
881
- msg.metadata = {};
882
- msg.isAdmin = false;
883
- msg.isBotAdmin = false;
884
- }
885
- } else {
886
- msg.metadata = {};
887
- msg.isAdmin = false;
888
- msg.isBotAdmin = false;
889
- }
890
- } catch {}
891
- // ─────────────────────────────────────────────────────────────────────
892
918
  ev.emit('messages.upsert', { messages: [msg], type });
893
919
  if (!!msg.pushName) {
894
920
  let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
@@ -906,6 +932,47 @@ export const makeChatsSocket = (config) => {
906
932
  ? shouldSyncHistoryMessage(historyMsg) &&
907
933
  PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
908
934
  : false;
935
+ if (historyMsg && shouldProcessHistoryMsg) {
936
+ const syncType = historyMsg.syncType;
937
+ // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
938
+ if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
939
+ !historySyncStatus.initialBootstrapComplete) {
940
+ historySyncStatus.initialBootstrapComplete = true;
941
+ ev.emit('messaging-history.status', {
942
+ syncType,
943
+ status: 'complete',
944
+ explicit: true
945
+ });
946
+ }
947
+ // RECENT with progress === 100 — explicit completion
948
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT &&
949
+ historyMsg.progress === 100 &&
950
+ !historySyncStatus.recentSyncComplete) {
951
+ historySyncStatus.recentSyncComplete = true;
952
+ clearTimeout(historySyncPausedTimeout);
953
+ historySyncPausedTimeout = undefined;
954
+ ev.emit('messaging-history.status', {
955
+ syncType,
956
+ status: 'complete',
957
+ explicit: true
958
+ });
959
+ }
960
+ // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
961
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
962
+ clearTimeout(historySyncPausedTimeout);
963
+ historySyncPausedTimeout = setTimeout(() => {
964
+ if (!historySyncStatus.recentSyncComplete) {
965
+ historySyncStatus.recentSyncComplete = true;
966
+ ev.emit('messaging-history.status', {
967
+ syncType: proto.HistorySync.HistorySyncType.RECENT,
968
+ status: 'paused',
969
+ explicit: false
970
+ });
971
+ }
972
+ historySyncPausedTimeout = undefined;
973
+ }, HISTORY_SYNC_PAUSED_TIMEOUT_MS);
974
+ }
975
+ }
909
976
  // State machine: decide on sync and flush
910
977
  if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
911
978
  if (awaitingSyncTimeout) {
@@ -925,6 +992,8 @@ export const makeChatsSocket = (config) => {
925
992
  }
926
993
  const doAppStateSync = async () => {
927
994
  if (syncState === SyncState.Syncing) {
995
+ // All collections will be synced, so clear any blocked ones
996
+ blockedCollections.clear();
928
997
  logger.info('Doing app state sync');
929
998
  await resyncAppState(ALL_WA_PATCH_NAMES, true);
930
999
  // Sync is complete, go online and flush everything
@@ -984,6 +1053,11 @@ export const makeChatsSocket = (config) => {
984
1053
  }
985
1054
  });
986
1055
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1056
+ if (connection === 'close') {
1057
+ blockedCollections.clear();
1058
+ clearTimeout(historySyncPausedTimeout);
1059
+ historySyncPausedTimeout = undefined;
1060
+ }
987
1061
  if (connection === 'open') {
988
1062
  if (fireInitQueries) {
989
1063
  executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
@@ -993,6 +1067,10 @@ export const makeChatsSocket = (config) => {
993
1067
  if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
994
1068
  return;
995
1069
  }
1070
+ historySyncStatus.initialBootstrapComplete = false;
1071
+ historySyncStatus.recentSyncComplete = false;
1072
+ clearTimeout(historySyncPausedTimeout);
1073
+ historySyncPausedTimeout = undefined;
996
1074
  syncState = SyncState.AwaitingInitialSync;
997
1075
  logger.info('Connection is now AwaitingInitialSync, buffering events');
998
1076
  ev.buffer();
@@ -1005,75 +1083,71 @@ export const makeChatsSocket = (config) => {
1005
1083
  setTimeout(() => ev.flush(), 0);
1006
1084
  return;
1007
1085
  }
1008
- logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
1086
+ // On reconnection (accountSyncCounter > 0), the server does not push
1087
+ // history sync notifications — the device already has its data.
1088
+ // Skip the 20s wait and go online immediately.
1089
+ if (authState.creds.accountSyncCounter > 0) {
1090
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
1091
+ syncState = SyncState.Online;
1092
+ setTimeout(() => ev.flush(), 0);
1093
+ return;
1094
+ }
1095
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.');
1009
1096
  if (awaitingSyncTimeout) {
1010
1097
  clearTimeout(awaitingSyncTimeout);
1011
1098
  }
1012
1099
  awaitingSyncTimeout = setTimeout(() => {
1013
1100
  if (syncState === SyncState.AwaitingInitialSync) {
1014
- // TODO: investigate
1015
1101
  logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1016
1102
  syncState = SyncState.Online;
1017
1103
  ev.flush();
1104
+ // Increment so subsequent reconnections skip the 20s wait.
1105
+ // Late-arriving history is still processed via processMessage
1106
+ // regardless of the state machine phase.
1107
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1108
+ ev.emit('creds.update', { accountSyncCounter });
1018
1109
  }
1019
1110
  }, 20000);
1020
1111
  });
1021
- ev.on('lid-mapping.update', async ({ lid, pn }) => {
1022
- try {
1023
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1112
+ // When an app state sync key arrives (myAppStateKeyId is set) and there are
1113
+ // collections blocked on a missing key, trigger a re-sync for just those collections.
1114
+ // This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
1115
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
1116
+ if (!myAppStateKeyId || blockedCollections.size === 0) {
1117
+ return;
1024
1118
  }
1025
- catch (error) {
1026
- logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1119
+ // If we're in the middle of a full sync, doAppStateSync handles all collections
1120
+ if (syncState === SyncState.Syncing) {
1121
+ blockedCollections.clear();
1122
+ return;
1027
1123
  }
1124
+ const collections = [...blockedCollections];
1125
+ blockedCollections.clear();
1126
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
1127
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
1028
1128
  });
1029
- ev.on('groups.upsert', async (groups) => {
1129
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
1030
1130
  try {
1031
- const mappings = [];
1032
- for (const group of groups) {
1033
- for (const p of group.participants || []) {
1034
- const lidJid = p.id?.endsWith('@lid') ? p.id : p.lid;
1035
- const pnJid = p.phoneNumber?.endsWith('@s.whatsapp.net')
1036
- ? p.phoneNumber
1037
- : p.id?.endsWith('@s.whatsapp.net') ? p.id : undefined;
1038
- if (lidJid && pnJid) {
1039
- mappings.push({ lid: lidJid, pn: pnJid });
1040
- }
1041
- }
1042
- }
1043
- if (mappings.length > 0) {
1044
- await signalRepository.lidMapping.storeLIDPNMappings(mappings);
1045
- logger.debug({ count: mappings.length }, 'groups.upsert: stored LID-PN mappings from participants');
1046
- }
1131
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1047
1132
  }
1048
1133
  catch (error) {
1049
- logger.warn({ error }, 'groups.upsert: failed to store LID-PN mappings');
1134
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1050
1135
  }
1051
1136
  });
1052
- ev.on('groups.update', async (updates) => {
1053
- try {
1054
- const mappings = [];
1055
- for (const update of updates) {
1056
- for (const p of update.participants || []) {
1057
- const lidJid = p.id?.endsWith('@lid') ? p.id : p.lid;
1058
- const pnJid = p.phoneNumber?.endsWith('@s.whatsapp.net')
1059
- ? p.phoneNumber
1060
- : p.id?.endsWith('@s.whatsapp.net') ? p.id : undefined;
1061
- if (lidJid && pnJid) {
1062
- mappings.push({ lid: lidJid, pn: pnJid });
1063
- }
1064
- }
1065
- }
1066
- if (mappings.length > 0) {
1067
- await signalRepository.lidMapping.storeLIDPNMappings(mappings);
1068
- logger.debug({ count: mappings.length }, 'groups.update: stored LID-PN mappings from participants');
1069
- }
1137
+ registerSocketEndHandler(() => {
1138
+ if (awaitingSyncTimeout) {
1139
+ clearTimeout(awaitingSyncTimeout);
1140
+ awaitingSyncTimeout = undefined;
1070
1141
  }
1071
- catch (error) {
1072
- logger.warn({ error }, 'groups.update: failed to store LID-PN mappings');
1142
+ if (!config.placeholderResendCache && placeholderResendCache.close) {
1143
+ placeholderResendCache.close();
1073
1144
  }
1145
+ syncState = SyncState.Connecting;
1146
+ privacySettings = undefined;
1074
1147
  });
1075
1148
  return {
1076
1149
  ...sock,
1150
+ serverProps,
1077
1151
  createCallLink,
1078
1152
  getBotListV2,
1079
1153
  messageMutex,
@@ -1110,6 +1184,7 @@ export const makeChatsSocket = (config) => {
1110
1184
  cleanDirtyBits,
1111
1185
  addOrEditContact,
1112
1186
  removeContact,
1187
+ placeholderResendCache,
1113
1188
  addLabel,
1114
1189
  addChatLabel,
1115
1190
  removeChatLabel,
@@ -1117,17 +1192,7 @@ export const makeChatsSocket = (config) => {
1117
1192
  removeMessageLabel,
1118
1193
  star,
1119
1194
  addOrEditQuickReply,
1120
- removeQuickReply,
1121
- clearMessage: (jid, key, timeStamp) => {
1122
- return chatModify({
1123
- delete: true,
1124
- lastMessages: [{
1125
- key: key,
1126
- messageTimestamp: timeStamp
1127
- }]
1128
- }, jid);
1129
- },
1130
- getLidUser
1195
+ removeQuickReply
1131
1196
  };
1132
1197
  };
1133
1198
  //# sourceMappingURL=chats.js.map