@sanzoffc/baileys 3.0.1

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