@badzz88/baileys 8.5.6 → 8.5.7

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 (279) hide show
  1. package/README.md +2 -2
  2. package/WAProto/WAProto.proto +75 -1256
  3. package/WAProto/fix-imports.js +79 -69
  4. package/WAProto/index.d.ts +71491 -15254
  5. package/WAProto/index.js +126432 -19810
  6. package/engine-requirements.js +4 -3
  7. package/lib/Defaults/index.js +187 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.js +92 -0
  10. package/lib/Signal/Group/group_cipher.js +89 -0
  11. package/lib/Signal/Group/index.js +136 -0
  12. package/lib/Signal/Group/keyhelper.js +73 -0
  13. package/lib/Signal/Group/sender-chain-key.js +32 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  15. package/lib/Signal/Group/sender-key-message.js +69 -0
  16. package/lib/Signal/Group/sender-key-name.js +50 -0
  17. package/lib/Signal/Group/sender-key-record.js +44 -0
  18. package/lib/Signal/Group/sender-key-state.js +97 -0
  19. package/lib/Signal/Group/sender-message-key.js +30 -0
  20. package/lib/Signal/libsignal.js +459 -0
  21. package/lib/Signal/lid-mapping.js +260 -0
  22. package/lib/Socket/Client/index.js +30 -0
  23. package/lib/Socket/Client/types.js +13 -0
  24. package/lib/Socket/Client/websocket.js +62 -0
  25. package/lib/Socket/aigroups.js +240 -0
  26. package/lib/Socket/business.js +422 -0
  27. package/lib/Socket/chats.js +1816 -0
  28. package/lib/Socket/communities.js +549 -0
  29. package/lib/Socket/graphql.js +656 -0
  30. package/lib/Socket/groups.js +764 -0
  31. package/lib/Socket/index.js +39 -0
  32. package/lib/Socket/interactive-handler.js +522 -0
  33. package/lib/Socket/interop.js +549 -0
  34. package/{src → lib}/Socket/luxu.js +120 -82
  35. package/lib/Socket/managed-account.js +183 -0
  36. package/lib/Socket/messages-recv.js +2442 -0
  37. package/lib/Socket/messages-send.js +1853 -0
  38. package/lib/Socket/mex.js +60 -0
  39. package/lib/Socket/newsletter.js +818 -0
  40. package/lib/Socket/privacy.js +449 -0
  41. package/lib/Socket/registration.js +427 -0
  42. package/lib/Socket/socket.js +1092 -0
  43. package/lib/Socket/text-router.js +83 -0
  44. package/lib/Socket/username.js +243 -0
  45. package/lib/Store/index.js +36 -0
  46. package/{src → lib}/Store/keyed-db.js +11 -21
  47. package/lib/Store/make-cache-manager-store.js +90 -0
  48. package/lib/Store/make-in-memory-store.js +604 -0
  49. package/lib/Store/make-ordered-dictionary.js +81 -0
  50. package/lib/Store/object-repository.js +29 -0
  51. package/lib/Types/Auth.js +38 -0
  52. package/lib/Types/Bussines.js +2 -0
  53. package/lib/Types/Call.js +2 -0
  54. package/lib/Types/Chat.js +4 -0
  55. package/lib/Types/Contact.js +2 -0
  56. package/lib/Types/Events.js +2 -0
  57. package/lib/Types/GroupMetadata.js +2 -0
  58. package/lib/Types/Label.js +27 -0
  59. package/lib/Types/LabelAssociation.js +9 -0
  60. package/lib/Types/Message.js +95 -0
  61. package/lib/Types/Mex.js +112 -0
  62. package/lib/Types/Newsletter.js +121 -0
  63. package/lib/Types/Product.js +2 -0
  64. package/lib/Types/Signal.js +2 -0
  65. package/lib/Types/Socket.js +2 -0
  66. package/lib/Types/State.js +70 -0
  67. package/lib/Types/USync.js +2 -0
  68. package/lib/Types/index.js +55 -0
  69. package/lib/Utils/auth-utils.js +306 -0
  70. package/lib/Utils/browser-utils.js +114 -0
  71. package/lib/Utils/business.js +247 -0
  72. package/lib/Utils/chat-utils.js +1208 -0
  73. package/lib/Utils/command-loader.d.ts +31 -0
  74. package/lib/Utils/command-loader.js +100 -0
  75. package/lib/Utils/companion-reg-client-utils.js +42 -0
  76. package/lib/Utils/consumer-application.js +107 -0
  77. package/lib/Utils/crypto.js +155 -0
  78. package/lib/Utils/curve25519-js.js +275 -0
  79. package/lib/Utils/decode-wa-message.js +560 -0
  80. package/lib/Utils/event-buffer.js +607 -0
  81. package/lib/Utils/generics.js +563 -0
  82. package/lib/Utils/group-history.js +60 -0
  83. package/lib/Utils/history.js +244 -0
  84. package/lib/Utils/identity-change-handler.js +52 -0
  85. package/lib/Utils/index.js +57 -0
  86. package/lib/Utils/jid-display-normalization.js +218 -0
  87. package/lib/Utils/link-preview.js +143 -0
  88. package/lib/Utils/logger.js +9 -0
  89. package/lib/Utils/lt-hash.js +39 -0
  90. package/lib/Utils/make-mutex.js +36 -0
  91. package/lib/Utils/message-composer.js +479 -0
  92. package/lib/Utils/message-retry-manager.js +270 -0
  93. package/lib/Utils/messages-media.js +896 -0
  94. package/lib/Utils/messages.js +2904 -0
  95. package/lib/Utils/meta-ai-msmsg.js +262 -0
  96. package/lib/Utils/native-bridge.js +82 -0
  97. package/lib/Utils/noise-handler.js +196 -0
  98. package/lib/Utils/offline-node-processor.js +42 -0
  99. package/lib/Utils/pre-key-manager.js +107 -0
  100. package/lib/Utils/process-message.js +1048 -0
  101. package/lib/Utils/reporting-utils.js +262 -0
  102. package/lib/Utils/session-pool.d.ts +16 -0
  103. package/lib/Utils/session-pool.js +94 -0
  104. package/lib/Utils/signal.js +224 -0
  105. package/lib/Utils/stanza-ack.js +40 -0
  106. package/lib/Utils/sticker.d.ts +17 -0
  107. package/lib/Utils/sticker.js +145 -0
  108. package/lib/Utils/sync-action-utils.js +54 -0
  109. package/lib/Utils/tc-token-utils.js +161 -0
  110. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  111. package/lib/Utils/validate-connection.js +219 -0
  112. package/lib/Utils/view-once-cache.d.ts +9 -0
  113. package/lib/Utils/view-once-cache.js +79 -0
  114. package/lib/Utils/voip-rekey.js +22 -0
  115. package/lib/WABinary/constants.js +1304 -0
  116. package/lib/WABinary/decode.js +343 -0
  117. package/{src → lib}/WABinary/encode.js +12 -9
  118. package/lib/WABinary/generic-utils.js +240 -0
  119. package/lib/WABinary/index.js +33 -0
  120. package/lib/WABinary/jid-utils.js +361 -0
  121. package/lib/WABinary/types.js +2 -0
  122. package/lib/WAM/BinaryInfo.js +13 -0
  123. package/lib/WAM/constants.js +39486 -0
  124. package/lib/WAM/encode.js +142 -0
  125. package/lib/WAM/index.js +31 -0
  126. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  127. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  128. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  129. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  130. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  131. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  132. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  133. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  134. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  135. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  136. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  137. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  138. package/lib/WAUSync/Protocols/index.js +39 -0
  139. package/lib/WAUSync/USyncQuery.js +133 -0
  140. package/lib/WAUSync/USyncUser.js +50 -0
  141. package/lib/WAUSync/index.js +31 -0
  142. package/lib/antiban.js +4637 -0
  143. package/{src → lib}/index.js +49 -51
  144. package/package.json +4 -4
  145. package/src/Defaults/index.js +0 -186
  146. package/src/Signal/Group/ciphertext-message.js +0 -15
  147. package/src/Signal/Group/group-session-builder.js +0 -86
  148. package/src/Signal/Group/group_cipher.js +0 -82
  149. package/src/Signal/Group/index.js +0 -140
  150. package/src/Signal/Group/keyhelper.js +0 -77
  151. package/src/Signal/Group/sender-chain-key.js +0 -29
  152. package/src/Signal/Group/sender-key-distribution-message.js +0 -66
  153. package/src/Signal/Group/sender-key-message.js +0 -69
  154. package/src/Signal/Group/sender-key-name.js +0 -51
  155. package/src/Signal/Group/sender-key-record.js +0 -44
  156. package/src/Signal/Group/sender-key-state.js +0 -87
  157. package/src/Signal/Group/sender-message-key.js +0 -29
  158. package/src/Signal/libsignal.js +0 -455
  159. package/src/Signal/lid-mapping.js +0 -273
  160. package/src/Socket/Client/index.js +0 -31
  161. package/src/Socket/Client/types.js +0 -13
  162. package/src/Socket/Client/websocket.js +0 -61
  163. package/src/Socket/aigroups.js +0 -221
  164. package/src/Socket/business.js +0 -411
  165. package/src/Socket/chats.js +0 -1449
  166. package/src/Socket/communities.js +0 -463
  167. package/src/Socket/graphql.js +0 -523
  168. package/src/Socket/groups.js +0 -516
  169. package/src/Socket/index.js +0 -31
  170. package/src/Socket/interactive-handler.js +0 -527
  171. package/src/Socket/interop.js +0 -339
  172. package/src/Socket/managed-account.js +0 -98
  173. package/src/Socket/messages-recv.js +0 -2685
  174. package/src/Socket/messages-send.js +0 -2047
  175. package/src/Socket/mex.js +0 -57
  176. package/src/Socket/newsletter.js +0 -455
  177. package/src/Socket/privacy.js +0 -125
  178. package/src/Socket/registration.js +0 -236
  179. package/src/Socket/socket.js +0 -983
  180. package/src/Socket/text-router.js +0 -65
  181. package/src/Socket/username.js +0 -130
  182. package/src/Store/index.js +0 -33
  183. package/src/Store/make-cache-manager-store.js +0 -84
  184. package/src/Store/make-in-memory-store.js +0 -551
  185. package/src/Store/make-ordered-dictionary.js +0 -81
  186. package/src/Store/object-repository.js +0 -26
  187. package/src/Types/Auth.js +0 -31
  188. package/src/Types/Bussines.js +0 -2
  189. package/src/Types/Call.js +0 -2
  190. package/src/Types/Chat.js +0 -4
  191. package/src/Types/Contact.js +0 -2
  192. package/src/Types/Events.js +0 -2
  193. package/src/Types/GroupMetadata.js +0 -2
  194. package/src/Types/Label.js +0 -26
  195. package/src/Types/LabelAssociation.js +0 -8
  196. package/src/Types/Message.js +0 -93
  197. package/src/Types/Mex.js +0 -112
  198. package/src/Types/Newsletter.js +0 -109
  199. package/src/Types/Product.js +0 -2
  200. package/src/Types/Signal.js +0 -2
  201. package/src/Types/Socket.js +0 -2
  202. package/src/Types/State.js +0 -62
  203. package/src/Types/USync.js +0 -2
  204. package/src/Types/index.js +0 -56
  205. package/src/Utils/auth-utils.js +0 -254
  206. package/src/Utils/browser-utils.js +0 -112
  207. package/src/Utils/business.js +0 -240
  208. package/src/Utils/chat-utils.js +0 -1230
  209. package/src/Utils/command-loader.d.ts +0 -27
  210. package/src/Utils/command-loader.js +0 -89
  211. package/src/Utils/companion-reg-client-utils.js +0 -40
  212. package/src/Utils/consumer-application.js +0 -105
  213. package/src/Utils/crypto.js +0 -118
  214. package/src/Utils/curve25519-js.js +0 -242
  215. package/src/Utils/decode-wa-message.js +0 -529
  216. package/src/Utils/event-buffer.js +0 -580
  217. package/src/Utils/generics.js +0 -483
  218. package/src/Utils/group-history.js +0 -44
  219. package/src/Utils/history.js +0 -232
  220. package/src/Utils/identity-change-handler.js +0 -52
  221. package/src/Utils/index.js +0 -58
  222. package/src/Utils/jid-display-normalization.js +0 -195
  223. package/src/Utils/link-preview.js +0 -135
  224. package/src/Utils/logger.js +0 -8
  225. package/src/Utils/lt-hash.js +0 -25
  226. package/src/Utils/make-mutex.js +0 -36
  227. package/src/Utils/message-composer.js +0 -471
  228. package/src/Utils/message-retry-manager.js +0 -217
  229. package/src/Utils/messages-media.js +0 -843
  230. package/src/Utils/messages.js +0 -2817
  231. package/src/Utils/meta-ai-msmsg.js +0 -222
  232. package/src/Utils/native-bridge.js +0 -68
  233. package/src/Utils/noise-handler.js +0 -169
  234. package/src/Utils/offline-node-processor.js +0 -34
  235. package/src/Utils/pre-key-manager.js +0 -90
  236. package/src/Utils/process-message.js +0 -950
  237. package/src/Utils/reporting-utils.js +0 -261
  238. package/src/Utils/session-pool.d.ts +0 -14
  239. package/src/Utils/session-pool.js +0 -70
  240. package/src/Utils/signal.js +0 -217
  241. package/src/Utils/stanza-ack.js +0 -30
  242. package/src/Utils/sticker.d.ts +0 -13
  243. package/src/Utils/sticker.js +0 -123
  244. package/src/Utils/sync-action-utils.js +0 -45
  245. package/src/Utils/tc-token-utils.js +0 -158
  246. package/src/Utils/use-multi-file-auth-state.js +0 -111
  247. package/src/Utils/validate-connection.js +0 -209
  248. package/src/Utils/view-once-cache.d.ts +0 -12
  249. package/src/Utils/view-once-cache.js +0 -63
  250. package/src/Utils/voip-rekey.js +0 -22
  251. package/src/WABinary/constants.js +0 -1304
  252. package/src/WABinary/decode.js +0 -342
  253. package/src/WABinary/generic-utils.js +0 -238
  254. package/src/WABinary/index.js +0 -34
  255. package/src/WABinary/jid-utils.js +0 -351
  256. package/src/WABinary/types.js +0 -2
  257. package/src/WAM/BinaryInfo.js +0 -13
  258. package/src/WAM/constants.js +0 -39484
  259. package/src/WAM/encode.js +0 -149
  260. package/src/WAM/index.js +0 -32
  261. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -53
  262. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +0 -44
  263. package/src/WAUSync/Protocols/USyncContactProtocol.js +0 -55
  264. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +0 -55
  265. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -31
  266. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +0 -54
  267. package/src/WAUSync/Protocols/USyncLIDProtocol.js +0 -32
  268. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -473
  269. package/src/WAUSync/Protocols/USyncPictureProtocol.js +0 -34
  270. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
  271. package/src/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  272. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
  273. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +0 -28
  274. package/src/WAUSync/Protocols/index.js +0 -40
  275. package/src/WAUSync/USyncQuery.js +0 -126
  276. package/src/WAUSync/USyncUser.js +0 -50
  277. package/src/WAUSync/index.js +0 -32
  278. package/src/antiban.js +0 -4152
  279. /package/{src → lib}/Defaults/phonenumber-mcc.json +0 -0
