@rakku-kun/baileys 2.0.20 → 2.0.23

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 (160) hide show
  1. package/WAProto/fix-imports.js +18 -22
  2. package/WAProto/index.js +18 -22
  3. package/lib/Defaults/index.d.ts +7 -8
  4. package/lib/Defaults/index.d.ts.map +1 -1
  5. package/lib/Defaults/index.js +17 -11
  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 +59 -52
  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 +3 -18
  13. package/lib/Socket/business.d.ts.map +1 -1
  14. package/lib/Socket/chats.d.ts +2 -16
  15. package/lib/Socket/chats.d.ts.map +1 -1
  16. package/lib/Socket/chats.js +173 -238
  17. package/lib/Socket/chats.js.map +1 -1
  18. package/lib/Socket/communities.d.ts +3 -18
  19. package/lib/Socket/communities.d.ts.map +1 -1
  20. package/lib/Socket/groups.d.ts +2 -13
  21. package/lib/Socket/groups.d.ts.map +1 -1
  22. package/lib/Socket/groups.js +138 -26
  23. package/lib/Socket/groups.js.map +1 -1
  24. package/lib/Socket/index.d.ts +3 -18
  25. package/lib/Socket/index.d.ts.map +1 -1
  26. package/lib/Socket/messages-recv.d.ts +6 -22
  27. package/lib/Socket/messages-recv.d.ts.map +1 -1
  28. package/lib/Socket/messages-recv.js +645 -736
  29. package/lib/Socket/messages-recv.js.map +1 -1
  30. package/lib/Socket/messages-send.d.ts +2 -18
  31. package/lib/Socket/messages-send.d.ts.map +1 -1
  32. package/lib/Socket/messages-send.js +642 -152
  33. package/lib/Socket/messages-send.js.map +1 -1
  34. package/lib/Socket/newsletter.d.ts +1 -11
  35. package/lib/Socket/newsletter.d.ts.map +1 -1
  36. package/lib/Socket/newsletter.js +92 -3
  37. package/lib/Socket/newsletter.js.map +1 -1
  38. package/lib/Socket/socket.d.ts +2 -6
  39. package/lib/Socket/socket.d.ts.map +1 -1
  40. package/lib/Socket/socket.js +35 -61
  41. package/lib/Socket/socket.js.map +1 -1
  42. package/lib/Types/Auth.d.ts +0 -1
  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 +0 -1
  47. package/lib/Types/Chat.d.ts.map +1 -1
  48. package/lib/Types/Contact.d.ts +0 -2
  49. package/lib/Types/Contact.d.ts.map +1 -1
  50. package/lib/Types/Events.d.ts +1 -20
  51. package/lib/Types/Events.d.ts.map +1 -1
  52. package/lib/Types/GroupMetadata.d.ts +0 -4
  53. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  54. package/lib/Types/Message.d.ts +200 -25
  55. package/lib/Types/Message.d.ts.map +1 -1
  56. package/lib/Types/Message.js.map +1 -1
  57. package/lib/Types/Signal.d.ts +1 -12
  58. package/lib/Types/Signal.d.ts.map +1 -1
  59. package/lib/Types/Socket.d.ts +0 -3
  60. package/lib/Types/Socket.d.ts.map +1 -1
  61. package/lib/Types/State.d.ts +0 -58
  62. package/lib/Types/State.d.ts.map +1 -1
  63. package/lib/Types/State.js +0 -43
  64. package/lib/Types/State.js.map +1 -1
  65. package/lib/Types/index.d.ts +1 -2
  66. package/lib/Types/index.d.ts.map +1 -1
  67. package/lib/Types/index.js +2 -1
  68. package/lib/Types/index.js.map +1 -1
  69. package/lib/Utils/auth-utils.d.ts +0 -5
  70. package/lib/Utils/auth-utils.d.ts.map +1 -1
  71. package/lib/Utils/auth-utils.js +0 -12
  72. package/lib/Utils/auth-utils.js.map +1 -1
  73. package/lib/Utils/browser-utils.d.ts.map +1 -1
  74. package/lib/Utils/browser-utils.js +33 -21
  75. package/lib/Utils/browser-utils.js.map +1 -1
  76. package/lib/Utils/chat-utils.d.ts +1 -31
  77. package/lib/Utils/chat-utils.d.ts.map +1 -1
  78. package/lib/Utils/chat-utils.js +20 -80
  79. package/lib/Utils/chat-utils.js.map +1 -1
  80. package/lib/Utils/decode-wa-message.d.ts +0 -18
  81. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  82. package/lib/Utils/decode-wa-message.js +0 -34
  83. package/lib/Utils/decode-wa-message.js.map +1 -1
  84. package/lib/Utils/event-buffer.d.ts +0 -2
  85. package/lib/Utils/event-buffer.d.ts.map +1 -1
  86. package/lib/Utils/event-buffer.js +1 -49
  87. package/lib/Utils/event-buffer.js.map +1 -1
  88. package/lib/Utils/generics.d.ts +0 -1
  89. package/lib/Utils/generics.d.ts.map +1 -1
  90. package/lib/Utils/generics.js +28 -10
  91. package/lib/Utils/generics.js.map +1 -1
  92. package/lib/Utils/history.d.ts +0 -2
  93. package/lib/Utils/history.d.ts.map +1 -1
  94. package/lib/Utils/history.js +9 -12
  95. package/lib/Utils/history.js.map +1 -1
  96. package/lib/Utils/identity-change-handler.d.ts +0 -7
  97. package/lib/Utils/identity-change-handler.d.ts.map +1 -1
  98. package/lib/Utils/identity-change-handler.js +0 -1
  99. package/lib/Utils/identity-change-handler.js.map +1 -1
  100. package/lib/Utils/index.d.ts +2 -2
  101. package/lib/Utils/index.d.ts.map +1 -1
  102. package/lib/Utils/index.js +7 -2
  103. package/lib/Utils/index.js.map +1 -1
  104. package/lib/Utils/link-preview.js +2 -2
  105. package/lib/Utils/link-preview.js.map +1 -1
  106. package/lib/Utils/message-retry-manager.d.ts +0 -5
  107. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  108. package/lib/Utils/message-retry-manager.js +0 -40
  109. package/lib/Utils/message-retry-manager.js.map +1 -1
  110. package/lib/Utils/messages-media.d.ts +1 -4
  111. package/lib/Utils/messages-media.d.ts.map +1 -1
  112. package/lib/Utils/messages-media.js +173 -131
  113. package/lib/Utils/messages-media.js.map +1 -1
  114. package/lib/Utils/messages.d.ts +1 -0
  115. package/lib/Utils/messages.d.ts.map +1 -1
  116. package/lib/Utils/messages.js +906 -100
  117. package/lib/Utils/messages.js.map +1 -1
  118. package/lib/Utils/process-message.d.ts.map +1 -1
  119. package/lib/Utils/process-message.js +1 -103
  120. package/lib/Utils/process-message.js.map +1 -1
  121. package/lib/Utils/signal.d.ts +0 -13
  122. package/lib/Utils/signal.d.ts.map +1 -1
  123. package/lib/Utils/signal.js +0 -42
  124. package/lib/Utils/signal.js.map +1 -1
  125. package/lib/Utils/sync-action-utils.d.ts.map +1 -1
  126. package/lib/Utils/sync-action-utils.js +0 -1
  127. package/lib/Utils/sync-action-utils.js.map +1 -1
  128. package/lib/Utils/tc-token-utils.d.ts +1 -26
  129. package/lib/Utils/tc-token-utils.d.ts.map +1 -1
  130. package/lib/Utils/tc-token-utils.js +5 -151
  131. package/lib/Utils/tc-token-utils.js.map +1 -1
  132. package/lib/Utils/validate-connection.d.ts.map +1 -1
  133. package/lib/Utils/validate-connection.js +2 -12
  134. package/lib/Utils/validate-connection.js.map +1 -1
  135. package/lib/WABinary/generic-utils.js +15 -0
  136. package/lib/WABinary/index.js +1 -0
  137. package/lib/WABinary/jid-utils.js +2 -0
  138. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -1
  139. package/lib/WAUSync/Protocols/USyncContactProtocol.js +3 -26
  140. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -1
  141. package/lib/WAUSync/Protocols/index.d.ts +0 -1
  142. package/lib/WAUSync/Protocols/index.d.ts.map +1 -1
  143. package/lib/WAUSync/Protocols/index.js +2 -2
  144. package/lib/WAUSync/Protocols/index.js.map +1 -1
  145. package/lib/WAUSync/USyncQuery.d.ts +0 -1
  146. package/lib/WAUSync/USyncQuery.d.ts.map +1 -1
  147. package/lib/WAUSync/USyncQuery.js +2 -6
  148. package/lib/WAUSync/USyncQuery.js.map +1 -1
  149. package/lib/WAUSync/USyncUser.d.ts +0 -4
  150. package/lib/WAUSync/USyncUser.d.ts.map +1 -1
  151. package/lib/WAUSync/USyncUser.js +0 -8
  152. package/lib/WAUSync/USyncUser.js.map +1 -1
  153. package/lib/index.d.ts +1 -1
  154. package/lib/index.js +24 -10
  155. package/package.json +1 -1
  156. package/lib/Store/index.js +0 -4
  157. package/lib/Store/make-cache-manager-store.js +0 -77
  158. package/lib/Store/make-in-memory-store.js +0 -400
  159. package/lib/Store/make-ordered-dictionary.js +0 -78
  160. package/lib/Store/object-repository.js +0 -23
