@nerxa/socketon 0.0.0-stage → 1.21.1

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 (289) hide show
  1. package/EXPERIMENTAL.md +350 -0
  2. package/LICENSE +24 -0
  3. package/README.md +6317 -2
  4. package/WAProto/index.d.ts +17301 -0
  5. package/WAProto/index.js +125088 -0
  6. package/engine-requirements.js +14 -0
  7. package/package.json +125 -4
  8. package/src/Defaults/index.d.ts +152 -0
  9. package/src/Defaults/index.js +164 -0
  10. package/src/MessageBuilder/bot-signature.d.ts +22 -0
  11. package/src/MessageBuilder/bot-signature.js +122 -0
  12. package/src/MessageBuilder/extras.d.ts +449 -0
  13. package/src/MessageBuilder/extras.js +1356 -0
  14. package/src/MessageBuilder/index.d.ts +210 -0
  15. package/src/MessageBuilder/index.js +3594 -0
  16. package/src/MessageBuilder/metaai.d.ts +438 -0
  17. package/src/MessageBuilder/metaai.js +890 -0
  18. package/src/Signal/Group/ciphertext-message.d.ts +9 -0
  19. package/src/Signal/Group/ciphertext-message.js +11 -0
  20. package/src/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/src/Signal/Group/group-session-builder.js +27 -0
  22. package/src/Signal/Group/group_cipher.d.ts +11 -0
  23. package/src/Signal/Group/group_cipher.js +78 -0
  24. package/src/Signal/Group/index.d.ts +11 -0
  25. package/src/Signal/Group/index.js +11 -0
  26. package/src/Signal/Group/keyhelper.d.ts +6 -0
  27. package/src/Signal/Group/keyhelper.js +17 -0
  28. package/src/Signal/Group/sender-chain-key.d.ts +13 -0
  29. package/src/Signal/Group/sender-chain-key.js +25 -0
  30. package/src/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  31. package/src/Signal/Group/sender-key-distribution-message.js +62 -0
  32. package/src/Signal/Group/sender-key-message.d.ts +18 -0
  33. package/src/Signal/Group/sender-key-message.js +65 -0
  34. package/src/Signal/Group/sender-key-name.d.ts +11 -0
  35. package/src/Signal/Group/sender-key-name.js +47 -0
  36. package/src/Signal/Group/sender-key-record.d.ts +12 -0
  37. package/src/Signal/Group/sender-key-record.js +40 -0
  38. package/src/Signal/Group/sender-key-state.d.ts +16 -0
  39. package/src/Signal/Group/sender-key-state.js +83 -0
  40. package/src/Signal/Group/sender-message-key.d.ts +11 -0
  41. package/src/Signal/Group/sender-message-key.js +25 -0
  42. package/src/Signal/libsignal.d.ts +54 -0
  43. package/src/Signal/libsignal.js +427 -0
  44. package/src/Signal/lid-mapping.d.ts +20 -0
  45. package/src/Signal/lid-mapping.js +274 -0
  46. package/src/Socket/Client/index.d.ts +2 -0
  47. package/src/Socket/Client/index.js +3 -0
  48. package/src/Socket/Client/tcp.js +177 -0
  49. package/src/Socket/Client/types.d.ts +5 -0
  50. package/src/Socket/Client/types.js +9 -0
  51. package/src/Socket/Client/websocket.d.ts +12 -0
  52. package/src/Socket/Client/websocket.js +53 -0
  53. package/src/Socket/business.d.ts +431 -0
  54. package/src/Socket/business.js +379 -0
  55. package/src/Socket/chats.d.ts +247 -0
  56. package/src/Socket/chats.js +1484 -0
  57. package/src/Socket/communities.d.ts +598 -0
  58. package/src/Socket/communities.js +421 -0
  59. package/src/Socket/email.js +145 -0
  60. package/src/Socket/groups.d.ts +298 -0
  61. package/src/Socket/groups.js +339 -0
  62. package/src/Socket/index.d.ts +581 -0
  63. package/src/Socket/index.js +77 -0
  64. package/src/Socket/messages-recv.d.ts +370 -0
  65. package/src/Socket/messages-recv.js +1864 -0
  66. package/src/Socket/messages-send.d.ts +390 -0
  67. package/src/Socket/messages-send.js +1574 -0
  68. package/src/Socket/mex.d.ts +1 -0
  69. package/src/Socket/mex.js +44 -0
  70. package/src/Socket/mobile-builders.js +72 -0
  71. package/src/Socket/mobile.js +424 -0
  72. package/src/Socket/newsletter.d.ts +468 -0
  73. package/src/Socket/newsletter.js +671 -0
  74. package/src/Socket/socket.d.ts +77 -0
  75. package/src/Socket/socket.js +1106 -0
  76. package/src/Store/index.d.ts +3 -0
  77. package/src/Store/index.js +3 -0
  78. package/src/Store/make-in-memory-store.d.ts +62 -0
  79. package/src/Store/make-in-memory-store.js +396 -0
  80. package/src/Store/make-ordered-dictionary.d.ts +12 -0
  81. package/src/Store/make-ordered-dictionary.js +78 -0
  82. package/src/Store/object-repository.d.ts +10 -0
  83. package/src/Store/object-repository.js +23 -0
  84. package/src/Types/Auth.d.ts +1 -0
  85. package/src/Types/Auth.js +1 -0
  86. package/src/Types/Bussines.d.ts +1 -0
  87. package/src/Types/Bussines.js +1 -0
  88. package/src/Types/Call.d.ts +1 -0
  89. package/src/Types/Call.js +1 -0
  90. package/src/Types/Chat.d.ts +2 -0
  91. package/src/Types/Chat.js +24 -0
  92. package/src/Types/Contact.d.ts +1 -0
  93. package/src/Types/Contact.js +1 -0
  94. package/src/Types/Events.d.ts +1 -0
  95. package/src/Types/Events.js +0 -0
  96. package/src/Types/GroupMetadata.d.ts +5 -0
  97. package/src/Types/GroupMetadata.js +6 -0
  98. package/src/Types/Label.d.ts +2 -0
  99. package/src/Types/Label.js +24 -0
  100. package/src/Types/LabelAssociation.d.ts +2 -0
  101. package/src/Types/LabelAssociation.js +6 -0
  102. package/src/Types/Message.d.ts +13 -0
  103. package/src/Types/Message.js +23 -0
  104. package/src/Types/Mex.d.ts +2 -0
  105. package/src/Types/Mex.js +95 -0
  106. package/src/Types/Product.d.ts +1 -0
  107. package/src/Types/Product.js +1 -0
  108. package/src/Types/Signal.d.ts +1 -0
  109. package/src/Types/Signal.js +0 -0
  110. package/src/Types/Socket.d.ts +1 -0
  111. package/src/Types/Socket.js +0 -0
  112. package/src/Types/State.d.ts +5 -0
  113. package/src/Types/State.js +54 -0
  114. package/src/Types/USync.d.ts +1 -0
  115. package/src/Types/USync.js +0 -0
  116. package/src/Types/index.d.ts +13 -0
  117. package/src/Types/index.js +25 -0
  118. package/src/Utils/auth-store.d.ts +29 -0
  119. package/src/Utils/auth-store.js +76 -0
  120. package/src/Utils/auth-utils.d.ts +58 -0
  121. package/src/Utils/auth-utils.js +273 -0
  122. package/src/Utils/browser-utils.d.ts +9 -0
  123. package/src/Utils/browser-utils.js +28 -0
  124. package/src/Utils/business.d.ts +49 -0
  125. package/src/Utils/business.js +226 -0
  126. package/src/Utils/chat-utils.d.ts +408 -0
  127. package/src/Utils/chat-utils.js +846 -0
  128. package/src/Utils/companion-reg-client-utils.d.ts +4 -0
  129. package/src/Utils/companion-reg-client-utils.js +39 -0
  130. package/src/Utils/crypto.d.ts +39 -0
  131. package/src/Utils/crypto.js +110 -0
  132. package/src/Utils/decode-wa-message.d.ts +99 -0
  133. package/src/Utils/decode-wa-message.js +373 -0
  134. package/src/Utils/event-buffer.d.ts +22 -0
  135. package/src/Utils/event-buffer.js +624 -0
  136. package/src/Utils/generics.d.ts +63 -0
  137. package/src/Utils/generics.js +375 -0
  138. package/src/Utils/group-metadata-cache.d.ts +4 -0
  139. package/src/Utils/group-metadata-cache.js +25 -0
  140. package/src/Utils/history.d.ts +75 -0
  141. package/src/Utils/history.js +131 -0
  142. package/src/Utils/html-app.d.ts +19 -0
  143. package/src/Utils/html-app.js +96 -0
  144. package/src/Utils/html-multiplayer.d.ts +10 -0
  145. package/src/Utils/html-multiplayer.js +94 -0
  146. package/src/Utils/identity-change-handler.d.ts +13 -0
  147. package/src/Utils/identity-change-handler.js +48 -0
  148. package/src/Utils/index.d.ts +44 -0
  149. package/src/Utils/index.js +44 -0
  150. package/src/Utils/link-preview-metadata.d.ts +47 -0
  151. package/src/Utils/link-preview-metadata.js +88 -0
  152. package/src/Utils/link-preview.d.ts +12 -0
  153. package/src/Utils/link-preview.js +79 -0
  154. package/src/Utils/logger.d.ts +2 -0
  155. package/src/Utils/logger.js +2 -0
  156. package/src/Utils/lt-hash.d.ts +6 -0
  157. package/src/Utils/lt-hash.js +3 -0
  158. package/src/Utils/make-mutex.d.ts +6 -0
  159. package/src/Utils/make-mutex.js +32 -0
  160. package/src/Utils/message-retry-manager.d.ts +79 -0
  161. package/src/Utils/message-retry-manager.js +255 -0
  162. package/src/Utils/messages-media.d.ts +136 -0
  163. package/src/Utils/messages-media.js +814 -0
  164. package/src/Utils/messages.d.ts +62 -0
  165. package/src/Utils/messages.js +2223 -0
  166. package/src/Utils/mobile-companion-crypto.js +191 -0
  167. package/src/Utils/modern-messages.d.ts +150 -0
  168. package/src/Utils/modern-messages.js +496 -0
  169. package/src/Utils/native-flow.d.ts +11 -0
  170. package/src/Utils/native-flow.js +115 -0
  171. package/src/Utils/newsletter-status.d.ts +158 -0
  172. package/src/Utils/newsletter-status.js +651 -0
  173. package/src/Utils/noise-handler.d.ts +20 -0
  174. package/src/Utils/noise-handler.js +200 -0
  175. package/src/Utils/offline-node-processor.d.ts +9 -0
  176. package/src/Utils/offline-node-processor.js +33 -0
  177. package/src/Utils/optional-media.d.ts +3 -0
  178. package/src/Utils/optional-media.js +45 -0
  179. package/src/Utils/payment-messages.d.ts +66 -0
  180. package/src/Utils/payment-messages.js +160 -0
  181. package/src/Utils/pre-key-manager.d.ts +25 -0
  182. package/src/Utils/pre-key-manager.js +95 -0
  183. package/src/Utils/process-message.d.ts +60 -0
  184. package/src/Utils/process-message.js +688 -0
  185. package/src/Utils/reporting-utils.d.ts +12 -0
  186. package/src/Utils/reporting-utils.js +256 -0
  187. package/src/Utils/scheduled-message.d.ts +51 -0
  188. package/src/Utils/scheduled-message.js +112 -0
  189. package/src/Utils/sender-key-memory.d.ts +19 -0
  190. package/src/Utils/sender-key-memory.js +51 -0
  191. package/src/Utils/signal.d.ts +82 -0
  192. package/src/Utils/signal.js +193 -0
  193. package/src/Utils/stanza-ack.d.ts +16 -0
  194. package/src/Utils/stanza-ack.js +30 -0
  195. package/src/Utils/status-stickers.d.ts +127 -0
  196. package/src/Utils/status-stickers.js +260 -0
  197. package/src/Utils/sync-action-utils.d.ts +2 -0
  198. package/src/Utils/sync-action-utils.js +44 -0
  199. package/src/Utils/tc-token-utils.d.ts +29 -0
  200. package/src/Utils/tc-token-utils.js +155 -0
  201. package/src/Utils/ttl-cache.d.ts +28 -0
  202. package/src/Utils/ttl-cache.js +120 -0
  203. package/src/Utils/use-mongo-auth-state.d.ts +21 -0
  204. package/src/Utils/use-mongo-auth-state.js +67 -0
  205. package/src/Utils/use-multi-file-auth-state.d.ts +11 -0
  206. package/src/Utils/use-multi-file-auth-state.js +106 -0
  207. package/src/Utils/use-mysql-auth-state.d.ts +19 -0
  208. package/src/Utils/use-mysql-auth-state.js +79 -0
  209. package/src/Utils/use-postgres-auth-state.d.ts +19 -0
  210. package/src/Utils/use-postgres-auth-state.js +79 -0
  211. package/src/Utils/use-redis-auth-state.d.ts +19 -0
  212. package/src/Utils/use-redis-auth-state.js +89 -0
  213. package/src/Utils/use-single-file-auth-state.d.ts +10 -0
  214. package/src/Utils/use-single-file-auth-state.js +108 -0
  215. package/src/Utils/use-sqlite-auth-state.d.ts +12 -0
  216. package/src/Utils/use-sqlite-auth-state.js +120 -0
  217. package/src/Utils/useNekoDBAuth.d.ts +19 -0
  218. package/src/Utils/useNekoDBAuth.js +111 -0
  219. package/src/Utils/username.d.ts +12 -0
  220. package/src/Utils/username.js +58 -0
  221. package/src/Utils/validate-connection.d.ts +43 -0
  222. package/src/Utils/validate-connection.js +277 -0
  223. package/src/Utils/voice-recognition.d.ts +53 -0
  224. package/src/Utils/voice-recognition.js +219 -0
  225. package/src/Voip/audio-feeder.d.ts +24 -0
  226. package/src/Voip/audio-feeder.js +268 -0
  227. package/src/Voip/index.d.ts +88 -0
  228. package/src/Voip/index.js +936 -0
  229. package/src/Voip/relay-transport.d.ts +5 -0
  230. package/src/Voip/relay-transport.js +824 -0
  231. package/src/Voip/signaling.d.ts +11 -0
  232. package/src/Voip/signaling.js +1099 -0
  233. package/src/Voip/types.d.ts +2 -0
  234. package/src/Voip/types.js +12 -0
  235. package/src/Voip/video-feeder.d.ts +24 -0
  236. package/src/Voip/video-feeder.js +268 -0
  237. package/src/Voip/wasm-engine.d.ts +26 -0
  238. package/src/Voip/wasm-engine.js +1307 -0
  239. package/src/Voip/worker-bootstrap.js +1023 -0
  240. package/src/WABinary/constants.d.ts +22 -0
  241. package/src/WABinary/constants.js +1300 -0
  242. package/src/WABinary/decode.d.ts +9 -0
  243. package/src/WABinary/decode.js +261 -0
  244. package/src/WABinary/encode.d.ts +2 -0
  245. package/src/WABinary/encode.js +219 -0
  246. package/src/WABinary/generic-utils.d.ts +76 -0
  247. package/src/WABinary/generic-utils.js +214 -0
  248. package/src/WABinary/index.d.ts +5 -0
  249. package/src/WABinary/index.js +5 -0
  250. package/src/WABinary/jid-utils.d.ts +30 -0
  251. package/src/WABinary/jid-utils.js +97 -0
  252. package/src/WABinary/types.d.ts +1 -0
  253. package/src/WABinary/types.js +0 -0
  254. package/src/WAM/BinaryInfo.d.ts +7 -0
  255. package/src/WAM/BinaryInfo.js +9 -0
  256. package/src/WAM/constants.d.ts +34926 -0
  257. package/src/WAM/constants.js +22852 -0
  258. package/src/WAM/encode.d.ts +1 -0
  259. package/src/WAM/encode.js +148 -0
  260. package/src/WAM/index.d.ts +3 -0
  261. package/src/WAM/index.js +3 -0
  262. package/src/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  263. package/src/WAUSync/Protocols/USyncContactProtocol.js +50 -0
  264. package/src/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  265. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +51 -0
  266. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  267. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  268. package/src/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  269. package/src/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  270. package/src/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  271. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +23 -0
  272. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  273. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  274. package/src/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  275. package/src/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  276. package/src/WAUSync/Protocols/index.d.ts +5 -0
  277. package/src/WAUSync/Protocols/index.js +5 -0
  278. package/src/WAUSync/USyncQuery.d.ts +20 -0
  279. package/src/WAUSync/USyncQuery.js +93 -0
  280. package/src/WAUSync/USyncUser.d.ts +16 -0
  281. package/src/WAUSync/USyncUser.js +30 -0
  282. package/src/WAUSync/index.d.ts +3 -0
  283. package/src/WAUSync/index.js +3 -0
  284. package/src/assets/wasm/README.md +76 -0
  285. package/src/assets/wasm/loader.js +5 -0
  286. package/src/assets/wasm/whatsapp.wasm +0 -0
  287. package/src/assets/wasm/worker-modules.js +273 -0
  288. package/src/index.d.ts +43 -0
  289. package/src/index.js +48 -0