@@ -1,983 +0,0 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', { value: true });
3
- exports.makeSocket = void 0;
4
- const boom_1 = require('@hapi/boom');
5
- const crypto_1 = require('crypto');
6
- const url_1 = require('url');
7
- const util_1 = require('util');
8
- const index_js_1 = require('../../WAProto/index.js');
9
- const Defaults_1 = require('../Defaults');
10
- const Types_1 = require('../Types');
11
- const Utils_1 = require('../Utils');
12
- const browser_utils_1 = require('../Utils/browser-utils');
13
- const WABinary_1 = require('../WABinary');
14
- const BinaryInfo_js_1 = require('../WAM/BinaryInfo.js');
15
- const WAUSync_1 = require('../WAUSync/');
16
- const Client_1 = require('./Client');
17
- const mex_1 = require('./mex');
18
- const makeSocket = config => {
19
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
20
- const publicWAMBuffer = new BinaryInfo_js_1.BinaryInfo();
21
- let serverTimeOffsetMs = 0;
22
- const uqTagId = (0, Utils_1.generateMdTagPrefix)();
23
- const generateMessageTag = () => `${uqTagId}${epoch++}`;
24
- if (printQRInTerminal) {
25
- logger.warn({}, '⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.');
26
- }
27
- const syncDisabled = Defaults_1.PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false).length === Defaults_1.PROCESSABLE_HISTORY_TYPES.length;
28
- if (syncDisabled) {
29
- logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
30
- }
31
- const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
32
- if (config.mobile || url.protocol === 'tcp:') {
33
- throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
34
- }
35
- if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
36
- url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
37
- }
38
- const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
39
- const noise = (0, Utils_1.makeNoiseHandler)({
40
- keyPair: ephemeralKeyPair,
41
- NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
42
- logger,
43
- routingInfo: authState?.creds?.routingInfo
44
- });
45
- const ws = new Client_1.WebSocketClient(url, config);
46
- ws.connect();
47
- const sendPromise = (0, util_1.promisify)(ws.send);
48
- const sendRawMessage = async (data) => {
49
- if (!ws.isOpen) {
50
- throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
51
- }
52
- const bytes = noise.encodeFrame(data);
53
- await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
54
- try {
55
- await sendPromise.call(ws, bytes);
56
- resolve();
57
- }
58
- catch (error) {
59
- reject(error);
60
- }
61
- });
62
- };
63
- const sendNode = frame => {
64
- if (logger.level === 'trace') {
65
- logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
66
- }
67
- const buff = (0, WABinary_1.encodeBinaryNode)(frame);
68
- return sendRawMessage(buff);
69
- };
70
- const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
71
- let onRecv;
72
- let onErr;
73
- try {
74
- const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
75
- onRecv = data => {
76
- resolve(data);
77
- };
78
- onErr = err => {
79
- reject(err ||
80
- new boom_1.Boom('Connection Closed', {
81
- statusCode: Types_1.DisconnectReason.connectionClosed
82
- }));
83
- };
84
- ws.on(`TAG:${msgId}`, onRecv);
85
- ws.on('close', onErr);
86
- ws.on('error', onErr);
87
- return () => reject(new boom_1.Boom('Query Cancelled'));
88
- });
89
- return result;
90
- }
91
- catch (error) {
92
- if (error instanceof boom_1.Boom && error.output?.statusCode === Types_1.DisconnectReason.timedOut) {
93
- logger?.warn?.({ msgId }, 'timed out waiting for message');
94
- return undefined;
95
- }
96
- throw error;
97
- }
98
- finally {
99
- if (onRecv)
100
- ws.off(`TAG:${msgId}`, onRecv);
101
- if (onErr) {
102
- ws.off('close', onErr);
103
- ws.off('error', onErr);
104
- }
105
- }
106
- };
107
- const query = async (node, timeoutMs) => {
108
- if (!node.attrs.id) {
109
- node.attrs.id = generateMessageTag();
110
- }
111
- const msgId = node.attrs.id;
112
- const result = await (0, Utils_1.promiseTimeout)(timeoutMs, async (resolve, reject) => {
113
- const result = waitForMessage(msgId, timeoutMs).catch(reject);
114
- sendNode(node)
115
- .then(async () => resolve(await result))
116
- .catch(reject);
117
- });
118
- if (result && 'tag' in result) {
119
- ;
120
- (0, WABinary_1.assertNodeErrorFree)(result);
121
- }
122
- return result;
123
- };
124
- const digestKeyBundle = async () => {
125
- const res = await query({
126
- tag: 'iq',
127
- attrs: { to: WABinary_1.S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
128
- content: [{ tag: 'digest', attrs: {} }]
129
- });
130
- const digestNode = (0, WABinary_1.getBinaryNodeChild)(res, 'digest');
131
- if (!digestNode) {
132
- await uploadPreKeys();
133
- throw new Error('encrypt/get digest returned no digest node');
134
- }
135
- };
136
- const rotateSignedPreKey = async () => {
137
- const newId = (creds.signedPreKey.keyId || 0) + 1;
138
- const skey = await (0, Utils_1.signedKeyPair)(creds.signedIdentityKey, newId);
139
- await query({
140
- tag: 'iq',
141
- attrs: { to: WABinary_1.S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
142
- content: [
143
- {
144
- tag: 'rotate',
145
- attrs: {},
146
- content: [(0, Utils_1.xmppSignedPreKey)(skey)]
147
- }
148
- ]
149
- });
150
- ev.emit('creds.update', { signedPreKey: skey });
151
- };
152
- const executeUSyncQuery = async (usyncQuery) => {
153
- if (usyncQuery.protocols.length === 0) {
154
- throw new boom_1.Boom('USyncQuery must have at least one protocol');
155
- }
156
- const validUsers = usyncQuery.users;
157
- const userNodes = validUsers.map(user => {
158
- return {
159
- tag: 'user',
160
- attrs: {
161
- jid: !user.phone ? user.id : undefined
162
- },
163
- content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
164
- };
165
- });
166
- const listNode = {
167
- tag: 'list',
168
- attrs: {},
169
- content: userNodes
170
- };
171
- const queryNode = {
172
- tag: 'query',
173
- attrs: {},
174
- content: usyncQuery.protocols.map(a => a.getQueryElement())
175
- };
176
- const iq = {
177
- tag: 'iq',
178
- attrs: {
179
- to: WABinary_1.S_WHATSAPP_NET,
180
- type: 'get',
181
- xmlns: 'usync'
182
- },
183
- content: [
184
- {
185
- tag: 'usync',
186
- attrs: {
187
- context: usyncQuery.context,
188
- mode: usyncQuery.mode,
189
- sid: generateMessageTag(),
190
- last: 'true',
191
- index: '0'
192
- },
193
- content: [queryNode, listNode]
194
- }
195
- ]
196
- };
197
- const result = await query(iq);
198
- return usyncQuery.parseUSyncQueryResult(result);
199
- };
200
- const onWhatsApp = async (...phoneNumber) => {
201
- let usyncQuery = new WAUSync_1.USyncQuery();
202
- let contactEnabled = false;
203
- for (const jid of phoneNumber) {
204
- if ((0, WABinary_1.isLidUser)(jid)) {
205
- logger?.warn('LIDs are not supported with onWhatsApp');
206
- continue;
207
- }
208
- else {
209
- if (!contactEnabled) {
210
- contactEnabled = true;
211
- usyncQuery = usyncQuery.withContactProtocol();
212
- }
213
- const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
214
- usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
215
- }
216
- }
217
- if (usyncQuery.users.length === 0) {
218
- return [];
219
- }
220
- const results = await executeUSyncQuery(usyncQuery);
221
- if (results) {
222
- return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }));
223
- }
224
- };
225
- const pnFromLIDUSync = async (jids) => {
226
- const usyncQuery = new WAUSync_1.USyncQuery().withLIDProtocol().withContext('background');
227
- for (const jid of jids) {
228
- if ((0, WABinary_1.isLidUser)(jid)) {
229
- logger?.warn('LID user found in LID fetch call');
230
- continue;
231
- }
232
- else {
233
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
234
- }
235
- }
236
- if (usyncQuery.users.length === 0) {
237
- return [];
238
- }
239
- const results = await executeUSyncQuery(usyncQuery);
240
- if (results) {
241
- return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
242
- }
243
- return [];
244
- };
245
- const toPn = async (lid) => {
246
- const lids = Array.isArray(lid) ? lid : [lid];
247
- const usyncQuery = new WAUSync_1.USyncQuery().withContactProtocol().withLIDProtocol();
248
- for (const l of lids) {
249
- const decoded = (0, WABinary_1.jidDecode)(l);
250
- if (!decoded)
251
- continue;
252
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId((0, WABinary_1.jidEncode)(decoded.user, 's.whatsapp.net')).withLid(l));
253
- }
254
- const result = await executeUSyncQuery(usyncQuery);
255
- return lids.map(l => {
256
- const decoded = (0, WABinary_1.jidDecode)(l);
257
- if (!decoded)
258
- return { lid: l, pn: null };
259
- const match = result?.list?.find(entry => {
260
- const entryDecoded = (0, WABinary_1.jidDecode)(entry.id);
261
- return entryDecoded?.user === decoded.user;
262
- });
263
- if (!match?.contact)
264
- return { lid: l, pn: null };
265
- const pn = (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(match.id)?.user, 's.whatsapp.net');
266
- return { lid: l, pn: pn ?? null };
267
- });
268
- };
269
- const toLID = async (pn) => {
270
- const pns = Array.isArray(pn) ? pn : [pn];
271
- const usyncQuery = new WAUSync_1.USyncQuery().withContactProtocol().withLIDProtocol();
272
- for (const p of pns) {
273
- const decoded = (0, WABinary_1.jidDecode)(p);
274
- if (!decoded)
275
- continue;
276
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId((0, WABinary_1.jidEncode)(decoded.user, 's.whatsapp.net')));
277
- }
278
- const result = await executeUSyncQuery(usyncQuery);
279
- return pns.map(p => {
280
- const decoded = (0, WABinary_1.jidDecode)(p);
281
- if (!decoded)
282
- return { pn: p, lid: null };
283
- const match = result?.list?.find(entry => {
284
- return (0, WABinary_1.jidDecode)(entry.id)?.user === decoded.user;
285
- });
286
- if (!match?.contact)
287
- return { pn: p, lid: null };
288
- const lidVal = match?.lid ?? null;
289
- const lid = lidVal ? (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(lidVal)?.user ?? lidVal, 'lid') : null;
290
- return { pn: p, lid };
291
- });
292
- };
293
- const fetchUsername = async (username, pin) => {
294
- const usernames = Array.isArray(username) ? username : [username];
295
- const usyncQuery = new WAUSync_1.USyncQuery().withContactProtocol().withLIDProtocol();
296
- for (const u of usernames) {
297
- const user = new WAUSync_1.USyncUser().withUsername(u);
298
- if (pin)
299
- user.withUsernameKey(pin);
300
- usyncQuery.withUser(user);
301
- }
302
- const result = await executeUSyncQuery(usyncQuery);
303
- return usernames.map(u => {
304
- const match = result?.list?.find(entry => entry?.username === u);
305
- if (!match?.contact)
306
- return { username: u, pn: null, lid: null };
307
- const lid = match.lid;
308
- const pn = (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(match.id)?.user, 's.whatsapp.net');
309
- return { username: u, pn: pn ?? null, lid: lid ?? null };
310
- });
311
- };
312
- const ev = (0, Utils_1.makeEventBuffer)(logger);
313
- const { creds } = authState;
314
- const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
315
- const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync);
316
- let lastDateRecv;
317
- let epoch = 1;
318
- let keepAliveReq;
319
- let qrTimer;
320
- let closed = false;
321
- const socketEndHandlers = [];
322
- const onUnexpectedError = (err, msg) => {
323
- logger.error({ err }, `unexpected error in '${msg}'`);
324
- };
325
- const awaitNextMessage = async (sendMsg) => {
326
- if (!ws.isOpen) {
327
- throw new boom_1.Boom('Connection Closed', {
328
- statusCode: Types_1.DisconnectReason.connectionClosed
329
- });
330
- }
331
- let onOpen;
332
- let onClose;
333
- const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
334
- onOpen = resolve;
335
- onClose = mapWebSocketError(reject);
336
- ws.on('frame', onOpen);
337
- ws.on('close', onClose);
338
- ws.on('error', onClose);
339
- }).finally(() => {
340
- ws.off('frame', onOpen);
341
- ws.off('close', onClose);
342
- ws.off('error', onClose);
343
- });
344
- if (sendMsg) {
345
- sendRawMessage(sendMsg).catch(onClose);
346
- }
347
- return result;
348
- };
349
- const validateConnection = async () => {
350
- let helloMsg = {
351
- clientHello: { ephemeral: ephemeralKeyPair.public }
352
- };
353
- helloMsg = index_js_1.proto.HandshakeMessage.fromObject(helloMsg);
354
- logger.info({ browser, helloMsg }, 'connected to WA');
355
- const init = index_js_1.proto.HandshakeMessage.encode(helloMsg).finish();
356
- const result = await awaitNextMessage(init);
357
- const handshake = index_js_1.proto.HandshakeMessage.decode(result);
358
- logger.trace({ handshake }, 'handshake recv from WA');
359
- const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
360
- let node;
361
- if (!creds.me) {
362
- node = (0, Utils_1.generateRegistrationNode)(creds, config);
363
- logger.info({ node }, 'not logged in, attempting registration...');
364
- }
365
- else {
366
- node = (0, Utils_1.generateLoginNode)(creds.me.id, config, creds);
367
- logger.info({ node }, 'logging in...');
368
- }
369
- const payloadEnc = noise.encrypt(index_js_1.proto.ClientPayload.encode(node).finish());
370
- await sendRawMessage(index_js_1.proto.HandshakeMessage.encode({
371
- clientFinish: {
372
- static: keyEnc,
373
- payload: payloadEnc
374
- }
375
- }).finish());
376
- await noise.finishInit();
377
- startKeepAliveRequest();
378
- };
379
- const getAvailablePreKeysOnServer = async () => {
380
- const result = await query({
381
- tag: 'iq',
382
- attrs: {
383
- id: generateMessageTag(),
384
- xmlns: 'encrypt',
385
- type: 'get',
386
- to: WABinary_1.S_WHATSAPP_NET
387
- },
388
- content: [{ tag: 'count', attrs: {} }]
389
- });
390
- const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
391
- return +countChild.attrs.value;
392
- };
393
- let uploadPreKeysPromise = null;
394
- let lastUploadTime = 0;
395
- const uploadPreKeys = async (count = Defaults_1.MIN_PREKEY_COUNT, retryCount = 0) => {
396
- if (retryCount === 0) {
397
- const timeSinceLastUpload = Date.now() - lastUploadTime;
398
- if (timeSinceLastUpload < Defaults_1.MIN_UPLOAD_INTERVAL) {
399
- logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`);
400
- return;
401
- }
402
- }
403
- if (uploadPreKeysPromise) {
404
- logger.debug('Pre-key upload already in progress, waiting for completion');
405
- await uploadPreKeysPromise;
406
- }
407
- const uploadLogic = async () => {
408
- logger.info({ count, retryCount }, 'uploading pre-keys');
409
- const node = await keys.transaction(async () => {
410
- logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
411
- const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
412
- ev.emit('creds.update', update);
413
- return node;
414
- }, creds?.me?.id || 'upload-pre-keys');
415
- try {
416
- await query(node);
417
- logger.info({ count }, 'uploaded pre-keys successfully');
418
- lastUploadTime = Date.now();
419
- }
420
- catch (uploadError) {
421
- logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
422
- if (retryCount < 3) {
423
- const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
424
- logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
425
- await new Promise(resolve => setTimeout(resolve, backoffDelay));
426
- return uploadPreKeys(count, retryCount + 1);
427
- }
428
- throw uploadError;
429
- }
430
- };
431
- uploadPreKeysPromise = Promise.race([
432
- uploadLogic(),
433
- new Promise((_, reject) => setTimeout(() => reject(new boom_1.Boom('Pre-key upload timeout', { statusCode: 408 })), Defaults_1.UPLOAD_TIMEOUT))
434
- ]);
435
- try {
436
- await uploadPreKeysPromise;
437
- }
438
- finally {
439
- uploadPreKeysPromise = null;
440
- }
441
- };
442
- const verifyCurrentPreKeyExists = async () => {
443
- const currentPreKeyId = creds.nextPreKeyId - 1;
444
- if (currentPreKeyId <= 0) {
445
- return { exists: false, currentPreKeyId: 0 };
446
- }
447
- const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
448
- const exists = !!preKeys[currentPreKeyId.toString()];
449
- return { exists, currentPreKeyId };
450
- };
451
- const uploadPreKeysToServerIfRequired = async () => {
452
- try {
453
- let count = 0;
454
- const preKeyCount = await getAvailablePreKeysOnServer();
455
- if (preKeyCount === 0)
456
- count = Defaults_1.INITIAL_PREKEY_COUNT;
457
- else
458
- count = Defaults_1.MIN_PREKEY_COUNT;
459
- const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
460
- logger.info(`${preKeyCount} pre-keys found on server`);
461
- logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
462
- const lowServerCount = preKeyCount <= count;
463
- const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
464
- const shouldUpload = lowServerCount || missingCurrentPreKey;
465
- if (shouldUpload) {
466
- const reasons = [];
467
- if (lowServerCount)
468
- reasons.push(`server count low (${preKeyCount})`);
469
- if (missingCurrentPreKey)
470
- reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
471
- logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
472
- await uploadPreKeys(count);
473
- }
474
- else {
475
- logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
476
- }
477
- }
478
- catch (error) {
479
- logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
480
- }
481
- };
482
- const onMessageReceived = async (data) => {
483
- await noise.decodeFrame(data, frame => {
484
- lastDateRecv = new Date();
485
- let anyTriggered = false;
486
- anyTriggered = ws.emit('frame', frame);
487
- if (!(frame instanceof Uint8Array)) {
488
- const msgId = frame.attrs.id;
489
- if (logger.level === 'trace') {
490
- logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
491
- }
492
- anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
493
- const l0 = frame.tag;
494
- const l1 = frame.attrs || {};
495
- const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
496
- for (const key of Object.keys(l1)) {
497
- anyTriggered =
498
- ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
499
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
500
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
501
- }
502
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
503
- anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
504
- if (!anyTriggered && logger.level === 'debug') {
505
- logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
506
- }
507
- }
508
- });
509
- };
510
- const end = async (error) => {
511
- if (closed) {
512
- logger.trace({ trace: error?.stack }, 'connection already closed');
513
- return;
514
- }
515
- closed = true;
516
- logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
517
- clearInterval(keepAliveReq);
518
- clearTimeout(qrTimer);
519
- ws.removeAllListeners('close');
520
- ws.removeAllListeners('open');
521
- ws.removeAllListeners('message');
522
- if (!ws.isClosed && !ws.isClosing) {
523
- try {
524
- await ws.close();
525
- }
526
- catch { }
527
- }
528
- for (const handler of socketEndHandlers) {
529
- try {
530
- await handler(error);
531
- }
532
- catch (err) {
533
- logger.error({ err }, 'error in socket end handler');
534
- }
535
- }
536
- ev.emit('connection.update', {
537
- connection: 'close',
538
- lastDisconnect: {
539
- error,
540
- date: new Date()
541
- }
542
- });
543
- ev.removeAllListeners('connection.update');
544
- };
545
- const waitForSocketOpen = async () => {
546
- if (ws.isOpen) {
547
- return;
548
- }
549
- if (ws.isClosed || ws.isClosing) {
550
- throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
551
- }
552
- let onOpen;
553
- let onClose;
554
- await new Promise((resolve, reject) => {
555
- onOpen = () => resolve(undefined);
556
- onClose = mapWebSocketError(reject);
557
- ws.on('open', onOpen);
558
- ws.on('close', onClose);
559
- ws.on('error', onClose);
560
- }).finally(() => {
561
- ws.off('open', onOpen);
562
- ws.off('close', onClose);
563
- ws.off('error', onClose);
564
- });
565
- };
566
- const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
567
- if (!lastDateRecv) {
568
- lastDateRecv = new Date();
569
- }
570
- const diff = Date.now() - lastDateRecv.getTime();
571
- if (diff > keepAliveIntervalMs + 5000) {
572
- void end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
573
- }
574
- else if (ws.isOpen) {
575
- query({
576
- tag: 'iq',
577
- attrs: {
578
- id: generateMessageTag(),
579
- to: WABinary_1.S_WHATSAPP_NET,
580
- type: 'get',
581
- xmlns: 'w:p'
582
- },
583
- content: [{ tag: 'ping', attrs: {} }]
584
- }).catch(err => {
585
- logger.error({ trace: err.stack }, 'error in sending keep alive');
586
- });
587
- }
588
- else {
589
- logger.warn('keep alive called when WS not open');
590
- }
591
- }, keepAliveIntervalMs));
592
- const sendPassiveIq = tag => query({
593
- tag: 'iq',
594
- attrs: {
595
- to: WABinary_1.S_WHATSAPP_NET,
596
- xmlns: 'passive',
597
- type: 'set'
598
- },
599
- content: [{ tag, attrs: {} }]
600
- });
601
- const logout = async (msg) => {
602
- const jid = authState.creds.me?.id;
603
- if (jid) {
604
- await sendNode({
605
- tag: 'iq',
606
- attrs: {
607
- to: WABinary_1.S_WHATSAPP_NET,
608
- type: 'set',
609
- id: generateMessageTag(),
610
- xmlns: 'md'
611
- },
612
- content: [
613
- {
614
- tag: 'remove-companion-device',
615
- attrs: {
616
- jid,
617
- reason: 'user_initiated'
618
- }
619
- }
620
- ]
621
- });
622
- }
623
- void end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
624
- };
625
- const requestPairingCode = async (phoneNumber, customPairingCode) => {
626
- const pairingCode = customPairingCode ?? (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
627
- if (customPairingCode && customPairingCode?.length !== 8) {
628
- throw new Error('Custom pairing code must be exactly 8 chars');
629
- }
630
- authState.creds.pairingCode = pairingCode;
631
- authState.creds.me = {
632
- id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
633
- name: '~'
634
- };
635
- ev.emit('creds.update', authState.creds);
636
- await sendNode({
637
- tag: 'iq',
638
- attrs: {
639
- to: WABinary_1.S_WHATSAPP_NET,
640
- type: 'set',
641
- id: generateMessageTag(),
642
- xmlns: 'md'
643
- },
644
- content: [
645
- {
646
- tag: 'link_code_companion_reg',
647
- attrs: {
648
- jid: authState.creds.me.id,
649
- stage: 'companion_hello',
650
- should_show_push_notification: 'true'
651
- },
652
- content: [
653
- {
654
- tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
655
- attrs: {},
656
- content: await generatePairingKey()
657
- },
658
- {
659
- tag: 'companion_server_auth_key_pub',
660
- attrs: {},
661
- content: authState.creds.noiseKey.public
662
- },
663
- {
664
- tag: 'companion_platform_id',
665
- attrs: {},
666
- content: (0, browser_utils_1.getPlatformId)(browser[1])
667
- },
668
- {
669
- tag: 'companion_platform_display',
670
- attrs: {},
671
- content: `${browser[1]} (${browser[0]})`
672
- },
673
- {
674
- tag: 'link_code_pairing_nonce',
675
- attrs: {},
676
- content: '0'
677
- }
678
- ]
679
- }
680
- ]
681
- });
682
- return authState.creds.pairingCode;
683
- };
684
- async function generatePairingKey() {
685
- const salt = (0, crypto_1.randomBytes)(32);
686
- const randomIv = (0, crypto_1.randomBytes)(16);
687
- const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
688
- const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
689
- return Buffer.concat([salt, randomIv, ciphered]);
690
- }
691
- const sendWAMBuffer = wamBuffer => {
692
- return query({
693
- tag: 'iq',
694
- attrs: {
695
- to: WABinary_1.S_WHATSAPP_NET,
696
- id: generateMessageTag(),
697
- xmlns: 'w:stats'
698
- },
699
- content: [
700
- {
701
- tag: 'add',
702
- attrs: { t: Math.round(Date.now() / 1000) + '' },
703
- content: wamBuffer
704
- }
705
- ]
706
- });
707
- };
708
- ws.on('message', onMessageReceived);
709
- ws.on('open', async () => {
710
- try {
711
- await validateConnection();
712
- }
713
- catch (err) {
714
- logger.error({ err }, 'error in validating connection');
715
- void end(err);
716
- }
717
- });
718
- ws.on('error', mapWebSocketError(end));
719
- ws.on('close', () => void end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
720
- ws.on('CB:xmlstreamend', () => void end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
721
- ws.on('CB:iq,type:set,pair-device', async (stanza) => {
722
- const iq = {
723
- tag: 'iq',
724
- attrs: {
725
- to: WABinary_1.S_WHATSAPP_NET,
726
- type: 'result',
727
- id: stanza.attrs.id
728
- }
729
- };
730
- await sendNode(iq);
731
- const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
732
- const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
733
- const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
734
- const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
735
- const advB64 = creds.advSecretKey;
736
- let qrMs = qrTimeout || 60000;
737
- const genPairQR = () => {
738
- if (!ws.isOpen) {
739
- return;
740
- }
741
- const refNode = refNodes.shift();
742
- if (!refNode) {
743
- void end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
744
- return;
745
- }
746
- const ref = refNode.content.toString('utf-8');
747
- const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
748
- ev.emit('connection.update', { qr });
749
- qrTimer = setTimeout(genPairQR, qrMs);
750
- qrMs = qrTimeout || 20000;
751
- };
752
- genPairQR();
753
- });
754
- ws.on('CB:iq,,pair-success', async (stanza) => {
755
- logger.debug('pair success recv');
756
- try {
757
- updateServerTimeOffset(stanza);
758
- const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
759
- logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
760
- ev.emit('creds.update', updatedCreds);
761
- ev.emit('connection.update', { isNewLogin: true, qr: undefined });
762
- await sendNode(reply);
763
- void sendUnifiedSession();
764
- }
765
- catch (error) {
766
- logger.info({ trace: error.stack }, 'error in pairing');
767
- void end(error);
768
- }
769
- });
770
- ws.on('CB:success', async (node) => {
771
- try {
772
- updateServerTimeOffset(node);
773
- await uploadPreKeysToServerIfRequired();
774
- if (!config.masqueradeAsPrimary) {
775
- await sendPassiveIq('active');
776
- }
777
- try {
778
- await digestKeyBundle();
779
- }
780
- catch (e) {
781
- logger.warn({ e }, 'failed to run digest after login');
782
- }
783
- }
784
- catch (err) {
785
- logger.warn({ err }, 'failed to send initial passive iq');
786
- }
787
- logger.info('opened connection to WA');
788
- clearTimeout(qrTimer);
789
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
790
- if (config.syncFullHistory && authState.creds.initialFullSyncDone !== true) {
791
- logger.debug('initial full history sync completed, persisting one-time flag');
792
- ev.emit('creds.update', { initialFullSyncDone: true });
793
- }
794
- ev.emit('connection.update', { connection: 'open' });
795
- void sendUnifiedSession();
796
- if (node.attrs.lid && authState.creds.me?.id) {
797
- const myLID = node.attrs.lid;
798
- process.nextTick(async () => {
799
- try {
800
- const myPN = authState.creds.me.id;
801
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
802
- const { user, device } = (0, WABinary_1.jidDecode)(myPN);
803
- await authState.keys.set({
804
- 'device-list': {
805
- [user]: [device?.toString() || '0']
806
- }
807
- });
808
- await signalRepository.migrateSession(myPN, myLID);
809
- logger.info({ myPN, myLID }, 'Own LID session created successfully');
810
- }
811
- catch (error) {
812
- logger.error({ error, lid: myLID }, 'Failed to create own LID session');
813
- }
814
- });
815
- }
816
- });
817
- ws.on('CB:stream:error', node => {
818
- const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
819
- logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out');
820
- const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
821
- void end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }));
822
- });
823
- ws.on('CB:failure', node => {
824
- const reason = +(node.attrs.reason || 500);
825
- void end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
826
- });
827
- ws.on('CB:ib,,downgrade_webclient', () => {
828
- void end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
829
- });
830
- ws.on('CB:ib,,offline_preview', async (node) => {
831
- logger.info('offline preview received', JSON.stringify(node));
832
- await sendNode({
833
- tag: 'ib',
834
- attrs: {},
835
- content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
836
- });
837
- });
838
- ws.on('CB:ib,,edge_routing', node => {
839
- const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
840
- const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
841
- if (routingInfo?.content) {
842
- authState.creds.routingInfo = Buffer.from(routingInfo?.content);
843
- ev.emit('creds.update', authState.creds);
844
- }
845
- });
846
- let didStartBuffer = false;
847
- process.nextTick(() => {
848
- if (creds.me?.id) {
849
- ev.buffer();
850
- didStartBuffer = true;
851
- }
852
- ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
853
- });
854
- ws.on('CB:ib,,offline', node => {
855
- const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
856
- const offlineNotifs = +(child?.attrs.count || 0);
857
- logger.info(`handled ${offlineNotifs} offline messages/notifications`);
858
- if (didStartBuffer) {
859
- ev.flush();
860
- logger.trace('flushed events for initial buffer');
861
- }
862
- ev.emit('connection.update', { receivedPendingNotifications: true });
863
- });
864
- ev.on('creds.update', update => {
865
- const name = update.me?.name;
866
- if (creds.me?.name !== name) {
867
- logger.debug({ name }, 'updated pushName');
868
- sendNode({
869
- tag: 'presence',
870
- attrs: { name: name }
871
- }).catch(err => {
872
- logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
873
- });
874
- }
875
- Object.assign(creds, update);
876
- });
877
- const updateServerTimeOffset = ({ attrs }) => {
878
- const tValue = attrs?.t;
879
- if (!tValue) {
880
- return;
881
- }
882
- const parsed = Number(tValue);
883
- if (Number.isNaN(parsed) || parsed <= 0) {
884
- return;
885
- }
886
- const localMs = Date.now();
887
- serverTimeOffsetMs = parsed * 1000 - localMs;
888
- logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
889
- };
890
- const getUnifiedSessionId = () => {
891
- const offsetMs = 3 * Defaults_1.TimeMs.Day;
892
- const now = Date.now() + serverTimeOffsetMs;
893
- const id = (now + offsetMs) % Defaults_1.TimeMs.Week;
894
- return id.toString();
895
- };
896
- const sendUnifiedSession = async () => {
897
- if (!ws.isOpen) {
898
- return;
899
- }
900
- const node = {
901
- tag: 'ib',
902
- attrs: {},
903
- content: [
904
- {
905
- tag: 'unified_session',
906
- attrs: {
907
- id: getUnifiedSessionId()
908
- }
909
- }
910
- ]
911
- };
912
- try {
913
- await sendNode(node);
914
- }
915
- catch (error) {
916
- logger.debug({ error }, 'failed to send unified_session telemetry');
917
- }
918
- };
919
- const fetchAccountReachoutTimelock = async () => {
920
- const queryResult = await (0, mex_1.executeWMexQuery)({}, Types_1.QueryIds.REACHOUT_TIMELOCK, Types_1.XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag);
921
- const result = {
922
- isActive: !!queryResult?.is_active,
923
- timeEnforcementEnds: queryResult?.time_enforcement_ends && queryResult?.time_enforcement_ends !== '0'
924
- ? new Date(parseInt(queryResult.time_enforcement_ends, 10) * 1000)
925
- : undefined,
926
- enforcementType: queryResult?.enforcement_type ?? Types_1.ReachoutTimelockEnforcementType.DEFAULT
927
- };
928
- ev.emit('connection.update', { reachoutTimeLock: result });
929
- return result;
930
- };
931
- const fetchNewChatMessageCap = async () => {
932
- return (0, mex_1.executeWMexQuery)({ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, Types_1.QueryIds.MESSAGE_CAPPING_INFO, Types_1.XWAPaths.xwa2_message_capping_info, query, generateMessageTag);
933
- };
934
- const registerSocketEndHandler = handler => {
935
- socketEndHandlers.push(handler);
936
- };
937
- return {
938
- type: 'md',
939
- ws,
940
- ev,
941
- authState: { creds, keys },
942
- signalRepository,
943
- get user() {
944
- return authState.creds.me;
945
- },
946
- generateMessageTag,
947
- query,
948
- waitForMessage,
949
- waitForSocketOpen,
950
- sendRawMessage,
951
- sendNode,
952
- logout,
953
- end,
954
- registerSocketEndHandler,
955
- toPn,
956
- toLID,
957
- fetchUsername,
958
- onUnexpectedError,
959
- uploadPreKeys,
960
- uploadPreKeysToServerIfRequired,
961
- digestKeyBundle,
962
- rotateSignedPreKey,
963
- requestPairingCode,
964
- updateServerTimeOffset,
965
- sendUnifiedSession,
966
- wamBuffer: publicWAMBuffer,
967
- waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
968
- sendWAMBuffer,
969
- executeUSyncQuery,
970
- onWhatsApp,
971
- fetchAccountReachoutTimelock,
972
- fetchNewChatMessageCap
973
- };
974
- };
975
- exports.makeSocket = makeSocket;
976
- function mapWebSocketError(handler) {
977
- return error => {
978
- handler(new boom_1.Boom(`WebSocket Error (${error?.message})`, {
979
- statusCode: (0, Utils_1.getCodeFromWSError)(error),
980
- data: error
981
- }));
982
- };
983
- }