@@ -1,38 +1,22 @@
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, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
4
+ import { DEFAULT_CACHE_TTLS, 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, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
7
+ import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, extractSyncdPatches, generateProfilePicture, getHistoryMsg, 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, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
11
+ import { getBinaryNodeChild, getBinaryNodeChildren, jidDecode, jidEncode, jidNormalizedUser, isLidUser, 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
- 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
- };
14
+ const MAX_SYNC_ATTEMPTS = 2;
21
15
  export const makeChatsSocket = (config) => {
22
16
  const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
23
17
  const sock = makeSocket(config);
24
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
25
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
18
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession } = sock;
26
19
  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
- };
36
20
  let syncState = SyncState.Connecting;
37
21
  /** this mutex ensures that messages are processed in order */
38
22
  const messageMutex = makeMutex();
@@ -44,20 +28,14 @@ export const makeChatsSocket = (config) => {
44
28
  const notificationMutex = makeMutex();
45
29
  // Timeout for AwaitingInitialSync state
46
30
  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();
56
31
  const placeholderResendCache = config.placeholderResendCache ||
57
32
  new NodeCache({
58
33
  stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
59
34
  useClones: false
60
35
  });
36
+ if (!config.placeholderResendCache) {
37
+ config.placeholderResendCache = placeholderResendCache;
38
+ }
61
39
  /** helper function to fetch the given app state sync key */
62
40
  const getAppStateSyncKey = async (keyId) => {
63
41
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
@@ -174,6 +152,23 @@ export const makeChatsSocket = (config) => {
174
152
  }
175
153
  return botList;
176
154
  };
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
+ };
177
172
  const fetchStatus = async (...jids) => {
178
173
  const usyncQuery = new USyncQuery().withStatusProtocol();
179
174
  for (const jid of jids) {
@@ -280,41 +275,23 @@ export const makeChatsSocket = (config) => {
280
275
  return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
281
276
  };
282
277
  const updateBlockStatus = async (jid, action) => {
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 });
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 {}
308
285
  }
