kage-baileys 3.0.6 → 3.2.4

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 (217) hide show
  1. package/Example/connection.cjs +4 -0
  2. package/README.MD +4726 -48
  3. package/README.md +5941 -0
  4. package/WAProto/WAProto.proto +3395 -415
  5. package/WAProto/compat.cjs +12 -0
  6. package/WAProto/index.d.ts +47104 -19888
  7. package/WAProto/index.js +131979 -57361
  8. package/lib/Addon/http-error.js +43 -0
  9. package/lib/Addon/index.js +32 -0
  10. package/lib/Addon/keyed-db.js +250 -0
  11. package/lib/Addon/link-preview.js +82 -0
  12. package/lib/Defaults/baileys-version.json +3 -0
  13. package/lib/Defaults/connection.js +110 -0
  14. package/lib/Defaults/constants.js +156 -0
  15. package/lib/Defaults/history.js +46 -0
  16. package/lib/Defaults/index.js +230 -0
  17. package/lib/Defaults/media.js +104 -0
  18. package/lib/Defaults/phonenumber-mcc.json +223 -0
  19. package/lib/Defaults/prefix.js +44 -0
  20. package/lib/Extensions/business-advanced.js +382 -0
  21. package/lib/Extensions/business.js +159 -0
  22. package/lib/Extensions/chats-advanced.js +1106 -0
  23. package/lib/Extensions/chats.js +349 -0
  24. package/lib/Extensions/communities-advanced.js +430 -0
  25. package/lib/Extensions/community.js +94 -0
  26. package/lib/Extensions/groups-advanced.js +343 -0
  27. package/lib/Extensions/index.js +30 -0
  28. package/lib/Extensions/messages-recv-advanced.js +1690 -0
  29. package/lib/Extensions/messages-send-advanced.js +622 -0
  30. package/lib/Extensions/messages-send.js +1380 -0
  31. package/lib/Extensions/newsletter-advanced.js +228 -0
  32. package/lib/Extensions/newsletter.js +72 -0
  33. package/lib/Extensions/socket.js +389 -0
  34. package/lib/Modded/message_builder.js +2084 -4
  35. package/lib/Signal/Group/ciphertext-message.js +54 -0
  36. package/lib/Signal/Group/group-session-builder.js +124 -0
  37. package/lib/Signal/Group/group_cipher.js +216 -0
  38. package/lib/Signal/Group/index.js +124 -0
  39. package/lib/Signal/Group/keyhelper.js +108 -0
  40. package/lib/Signal/Group/sender-chain-key.js +83 -0
  41. package/lib/Signal/Group/sender-key-distribution-message.js +157 -0
  42. package/lib/Signal/Group/sender-key-message.js +166 -0
  43. package/lib/Signal/Group/sender-key-name.js +130 -0
  44. package/lib/Signal/Group/sender-key-record.js +113 -0
  45. package/lib/Signal/Group/sender-key-state.js +208 -0
  46. package/lib/Signal/Group/sender-message-key.js +82 -0
  47. package/lib/Signal/libsignal.js +935 -0
  48. package/lib/Signal/lid-mapping.js +545 -1
  49. package/lib/Socket/Client/index.js +60 -0
  50. package/lib/Socket/Client/types.js +51 -0
  51. package/lib/Socket/Client/websocket.js +152 -0
  52. package/lib/Socket/business.js +831 -0
  53. package/lib/Socket/chats.js +2535 -49
  54. package/lib/Socket/communities.js +450 -1
  55. package/lib/Socket/community.js +1022 -0
  56. package/lib/Socket/dugong.js +1 -1
  57. package/lib/Socket/groups.js +747 -0
  58. package/lib/Socket/index.js +60 -2
  59. package/lib/Socket/messages-recv.js +3450 -5
  60. package/lib/Socket/messages-send.js +3123 -0
  61. package/lib/Socket/mex.js +126 -1
  62. package/lib/Socket/newsletter.js +465 -0
  63. package/lib/Socket/socket.js +2217 -1
  64. package/lib/Store/index.js +79 -0
  65. package/lib/Store/make-cache-manager-store.js +186 -0
  66. package/lib/Store/make-in-memory-store.js +878 -0
  67. package/lib/Store/make-ordered-dictionary.js +187 -0
  68. package/lib/Store/object-repository.js +78 -0
  69. package/lib/Types/Auth.js +25 -0
  70. package/lib/Types/Bussines.js +25 -1
  71. package/lib/Types/Call.js +25 -0
  72. package/lib/Types/Chat.js +39 -0
  73. package/lib/Types/Contact.js +25 -0
  74. package/lib/Types/Events.js +25 -0
  75. package/lib/Types/GroupMetadata.js +25 -0
  76. package/lib/Types/Label.js +76 -0
  77. package/lib/Types/LabelAssociation.js +40 -0
  78. package/lib/Types/Message.js +57 -0
  79. package/lib/Types/Mex.js +56 -1
  80. package/lib/Types/MexUpdates.js +46 -0
  81. package/lib/Types/Newsletter.js +56 -0
  82. package/lib/Types/Product.js +25 -0
  83. package/lib/Types/RichType.js +23 -0
  84. package/lib/Types/Signal.js +25 -0
  85. package/lib/Types/Socket.js +25 -0
  86. package/lib/Types/State.js +92 -0
  87. package/lib/Types/USync.js +25 -0
  88. package/lib/Types/index.js +133 -0
  89. package/lib/Utils/auth-utils.js +703 -0
  90. package/lib/Utils/automation-tools.js +51 -16
  91. package/lib/Utils/baileys-event-stream.js +146 -0
  92. package/lib/Utils/browser-utils.js +95 -0
  93. package/lib/Utils/business.js +525 -0
  94. package/lib/Utils/chat-utils.js +1861 -0
  95. package/lib/Utils/companion-reg-client-utils.js +55 -1
  96. package/lib/Utils/crypto.js +355 -0
  97. package/lib/Utils/decode-wa-message.js +709 -0
  98. package/lib/Utils/event-buffer.js +1323 -8
  99. package/lib/Utils/generics.js +945 -1
  100. package/lib/Utils/history.js +266 -0
  101. package/lib/Utils/identity-change-handler.js +62 -1
  102. package/lib/Utils/index.js +114 -0
  103. package/lib/Utils/link-preview.js +179 -0
  104. package/lib/Utils/logger.js +42 -0
  105. package/lib/Utils/lt-hash.js +73 -0
  106. package/lib/Utils/make-mutex.js +104 -0
  107. package/lib/Utils/message-inspector.js +110 -0
  108. package/lib/Utils/message-retry-manager.js +507 -2
  109. package/lib/Utils/messages-media.js +1931 -1
  110. package/lib/Utils/messages.js +3748 -0
  111. package/lib/Utils/noise-handler.js +423 -0
  112. package/lib/Utils/offline-node-processor.js +53 -1
  113. package/lib/Utils/pre-key-manager.js +255 -1
  114. package/lib/Utils/process-message.js +1592 -0
  115. package/lib/Utils/reporting-utils.js +272 -1
  116. package/lib/Utils/rich-message-utils.js +377 -0
  117. package/lib/Utils/rich-messages.js +1 -1
  118. package/lib/Utils/signal.js +437 -0
  119. package/lib/Utils/stanza-ack.js +51 -1
  120. package/lib/Utils/status-refresh.js +37 -0
  121. package/lib/Utils/status-tools.js +4 -2
  122. package/lib/Utils/sync-action-utils.js +63 -1
  123. package/lib/Utils/tc-token-utils.js +185 -1
  124. package/lib/Utils/terminal-banner.js +31 -0
  125. package/lib/Utils/use-multi-file-auth-state.js +271 -0
  126. package/lib/Utils/use-single-file-auth-state.js +108 -0
  127. package/lib/Utils/use-sqlite-auth-state.js +142 -0
  128. package/lib/Utils/validate-connection.js +497 -1
  129. package/lib/Utils/view-once-compat.js +13 -5
  130. package/lib/VoIP/audio-feeder.js +150 -0
  131. package/lib/VoIP/index.js +289 -0
  132. package/lib/VoIP/relay-transport.js +608 -0
  133. package/lib/VoIP/signaling.js +583 -0
  134. package/lib/VoIP/types.js +30 -0
  135. package/lib/VoIP/wasm-engine.js +1261 -2
  136. package/lib/VoIP/worker-bootstrap.js +1090 -2
  137. package/lib/WABinary/constants.js +2805 -0
  138. package/lib/WABinary/decode.js +649 -2
  139. package/lib/WABinary/encode.js +564 -2
  140. package/lib/WABinary/generic-utils.js +401 -0
  141. package/lib/WABinary/index.js +82 -0
  142. package/lib/WABinary/jid-utils.js +290 -0
  143. package/lib/WABinary/types.js +25 -0
  144. package/lib/WAM/BinaryInfo.js +50 -0
  145. package/lib/WAM/constants.js +45747 -0
  146. package/lib/WAM/encode.js +393 -0
  147. package/lib/WAM/index.js +78 -0
  148. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +135 -0
  149. package/lib/WAUSync/Protocols/USyncContactProtocol.js +110 -0
  150. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +142 -0
  151. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +85 -0
  152. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +69 -0
  153. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +107 -0
  154. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +38 -1
  155. package/lib/WAUSync/Protocols/index.js +83 -0
  156. package/lib/WAUSync/USyncQuery.js +241 -2
  157. package/lib/WAUSync/USyncUser.js +86 -0
  158. package/lib/WAUSync/index.js +78 -0
  159. package/lib/assets/wasm/loader.js +1875 -1
  160. package/lib/assets/wasm/worker-modules.js +11047 -1
  161. package/lib/index.d.ts +126 -0
  162. package/lib/index.js +53 -21
  163. package/lib/index.mjs +437 -0
  164. package/licenses/upstream-MIT.txt +22 -0
  165. package/maintenance/api-coverage.json +1642 -0
  166. package/maintenance/archivos-sha256.json +207 -0
  167. package/maintenance/consumer-validation.log +3 -0
  168. package/maintenance/dependency-audit.json +4 -4
  169. package/maintenance/extension-inventory.json +57 -0
  170. package/maintenance/protocol-update.json +1101 -0
  171. package/maintenance/protocol-wire-audit.json +4 -0
  172. package/maintenance/reference-socket-surface.json +209 -0
  173. package/maintenance/resumen-validacion.json +50 -0
  174. package/maintenance/validation.log +2725 -0
  175. package/maintenance/verification.json +566 -0
  176. package/package.json +107 -9
  177. package/scripts/check-imports.cjs +10 -0
  178. package/scripts/check-package.cjs +40 -0
  179. package/scripts/check-syntax.cjs +1 -1
  180. package/scripts/generate-protobuf.cjs +6 -1
  181. package/scripts/generate-public-types.cjs +9 -0
  182. package/scripts/kage-base64-fix.cjs +45 -0
  183. package/scripts/maintenance.cjs +10 -0
  184. package/test/advanced.test.cjs +24 -0
  185. package/test/base64-fix.test.cjs +49 -0
  186. package/test/maintenance.test.cjs +1 -1
  187. package/test/npm-publication.test.cjs +141 -0
  188. package/test/recepcion-reparada.test.cjs +98 -0
  189. package/test/resilience-binary.test.cjs +69 -0
  190. package/test/resilience-transport.test.cjs +34 -0
  191. package/test/types.test.ts +5 -0
  192. package/test/upgrade.test.cjs +104 -0
  193. package/tsconfig.json +20 -0
  194. package/WAProto/p.html +0 -1
  195. package/lib/KageExtra/Modded/message_builder.js +0 -2330
  196. package/lib/KageExtra/VoIP/audio-feeder.js +0 -136
  197. package/lib/KageExtra/VoIP/index.js +0 -282
  198. package/lib/KageExtra/VoIP/relay-transport.js +0 -559
  199. package/lib/KageExtra/VoIP/signaling.js +0 -603
  200. package/lib/KageExtra/VoIP/types.js +0 -17
  201. package/lib/KageExtra/VoIP/wasm-engine.js +0 -1214
  202. package/lib/KageExtra/VoIP/worker-bootstrap.js +0 -1042
  203. package/lib/KageExtra/assets/wasm/loader.js +0 -5
  204. package/lib/KageExtra/assets/wasm/whatsapp.wasm +0 -0
  205. package/lib/KageExtra/assets/wasm/worker-modules.js +0 -273
  206. package/lib/KageExtra/index.js +0 -3
  207. package/lib/KageExtra/package.json +0 -1
  208. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  209. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  210. package/maintenance/revision-full-check.txt +0 -1097
  211. package/maintenance/revision-library-tests.tap +0 -1088
  212. package/maintenance/revision-protobuf.txt +0 -5
  213. package/maintenance/revision-syntax.txt +0 -5
  214. package/maintenance/schema-coverage.json +0 -23
  215. package/maintenance/schema-merge.json +0 -30
  216. package/maintenance/validation-node20.txt +0 -191
  217. package/maintenance/validation-node22.txt +0 -237
@@ -29,7 +29,17 @@ const makeChatsSocket = (config) => {
29
29
  const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, } = sock;
30
30
  let privacySettings;
31
31
  let syncState = SyncState.Connecting;
32
- let needToFlushWithAppStateSync = false;
32
+ let releaseInitialSync;
33
+ let initialAppStateJob;
34
+ let socketClosed = false;
35
+ const releaseInitialEvents = () => {
36
+ clearTimeout(awaitingSyncTimeout);
37
+ awaitingSyncTimeout = undefined;
38
+ syncState = SyncState.Online;
39
+ const release = releaseInitialSync;
40
+ releaseInitialSync = undefined;
41
+ release?.();
42
+ };
33
43
  let pendingAppStateSync = false;
