@modzneverdie/baileys 17.1.13 → 17.1.17

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