ell-bail 1.2.0 → 2.0.0

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