34
44
  let awaitingSyncTimeout;
35
45
  const processingMutex = (0, make_mutex_1.makeMutex)();
@@ -361,7 +371,7 @@ const makeChatsSocket = (config) => {
361
371
  }
362
372
  };
363
373
  };
364
- const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
374
+ const resyncAppStateWork = async (collections, isInitialSync) => {
365
375
  const initialVersionMap = {};
366
376
  const globalMutationMap = {};
367
377
  await authState.keys.transaction(async () => {
@@ -452,7 +462,11 @@ const makeChatsSocket = (config) => {
452
462
  for (const key in globalMutationMap) {
453
463
  onMutation(globalMutationMap[key]);
454
464
  }
455
- });
465
+ };
466
+ const bufferedResyncAppState = ev.createBufferedFunction(resyncAppStateWork);
467
+ const resyncAppState = (collections, isInitialSync, background = false) =>
468
+ background ? resyncAppStateWork(collections, isInitialSync) : bufferedResyncAppState(collections, isInitialSync);
469
+
456
470
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
457
471
  var _a;
458
472
  jid = (0, WABinary_1.jidNormalizedUser)(jid);
@@ -737,7 +751,7 @@ const makeChatsSocket = (config) => {
737
751
  return jid;
738
752
  }
739
753
  if ((0, WABinary_1.isLidUser)(jid)) {
740
- return (0, WABinary_1.lidToJid)(jid);
754
+ return (0, WABinary_1.jidNormalizedUser)(jid);
741
755
  }
742
756
  return jid;
743
757
  };
@@ -770,7 +784,7 @@ const makeChatsSocket = (config) => {
770
784
  }
771
785
  return keys;
772
786
  };
773
- const getDedupState = (msg) => msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT
787
+ const getDedupState = (msg) => ['ciphertext', 'stub', 'unknown'].includes(require('../Utils/message-inspector').inspectMessage(msg).type)
774
788
  ? 'ciphertext'
775
789
  : 'final';
776
790
  const getPendingDedupState = (dedupState) => dedupState === 'final' ? 'processing' : dedupState;
@@ -810,54 +824,52 @@ const makeChatsSocket = (config) => {
810
824
  && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
811
825
  : false;
812
826
  if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
813
- if (awaitingSyncTimeout) {
814
- clearTimeout(awaitingSyncTimeout);
815
- awaitingSyncTimeout = undefined;
816
- }
817
827
  if (shouldProcessHistoryMsg) {
818
828
  syncState = SyncState.Syncing;
819
829
  logger.info('Transitioned to Syncing state');
820
830
  } else {
821
831
  syncState = SyncState.Online;
822
832
  logger.info('History sync skipped, transitioning to Online state and flushing buffer');
823
- ev.flush();
833
+ releaseInitialEvents();
824
834
  }
825
835
  }
826
- const doAppStateSync = async () => {
827
- if (syncState === SyncState.Syncing) {
828
- logger.info('Doing app state sync');
829
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
830
- syncState = SyncState.Online;
831
- logger.info('App state sync complete, transitioning to Online state and flushing buffer');
832
- ev.flush();
833
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
834
- ev.emit('creds.update', { accountSyncCounter });
835
- }
836
+ const doAppStateSync = () => {
837
+ if (socketClosed || initialAppStateJob || (!pendingAppStateSync && syncState !== SyncState.Syncing)) return;
838
+ // Network synchronization must not hold the live message processing mutex.
839
+ initialAppStateJob = Promise.resolve().then(() => resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true, true))
840
+ .then(() => {
841
+ pendingAppStateSync = false;
842
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
843
+ ev.emit('creds.update', { accountSyncCounter });
844
+ })
845
+ .catch(error => onUnexpectedError(error, 'initial app state sync'))
846
+ .finally(() => { initialAppStateJob = undefined; releaseInitialEvents(); });
847
+ // The short synchronization lease is released separately by its watchdog.
836
848
  };
837
849
  if (historyMsg && !authState.creds.myAppStateKeyId) {
838
850
  logger.warn('skipping app state sync, as myAppStateKeyId is not set');
839
851
  pendingAppStateSync = true;
840
852
  }
841
- await Promise.all([
842
- (async () => {
843
- if (historyMsg
844
- && authState.creds.myAppStateKeyId) {
845
- pendingAppStateSync = false;
846
- await doAppStateSync();
847
- }
848
- })(),
849
- (0, process_message_1.default)(msg, {
850
- signalRepository,
851
- shouldProcessHistoryMsg,
852
- placeholderResendCache,
853
- ev,
854
- creds: authState.creds,
855
- keyStore: authState.keys,
856
- logger,
857
- options: config.options,
858
- getMessage: config.getMessage,
859
- })
860
- ]);
853
+ if (historyMsg && authState.creds.myAppStateKeyId) {
854
+ doAppStateSync();
855
+ }
856
+ const processJob = (0, process_message_1.default)(msg, {
857
+ signalRepository,
858
+ shouldProcessHistoryMsg,
859
+ placeholderResendCache,
860
+ ev,
861
+ creds: authState.creds,
862
+ keyStore: authState.keys,
863
+ logger,
864
+ options: config.options,
865
+ getMessage: config.getMessage,
866
+ });
867
+ if (historyMsg) {
868
+ // A history CDN download cannot hold processingMutex or a global event lease.
869
+ Promise.resolve(processJob).catch(error => onUnexpectedError(error, 'history processing'));
870
+ } else {
871
+ await processJob;
872
+ }
861
873
  if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
862
874
  && pendingAppStateSync) {
863
875
  await doAppStateSync();
@@ -916,17 +928,13 @@ const makeChatsSocket = (config) => {
916
928
  sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
917
929
  .catch(error => onUnexpectedError(error, 'presence update requests'));
918
930
  }
919
- if (receivedPendingNotifications &&
920
- !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
921
- ev.buffer();
922
- needToFlushWithAppStateSync = true;
923
- }
931
+ if (connection === 'close') { socketClosed = true; releaseInitialEvents(); receivedMessageDedupCache.close?.(); return; }
924
932
  if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
925
933
  return;
926
934
  }
927
935
  syncState = SyncState.AwaitingInitialSync;
928
936
  logger.info('Connection is now AwaitingInitialSync, buffering events');
