@baileys-md/baileys 11.0.3 → 11.1.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 (122) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1 -1
  3. package/WAProto/index.js +4182 -13516
  4. package/WASignalGroup/GroupProtocol.js +1697 -0
  5. package/WASignalGroup/ciphertext_message.js +16 -0
  6. package/WASignalGroup/group_cipher.js +120 -0
  7. package/WASignalGroup/group_session_builder.js +46 -0
  8. package/WASignalGroup/index.js +5 -0
  9. package/WASignalGroup/keyhelper.js +21 -0
  10. package/WASignalGroup/protobufs.js +3 -0
  11. package/WASignalGroup/queue_job.js +69 -0
  12. package/WASignalGroup/sender_chain_key.js +50 -0
  13. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  14. package/WASignalGroup/sender_key_message.js +92 -0
  15. package/WASignalGroup/sender_key_name.js +70 -0
  16. package/WASignalGroup/sender_key_record.js +56 -0
  17. package/WASignalGroup/sender_key_state.js +129 -0
  18. package/{lib/Signal/Group/sender-message-key.js → WASignalGroup/sender_message_key.js} +16 -4
  19. package/lib/Defaults/baileys-version.json +3 -0
  20. package/lib/Defaults/index.js +71 -52
  21. package/lib/Defaults/{phonenumber-mcc.js → phonenumber-mcc.json} +1 -1
  22. package/lib/Signal/libsignal.js +61 -41
  23. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  24. package/lib/Socket/Client/index.js +19 -3
  25. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  26. package/lib/Socket/Client/web-socket-client.js +62 -0
  27. package/lib/Socket/business.js +42 -37
  28. package/lib/Socket/chats.js +187 -194
  29. package/lib/Socket/groups.js +90 -87
  30. package/lib/Socket/index.js +8 -7
  31. package/lib/Socket/messages-recv.js +335 -360
  32. package/lib/Socket/messages-send.js +279 -156
  33. package/lib/Socket/newsletter.js +213 -144
  34. package/lib/Socket/registration.js +166 -0
  35. package/lib/Socket/socket.js +161 -128
  36. package/lib/Socket/usync.js +26 -19
  37. package/lib/Store/index.js +8 -0
  38. package/lib/Store/make-cache-manager-store.js +83 -0
  39. package/lib/{Utils → Store}/make-in-memory-store.js +27 -19
  40. package/lib/Store/make-mongo-store.js +567 -0
  41. package/lib/{Utils → Store}/make-ordered-dictionary.js +5 -2
  42. package/lib/{Utils → Store}/object-repository.js +4 -1
  43. package/lib/Types/Auth.js +2 -2
  44. package/lib/Types/Call.js +2 -2
  45. package/lib/Types/Chat.js +4 -8
  46. package/lib/Types/Contact.js +2 -2
  47. package/lib/Types/Events.js +2 -2
  48. package/lib/Types/GroupMetadata.js +2 -2
  49. package/lib/Types/Label.js +5 -3
  50. package/lib/Types/LabelAssociation.js +5 -3
  51. package/lib/Types/Message.js +7 -7
  52. package/lib/Types/Newsletter.js +17 -30
  53. package/lib/Types/Product.js +2 -2
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.js +2 -3
  56. package/lib/Types/State.js +2 -2
  57. package/lib/Types/USync.js +2 -2
  58. package/lib/Types/index.js +31 -15
  59. package/lib/Utils/auth-utils.js +47 -31
  60. package/lib/Utils/baileys-event-stream.js +22 -15
  61. package/lib/Utils/business.js +69 -66
  62. package/lib/Utils/chat-utils.js +195 -200
  63. package/lib/Utils/crypto.js +85 -70
  64. package/lib/Utils/decode-wa-message.js +51 -46
  65. package/lib/Utils/event-buffer.js +46 -36
  66. package/lib/Utils/generics.js +188 -116
  67. package/lib/Utils/history.js +46 -37
  68. package/lib/Utils/index.js +33 -19
  69. package/lib/Utils/link-preview.js +55 -14
  70. package/lib/Utils/logger.js +7 -3
  71. package/lib/Utils/lt-hash.js +26 -23
  72. package/lib/Utils/make-mutex.js +10 -7
  73. package/lib/Utils/messages-media.js +368 -239
  74. package/lib/Utils/messages.js +510 -278
  75. package/lib/Utils/noise-handler.js +31 -22
  76. package/lib/Utils/process-message.js +148 -144
  77. package/lib/Utils/signal.js +64 -71
  78. package/lib/Utils/use-multi-file-auth-state.js +32 -14
  79. package/lib/Utils/validate-connection.js +115 -72
  80. package/lib/WABinary/constants.js +20 -1281
  81. package/lib/WABinary/decode.js +52 -15
  82. package/lib/WABinary/encode.js +48 -14
  83. package/lib/WABinary/generic-utils.js +39 -31
  84. package/lib/WABinary/index.js +21 -6
  85. package/lib/WABinary/jid-utils.js +40 -23
  86. package/lib/WABinary/types.js +2 -2
  87. package/lib/WAM/BinaryInfo.js +5 -2
  88. package/lib/WAM/constants.js +2366 -2257
  89. package/lib/WAM/encode.js +21 -17
  90. package/lib/WAM/index.js +19 -4
  91. package/lib/WAUSync/Protocols/USyncContactProtocol.js +11 -8
  92. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  93. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  94. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  95. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  96. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +6 -3
  97. package/lib/WAUSync/Protocols/index.js +20 -5
  98. package/lib/WAUSync/USyncQuery.js +32 -34
  99. package/lib/WAUSync/USyncUser.js +5 -2
  100. package/lib/WAUSync/index.js +19 -4
  101. package/lib/index.js +33 -11
  102. package/package.json +61 -21
  103. package/WAProto/GenerateStatics.sh +0 -3
  104. package/WAProto/WAProto.proto +0 -4633
  105. package/WAProto/fix-imports.js +0 -29
  106. package/lib/Defaults/baileys-version.js +0 -1
  107. package/lib/Signal/Group/ciphertext-message.js +0 -12
  108. package/lib/Signal/Group/group-session-builder.js +0 -30
  109. package/lib/Signal/Group/group_cipher.js +0 -94
  110. package/lib/Signal/Group/index.js +0 -12
  111. package/lib/Signal/Group/keyhelper.js +0 -19
  112. package/lib/Signal/Group/queue-job.js +0 -54
  113. package/lib/Signal/Group/sender-chain-key.js +0 -32
  114. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  115. package/lib/Signal/Group/sender-key-message.js +0 -67
  116. package/lib/Signal/Group/sender-key-name.js +0 -48
  117. package/lib/Signal/Group/sender-key-record.js +0 -50
  118. package/lib/Signal/Group/sender-key-state.js +0 -96
  119. package/lib/Socket/Client/types.js +0 -11
  120. package/lib/Socket/Client/websocket.js +0 -50
  121. package/lib/Socket/communities.js +0 -351
  122. package/lib/Socket/mex.js +0 -42
