@badzz88/baileys 8.5.4 → 8.5.6

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 (269) hide show
  1. package/README.md +2 -2
  2. package/WAProto/fix-imports.js +69 -79
  3. package/WAProto/index.d.ts +15305 -87935
  4. package/WAProto/index.js +41109 -194076
  5. package/engine-requirements.js +15 -8
  6. package/package.json +23 -19
  7. package/src/Defaults/index.js +186 -0
  8. package/src/Signal/Group/ciphertext-message.js +15 -0
  9. package/src/Signal/Group/group-session-builder.js +86 -0
  10. package/src/Signal/Group/group_cipher.js +82 -0
  11. package/src/Signal/Group/index.js +140 -0
  12. package/src/Signal/Group/keyhelper.js +77 -0
  13. package/src/Signal/Group/sender-chain-key.js +29 -0
  14. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  15. package/src/Signal/Group/sender-key-message.js +69 -0
  16. package/src/Signal/Group/sender-key-name.js +51 -0
  17. package/src/Signal/Group/sender-key-record.js +44 -0
  18. package/src/Signal/Group/sender-key-state.js +87 -0
  19. package/src/Signal/Group/sender-message-key.js +29 -0
  20. package/src/Signal/libsignal.js +455 -0
  21. package/src/Signal/lid-mapping.js +273 -0
  22. package/src/Socket/Client/index.js +31 -0
  23. package/src/Socket/Client/types.js +13 -0
  24. package/src/Socket/Client/websocket.js +61 -0
  25. package/src/Socket/aigroups.js +221 -0
  26. package/src/Socket/business.js +411 -0
  27. package/src/Socket/chats.js +1449 -0
  28. package/src/Socket/communities.js +463 -0
  29. package/src/Socket/graphql.js +523 -0
  30. package/src/Socket/groups.js +516 -0
  31. package/src/Socket/index.js +31 -0
  32. package/src/Socket/interactive-handler.js +527 -0
  33. package/src/Socket/interop.js +339 -0
  34. package/src/Socket/luxu.js +349 -0
  35. package/src/Socket/managed-account.js +98 -0
  36. package/src/Socket/messages-recv.js +2685 -0
  37. package/src/Socket/messages-send.js +2047 -0
  38. package/src/Socket/mex.js +57 -0
  39. package/src/Socket/newsletter.js +455 -0
  40. package/src/Socket/privacy.js +125 -0
  41. package/src/Socket/registration.js +236 -0
  42. package/src/Socket/socket.js +983 -0
  43. package/src/Socket/text-router.js +65 -0
  44. package/src/Socket/username.js +130 -0
  45. package/src/Store/index.js +33 -0
  46. package/src/Store/keyed-db.js +118 -0
  47. package/src/Store/make-cache-manager-store.js +84 -0
  48. package/src/Store/make-in-memory-store.js +551 -0
  49. package/src/Store/make-ordered-dictionary.js +81 -0
  50. package/src/Store/object-repository.js +26 -0
  51. package/src/Types/Auth.js +31 -0
  52. package/src/Types/Bussines.js +2 -0
  53. package/src/Types/Call.js +2 -0
  54. package/src/Types/Chat.js +4 -0
  55. package/src/Types/Contact.js +2 -0
  56. package/src/Types/Events.js +2 -0
  57. package/src/Types/GroupMetadata.js +2 -0
  58. package/src/Types/Label.js +26 -0
  59. package/src/Types/LabelAssociation.js +8 -0
  60. package/src/Types/Message.js +93 -0
  61. package/src/Types/Mex.js +112 -0
  62. package/src/Types/Newsletter.js +109 -0
  63. package/src/Types/Product.js +2 -0
  64. package/src/Types/Signal.js +2 -0
  65. package/src/Types/Socket.js +2 -0
  66. package/src/Types/State.js +62 -0
  67. package/src/Types/USync.js +2 -0
  68. package/src/Types/index.js +56 -0
  69. package/src/Utils/auth-utils.js +254 -0
  70. package/src/Utils/browser-utils.js +112 -0
  71. package/src/Utils/business.js +240 -0
  72. package/src/Utils/chat-utils.js +1230 -0
  73. package/src/Utils/command-loader.d.ts +27 -0
  74. package/src/Utils/command-loader.js +89 -0
  75. package/src/Utils/companion-reg-client-utils.js +40 -0
  76. package/src/Utils/consumer-application.js +105 -0
  77. package/src/Utils/crypto.js +118 -0
  78. package/src/Utils/curve25519-js.js +242 -0
  79. package/src/Utils/decode-wa-message.js +529 -0
  80. package/src/Utils/event-buffer.js +580 -0
  81. package/src/Utils/generics.js +483 -0
  82. package/src/Utils/group-history.js +44 -0
  83. package/src/Utils/history.js +232 -0
  84. package/src/Utils/identity-change-handler.js +52 -0
  85. package/src/Utils/index.js +58 -0
  86. package/src/Utils/jid-display-normalization.js +195 -0
  87. package/src/Utils/link-preview.js +135 -0
  88. package/src/Utils/logger.js +8 -0
  89. package/src/Utils/lt-hash.js +25 -0
  90. package/src/Utils/make-mutex.js +36 -0
  91. package/src/Utils/message-composer.js +471 -0
  92. package/src/Utils/message-retry-manager.js +217 -0
  93. package/src/Utils/messages-media.js +843 -0
  94. package/src/Utils/messages.js +2817 -0
  95. package/src/Utils/meta-ai-msmsg.js +222 -0
  96. package/src/Utils/native-bridge.js +68 -0
  97. package/src/Utils/noise-handler.js +169 -0
  98. package/src/Utils/offline-node-processor.js +34 -0
  99. package/src/Utils/pre-key-manager.js +90 -0
  100. package/src/Utils/process-message.js +950 -0
  101. package/src/Utils/reporting-utils.js +261 -0
  102. package/src/Utils/session-pool.d.ts +14 -0
  103. package/src/Utils/session-pool.js +70 -0
  104. package/src/Utils/signal.js +217 -0
  105. package/src/Utils/stanza-ack.js +30 -0
  106. package/src/Utils/sticker.d.ts +13 -0
  107. package/src/Utils/sticker.js +123 -0
  108. package/src/Utils/sync-action-utils.js +45 -0
  109. package/src/Utils/tc-token-utils.js +158 -0
  110. package/src/Utils/use-multi-file-auth-state.js +111 -0
  111. package/src/Utils/validate-connection.js +209 -0
  112. package/src/Utils/view-once-cache.d.ts +12 -0
  113. package/src/Utils/view-once-cache.js +63 -0
  114. package/src/Utils/voip-rekey.js +22 -0
  115. package/src/WABinary/constants.js +1304 -0
  116. package/src/WABinary/decode.js +342 -0
  117. package/src/WABinary/encode.js +225 -0
  118. package/src/WABinary/generic-utils.js +238 -0
  119. package/src/WABinary/index.js +34 -0
  120. package/src/WABinary/jid-utils.js +351 -0
  121. package/src/WABinary/types.js +2 -0
  122. package/src/WAM/BinaryInfo.js +13 -0
  123. package/src/WAM/constants.js +39484 -0
  124. package/src/WAM/encode.js +149 -0
  125. package/src/WAM/index.js +32 -0
  126. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  127. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +44 -0
  128. package/src/WAUSync/Protocols/USyncContactProtocol.js +55 -0
  129. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +55 -0
  130. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  131. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +54 -0
  132. package/src/WAUSync/Protocols/USyncLIDProtocol.js +32 -0
  133. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +473 -0
  134. package/src/WAUSync/Protocols/USyncPictureProtocol.js +34 -0
  135. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  136. package/src/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  137. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  138. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  139. package/src/WAUSync/Protocols/index.js +40 -0
  140. package/src/WAUSync/USyncQuery.js +126 -0
  141. package/src/WAUSync/USyncUser.js +50 -0
  142. package/src/WAUSync/index.js +32 -0
  143. package/src/antiban.js +4152 -0
  144. package/{lib → src}/index.js +51 -49
  145. package/lib/Defaults/index.js +0 -195
  146. package/lib/Signal/Group/ciphertext-message.js +0 -15
  147. package/lib/Signal/Group/group-session-builder.js +0 -92
  148. package/lib/Signal/Group/group_cipher.js +0 -89
  149. package/lib/Signal/Group/index.js +0 -136
  150. package/lib/Signal/Group/keyhelper.js +0 -73
  151. package/lib/Signal/Group/sender-chain-key.js +0 -32
  152. package/lib/Signal/Group/sender-key-distribution-message.js +0 -66
  153. package/lib/Signal/Group/sender-key-message.js +0 -69
  154. package/lib/Signal/Group/sender-key-name.js +0 -50
  155. package/lib/Signal/Group/sender-key-record.js +0 -44
  156. package/lib/Signal/Group/sender-key-state.js +0 -97
  157. package/lib/Signal/Group/sender-message-key.js +0 -30
  158. package/lib/Signal/libsignal.js +0 -470
  159. package/lib/Signal/lid-mapping.js +0 -280
  160. package/lib/Socket/Client/index.js +0 -30
  161. package/lib/Socket/Client/types.js +0 -13
  162. package/lib/Socket/Client/websocket.js +0 -62
  163. package/lib/Socket/aigroups.js +0 -240
  164. package/lib/Socket/business.js +0 -414
  165. package/lib/Socket/chats.js +0 -2165
  166. package/lib/Socket/communities.js +0 -545
  167. package/lib/Socket/graphql.js +0 -863
  168. package/lib/Socket/groups.js +0 -685
  169. package/lib/Socket/index.js +0 -41
  170. package/lib/Socket/interactive-handler.js +0 -579
  171. package/lib/Socket/interop.js +0 -430
  172. package/lib/Socket/managed-account.js +0 -214
  173. package/lib/Socket/messages-recv.js +0 -3000
  174. package/lib/Socket/messages-send.js +0 -2155
  175. package/lib/Socket/mex.js +0 -47
  176. package/lib/Socket/newsletter.js +0 -814
  177. package/lib/Socket/privacy.js +0 -261
  178. package/lib/Socket/registration.js +0 -434
  179. package/lib/Socket/socket.js +0 -1074
  180. package/lib/Socket/username.js +0 -160
  181. package/lib/Store/index.js +0 -36
  182. package/lib/Store/make-cache-manager-store.js +0 -90
  183. package/lib/Store/make-in-memory-store.js +0 -488
  184. package/lib/Store/make-ordered-dictionary.js +0 -81
  185. package/lib/Store/object-repository.js +0 -29
  186. package/lib/Types/Auth.js +0 -38
  187. package/lib/Types/Bussines.js +0 -2
  188. package/lib/Types/Call.js +0 -2
  189. package/lib/Types/Chat.js +0 -4
  190. package/lib/Types/Contact.js +0 -2
  191. package/lib/Types/Events.js +0 -2
  192. package/lib/Types/GroupMetadata.js +0 -2
  193. package/lib/Types/Label.js +0 -27
  194. package/lib/Types/LabelAssociation.js +0 -9
  195. package/lib/Types/Message.js +0 -95
  196. package/lib/Types/Newsletter.js +0 -152
  197. package/lib/Types/Product.js +0 -2
  198. package/lib/Types/Signal.js +0 -2
  199. package/lib/Types/Socket.js +0 -2
  200. package/lib/Types/State.js +0 -70
  201. package/lib/Types/USync.js +0 -2
  202. package/lib/Types/index.js +0 -55
  203. package/lib/Utils/auth-utils.js +0 -301
  204. package/lib/Utils/browser-utils.js +0 -114
  205. package/lib/Utils/business.js +0 -243
  206. package/lib/Utils/chat-utils.js +0 -1272
  207. package/lib/Utils/consumer-application.js +0 -107
  208. package/lib/Utils/crypto.js +0 -125
  209. package/lib/Utils/decode-wa-message.js +0 -793
  210. package/lib/Utils/event-buffer.js +0 -583
  211. package/lib/Utils/generics.js +0 -617
  212. package/lib/Utils/group-history.js +0 -51
  213. package/lib/Utils/history.js +0 -244
  214. package/lib/Utils/identity-change-handler.js +0 -52
  215. package/lib/Utils/index.js +0 -53
  216. package/lib/Utils/jid-display-normalization.js +0 -218
  217. package/lib/Utils/link-preview.js +0 -138
  218. package/lib/Utils/logger.js +0 -9
  219. package/lib/Utils/lt-hash.js +0 -6
  220. package/lib/Utils/make-mutex.js +0 -36
  221. package/lib/Utils/message-composer.js +0 -479
  222. package/lib/Utils/message-inspect.js +0 -393
  223. package/lib/Utils/message-retry-manager.js +0 -205
  224. package/lib/Utils/messages-media.js +0 -925
  225. package/lib/Utils/messages.js +0 -2482
  226. package/lib/Utils/meta-ai-msmsg.js +0 -122
  227. package/lib/Utils/noise-handler.js +0 -194
  228. package/lib/Utils/offline-node-processor.js +0 -37
  229. package/lib/Utils/pre-key-manager.js +0 -97
  230. package/lib/Utils/process-message.js +0 -1139
  231. package/lib/Utils/reporting-utils.js +0 -262
  232. package/lib/Utils/signal.js +0 -189
  233. package/lib/Utils/stanza-ack.js +0 -67
  234. package/lib/Utils/sync-action-utils.js +0 -51
  235. package/lib/Utils/tc-token-utils.js +0 -156
  236. package/lib/Utils/use-multi-file-auth-state.js +0 -137
  237. package/lib/Utils/validate-connection.js +0 -259
  238. package/lib/Utils/voip-rekey.js +0 -22
  239. package/lib/WABinary/constants.js +0 -1304
  240. package/lib/WABinary/decode.js +0 -377
  241. package/lib/WABinary/encode.js +0 -58
  242. package/lib/WABinary/generic-utils.js +0 -150
  243. package/lib/WABinary/index.js +0 -33
  244. package/lib/WABinary/jid-utils.js +0 -374
  245. package/lib/WABinary/types.js +0 -2
  246. package/lib/WAM/BinaryInfo.js +0 -13
  247. package/lib/WAM/constants.js +0 -39486
  248. package/lib/WAM/encode.js +0 -142
  249. package/lib/WAM/index.js +0 -31
  250. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -55
  251. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +0 -100
  252. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -60
  253. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -65
  254. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  255. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +0 -72
  256. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -31
  257. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -865
  258. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +0 -32
  259. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
  260. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -44
  261. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
  262. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -28
  263. package/lib/WAUSync/Protocols/index.js +0 -40
  264. package/lib/WAUSync/USyncBackoff.js +0 -26
  265. package/lib/WAUSync/USyncQuery.js +0 -204
  266. package/lib/WAUSync/USyncUser.js +0 -58
  267. package/lib/WAUSync/index.js +0 -32
  268. package/lib/antiban.js +0 -4391
  269. /package/{lib → src}/Defaults/phonenumber-mcc.json +0 -0
@@ -0,0 +1,983 @@
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
+ }