929
- ev.buffer();
937
+ releaseInitialSync = ev.buffer();
930
938
  const willSyncHistory = shouldSyncHistoryMessage(
931
939
  WAProto_1.proto.Message.HistorySyncNotification.create({
932
940
  syncType: WAProto_1.proto.HistorySync.HistorySyncType.RECENT
@@ -935,7 +943,7 @@ const makeChatsSocket = (config) => {
935
943
  if (!willSyncHistory) {
936
944
  logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
937
945
  syncState = SyncState.Online;
938
- setTimeout(() => ev.flush(), 0);
946
+ releaseInitialEvents();
939
947
  return;
940
948
  }
941
949
  const initialSyncTimeoutMs = Number.isFinite(config.initialSyncTimeoutMs) && config.initialSyncTimeoutMs >= 1000 ? config.initialSyncTimeoutMs : 20000;
@@ -944,10 +952,10 @@ const makeChatsSocket = (config) => {
944
952
  clearTimeout(awaitingSyncTimeout);
945
953
  }
946
954
  awaitingSyncTimeout = setTimeout(() => {
947
- if (syncState === SyncState.AwaitingInitialSync) {
955
+ if (syncState === SyncState.AwaitingInitialSync || syncState === SyncState.Syncing) {
948
956
  logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
949
957
  syncState = SyncState.Online;
950
- ev.flush();
958
+ releaseInitialEvents();
951
959
  }
952
960
  }, initialSyncTimeoutMs);
953
961
  awaitingSyncTimeout.unref?.();
@@ -997,3 +1005,2481 @@ const makeChatsSocket = (config) => {
997
1005
  };
998
1006
  };
999
1007
  exports.makeChatsSocket = makeChatsSocket;
1008
+
1009
+ // Kage: compatibilidad de API.
1010
+ const __kageModule25 = (() => {
1011
+ const module = { exports: {} }; const exports = module.exports;
1012
+ "use strict"
1013
+
1014
+ Object.defineProperty(exports, "__esModule", { value: true })
1015
+
1016
+ const { default: NodeCache } = require("@cacheable/node-cache")
1017
+ const { Boom } = require("@hapi/boom")
1018
+ const { proto } = require("../../WAProto")
1019
+ const {
1020
+ CALL_VIDEO_PREFIX,
1021
+ CALL_AUDIO_PREFIX
1022
+ } = require("../Defaults/prefix")
1023
+ const { DEFAULT_CACHE_TTLS } = require("../Defaults/constants")
1024
+ const { PROCESSABLE_HISTORY_TYPES } = require("../Defaults/history")
1025
+ const {
1026
+ SyncState,
1027
+ ALL_WA_PATCH_NAMES
1028
+ } = require("../Types")
1029
+ const {
1030
+ newLTHashState,
1031
+ processSyncAction,
1032
+ extractSyncdPatches,
1033
+ generateProfilePicture,
1034
+ decodeSyncdSnapshot,
1035
+ decodePatches,
1036
+ encodeSyncdPatch,
1037
+ chatModificationToAppPatch,
1038
+ getHistoryMsg,
1039
+ processMessage
1040
+ } = require("../Utils")
1041
+ const { makeMutex } = require("../Utils/make-mutex")
1042
+ const {
1043
+ isPnUser,
1044
+ getBinaryNodeChild,
1045
+ getBinaryNodeChildren,
1046
+ jidDecode,
1047
+ jidNormalizedUser,
1048
+ reduceBinaryNodeToDictionary,
1049
+ S_WHATSAPP_NET
1050
+ } = require("../WABinary")
1051
+ const {
1052
+ USyncUser,
1053
+ USyncQuery
1054
+ } = require("../WAUSync")
1055
+ const { makeSocket } = require("./socket")
1056
+ const MAX_SYNC_ATTEMPTS = 2
1057
+
1058
+ const makeChatsSocket = (config) => {
1059
+ const {
1060
+ logger,
1061
+ markOnlineOnConnect,
1062
+ fireInitQueries,
1063
+ appStateMacVerification,
1064
+ shouldIgnoreJid,
1065
+ shouldSyncHistoryMessage,
1066
+ getMessage
1067
+ } = config
1068
+
1069
+ const suki = makeSocket(config)
1070
+
1071
+ const {
1072
+ ev,
1073
+ ws,
1074
+ authState,
1075
+ generateMessageTag,
1076
+ sendNode,
1077
+ query,
1078
+ signalRepository,
1079
+ onUnexpectedError
1080
+ } = suki
1081
+
1082
+ let privacySettings
1083
+ let syncState = SyncState.Connecting
1084
+
1085
+ /** this mutex ensures that messages are processed in order */
1086
+ const messageMutex = makeMutex()
1087
+
1088
+ /** this mutex ensures that receipts are processed in order */
1089
+ const receiptMutex = makeMutex()
1090
+
1091
+ /** this mutex ensures that app state patches are processed in order */
1092
+ const appStatePatchMutex = makeMutex()
1093
+
1094
+ /** this mutex ensures that notifications are processed in order */
1095
+ const notificationMutex = makeMutex()
1096
+
1097
+ // Timeout for AwaitingInitialSync state
1098
+ let awaitingSyncTimeout
1099
+
1100
+ const placeholderResendCache = config.placeholderResendCache ||
1101
+ new NodeCache({
1102
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
1103
+ useClones: false
1104
+ })
1105
+
1106
+ if (!config.placeholderResendCache) {
1107
+ config.placeholderResendCache = placeholderResendCache
1108
+ }
1109
+
1110
+ /** helper function to fetch the given app state sync key */
1111
+ const getAppStateSyncKey = async (keyId) => {
1112
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
1113
+ return key
1114
+ }
1115
+
1116
+ const fetchPrivacySettings = async (force = false) => {
1117
+ if (!privacySettings || force) {
1118
+ const { content } = await query({
1119
+ tag: 'iq',
1120
+ attrs: {
1121
+ xmlns: 'privacy',
1122
+ to: S_WHATSAPP_NET,
1123
+ type: 'get'
1124
+ },
1125
+ content: [
1126
+ { tag: 'privacy', attrs: {} }
1127
+ ]
1128
+ })
1129
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category')
1130
+ }
1131
+ return privacySettings
1132
+ }
1133
+
1134
+ /** helper function to run a privacy IQ query */
1135
+ const privacyQuery = async (name, value) => {
1136
+ await query({
1137
+ tag: 'iq',
1138
+ attrs: {
1139
+ xmlns: 'privacy',
1140
+ to: S_WHATSAPP_NET,
1141
+ type: 'set'
1142
+ },
1143
+ content: [{
1144
+ tag: 'privacy',
1145
+ attrs: {},
1146
+ content: [
1147
+ {
1148
+ tag: 'category',
1149
+ attrs: { name, value }
1150
+ }
1151
+ ]
1152
+ }]
1153
+ })
1154
+ }
1155
+
1156
+ const updateMessagesPrivacy = async (value) => {
1157
+ await privacyQuery('messages', value)
1158
+ }
1159
+
1160
+ const updateCallPrivacy = async (value) => {
1161
+ await privacyQuery('calladd', value)
1162
+ }
1163
+
1164
+ const updateLastSeenPrivacy = async (value) => {
1165
+ await privacyQuery('last', value)
1166
+ }
1167
+
1168
+ const updateOnlinePrivacy = async (value) => {
1169
+ await privacyQuery('online', value)
1170
+ }
1171
+
1172
+ const updateProfilePicturePrivacy = async (value) => {
1173
+ await privacyQuery('profile', value)
1174
+ }
1175
+
1176
+ const updateStatusPrivacy = async (value) => {
1177
+ await privacyQuery('status', value)
1178
+ }
1179
+
1180
+ const updateReadReceiptsPrivacy = async (value) => {
1181
+ await privacyQuery('readreceipts', value)
1182
+ }
1183
+
1184
+ const updateGroupsAddPrivacy = async (value) => {
1185
+ await privacyQuery('groupadd', value)
1186
+ }
1187
+
1188
+ const updateDefaultDisappearingMode = async (duration) => {
1189
+ await query({
1190
+ tag: 'iq',
1191
+ attrs: {
1192
+ xmlns: 'disappearing_mode',
1193
+ to: S_WHATSAPP_NET,
1194
+ type: 'set'
1195
+ },
1196
+ content: [{
1197
+ tag: 'disappearing_mode',
1198
+ attrs: {
1199
+ duration: duration.toString()
1200
+ }
1201
+ }]
1202
+ })
1203
+ }
1204
+
1205
+ const getBotListV2 = async () => {
1206
+ const resp = await query({
1207
+ tag: 'iq',
1208
+ attrs: {
1209
+ xmlns: 'bot',
1210
+ to: S_WHATSAPP_NET,
1211
+ type: 'get'
1212
+ },
1213
+ content: [{
1214
+ tag: 'bot',
1215
+ attrs: {
1216
+ v: '2'
1217
+ }
1218
+ }]
1219
+ })
1220
+
1221
+ const botNode = getBinaryNodeChild(resp, 'bot')
1222
+
1223
+ const botList = []
1224
+
1225
+ for(const section of getBinaryNodeChildren(botNode, 'section')) {
1226
+ if(section.attrs.type === 'all') {
1227
+ for(const bot of getBinaryNodeChildren(section, 'bot')) {
1228
+ botList.push({
1229
+ jid: bot.attrs.jid,
1230
+ personaId: bot.attrs['persona_id']
1231
+ })
1232
+ }
1233
+ }
1234
+ }
1235
+ return botList
1236
+ }
1237
+
1238
+ const getLidUser = async (jid) => {
1239
+ if (!jid) {
1240
+ throw new Boom('Please input a jid user')
1241
+ }
1242
+
1243
+ if (!isPnUser(jid)) {
1244
+ throw new Boom('Invalid JID: Not a user JID!')
1245
+ }
1246
+
1247
+ const targetJid = jidNormalizedUser(jid)
1248
+
1249
+ const usyncQuery = new USyncQuery()
1250
+ usyncQuery.protocols.push({
1251
+ name: 'lid',
1252
+ getQueryElement: () => ({
1253
+ tag: 'lid',
1254
+ attrs: {},
1255
+ content: undefined
1256
+ }),
1257
+ getUserElement: () => null,
1258
+ parser: (node) => node.attrs.val
1259
+ })
1260
+ usyncQuery.users.push({
1261
+ id: targetJid
1262
+ })
1263
+
1264
+ const result = await suki.executeUSyncQuery(usyncQuery)
1265
+
1266
+ if (result) {
1267
+ return result.list
1268
+ }
1269
+ }
1270
+
1271
+ const fetchStatus = async (...jids) => {
1272
+ const usyncQuery = new USyncQuery().withStatusProtocol()
1273
+
1274
+ for (const jid of jids) {
1275
+ usyncQuery.withUser(new USyncUser().withId(jid))
1276
+ }
1277
+
1278
+ const result = await suki.executeUSyncQuery(usyncQuery)
1279
+
1280
+ if (result) {
1281
+ return result.list
1282
+ }
1283
+ }
1284
+
1285
+ const fetchDisappearingDuration = async (...jids) => {
1286
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol()
1287
+
1288
+ for (const jid of jids) {
1289
+ usyncQuery.withUser(new USyncUser().withId(jid))
1290
+ }
1291
+
1292
+ const result = await suki.executeUSyncQuery(usyncQuery)
1293
+
1294
+ if (result) {
1295
+ return result.list
1296
+ }
1297
+ }
1298
+
1299
+ /** update the profile picture for yourself or a group */
1300
+ const updateProfilePicture = async (jid, content, dimensions) => {
1301
+ let targetJid
1302
+
1303
+ if (!jid) {
1304
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
1305
+ }
1306
+
1307
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
1308
+ targetJid = jidNormalizedUser(jid) // in case it is someone other than us
1309
+ }
1310
+
1311
+ else {
1312
+ targetJid = undefined
1313
+ }
1314
+
1315
+ const { img } = await generateProfilePicture(content, dimensions)
1316
+
1317
+ await query({
1318
+ tag: 'iq',
1319
+ attrs: {
1320
+ to: S_WHATSAPP_NET,
1321
+ type: 'set',
1322
+ xmlns: 'w:profile:picture',
1323
+ ...(targetJid ? { target: targetJid } : {})
1324
+ },
1325
+ content: [
1326
+ {
1327
+ tag: 'picture',
1328
+ attrs: { type: 'image' },
1329
+ content: img
1330
+ }
1331
+ ]
1332
+ })
1333
+ }
1334
+
1335
+ /** remove the profile picture for yourself or a group */
1336
+ const removeProfilePicture = async (jid) => {
1337
+ let targetJid
1338
+
1339
+ if (!jid) {
1340
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
1341
+ }
1342
+
1343
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
1344
+ targetJid = jidNormalizedUser(jid) // in case it is someone other than us
1345
+ }
1346
+
1347
+ else {
1348
+ targetJid = undefined
1349
+ }
1350
+
1351
+ await query({
1352
+ tag: 'iq',
1353
+ attrs: {
1354
+ to: S_WHATSAPP_NET,
1355
+ type: 'set',
1356
+ xmlns: 'w:profile:picture',
1357
+ ...(targetJid ? { target: targetJid } : {})
1358
+ }
1359
+ })
1360
+ }
1361
+
1362
+ /** update the profile status for yourself */
1363
+ const updateProfileStatus = async (status) => {
1364
+ await query({
1365
+ tag: 'iq',
1366
+ attrs: {
1367
+ to: S_WHATSAPP_NET,
1368
+ type: 'set',
1369
+ xmlns: 'status'
1370
+ },
1371
+ content: [
1372
+ {
1373
+ tag: 'status',
1374
+ attrs: {},
1375
+ content: Buffer.from(status, 'utf-8')
1376
+ }
1377
+ ]
1378
+ })
1379
+ }
1380
+
1381
+ const updateProfileName = async (name) => {
1382
+ await chatModify({ pushNameSetting: name }, '')
1383
+ }
1384
+
1385
+ const fetchBlocklist = async () => {
1386
+ const result = await query({
1387
+ tag: 'iq',
1388
+ attrs: {
1389
+ xmlns: 'blocklist',
1390
+ to: S_WHATSAPP_NET,
1391
+ type: 'get'
1392
+ }
1393
+ })
1394
+
1395
+ const listNode = getBinaryNodeChild(result, 'list')
1396
+
1397
+ return getBinaryNodeChildren(listNode, 'item').map((n) => n.attrs.jid)
1398
+ }
1399
+
1400
+ const updateBlockStatus = async (jid, action) => {
1401
+ await query({
1402
+ tag: 'iq',
1403
+ attrs: {
1404
+ xmlns: 'blocklist',
1405
+ to: S_WHATSAPP_NET,
1406
+ type: 'set'
1407
+ },
1408
+ content: [
1409
+ {
1410
+ tag: 'item',
1411
+ attrs: {
1412
+ action,
1413
+ jid
1414
+ }
1415
+ }
1416
+ ]
1417
+ })
1418
+ }
1419
+
1420
+ const getBusinessProfile = async (jid) => {
1421
+ const results = await query({
1422
+ tag: 'iq',
1423
+ attrs: {
1424
+ to: 's.whatsapp.net',
1425
+ xmlns: 'w:biz',
1426
+ type: 'get'
1427
+ },
1428
+ content: [{
1429
+ tag: 'business_profile',
1430
+ attrs: { v: '244' },
1431
+ content: [{
1432
+ tag: 'profile',
1433
+ attrs: { jid }
1434
+ }]
1435
+ }]
1436
+ })
1437
+
1438
+ const profileNode = getBinaryNodeChild(results, 'business_profile')
1439
+
1440
+ const profiles = getBinaryNodeChild(profileNode, 'profile')
1441
+
1442
+ if (profiles) {
1443
+ const address = getBinaryNodeChild(profiles, 'address')
1444
+ const description = getBinaryNodeChild(profiles, 'description')
1445
+ const website = getBinaryNodeChild(profiles, 'website')
1446
+ const email = getBinaryNodeChild(profiles, 'email')
1447
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category')
1448
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours')
1449
+ const businessHoursConfig = businessHours
1450
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
1451
+ : undefined
1452
+ const websiteStr = website?.content?.toString()
1453
+
1454
+ return {
1455
+ wid: profiles?.attrs?.jid,
1456
+ address: address?.content?.toString(),
1457
+ description: description?.content?.toString() || '',
1458
+ website: websiteStr ? [websiteStr] : [],
1459
+ email: email?.content?.toString(),
1460
+ category: category?.content?.toString(),
1461
+ 'business_hours': {
1462
+ timezone: businessHours?.attrs?.timezone,
1463
+ 'business_config': businessHoursConfig?.map(({ attrs }) => attrs)
1464
+ }
1465
+ }
1466
+ }
1467
+ }
1468
+
1469
+ const cleanDirtyBits = async (type, fromTimestamp) => {
1470
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
1471
+ await sendNode({
1472
+ tag: 'iq',
1473
+ attrs: {
1474
+ to: S_WHATSAPP_NET,
1475
+ type: 'set',
1476
+ xmlns: 'urn:xmpp:whatsapp:dirty',
1477
+ id: generateMessageTag(),
1478
+ },
1479
+ content: [
1480
+ {
1481
+ tag: 'clean',
1482
+ attrs: {
1483
+ type,
1484
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
1485
+ }
1486
+ }
1487
+ ]
1488
+ })
1489
+ }
1490
+
1491
+ const newAppStateChunkHandler = (isInitialSync) => {
1492
+ return {
1493
+ onMutation(mutation) {
1494
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
1495
+ }
1496
+ }
1497
+ }
1498
+
1499
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
1500
+ // we use this to determine which events to fire
1501
+ // otherwise when we resync from scratch -- all notifications will fire
1502
+ const initialVersionMap = {}
1503
+ const globalMutationMap = {}
1504
+
1505
+ await authState.keys.transaction(async () => {
1506
+ const collectionsToHandle = new Set(collections)
1507
+
1508
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
1509
+ const attemptsMap = {}
1510
+
1511
+ // keep executing till all collections are done
1512
+ // sometimes a single patch request will not return all the patches (God knows why)
1513
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
1514
+ while (collectionsToHandle.size) {
1515
+ const states = {}
1516
+ const nodes = []
1517
+
1518
+ for (const name of collectionsToHandle) {
1519
+ const result = await authState.keys.get('app-state-sync-version', [name])
1520
+
1521
+ let state = result[name]
1522
+
1523
+ if (state) {
1524
+ if (typeof initialVersionMap[name] === 'undefined') {
1525
+ initialVersionMap[name] = state.version
1526
+ }
1527
+ }
1528
+
1529
+ else {
1530
+ state = newLTHashState()
1531
+ }
1532
+
1533
+ states[name] = state
1534
+ logger.info(`resyncing ${name} from v${state.version}`)
1535
+ nodes.push({
1536
+ tag: 'collection',
1537
+ attrs: {
1538
+ name,
1539
+ version: state.version.toString(),
1540
+ // return snapshot if being synced from scratch
1541
+ return_snapshot: (!state.version).toString()
1542
+ }
1543
+ })
1544
+ }
1545
+
1546
+ const result = await query({
1547
+ tag: 'iq',
1548
+ attrs: {
1549
+ to: S_WHATSAPP_NET,
1550
+ xmlns: 'w:sync:app:state',
1551
+ type: 'set'
1552
+ },
1553
+ content: [
1554
+ {
1555
+ tag: 'sync',
1556
+ attrs: {},
1557
+ content: nodes
1558
+ }
1559
+ ]
1560
+ })
1561
+
1562
+ // extract from binary node
1563
+ const decoded = await extractSyncdPatches(result, config?.options)
1564
+
1565
+ for (const key in decoded) {
1566
+ const name = key
1567
+ const { patches, hasMorePatches, snapshot } = decoded[name]
1568
+
1569
+ try {
1570
+ if (snapshot) {
1571
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot)
1572
+
1573
+ states[name] = newState
1574
+
1575
+ Object.assign(globalMutationMap, mutationMap)
1576
+
1577
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
1578
+
1579
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
1580
+ }
1581
+
1582
+ // only process if there are syncd patches
1583
+ if (patches.length) {
1584
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch)
1585
+
1586
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
1587
+
1588
+ logger.info(`synced ${name} to v${newState.version}`)
1589
+
1590
+ initialVersionMap[name] = newState.version
1591
+
1592
+ Object.assign(globalMutationMap, mutationMap)
1593
+ }
1594
+
1595
+ if (hasMorePatches) {
1596
+ logger.info(`${name} has more patches...`)
1597
+ }
1598
+
1599
+ else {
1600
+ // collection is done with sync
1601
+ collectionsToHandle.delete(name)
1602
+ }
1603
+ }
1604
+
1605
+ catch (error) {
1606
+ // if retry attempts overshoot
1607
+ // or key not found
1608
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
1609
+ error.output?.statusCode === 404 ||
1610
+ error.name === 'TypeError'
1611
+
1612
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`)
1613
+
1614
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } })
1615
+
1616
+ // increment number of retries
1617
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1
1618
+
1619
+ if (isIrrecoverableError) {
1620
+ // stop retrying
1621
+ collectionsToHandle.delete(name);
1622
+ }
1623
+ }
1624
+ }
1625
+ }
1626
+ }, authState?.creds?.me?.id || 'resync-app-state')
1627
+ const { onMutation } = newAppStateChunkHandler(isInitialSync)
1628
+
1629
+ for (const key in globalMutationMap) {
1630
+ onMutation(globalMutationMap[key])
1631
+ }
1632
+ })
1633
+
1634
+ // source: https://github.com/WhiskeySockets/Baileys/pull/1677
1635
+ const createCallLink = async (type, event, timeoutMs) => {
1636
+ type = type?.toLowerCase()
1637
+
1638
+ if (!type || (type !== 'audio' && type !== 'video')) {
1639
+ throw new Error('Make sure the type is audio or video!')
1640
+ }
1641
+
1642
+ const result = await query({
1643
+ tag: 'call',
1644
+ attrs: {
1645
+ id: generateMessageTag(),
1646
+ to: '@call'
1647
+ },
1648
+ content: [{
1649
+ tag: 'link_create',
1650
+ attrs: {
1651
+ media: type
1652
+ },
1653
+ content: event ? [{
1654
+ tag: 'event',
1655
+ attrs: {
1656
+ start_time: String(event)
1657
+ }
1658
+ }] : undefined
1659
+ }]
1660
+ }, timeoutMs)
1661
+
1662
+ const child = getBinaryNodeChild(result, 'link_create')
1663
+ const token = child?.attrs?.token
1664
+
1665
+ return type === 'audio' ? CALL_AUDIO_PREFIX + token : CALL_VIDEO_PREFIX + token
1666
+ }
1667
+
1668
+ const sendPresenceUpdate = async (type, toJid) => {
1669
+ const me = authState.creds.me
1670
+
1671
+ if (type === 'available' || type === 'unavailable') {
1672
+ if (!me.name) {
1673
+ logger.warn('no name present, ignoring presence update request...')
1674
+ return
1675
+ }
1676
+
1677
+ ev.emit('connection.update', { isOnline: type === 'available' })
1678
+ await sendNode({
1679
+ tag: 'presence',
1680
+ attrs: {
1681
+ name: me.name.replace(/@/g, ''),
1682
+ type
1683
+ }
1684
+ })
1685
+ }
1686
+ else {
1687
+ const { server } = jidDecode(toJid)
1688
+
1689
+ await sendNode({
1690
+ tag: 'chatstate',
1691
+ attrs: {
1692
+ from: server === 'lid' ? me.lid : me.id,
1693
+ to: toJid
1694
+ },
1695
+ content: [
1696
+ {
1697
+ tag: type === 'recording' ? 'composing' : type,
1698
+ attrs: type === 'recording' ? { media: 'audio' } : {}
1699
+ }
1700
+ ]
1701
+ })
1702
+ }
1703
+ }
1704
+
1705
+ /**
1706
+ * @param toJid the jid to subscribe to
1707
+ * @param tcToken token for subscription, use if present
1708
+ */
1709
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
1710
+ tag: 'presence',
1711
+ attrs: {
1712
+ to: toJid,
1713
+ id: generateMessageTag(),
1714
+ type: 'subscribe'
1715
+ },
1716
+ content: tcToken
1717
+ ? [
1718
+ {
1719
+ tag: 'tctoken',
1720
+ attrs: {},
1721
+ content: tcToken
1722
+ }
1723
+ ]
1724
+ : undefined
1725
+ }))
1726
+
1727
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
1728
+ let presence
1729
+
1730
+ const jid = attrs.from
1731
+ const participant = attrs.participant || attrs.from
1732
+
1733
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
1734
+ return
1735
+ }
1736
+
1737
+ if (tag === 'presence') {
1738
+ presence = {
1739
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
1740
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
1741
+ }
1742
+ }
1743
+
1744
+ else if (Array.isArray(content)) {
1745
+ const [firstChild] = content
1746
+
1747
+ let type = firstChild.tag
1748
+
1749
+ if (type === 'paused') {
1750
+ type = 'available'
1751
+ }
1752
+
1753
+ if (firstChild.attrs?.media === 'audio') {
1754
+ type = 'recording'
1755
+ }
1756
+
1757
+ presence = { lastKnownPresence: type }
1758
+ }
1759
+
1760
+ else {
1761
+ logger.error({ tag, attrs, content }, 'recv invalid presence node')
1762
+ }
1763
+
1764
+ if (presence) {
1765
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
1766
+ }
1767
+ }
1768
+
1769
+ const appPatch = async (patchCreate) => {
1770
+ const name = patchCreate.type
1771
+ const myAppStateKeyId = authState.creds.myAppStateKeyId
1772
+
1773
+ if (!myAppStateKeyId) {
1774
+ throw new Boom('App state key not present!', { statusCode: 400 })
1775
+ }
1776
+
1777
+ let initial
1778
+ let encodeResult
1779
+
1780
+ await appStatePatchMutex.mutex(async () => {
1781
+ await authState.keys.transaction(async () => {
1782
+ logger.debug({ patch: patchCreate }, 'applying app patch')
1783
+
1784
+ await resyncAppState([name], false)
1785
+
1786
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
1787
+
1788
+ initial = currentSyncVersion || newLTHashState()
1789
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
1790
+
1791
+ const { patch, state } = encodeResult
1792
+ const node = {
1793
+ tag: 'iq',
1794
+ attrs: {
1795
+ to: S_WHATSAPP_NET,
1796
+ type: 'set',
1797
+ xmlns: 'w:sync:app:state'
1798
+ },
1799
+ content: [
1800
+ {
1801
+ tag: 'sync',
1802
+ attrs: {},
1803
+ content: [
1804
+ {
1805
+ tag: 'collection',
1806
+ attrs: {
1807
+ name,
1808
+ version: (state.version - 1).toString(),
1809
+ return_snapshot: 'false'
1810
+ },
1811
+ content: [
1812
+ {
1813
+ tag: 'patch',
1814
+ attrs: {},
1815
+ content: proto.SyncdPatch.encode(patch).finish()
1816
+ }
1817
+ ]
1818
+ }
1819
+ ]
1820
+ }
1821
+ ]
1822
+ }
1823
+
1824
+ await query(node)
1825
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
1826
+ }, authState?.creds?.me?.id || 'app-patch')
1827
+ })
1828
+
1829
+ if (config.emitOwnEvents) {
1830
+ const { onMutation } = newAppStateChunkHandler(false)
1831
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger)
1832
+
1833
+ for (const key in mutationMap) {
1834
+ onMutation(mutationMap[key])
1835
+ }
1836
+ }
1837
+ }
1838
+
1839
+ /** sending non-abt props may fix QR scan fail if server expects */
1840
+ const fetchProps = async () => {
1841
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
1842
+ const resultNode = await query({
1843
+ tag: 'iq',
1844
+ attrs: {
1845
+ to: S_WHATSAPP_NET,
1846
+ xmlns: 'w',
1847
+ type: 'get'
1848
+ },
1849
+ content: [
1850
+ {
1851
+ tag: 'props',
1852
+ attrs: {
1853
+ protocol: '2',
1854
+ hash: authState?.creds?.lastPropHash || ''
1855
+ }
1856
+ }
1857
+ ]
1858
+ })
1859
+
1860
+ const propsNode = getBinaryNodeChild(resultNode, 'props')
1861
+ let props = {}
1862
+
1863
+ if (propsNode) {
1864
+ if (propsNode.attrs?.hash) {
1865
+ // on some clients, the hash is returning as undefined
1866
+ authState.creds.lastPropHash = propsNode?.attrs?.hash
1867
+ ev.emit('creds.update', authState.creds)
1868
+ }
1869
+
1870
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop')
1871
+ }
1872
+ logger.debug('fetched props')
1873
+
1874
+ return props
1875
+ }
1876
+
1877
+ /**
1878
+ * modify a chat -- mark unread, read etc.
1879
+ * lastMessages must be sorted in reverse chronologically
1880
+ * requires the last messages till the last message received required for archive & unread
1881
+ */
1882
+ const chatModify = (mod, jid) => {
1883
+ const patch = chatModificationToAppPatch(mod, jid)
1884
+ return appPatch(patch)
1885
+ }
1886
+
1887
+ /**
1888
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
1889
+ */
1890
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
1891
+ return chatModify({
1892
+ disableLinkPreviews: {
1893
+ isPreviewsDisabled
1894
+ }
1895
+ }, '')
1896
+ }
1897
+
1898
+ /**
1899
+ * Star or Unstar a message
1900
+ */
1901
+ const star = (jid, messages, star) => {
1902
+ return chatModify({
1903
+ star: {
1904
+ messages,
1905
+ star
1906
+ }
1907
+ }, jid)
1908
+ }
1909
+
1910
+ /**
1911
+ * Add Or Edit Contact
1912
+ */
1913
+ const addOrEditContact = (jid, contact) => {
1914
+ return chatModify({
1915
+ contact
1916
+ }, jid)
1917
+ }
1918
+
1919
+ /**
1920
+ * Remove Contact
1921
+ */
1922
+ const removeContact = (jid) => {
1923
+ return chatModify({
1924
+ contact: null
1925
+ }, jid)
1926
+ }
1927
+
1928
+ /**
1929
+ * Adds label
1930
+ */
1931
+ const addLabel = (jid, labels) => {
1932
+ return chatModify({
1933
+ addLabel: {
1934
+ ...labels
1935
+ }
1936
+ }, jid)
1937
+ }
1938
+
1939
+ /**
1940
+ * Adds label for the chats
1941
+ */
1942
+ const addChatLabel = (jid, labelId) => {
1943
+ return chatModify({
1944
+ addChatLabel: {
1945
+ labelId
1946
+ }
1947
+ }, jid)
1948
+ }
1949
+
1950
+ /**
1951
+ * Removes label for the chat
1952
+ */
1953
+ const removeChatLabel = (jid, labelId) => {
1954
+ return chatModify({
1955
+ removeChatLabel: {
1956
+ labelId
1957
+ }
1958
+ }, jid)
1959
+ }
1960
+
1961
+ /**
1962
+ * Adds label for the message
1963
+ */
1964
+ const addMessageLabel = (jid, messageId, labelId) => {
1965
+ return chatModify({
1966
+ addMessageLabel: {
1967
+ messageId,
1968
+ labelId
1969
+ }
1970
+ }, jid)
1971
+ }
1972
+
1973
+ /**
1974
+ * Removes label for the message
1975
+ */
1976
+ const removeMessageLabel = (jid, messageId, labelId) => {
1977
+ return chatModify({
1978
+ removeMessageLabel: {
1979
+ messageId,
1980
+ labelId
1981
+ }
1982
+ }, jid)
1983
+ }
1984
+
1985
+ /**
1986
+ * Removes Chats
1987
+ */
1988
+ const clearMessage = (jid, key, timeStamp) => {
1989
+ return chatModify({
1990
+ delete: true,
1991
+ lastMessages: [{
1992
+ key: key,
1993
+ messageTimestamp: timeStamp
1994
+ }],
1995
+ }, jid)
1996
+ }
1997
+
1998
+ /**
1999
+ * Add or Edit Quick Reply
2000
+ */
2001
+ const addOrEditQuickReply = (quickReply) => {
2002
+ return chatModify({
2003
+ quickReply
2004
+ }, '')
2005
+ }
2006
+
2007
+ /**
2008
+ * Remove Quick Reply
2009
+ */
2010
+ const removeQuickReply = (timestamp) => {
2011
+ return chatModify({
2012
+ quickReply: { timestamp, deleted: true }
2013
+ }, '')
2014
+ }
2015
+
2016
+ /**
2017
+ * queries need to be fired on connection open
2018
+ * help ensure parity with WA Web
2019
+ * */
2020
+ const executeInitQueries = async () => {
2021
+ await Promise.all([
2022
+ fetchProps(),
2023
+ fetchBlocklist(),
2024
+ fetchPrivacySettings(),
2025
+ ])
2026
+ }
2027
+
2028
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
2029
+ ev.emit('messages.upsert', { messages: [msg], type })
2030
+
2031
+ if (!!msg.pushName) {
2032
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid
2033
+
2034
+ jid = jidNormalizedUser(jid)
2035
+
2036
+ if (!msg.key.fromMe) {
2037
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
2038
+ }
2039
+
2040
+ // update our pushname too
2041
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
2042
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } })
2043
+ }
2044
+ }
2045
+
2046
+ const historyMsg = getHistoryMsg(msg.message)
2047
+ const shouldProcessHistoryMsg = historyMsg
2048
+ ? shouldSyncHistoryMessage(historyMsg) &&
2049
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
2050
+ : false
2051
+
2052
+ // State machine: decide on sync and flush
2053
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
2054
+ if (awaitingSyncTimeout) {
2055
+ clearTimeout(awaitingSyncTimeout)
2056
+ awaitingSyncTimeout = undefined
2057
+ }
2058
+
2059
+ if (shouldProcessHistoryMsg) {
2060
+ syncState = SyncState.Syncing
2061
+ logger.info('Transitioned to Syncing state')
2062
+ // Let doAppStateSync handle the final flush after it's done
2063
+ }
2064
+
2065
+ else {
2066
+ syncState = SyncState.Online
2067
+
2068
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer')
2069
+
2070
+ ev.flush()
2071
+ }
2072
+ }
2073
+
2074
+ const doAppStateSync = async () => {
2075
+ if (syncState === SyncState.Syncing) {
2076
+ logger.info('Doing app state sync')
2077
+
2078
+ await resyncAppState(ALL_WA_PATCH_NAMES, true)
2079
+
2080
+ // Sync is complete, go online and flush everything
2081
+ syncState = SyncState.Online
2082
+
2083
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer')
2084
+
2085
+ ev.flush()
2086
+
2087
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
2088
+
2089
+ ev.emit('creds.update', { accountSyncCounter })
2090
+ }
2091
+ }
2092
+
2093
+ await Promise.all([
2094
+ (async () => {
2095
+ if (shouldProcessHistoryMsg) {
2096
+ await doAppStateSync()
2097
+ }
2098
+ })(),
2099
+ processMessage(msg, {
2100
+ signalRepository,
2101
+ shouldProcessHistoryMsg,
2102
+ placeholderResendCache,
2103
+ ev,
2104
+ creds: authState.creds,
2105
+ keyStore: authState.keys,
2106
+ logger,
2107
+ options: config.options,
2108
+ getMessage
2109
+ })
2110
+ ])
2111
+
2112
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
2113
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
2114
+ logger.info('App state sync key arrived, triggering app state sync')
2115
+ await doAppStateSync()
2116
+ }
2117
+ })
2118
+
2119
+ ws.on('CB:presence', handlePresenceUpdate)
2120
+ ws.on('CB:chatstate', handlePresenceUpdate)
2121
+ ws.on('CB:ib,,dirty', async (node) => {
2122
+ const { attrs } = getBinaryNodeChild(node, 'dirty')
2123
+ const type = attrs.type
2124
+
2125
+ switch (type) {
2126
+ case 'account_sync':
2127
+ if (attrs.timestamp) {
2128
+ let { lastAccountSyncTimestamp } = authState.creds
2129
+
2130
+ if (lastAccountSyncTimestamp) {
2131
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
2132
+ }
2133
+
2134
+ lastAccountSyncTimestamp = +attrs.timestamp
2135
+
2136
+ ev.emit('creds.update', { lastAccountSyncTimestamp })
2137
+ }
2138
+ break
2139
+ case 'groups':
2140
+ // handled in groups.js
2141
+ break
2142
+ default:
2143
+ logger.info({ node }, 'received unknown sync')
2144
+ break
2145
+ }
2146
+ })
2147
+
2148
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
2149
+ if (connection === 'open') {
2150
+ if (fireInitQueries) {
2151
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'))
2152
+ }
2153
+
2154
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'))
2155
+ }
2156
+
2157
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
2158
+ return
2159
+ }
2160
+
2161
+ syncState = SyncState.AwaitingInitialSync
2162
+
2163
+ logger.info('Connection is now AwaitingInitialSync, buffering events')
2164
+ ev.buffer()
2165
+
2166
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
2167
+ syncType: proto.HistorySync.HistorySyncType.RECENT
2168
+ }))
2169
+
2170
+ if (!willSyncHistory) {
2171
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.')
2172
+ syncState = SyncState.Online
2173
+ setTimeout(() => ev.flush(), 0)
2174
+ return
2175
+ }
2176
+
2177
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.')
2178
+
2179
+ if (awaitingSyncTimeout) {
2180
+ clearTimeout(awaitingSyncTimeout);
2181
+ }
2182
+
2183
+ awaitingSyncTimeout = setTimeout(() => {
2184
+ if (syncState === SyncState.AwaitingInitialSync) {
2185
+ // TODO: investigate
2186
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer')
2187
+ syncState = SyncState.Online
2188
+ ev.flush()
2189
+ }
2190
+ }, 20000)
2191
+ })
2192
+
2193
+ return {
2194
+ ...suki,
2195
+ star,
2196
+ addOrEditContact,
2197
+ removeContact,
2198
+ fetchPrivacySettings,
2199
+ upsertMessage,
2200
+ appPatch,
2201
+ createCallLink,
2202
+ sendPresenceUpdate,
2203
+ presenceSubscribe,
2204
+ getBotListV2,
2205
+ messageMutex,
2206
+ receiptMutex,
2207
+ appStatePatchMutex,
2208
+ notificationMutex,
2209
+ getLidUser,
2210
+ fetchBlocklist,
2211
+ fetchStatus,
2212
+ fetchDisappearingDuration,
2213
+ updateProfilePicture,
2214
+ removeProfilePicture,
2215
+ updateProfileStatus,
2216
+ updateProfileName,
2217
+ updateBlockStatus,
2218
+ updateCallPrivacy,
2219
+ updateMessagesPrivacy,
2220
+ updateLastSeenPrivacy,
2221
+ updateOnlinePrivacy,
2222
+ updateProfilePicturePrivacy,
2223
+ updateStatusPrivacy,
2224
+ updateReadReceiptsPrivacy,
2225
+ updateGroupsAddPrivacy,
2226
+ updateDefaultDisappearingMode,
2227
+ updateDisableLinkPreviewsPrivacy,
2228
+ getBusinessProfile,
2229
+ resyncAppState,
2230
+ chatModify,
2231
+ cleanDirtyBits,
2232
+ addLabel,
2233
+ addChatLabel,
2234
+ removeChatLabel,
2235
+ addMessageLabel,
2236
+ removeMessageLabel,
2237
+ clearMessage,
2238
+ addOrEditQuickReply,
2239
+ removeQuickReply
2240
+ }
2241
+ }
2242
+
2243
+ module.exports = {
2244
+ makeChatsSocket
2245
+ }
2246
+ return module.exports;
2247
+ })();
2248
+ for (const key of Object.keys(__kageModule25)) {
2249
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule25[key]});
2250
+ }
2251
+
2252
+ // Kage: funciones avanzadas.
2253
+ const __kageModule131 = (() => {
2254
+ const module = { exports: {} }; const exports = module.exports;
2255
+ "use strict";
2256
+ var __importDefault = (this && this.__importDefault) || function (mod) {
2257
+ return (mod && mod.__esModule) ? mod : { "default": mod };
2258
+ };
2259
+ Object.defineProperty(exports, "__esModule", { value: true });
2260
+ exports.makeChatsSocket = exports.buildProfilePictureQueryContent = void 0;
2261
+ const index_js_1 = require("../../WAProto/index.js");
2262
+ const index_js_2 = require("../Addon/index.js");
2263
+ const index_js_3 = require("../Defaults/index.js");
2264
+ const index_js_4 = require("../Types/index.js");
2265
+ const State_js_1 = require("../Types/State.js");
2266
+ const index_js_5 = require("../Utils/index.js");
2267
+ const make_mutex_js_1 = require("../Utils/make-mutex.js");
2268
+ const process_message_js_1 = __importDefault(require("../Utils/process-message.js"));
2269
+ const tc_token_utils_js_1 = require("../Utils/tc-token-utils.js");
2270
+ const index_js_6 = require("../WABinary/index.js");
2271
+ const index_js_7 = require("../WAUSync/index.js");
2272
+ const socket_js_1 = require("./socket.js");
2273
+ const buildProfilePictureQueryContent = (type, tcTokenContent) => {
2274
+ const picture = { tag: 'picture', attrs: { type, query: 'url' } };
2275
+ if (tcTokenContent?.length) {
2276
+ picture.content = tcTokenContent;
2277
+ }
2278
+ return [picture];
2279
+ };
2280
+ exports.buildProfilePictureQueryContent = buildProfilePictureQueryContent;
2281
+ const makeChatsSocket = (config) => {
2282
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
2283
+ const sock = (0, socket_js_1.makeSocket)(config);
2284
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
2285
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
2286
+ let privacySettings;
2287
+ /** Server-assigned AB props for protocol behavior. */
2288
+ const serverProps = {
2289
+ /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
2290
+ privacyTokenOn1to1: true,
2291
+ /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
2292
+ profilePicPrivacyToken: true,
2293
+ /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
2294
+ lidTrustedTokenIssueToLid: false
2295
+ };
2296
+ let syncState = State_js_1.SyncState.Connecting;
2297
+ /** this mutex ensures that messages are processed in order */
2298
+ const messageMutex = (0, make_mutex_js_1.makeMutex)();
2299
+ /** this mutex ensures that receipts are processed in order */
2300
+ const receiptMutex = (0, make_mutex_js_1.makeMutex)();
2301
+ /** this mutex ensures that app state patches are processed in order */
2302
+ const appStatePatchMutex = (0, make_mutex_js_1.makeMutex)();
2303
+ /** this mutex ensures that notifications are processed in order */
2304
+ const notificationMutex = (0, make_mutex_js_1.makeMutex)();
2305
+ // Timeout for AwaitingInitialSync state
2306
+ let awaitingSyncTimeout;
2307
+ // In-memory history sync completion tracking (resets on reconnection)
2308
+ const historySyncStatus = {
2309
+ initialBootstrapComplete: false,
2310
+ recentSyncComplete: false
2311
+ };
2312
+ let historySyncPausedTimeout;
2313
+ // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
2314
+ // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
2315
+ const blockedCollections = new Set();
2316
+ const placeholderResendCache = config.placeholderResendCache ||
2317
+ (0, index_js_2.createCache)({
2318
+ ttl: index_js_3.DEFAULT_CACHE_TTLS.MSG_RETRY // 1 hour
2319
+ });
2320
+ /** helper function to fetch the given app state sync key */
2321
+ const getAppStateSyncKey = async (keyId) => {
2322
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
2323
+ return key;
2324
+ };
2325
+ const fetchPrivacySettings = async (force = false) => {
2326
+ if (!privacySettings || force) {
2327
+ const { content } = await query({
2328
+ tag: 'iq',
2329
+ attrs: {
2330
+ xmlns: 'privacy',
2331
+ to: index_js_6.S_WHATSAPP_NET,
2332
+ type: 'get'
2333
+ },
2334
+ content: [{ tag: 'privacy', attrs: {} }]
2335
+ });
2336
+ privacySettings = (0, index_js_6.reduceBinaryNodeToDictionary)(content?.[0], 'category');
2337
+ }
2338
+ return privacySettings;
2339
+ };
2340
+ /** helper function to run a privacy IQ query */
2341
+ const privacyQuery = async (name, value) => {
2342
+ await query({
2343
+ tag: 'iq',
2344
+ attrs: {
2345
+ xmlns: 'privacy',
2346
+ to: index_js_6.S_WHATSAPP_NET,
2347
+ type: 'set'
2348
+ },
2349
+ content: [
2350
+ {
2351
+ tag: 'privacy',
2352
+ attrs: {},
2353
+ content: [
2354
+ {
2355
+ tag: 'category',
2356
+ attrs: { name, value }
2357
+ }
2358
+ ]
2359
+ }
2360
+ ]
2361
+ });
2362
+ };
2363
+ const updateMessagesPrivacy = async (value) => {
2364
+ await privacyQuery('messages', value);
2365
+ };
2366
+ const updateCallPrivacy = async (value) => {
2367
+ await privacyQuery('calladd', value);
2368
+ };
2369
+ const updateLastSeenPrivacy = async (value) => {
2370
+ await privacyQuery('last', value);
2371
+ };
2372
+ const updateOnlinePrivacy = async (value) => {
2373
+ await privacyQuery('online', value);
2374
+ };
2375
+ const updateProfilePicturePrivacy = async (value) => {
2376
+ await privacyQuery('profile', value);
2377
+ };
2378
+ const updateStatusPrivacy = async (value) => {
2379
+ await privacyQuery('status', value);
2380
+ };
2381
+ const updateReadReceiptsPrivacy = async (value) => {
2382
+ await privacyQuery('readreceipts', value);
2383
+ };
2384
+ const updateGroupsAddPrivacy = async (value) => {
2385
+ await privacyQuery('groupadd', value);
2386
+ };
2387
+ const updateDefaultDisappearingMode = async (duration) => {
2388
+ await query({
2389
+ tag: 'iq',
2390
+ attrs: {
2391
+ xmlns: 'disappearing_mode',
2392
+ to: index_js_6.S_WHATSAPP_NET,
2393
+ type: 'set'
2394
+ },
2395
+ content: [
2396
+ {
2397
+ tag: 'disappearing_mode',
2398
+ attrs: {
2399
+ duration: duration.toString()
2400
+ }
2401
+ }
2402
+ ]
2403
+ });
2404
+ };
2405
+ const getBotListV2 = async () => {
2406
+ const resp = await query({
2407
+ tag: 'iq',
2408
+ attrs: {
2409
+ xmlns: 'bot',
2410
+ to: index_js_6.S_WHATSAPP_NET,
2411
+ type: 'get'
2412
+ },
2413
+ content: [
2414
+ {
2415
+ tag: 'bot',
2416
+ attrs: {
2417
+ v: '2'
2418
+ }
2419
+ }
2420
+ ]
2421
+ });
2422
+ const botNode = (0, index_js_6.getBinaryNodeChild)(resp, 'bot');
2423
+ const botList = [];
2424
+ for (const section of (0, index_js_6.getBinaryNodeChildren)(botNode, 'section')) {
2425
+ if (section.attrs.type === 'all') {
2426
+ for (const bot of (0, index_js_6.getBinaryNodeChildren)(section, 'bot')) {
2427
+ botList.push({
2428
+ jid: bot.attrs.jid,
2429
+ personaId: bot.attrs['persona_id']
2430
+ });
2431
+ }
2432
+ }
2433
+ }
2434
+ return botList;
2435
+ };
2436
+ const fetchStatus = async (...jids) => {
2437
+ const usyncQuery = new index_js_7.USyncQuery().withStatusProtocol();
2438
+ for (const jid of jids) {
2439
+ usyncQuery.withUser(new index_js_7.USyncUser().withId(jid));
2440
+ }
2441
+ const result = await sock.executeUSyncQuery(usyncQuery);
2442
+ if (result) {
2443
+ return result.list;
2444
+ }
2445
+ };
2446
+ const fetchDisappearingDuration = async (...jids) => {
2447
+ const usyncQuery = new index_js_7.USyncQuery().withDisappearingModeProtocol();
2448
+ for (const jid of jids) {
2449
+ usyncQuery.withUser(new index_js_7.USyncUser().withId(jid));
2450
+ }
2451
+ const result = await sock.executeUSyncQuery(usyncQuery);
2452
+ if (result) {
2453
+ return result.list;
2454
+ }
2455
+ };
2456
+ // Kage: nota de compatibilidad.
2457
+ const findUserId = async (pnLid) => {
2458
+ const normalizedJid = (0, index_js_6.jidNormalizedUser)(pnLid);
2459
+ const userId = {
2460
+ lid: undefined,
2461
+ phoneNumber: undefined
2462
+ };
2463
+ if ((0, index_js_6.isPnUser)(normalizedJid) || (0, index_js_6.isHostedPnUser)(normalizedJid)) {
2464
+ userId.phoneNumber = normalizedJid;
2465
+ userId.lid = (0, index_js_6.jidNormalizedUser)((await signalRepository.lidMapping.getLIDsForPNs([normalizedJid]))?.[0]?.lid);
2466
+ }
2467
+ else if ((0, index_js_6.isLidUser)(normalizedJid) || (0, index_js_6.isHostedLidUser)(normalizedJid)) {
2468
+ userId.lid = normalizedJid;
2469
+ userId.phoneNumber = (0, index_js_6.jidNormalizedUser)((await signalRepository.lidMapping.getPNsForLIDs([normalizedJid]))?.[0]?.pn);
2470
+ }
2471
+ else {
2472
+ throw new index_js_2.HttpError('Invalid id input to find user ids', { statusCode: 400 });
2473
+ }
2474
+ return userId;
2475
+ };
2476
+ /** update the profile picture for yourself or a group */
2477
+ const updateProfilePicture = async (jid, content, dimensions) => {
2478
+ let targetJid;
2479
+ if (!jid) {
2480
+ throw new index_js_2.HttpError('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
2481
+ }
2482
+ if ((0, index_js_6.jidNormalizedUser)(jid) !== (0, index_js_6.jidNormalizedUser)(authState.creds.me.id)) {
2483
+ targetJid = (0, index_js_6.jidNormalizedUser)(jid); // in case it is someone other than us
2484
+ }
2485
+ else {
2486
+ targetJid = undefined;
2487
+ }
2488
+ const { img } = await (0, index_js_5.generateProfilePicture)(content, dimensions);
2489
+ await query({
2490
+ tag: 'iq',
2491
+ attrs: {
2492
+ to: index_js_6.S_WHATSAPP_NET,
2493
+ type: 'set',
2494
+ xmlns: 'w:profile:picture',
2495
+ ...(targetJid ? { target: targetJid } : {})
2496
+ },
2497
+ content: [
2498
+ {
2499
+ tag: 'picture',
2500
+ attrs: { type: 'image' },
2501
+ content: img
2502
+ }
2503
+ ]
2504
+ });
2505
+ };
2506
+ /** remove the profile picture for yourself or a group */
2507
+ const removeProfilePicture = async (jid) => {
2508
+ let targetJid;
2509
+ if (!jid) {
2510
+ throw new index_js_2.HttpError('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
2511
+ }
2512
+ if ((0, index_js_6.jidNormalizedUser)(jid) !== (0, index_js_6.jidNormalizedUser)(authState.creds.me.id)) {
2513
+ targetJid = (0, index_js_6.jidNormalizedUser)(jid); // in case it is someone other than us
2514
+ }
2515
+ else {
2516
+ targetJid = undefined;
2517
+ }
2518
+ await query({
2519
+ tag: 'iq',
2520
+ attrs: {
2521
+ to: index_js_6.S_WHATSAPP_NET,
2522
+ type: 'set',
2523
+ xmlns: 'w:profile:picture',
2524
+ ...(targetJid ? { target: targetJid } : {})
2525
+ }
2526
+ });
2527
+ };
2528
+ /** update the profile status for yourself */
2529
+ const updateProfileStatus = async (status) => {
2530
+ await query({
2531
+ tag: 'iq',
2532
+ attrs: {
2533
+ to: index_js_6.S_WHATSAPP_NET,
2534
+ type: 'set',
2535
+ xmlns: 'status'
2536
+ },
2537
+ content: [
2538
+ {
2539
+ tag: 'status',
2540
+ attrs: {},
2541
+ content: Buffer.from(status, 'utf-8')
2542
+ }
2543
+ ]
2544
+ });
2545
+ };
2546
+ const updateProfileName = async (name) => {
2547
+ await chatModify({ pushNameSetting: name }, '');
2548
+ };
2549
+ const fetchBlocklist = async () => {
2550
+ const result = await query({
2551
+ tag: 'iq',
2552
+ attrs: {
2553
+ xmlns: 'blocklist',
2554
+ to: index_js_6.S_WHATSAPP_NET,
2555
+ type: 'get'
2556
+ }
2557
+ });
2558
+ const listNode = (0, index_js_6.getBinaryNodeChild)(result, 'list');
2559
+ return (0, index_js_6.getBinaryNodeChildren)(listNode, 'item').map(n => n.attrs.jid);
2560
+ };
2561
+ const updateBlockStatus = async (jid, action) => {
2562
+ const normalizedJid = (0, index_js_6.jidNormalizedUser)(jid);
2563
+ let lid;
2564
+ let pn_jid;
2565
+ if ((0, index_js_6.isLidUser)(normalizedJid) || (0, index_js_6.isHostedLidUser)(normalizedJid)) {
2566
+ lid = normalizedJid;
2567
+ if (action === 'block') {
2568
+ const pn = (await findUserId(normalizedJid)).phoneNumber;
2569
+ if (!pn) {
2570
+ throw new index_js_2.HttpError(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
2571
+ }
2572
+ pn_jid = (0, index_js_6.jidNormalizedUser)(pn);
2573
+ }
2574
+ }
2575
+ else if ((0, index_js_6.isPnUser)(normalizedJid) || (0, index_js_6.isHostedPnUser)(normalizedJid)) {
2576
+ const mapped = (await findUserId(normalizedJid)).lid;
2577
+ if (!mapped) {
2578
+ throw new index_js_2.HttpError(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
2579
+ }
2580
+ lid = mapped;
2581
+ if (action === 'block') {
2582
+ pn_jid = (0, index_js_6.jidNormalizedUser)(normalizedJid);
2583
+ }
2584
+ }
2585
+ else {
2586
+ throw new index_js_2.HttpError(`Invalid jid: ${jid}`, { statusCode: 400 });
2587
+ }
2588
+ const itemAttrs = {
2589
+ action,
2590
+ jid: lid
2591
+ };
2592
+ if (action === 'block') {
2593
+ if (!pn_jid) {
2594
+ throw new index_js_2.HttpError(`pn_jid required for block: ${jid}`, { statusCode: 400 });
2595
+ }
2596
+ itemAttrs.pn_jid = pn_jid;
2597
+ }
2598
+ await query({
2599
+ tag: 'iq',
2600
+ attrs: {
2601
+ xmlns: 'blocklist',
2602
+ to: index_js_6.S_WHATSAPP_NET,
2603
+ type: 'set'
2604
+ },
2605
+ content: [
2606
+ {
2607
+ tag: 'item',
2608
+ attrs: itemAttrs
2609
+ }
2610
+ ]
2611
+ });
2612
+ };
2613
+ const getBusinessProfile = async (jid) => {
2614
+ const results = await query({
2615
+ tag: 'iq',
2616
+ attrs: {
2617
+ to: 's.whatsapp.net',
2618
+ xmlns: 'w:biz',
2619
+ type: 'get'
2620
+ },
2621
+ content: [
2622
+ {
2623
+ tag: 'business_profile',
2624
+ attrs: { v: '244' },
2625
+ content: [
2626
+ {
2627
+ tag: 'profile',
2628
+ attrs: { jid }
2629
+ }
2630
+ ]
2631
+ }
2632
+ ]
2633
+ });
2634
+ const profileNode = (0, index_js_6.getBinaryNodeChild)(results, 'business_profile');
2635
+ const profiles = (0, index_js_6.getBinaryNodeChild)(profileNode, 'profile');
2636
+ if (profiles) {
2637
+ const address = (0, index_js_6.getBinaryNodeChild)(profiles, 'address');
2638
+ const description = (0, index_js_6.getBinaryNodeChild)(profiles, 'description');
2639
+ const website = (0, index_js_6.getBinaryNodeChild)(profiles, 'website');
2640
+ const email = (0, index_js_6.getBinaryNodeChild)(profiles, 'email');
2641
+ const category = (0, index_js_6.getBinaryNodeChild)((0, index_js_6.getBinaryNodeChild)(profiles, 'categories'), 'category');
2642
+ const businessHours = (0, index_js_6.getBinaryNodeChild)(profiles, 'business_hours');
2643
+ const businessHoursConfig = businessHours
2644
+ ? (0, index_js_6.getBinaryNodeChildren)(businessHours, 'business_hours_config')
2645
+ : undefined;
2646
+ const websiteStr = website?.content?.toString();
2647
+ return {
2648
+ wid: profiles.attrs?.jid,
2649
+ address: address?.content?.toString(),
2650
+ description: description?.content?.toString() || '',
2651
+ website: websiteStr ? [websiteStr] : [],
2652
+ email: email?.content?.toString(),
2653
+ category: category?.content?.toString(),
2654
+ business_hours: {
2655
+ timezone: businessHours?.attrs?.timezone,
2656
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
2657
+ }
2658
+ };
2659
+ }
2660
+ };
2661
+ const cleanDirtyBits = async (type, fromTimestamp) => {
2662
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
2663
+ await sendNode({
2664
+ tag: 'iq',
2665
+ attrs: {
2666
+ to: index_js_6.S_WHATSAPP_NET,
2667
+ type: 'set',
2668
+ xmlns: 'urn:xmpp:whatsapp:dirty',
2669
+ id: generateMessageTag()
2670
+ },
2671
+ content: [
2672
+ {
2673
+ tag: 'clean',
2674
+ attrs: {
2675
+ type,
2676
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
2677
+ }
2678
+ }
2679
+ ]
2680
+ });
2681
+ };
2682
+ const newAppStateChunkHandler = (isInitialSync) => {
2683
+ return {
2684
+ onMutation(mutation) {
2685
+ (0, index_js_5.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
2686
+ }
2687
+ };
2688
+ };
2689
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
2690
+ const appStateSyncKeyCache = new Map();
2691
+ const getCachedAppStateSyncKey = async (keyId) => {
2692
+ if (appStateSyncKeyCache.has(keyId)) {
2693
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
2694
+ }
2695
+ const key = await getAppStateSyncKey(keyId);
2696
+ appStateSyncKeyCache.set(keyId, key ?? null);
2697
+ return key;
2698
+ };
2699
+ // we use this to determine which events to fire
2700
+ // otherwise when we resync from scratch -- all notifications will fire
2701
+ const initialVersionMap = {};
2702
+ const globalMutationMap = {};
2703
+ await authState.keys.transaction(async () => {
2704
+ const collectionsToHandle = new Set(collections);
2705
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
2706
+ const attemptsMap = {};
2707
+ // collections that failed and need a full snapshot on retry
2708
+ // mirrors WA Web's ErrorFatal -> force snapshot behavior
2709
+ const forceSnapshotCollections = new Set();
2710
+ // keep executing till all collections are done
2711
+ // sometimes a single patch request will not return all the patches (God knows why)
2712
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
2713
+ while (collectionsToHandle.size) {
2714
+ const states = {};
2715
+ const nodes = [];
2716
+ for (const name of collectionsToHandle) {
2717
+ const result = await authState.keys.get('app-state-sync-version', [name]);
2718
+ let state = result[name];
2719
+ if (state) {
2720
+ state = (0, index_js_5.ensureLTHashStateVersion)(state);
2721
+ if (typeof initialVersionMap[name] === 'undefined') {
2722
+ initialVersionMap[name] = state.version;
2723
+ }
2724
+ }
2725
+ else {
2726
+ state = (0, index_js_5.newLTHashState)();
2727
+ }
2728
+ states[name] = state;
2729
+ const shouldForceSnapshot = forceSnapshotCollections.has(name);
2730
+ if (shouldForceSnapshot) {
2731
+ forceSnapshotCollections.delete(name);
2732
+ }
2733
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
2734
+ nodes.push({
2735
+ tag: 'collection',
2736
+ attrs: {
2737
+ name,
2738
+ version: state.version.toString(),
2739
+ // return snapshot if syncing from scratch or forcing after a failed attempt
2740
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
2741
+ }
2742
+ });
2743
+ }
2744
+ const result = await query({
2745
+ tag: 'iq',
2746
+ attrs: {
2747
+ to: index_js_6.S_WHATSAPP_NET,
2748
+ xmlns: 'w:sync:app:state',
2749
+ type: 'set'
2750
+ },
2751
+ content: [
2752
+ {
2753
+ tag: 'sync',
2754
+ attrs: {},
2755
+ content: nodes
2756
+ }
2757
+ ]
2758
+ });
2759
+ // extract from binary node
2760
+ const decoded = await (0, index_js_5.extractSyncdPatches)(result, config?.options);
2761
+ for (const key in decoded) {
2762
+ const name = key;
2763
+ const { patches, hasMorePatches, snapshot } = decoded[name];
2764
+ try {
2765
+ if (snapshot) {
2766
+ const { state: newState, mutationMap } = await (0, index_js_5.decodeSyncdSnapshot)(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
2767
+ states[name] = newState;
2768
+ Object.assign(globalMutationMap, mutationMap);
2769
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
2770
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
2771
+ }
2772
+ // only process if there are syncd patches
2773
+ if (patches.length) {
2774
+ const { state: newState, mutationMap } = await (0, index_js_5.decodePatches)(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
2775
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
2776
+ logger.info(`synced ${name} to v${newState.version}`);
2777
+ initialVersionMap[name] = newState.version;
2778
+ Object.assign(globalMutationMap, mutationMap);
2779
+ }
2780
+ if (hasMorePatches) {
2781
+ logger.info(`${name} has more patches...`);
2782
+ }
2783
+ else {
2784
+ // collection is done with sync
2785
+ collectionsToHandle.delete(name);
2786
+ }
2787
+ }
2788
+ catch (error) {
2789
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
2790
+ const logData = {
2791
+ name,
2792
+ attempt: attemptsMap[name],
2793
+ version: states[name].version,
2794
+ statusCode: error.output?.statusCode,
2795
+ errorType: error.name,
2796
+ error: error.stack
2797
+ };
2798
+ if ((0, index_js_5.isMissingKeyError)(error) && attemptsMap[name] >= index_js_5.MAX_SYNC_ATTEMPTS) {
2799
+ // WA Web treats missing keys as "Blocked" — park the collection
2800
+ // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
2801
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
2802
+ blockedCollections.add(name);
2803
+ collectionsToHandle.delete(name);
2804
+ }
2805
+ else if ((0, index_js_5.isMissingKeyError)(error)) {
2806
+ // Retry with a snapshot which may use a different key.
2807
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
2808
+ forceSnapshotCollections.add(name);
2809
+ }
2810
+ else if ((0, index_js_5.isAppStateSyncIrrecoverable)(error, attemptsMap[name])) {
2811
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
2812
+ collectionsToHandle.delete(name);
2813
+ }
2814
+ else {
2815
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
2816
+ // force a full snapshot on retry to recover from
2817
+ // corrupted local state (e.g. LTHash MAC mismatch)
2818
+ forceSnapshotCollections.add(name);
2819
+ }
2820
+ }
2821
+ }
2822
+ }
2823
+ }, authState?.creds?.me?.id || 'resync-app-state');
2824
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
2825
+ for (const key in globalMutationMap) {
2826
+ onMutation(globalMutationMap[key]);
2827
+ }
2828
+ });
2829
+ /**
2830
+ * fetch the profile picture of a user/group
2831
+ * type = "preview" for a low res picture
2832
+ * type = "image for the high res picture"
2833
+ */
2834
+ const profilePictureUrl = async (jid, type = 'image', timeoutMs = 5000, shouldIncludeTcToken = true) => {
2835
+ // WA Web only includes tctoken for user JIDs (not groups/newsletters)
2836
+ // and never for own profile pic (Chat model for self has no tcToken).
2837
+ // Including tctoken for own JID causes the server to never respond.
2838
+ const normalizedJid = (0, index_js_6.jidNormalizedUser)(jid);
2839
+ const isUserJid = (0, index_js_6.isPnUser)(normalizedJid) || (0, index_js_6.isLidUser)(normalizedJid);
2840
+ const me = authState.creds.me;
2841
+ const isSelf = me && (normalizedJid === (0, index_js_6.jidNormalizedUser)(me.id) || (me.lid && normalizedJid === (0, index_js_6.jidNormalizedUser)(me.lid)));
2842
+ let tcTokenContent;
2843
+ if (shouldIncludeTcToken && serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
2844
+ tcTokenContent = await (0, tc_token_utils_js_1.buildTcTokenFromJid)({
2845
+ authState,
2846
+ jid: normalizedJid,
2847
+ getLIDForPN
2848
+ });
2849
+ }
2850
+ jid = (0, index_js_6.jidNormalizedUser)(jid);
2851
+ const result = await query({
2852
+ tag: 'iq',
2853
+ attrs: {
2854
+ target: jid,
2855
+ to: index_js_6.S_WHATSAPP_NET,
2856
+ type: 'get',
2857
+ xmlns: 'w:profile:picture'
2858
+ },
2859
+ content: (0, exports.buildProfilePictureQueryContent)(type, tcTokenContent)
2860
+ }, timeoutMs);
2861
+ const child = (0, index_js_6.getBinaryNodeChild)(result, 'picture');
2862
+ return child?.attrs?.url;
2863
+ };
2864
+ const createCallLink = async (type, event, timeoutMs) => {
2865
+ const result = await query({
2866
+ tag: 'call',
2867
+ attrs: {
2868
+ id: generateMessageTag(),
2869
+ to: '@call'
2870
+ },
2871
+ content: [
2872
+ {
2873
+ tag: 'link_create',
2874
+ attrs: { media: type },
2875
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
2876
+ }
2877
+ ]
2878
+ }, timeoutMs);
2879
+ const child = (0, index_js_6.getBinaryNodeChild)(result, 'link_create');
2880
+ return child?.attrs?.token;
2881
+ };
2882
+ const sendPresenceUpdate = async (type, toJid) => {
2883
+ const me = authState.creds.me;
2884
+ const isAvailableType = type === 'available';
2885
+ if (isAvailableType || type === 'unavailable') {
2886
+ if (!me.name) {
2887
+ logger.warn('no name present, ignoring presence update request...');
2888
+ return;
2889
+ }
2890
+ ev.emit('connection.update', { isOnline: isAvailableType });
2891
+ if (isAvailableType) {
2892
+ void sendUnifiedSession();
2893
+ }
2894
+ await sendNode({
2895
+ tag: 'presence',
2896
+ attrs: {
2897
+ name: me.name.replace(/@/g, ''),
2898
+ type
2899
+ }
2900
+ });
2901
+ }
2902
+ else {
2903
+ const { server } = (0, index_js_6.jidDecode)(toJid);
2904
+ const isLid = server === 'lid';
2905
+ await sendNode({
2906
+ tag: 'chatstate',
2907
+ attrs: {
2908
+ from: isLid ? me.lid : me.id,
2909
+ to: toJid
2910
+ },
2911
+ content: [
2912
+ {
2913
+ tag: type === 'recording' ? 'composing' : type,
2914
+ attrs: type === 'recording' ? { media: 'audio' } : {}
2915
+ }
2916
+ ]
2917
+ });
2918
+ }
2919
+ };
2920
+ /**
2921
+ * @param toJid the jid to subscribe to
2922
+ * @param tcToken token for subscription, use if present
2923
+ */
2924
+ const presenceSubscribe = async (toJid) => {
2925
+ // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
2926
+ const normalizedToJid = (0, index_js_6.jidNormalizedUser)(toJid);
2927
+ const isUserJid = (0, index_js_6.isPnUser)(normalizedToJid) || (0, index_js_6.isLidUser)(normalizedToJid);
2928
+ const tcTokenContent = isUserJid
2929
+ ? await (0, tc_token_utils_js_1.buildTcTokenFromJid)({ authState, jid: normalizedToJid, getLIDForPN })
2930
+ : undefined;
2931
+ return sendNode({
2932
+ tag: 'presence',
2933
+ attrs: {
2934
+ to: toJid,
2935
+ id: generateMessageTag(),
2936
+ type: 'subscribe'
2937
+ },
2938
+ content: tcTokenContent
2939
+ });
2940
+ };
2941
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
2942
+ let presence;
2943
+ const jid = attrs.from;
2944
+ const participant = attrs.participant || attrs.from;
2945
+ if (shouldIgnoreJid(jid) && jid !== index_js_6.S_WHATSAPP_NET) {
2946
+ return;
2947
+ }
2948
+ if (tag === 'presence') {
2949
+ presence = {
2950
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
2951
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
2952
+ groupOnlineCount: attrs.count ? +attrs.count : undefined
2953
+ };
2954
+ }
2955
+ else if (Array.isArray(content)) {
2956
+ const [firstChild] = content;
2957
+ let type = firstChild.tag;
2958
+ if (type === 'paused') {
2959
+ type = 'available';
2960
+ }
2961
+ if (firstChild.attrs?.media === 'audio') {
2962
+ type = 'recording';
2963
+ }
2964
+ presence = { lastKnownPresence: type };
2965
+ }
2966
+ else {
2967
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
2968
+ }
2969
+ if (presence) {
2970
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
2971
+ }
2972
+ };
2973
+ const appPatch = async (patchCreate) => {
2974
+ const name = patchCreate.type;
2975
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
2976
+ if (!myAppStateKeyId) {
2977
+ throw new index_js_2.HttpError('App state key not present!', { statusCode: 400 });
2978
+ }
2979
+ let initial;
2980
+ let encodeResult;
2981
+ await appStatePatchMutex.mutex(async () => {
2982
+ await authState.keys.transaction(async () => {
2983
+ logger.debug({ patch: patchCreate }, 'applying app patch');
2984
+ await resyncAppState([name], false);
2985
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
2986
+ initial = currentSyncVersion ? (0, index_js_5.ensureLTHashStateVersion)(currentSyncVersion) : (0, index_js_5.newLTHashState)();
2987
+ encodeResult = await (0, index_js_5.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
2988
+ const { patch, state } = encodeResult;
2989
+ const node = {
2990
+ tag: 'iq',
2991
+ attrs: {
2992
+ to: index_js_6.S_WHATSAPP_NET,
2993
+ type: 'set',
2994
+ xmlns: 'w:sync:app:state'
2995
+ },
2996
+ content: [
2997
+ {
2998
+ tag: 'sync',
2999
+ attrs: {},
3000
+ content: [
3001
+ {
3002
+ tag: 'collection',
3003
+ attrs: {
3004
+ name,
3005
+ version: (state.version - 1).toString(),
3006
+ return_snapshot: 'false'
3007
+ },
3008
+ content: [
3009
+ {
3010
+ tag: 'patch',
3011
+ attrs: {},
3012
+ content: index_js_1.proto.SyncdPatch.encode(patch).finish()
3013
+ }
3014
+ ]
3015
+ }
3016
+ ]
3017
+ }
3018
+ ]
3019
+ };
3020
+ await query(node);
3021
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
3022
+ }, authState?.creds?.me?.id || 'app-patch');
3023
+ });
3024
+ if (config.emitOwnEvents) {
3025
+ const { onMutation } = newAppStateChunkHandler(false);
3026
+ const { mutationMap } = await (0, index_js_5.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
3027
+ for (const key in mutationMap) {
3028
+ onMutation(mutationMap[key]);
3029
+ }
3030
+ }
3031
+ };
3032
+ /** fetch AB props */
3033
+ const fetchProps = async () => {
3034
+ const resultNode = await query({
3035
+ tag: 'iq',
3036
+ attrs: {
3037
+ to: index_js_6.S_WHATSAPP_NET,
3038
+ xmlns: 'abt',
3039
+ type: 'get'
3040
+ },
3041
+ content: [
3042
+ {
3043
+ tag: 'props',
3044
+ attrs: {
3045
+ protocol: '1',
3046
+ ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
3047
+ }
3048
+ }
3049
+ ]
3050
+ });
3051
+ const propsNode = (0, index_js_6.getBinaryNodeChild)(resultNode, 'props');
3052
+ let props = {};
3053
+ if (propsNode) {
3054
+ if (propsNode.attrs?.hash) {
3055
+ // on some clients, the hash is returning as undefined
3056
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
3057
+ ev.emit('creds.update', authState.creds);
3058
+ }
3059
+ props = (0, index_js_6.reduceBinaryNodeToDictionary)(propsNode, 'prop');
3060
+ }
3061
+ // Extract protocol-relevant AB props (only the ones we need)
3062
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
3063
+ if (privacyTokenProp !== undefined) {
3064
+ serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
3065
+ }
3066
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
3067
+ if (profilePicProp !== undefined) {
3068
+ serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
3069
+ }
3070
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
3071
+ if (lidIssueProp !== undefined) {
3072
+ serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
3073
+ }
3074
+ logger.debug({ serverProps }, 'fetched props');
3075
+ return props;
3076
+ };
3077
+ /**
3078
+ * modify a chat -- mark unread, read etc.
3079
+ * lastMessages must be sorted in reverse chronologically
3080
+ * requires the last messages till the last message received; required for archive & unread
3081
+ */
3082
+ const chatModify = (mod, jid) => {
3083
+ const patch = (0, index_js_5.chatModificationToAppPatch)(mod, jid);
3084
+ return appPatch(patch);
3085
+ };
3086
+ /**
3087
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
3088
+ */
3089
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
3090
+ return chatModify({
3091
+ disableLinkPreviews: { isPreviewsDisabled }
3092
+ }, '');
3093
+ };
3094
+ /**
3095
+ * Star or Unstar a message
3096
+ */
3097
+ const star = (jid, messages, star) => {
3098
+ return chatModify({
3099
+ star: {
3100
+ messages,
3101
+ star
3102
+ }
3103
+ }, jid);
3104
+ };
3105
+ /**
3106
+ * Add or Edit Contact
3107
+ */
3108
+ const addOrEditContact = (jid, contact) => {
3109
+ return chatModify({
3110
+ contact
3111
+ }, jid);
3112
+ };
3113
+ /**
3114
+ * Remove Contact
3115
+ */
3116
+ const removeContact = (jid) => {
3117
+ return chatModify({
3118
+ contact: null
3119
+ }, jid);
3120
+ };
3121
+ /**
3122
+ * Adds label
3123
+ */
3124
+ const addLabel = (jid, labels) => {
3125
+ return chatModify({
3126
+ addLabel: {
3127
+ ...labels
3128
+ }
3129
+ }, jid);
3130
+ };
3131
+ /**
3132
+ * Adds label for the chats
3133
+ */
3134
+ const addChatLabel = (jid, labelId) => {
3135
+ return chatModify({
3136
+ addChatLabel: {
3137
+ labelId
3138
+ }
3139
+ }, jid);
3140
+ };
3141
+ /**
3142
+ * Removes label for the chat
3143
+ */
3144
+ const removeChatLabel = (jid, labelId) => {
3145
+ return chatModify({
3146
+ removeChatLabel: {
3147
+ labelId
3148
+ }
3149
+ }, jid);
3150
+ };
3151
+ /**
3152
+ * Adds label for the message
3153
+ */
3154
+ const addMessageLabel = (jid, messageId, labelId) => {
3155
+ return chatModify({
3156
+ addMessageLabel: {
3157
+ messageId,
3158
+ labelId
3159
+ }
3160
+ }, jid);
3161
+ };
3162
+ /**
3163
+ * Removes label for the message
3164
+ */
3165
+ const removeMessageLabel = (jid, messageId, labelId) => {
3166
+ return chatModify({
3167
+ removeMessageLabel: {
3168
+ messageId,
3169
+ labelId
3170
+ }
3171
+ }, jid);
3172
+ };
3173
+ /**
3174
+ * Add or Edit Quick Reply
3175
+ */
3176
+ const addOrEditQuickReply = (quickReply) => {
3177
+ return chatModify({
3178
+ quickReply
3179
+ }, '');
3180
+ };
3181
+ /**
3182
+ * Remove Quick Reply
3183
+ */
3184
+ const removeQuickReply = (timestamp) => {
3185
+ return chatModify({
3186
+ quickReply: { timestamp, deleted: true }
3187
+ }, '');
3188
+ };
3189
+ /**
3190
+ * queries need to be fired on connection open
3191
+ * help ensure parity with WA Web
3192
+ * */
3193
+ const executeInitQueries = async () => {
3194
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
3195
+ };
3196
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
3197
+ ev.emit('messages.upsert', { messages: [msg], type });
3198
+ if (!!msg.pushName) {
3199
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
3200
+ jid = (0, index_js_6.jidNormalizedUser)(jid);
3201
+ if (!msg.key.fromMe) {
3202
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
3203
+ }
3204
+ // update our pushname too
3205
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
3206
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
3207
+ }
3208
+ }
3209
+ const historyMsg = (0, index_js_5.getHistoryMsg)(msg.message);
3210
+ const shouldProcessHistoryMsg = historyMsg
3211
+ ? shouldSyncHistoryMessage(historyMsg) &&
3212
+ index_js_3.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
3213
+ : false;
3214
+ if (historyMsg && shouldProcessHistoryMsg) {
3215
+ const syncType = historyMsg.syncType;
3216
+ // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
3217
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
3218
+ !historySyncStatus.initialBootstrapComplete) {
3219
+ historySyncStatus.initialBootstrapComplete = true;
3220
+ ev.emit('messaging-history.status', {
3221
+ syncType,
3222
+ status: 'complete',
3223
+ explicit: true
3224
+ });
3225
+ }
3226
+ // RECENT with progress === 100 — explicit completion
3227
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.RECENT &&
3228
+ historyMsg.progress === 100 &&
3229
+ !historySyncStatus.recentSyncComplete) {
3230
+ historySyncStatus.recentSyncComplete = true;
3231
+ clearTimeout(historySyncPausedTimeout);
3232
+ historySyncPausedTimeout = undefined;
3233
+ ev.emit('messaging-history.status', {
3234
+ syncType,
3235
+ status: 'complete',
3236
+ explicit: true
3237
+ });
3238
+ }
3239
+ // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
3240
+ if (syncType === index_js_1.proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
3241
+ clearTimeout(historySyncPausedTimeout);
3242
+ historySyncPausedTimeout = setTimeout(() => {
3243
+ if (!historySyncStatus.recentSyncComplete) {
3244
+ historySyncStatus.recentSyncComplete = true;
3245
+ ev.emit('messaging-history.status', {
3246
+ syncType: index_js_1.proto.HistorySync.HistorySyncType.RECENT,
3247
+ status: 'paused',
3248
+ explicit: false
3249
+ });
3250
+ }
3251
+ historySyncPausedTimeout = undefined;
3252
+ }, index_js_3.HISTORY_SYNC_PAUSED_TIMEOUT_MS);
3253
+ }
3254
+ }
3255
+ // State machine: decide on sync and flush
3256
+ if (historyMsg && syncState === State_js_1.SyncState.AwaitingInitialSync) {
3257
+ if (awaitingSyncTimeout) {
3258
+ clearTimeout(awaitingSyncTimeout);
3259
+ awaitingSyncTimeout = undefined;
3260
+ }
3261
+ if (shouldProcessHistoryMsg) {
3262
+ syncState = State_js_1.SyncState.Syncing;
3263
+ logger.info('Transitioned to Syncing state');
3264
+ // Let doAppStateSync handle the final flush after it's done
3265
+ }
3266
+ else {
3267
+ syncState = State_js_1.SyncState.Online;
3268
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
3269
+ ev.flush();
3270
+ }
3271
+ }
3272
+ const doAppStateSync = async () => {
3273
+ if (syncState === State_js_1.SyncState.Syncing) {
3274
+ // All collections will be synced, so clear any blocked ones
3275
+ blockedCollections.clear();
3276
+ logger.info('Doing app state sync');
3277
+ await resyncAppState(index_js_4.ALL_WA_PATCH_NAMES, true);
3278
+ // Sync is complete, go online and flush everything
3279
+ syncState = State_js_1.SyncState.Online;
3280
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
3281
+ ev.flush();
3282
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
3283
+ ev.emit('creds.update', { accountSyncCounter });
3284
+ }
3285
+ };
3286
+ await Promise.all([
3287
+ (async () => {
3288
+ if (shouldProcessHistoryMsg) {
3289
+ await doAppStateSync();
3290
+ }
3291
+ })(),
3292
+ (0, process_message_js_1.default)(msg, {
3293
+ signalRepository,
3294
+ shouldProcessHistoryMsg,
3295
+ placeholderResendCache,
3296
+ ev,
3297
+ creds: authState.creds,
3298
+ keyStore: authState.keys,
3299
+ logger,
3300
+ options: config.options,
3301
+ getMessage
3302
+ })
3303
+ ]);
3304
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
3305
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === State_js_1.SyncState.Syncing) {
3306
+ logger.info('App state sync key arrived, triggering app state sync');
3307
+ await doAppStateSync();
3308
+ }
3309
+ });
3310
+ ws.on('CB:presence', handlePresenceUpdate);
3311
+ ws.on('CB:chatstate', handlePresenceUpdate);
3312
+ ws.on('CB:ib,,dirty', async (node) => {
3313
+ const { attrs } = (0, index_js_6.getBinaryNodeChild)(node, 'dirty');
3314
+ const type = attrs.type;
3315
+ switch (type) {
3316
+ case 'account_sync':
3317
+ if (attrs.timestamp) {
3318
+ let { lastAccountSyncTimestamp } = authState.creds;
3319
+ if (lastAccountSyncTimestamp) {
3320
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
3321
+ }
3322
+ lastAccountSyncTimestamp = +attrs.timestamp;
3323
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
3324
+ }
3325
+ break;
3326
+ case 'groups':
3327
+ // handled in groups.ts
3328
+ break;
3329
+ default:
3330
+ logger.info({ node }, 'received unknown sync');
3331
+ break;
3332
+ }
3333
+ });
3334
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
3335
+ if (connection === 'close') {
3336
+ blockedCollections.clear();
3337
+ clearTimeout(historySyncPausedTimeout);
3338
+ historySyncPausedTimeout = undefined;
3339
+ }
3340
+ if (connection === 'open') {
3341
+ if (fireInitQueries) {
3342
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
3343
+ }
3344
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
3345
+ }
3346
+ if (!receivedPendingNotifications || syncState !== State_js_1.SyncState.Connecting) {
3347
+ return;
3348
+ }
3349
+ historySyncStatus.initialBootstrapComplete = false;
3350
+ historySyncStatus.recentSyncComplete = false;
3351
+ clearTimeout(historySyncPausedTimeout);
3352
+ historySyncPausedTimeout = undefined;
3353
+ syncState = State_js_1.SyncState.AwaitingInitialSync;
3354
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
3355
+ ev.buffer();
3356
+ const willSyncHistory = shouldSyncHistoryMessage(index_js_1.proto.Message.HistorySyncNotification.create({
3357
+ syncType: index_js_1.proto.HistorySync.HistorySyncType.RECENT
3358
+ }));
3359
+ if (!willSyncHistory) {
3360
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
3361
+ syncState = State_js_1.SyncState.Online;
3362
+ setTimeout(() => ev.flush(), 0);
3363
+ return;
3364
+ }
3365
+ // On reconnection (accountSyncCounter > 0), the server does not push
3366
+ // history sync notifications — the device already has its data.
3367
+ // Skip the 20s wait and go online immediately.
3368
+ if (authState.creds.accountSyncCounter > 0) {
3369
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
3370
+ syncState = State_js_1.SyncState.Online;
3371
+ setTimeout(() => ev.flush(), 0);
3372
+ return;
3373
+ }
3374
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.');
3375
+ if (awaitingSyncTimeout) {
3376
+ clearTimeout(awaitingSyncTimeout);
3377
+ }
3378
+ awaitingSyncTimeout = setTimeout(() => {
3379
+ if (syncState === State_js_1.SyncState.AwaitingInitialSync) {
3380
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
3381
+ syncState = State_js_1.SyncState.Online;
3382
+ ev.flush();
3383
+ // Increment so subsequent reconnections skip the 20s wait.
3384
+ // Late-arriving history is still processed via processMessage
3385
+ // regardless of the state machine phase.
3386
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
3387
+ ev.emit('creds.update', { accountSyncCounter });
3388
+ }
3389
+ }, 20000);
3390
+ });
3391
+ // When an app state sync key arrives (myAppStateKeyId is set) and there are
3392
+ // collections blocked on a missing key, trigger a re-sync for just those collections.
3393
+ // This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
3394
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
3395
+ if (!myAppStateKeyId || blockedCollections.size === 0) {
3396
+ return;
3397
+ }
3398
+ // If we're in the middle of a full sync, doAppStateSync handles all collections
3399
+ if (syncState === State_js_1.SyncState.Syncing) {
3400
+ blockedCollections.clear();
3401
+ return;
3402
+ }
3403
+ const collections = [...blockedCollections];
3404
+ blockedCollections.clear();
3405
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
3406
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
3407
+ });
3408
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
3409
+ try {
3410
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
3411
+ }
3412
+ catch (error) {
3413
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
3414
+ }
3415
+ });
3416
+ registerSocketEndHandler(() => {
3417
+ if (awaitingSyncTimeout) {
3418
+ clearTimeout(awaitingSyncTimeout);
3419
+ awaitingSyncTimeout = undefined;
3420
+ }
3421
+ if (!config.placeholderResendCache && placeholderResendCache.close) {
3422
+ placeholderResendCache.close();
3423
+ }
3424
+ syncState = State_js_1.SyncState.Connecting;
3425
+ privacySettings = undefined;
3426
+ });
3427
+ return {
3428
+ ...sock,
3429
+ findUserId,
3430
+ serverProps,
3431
+ createCallLink,
3432
+ getBotListV2,
3433
+ messageMutex,
3434
+ receiptMutex,
3435
+ appStatePatchMutex,
3436
+ notificationMutex,
3437
+ fetchPrivacySettings,
3438
+ upsertMessage,
3439
+ appPatch,
3440
+ sendPresenceUpdate,
3441
+ presenceSubscribe,
3442
+ profilePictureUrl,
3443
+ fetchBlocklist,
3444
+ fetchStatus,
3445
+ fetchDisappearingDuration,
3446
+ updateProfilePicture,
3447
+ removeProfilePicture,
3448
+ updateProfileStatus,
3449
+ updateProfileName,
3450
+ updateBlockStatus,
3451
+ updateDisableLinkPreviewsPrivacy,
3452
+ updateCallPrivacy,
3453
+ updateMessagesPrivacy,
3454
+ updateLastSeenPrivacy,
3455
+ updateOnlinePrivacy,
3456
+ updateProfilePicturePrivacy,
3457
+ updateStatusPrivacy,
3458
+ updateReadReceiptsPrivacy,
3459
+ updateGroupsAddPrivacy,
3460
+ updateDefaultDisappearingMode,
3461
+ getBusinessProfile,
3462
+ resyncAppState,
3463
+ chatModify,
3464
+ cleanDirtyBits,
3465
+ addOrEditContact,
3466
+ removeContact,
3467
+ placeholderResendCache,
3468
+ addLabel,
3469
+ addChatLabel,
3470
+ removeChatLabel,
3471
+ addMessageLabel,
3472
+ removeMessageLabel,
3473
+ star,
3474
+ addOrEditQuickReply,
3475
+ removeQuickReply
3476
+ };
3477
+ };
3478
+ exports.makeChatsSocket = makeChatsSocket;
3479
+
3480
+ return module.exports;
3481
+ })();
3482
+ for (const key of Object.keys(__kageModule131)) {
3483
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule131[key]});
3484
+ }
3485
+ Object.defineProperty(exports, Symbol.for('kage.advanced'), {value:__kageModule131, configurable:true});