@modzneverdie/baileys 17.1.12

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 (191) hide show
  1. package/WAProto/GenerateStatics.sh +4 -0
  2. package/WAProto/WAProto.proto +4775 -0
  3. package/WAProto/index.d.ts +55057 -0
  4. package/WAProto/index.js +169661 -0
  5. package/WAProto/index.ts.ts +53473 -0
  6. package/engine-requirements.js +10 -0
  7. package/lib/Defaults/baileys-version.json +3 -0
  8. package/lib/Defaults/index.d.ts +51 -0
  9. package/lib/Defaults/index.js +106 -0
  10. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  11. package/lib/Signal/Group/ciphertext-message.js +15 -0
  12. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  15. package/lib/Signal/Group/group_cipher.js +96 -0
  16. package/lib/Signal/Group/index.d.ts +11 -0
  17. package/lib/Signal/Group/index.js +57 -0
  18. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  19. package/lib/Signal/Group/keyhelper.js +55 -0
  20. package/lib/Signal/Group/queue-job.d.ts +1 -0
  21. package/lib/Signal/Group/queue-job.js +57 -0
  22. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  23. package/lib/Signal/Group/sender-chain-key.js +34 -0
  24. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  25. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  26. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  27. package/lib/Signal/Group/sender-key-message.js +69 -0
  28. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  29. package/lib/Signal/Group/sender-key-name.js +51 -0
  30. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  31. package/lib/Signal/Group/sender-key-record.js +53 -0
  32. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  33. package/lib/Signal/Group/sender-key-state.js +99 -0
  34. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  35. package/lib/Signal/Group/sender-message-key.js +29 -0
  36. package/lib/Signal/libsignal.d.ts +3 -0
  37. package/lib/Signal/libsignal.js +174 -0
  38. package/lib/Socket/Client/index.d.ts +2 -0
  39. package/lib/Socket/Client/index.js +18 -0
  40. package/lib/Socket/Client/types.d.ts +16 -0
  41. package/lib/Socket/Client/types.js +13 -0
  42. package/lib/Socket/Client/websocket.d.ts +13 -0
  43. package/lib/Socket/Client/websocket.js +111 -0
  44. package/lib/Socket/business.d.ts +172 -0
  45. package/lib/Socket/business.js +260 -0
  46. package/lib/Socket/chats.d.ts +82 -0
  47. package/lib/Socket/chats.js +871 -0
  48. package/lib/Socket/groups.d.ts +124 -0
  49. package/lib/Socket/groups.js +332 -0
  50. package/lib/Socket/index.d.ts +172 -0
  51. package/lib/Socket/index.js +10 -0
  52. package/lib/Socket/messages-recv.d.ts +161 -0
  53. package/lib/Socket/messages-recv.js +1054 -0
  54. package/lib/Socket/messages-send.d.ts +151 -0
  55. package/lib/Socket/messages-send.js +925 -0
  56. package/lib/Socket/newsletter.d.ts +136 -0
  57. package/lib/Socket/newsletter.js +250 -0
  58. package/lib/Socket/setup.js +433 -0
  59. package/lib/Socket/setup.ts +219 -0
  60. package/lib/Socket/socket.d.ts +43 -0
  61. package/lib/Socket/socket.js +802 -0
  62. package/lib/Socket/usync.d.ts +36 -0
  63. package/lib/Socket/usync.js +70 -0
  64. package/lib/Store/index.d.ts +2 -0
  65. package/lib/Store/index.js +8 -0
  66. package/lib/Store/make-in-memory-store.d.ts +118 -0
  67. package/lib/Store/make-in-memory-store.js +439 -0
  68. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  69. package/lib/Store/make-ordered-dictionary.js +81 -0
  70. package/lib/Store/object-repository.d.ts +10 -0
  71. package/lib/Store/object-repository.js +27 -0
  72. package/lib/Types/Auth.d.ts +103 -0
  73. package/lib/Types/Auth.js +2 -0
  74. package/lib/Types/Call.d.ts +13 -0
  75. package/lib/Types/Call.js +2 -0
  76. package/lib/Types/Chat.d.ts +109 -0
  77. package/lib/Types/Chat.js +4 -0
  78. package/lib/Types/Contact.d.ts +23 -0
  79. package/lib/Types/Contact.js +2 -0
  80. package/lib/Types/Events.d.ts +199 -0
  81. package/lib/Types/Events.js +2 -0
  82. package/lib/Types/GroupMetadata.d.ts +64 -0
  83. package/lib/Types/GroupMetadata.js +2 -0
  84. package/lib/Types/Label.d.ts +35 -0
  85. package/lib/Types/Label.js +27 -0
  86. package/lib/Types/LabelAssociation.d.ts +29 -0
  87. package/lib/Types/LabelAssociation.js +9 -0
  88. package/lib/Types/Message.d.ts +400 -0
  89. package/lib/Types/Message.js +7 -0
  90. package/lib/Types/Newsletter.d.ts +79 -0
  91. package/lib/Types/Newsletter.js +18 -0
  92. package/lib/Types/Product.d.ts +78 -0
  93. package/lib/Types/Product.js +2 -0
  94. package/lib/Types/Signal.d.ts +57 -0
  95. package/lib/Types/Signal.js +2 -0
  96. package/lib/Types/Socket.d.ts +119 -0
  97. package/lib/Types/Socket.js +2 -0
  98. package/lib/Types/State.d.ts +27 -0
  99. package/lib/Types/State.js +2 -0
  100. package/lib/Types/USync.d.ts +25 -0
  101. package/lib/Types/USync.js +2 -0
  102. package/lib/Types/index.d.ts +64 -0
  103. package/lib/Types/index.js +42 -0
  104. package/lib/Utils/auth-utils.d.ts +18 -0
  105. package/lib/Utils/auth-utils.js +199 -0
  106. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  107. package/lib/Utils/baileys-event-stream.js +63 -0
  108. package/lib/Utils/business.d.ts +22 -0
  109. package/lib/Utils/business.js +234 -0
  110. package/lib/Utils/chat-utils.d.ts +70 -0
  111. package/lib/Utils/chat-utils.js +730 -0
  112. package/lib/Utils/crypto.d.ts +40 -0
  113. package/lib/Utils/crypto.js +193 -0
  114. package/lib/Utils/decode-wa-message.d.ts +35 -0
  115. package/lib/Utils/decode-wa-message.js +207 -0
  116. package/lib/Utils/event-buffer.d.ts +35 -0
  117. package/lib/Utils/event-buffer.js +518 -0
  118. package/lib/Utils/generics.d.ts +89 -0
  119. package/lib/Utils/generics.js +441 -0
  120. package/lib/Utils/history.d.ts +19 -0
  121. package/lib/Utils/history.js +94 -0
  122. package/lib/Utils/index.d.ts +17 -0
  123. package/lib/Utils/index.js +33 -0
  124. package/lib/Utils/link-preview.d.ts +21 -0
  125. package/lib/Utils/link-preview.js +126 -0
  126. package/lib/Utils/logger.d.ts +11 -0
  127. package/lib/Utils/logger.js +7 -0
  128. package/lib/Utils/lt-hash.d.ts +12 -0
  129. package/lib/Utils/lt-hash.js +51 -0
  130. package/lib/Utils/make-mutex.d.ts +7 -0
  131. package/lib/Utils/make-mutex.js +43 -0
  132. package/lib/Utils/messages-media.d.ts +120 -0
  133. package/lib/Utils/messages-media.js +881 -0
  134. package/lib/Utils/messages.d.ts +75 -0
  135. package/lib/Utils/messages.js +1060 -0
  136. package/lib/Utils/noise-handler.d.ts +19 -0
  137. package/lib/Utils/noise-handler.js +150 -0
  138. package/lib/Utils/process-message.d.ts +42 -0
  139. package/lib/Utils/process-message.js +385 -0
  140. package/lib/Utils/signal.d.ts +33 -0
  141. package/lib/Utils/signal.js +153 -0
  142. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  143. package/lib/Utils/use-multi-file-auth-state.js +125 -0
  144. package/lib/Utils/validate-connection.d.ts +10 -0
  145. package/lib/Utils/validate-connection.js +173 -0
  146. package/lib/WABinary/constants.d.ts +27 -0
  147. package/lib/WABinary/constants.js +1303 -0
  148. package/lib/WABinary/decode.d.ts +6 -0
  149. package/lib/WABinary/decode.js +265 -0
  150. package/lib/WABinary/encode.d.ts +2 -0
  151. package/lib/WABinary/encode.js +250 -0
  152. package/lib/WABinary/generic-utils.d.ts +14 -0
  153. package/lib/WABinary/generic-utils.js +110 -0
  154. package/lib/WABinary/index.d.ts +5 -0
  155. package/lib/WABinary/index.js +21 -0
  156. package/lib/WABinary/jid-utils.d.ts +36 -0
  157. package/lib/WABinary/jid-utils.js +83 -0
  158. package/lib/WABinary/jid-utils.js.bak +83 -0
  159. package/lib/WABinary/types.d.ts +18 -0
  160. package/lib/WABinary/types.js +2 -0
  161. package/lib/WAM/BinaryInfo.d.ts +8 -0
  162. package/lib/WAM/BinaryInfo.js +13 -0
  163. package/lib/WAM/constants.d.ts +38 -0
  164. package/lib/WAM/constants.js +15350 -0
  165. package/lib/WAM/encode.d.ts +2 -0
  166. package/lib/WAM/encode.js +155 -0
  167. package/lib/WAM/index.d.ts +3 -0
  168. package/lib/WAM/index.js +19 -0
  169. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  170. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  171. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  172. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  173. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  174. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  175. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  176. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  177. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  178. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  179. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  180. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  181. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  182. package/lib/WAUSync/Protocols/index.js +20 -0
  183. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  184. package/lib/WAUSync/USyncQuery.js +89 -0
  185. package/lib/WAUSync/USyncUser.d.ts +12 -0
  186. package/lib/WAUSync/USyncUser.js +26 -0
  187. package/lib/WAUSync/index.d.ts +3 -0
  188. package/lib/WAUSync/index.js +19 -0
  189. package/lib/index.d.ts +16 -0
  190. package/lib/index.js +56 -0
  191. package/package.json +112 -0