@@ -1,62 +1,65 @@
1
- import { Boom } from '@hapi/boom';
2
- import { randomBytes } from 'crypto';
3
- import { URL } from 'url';
4
- import { promisify } from 'util';
5
- import { proto } from '../../WAProto/index.js';
6
- import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, NOISE_WA_HEADER } from '../Defaults/index.js';
7
- import { DisconnectReason } from '../Types/index.js';
8
- import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getErrorCodeFromStreamError, getNextPreKeysNode, getPlatformId, makeEventBuffer, makeNoiseHandler, promiseTimeout } from '../Utils/index.js';
9
- import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getBinaryNodeChild, getBinaryNodeChildren, jidEncode, S_WHATSAPP_NET } from '../WABinary/index.js';
10
- import { WebSocketClient } from './Client/index.js';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeSocket = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const crypto_1 = require("crypto");
6
+ const url_1 = require("url");
7
+ const util_1 = require("util");
8
+ const WAProto_1 = require("../../WAProto");
9
+ const Defaults_1 = require("../Defaults");
10
+ const Types_1 = require("../Types");
11
+ const Utils_1 = require("../Utils");
12
+ const WABinary_1 = require("../WABinary");
13
+ const Client_1 = require("./Client");
11
14
  /**
12
15
  * Connects to WA servers and performs:
13
16
  * - simple queries (no retry mechanism, wait for connection establishment)
14
17
  * - listen to messages and emit events
15
18
  * - query phone connection
16
19
  */