286
+ const dhash = String(Date.now());
309
287
  const itemAttrs = {
288
+ dhash,
310
289
  action,
311
- jid: lid
290
+ jid, // selalu PN
312
291
  };
292
+ // Block: tambah pn_jid juga
313
293
  if (action === 'block') {
314
- if (!pn_jid) {
315
- throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
316
- }
317
- itemAttrs.pn_jid = pn_jid;
294
+ itemAttrs.pn_jid = jid;
318
295
  }
319
296
  await query({
320
297
  tag: 'iq',
@@ -425,9 +402,6 @@ export const makeChatsSocket = (config) => {
425
402
  const collectionsToHandle = new Set(collections);
426
403
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
427
404
  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();
431
405
  // keep executing till all collections are done
432
406
  // sometimes a single patch request will not return all the patches (God knows why)
433
407
  // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
@@ -438,7 +412,6 @@ export const makeChatsSocket = (config) => {
438
412
  const result = await authState.keys.get('app-state-sync-version', [name]);
439
413
  let state = result[name];
440
414
  if (state) {
441
- state = ensureLTHashStateVersion(state);
442
415
  if (typeof initialVersionMap[name] === 'undefined') {
443
416
  initialVersionMap[name] = state.version;
444
417
  }
@@ -447,18 +420,14 @@ export const makeChatsSocket = (config) => {
447
420
  state = newLTHashState();
448
421
  }
449
422
  states[name] = state;
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)' : ''}`);
423
+ logger.info(`resyncing ${name} from v${state.version}`);
455
424
  nodes.push({
456
425
  tag: 'collection',
457
426
  attrs: {
458
427
  name,
459
428
  version: state.version.toString(),
460
- // return snapshot if syncing from scratch or forcing after a failed attempt
461
- return_snapshot: (shouldForceSnapshot || !state.version).toString()
429
+ // return snapshot if being synced from scratch
430
+ return_snapshot: (!state.version).toString()
462
431
  }
463
432
  });
464
433
  }
@@ -484,7 +453,7 @@ export const makeChatsSocket = (config) => {
484
453
  const { patches, hasMorePatches, snapshot } = decoded[name];
485
454
  try {
486
455
  if (snapshot) {
487
- const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
456
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
488
457
  states[name] = newState;
489
458
  Object.assign(globalMutationMap, mutationMap);
490
459
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
@@ -507,37 +476,19 @@ export const makeChatsSocket = (config) => {
507
476
  }
508
477
  }
509
478
  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
510
487
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
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);
488
+ if (isIrrecoverableError) {
489
+ // stop retrying
524
490
  collectionsToHandle.delete(name);
525
491
  }
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
- }
541
492
  }
542
493
  }
543
494
  }