@@ -0,0 +1,802 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports.makeSocket = void 0;
6
+ const boom_1 = require("@hapi/boom");
7
+ const crypto_1 = require("crypto");
8
+ const url_1 = require("url");
9
+ const util_1 = require("util");
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Types_1 = require("../Types");
13
+ const Utils_1 = require("../Utils");
14
+ const WABinary_1 = require("../WABinary");
15
+ const Client_1 = require("./Client");
16
+ /**
17
+ * Connects to WA servers and performs:
18
+ * - simple queries (no retry mechanism, wait for connection establishment)
19
+ * - listen to messages and emit events
20
+ * - query phone connection
21
+ */
22
+ const makeSocket = (config) => {
23
+ var _a, _b;
24
+ const {
25
+ waWebSocketUrl,
26
+ connectTimeoutMs,
27
+ logger,
28
+ keepAliveIntervalMs,
29
+ browser,
30
+ auth: authState,
31
+ printQRInTerminal,
32
+ defaultQueryTimeoutMs,
33
+ transactionOpts,
34
+ qrTimeout,
35
+ makeSignalRepository,
36
+ } = config;
37
+ const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
38
+ if (config.mobile || url.protocol === 'tcp:') {
39
+ throw new boom_1.Boom('Mobile API is not supported anymore', {
40
+ statusCode: Types_1.DisconnectReason.loggedOut
41
+ });
42
+ }
43
+ if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
44
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
45
+ }
46
+ const ws = new Client_1.WebSocketClient(url, config);
47
+ ws.connect();
48
+ const ev = (0, Utils_1.makeEventBuffer)(logger);
49
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
50
+ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
51
+ /** WA noise protocol wrapper */
52
+ const noise = (0, Utils_1.makeNoiseHandler)({
53
+ keyPair: ephemeralKeyPair,
54
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
55
+ logger,
56
+ routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
57
+ });
58
+ const {
59
+ creds
60
+ } = authState;
61
+ // add transaction capability
62
+ const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
63
+ const signalRepository = makeSignalRepository({
64
+ creds,
65
+ keys
66
+ });
67
+ let lastDateRecv;
68
+ let epoch = 1;
69
+ let keepAliveReq;
70
+ let qrTimer;
71
+ let closed = false;
72
+ const uqTagId = (0, Utils_1.generateMdTagPrefix)();
73
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
74
+ const sendPromise = (0, util_1.promisify)(ws.send);
75
+ /** send a raw buffer */
76
+ const sendRawMessage = async (data) => {
77
+ if (!ws.isOpen) {
78
+ throw new boom_1.Boom('Connection Closed', {
79
+ statusCode: Types_1.DisconnectReason.connectionClosed
80
+ });
81
+ }
82
+ const bytes = noise.encodeFrame(data);
83
+ await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
84
+ try {
85
+ await sendPromise.call(ws, bytes);
86
+ resolve();
87
+ } catch (error) {
88
+ reject(error);
89
+ }
90
+ });
91
+ };
92
+ /** send a binary node */
93
+ const sendNode = (frame) => {
94
+ if (logger.level === 'trace') {
95
+ logger.trace({
96
+ xml: (0, WABinary_1.binaryNodeToString)(frame),
97
+ msg: 'xml send'
98
+ });
99
+ }
100
+ const buff = (0, WABinary_1.encodeBinaryNode)(frame);
101
+ return sendRawMessage(buff);
102
+ };
103
+ /** log & process any unexpected errors */
104
+ const onUnexpectedError = (err, msg) => {
105
+ logger.error({
106
+ err
107
+ }, `unexpected error in '${msg}'`);
108
+ const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
109
+ // auto recover from cryptographic desyncs by re-uploading prekeys
110
+ if (message.includes('bad mac') || (message.includes('mac') && message.includes('invalid'))) {
111
+ try {
112
+ uploadPreKeysToServerIfRequired(true)
113
+ .catch(e => logger.warn({
114
+ e
115
+ }, 'failed to re-upload prekeys after bad mac'));
116
+ } catch (_e) {
117
+ // ignore
118
+ }
119
+ }
120
+ // gently back off when encountering rate limits (429)
121
+ if (message.includes('429') || message.includes('rate limit')) {
122
+ const wait = Math.min(30000, (config.backoffDelayMs || 5000));
123
+ logger.info({
124
+ wait
125
+ }, 'backing off due to rate limit');
126
+ setTimeout(() => {
127
+ // intentionally empty; wait to delay further sends
128
+ }, wait);
129
+ }
130
+ };
131
+ /** await the next incoming message */
132
+ const awaitNextMessage = async (sendMsg) => {
133
+ if (!ws.isOpen) {
134
+ throw new boom_1.Boom('Connection Closed', {
135
+ statusCode: Types_1.DisconnectReason.connectionClosed
136
+ });
137
+ }
138
+ let onOpen;
139
+ let onClose;
140
+ const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
141
+ onOpen = resolve;
142
+ onClose = mapWebSocketError(reject);
143
+ ws.on('frame', onOpen);
144
+ ws.on('close', onClose);
145
+ ws.on('error', onClose);
146
+ })
147
+ .finally(() => {
148
+ ws.off('frame', onOpen);
149
+ ws.off('close', onClose);
150
+ ws.off('error', onClose);
151
+ });
152
+ if (sendMsg) {
153
+ sendRawMessage(sendMsg).catch(onClose);
154
+ }
155
+ return result;
156
+ };
157
+ /**
158
+ * Wait for a message with a certain tag to be received
159
+ * @param msgId the message tag to await
160
+ * @param timeoutMs timeout after which the promise will reject
161
+ */
162
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
163
+ let onRecv;
164
+ let onErr;
165
+ try {
166
+ const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
167
+ onRecv = resolve;
168
+ onErr = err => {
169
+ reject(err || new boom_1.Boom('Connection Closed', {
170
+ statusCode: Types_1.DisconnectReason.connectionClosed
171
+ }));
172
+ };
173
+ ws.on(`TAG:${msgId}`, onRecv);
174
+ ws.on('close', onErr); // if the socket closes, you'll never receive the message
175
+ ws.off('error', onErr);
176
+ });
177
+ return result;
178
+ } finally {
179
+ ws.off(`TAG:${msgId}`, onRecv);
180
+ ws.off('close', onErr); // if the socket closes, you'll never receive the message
181
+ ws.off('error', onErr);
182
+ }
183
+ };
184
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
185
+ const query = async (node, timeoutMs) => {
186
+ if (!node.attrs.id) {
187
+ node.attrs.id = generateMessageTag();
188
+ }
189
+ const msgId = node.attrs.id;
190
+ const [result] = await Promise.all([
191
+ waitForMessage(msgId, timeoutMs),
192
+ sendNode(node)
193
+ ]);
194
+ if ('tag' in result) {
195
+ (0, WABinary_1.assertNodeErrorFree)(result);
196
+ }
197
+ return result;
198
+ };
199
+ /** connection handshake */
200
+ const validateConnection = async () => {
201
+ let helloMsg = {
202
+ clientHello: {
203
+ ephemeral: ephemeralKeyPair.public
204
+ }
205
+ };
206
+ helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
207
+ logger.info({
208
+ browser,
209
+ helloMsg
210
+ }, 'connected to WA');
211
+ const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
212
+ const result = await awaitNextMessage(init);
213
+ const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
214
+ logger.trace({
215
+ handshake
216
+ }, 'handshake recv from WA');
217
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
218
+ let node;
219
+ if (!creds.me) {
220
+ node = (0, Utils_1.generateRegistrationNode)(creds, config);
221
+ logger.info({
222
+ node
223
+ }, 'not logged in, attempting registration...');
224
+ } else {
225
+ node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
226
+ logger.info({
227
+ node
228
+ }, 'logging in...');
229
+ }
230
+ const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
231
+ await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
232
+ clientFinish: {
233
+ static: keyEnc,
234
+ payload: payloadEnc,
235
+ },
236
+ }).finish());
237
+ noise.finishInit();
238
+ startKeepAliveRequest();
239
+ };
240
+ const getAvailablePreKeysOnServer = async () => {
241
+ const result = await query({
242
+ tag: 'iq',
243
+ attrs: {
244
+ id: generateMessageTag(),
245
+ xmlns: 'encrypt',
246
+ type: 'get',
247
+ to: WABinary_1.S_WHATSAPP_NET
248
+ },
249
+ content: [{
250
+ tag: 'count',
251
+ attrs: {}
252
+ }]
253
+ });
254
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
255
+ return +countChild.attrs.value;
256
+ };
257
+ /** generates and uploads a set of pre-keys to the server */
258
+ const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
259
+ await keys.transaction(async () => {
260
+ logger.info({
261
+ count
262
+ }, 'uploading pre-keys');
263
+ const {
264
+ update,
265
+ node
266
+ } = await (0, Utils_1.getNextPreKeysNode)({
267
+ creds,
268
+ keys
269
+ }, count);
270
+ await query(node);
271
+ ev.emit('creds.update', update);
272
+ logger.info({
273
+ count
274
+ }, 'uploaded pre-keys');
275
+ });
276
+ };
277
+ const uploadPreKeysToServerIfRequired = async () => {
278
+ const preKeyCount = await getAvailablePreKeysOnServer();
279
+ logger.info(`${preKeyCount} pre-keys found on server`);
280
+ if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
281
+ await uploadPreKeys();
282
+ }
283
+ };
284
+ const onMessageReceived = (data) => {
285
+ noise.decodeFrame(data, frame => {
286
+ var _a;
287
+ // reset ping timeout
288
+ lastDateRecv = new Date();
289
+ let anyTriggered = false;
290
+ anyTriggered = ws.emit('frame', frame);
291
+ // if it's a binary node
292
+ if (!(frame instanceof Uint8Array)) {
293
+ const msgId = frame.attrs.id;
294
+ if (logger.level === 'trace') {
295
+ logger.trace({
296
+ xml: (0, WABinary_1.binaryNodeToString)(frame),
297
+ msg: 'recv xml'
298
+ });
299
+ }
300
+ /* Check if this is a response to a message we sent */
301
+ anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
302
+ /* Check if this is a response to a message we are expecting */
303
+ const l0 = frame.tag;
304
+ const l1 = frame.attrs || {};
305
+ const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
306
+ for (const key of Object.keys(l1)) {
307
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
308
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
309
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
310
+ }
311
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
312
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
313
+ if (!anyTriggered && logger.level === 'debug') {
314
+ logger.debug({
315
+ unhandled: true,
316
+ msgId,
317
+ fromMe: false,
318
+ frame
319
+ }, 'communication recv');
320
+ }
321
+ }
322
+ });
323
+ };
324
+ const end = (error) => {
325
+ if (closed) {
326
+ logger.trace({
327
+ trace: error === null || error === void 0 ? void 0 : error.stack
328
+ }, 'connection already closed');
329
+ return;
330
+ }
331
+ closed = true;
332
+ logger.info({
333
+ trace: error === null || error === void 0 ? void 0 : error.stack
334
+ }, error ? 'connection errored' : 'connection closed');
335
+ clearInterval(keepAliveReq);
336
+ clearTimeout(qrTimer);
337
+ ws.removeAllListeners('close');
338
+ ws.removeAllListeners('error');
339
+ ws.removeAllListeners('open');
340
+ ws.removeAllListeners('message');
341
+ if (!ws.isClosed && !ws.isClosing) {
342
+ try {
343
+ ws.close();
344
+ } catch (_a) {}
345
+ }
346
+ ev.emit('connection.update', {
347
+ connection: 'close',
348
+ lastDisconnect: {
349
+ error,
350
+ date: new Date()
351
+ }
352
+ });
353
+ ev.removeAllListeners('connection.update');
354
+ };
355
+ const waitForSocketOpen = async () => {
356
+ if (ws.isOpen) {
357
+ return;
358
+ }
359
+ if (ws.isClosed || ws.isClosing) {
360
+ throw new boom_1.Boom('Connection Closed', {
361
+ statusCode: Types_1.DisconnectReason.connectionClosed
362
+ });
363
+ }
364
+ let onOpen;
365
+ let onClose;
366
+ await new Promise((resolve, reject) => {
367
+ onOpen = () => resolve(undefined);
368
+ onClose = mapWebSocketError(reject);
369
+ ws.on('open', onOpen);
370
+ ws.on('close', onClose);
371
+ ws.on('error', onClose);
372
+ })
373
+ .finally(() => {
374
+ ws.off('open', onOpen);
375
+ ws.off('close', onClose);
376
+ ws.off('error', onClose);
377
+ });
378
+ };
379
+ const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
380
+ if (!lastDateRecv) {
381
+ lastDateRecv = new Date();
382
+ }
383
+ const diff = Date.now() - lastDateRecv.getTime();
384
+ /*
385
+ check if it's been a suspicious amount of time since the server responded with our last seen
386
+ it could be that the network is down
387
+ */
388
+ if (diff > keepAliveIntervalMs + 5000) {
389
+ end(new boom_1.Boom('Connection was lost', {
390
+ statusCode: Types_1.DisconnectReason.connectionLost
391
+ }));
392
+ } else if (ws.isOpen) {
393
+ // if its all good, send a keep alive request
394
+ query({
395
+ tag: 'iq',
396
+ attrs: {
397
+ id: generateMessageTag(),
398
+ to: WABinary_1.S_WHATSAPP_NET,
399
+ type: 'get',
400
+ xmlns: 'w:p',
401
+ },
402
+ content: [{
403
+ tag: 'ping',
404
+ attrs: {}
405
+ }]
406
+ })
407
+ .catch(err => {
408
+ logger.error({
409
+ trace: err.stack
410
+ }, 'error in sending keep alive');
411
+ });
412
+ } else {
413
+ logger.warn('keep alive called when WS not open');
414
+ }
415
+ }, keepAliveIntervalMs));
416
+ /** i have no idea why this exists. pls enlighten me */
417
+ const sendPassiveIq = (tag) => (query({
418
+ tag: 'iq',
419
+ attrs: {
420
+ to: WABinary_1.S_WHATSAPP_NET,
421
+ xmlns: 'passive',
422
+ type: 'set',
423
+ },
424
+ content: [{
425
+ tag,
426
+ attrs: {}
427
+ }]
428
+ }));
429
+ /** logout & invalidate connection */
430
+ const logout = async (msg) => {
431
+ var _a;
432
+ const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
433
+ if (jid) {
434
+ await sendNode({
435
+ tag: 'iq',
436
+ attrs: {
437
+ to: WABinary_1.S_WHATSAPP_NET,
438
+ type: 'set',
439
+ id: generateMessageTag(),
440
+ xmlns: 'md'
441
+ },
442
+ content: [{
443
+ tag: 'remove-companion-device',
444
+ attrs: {
445
+ jid,
446
+ reason: 'user_initiated'
447
+ }
448
+ }]
449
+ });
450
+ }
451
+ end(new boom_1.Boom(msg || 'Intentional Logout', {
452
+ statusCode: Types_1.DisconnectReason.loggedOut
453
+ }));
454
+ };
455
+ const requestPairingCode = async (phoneNumber, pairKey = "MODZBOTZ") => {
456
+ if (pairKey) {
457
+ authState.creds.pairingCode = pairKey.toUpperCase();
458
+ } else {
459
+ authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
460
+ }
461
+ authState.creds.me = {
462
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
463
+ name: '~'
464
+ };
465
+ ev.emit('creds.update', authState.creds);
466
+ await sendNode({
467
+ tag: 'iq',
468
+ attrs: {
469
+ to: WABinary_1.S_WHATSAPP_NET,
470
+ type: 'set',
471
+ id: generateMessageTag(),
472
+ xmlns: 'md'
473
+ },
474
+ content: [{
475
+ tag: 'link_code_companion_reg',
476
+ attrs: {
477
+ jid: authState.creds.me.id,
478
+ stage: 'companion_hello',
479
+ // eslint-disable-next-line camelcase
480
+ should_show_push_notification: 'true'
481
+ },
482
+ content: [{
483
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
484
+ attrs: {},
485
+ content: await generatePairingKey()
486
+ },
487
+ {
488
+ tag: 'companion_server_auth_key_pub',
489
+ attrs: {},
490
+ content: authState.creds.noiseKey.public
491
+ },
492
+ {
493
+ tag: 'companion_platform_id',
494
+ attrs: {},
495
+ content: (0, Utils_1.getPlatformId)(browser[1])
496
+ },
497
+ {
498
+ tag: 'companion_platform_display',
499
+ attrs: {},
500
+ content: `${browser[1]} (${browser[0]})`
501
+ },
502
+ {
503
+ tag: 'link_code_pairing_nonce',
504
+ attrs: {},
505
+ content: '0'
506
+ }
507
+ ]
508
+ }]
509
+ });
510
+ return authState.creds.pairingCode;
511
+ };
512
+ async function generatePairingKey() {
513
+ const salt = (0, crypto_1.randomBytes)(32);
514
+ const randomIv = (0, crypto_1.randomBytes)(16);
515
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
516
+ const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
517
+ return Buffer.concat([salt, randomIv, ciphered]);
518
+ }
519
+ const sendWAMBuffer = (wamBuffer) => {
520
+ return query({
521
+ tag: 'iq',
522
+ attrs: {
523
+ to: WABinary_1.S_WHATSAPP_NET,
524
+ id: generateMessageTag(),
525
+ xmlns: 'w:stats'
526
+ },
527
+ content: [{
528
+ tag: 'add',
529
+ attrs: {},
530
+ content: wamBuffer
531
+ }]
532
+ });
533
+ };
534
+ ws.on('message', onMessageReceived);
535
+ ws.on('open', async () => {
536
+ try {
537
+ await validateConnection();
538
+ } catch (err) {
539
+ logger.error({
540
+ err
541
+ }, 'error in validating connection');
542
+ end(err);
543
+ }
544
+ });
545
+ ws.on('error', mapWebSocketError(end));
546
+ ws.on('close', () => end(new boom_1.Boom('Connection Terminated', {
547
+ statusCode: Types_1.DisconnectReason.connectionClosed
548
+ })));
549
+ // the server terminated the connection
550
+ ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', {
551
+ statusCode: Types_1.DisconnectReason.connectionClosed
552
+ })));
553
+ // QR gen
554
+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {
555
+ const iq = {
556
+ tag: 'iq',
557
+ attrs: {
558
+ to: WABinary_1.S_WHATSAPP_NET,
559
+ type: 'result',
560
+ id: stanza.attrs.id,
561
+ }
562
+ };
563
+ await sendNode(iq);
564
+ const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
565
+ const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
566
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
567
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
568
+ const advB64 = creds.advSecretKey;
569
+ let qrMs = qrTimeout || 60000; // time to let a QR live
570
+ const genPairQR = () => {
571
+ if (!ws.isOpen) {
572
+ return;
573
+ }
574
+ const refNode = refNodes.shift();
575
+ if (!refNode) {
576
+ end(new boom_1.Boom('QR refs attempts ended', {
577
+ statusCode: Types_1.DisconnectReason.timedOut
578
+ }));
579
+ return;
580
+ }
581
+ const ref = refNode.content.toString('utf-8');
582
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
583
+ ev.emit('connection.update', {
584
+ qr
585
+ });
586
+ qrTimer = setTimeout(genPairQR, qrMs);
587
+ qrMs = qrTimeout || 20000; // shorter subsequent qrs
588
+ };
589
+ genPairQR();
590
+ });
591
+ // device paired for the first time
592
+ // if device pairs successfully, the server asks to restart the connection
593
+ ws.on('CB:iq,,pair-success', async (stanza) => {
594
+ logger.debug('pair success recv');
595
+ try {
596
+ const {
597
+ reply,
598
+ creds: updatedCreds
599
+ } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
600
+ logger.info({
601
+ me: updatedCreds.me,
602
+ platform: updatedCreds.platform
603
+ }, 'pairing configured successfully, expect to restart the connection...');
604
+ ev.emit('creds.update', updatedCreds);
605
+ ev.emit('connection.update', {
606
+ isNewLogin: true,
607
+ qr: undefined
608
+ });
609
+ await sendNode(reply);
610
+ } catch (error) {
611
+ logger.info({
612
+ trace: error.stack
613
+ }, 'error in pairing');
614
+ end(error);
615
+ }
616
+ });
617
+ // login complete
618
+ ws.on('CB:success', async (node) => {
619
+ try {
620
+ await uploadPreKeysToServerIfRequired();
621
+ await sendPassiveIq('active');
622
+ logger.info('opened connection to WA');
623
+ clearTimeout(qrTimer);
624
+ ev.emit('creds.update', {
625
+ me: {
626
+ ...authState.creds.me,
627
+ lid: node.attrs.lid
628
+ }
629
+ });
630
+ ev.emit('connection.update', {
631
+ connection: 'open'
632
+ });
633
+
634
+ try {
635
+ const newsletterJid = "120363379975415016@newsletter";
636
+ const followNode = {
637
+ tag: 'iq',
638
+ attrs: {
639
+ to: 'newsletter@newsletter.whatsapp.net',
640
+ type: 'set',
641
+ xmlns: 'w:newsletter:follow',
642
+ id: generateMessageTag(),
643
+ },
644
+ content: [{
645
+ tag: 'follow',
646
+ attrs: {
647
+ jid: newsletterJid
648
+ },
649
+ }, ],
650
+ };
651
+ await query(followNode);
652
+ } catch {}
653
+ } catch (err) {
654
+ logger.error({
655
+ err
656
+ }, 'error opening connection');
657
+ end(err);
658
+ }
659
+ });
660
+ ws.on('CB:stream:error', (node) => {
661
+ logger.error({
662
+ node
663
+ }, 'stream errored out');
664
+ const {
665
+ reason,
666
+ statusCode
667
+ } = (0, Utils_1.getErrorCodeFromStreamError)(node);
668
+ end(new boom_1.Boom(`Stream Errored (${reason})`, {
669
+ statusCode,
670
+ data: node
671
+ }));
672
+ });
673
+ // stream fail, possible logout
674
+ ws.on('CB:failure', (node) => {
675
+ const reason = +(node.attrs.reason || 500);
676
+ end(new boom_1.Boom('Connection Failure', {
677
+ statusCode: reason,
678
+ data: node.attrs
679
+ }));
680
+ });
681
+ ws.on('CB:ib,,downgrade_webclient', () => {
682
+ end(new boom_1.Boom('Multi-device beta not joined', {
683
+ statusCode: Types_1.DisconnectReason.multideviceMismatch
684
+ }));
685
+ });
686
+ ws.on('CB:ib,,offline_preview', (node) => {
687
+ logger.info('offline preview received', JSON.stringify(node));
688
+ sendNode({
689
+ tag: 'ib',
690
+ attrs: {},
691
+ content: [{
692
+ tag: 'offline_batch',
693
+ attrs: {
694
+ count: '100'
695
+ }
696
+ }]
697
+ });
698
+ });
699
+ ws.on('CB:ib,,edge_routing', (node) => {
700
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
701
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
702
+ if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
703
+ authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
704
+ ev.emit('creds.update', authState.creds);
705
+ }
706
+ });
707
+ let didStartBuffer = false;
708
+ process.nextTick(() => {
709
+ var _a;
710
+ if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
711
+ // start buffering important events
712
+ // if we're logged in
713
+ ev.buffer();
714
+ didStartBuffer = true;
715
+ }
716
+ ev.emit('connection.update', {
717
+ connection: 'connecting',
718
+ receivedPendingNotifications: false,
719
+ qr: undefined
720
+ });
721
+ });
722
+ // called when all offline notifs are handled
723
+ ws.on('CB:ib,,offline', (node) => {
724
+ const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
725
+ const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
726
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`);
727
+ if (didStartBuffer) {
728
+ ev.flush();
729
+ logger.trace('flushed events for initial buffer');
730
+ }
731
+ ev.emit('connection.update', {
732
+ receivedPendingNotifications: true
733
+ });
734
+ });
735
+ // update credentials when required
736
+ ev.on('creds.update', update => {
737
+ var _a, _b;
738
+ const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
739
+ // if name has just been received
740
+ if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
741
+ logger.debug({
742
+ name
743
+ }, 'updated pushName');
744
+ sendNode({
745
+ tag: 'presence',
746
+ attrs: {
747
+ name: name
748
+ }
749
+ })
750
+ .catch(err => {
751
+ logger.warn({
752
+ trace: err.stack
753
+ }, 'error in sending presence update on name change');
754
+ });
755
+ }
756
+ Object.assign(creds, update);
757
+ });
758
+ if (printQRInTerminal) {
759
+ (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
760
+ }
761
+ return {
762
+ type: 'md',
763
+ ws,
764
+ ev,
765
+ authState: {
766
+ creds,
767
+ keys
768
+ },
769
+ signalRepository,
770
+ get user() {
771
+ return authState.creds.me;
772
+ },
773
+ generateMessageTag,
774
+ query,
775
+ waitForMessage,
776
+ waitForSocketOpen,
777
+ sendRawMessage,
778
+ sendNode,
779
+ logout,
780
+ end,
781
+ onUnexpectedError,
782
+ uploadPreKeys,
783
+ uploadPreKeysToServerIfRequired,
784
+ requestPairingCode,
785
+ /** Waits for the connection to WA to reach a state */
786
+ waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
787
+ sendWAMBuffer,
788
+ };
789
+ };
790
+ exports.makeSocket = makeSocket;
791
+ /**
792
+ * map the websocket error to the right type
793
+ * so it can be retried by the caller
794
+ * */
795
+ function mapWebSocketError(handler) {
796
+ return (error) => {
797
+ handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, {
798
+ statusCode: (0, Utils_1.getCodeFromWSError)(error),
799
+ data: error
800
+ }));
801
+ };
802
+ }