amiudmodz 4.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 (100) hide show
  1. package/WAProto/index.js +169661 -0
  2. package/engine-requirements.js +10 -0
  3. package/lib/Defaults/baileys-version.json +3 -0
  4. package/lib/Defaults/index.js +156 -0
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Signal/Group/ciphertext-message.js +15 -0
  7. package/lib/Signal/Group/group-session-builder.js +64 -0
  8. package/lib/Signal/Group/group_cipher.js +96 -0
  9. package/lib/Signal/Group/index.js +57 -0
  10. package/lib/Signal/Group/keyhelper.js +55 -0
  11. package/lib/Signal/Group/queue-job.js +57 -0
  12. package/lib/Signal/Group/sender-chain-key.js +34 -0
  13. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  14. package/lib/Signal/Group/sender-key-message.js +69 -0
  15. package/lib/Signal/Group/sender-key-name.js +51 -0
  16. package/lib/Signal/Group/sender-key-record.js +53 -0
  17. package/lib/Signal/Group/sender-key-state.js +99 -0
  18. package/lib/Signal/Group/sender-message-key.js +29 -0
  19. package/lib/Signal/libsignal.js +177 -0
  20. package/lib/Signal/lid-mapping.js +185 -0
  21. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  22. package/lib/Socket/Client/index.js +19 -0
  23. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  24. package/lib/Socket/Client/web-socket-client.js +66 -0
  25. package/lib/Socket/business.js +260 -0
  26. package/lib/Socket/chats.js +1066 -0
  27. package/lib/Socket/groupStatus.js +637 -0
  28. package/lib/Socket/groups.js +317 -0
  29. package/lib/Socket/index.js +11 -0
  30. package/lib/Socket/messages-recv.js +1112 -0
  31. package/lib/Socket/messages-send.js +807 -0
  32. package/lib/Socket/newsletter.js +73 -0
  33. package/lib/Socket/registration.js +166 -0
  34. package/lib/Socket/socket.js +729 -0
  35. package/lib/Socket/usync.js +70 -0
  36. package/lib/Store/index.js +10 -0
  37. package/lib/Store/make-cache-manager-store.js +83 -0
  38. package/lib/Store/make-in-memory-store.js +427 -0
  39. package/lib/Store/make-ordered-dictionary.js +81 -0
  40. package/lib/Store/object-repository.js +27 -0
  41. package/lib/Types/Auth.js +2 -0
  42. package/lib/Types/Call.js +2 -0
  43. package/lib/Types/Chat.js +4 -0
  44. package/lib/Types/Contact.js +2 -0
  45. package/lib/Types/Events.js +2 -0
  46. package/lib/Types/GroupMetadata.js +2 -0
  47. package/lib/Types/Label.js +27 -0
  48. package/lib/Types/LabelAssociation.js +9 -0
  49. package/lib/Types/Message.js +9 -0
  50. package/lib/Types/Newsletter.js +38 -0
  51. package/lib/Types/Product.js +2 -0
  52. package/lib/Types/Signal.js +2 -0
  53. package/lib/Types/Socket.js +2 -0
  54. package/lib/Types/State.js +2 -0
  55. package/lib/Types/USync.js +2 -0
  56. package/lib/Types/index.js +42 -0
  57. package/lib/Utils/auth-utils.js +206 -0
  58. package/lib/Utils/baileys-event-stream.js +63 -0
  59. package/lib/Utils/business.js +234 -0
  60. package/lib/Utils/chat-utils.js +729 -0
  61. package/lib/Utils/crypto.js +151 -0
  62. package/lib/Utils/decode-wa-message.js +198 -0
  63. package/lib/Utils/event-buffer.js +525 -0
  64. package/lib/Utils/generics.js +502 -0
  65. package/lib/Utils/history.js +96 -0
  66. package/lib/Utils/index.js +33 -0
  67. package/lib/Utils/link-preview.js +93 -0
  68. package/lib/Utils/logger.js +7 -0
  69. package/lib/Utils/lt-hash.js +51 -0
  70. package/lib/Utils/make-mutex.js +43 -0
  71. package/lib/Utils/messages-media.js +814 -0
  72. package/lib/Utils/messages.js +819 -0
  73. package/lib/Utils/noise-handler.js +155 -0
  74. package/lib/Utils/process-message.js +321 -0
  75. package/lib/Utils/signal.js +153 -0
  76. package/lib/Utils/use-multi-file-auth-state.js +126 -0
  77. package/lib/Utils/validate-connection.js +222 -0
  78. package/lib/WABinary/constants.js +1304 -0
  79. package/lib/WABinary/decode.js +283 -0
  80. package/lib/WABinary/encode.js +263 -0
  81. package/lib/WABinary/generic-utils.js +198 -0
  82. package/lib/WABinary/index.js +21 -0
  83. package/lib/WABinary/jid-utils.js +62 -0
  84. package/lib/WABinary/types.js +2 -0
  85. package/lib/WAM/BinaryInfo.js +13 -0
  86. package/lib/WAM/constants.js +15350 -0
  87. package/lib/WAM/encode.js +155 -0
  88. package/lib/WAM/index.js +19 -0
  89. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  90. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  91. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  92. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  93. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  94. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  95. package/lib/WAUSync/Protocols/index.js +20 -0
  96. package/lib/WAUSync/USyncQuery.js +89 -0
  97. package/lib/WAUSync/USyncUser.js +26 -0
  98. package/lib/WAUSync/index.js +19 -0
  99. package/lib/index.js +39 -0
  100. package/package.json +93 -0