@@ -0,0 +1,1484 @@
1
+ import { TTLCache } from '../Utils/ttl-cache.js';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
+ import { ALL_WA_PATCH_NAMES, SPAM_FLOWS } from '../Types/index.js';
6
+ import { SyncState } from '../Types/State.js';
7
+ import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
8
+ import { makeMutex } from '../Utils/make-mutex.js';
9
+ import processMessage from '../Utils/process-message.js';
10
+ import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
11
+ import { isUsernamePin, stripUsernamePrefix, validateUsername } from '../Utils/username.js';
12
+ import { executeWMexQuery as genericExecuteWMexQuery } from './mex.js';
13
+ import { QueryIds, XWAPaths } from '../Types/Mex.js';
14
+ import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidGroup, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
15
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
16
+ import { makeSocket } from './socket.js';
17
+ export const buildProfilePictureQueryContent = (type, tcTokenContent) => {
18
+ const picture = { tag: 'picture', attrs: { type, query: 'url' } };
19
+ if (tcTokenContent?.length) {
20
+ picture.content = tcTokenContent;
21
+ }
22
+ return [picture];
23
+ };
24
+ export const buildSpamListNode = (jid, options = {}) => {
25
+ if (typeof jid !== 'string' || !jid.includes('@')) {
26
+ throw new Boom(`${JSON.stringify(jid)} is not a jid to report`, { statusCode: 400, data: { jid } });
27
+ }
28
+ const flow = options.flow ?? SPAM_FLOWS.OverflowMenuReport;
29
+ if (typeof flow !== 'string' || !flow.length) {
30
+ throw new Boom('spam flow must be a non-empty string, see SPAM_FLOWS', { statusCode: 400, data: { flow } });
31
+ }
32
+ const attrs = {
33
+ jid: isJidGroup(jid) ? jid : jidNormalizedUser(jid),
34
+ spam_flow: flow
35
+ };
36
+ if (options.source) {
37
+ attrs.source = jidNormalizedUser(options.source);
38
+ }
39
+ if (options.subject) {
40
+ attrs.subject = options.subject;
41
+ }
42
+ if (typeof options.isKnownChat === 'boolean') {
43
+ attrs.is_known_chat = options.isKnownChat ? 'true' : 'false';
44
+ }
45
+ return { tag: 'spam_list', attrs };
46
+ };
47
+ export const readSpamReportResult = (sent, result) => {
48
+ const error = getBinaryNodeChild(result, 'error');
49
+ if (error) {
50
+ throw new Boom('reportSpam was rejected by the server', {
51
+ statusCode: Number(error.attrs?.code) || 400,
52
+ data: { jid: sent.attrs.jid, flow: sent.attrs.spam_flow, text: error.attrs?.text }
53
+ });
54
+ }
55
+ return {
56
+ jid: sent.attrs.jid,
57
+ flow: sent.attrs.spam_flow,
58
+ reported: true,
59
+ node: result
60
+ };
61
+ };
62
+ export const makeChatsSocket = (config) => {
63
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
64
+ const sock = makeSocket(config);
65
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
66
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
67
+ let privacySettings;
68
+
69
+ const serverProps = {
70
+
71
+ privacyTokenOn1to1: true,
72
+
73
+ profilePicPrivacyToken: true,
74
+
75
+ lidTrustedTokenIssueToLid: false
76
+ };
77
+ let lastServerProps = { ...(authState?.creds?.serverProps || {}) };
78
+ let syncState = SyncState.Connecting;
79
+
80
+ const messageMutex = makeMutex();
81
+
82
+ const receiptMutex = makeMutex();
83
+
84
+ const appStatePatchMutex = makeMutex();
85
+
86
+ const notificationMutex = makeMutex();
87
+
88
+ let awaitingSyncTimeout;
89
+
90
+ const historySyncStatus = {
91
+ initialBootstrapComplete: false,
92
+ recentSyncComplete: false
93
+ };
94
+ let historySyncPausedTimeout;
95
+
96
+ const blockedCollections = new Set();
97
+ const placeholderResendCache = config.placeholderResendCache ||
98
+ new TTLCache({ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY });
99
+
100
+ const getAppStateSyncKey = async (keyId) => {
101
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
102
+ return key;
103
+ };
104
+ const fetchPrivacySettings = async (force = false) => {
105
+ if (!privacySettings || force) {
106
+ const { content } = await query({
107
+ tag: 'iq',
108
+ attrs: {
109
+ xmlns: 'privacy',
110
+ to: S_WHATSAPP_NET,
111
+ type: 'get'
112
+ },
113
+ content: [{ tag: 'privacy', attrs: {} }]
114
+ });
115
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
116
+ }
117
+ return privacySettings;
118
+ };
119
+
120
+ const privacyQuery = async (name, value) => {
121
+ await query({
122
+ tag: 'iq',
123
+ attrs: {
124
+ xmlns: 'privacy',
125
+ to: S_WHATSAPP_NET,
126
+ type: 'set'
127
+ },
128
+ content: [
129
+ {
130
+ tag: 'privacy',
131
+ attrs: {},
132
+ content: [
133
+ {
134
+ tag: 'category',
135
+ attrs: { name, value }
136
+ }
137
+ ]
138
+ }
139
+ ]
140
+ });
141
+ };
142
+ const updateMessagesPrivacy = async (value) => {
143
+ await privacyQuery('messages', value);
144
+ };
145
+ const updateCallPrivacy = async (value) => {
146
+ await privacyQuery('calladd', value);
147
+ };
148
+ const updateLastSeenPrivacy = async (value) => {
149
+ await privacyQuery('last', value);
150
+ };
151
+ const updateOnlinePrivacy = async (value) => {
152
+ await privacyQuery('online', value);
153
+ };
154
+ const updateProfilePicturePrivacy = async (value) => {
155
+ await privacyQuery('profile', value);
156
+ };
157
+ const updateStatusPrivacy = async (value) => {
158
+ await privacyQuery('status', value);
159
+ };
160
+ const updateReadReceiptsPrivacy = async (value) => {
161
+ await privacyQuery('readreceipts', value);
162
+ };
163
+ const updateGroupsAddPrivacy = async (value) => {
164
+ await privacyQuery('groupadd', value);
165
+ };
166
+ const updateDefaultDisappearingMode = async (duration) => {
167
+ await query({
168
+ tag: 'iq',
169
+ attrs: {
170
+ xmlns: 'disappearing_mode',
171
+ to: S_WHATSAPP_NET,
172
+ type: 'set'
173
+ },
174
+ content: [
175
+ {
176
+ tag: 'disappearing_mode',
177
+ attrs: {
178
+ duration: duration.toString()
179
+ }
180
+ }
181
+ ]
182
+ });
183
+ };
184
+ const getBotListV2 = async () => {
185
+ const resp = await query({
186
+ tag: 'iq',
187
+ attrs: {
188
+ xmlns: 'bot',
189
+ to: S_WHATSAPP_NET,
190
+ type: 'get'
191
+ },
192
+ content: [
193
+ {
194
+ tag: 'bot',
195
+ attrs: {
196
+ v: '2'
197
+ }
198
+ }
199
+ ]
200
+ });
201
+ const botNode = getBinaryNodeChild(resp, 'bot');
202
+ const botList = [];
203
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
204
+ if (section.attrs.type === 'all') {
205
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
206
+ botList.push({
207
+ jid: bot.attrs.jid,
208
+ personaId: bot.attrs['persona_id']
209
+ });
210
+ }
211
+ }
212
+ }
213
+ return botList;
214
+ };
215
+ const fetchStatus = async (...jids) => {
216
+ const usyncQuery = new USyncQuery().withStatusProtocol();
217
+ for (const jid of jids) {
218
+ usyncQuery.withUser(new USyncUser().withId(jid));
219
+ }
220
+ const result = await sock.executeUSyncQuery(usyncQuery);
221
+ if (result) {
222
+ return result.list;
223
+ }
224
+ };
225
+ const fetchDisappearingDuration = async (...jids) => {
226
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
227
+ for (const jid of jids) {
228
+ usyncQuery.withUser(new USyncUser().withId(jid));
229
+ }
230
+ const result = await sock.executeUSyncQuery(usyncQuery);
231
+ if (result) {
232
+ return result.list;
233
+ }
234
+ };
235
+
236
+ const findUserId = async (pnLid) => {
237
+ const normalizedJid = jidNormalizedUser(pnLid);
238
+ const userId = {
239
+ lid: undefined,
240
+ phoneNumber: undefined
241
+ };
242
+ if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
243
+ userId.phoneNumber = normalizedJid;
244
+ userId.lid = jidNormalizedUser((await signalRepository.lidMapping.getLIDsForPNs([normalizedJid]))?.[0]?.lid);
245
+ }
246
+ else if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
247
+ userId.lid = normalizedJid;
248
+ userId.phoneNumber = jidNormalizedUser((await signalRepository.lidMapping.getPNsForLIDs([normalizedJid]))?.[0]?.pn);
249
+ }
250
+ else {
251
+ throw new Boom('Invalid id input to find user ids', { statusCode: 400 });
252
+ }
253
+ return userId;
254
+ };
255
+
256
+ const updateProfilePicture = async (jid, content, dimensions) => {
257
+ let targetJid;
258
+ if (!jid) {
259
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
260
+ }
261
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
262
+ targetJid = jidNormalizedUser(jid);
263
+ }
264
+ else {
265
+ targetJid = undefined;
266
+ }
267
+ const { img } = await generateProfilePicture(content, dimensions);
268
+ await query({
269
+ tag: 'iq',
270
+ attrs: {
271
+ to: S_WHATSAPP_NET,
272
+ type: 'set',
273
+ xmlns: 'w:profile:picture',
274
+ ...(targetJid ? { target: targetJid } : {})
275
+ },
276
+ content: [
277
+ {
278
+ tag: 'picture',
279
+ attrs: { type: 'image' },
280
+ content: img
281
+ }
282
+ ]
283
+ });
284
+ };
285
+
286
+ const removeProfilePicture = async (jid) => {
287
+ let targetJid;
288
+ if (!jid) {
289
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
290
+ }
291
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
292
+ targetJid = jidNormalizedUser(jid);
293
+ }
294
+ else {
295
+ targetJid = undefined;
296
+ }
297
+ await query({
298
+ tag: 'iq',
299
+ attrs: {
300
+ to: S_WHATSAPP_NET,
301
+ type: 'set',
302
+ xmlns: 'w:profile:picture',
303
+ ...(targetJid ? { target: targetJid } : {})
304
+ }
305
+ });
306
+ };
307
+
308
+ const updateProfileStatus = async (status) => {
309
+ await query({
310
+ tag: 'iq',
311
+ attrs: {
312
+ to: S_WHATSAPP_NET,
313
+ type: 'set',
314
+ xmlns: 'status'
315
+ },
316
+ content: [
317
+ {
318
+ tag: 'status',
319
+ attrs: {},
320
+ content: Buffer.from(status, 'utf-8')
321
+ }
322
+ ]
323
+ });
324
+ };
325
+ const updateProfileName = async (name) => {
326
+ await chatModify({ pushNameSetting: name }, '');
327
+ };
328
+ const executeWMexQuery = (variables, queryId, dataPath) => {
329
+ return genericExecuteWMexQuery(variables, queryId, dataPath, query, generateMessageTag);
330
+ };
331
+ const getUsername = async () => {
332
+ const response = await executeWMexQuery({}, QueryIds.USERNAME_GET, XWAPaths.xwa2_username_get);
333
+ const info = response?.username_info;
334
+ return {
335
+ username: info?.username ?? null,
336
+ state: info?.state ?? null,
337
+ pin: info?.pin ?? null
338
+ };
339
+ };
340
+ const assertUsername = (username) => {
341
+ const value = stripUsernamePrefix(username);
342
+ const { isValid, errorType } = validateUsername(value);
343
+ if (!isValid) {
344
+ throw new Boom(`username is not accepted by WhatsApp: ${errorType}`, { statusCode: 400, data: { username: value, errorType } });
345
+ }
346
+ return value;
347
+ };
348
+ const setUsername = async (username, options = {}) => {
349
+ const variables = username
350
+ ? {
351
+ input: assertUsername(username),
352
+ reserved: options.reserved ?? false,
353
+ session_id: options.sessionId ?? generateMessageTag(),
354
+ source: options.source ?? 'USER_INPUT'
355
+ }
356
+ : {};
357
+ const response = await executeWMexQuery(variables, QueryIds.USERNAME_SET, XWAPaths.xwa2_username_set);
358
+ return response?.result === 'SUCCESS';
359
+ };
360
+ const removeUsername = async () => {
361
+ return setUsername(undefined);
362
+ };
363
+ const checkUsernameAvailability = async (username, options = {}) => {
364
+ const response = await executeWMexQuery({
365
+ input: assertUsername(username),
366
+ session_id: options.sessionId ?? generateMessageTag(),
367
+ source: options.source ?? 'USER_INPUT'
368
+ }, QueryIds.USERNAME_CHECK, XWAPaths.xwa2_username_check);
369
+ return {
370
+ available: response?.result === 'SUCCESS',
371
+ suggestions: response?.suggestions ?? [],
372
+ response
373
+ };
374
+ };
375
+ const setUsernamePin = async (pin) => {
376
+ const value = String(pin ?? '');
377
+ if (!isUsernamePin(value)) {
378
+ throw new Boom('username pin must be exactly 4 digits', { statusCode: 400, data: { pin: value } });
379
+ }
380
+ const response = await executeWMexQuery({ pin: value }, QueryIds.USERNAME_PIN_SET, XWAPaths.xwa2_username_pin_set);
381
+ return response?.result === 'SUCCESS';
382
+ };
383
+ const removeUsernamePin = async () => {
384
+ const response = await executeWMexQuery({ pin: null }, QueryIds.USERNAME_PIN_SET, XWAPaths.xwa2_username_pin_set);
385
+ return response?.result === 'SUCCESS';
386
+ };
387
+ const updateTextStatus = async (text, options = {}) => {
388
+ const input = {
389
+ text: text === '' ? null : text ?? null,
390
+ ephemeral_duration_sec: options.ephemeralDurationSec ?? 0
391
+ };
392
+ if (options.emoji) {
393
+ input.emoji = { content: options.emoji };
394
+ }
395
+ return executeWMexQuery({ input }, QueryIds.UPDATE_TEXT_STATUS, XWAPaths.xwa2_update_text_status);
396
+ };
397
+ const fetchTextStatus = async (jids) => {
398
+ const list = (Array.isArray(jids) ? jids : [jids]).map(jid => ({ jid: jidNormalizedUser(jid) }));
399
+ return executeWMexQuery({ input: list }, QueryIds.TEXT_STATUS_LIST, XWAPaths.xwa2_text_status_list);
400
+ };
401
+ const fetchAbout = async (jid) => {
402
+ const { user } = jidDecode(jidNormalizedUser(jid)) || {};
403
+ if (!user) {
404
+ throw new Boom('Invalid user jid', { statusCode: 400 });
405
+ }
406
+ const response = await executeWMexQuery({ user: { user_id: user } }, QueryIds.ABOUT_STATUS, XWAPaths.xwa2_users_updates_since);
407
+ const updates = Array.isArray(response) ? response[0]?.updates : undefined;
408
+ return {
409
+ jid: jidNormalizedUser(jid),
410
+ status: updates?.[0]?.text ?? null,
411
+ response
412
+ };
413
+ };
414
+ const fetchUserNotices = async (since = 0) => {
415
+ const result = await query({
416
+ tag: 'iq',
417
+ attrs: {
418
+ to: S_WHATSAPP_NET,
419
+ type: 'get',
420
+ xmlns: 'tos',
421
+ id: generateMessageTag()
422
+ },
423
+ content: [{ tag: 'get_user_disclosures', attrs: { t: String(since) } }]
424
+ });
425
+ const notices = [];
426
+ for (const node of getBinaryNodeChildren(result, 'notice')) {
427
+ notices.push({
428
+ id: node.attrs.id,
429
+ stage: node.attrs.stage,
430
+ t: node.attrs.t,
431
+ version: node.attrs.version,
432
+ type: node.attrs.type
433
+ });
434
+ }
435
+ return notices;
436
+ };
437
+ const updateUserNoticeStage = async (noticeId, stage) => {
438
+ await query({
439
+ tag: 'iq',
440
+ attrs: {
441
+ to: S_WHATSAPP_NET,
442
+ type: 'set',
443
+ xmlns: 'tos',
444
+ id: generateMessageTag()
445
+ },
446
+ content: [{ tag: 'notice', attrs: { id: String(noticeId), stage: String(stage) } }]
447
+ });
448
+ };
449
+ const fetchOptOutList = async (options = {}) => {
450
+ const attrs = {
451
+ to: S_WHATSAPP_NET,
452
+ type: 'get',
453
+ xmlns: 'optoutlist',
454
+ id: generateMessageTag()
455
+ };
456
+ if (options.category) {
457
+ attrs.category = options.category;
458
+ }
459
+ const content = options.dhash ? [{ tag: 'item', attrs: { dhash: options.dhash } }] : undefined;
460
+ const result = await query({ tag: 'iq', attrs, content });
461
+ return getBinaryNodeChildren(result, 'item').map(node => node.attrs);
462
+ };
463
+ const updateOptOut = async ({ jid, category, action, dhash, reason, entryPoint, signupId, duration }) => {
464
+ const attrs = {
465
+ jid: jidNormalizedUser(jid),
466
+ category,
467
+ action
468
+ };
469
+ if (dhash)
470
+ attrs.dhash = dhash;
471
+ if (reason)
472
+ attrs.reason = reason;
473
+ if (entryPoint)
474
+ attrs.entry_point = entryPoint;
475
+ if (signupId)
476
+ attrs.signup_id = signupId;
477
+ if (duration !== undefined && duration !== null)
478
+ attrs.duration = String(duration);
479
+ await query({
480
+ tag: 'iq',
481
+ attrs: {
482
+ to: S_WHATSAPP_NET,
483
+ type: 'set',
484
+ xmlns: 'optoutlist',
485
+ id: generateMessageTag()
486
+ },
487
+ content: [{ tag: 'item', attrs }]
488
+ });
489
+ };
490
+ const fetchPushSettings = async () => {
491
+ const result = await query({
492
+ tag: 'iq',
493
+ attrs: {
494
+ to: S_WHATSAPP_NET,
495
+ type: 'get',
496
+ xmlns: 'urn:xmpp:whatsapp:push',
497
+ id: generateMessageTag()
498
+ },
499
+ content: [{ tag: 'settings', attrs: {} }]
500
+ });
501
+ return getBinaryNodeChild(result, 'settings')?.attrs ?? {};
502
+ };
503
+ const fetchServerLinkPreview = async (url) => {
504
+ return executeWMexQuery({ input: { url } }, QueryIds.PLAINTEXT_LINK_PREVIEW, XWAPaths.xwa2_newsletter_link_preview);
505
+ };
506
+ const fetchBlocklist = async () => {
507
+ const result = await query({
508
+ tag: 'iq',
509
+ attrs: {
510
+ xmlns: 'blocklist',
511
+ to: S_WHATSAPP_NET,
512
+ type: 'get'
513
+ }
514
+ });
515
+ const listNode = getBinaryNodeChild(result, 'list');
516
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
517
+ };
518
+ const updateBlockStatus = async (jid, action) => {
519
+ const normalizedJid = jidNormalizedUser(jid);
520
+ let lid;
521
+ let pn_jid;
522
+ if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
523
+ lid = normalizedJid;
524
+ if (action === 'block') {
525
+ const pn = (await findUserId(normalizedJid)).phoneNumber;
526
+ if (!pn) {
527
+ throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
528
+ }
529
+ pn_jid = jidNormalizedUser(pn);
530
+ }
531
+ }
532
+ else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
533
+ const mapped = (await findUserId(normalizedJid)).lid;
534
+ if (!mapped) {
535
+ throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
536
+ }
537
+ lid = mapped;
538
+ if (action === 'block') {
539
+ pn_jid = jidNormalizedUser(normalizedJid);
540
+ }
541
+ }
542
+ else {
543
+ throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
544
+ }
545
+ const itemAttrs = {
546
+ action,
547
+ jid: lid
548
+ };
549
+ if (action === 'block') {
550
+ if (!pn_jid) {
551
+ throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
552
+ }
553
+ itemAttrs.pn_jid = pn_jid;
554
+ }
555
+ await query({
556
+ tag: 'iq',
557
+ attrs: {
558
+ xmlns: 'blocklist',
559
+ to: S_WHATSAPP_NET,
560
+ type: 'set'
561
+ },
562
+ content: [
563
+ {
564
+ tag: 'item',
565
+ attrs: itemAttrs
566
+ }
567
+ ]
568
+ });
569
+ };
570
+ const reportSpam = async (jid, options = {}) => {
571
+ const node = buildSpamListNode(jid, options);
572
+ const result = await query({
573
+ tag: 'iq',
574
+ attrs: {
575
+ xmlns: 'spam',
576
+ to: S_WHATSAPP_NET,
577
+ type: 'set'
578
+ },
579
+ content: [node]
580
+ });
581
+ return readSpamReportResult(node, result);
582
+ };
583
+ const getBusinessProfile = async (jid) => {
584
+ const results = await query({
585
+ tag: 'iq',
586
+ attrs: {
587
+ to: 's.whatsapp.net',
588
+ xmlns: 'w:biz',
589
+ type: 'get'
590
+ },
591
+ content: [
592
+ {
593
+ tag: 'business_profile',
594
+ attrs: { v: '244' },
595
+ content: [
596
+ {
597
+ tag: 'profile',
598
+ attrs: { jid }
599
+ }
600
+ ]
601
+ }
602
+ ]
603
+ });
604
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
605
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
606
+ if (profiles) {
607
+ const address = getBinaryNodeChild(profiles, 'address');
608
+ const description = getBinaryNodeChild(profiles, 'description');
609
+ const website = getBinaryNodeChild(profiles, 'website');
610
+ const email = getBinaryNodeChild(profiles, 'email');
611
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
612
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours');
613
+ const businessHoursConfig = businessHours
614
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
615
+ : undefined;
616
+ const websiteStr = website?.content?.toString();
617
+ return {
618
+ wid: profiles.attrs?.jid,
619
+ address: address?.content?.toString(),
620
+ description: description?.content?.toString() || '',
621
+ website: websiteStr ? [websiteStr] : [],
622
+ email: email?.content?.toString(),
623
+ category: category?.content?.toString(),
624
+ business_hours: {
625
+ timezone: businessHours?.attrs?.timezone,
626
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
627
+ }
628
+ };
629
+ }
630
+ };
631
+ const cleanDirtyBits = async (type, fromTimestamp) => {
632
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
633
+ await sendNode({
634
+ tag: 'iq',
635
+ attrs: {
636
+ to: S_WHATSAPP_NET,
637
+ type: 'set',
638
+ xmlns: 'urn:xmpp:whatsapp:dirty',
639
+ id: generateMessageTag()
640
+ },
641
+ content: [
642
+ {
643
+ tag: 'clean',
644
+ attrs: {
645
+ type,
646
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
647
+ }
648
+ }
649
+ ]
650
+ });
651
+ };
652
+ const newAppStateChunkHandler = (isInitialSync) => {
653
+ return {
654
+ onMutation(mutation) {
655
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
656
+ }
657
+ };
658
+ };
659
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
660
+ const appStateSyncKeyCache = new Map();
661
+ const getCachedAppStateSyncKey = async (keyId) => {
662
+ if (appStateSyncKeyCache.has(keyId)) {
663
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
664
+ }
665
+ const key = await getAppStateSyncKey(keyId);
666
+ appStateSyncKeyCache.set(keyId, key ?? null);
667
+ return key;
668
+ };
669
+
670
+ const initialVersionMap = {};
671
+ const globalMutationMap = {};
672
+ await authState.keys.transaction(async () => {
673
+ const collectionsToHandle = new Set(collections);
674
+
675
+ const attemptsMap = {};
676
+
677
+ const forceSnapshotCollections = new Set();
678
+
679
+ while (collectionsToHandle.size) {
680
+ const states = {};
681
+ const nodes = [];
682
+ for (const name of collectionsToHandle) {
683
+ const result = await authState.keys.get('app-state-sync-version', [name]);
684
+ let state = result[name];
685
+ if (state) {
686
+ state = ensureLTHashStateVersion(state);
687
+ if (typeof initialVersionMap[name] === 'undefined') {
688
+ initialVersionMap[name] = state.version;
689
+ }
690
+ }
691
+ else {
692
+ state = newLTHashState();
693
+ }
694
+ states[name] = state;
695
+ const shouldForceSnapshot = forceSnapshotCollections.has(name);
696
+ if (shouldForceSnapshot) {
697
+ forceSnapshotCollections.delete(name);
698
+ }
699
+ logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
700
+ nodes.push({
701
+ tag: 'collection',
702
+ attrs: {
703
+ name,
704
+ version: state.version.toString(),
705
+
706
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
707
+ }
708
+ });
709
+ }
710
+ const result = await query({
711
+ tag: 'iq',
712
+ attrs: {
713
+ to: S_WHATSAPP_NET,
714
+ xmlns: 'w:sync:app:state',
715
+ type: 'set'
716
+ },
717
+ content: [
718
+ {
719
+ tag: 'sync',
720
+ attrs: {},
721
+ content: nodes
722
+ }
723
+ ]
724
+ });
725
+
726
+ const decoded = await extractSyncdPatches(result, config?.options);
727
+ for (const key in decoded) {
728
+ const name = key;
729
+ const { patches, hasMorePatches, snapshot } = decoded[name];
730
+ try {
731
+ if (snapshot) {
732
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
733
+ states[name] = newState;
734
+ Object.assign(globalMutationMap, mutationMap);
735
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
736
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
737
+ }
738
+
739
+ if (patches.length) {
740
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
741
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
742
+ logger.info(`synced ${name} to v${newState.version}`);
743
+ initialVersionMap[name] = newState.version;
744
+ Object.assign(globalMutationMap, mutationMap);
745
+ }
746
+ if (hasMorePatches) {
747
+ logger.info(`${name} has more patches...`);
748
+ }
749
+ else {
750
+
751
+ collectionsToHandle.delete(name);
752
+ }
753
+ }
754
+ catch (error) {
755
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
756
+ const logData = {
757
+ name,
758
+ attempt: attemptsMap[name],
759
+ version: states[name].version,
760
+ statusCode: error.output?.statusCode,
761
+ errorType: error.name,
762
+ error: error.stack
763
+ };
764
+ if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
765
+
766
+ logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
767
+ blockedCollections.add(name);
768
+ collectionsToHandle.delete(name);
769
+ }
770
+ else if (isMissingKeyError(error)) {
771
+
772
+ logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
773
+ forceSnapshotCollections.add(name);
774
+ }
775
+ else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
776
+ logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
777
+ collectionsToHandle.delete(name);
778
+ }
779
+ else {
780
+ logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
781
+
782
+ forceSnapshotCollections.add(name);
783
+ }
784
+ }
785
+ }
786
+ }
787
+ }, authState?.creds?.me?.id || 'resync-app-state');
788
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
789
+ for (const key in globalMutationMap) {
790
+ onMutation(globalMutationMap[key]);
791
+ }
792
+ });
793
+
794
+ const profilePictureUrl = async (jid, type = 'image', timeoutMs = 5000, shouldIncludeTcToken = true) => {
795
+
796
+ const normalizedJid = jidNormalizedUser(jid);
797
+ const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
798
+ const me = authState.creds.me;
799
+ const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
800
+ let tcTokenContent;
801
+ if (shouldIncludeTcToken && serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
802
+ tcTokenContent = await buildTcTokenFromJid({
803
+ authState,
804
+ jid: normalizedJid,
805
+ getLIDForPN
806
+ });
807
+ }
808
+ jid = jidNormalizedUser(jid);
809
+ const result = await query({
810
+ tag: 'iq',
811
+ attrs: {
812
+ target: jid,
813
+ to: S_WHATSAPP_NET,
814
+ type: 'get',
815
+ xmlns: 'w:profile:picture'
816
+ },
817
+ content: buildProfilePictureQueryContent(type, tcTokenContent)
818
+ }, timeoutMs);
819
+ const child = getBinaryNodeChild(result, 'picture');
820
+ return child?.attrs?.url;
821
+ };
822
+ const createCallLink = async (type, event, timeoutMs) => {
823
+ const result = await query({
824
+ tag: 'call',
825
+ attrs: {
826
+ id: generateMessageTag(),
827
+ to: '@call'
828
+ },
829
+ content: [
830
+ {
831
+ tag: 'link_create',
832
+ attrs: { media: type },
833
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
834
+ }
835
+ ]
836
+ }, timeoutMs);
837
+ const child = getBinaryNodeChild(result, 'link_create');
838
+ return child?.attrs?.token;
839
+ };
840
+ const sendPresenceUpdate = async (type, toJid) => {
841
+ const me = authState.creds.me;
842
+ const isAvailableType = type === 'available';
843
+ if (isAvailableType || type === 'unavailable') {
844
+ if (!me.name) {
845
+ logger.warn('no name present, ignoring presence update request...');
846
+ return;
847
+ }
848
+ ev.emit('connection.update', { isOnline: isAvailableType });
849
+ if (isAvailableType) {
850
+ void sendUnifiedSession();
851
+ }
852
+ await sendNode({
853
+ tag: 'presence',
854
+ attrs: {
855
+ name: me.name.replace(/@/g, ''),
856
+ type
857
+ }
858
+ });
859
+ }
860
+ else {
861
+ const { server } = jidDecode(toJid);
862
+ const isLid = server === 'lid';
863
+ await sendNode({
864
+ tag: 'chatstate',
865
+ attrs: {
866
+ from: isLid ? me.lid : me.id,
867
+ to: toJid
868
+ },
869
+ content: [
870
+ {
871
+ tag: type === 'recording' ? 'composing' : type,
872
+ attrs: type === 'recording' ? { media: 'audio' } : {}
873
+ }
874
+ ]
875
+ });
876
+ }
877
+ };
878
+
879
+ const presenceSubscribe = async (toJid) => {
880
+
881
+ const normalizedToJid = jidNormalizedUser(toJid);
882
+ const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid);
883
+ const tcTokenContent = isUserJid
884
+ ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN })
885
+ : undefined;
886
+ return sendNode({
887
+ tag: 'presence',
888
+ attrs: {
889
+ to: toJid,
890
+ id: generateMessageTag(),
891
+ type: 'subscribe'
892
+ },
893
+ content: tcTokenContent
894
+ });
895
+ };
896
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
897
+ let presence;
898
+ const jid = attrs.from;
899
+ const participant = attrs.participant || attrs.from;
900
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
901
+ return;
902
+ }
903
+ if (tag === 'presence') {
904
+ presence = {
905
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
906
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
907
+ groupOnlineCount: attrs.count ? +attrs.count : undefined
908
+ };
909
+ }
910
+ else if (Array.isArray(content)) {
911
+ const [firstChild] = content;
912
+ let type = firstChild.tag;
913
+ if (type === 'paused') {
914
+ type = 'available';
915
+ }
916
+ if (firstChild.attrs?.media === 'audio') {
917
+ type = 'recording';
918
+ }
919
+ presence = { lastKnownPresence: type };
920
+ }
921
+ else {
922
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
923
+ }
924
+ if (presence) {
925
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
926
+ }
927
+ };
928
+ const appPatch = async (patchCreate) => {
929
+ const name = patchCreate.type;
930
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
931
+ if (!myAppStateKeyId) {
932
+ throw new Boom('App state key not present!', { statusCode: 400 });
933
+ }
934
+ let initial;
935
+ let encodeResult;
936
+ await appStatePatchMutex.mutex(async () => {
937
+ await authState.keys.transaction(async () => {
938
+ logger.debug({ patch: patchCreate }, 'applying app patch');
939
+ await resyncAppState([name], false);
940
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
941
+ initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
942
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
943
+ const { patch, state } = encodeResult;
944
+ const node = {
945
+ tag: 'iq',
946
+ attrs: {
947
+ to: S_WHATSAPP_NET,
948
+ type: 'set',
949
+ xmlns: 'w:sync:app:state'
950
+ },
951
+ content: [
952
+ {
953
+ tag: 'sync',
954
+ attrs: {},
955
+ content: [
956
+ {
957
+ tag: 'collection',
958
+ attrs: {
959
+ name,
960
+ version: (state.version - 1).toString(),
961
+ return_snapshot: 'false'
962
+ },
963
+ content: [
964
+ {
965
+ tag: 'patch',
966
+ attrs: {},
967
+ content: proto.SyncdPatch.encode(patch).finish()
968
+ }
969
+ ]
970
+ }
971
+ ]
972
+ }
973
+ ]
974
+ };
975
+ await query(node);
976
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
977
+ }, authState?.creds?.me?.id || 'app-patch');
978
+ });
979
+ if (config.emitOwnEvents) {
980
+ const { onMutation } = newAppStateChunkHandler(false);
981
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
982
+ for (const key in mutationMap) {
983
+ onMutation(mutationMap[key]);
984
+ }
985
+ }
986
+ };
987
+
988
+ const fetchProps = async ({ full = false } = {}) => {
989
+ const hash = full ? undefined : authState?.creds?.lastPropHash;
990
+ const resultNode = await query({
991
+ tag: 'iq',
992
+ attrs: {
993
+ to: S_WHATSAPP_NET,
994
+ xmlns: 'abt',
995
+ type: 'get'
996
+ },
997
+ content: [
998
+ {
999
+ tag: 'props',
1000
+ attrs: {
1001
+ protocol: '1',
1002
+ ...(hash ? { hash } : {})
1003
+ }
1004
+ }
1005
+ ]
1006
+ });
1007
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
1008
+ if (propsNode) {
1009
+ const delta = reduceBinaryNodeToDictionary(propsNode, 'prop');
1010
+ const update = {};
1011
+ if (full) {
1012
+ lastServerProps = delta;
1013
+ update.serverProps = delta;
1014
+ }
1015
+ else if (Object.keys(delta).length) {
1016
+ lastServerProps = { ...lastServerProps, ...delta };
1017
+ update.serverProps = lastServerProps;
1018
+ }
1019
+ if (propsNode.attrs?.hash && propsNode.attrs.hash !== authState.creds.lastPropHash) {
1020
+ update.lastPropHash = propsNode.attrs.hash;
1021
+ }
1022
+ if (Object.keys(update).length) {
1023
+ Object.assign(authState.creds, update);
1024
+ ev.emit('creds.update', update);
1025
+ }
1026
+ }
1027
+ const props = lastServerProps;
1028
+
1029
+ const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
1030
+ if (privacyTokenProp !== undefined) {
1031
+ serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
1032
+ }
1033
+ const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
1034
+ if (profilePicProp !== undefined) {
1035
+ serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
1036
+ }
1037
+ const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
1038
+ if (lidIssueProp !== undefined) {
1039
+ serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
1040
+ }
1041
+ logger.debug({ serverProps, count: Object.keys(props).length }, 'fetched props');
1042
+ return props;
1043
+ };
1044
+
1045
+ const getServerProps = async ({ refresh = false } = {}) => {
1046
+ if (refresh) {
1047
+ return fetchProps({ full: true });
1048
+ }
1049
+ if (!Object.keys(lastServerProps).length) {
1050
+ await fetchProps({ full: true });
1051
+ }
1052
+ return lastServerProps;
1053
+ };
1054
+
1055
+ const chatModify = (mod, jid) => {
1056
+ const patch = chatModificationToAppPatch(mod, jid);
1057
+ return appPatch(patch);
1058
+ };
1059
+
1060
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
1061
+ return chatModify({
1062
+ disableLinkPreviews: { isPreviewsDisabled }
1063
+ }, '');
1064
+ };
1065
+
1066
+ const star = (jid, messages, star) => {
1067
+ return chatModify({
1068
+ star: {
1069
+ messages,
1070
+ star
1071
+ }
1072
+ }, jid);
1073
+ };
1074
+
1075
+ const addOrEditContact = (jid, contact) => {
1076
+ return chatModify({
1077
+ contact
1078
+ }, jid);
1079
+ };
1080
+
1081
+ const removeContact = (jid) => {
1082
+ return chatModify({
1083
+ contact: null
1084
+ }, jid);
1085
+ };
1086
+
1087
+ const addLabel = (jid, labels) => {
1088
+ return chatModify({
1089
+ addLabel: {
1090
+ ...labels
1091
+ }
1092
+ }, jid);
1093
+ };
1094
+
1095
+ const addChatLabel = (jid, labelId) => {
1096
+ return chatModify({
1097
+ addChatLabel: {
1098
+ labelId
1099
+ }
1100
+ }, jid);
1101
+ };
1102
+
1103
+ const removeChatLabel = (jid, labelId) => {
1104
+ return chatModify({
1105
+ removeChatLabel: {
1106
+ labelId
1107
+ }
1108
+ }, jid);
1109
+ };
1110
+
1111
+ const addMessageLabel = (jid, messageId, labelId) => {
1112
+ return chatModify({
1113
+ addMessageLabel: {
1114
+ messageId,
1115
+ labelId
1116
+ }
1117
+ }, jid);
1118
+ };
1119
+
1120
+ const removeMessageLabel = (jid, messageId, labelId) => {
1121
+ return chatModify({
1122
+ removeMessageLabel: {
1123
+ messageId,
1124
+ labelId
1125
+ }
1126
+ }, jid);
1127
+ };
1128
+
1129
+ const addOrEditQuickReply = (quickReply) => {
1130
+ return chatModify({
1131
+ quickReply
1132
+ }, '');
1133
+ };
1134
+
1135
+ const removeQuickReply = (timestamp) => {
1136
+ return chatModify({
1137
+ quickReply: { timestamp, deleted: true }
1138
+ }, '');
1139
+ };
1140
+
1141
+ const executeInitQueries = async () => {
1142
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
1143
+ };
1144
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
1145
+ ev.emit('messages.upsert', { messages: [msg], type });
1146
+ if (!!msg.pushName) {
1147
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
1148
+ jid = jidNormalizedUser(jid);
1149
+ if (!msg.key.fromMe) {
1150
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
1151
+ }
1152
+
1153
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
1154
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
1155
+ }
1156
+ }
1157
+ const historyMsg = getHistoryMsg(msg.message);
1158
+ const shouldProcessHistoryMsg = historyMsg
1159
+ ? shouldSyncHistoryMessage(historyMsg) &&
1160
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
1161
+ : false;
1162
+ if (historyMsg && shouldProcessHistoryMsg) {
1163
+ const syncType = historyMsg.syncType;
1164
+
1165
+ if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
1166
+ !historySyncStatus.initialBootstrapComplete) {
1167
+ historySyncStatus.initialBootstrapComplete = true;
1168
+ ev.emit('messaging-history.status', {
1169
+ syncType,
1170
+ status: 'complete',
1171
+ explicit: true
1172
+ });
1173
+ }
1174
+
1175
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT &&
1176
+ historyMsg.progress === 100 &&
1177
+ !historySyncStatus.recentSyncComplete) {
1178
+ historySyncStatus.recentSyncComplete = true;
1179
+ clearTimeout(historySyncPausedTimeout);
1180
+ historySyncPausedTimeout = undefined;
1181
+ ev.emit('messaging-history.status', {
1182
+ syncType,
1183
+ status: 'complete',
1184
+ explicit: true
1185
+ });
1186
+ }
1187
+
1188
+ if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
1189
+ clearTimeout(historySyncPausedTimeout);
1190
+ historySyncPausedTimeout = setTimeout(() => {
1191
+ if (!historySyncStatus.recentSyncComplete) {
1192
+ historySyncStatus.recentSyncComplete = true;
1193
+ ev.emit('messaging-history.status', {
1194
+ syncType: proto.HistorySync.HistorySyncType.RECENT,
1195
+ status: 'paused',
1196
+ explicit: false
1197
+ });
1198
+ }
1199
+ historySyncPausedTimeout = undefined;
1200
+ }, HISTORY_SYNC_PAUSED_TIMEOUT_MS);
1201
+ }
1202
+ }
1203
+
1204
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
1205
+ if (awaitingSyncTimeout) {
1206
+ clearTimeout(awaitingSyncTimeout);
1207
+ awaitingSyncTimeout = undefined;
1208
+ }
1209
+ if (shouldProcessHistoryMsg) {
1210
+ syncState = SyncState.Syncing;
1211
+ logger.info('Transitioned to Syncing state');
1212
+
1213
+ }
1214
+ else {
1215
+ syncState = SyncState.Online;
1216
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
1217
+ ev.flush();
1218
+ }
1219
+ }
1220
+ const doAppStateSync = async () => {
1221
+ if (syncState === SyncState.Syncing) {
1222
+
1223
+ blockedCollections.clear();
1224
+ logger.info('Doing app state sync');
1225
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
1226
+
1227
+ syncState = SyncState.Online;
1228
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
1229
+ ev.flush();
1230
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1231
+ ev.emit('creds.update', { accountSyncCounter });
1232
+ }
1233
+ };
1234
+ await Promise.all([
1235
+ (async () => {
1236
+ if (shouldProcessHistoryMsg) {
1237
+ await doAppStateSync();
1238
+ }
1239
+ })(),
1240
+ processMessage(msg, {
1241
+ signalRepository,
1242
+ shouldProcessHistoryMsg,
1243
+ placeholderResendCache,
1244
+ ev,
1245
+ creds: authState.creds,
1246
+ keyStore: authState.keys,
1247
+ logger,
1248
+ options: config.options,
1249
+ getMessage
1250
+ })
1251
+ ]);
1252
+
1253
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
1254
+ logger.info('App state sync key arrived, triggering app state sync');
1255
+ await doAppStateSync();
1256
+ }
1257
+ });
1258
+ ws.on('CB:presence', handlePresenceUpdate);
1259
+ ws.on('CB:chatstate', handlePresenceUpdate);
1260
+ ws.on('CB:ib,,dirty', async (node) => {
1261
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
1262
+ const type = attrs.type;
1263
+ switch (type) {
1264
+ case 'account_sync':
1265
+ if (attrs.timestamp) {
1266
+ let { lastAccountSyncTimestamp } = authState.creds;
1267
+ if (lastAccountSyncTimestamp) {
1268
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
1269
+ }
1270
+ lastAccountSyncTimestamp = +attrs.timestamp;
1271
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
1272
+ }
1273
+ break;
1274
+ case 'groups':
1275
+
1276
+ break;
1277
+ default:
1278
+ logger.info({ node }, 'received unknown sync');
1279
+ break;
1280
+ }
1281
+ });
1282
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1283
+ if (connection === 'close') {
1284
+ blockedCollections.clear();
1285
+ clearTimeout(historySyncPausedTimeout);
1286
+ historySyncPausedTimeout = undefined;
1287
+ }
1288
+ if (connection === 'open') {
1289
+ if (fireInitQueries) {
1290
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
1291
+ }
1292
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
1293
+ }
1294
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1295
+ return;
1296
+ }
1297
+ historySyncStatus.initialBootstrapComplete = false;
1298
+ historySyncStatus.recentSyncComplete = false;
1299
+ clearTimeout(historySyncPausedTimeout);
1300
+ historySyncPausedTimeout = undefined;
1301
+ syncState = SyncState.AwaitingInitialSync;
1302
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
1303
+ ev.buffer();
1304
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
1305
+ syncType: proto.HistorySync.HistorySyncType.RECENT
1306
+ }));
1307
+ if (!willSyncHistory) {
1308
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1309
+ syncState = SyncState.Online;
1310
+ setTimeout(() => ev.flush(), 0);
1311
+ return;
1312
+ }
1313
+
1314
+ if (authState.creds.accountSyncCounter > 0) {
1315
+ logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
1316
+ syncState = SyncState.Online;
1317
+ setTimeout(() => ev.flush(), 0);
1318
+ return;
1319
+ }
1320
+ logger.info('First connection, awaiting history sync notification with a 20s timeout.');
1321
+ if (awaitingSyncTimeout) {
1322
+ clearTimeout(awaitingSyncTimeout);
1323
+ }
1324
+ awaitingSyncTimeout = setTimeout(() => {
1325
+ if (syncState === SyncState.AwaitingInitialSync) {
1326
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1327
+ syncState = SyncState.Online;
1328
+ ev.flush();
1329
+
1330
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1331
+ ev.emit('creds.update', { accountSyncCounter });
1332
+ }
1333
+ }, 20000);
1334
+ });
1335
+
1336
+ ev.on('creds.update', ({ myAppStateKeyId }) => {
1337
+ if (!myAppStateKeyId || blockedCollections.size === 0) {
1338
+ return;
1339
+ }
1340
+
1341
+ if (syncState === SyncState.Syncing) {
1342
+ blockedCollections.clear();
1343
+ return;
1344
+ }
1345
+ const collections = [...blockedCollections];
1346
+ blockedCollections.clear();
1347
+ logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
1348
+ resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
1349
+ });
1350
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
1351
+ try {
1352
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1353
+ }
1354
+ catch (error) {
1355
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1356
+ }
1357
+ });
1358
+ registerSocketEndHandler(() => {
1359
+ if (awaitingSyncTimeout) {
1360
+ clearTimeout(awaitingSyncTimeout);
1361
+ awaitingSyncTimeout = undefined;
1362
+ }
1363
+ if (!config.placeholderResendCache && placeholderResendCache.close) {
1364
+ placeholderResendCache.close();
1365
+ }
1366
+ syncState = SyncState.Connecting;
1367
+ privacySettings = undefined;
1368
+ });
1369
+ const checkAccountHealth = async (jid) => {
1370
+ const number = String(jid).split('@')[0].split(':')[0];
1371
+ const info = {
1372
+ jid,
1373
+ exists: false,
1374
+ isBusiness: false,
1375
+ verifiedName: null,
1376
+ about: null,
1377
+ hasProfilePhoto: false,
1378
+ self: null,
1379
+ notes: []
1380
+ };
1381
+ const [onWa] = await sock.onWhatsApp(number).catch(() => []);
1382
+ info.exists = !!onWa?.exists;
1383
+ if (onWa?.jid) {
1384
+ info.jid = onWa.jid;
1385
+ }
1386
+ if (!info.exists) {
1387
+ info.notes.push('Nomor tidak terdaftar di WhatsApp');
1388
+ return info;
1389
+ }
1390
+ const biz = await getBusinessProfile(info.jid).catch(() => null);
1391
+ if (biz && Object.keys(biz).length) {
1392
+ info.isBusiness = true;
1393
+ info.verifiedName = biz.verifiedName || biz.business_name || biz.description || null;
1394
+ }
1395
+ const status = await fetchStatus(info.jid).catch(() => null);
1396
+ const entry = Array.isArray(status) ? status[0] : status;
1397
+ info.about = entry?.status?.status ?? entry?.status ?? null;
1398
+ const pic = await profilePictureUrl(info.jid, 'image').catch(() => null);
1399
+ info.hasProfilePhoto = !!pic;
1400
+ const cap = await sock.fetchNewChatMessageCap().catch(() => null);
1401
+ if (cap) {
1402
+ info.self = { capped: cap.capped, warned: cap.warned, unlimited: cap.unlimited, remaining: cap.remaining };
1403
+ if (cap.capped) {
1404
+ info.notes.push('Akunmu sedang di-cap untuk chat baru, rem dulu');
1405
+ }
1406
+ else if (cap.warned) {
1407
+ info.notes.push('Akunmu sudah diperingatkan soal chat baru');
1408
+ }
1409
+ else {
1410
+ info.notes.push('Akunmu sehat untuk chat baru');
1411
+ }
1412
+ }
1413
+ return info;
1414
+ };
1415
+ return {
1416
+ ...sock,
1417
+ checkAccountHealth,
1418
+ findUserId,
1419
+ serverProps,
1420
+ fetchProps,
1421
+ getServerProps,
1422
+ createCallLink,
1423
+ getBotListV2,
1424
+ messageMutex,
1425
+ receiptMutex,
1426
+ appStatePatchMutex,
1427
+ notificationMutex,
1428
+ fetchPrivacySettings,
1429
+ upsertMessage,
1430
+ appPatch,
1431
+ sendPresenceUpdate,
1432
+ presenceSubscribe,
1433
+ profilePictureUrl,
1434
+ fetchBlocklist,
1435
+ fetchStatus,
1436
+ fetchDisappearingDuration,
1437
+ updateProfilePicture,
1438
+ removeProfilePicture,
1439
+ updateProfileStatus,
1440
+ getUsername,
1441
+ setUsername,
1442
+ removeUsername,
1443
+ setUsernamePin,
1444
+ removeUsernamePin,
1445
+ checkUsernameAvailability,
1446
+ updateTextStatus,
1447
+ fetchTextStatus,
1448
+ fetchAbout,
1449
+ fetchServerLinkPreview,
1450
+ fetchUserNotices,
1451
+ updateUserNoticeStage,
1452
+ fetchOptOutList,
1453
+ updateOptOut,
1454
+ fetchPushSettings,
1455
+ updateProfileName,
1456
+ updateBlockStatus,
1457
+ reportSpam,
1458
+ updateDisableLinkPreviewsPrivacy,
1459
+ updateCallPrivacy,
1460
+ updateMessagesPrivacy,
1461
+ updateLastSeenPrivacy,
1462
+ updateOnlinePrivacy,
1463
+ updateProfilePicturePrivacy,
1464
+ updateStatusPrivacy,
1465
+ updateReadReceiptsPrivacy,
1466
+ updateGroupsAddPrivacy,
1467
+ updateDefaultDisappearingMode,
1468
+ getBusinessProfile,
1469
+ resyncAppState,
1470
+ chatModify,
1471
+ cleanDirtyBits,
1472
+ addOrEditContact,
1473
+ removeContact,
1474
+ placeholderResendCache,
1475
+ addLabel,
1476
+ addChatLabel,
1477
+ removeChatLabel,
1478
+ addMessageLabel,
1479
+ removeMessageLabel,
1480
+ star,
1481
+ addOrEditQuickReply,
1482
+ removeQuickReply
1483
+ };
1484
+ };