17
- export const makeSocket = (config) => {
18
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
19
- if (printQRInTerminal) {
20
- console.warn('⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.');
21
- }
22
- const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl;
23
- if (config.mobile || url.protocol === 'tcp:') {
24
- throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut });
20
+ const makeSocket = (config) => {
21
+ var _a, _b;
22
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
23
+ let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
+ config.mobile = config.mobile || url.protocol === 'tcp:';
25
+ if (config.mobile && url.protocol !== 'tcp:') {
26
+ url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
25
27
  }
26
- if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
28
+ if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
27
29
  url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
28
30
  }
29
- const ws = new WebSocketClient(url, config);
31
+ const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
30
32
  ws.connect();
31
- const ev = makeEventBuffer(logger);
33
+ const ev = (0, Utils_1.makeEventBuffer)(logger);
32
34
  /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
33
- const ephemeralKeyPair = Curve.generateKeyPair();
35
+ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
34
36
  /** WA noise protocol wrapper */
35
- const noise = makeNoiseHandler({
37
+ const noise = (0, Utils_1.makeNoiseHandler)({
36
38
  keyPair: ephemeralKeyPair,
37
- NOISE_HEADER: NOISE_WA_HEADER,
39
+ NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
40
+ mobile: config.mobile,
38
41
  logger,
39
- routingInfo: authState?.creds?.routingInfo
42
+ routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
40
43
  });
41
44
  const { creds } = authState;
42
45
  // add transaction capability
43
- const keys = addTransactionCapability(authState.keys, logger, transactionOpts);
46
+ const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
44
47
  const signalRepository = makeSignalRepository({ creds, keys });
45
48
  let lastDateRecv;
46
49
  let epoch = 1;
47
50
  let keepAliveReq;
48
51
  let qrTimer;
49
52
  let closed = false;
50
- const uqTagId = generateMdTagPrefix();
53
+ const uqTagId = (0, Utils_1.generateMdTagPrefix)();
51
54
  const generateMessageTag = () => `${uqTagId}${epoch++}`;
52
- const sendPromise = promisify(ws.send);
55
+ const sendPromise = (0, util_1.promisify)(ws.send);
53
56
  /** send a raw buffer */
54
57
  const sendRawMessage = async (data) => {
55
58
  if (!ws.isOpen) {
56
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
59
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
57
60
  }
58
61
  const bytes = noise.encodeFrame(data);
59
- await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
62
+ await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
60
63
  try {
61
64
  await sendPromise.call(ws, bytes);
62
65
  resolve();
@@ -69,9 +72,9 @@ export const makeSocket = (config) => {
69
72
  /** send a binary node */
70
73
  const sendNode = (frame) => {
71
74
  if (logger.level === 'trace') {
72
- logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' });
75
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
73
76
  }
74
- const buff = encodeBinaryNode(frame);
77
+ const buff = (0, WABinary_1.encodeBinaryNode)(frame);
75
78
  return sendRawMessage(buff);
76
79
  };
77
80
  /** log & process any unexpected errors */
@@ -81,19 +84,20 @@ export const makeSocket = (config) => {
81
84
  /** await the next incoming message */
82
85
  const awaitNextMessage = async (sendMsg) => {
83
86
  if (!ws.isOpen) {
84
- throw new Boom('Connection Closed', {
85
- statusCode: DisconnectReason.connectionClosed
87
+ throw new boom_1.Boom('Connection Closed', {
88
+ statusCode: Types_1.DisconnectReason.connectionClosed
86
89
  });
87
90
  }
88
91
  let onOpen;
89
92
  let onClose;
90
- const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
93
+ const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
91
94
  onOpen = resolve;
92
95
  onClose = mapWebSocketError(reject);
93
96
  ws.on('frame', onOpen);
94
97
  ws.on('close', onClose);
95
98
  ws.on('error', onClose);
96
- }).finally(() => {
99
+ })
100
+ .finally(() => {
97
101
  ws.off('frame', onOpen);
98
102
  ws.off('close', onClose);
99
103
  ws.off('error', onClose);
@@ -112,10 +116,10 @@ export const makeSocket = (config) => {
112
116
  let onRecv;
113
117
  let onErr;
114
118
  try {
115
- const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
119
+ const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
116
120
  onRecv = resolve;
117
121
  onErr = err => {
118
- reject(err || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
122
+ reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
119
123
  };
120
124
  ws.on(`TAG:${msgId}`, onRecv);
121
125
  ws.on('close', onErr); // if the socket closes, you'll never receive the message
@@ -135,9 +139,12 @@ export const makeSocket = (config) => {
135
139
  node.attrs.id = generateMessageTag();
136
140
  }
137
141
  const msgId = node.attrs.id;
138
- const [result] = await Promise.all([waitForMessage(msgId, timeoutMs), sendNode(node)]);
142
+ const [result] = await Promise.all([
143
+ waitForMessage(msgId, timeoutMs),
144
+ sendNode(node)
145
+ ]);
139
146
  if ('tag' in result) {
140
- assertNodeErrorFree(result);
147
+ (0, WABinary_1.assertNodeErrorFree)(result);
141
148
  }
142
149
  return result;
143
150
  };
@@ -146,28 +153,31 @@ export const makeSocket = (config) => {
146
153
  let helloMsg = {
147
154
  clientHello: { ephemeral: ephemeralKeyPair.public }
148
155
  };
149
- helloMsg = proto.HandshakeMessage.fromObject(helloMsg);
156
+ helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
150
157
  logger.info({ browser, helloMsg }, 'connected to WA');
151
- const init = proto.HandshakeMessage.encode(helloMsg).finish();
158
+ const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
152
159
  const result = await awaitNextMessage(init);
153
- const handshake = proto.HandshakeMessage.decode(result);
160
+ const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
154
161
  logger.trace({ handshake }, 'handshake recv from WA');
155
162
  const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
156
163
  let node;
157
- if (!creds.me) {
158
- node = generateRegistrationNode(creds, config);
164
+ if (config.mobile) {
165
+ node = (0, Utils_1.generateMobileNode)(config);
166
+ }
167
+ else if (!creds.me) {
168
+ node = (0, Utils_1.generateRegistrationNode)(creds, config);
159
169
  logger.info({ node }, 'not logged in, attempting registration...');
160
170
  }
161
171
  else {
162
- node = generateLoginNode(creds.me.id, config);
172
+ node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
163
173
  logger.info({ node }, 'logging in...');
164
174
  }
165
- const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
166
- await sendRawMessage(proto.HandshakeMessage.encode({
175
+ const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
176
+ await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
167
177
  clientFinish: {
168
178
  static: keyEnc,
169
- payload: payloadEnc
170
- }
179
+ payload: payloadEnc,
180
+ },
171
181
  }).finish());
172
182
  noise.finishInit();
173
183
  startKeepAliveRequest();
@@ -179,18 +189,20 @@ export const makeSocket = (config) => {
179
189
  id: generateMessageTag(),
180
190
  xmlns: 'encrypt',
181
191
  type: 'get',
182
- to: S_WHATSAPP_NET
192
+ to: WABinary_1.S_WHATSAPP_NET
183
193
  },
184
- content: [{ tag: 'count', attrs: {} }]
194
+ content: [
195
+ { tag: 'count', attrs: {} }
196
+ ]
185
197
  });
186
- const countChild = getBinaryNodeChild(result, 'count');
198
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
187
199
  return +countChild.attrs.value;
188
200
  };
189
201
  /** generates and uploads a set of pre-keys to the server */
190
- const uploadPreKeys = async (count = INITIAL_PREKEY_COUNT) => {
202
+ const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
191
203
  await keys.transaction(async () => {
192
204
  logger.info({ count }, 'uploading pre-keys');
193
- const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
205
+ const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
194
206
  await query(node);
195
207
  ev.emit('creds.update', update);
196
208
  logger.info({ count }, 'uploaded pre-keys');
@@ -199,12 +211,13 @@ export const makeSocket = (config) => {
199
211
  const uploadPreKeysToServerIfRequired = async () => {
200
212
  const preKeyCount = await getAvailablePreKeysOnServer();
201
213
  logger.info(`${preKeyCount} pre-keys found on server`);
202
- if (preKeyCount <= MIN_PREKEY_COUNT) {
214
+ if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
203
215
  await uploadPreKeys();
204
216
  }
205
217
  };
206
218
  const onMessageReceived = (data) => {
207
219
  noise.decodeFrame(data, frame => {
220
+ var _a;
208
221
  // reset ping timeout
209
222
  lastDateRecv = new Date();
210
223
  let anyTriggered = false;
@@ -213,21 +226,21 @@ export const makeSocket = (config) => {
213
226
  if (!(frame instanceof Uint8Array)) {
214
227
  const msgId = frame.attrs.id;
215
228
  if (logger.level === 'trace') {
216
- logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' });
229
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
217
230
  }
218
231
  /* Check if this is a response to a message we sent */
219
- anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
232
+ anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
220
233
  /* Check if this is a response to a message we are expecting */
221
234
  const l0 = frame.tag;
222
235
  const l1 = frame.attrs || {};
223
- const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
224
- for (const key of Object.keys(l1)) {
225
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
226
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
227
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
228
- }
229
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
230
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
236
+ const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
237
+ Object.keys(l1).forEach(key => {
238
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
239
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
240
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
241
+ });
242
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
243
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
231
244
  if (!anyTriggered && logger.level === 'debug') {
232
245
  logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
233
246
  }
@@ -236,21 +249,22 @@ export const makeSocket = (config) => {
236
249
  };
237
250
  const end = (error) => {
238
251
  if (closed) {
239
- logger.trace({ trace: error?.stack }, 'connection already closed');
252
+ logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
240
253
  return;
241
254
  }
242
255
  closed = true;
243
- logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
256
+ logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
244
257
  clearInterval(keepAliveReq);
245
258
  clearTimeout(qrTimer);
246
259
  ws.removeAllListeners('close');
260
+ ws.removeAllListeners('error');
247
261
  ws.removeAllListeners('open');
248
262
  ws.removeAllListeners('message');
249
263
  if (!ws.isClosed && !ws.isClosing) {
250
264
  try {
251
265
  ws.close();
252
266
  }
253
- catch { }
267
+ catch (_a) { }
254
268
  }
255
269
  ev.emit('connection.update', {
256
270
  connection: 'close',
@@ -266,7 +280,7 @@ export const makeSocket = (config) => {
266
280
  return;
267
281
  }
268
282
  if (ws.isClosed || ws.isClosing) {
269
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
283
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
270
284
  }
271
285
  let onOpen;
272
286
  let onClose;
@@ -276,7 +290,8 @@ export const makeSocket = (config) => {
276
290
  ws.on('open', onOpen);
277
291
  ws.on('close', onClose);
278
292
  ws.on('error', onClose);
279
- }).finally(() => {
293
+ })
294
+ .finally(() => {
280
295
  ws.off('open', onOpen);
281
296
  ws.off('close', onClose);
282
297
  ws.off('error', onClose);
@@ -292,7 +307,7 @@ export const makeSocket = (config) => {
292
307
  it could be that the network is down
293
308
  */
294
309
  if (diff > keepAliveIntervalMs + 5000) {
295
- end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }));
310
+ end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
296
311
  }
297
312
  else if (ws.isOpen) {
298
313
  // if its all good, send a keep alive request
@@ -300,12 +315,13 @@ export const makeSocket = (config) => {
300
315
  tag: 'iq',
301
316
  attrs: {
302
317
  id: generateMessageTag(),
303
- to: S_WHATSAPP_NET,
318
+ to: WABinary_1.S_WHATSAPP_NET,
304
319
  type: 'get',
305
- xmlns: 'w:p'
320
+ xmlns: 'w:p',
306
321
  },
307
322
  content: [{ tag: 'ping', attrs: {} }]
308
- }).catch(err => {
323
+ })
324
+ .catch(err => {
309
325
  logger.error({ trace: err.stack }, 'error in sending keep alive');
310
326
  });
311
327
  }
@@ -314,23 +330,26 @@ export const makeSocket = (config) => {
314
330
  }
315
331
  }, keepAliveIntervalMs));
316
332
  /** i have no idea why this exists. pls enlighten me */
317
- const sendPassiveIq = (tag) => query({
333
+ const sendPassiveIq = (tag) => (query({
318
334
  tag: 'iq',
319
335
  attrs: {
320
- to: S_WHATSAPP_NET,
336
+ to: WABinary_1.S_WHATSAPP_NET,
321
337
  xmlns: 'passive',
322
- type: 'set'
338
+ type: 'set',
323
339
  },
324
- content: [{ tag, attrs: {} }]
325
- });
340
+ content: [
341
+ { tag, attrs: {} }
342
+ ]
343
+ }));
326
344
  /** logout & invalidate connection */
327
345
  const logout = async (msg) => {
328
- const jid = authState.creds.me?.id;
346
+ var _a;
347
+ const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
329
348
  if (jid) {
330
349
  await sendNode({
331
350
  tag: 'iq',
332
351
  attrs: {
333
- to: S_WHATSAPP_NET,
352
+ to: WABinary_1.S_WHATSAPP_NET,
334
353
  type: 'set',
335
354
  id: generateMessageTag(),
336
355
  xmlns: 'md'
@@ -346,23 +365,24 @@ export const makeSocket = (config) => {
346
365
  ]
347
366
  });
348
367
  }
349
- end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
368
+ end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
350
369
  };
351
- const requestPairingCode = async (phoneNumber, customPairingCode) => {
352
- const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
353
- if (customPairingCode && customPairingCode?.length !== 8) {
354
- throw new Error('Custom pairing code must be exactly 8 chars');
370
+ const requestPairingCode = async (phoneNumber, pairCode) => {
371
+ if (pairCode) {
372
+ authState.creds.pairingCode = pairCode.substring(0, 8).toUpperCase();
373
+ }
374
+ else {
375
+ authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
355
376
  }
356
- authState.creds.pairingCode = pairingCode;
357
377
  authState.creds.me = {
358
- id: jidEncode(phoneNumber, 's.whatsapp.net'),
378
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
359
379
  name: '~'
360
380
  };
361
381
  ev.emit('creds.update', authState.creds);
362
382
  await sendNode({
363
383
  tag: 'iq',
364
384
  attrs: {
365
- to: S_WHATSAPP_NET,
385
+ to: WABinary_1.S_WHATSAPP_NET,
366
386
  type: 'set',
367
387
  id: generateMessageTag(),
368
388
  xmlns: 'md'
@@ -373,6 +393,7 @@ export const makeSocket = (config) => {
373
393
  attrs: {
374
394
  jid: authState.creds.me.id,
375
395
  stage: 'companion_hello',
396
+ // eslint-disable-next-line camelcase
376
397
  should_show_push_notification: 'true'
377
398
  },
378
399
  content: [
@@ -389,7 +410,7 @@ export const makeSocket = (config) => {
389
410
  {
390
411
  tag: 'companion_platform_id',
391
412
  attrs: {},
392
- content: getPlatformId(browser[1])
413
+ content: (0, Utils_1.getPlatformId)(browser[1])
393
414
  },
394
415
  {
395
416
  tag: 'companion_platform_display',
@@ -408,17 +429,17 @@ export const makeSocket = (config) => {
408
429
  return authState.creds.pairingCode;
409
430
  };
410
431
  async function generatePairingKey() {
411
- const salt = randomBytes(32);
412
- const randomIv = randomBytes(16);
413
- const key = await derivePairingCodeKey(authState.creds.pairingCode, salt);
414
- const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
432
+ const salt = (0, crypto_1.randomBytes)(32);
433
+ const randomIv = (0, crypto_1.randomBytes)(16);
434
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
435
+ const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
415
436
  return Buffer.concat([salt, randomIv, ciphered]);
416
437
  }
417
438
  const sendWAMBuffer = (wamBuffer) => {
418
439
  return query({
419
440
  tag: 'iq',
420
441
  attrs: {
421
- to: S_WHATSAPP_NET,
442
+ to: WABinary_1.S_WHATSAPP_NET,
422
443
  id: generateMessageTag(),
423
444
  xmlns: 'w:stats'
424
445
  },
@@ -442,22 +463,22 @@ export const makeSocket = (config) => {
442
463
  }
443
464
  });
444
465
  ws.on('error', mapWebSocketError(end));
445
- ws.on('close', () => end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
466
+ ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
446
467
  // the server terminated the connection
447
- ws.on('CB:xmlstreamend', () => end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
468
+ ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
448
469
  // QR gen
449
470
  ws.on('CB:iq,type:set,pair-device', async (stanza) => {
450
471
  const iq = {
451
472
  tag: 'iq',
452
473
  attrs: {
453
- to: S_WHATSAPP_NET,
474
+ to: WABinary_1.S_WHATSAPP_NET,
454
475
  type: 'result',
455
- id: stanza.attrs.id
476
+ id: stanza.attrs.id,
456
477
  }
457
478
  };
458
479
  await sendNode(iq);
459
- const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
460
- const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
480
+ const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
481
+ const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
461
482
  const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
462
483
  const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
463
484
  const advB64 = creds.advSecretKey;
@@ -468,7 +489,7 @@ export const makeSocket = (config) => {
468
489
  }
469
490
  const refNode = refNodes.shift();
470
491
  if (!refNode) {
471
- end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
492
+ end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
472
493
  return;
473
494
  }
474
495
  const ref = refNode.content.toString('utf-8');
@@ -484,7 +505,7 @@ export const makeSocket = (config) => {
484
505
  ws.on('CB:iq,,pair-success', async (stanza) => {
485
506
  logger.debug('pair success recv');
486
507
  try {
487
- const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
508
+ const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
488
509
  logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
489
510
  ev.emit('creds.update', updatedCreds);
490
511
  ev.emit('connection.update', { isNewLogin: true, qr: undefined });
@@ -497,25 +518,31 @@ export const makeSocket = (config) => {
497
518
  });
498
519
  // login complete
499
520
  ws.on('CB:success', async (node) => {
500
- await uploadPreKeysToServerIfRequired();
501
- await sendPassiveIq('active');
502
- logger.info('opened connection to WA');
503
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
504
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
505
- ev.emit('connection.update', { connection: 'open' });
521
+ try {
522
+ await uploadPreKeysToServerIfRequired();
523
+ await sendPassiveIq('active');
524
+ logger.info('opened connection to WA');
525
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
526
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
527
+ ev.emit('connection.update', { connection: 'open' });
528
+ }
529
+ catch (err) {
530
+ logger.error({ err }, 'error opening connection');
531
+ end(err);
532
+ }
506
533
  });
507
534
  ws.on('CB:stream:error', (node) => {
508
535
  logger.error({ node }, 'stream errored out');
509
- const { reason, statusCode } = getErrorCodeFromStreamError(node);
510
- end(new Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
536
+ const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
537
+ end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
511
538
  });
512
539
  // stream fail, possible logout
513
540
  ws.on('CB:failure', (node) => {
514
541
  const reason = +(node.attrs.reason || 500);
515
- end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
542
+ end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
516
543
  });
517
544
  ws.on('CB:ib,,downgrade_webclient', () => {
518
- end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }));
545
+ end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
519
546
  });
520
547
  ws.on('CB:ib,,offline_preview', (node) => {
521
548
  logger.info('offline preview received', JSON.stringify(node));
@@ -526,16 +553,17 @@ export const makeSocket = (config) => {
526
553
  });
527
554
  });
528
555
  ws.on('CB:ib,,edge_routing', (node) => {
529
- const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing');
530
- const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info');
531
- if (routingInfo?.content) {
532
- authState.creds.routingInfo = Buffer.from(routingInfo?.content);
556
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
557
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
558
+ if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
559
+ authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
533
560
  ev.emit('creds.update', authState.creds);
534
561
  }
535
562
  });
536
563
  let didStartBuffer = false;
537
564
  process.nextTick(() => {
538
- if (creds.me?.id) {
565
+ var _a;
566
+ if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
539
567
  // start buffering important events
540
568
  // if we're logged in
541
569
  ev.buffer();
@@ -545,8 +573,8 @@ export const makeSocket = (config) => {
545
573
  });
546
574
  // called when all offline notifs are handled
547
575
  ws.on('CB:ib,,offline', (node) => {
548
- const child = getBinaryNodeChild(node, 'offline');
549
- const offlineNotifs = +(child?.attrs.count || 0);
576
+ const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
577
+ const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
550
578
  logger.info(`handled ${offlineNotifs} offline messages/notifications`);
551
579
  if (didStartBuffer) {
552
580
  ev.flush();
@@ -556,19 +584,24 @@ export const makeSocket = (config) => {
556
584
  });
557
585
  // update credentials when required
558
586
  ev.on('creds.update', update => {
559
- const name = update.me?.name;
587
+ var _a, _b;
588
+ const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
560
589
  // if name has just been received
561
- if (creds.me?.name !== name) {
590
+ if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
562
591
  logger.debug({ name }, 'updated pushName');
563
592
  sendNode({
564
593
  tag: 'presence',
565
594
  attrs: { name: name }
566
- }).catch(err => {
595
+ })
596
+ .catch(err => {
567
597
  logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
568
598
  });
569
599
  }
570
600
  Object.assign(creds, update);
571
601
  });
602
+ if (printQRInTerminal) {
603
+ (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
604
+ }
572
605
  return {
573
606
  type: 'md',
574
607
  ws,
@@ -591,17 +624,17 @@ export const makeSocket = (config) => {
591
624
  uploadPreKeysToServerIfRequired,
592
625
  requestPairingCode,
593
626
  /** Waits for the connection to WA to reach a state */
594
- waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
595
- sendWAMBuffer
627
+ waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
628
+ sendWAMBuffer,
596
629
  };
597
630
  };
631
+ exports.makeSocket = makeSocket;
598
632
  /**
599
633
  * map the websocket error to the right type
600
634
  * so it can be retried by the caller
601
635
  * */
602
636
  function mapWebSocketError(handler) {
603
637
  return (error) => {
604
- handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
638
+ handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
605
639
  };
606
640
  }
607
- //# sourceMappingURL=socket.js.map