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