@@ -553,21 +504,8 @@ export const makeChatsSocket = (config) => {
553
504
  * type = "image for the high res picture"
554
505
  */
555
506
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
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
- }
507
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
508
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid, baseContent });
571
509
  jid = jidNormalizedUser(jid);
572
510
  const result = await query({
573
511
  tag: 'iq',
@@ -577,7 +515,7 @@ export const makeChatsSocket = (config) => {
577
515
  type: 'get',
578
516
  xmlns: 'w:profile:picture'
579
517
  },
580
- content: buildProfilePictureQueryContent(type, tcTokenContent)
518
+ content: tcTokenContent
581
519
  }, timeoutMs);
582
520
  const child = getBinaryNodeChild(result, 'picture');
583
521
  return child?.attrs?.url;
@@ -643,12 +581,7 @@ export const makeChatsSocket = (config) => {
643
581
  * @param tcToken token for subscription, use if present
644
582
  */
645
583
  const presenceSubscribe = async (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;
584
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid: toJid });
652
585
  return sendNode({
653
586
  tag: 'presence',
654
587
  attrs: {
@@ -669,8 +602,7 @@ export const makeChatsSocket = (config) => {
669
602
  if (tag === 'presence') {
670
603
  presence = {
671
604
  lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
672
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
673
- groupOnlineCount: attrs.count ? +attrs.count : undefined
605
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
674
606
  };
675
607
  }
676
608
  else if (Array.isArray(content)) {
@@ -704,7 +636,7 @@ export const makeChatsSocket = (config) => {
704
636
  logger.debug({ patch: patchCreate }, 'applying app patch');
705
637
  await resyncAppState([name], false);
706
638
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
707
- initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
639
+ initial = currentSyncVersion || newLTHashState();
708
640
  encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
709
641
  const { patch, state } = encodeResult;
710
642
  const node = {
@@ -750,21 +682,22 @@ export const makeChatsSocket = (config) => {
750
682
  }
751
683
  }
752
684
  };
753
- /** fetch AB props */
685
+ /** sending non-abt props may fix QR scan fail if server expects */
754
686
  const fetchProps = async () => {
687
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
755
688
  const resultNode = await query({
756
689
  tag: 'iq',
757
690
  attrs: {
758
691
  to: S_WHATSAPP_NET,
759
- xmlns: 'abt',
692
+ xmlns: 'w',
760
693
  type: 'get'
761
694
  },
762
695
  content: [
763
696
  {
764
697
  tag: 'props',
765
698
  attrs: {
766
- protocol: '1',
767
- ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
699
+ protocol: '2',
700
+ hash: authState?.creds?.lastPropHash || ''
768
701
  }
769
702
  }
770
703
  ]
@@ -779,20 +712,7 @@ export const makeChatsSocket = (config) => {
779
712
  }
780
713
  props = reduceBinaryNodeToDictionary(propsNode, 'prop');
781
714
  }
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');
715
+ logger.debug('fetched props');
796
716
  return props;
797
717
  };
798
718
  /**
@@ -915,6 +835,60 @@ export const makeChatsSocket = (config) => {
915
835
  await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
916
836
  };
917
837
  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
+ // ─────────────────────────────────────────────────────────────────────
918
892
  ev.emit('messages.upsert', { messages: [msg], type });
919
893
  if (!!msg.pushName) {
920
894
  let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
@@ -932,47 +906,6 @@ export const makeChatsSocket = (config) => {
932
906
  ? shouldSyncHistoryMessage(historyMsg) &&
933
907
  PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
934
908
  : 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
- }
976
909
  // State machine: decide on sync and flush
977
910
  if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
978
911
  if (awaitingSyncTimeout) {
@@ -992,8 +925,6 @@ export const makeChatsSocket = (config) => {
992
925
  }
993
926
  const doAppStateSync = async () => {
994
927
  if (syncState === SyncState.Syncing) {
995
- // All collections will be synced, so clear any blocked ones
996
- blockedCollections.clear();
997
928
  logger.info('Doing app state sync');
998
929
  await resyncAppState(ALL_WA_PATCH_NAMES, true);
999
930
  // Sync is complete, go online and flush everything
@@ -1053,11 +984,6 @@ export const makeChatsSocket = (config) => {
1053
984
  }
1054
985
  });
1055
986
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1056
- if (connection === 'close') {
1057
- blockedCollections.clear();
1058
- clearTimeout(historySyncPausedTimeout);
1059
- historySyncPausedTimeout = undefined;
1060
- }
1061
987
  if (connection === 'open') {
1062
988
  if (fireInitQueries) {
1063
989
  executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
@@ -1067,10 +993,6 @@ export const makeChatsSocket = (config) => {
1067
993
  if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1068
994
  return;
1069
995
  }
1070
- historySyncStatus.initialBootstrapComplete = false;
1071
- historySyncStatus.recentSyncComplete = false;
1072
- clearTimeout(historySyncPausedTimeout);
1073
- historySyncPausedTimeout = undefined;
1074
996
  syncState = SyncState.AwaitingInitialSync;
1075
997
  logger.info('Connection is now AwaitingInitialSync, buffering events');
1076
998
  ev.buffer();
@@ -1083,49 +1005,19 @@ export const makeChatsSocket = (config) => {
1083
1005
  setTimeout(() => ev.flush(), 0);
1084
1006
  return;
1085
1007
  }
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.');
1008
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
1096
1009
  if (awaitingSyncTimeout) {
1097
1010
  clearTimeout(awaitingSyncTimeout);
1098
1011
  }
1099
1012
  awaitingSyncTimeout = setTimeout(() => {
1100
1013
  if (syncState === SyncState.AwaitingInitialSync) {
1014
+ // TODO: investigate
1101
1015
  logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1102
1016
  syncState = SyncState.Online;
1103
1017
  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 });
1109
1018
  }
1110
1019
  }, 20000);
1111
1020
  });
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;
1118
- }
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;
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'));
1128
- });
1129
1021
  ev.on('lid-mapping.update', async ({ lid, pn }) => {
1130
1022
  try {
1131
1023
  await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
@@ -1134,20 +1026,54 @@ export const makeChatsSocket = (config) => {
1134
1026
  logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1135
1027
  }
1136
1028
  });
1137
- registerSocketEndHandler(() => {
1138
- if (awaitingSyncTimeout) {
1139
- clearTimeout(awaitingSyncTimeout);
1140
- awaitingSyncTimeout = undefined;
1029
+ ev.on('groups.upsert', async (groups) => {
1030
+ 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
+ }
1141
1047
  }
1142
- if (!config.placeholderResendCache && placeholderResendCache.close) {
1143
- placeholderResendCache.close();
1048
+ catch (error) {
1049
+ logger.warn({ error }, 'groups.upsert: failed to store LID-PN mappings');
1050
+ }
1051
+ });
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
+ }
1070
+ }
1071
+ catch (error) {
1072
+ logger.warn({ error }, 'groups.update: failed to store LID-PN mappings');
1144
1073
  }
1145
- syncState = SyncState.Connecting;
1146
- privacySettings = undefined;
1147
1074
  });
1148
1075
  return {
1149
1076
  ...sock,
1150
- serverProps,
1151
1077
  createCallLink,
1152
1078
  getBotListV2,
1153
1079
  messageMutex,
@@ -1184,7 +1110,6 @@ export const makeChatsSocket = (config) => {
1184
1110
  cleanDirtyBits,
1185
1111
  addOrEditContact,
1186
1112
  removeContact,
1187
- placeholderResendCache,
1188
1113
  addLabel,
1189
1114
  addChatLabel,
1190
1115
  removeChatLabel,
@@ -1192,7 +1117,17 @@ export const makeChatsSocket = (config) => {
1192
1117
  removeMessageLabel,
1193
1118
  star,
1194
1119
  addOrEditQuickReply,
1195
- removeQuickReply
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
1196
1131
  };
1197
1132
  };
1198
1133
  //# sourceMappingURL=chats.js.map