@@ -0,0 +1,729 @@
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', {
26
+ statusCode: Types_1.DisconnectReason.loggedOut
27
+ });
28
+ }
29
+ if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
30
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
31
+ }
32
+ const ws = new Client_1.WebSocketClient(url, config);
33
+ ws.connect();
34
+ const ev = (0, Utils_1.makeEventBuffer)(logger);
35
+ /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
36
+ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
37
+ /** WA noise protocol wrapper */
38
+ const noise = (0, Utils_1.makeNoiseHandler)({
39
+ keyPair: ephemeralKeyPair,
40
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
41
+ logger,
42
+ routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
43
+ });
44
+ const { creds } = authState;
45
+
46
+ const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
47
+ const signalRepository = makeSignalRepository({ creds, keys });
48
+ let lastDateRecv;
49
+ let epoch = 1;
50
+ let keepAliveReq;
51
+ let qrTimer;
52
+ let closed = false;
53
+ const uqTagId = (0, Utils_1.generateMdTagPrefix)();
54
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
55
+ const sendPromise = (0, util_1.promisify)(ws.send);
56
+ /** send a raw buffer */
57
+ const sendRawMessage = async (data) => {
58
+ if (!ws.isOpen) {
59
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
60
+ }
61
+ const bytes = noise.encodeFrame(data);
62
+ await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
63
+ try {
64
+ await sendPromise.call(ws, bytes);
65
+ resolve();
66
+ }
67
+ catch (error) {
68
+ reject(error);
69
+ }
70
+ });
71
+ };
72
+ /** send a binary node */
73
+ const sendNode = (frame) => {
74
+ if (logger.level === 'trace') {
75
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
76
+ }
77
+ const buff = (0, WABinary_1.encodeBinaryNode)(frame);
78
+ return sendRawMessage(buff);
79
+ };
80
+ /** log & process any unexpected errors */
81
+ const onUnexpectedError = (err, msg) => {
82
+ logger.error({ err }, `unexpected error in '${msg}'`);
83
+ const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
84
+ if (message.includes('bad mac') || (message.includes('mac') && message.includes('invalid'))) {
85
+ try {
86
+ uploadPreKeys()
87
+ .catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
88
+ }
89
+ catch (_e) {
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);
135
+ ws.on('error', onErr);
136
+ });
137
+ return result;
138
+ }
139
+ finally {
140
+ ws.off(`TAG:${msgId}`, onRecv);
141
+ ws.off('close', onErr);
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
+ let uploadPreKeysPromise = null;
208
+ let lastUploadTime = 0;
209
+ const uploadPreKeys = async (count = Defaults_1.MIN_PREKEY_COUNT, retryCount = 0) => {
210
+ if (retryCount === 0) {
211
+ const timeSinceLastUpload = Date.now() - lastUploadTime;
212
+ if (timeSinceLastUpload < Defaults_1.MIN_UPLOAD_INTERVAL) {
213
+ logger.debug(`Skipping upload, only ${timeSinceLastUpload}ms since last upload`);
214
+ return;
215
+ }
216
+ }
217
+ if (uploadPreKeysPromise) {
218
+ logger.debug('Pre-key upload already in progress, waiting for completion');
219
+ await uploadPreKeysPromise;
220
+ }
221
+ const uploadLogic = async () => {
222
+ logger.info({ count, retryCount }, 'uploading pre-keys');
223
+ const node = await keys.transaction(async () => {
224
+ const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
225
+ ev.emit('creds.update', update);
226
+ return node;
227
+ });
228
+ try {
229
+ await query(node);
230
+ logger.info({ count }, 'uploaded pre-keys');
231
+ lastUploadTime = Date.now();
232
+ } catch (uploadError) {
233
+ logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
234
+ if (retryCount < 3) {
235
+ const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
236
+ logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
237
+ await new Promise(resolve => setTimeout(resolve, backoffDelay));
238
+ return uploadPreKeys(count, retryCount + 1);
239
+ }
240
+ throw uploadError;
241
+ }
242
+ };
243
+ uploadPreKeysPromise = Promise.race([
244
+ uploadLogic(),
245
+ new Promise((_, reject) =>
246
+ setTimeout(() => reject(new boom_1.Boom('Pre-key upload timeout', { statusCode: 408 })), Defaults_1.UPLOAD_TIMEOUT)
247
+ )
248
+ ]);
249
+ try {
250
+ await uploadPreKeysPromise;
251
+ } finally {
252
+ uploadPreKeysPromise = null;
253
+ }
254
+ };
255
+ const uploadPreKeysToServerIfRequired = async () => {
256
+ try {
257
+ const preKeyCount = await getAvailablePreKeysOnServer();
258
+ const count = preKeyCount === 0 ? Defaults_1.INITIAL_PREKEY_COUNT : Defaults_1.MIN_PREKEY_COUNT;
259
+ logger.info(`${preKeyCount} pre-keys found on server`);
260
+ if (preKeyCount <= count) {
261
+ await uploadPreKeys(count);
262
+ }
263
+ } catch (error) {
264
+ logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
265
+ }
266
+ };
267
+ const onMessageReceived = (data) => {
268
+ noise.decodeFrame(data, frame => {
269
+ var _a;
270
+
271
+ lastDateRecv = new Date();
272
+ let anyTriggered = false;
273
+ anyTriggered = ws.emit('frame', frame);
274
+
275
+ if (!(frame instanceof Uint8Array)) {
276
+ const msgId = frame.attrs.id;
277
+ if (logger.level === 'trace') {
278
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
279
+ }
280
+ /* Check if this is a response to a message we sent */
281
+ anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
282
+ /* Check if this is a response to a message we are expecting */
283
+ const l0 = frame.tag;
284
+ const l1 = frame.attrs || {};
285
+ const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
286
+ for (const key of Object.keys(l1)) {
287
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
288
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
289
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
290
+ }
291
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
292
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
293
+ if (!anyTriggered && logger.level === 'debug') {
294
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
295
+ }
296
+ }
297
+ });
298
+ };
299
+ const end = async (error) => {
300
+ if (closed) {
301
+ logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
302
+ return;
303
+ }
304
+ closed = true;
305
+ logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
306
+ clearInterval(keepAliveReq);
307
+ clearTimeout(qrTimer);
308
+ ws.removeAllListeners('close');
309
+ ws.removeAllListeners('error');
310
+ ws.removeAllListeners('open');
311
+ ws.removeAllListeners('message');
312
+ if (!ws.isClosed && !ws.isClosing) {
313
+ try {
314
+ await ws.close();
315
+ }
316
+ catch (_a) { }
317
+ }
318
+ ev.emit('connection.update', {
319
+ connection: 'close',
320
+ lastDisconnect: {
321
+ error,
322
+ date: new Date()
323
+ }
324
+ });
325
+ ev.removeAllListeners('connection.update');
326
+ };
327
+ const waitForSocketOpen = async () => {
328
+ if (ws.isOpen) {
329
+ return;
330
+ }
331
+ if (ws.isClosed || ws.isClosing) {
332
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
333
+ }
334
+ let onOpen;
335
+ let onClose;
336
+ await new Promise((resolve, reject) => {
337
+ onOpen = () => resolve(undefined);
338
+ onClose = mapWebSocketError(reject);
339
+ ws.on('open', onOpen);
340
+ ws.on('close', onClose);
341
+ ws.on('error', onClose);
342
+ })
343
+ .finally(() => {
344
+ ws.off('open', onOpen);
345
+ ws.off('close', onClose);
346
+ ws.off('error', onClose);
347
+ });
348
+ };
349
+ const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
350
+ if (!lastDateRecv) {
351
+ lastDateRecv = new Date();
352
+ }
353
+ const diff = Date.now() - lastDateRecv.getTime();
354
+ /*
355
+ check if it's been a suspicious amount of time since the server responded with our last seen
356
+ it could be that the network is down
357
+ */
358
+ if (diff > keepAliveIntervalMs + 5000) {
359
+ void end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
360
+ }
361
+ else if (ws.isOpen) {
362
+
363
+ query({
364
+ tag: 'iq',
365
+ attrs: {
366
+ id: generateMessageTag(),
367
+ to: WABinary_1.S_WHATSAPP_NET,
368
+ type: 'get',
369
+ xmlns: 'w:p',
370
+ },
371
+ content: [{ tag: 'ping', attrs: {} }]
372
+ })
373
+ .catch(err => {
374
+ logger.error({ trace: err.stack }, 'error in sending keep alive');
375
+ });
376
+ }
377
+ }, keepAliveIntervalMs));
378
+ /** i have no idea why this exists. pls enlighten me */
379
+ const sendPassiveIq = (tag) => (query({
380
+ tag: 'iq',
381
+ attrs: {
382
+ to: WABinary_1.S_WHATSAPP_NET,
383
+ xmlns: 'passive',
384
+ type: 'set',
385
+ },
386
+ content: [
387
+ { tag, attrs: {} }
388
+ ]
389
+ }));
390
+ /** logout & invalidate connection */
391
+ const logout = async (msg) => {
392
+ var _a;
393
+ const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
394
+ if (jid) {
395
+ await sendNode({
396
+ tag: 'iq',
397
+ attrs: {
398
+ to: WABinary_1.S_WHATSAPP_NET,
399
+ type: 'set',
400
+ id: generateMessageTag(),
401
+ xmlns: 'md'
402
+ },
403
+ content: [
404
+ {
405
+ tag: 'remove-companion-device',
406
+ attrs: {
407
+ jid,
408
+ reason: 'user_initiated'
409
+ }
410
+ }
411
+ ]
412
+ });
413
+ }
414
+ end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
415
+ };
416
+
417
+ const requestPairingCode = async (phoneNumber, pairKey) => {
418
+ if (pairKey) {
419
+ authState.creds.pairingCode = pairKey.toUpperCase();
420
+ } else {
421
+ authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
422
+ }
423
+
424
+ authState.creds.me = {
425
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
426
+ name: '~'
427
+ };
428
+
429
+ ev.emit('creds.update', authState.creds);
430
+
431
+ await sendNode({
432
+ tag: 'iq',
433
+ attrs: {
434
+ to: WABinary_1.S_WHATSAPP_NET,
435
+ type: 'set',
436
+ id: generateMessageTag(),
437
+ xmlns: 'md'
438
+ },
439
+ content: [
440
+ {
441
+ tag: 'link_code_companion_reg',
442
+ attrs: {
443
+ jid: authState.creds.me.id,
444
+ stage: 'companion_hello',
445
+ should_show_push_notification: 'true'
446
+ },
447
+ content: [
448
+ {
449
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
450
+ attrs: {},
451
+ content: await generatePairingKey()
452
+ },
453
+ {
454
+ tag: 'companion_server_auth_key_pub',
455
+ attrs: {},
456
+ content: authState.creds.noiseKey.public
457
+ },
458
+ {
459
+ tag: 'companion_platform_id',
460
+ attrs: {},
461
+ content: (0, Utils_1.getPlatformId)(browser[1])
462
+ },
463
+ {
464
+ tag: 'companion_platform_display',
465
+ attrs: {},
466
+ content: `${browser[1]} (${browser[0]})`
467
+ },
468
+ {
469
+ tag: 'link_code_pairing_nonce',
470
+ attrs: {},
471
+ content: "0"
472
+ }
473
+ ]
474
+ }
475
+ ]
476
+ });
477
+
478
+ return authState.creds.pairingCode;
479
+ }
480
+ async function generatePairingKey() {
481
+ const salt = (0, crypto_1.randomBytes)(32);
482
+ const randomIv = (0, crypto_1.randomBytes)(16);
483
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
484
+ const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
485
+ return Buffer.concat([salt, randomIv, ciphered]);
486
+ }
487
+ const sendWAMBuffer = (wamBuffer) => {
488
+ return query({
489
+ tag: 'iq',
490
+ attrs: {
491
+ to: WABinary_1.S_WHATSAPP_NET,
492
+ id: generateMessageTag(),
493
+ xmlns: 'w:stats'
494
+ },
495
+ content: [
496
+ {
497
+ tag: 'add',
498
+ attrs: {},
499
+ content: wamBuffer
500
+ }
501
+ ]
502
+ });
503
+ };
504
+ let serverTimeOffsetMs = 0;
505
+ const updateServerTimeOffset = ({ attrs }) => {
506
+ const tValue = attrs && attrs.t;
507
+ if (!tValue) return;
508
+ const parsed = Number(tValue);
509
+ if (Number.isNaN(parsed) || parsed <= 0) return;
510
+ const localMs = Date.now();
511
+ serverTimeOffsetMs = parsed * 1000 - localMs;
512
+ logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
513
+ };
514
+ const getUnifiedSessionId = () => {
515
+ const offsetMs = 3 * Defaults_1.TimeMs.Day;
516
+ const now = Date.now() + serverTimeOffsetMs;
517
+ const id = (now + offsetMs) % Defaults_1.TimeMs.Week;
518
+ return id.toString();
519
+ };
520
+ const sendUnifiedSession = async () => {
521
+ if (!ws.isOpen) return;
522
+ const node = {
523
+ tag: 'ib',
524
+ attrs: {},
525
+ content: [{ tag: 'unified_session', attrs: { id: getUnifiedSessionId() } }]
526
+ };
527
+ try {
528
+ await sendNode(node);
529
+ } catch (error) {
530
+ logger.debug({ error }, 'failed to send unified_session telemetry');
531
+ }
532
+ };
533
+ ws.on('message', onMessageReceived);
534
+ ws.on('open', async () => {
535
+ try {
536
+ await validateConnection();
537
+ }
538
+ catch (err) {
539
+ logger.error({ err }, 'error in validating connection');
540
+ end(err);
541
+ }
542
+ });
543
+ ws.on('error', mapWebSocketError(end));
544
+ ws.on('close', () => void end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
545
+ ws.on('CB:xmlstreamend', () => void end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
546
+
547
+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {
548
+ const iq = {
549
+ tag: 'iq',
550
+ attrs: {
551
+ to: WABinary_1.S_WHATSAPP_NET,
552
+ type: 'result',
553
+ id: stanza.attrs.id,
554
+ }
555
+ };
556
+ await sendNode(iq);
557
+ const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
558
+ const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
559
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
560
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
561
+ const advB64 = creds.advSecretKey;
562
+ let qrMs = qrTimeout || 60000;
563
+ const genPairQR = () => {
564
+ if (!ws.isOpen) {
565
+ return;
566
+ }
567
+ const refNode = refNodes.shift();
568
+ if (!refNode) {
569
+ void end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
570
+ return;
571
+ }
572
+ const ref = refNode.content.toString('utf-8');
573
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
574
+ ev.emit('connection.update', { qr });
575
+ qrTimer = setTimeout(genPairQR, qrMs);
576
+ qrMs = qrTimeout || 20000;
577
+ };
578
+ genPairQR();
579
+ });
580
+
581
+
582
+ ws.on('CB:iq,,pair-success', async (stanza) => {
583
+ logger.debug('pair success recv');
584
+ try {
585
+ updateServerTimeOffset(stanza);
586
+ const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
587
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
588
+ ev.emit('creds.update', updatedCreds);
589
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined });
590
+ await sendNode(reply);
591
+ void sendUnifiedSession();
592
+ }
593
+ catch (error) {
594
+ logger.info({ trace: error.stack }, 'error in pairing');
595
+ void end(error);
596
+ }
597
+ });
598
+ ws.on('CB:success', async (node) => {
599
+ try {
600
+ updateServerTimeOffset(node);
601
+ await uploadPreKeysToServerIfRequired();
602
+ await sendPassiveIq('active');
603
+ } catch (err) {
604
+ logger.warn({ err }, 'failed to send initial passive iq');
605
+ }
606
+ logger.info('opened connection to WA');
607
+ clearTimeout(qrTimer);
608
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
609
+ ev.emit('connection.update', { connection: 'open' });
610
+ void sendUnifiedSession();
611
+ });
612
+ ws.on('CB:stream:error', (node) => {
613
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
614
+ logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out');
615
+ const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
616
+ void end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }));
617
+ });
618
+ ws.on('CB:failure', (node) => {
619
+ const reason = +(node.attrs.reason || 500);
620
+ void end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
621
+ });
622
+ ws.on('CB:ib,,downgrade_webclient', () => {
623
+ void end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
624
+ });
625
+ ws.on('CB:ib,,offline_preview', (node) => {
626
+ logger.info('offline preview received', JSON.stringify(node));
627
+ sendNode({
628
+ tag: 'ib',
629
+ attrs: {},
630
+ content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
631
+ });
632
+ });
633
+ ws.on('CB:ib,,edge_routing', (node) => {
634
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
635
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
636
+ if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
637
+ authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
638
+ ev.emit('creds.update', authState.creds);
639
+ }
640
+ });
641
+ let didStartBuffer = false;
642
+ process.nextTick(() => {
643
+ var _a;
644
+ if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
645
+
646
+
647
+ ev.buffer();
648
+ didStartBuffer = true;
649
+ }
650
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
651
+ });
652
+
653
+ ws.on('CB:ib,,offline', (node) => {
654
+ const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
655
+ const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
656
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`);
657
+ if (didStartBuffer) {
658
+ ev.flush();
659
+ logger.trace('flushed events for initial buffer');
660
+ }
661
+ ev.emit('connection.update', { receivedPendingNotifications: true });
662
+ });
663
+
664
+ ev.on('creds.update', update => {
665
+ var _a, _b;
666
+ const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
667
+
668
+ if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
669
+ logger.debug({ name }, 'updated pushName');
670
+ sendNode({
671
+ tag: 'presence',
672
+ attrs: { name: name }
673
+ })
674
+ .catch(err => {
675
+ logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
676
+ });
677
+ }
678
+ Object.assign(creds, update);
679
+ });
680
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
681
+ try {
682
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
683
+ } catch (error) {
684
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
685
+ }
686
+ });
687
+ if (printQRInTerminal) {
688
+ (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
689
+ }
690
+ return {
691
+ type: 'md',
692
+ ws,
693
+ ev,
694
+ authState: {
695
+ creds,
696
+ keys
697
+ },
698
+ signalRepository,
699
+ get user() {
700
+ return authState.creds.me;
701
+ },
702
+ generateMessageTag,
703
+ query,
704
+ waitForMessage,
705
+ waitForSocketOpen,
706
+ sendRawMessage,
707
+ sendNode,
708
+ logout,
709
+ end,
710
+ onUnexpectedError,
711
+ uploadPreKeys,
712
+ uploadPreKeysToServerIfRequired,
713
+ requestPairingCode,
714
+ updateServerTimeOffset,
715
+ sendUnifiedSession,
716
+ waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
717
+ sendWAMBuffer,
718
+ };
719
+ };
720
+ exports.makeSocket = makeSocket;
721
+ /**
722
+ * map the websocket error to the right type
723
+ * so it can be retried by the caller
724
+ * */
725
+ function mapWebSocketError(handler) {
726
+ return (error) => {
727
+ handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
728
+ };
729
+ }