@d0v3riz/baileys 6.7.18 → 6.7.20

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 (114) hide show
  1. package/README.md +1263 -4
  2. package/WAProto/GenerateStatics.sh +2 -0
  3. package/WAProto/WAProto.proto +4633 -0
  4. package/WAProto/index.d.ts +3212 -122
  5. package/WAProto/index.js +9635 -299
  6. package/lib/Defaults/baileys-version.json +1 -1
  7. package/lib/Defaults/index.d.ts +1 -1
  8. package/lib/Defaults/index.js +16 -16
  9. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  12. package/lib/Signal/Group/group-session-builder.js +64 -0
  13. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.d.ts +11 -0
  16. package/lib/Signal/Group/index.js +57 -0
  17. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  18. package/lib/Signal/Group/keyhelper.js +55 -0
  19. package/lib/Signal/Group/queue-job.d.ts +1 -0
  20. package/lib/Signal/Group/queue-job.js +57 -0
  21. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  22. package/lib/Signal/Group/sender-chain-key.js +34 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  24. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  25. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  26. package/lib/Signal/Group/sender-key-message.js +69 -0
  27. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  28. package/lib/Signal/Group/sender-key-name.js +51 -0
  29. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  30. package/lib/Signal/Group/sender-key-record.js +53 -0
  31. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  32. package/lib/Signal/Group/sender-key-state.js +99 -0
  33. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  34. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +29 -39
  35. package/lib/Signal/libsignal.js +33 -20
  36. package/lib/Socket/Client/websocket.js +1 -1
  37. package/lib/Socket/business.d.ts +5 -5
  38. package/lib/Socket/business.js +5 -5
  39. package/lib/Socket/chats.d.ts +4 -4
  40. package/lib/Socket/chats.js +70 -70
  41. package/lib/Socket/groups.d.ts +6 -6
  42. package/lib/Socket/groups.js +39 -24
  43. package/lib/Socket/index.d.ts +5 -5
  44. package/lib/Socket/index.js +2 -2
  45. package/lib/Socket/messages-recv.d.ts +5 -5
  46. package/lib/Socket/messages-recv.js +73 -56
  47. package/lib/Socket/messages-send.d.ts +5 -5
  48. package/lib/Socket/messages-send.js +53 -46
  49. package/lib/Socket/socket.d.ts +3 -3
  50. package/lib/Socket/socket.js +22 -29
  51. package/lib/Socket/usync.d.ts +3 -3
  52. package/lib/Socket/usync.js +10 -15
  53. package/lib/Types/Auth.d.ts +1 -1
  54. package/lib/Types/Chat.d.ts +1 -1
  55. package/lib/Types/Chat.js +7 -1
  56. package/lib/Types/Contact.d.ts +4 -0
  57. package/lib/Types/Events.d.ts +1 -1
  58. package/lib/Types/GroupMetadata.d.ts +7 -3
  59. package/lib/Types/Message.d.ts +7 -2
  60. package/lib/Types/Socket.d.ts +3 -3
  61. package/lib/Utils/auth-utils.js +8 -9
  62. package/lib/Utils/baileys-event-stream.js +1 -1
  63. package/lib/Utils/business.js +17 -11
  64. package/lib/Utils/chat-utils.d.ts +4 -4
  65. package/lib/Utils/chat-utils.js +64 -69
  66. package/lib/Utils/crypto.js +4 -10
  67. package/lib/Utils/decode-wa-message.js +6 -2
  68. package/lib/Utils/event-buffer.d.ts +2 -2
  69. package/lib/Utils/event-buffer.js +9 -13
  70. package/lib/Utils/generics.d.ts +1 -1
  71. package/lib/Utils/generics.js +28 -30
  72. package/lib/Utils/history.js +10 -5
  73. package/lib/Utils/link-preview.js +5 -9
  74. package/lib/Utils/lt-hash.js +2 -2
  75. package/lib/Utils/make-mutex.js +1 -1
  76. package/lib/Utils/messages-media.d.ts +2 -3
  77. package/lib/Utils/messages-media.js +80 -95
  78. package/lib/Utils/messages.d.ts +1 -1
  79. package/lib/Utils/messages.js +83 -75
  80. package/lib/Utils/process-message.d.ts +1 -1
  81. package/lib/Utils/process-message.js +25 -30
  82. package/lib/Utils/signal.js +9 -7
  83. package/lib/Utils/use-multi-file-auth-state.js +2 -3
  84. package/lib/Utils/validate-connection.js +17 -22
  85. package/lib/WABinary/constants.d.ts +4 -4
  86. package/lib/WABinary/constants.js +1271 -8
  87. package/lib/WABinary/decode.js +2 -1
  88. package/lib/WABinary/encode.js +2 -2
  89. package/lib/WABinary/generic-utils.js +1 -1
  90. package/lib/WABinary/jid-utils.js +8 -11
  91. package/lib/WAM/constants.js +2252 -2359
  92. package/lib/WAM/encode.js +5 -7
  93. package/lib/WAUSync/Protocols/USyncContactProtocol.js +2 -2
  94. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +2 -2
  95. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +2 -2
  96. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +5 -5
  97. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +1 -1
  98. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +1 -1
  99. package/lib/WAUSync/USyncQuery.js +17 -13
  100. package/package.json +11 -6
  101. package/WASignalGroup/GroupProtocol.js +0 -1697
  102. package/WASignalGroup/ciphertext_message.js +0 -16
  103. package/WASignalGroup/group_cipher.js +0 -120
  104. package/WASignalGroup/group_session_builder.js +0 -46
  105. package/WASignalGroup/index.js +0 -5
  106. package/WASignalGroup/keyhelper.js +0 -21
  107. package/WASignalGroup/protobufs.js +0 -3
  108. package/WASignalGroup/queue_job.js +0 -69
  109. package/WASignalGroup/sender_chain_key.js +0 -50
  110. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  111. package/WASignalGroup/sender_key_message.js +0 -92
  112. package/WASignalGroup/sender_key_name.js +0 -70
  113. package/WASignalGroup/sender_key_record.js +0 -56
  114. package/WASignalGroup/sender_key_state.js +0 -129
@@ -14,24 +14,25 @@ const WABinary_1 = require("../WABinary");
14
14
  const WAUSync_1 = require("../WAUSync");
15
15
  const groups_1 = require("./groups");
16
16
  const makeMessagesSocket = (config) => {
17
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config;
17
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata } = config;
18
18
  const sock = (0, groups_1.makeGroupsSocket)(config);
19
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
20
- const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
21
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
22
- useClones: false
23
- });
19
+ const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral } = sock;
20
+ const userDevicesCache = config.userDevicesCache ||
21
+ new node_cache_1.default({
22
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
23
+ useClones: false
24
+ });
24
25
  let mediaConn;
25
26
  const refreshMediaConn = async (forceGet = false) => {
26
27
  const media = await mediaConn;
27
- if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
28
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
28
29
  mediaConn = (async () => {
29
30
  const result = await query({
30
31
  tag: 'iq',
31
32
  attrs: {
32
33
  type: 'set',
33
34
  xmlns: 'w:m',
34
- to: WABinary_1.S_WHATSAPP_NET,
35
+ to: WABinary_1.S_WHATSAPP_NET
35
36
  },
36
37
  content: [{ tag: 'media_conn', attrs: {} }]
37
38
  });
@@ -39,7 +40,7 @@ const makeMessagesSocket = (config) => {
39
40
  const node = {
40
41
  hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
41
42
  hostname: attrs.hostname,
42
- maxContentLengthBytes: +attrs.maxContentLengthBytes,
43
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
43
44
  })),
44
45
  auth: mediaConnNode.attrs.auth,
45
46
  ttl: +mediaConnNode.attrs.ttl,
@@ -59,8 +60,8 @@ const makeMessagesSocket = (config) => {
59
60
  const node = {
60
61
  tag: 'receipt',
61
62
  attrs: {
62
- id: messageIds[0],
63
- },
63
+ id: messageIds[0]
64
+ }
64
65
  };
65
66
  const isReadReceipt = type === 'read' || type === 'read-self';
66
67
  if (isReadReceipt) {
@@ -138,9 +139,7 @@ const makeMessagesSocket = (config) => {
138
139
  if (!toFetch.length) {
139
140
  return deviceResults;
140
141
  }
141
- const query = new WAUSync_1.USyncQuery()
142
- .withContext('message')
143
- .withDeviceProtocol();
142
+ const query = new WAUSync_1.USyncQuery().withContext('message').withDeviceProtocol();
144
143
  for (const jid of toFetch) {
145
144
  query.withUser(new WAUSync_1.USyncUser().withId(jid));
146
145
  }
@@ -166,12 +165,10 @@ const makeMessagesSocket = (config) => {
166
165
  jidsRequiringFetch = jids;
167
166
  }
168
167
  else {
169
- const addrs = jids.map(jid => (signalRepository
170
- .jidToSignalProtocolAddress(jid)));
168
+ const addrs = jids.map(jid => signalRepository.jidToSignalProtocolAddress(jid));
171
169
  const sessions = await authState.keys.get('session', addrs);
172
170
  for (const jid of jids) {
173
- const signalId = signalRepository
174
- .jidToSignalProtocolAddress(jid);
171
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
175
172
  if (!sessions[signalId]) {
176
173
  jidsRequiringFetch.push(jid);
177
174
  }
@@ -184,7 +181,7 @@ const makeMessagesSocket = (config) => {
184
181
  attrs: {
185
182
  xmlns: 'encrypt',
186
183
  type: 'get',
187
- to: WABinary_1.S_WHATSAPP_NET,
184
+ to: WABinary_1.S_WHATSAPP_NET
188
185
  },
189
186
  content: [
190
187
  {
@@ -192,7 +189,7 @@ const makeMessagesSocket = (config) => {
192
189
  attrs: {},
193
190
  content: jidsRequiringFetch.map(jid => ({
194
191
  tag: 'user',
195
- attrs: { jid },
192
+ attrs: { jid }
196
193
  }))
197
194
  }
198
195
  ]
@@ -219,8 +216,8 @@ const makeMessagesSocket = (config) => {
219
216
  additionalAttributes: {
220
217
  category: 'peer',
221
218
  // eslint-disable-next-line camelcase
222
- push_priority: 'high_force',
223
- },
219
+ push_priority: 'high_force'
220
+ }
224
221
  });
225
222
  return msgId;
226
223
  };
@@ -236,23 +233,24 @@ const makeMessagesSocket = (config) => {
236
233
  return {};
237
234
  }
238
235
  const bytes = (0, Utils_1.encodeWAMessage)(patchedMessage);
239
- const { type, ciphertext } = await signalRepository
240
- .encryptMessage({ jid, data: bytes });
236
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
241
237
  if (type === 'pkmsg') {
242
238
  shouldIncludeDeviceIdentity = true;
243
239
  }
244
240
  const node = {
245
241
  tag: 'to',
246
242
  attrs: { jid },
247
- content: [{
243
+ content: [
244
+ {
248
245
  tag: 'enc',
249
246
  attrs: {
250
247
  v: '2',
251
248
  type,
252
- ...extraAttrs || {}
249
+ ...(extraAttrs || {})
253
250
  },
254
251
  content: ciphertext
255
- }]
252
+ }
253
+ ]
256
254
  };
257
255
  return node;
258
256
  }));
@@ -271,7 +269,7 @@ const makeMessagesSocket = (config) => {
271
269
  useUserDevicesCache = useUserDevicesCache !== false;
272
270
  useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
273
271
  const participants = [];
274
- const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : 's.whatsapp.net') : statusJid;
272
+ const destinationJid = !isStatus ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : 's.whatsapp.net') : statusJid;
275
273
  const binaryNodeContent = [];
276
274
  const devices = [];
277
275
  const meMsg = {
@@ -286,7 +284,7 @@ const makeMessagesSocket = (config) => {
286
284
  // only send to the specific device that asked for a retry
287
285
  // otherwise the message is sent out to every device that should be a recipient
288
286
  if (!isGroup && !isStatus) {
289
- additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
287
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
290
288
  }
291
289
  const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
292
290
  devices.push({ user, device });
@@ -321,7 +319,7 @@ const makeMessagesSocket = (config) => {
321
319
  })()
322
320
  ]);
323
321
  if (!participant) {
324
- const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
322
+ const participantsList = groupData && !isStatus ? groupData.participants.map(p => p.id) : [];
325
323
  if (isStatus && statusJidList) {
326
324
  participantsList.push(...statusJidList);
327
325
  }
@@ -342,7 +340,7 @@ const makeMessagesSocket = (config) => {
342
340
  const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
343
341
  group: destinationJid,
344
342
  data: bytes,
345
- meId,
343
+ meId
346
344
  });
347
345
  const senderKeyJids = [];
348
346
  // ensure a connection is established with every device
@@ -455,6 +453,7 @@ const makeMessagesSocket = (config) => {
455
453
  stanza.attrs.to = destinationJid;
456
454
  }
457
455
  if (shouldIncludeDeviceIdentity) {
456
+ ;
458
457
  stanza.content.push({
459
458
  tag: 'device-identity',
460
459
  attrs: {},
@@ -463,6 +462,7 @@ const makeMessagesSocket = (config) => {
463
462
  logger.debug({ jid }, 'adding device identity');
464
463
  }
465
464
  if (additionalNodes && additionalNodes.length > 0) {
465
+ ;
466
466
  stanza.content.push(...additionalNodes);
467
467
  }
468
468
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
@@ -584,7 +584,10 @@ const makeMessagesSocket = (config) => {
584
584
  const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
585
585
  if (media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
586
586
  const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
587
- throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
587
+ throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, {
588
+ data: media,
589
+ statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404
590
+ });
588
591
  }
589
592
  content.directPath = media.directPath;
590
593
  content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
@@ -601,9 +604,7 @@ const makeMessagesSocket = (config) => {
601
604
  if (error) {
602
605
  throw error;
603
606
  }
604
- ev.emit('messages.update', [
605
- { key: message.key, update: { message: message.message } }
606
- ]);
607
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
607
608
  return message;
608
609
  },
609
610
  sendMessage: async (jid, content, options = {}) => {
@@ -614,9 +615,11 @@ const makeMessagesSocket = (config) => {
614
615
  typeof content['disappearingMessagesInChat'] !== 'undefined' &&
615
616
  (0, WABinary_1.isJidGroup)(jid)) {
616
617
  const { disappearingMessagesInChat } = content;
617
- const value = typeof disappearingMessagesInChat === 'boolean' ?
618
- (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
619
- disappearingMessagesInChat;
618
+ const value = typeof disappearingMessagesInChat === 'boolean'
619
+ ? disappearingMessagesInChat
620
+ ? Defaults_1.WA_DEFAULT_EPHEMERAL
621
+ : 0
622
+ : disappearingMessagesInChat;
620
623
  await groupToggleEphemeral(jid, value);
621
624
  }
622
625
  else {
@@ -627,12 +630,10 @@ const makeMessagesSocket = (config) => {
627
630
  thumbnailWidth: linkPreviewImageThumbnailWidth,
628
631
  fetchOpts: {
629
632
  timeout: 3000,
630
- ...axiosOptions || {}
633
+ ...(axiosOptions || {})
631
634
  },
632
635
  logger,
633
- uploadImage: generateHighQualityLinkPreview
634
- ? waUploadToServer
635
- : undefined
636
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
636
637
  }),
637
638
  //TODO: CACHE
638
639
  getProfilePicUrl: sock.profilePictureUrl,
@@ -640,7 +641,7 @@ const makeMessagesSocket = (config) => {
640
641
  mediaCache: config.mediaCache,
641
642
  options: config.options,
642
643
  messageId: (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id),
643
- ...options,
644
+ ...options
644
645
  });
645
646
  const isDeleteMsg = 'delete' in content && !!content.delete;
646
647
  const isEditMsg = 'edit' in content && !!content.edit;
@@ -669,16 +670,22 @@ const makeMessagesSocket = (config) => {
669
670
  tag: 'meta',
670
671
  attrs: {
671
672
  polltype: 'creation'
672
- },
673
+ }
673
674
  });
674
675
  }
675
676
  if ('cachedGroupMetadata' in options) {
676
677
  console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
677
678
  }
678
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes });
679
+ await relayMessage(jid, fullMsg.message, {
680
+ messageId: fullMsg.key.id,
681
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
682
+ additionalAttributes,
683
+ statusJidList: options.statusJidList,
684
+ additionalNodes
685
+ });
679
686
  if (config.emitOwnEvents) {
680
687
  process.nextTick(() => {
681
- processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
688
+ processingMutex.mutex(() => upsertMessage(fullMsg, 'append'));
682
689
  });
683
690
  }
684
691
  return fullMsg;
@@ -12,9 +12,9 @@ export declare const makeSocket: (config: SocketConfig) => {
12
12
  type: "md";
13
13
  ws: WebSocketClient;
14
14
  ev: import("../Types").BaileysEventEmitter & {
15
- process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): (() => void);
15
+ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
16
16
  buffer(): void;
17
- createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): ((...args: A) => Promise<T>);
17
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>;
18
18
  flush(force?: boolean): boolean;
19
19
  isBuffering(): boolean;
20
20
  };
@@ -35,7 +35,7 @@ export declare const makeSocket: (config: SocketConfig) => {
35
35
  onUnexpectedError: (err: Error | Boom, msg: string) => void;
36
36
  uploadPreKeys: (count?: number) => Promise<void>;
37
37
  uploadPreKeysToServerIfRequired: () => Promise<void>;
38
- requestPairingCode: (phoneNumber: string) => Promise<string>;
38
+ requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
39
39
  /** Waits for the connection to WA to reach a state */
40
40
  waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
41
41
  sendWAMBuffer: (wamBuffer: Buffer) => Promise<any>;
@@ -19,7 +19,7 @@ const Client_1 = require("./Client");
19
19
  */
20
20
  const makeSocket = (config) => {
21
21
  var _a, _b;
22
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
22
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
23
23
  if (printQRInTerminal) {
24
24
  console.warn('⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.');
25
25
  }
@@ -97,8 +97,7 @@ const makeSocket = (config) => {
97
97
  ws.on('frame', onOpen);
98
98
  ws.on('close', onClose);
99
99
  ws.on('error', onClose);
100
- })
101
- .finally(() => {
100
+ }).finally(() => {
102
101
  ws.off('frame', onOpen);
103
102
  ws.off('close', onClose);
104
103
  ws.off('error', onClose);
@@ -140,10 +139,7 @@ const makeSocket = (config) => {
140
139
  node.attrs.id = generateMessageTag();
141
140
  }
142
141
  const msgId = node.attrs.id;
143
- const [result] = await Promise.all([
144
- waitForMessage(msgId, timeoutMs),
145
- sendNode(node)
146
- ]);
142
+ const [result] = await Promise.all([waitForMessage(msgId, timeoutMs), sendNode(node)]);
147
143
  if ('tag' in result) {
148
144
  (0, WABinary_1.assertNodeErrorFree)(result);
149
145
  }
@@ -174,8 +170,8 @@ const makeSocket = (config) => {
174
170
  await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
175
171
  clientFinish: {
176
172
  static: keyEnc,
177
- payload: payloadEnc,
178
- },
173
+ payload: payloadEnc
174
+ }
179
175
  }).finish());
180
176
  noise.finishInit();
181
177
  startKeepAliveRequest();
@@ -189,9 +185,7 @@ const makeSocket = (config) => {
189
185
  type: 'get',
190
186
  to: WABinary_1.S_WHATSAPP_NET
191
187
  },
192
- content: [
193
- { tag: 'count', attrs: {} }
194
- ]
188
+ content: [{ tag: 'count', attrs: {} }]
195
189
  });
196
190
  const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
197
191
  return +countChild.attrs.value;
@@ -288,8 +282,7 @@ const makeSocket = (config) => {
288
282
  ws.on('open', onOpen);
289
283
  ws.on('close', onClose);
290
284
  ws.on('error', onClose);
291
- })
292
- .finally(() => {
285
+ }).finally(() => {
293
286
  ws.off('open', onOpen);
294
287
  ws.off('close', onClose);
295
288
  ws.off('error', onClose);
@@ -315,11 +308,10 @@ const makeSocket = (config) => {
315
308
  id: generateMessageTag(),
316
309
  to: WABinary_1.S_WHATSAPP_NET,
317
310
  type: 'get',
318
- xmlns: 'w:p',
311
+ xmlns: 'w:p'
319
312
  },
320
313
  content: [{ tag: 'ping', attrs: {} }]
321
- })
322
- .catch(err => {
314
+ }).catch(err => {
323
315
  logger.error({ trace: err.stack }, 'error in sending keep alive');
324
316
  });
325
317
  }
@@ -328,17 +320,15 @@ const makeSocket = (config) => {
328
320
  }
329
321
  }, keepAliveIntervalMs));
330
322
  /** i have no idea why this exists. pls enlighten me */
331
- const sendPassiveIq = (tag) => (query({
323
+ const sendPassiveIq = (tag) => query({
332
324
  tag: 'iq',
333
325
  attrs: {
334
326
  to: WABinary_1.S_WHATSAPP_NET,
335
327
  xmlns: 'passive',
336
- type: 'set',
328
+ type: 'set'
337
329
  },
338
- content: [
339
- { tag, attrs: {} }
340
- ]
341
- }));
330
+ content: [{ tag, attrs: {} }]
331
+ });
342
332
  /** logout & invalidate connection */
343
333
  const logout = async (msg) => {
344
334
  var _a;
@@ -365,8 +355,12 @@ const makeSocket = (config) => {
365
355
  }
366
356
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
367
357
  };
368
- const requestPairingCode = async (phoneNumber) => {
369
- authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
358
+ const requestPairingCode = async (phoneNumber, customPairingCode) => {
359
+ const pairingCode = customPairingCode !== null && customPairingCode !== void 0 ? customPairingCode : (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
360
+ if (customPairingCode && (customPairingCode === null || customPairingCode === void 0 ? void 0 : customPairingCode.length) !== 8) {
361
+ throw new Error('Custom pairing code must be exactly 8 chars');
362
+ }
363
+ authState.creds.pairingCode = pairingCode;
370
364
  authState.creds.me = {
371
365
  id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
372
366
  name: '~'
@@ -466,7 +460,7 @@ const makeSocket = (config) => {
466
460
  attrs: {
467
461
  to: WABinary_1.S_WHATSAPP_NET,
468
462
  type: 'result',
469
- id: stanza.attrs.id,
463
+ id: stanza.attrs.id
470
464
  }
471
465
  };
472
466
  await sendNode(iq);
@@ -579,8 +573,7 @@ const makeSocket = (config) => {
579
573
  sendNode({
580
574
  tag: 'presence',
581
575
  attrs: { name: name }
582
- })
583
- .catch(err => {
576
+ }).catch(err => {
584
577
  logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
585
578
  });
586
579
  }
@@ -609,7 +602,7 @@ const makeSocket = (config) => {
609
602
  requestPairingCode,
610
603
  /** Waits for the connection to WA to reach a state */
611
604
  waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
612
- sendWAMBuffer,
605
+ sendWAMBuffer
613
606
  };
614
607
  };
615
608
  exports.makeSocket = makeSocket;
@@ -7,9 +7,9 @@ export declare const makeUSyncSocket: (config: SocketConfig) => {
7
7
  type: "md";
8
8
  ws: import("./Client").WebSocketClient;
9
9
  ev: import("../Types").BaileysEventEmitter & {
10
- process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): (() => void);
10
+ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;
11
11
  buffer(): void;
12
- createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): ((...args: A) => Promise<T>);
12
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>;
13
13
  flush(force?: boolean): boolean;
14
14
  isBuffering(): boolean;
15
15
  };
@@ -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: 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
35
  sendWAMBuffer: (wamBuffer: Buffer) => Promise<any>;
36
36
  };
@@ -6,7 +6,7 @@ const WABinary_1 = require("../WABinary");
6
6
  const socket_1 = require("./socket");
7
7
  const makeUSyncSocket = (config) => {
8
8
  const sock = (0, socket_1.makeSocket)(config);
9
- const { generateMessageTag, query, } = sock;
9
+ const { generateMessageTag, query } = sock;
10
10
  const executeUSyncQuery = async (usyncQuery) => {
11
11
  if (usyncQuery.protocols.length === 0) {
12
12
  throw new boom_1.Boom('USyncQuery must have at least one protocol');
@@ -14,15 +14,13 @@ const makeUSyncSocket = (config) => {
14
14
  // todo: validate users, throw WARNING on no valid users
15
15
  // variable below has only validated users
16
16
  const validUsers = usyncQuery.users;
17
- const userNodes = validUsers.map((user) => {
17
+ const userNodes = validUsers.map(user => {
18
18
  return {
19
19
  tag: 'user',
20
20
  attrs: {
21
- jid: !user.phone ? user.id : undefined,
21
+ jid: !user.phone ? user.id : undefined
22
22
  },
23
- content: usyncQuery.protocols
24
- .map((a) => a.getUserElement(user))
25
- .filter(a => a !== null)
23
+ content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
26
24
  };
27
25
  });
28
26
  const listNode = {
@@ -33,14 +31,14 @@ const makeUSyncSocket = (config) => {
33
31
  const queryNode = {
34
32
  tag: 'query',
35
33
  attrs: {},
36
- content: usyncQuery.protocols.map((a) => a.getQueryElement())
34
+ content: usyncQuery.protocols.map(a => a.getQueryElement())
37
35
  };
38
36
  const iq = {
39
37
  tag: 'iq',
40
38
  attrs: {
41
39
  to: WABinary_1.S_WHATSAPP_NET,
42
40
  type: 'get',
43
- xmlns: 'usync',
41
+ xmlns: 'usync'
44
42
  },
45
43
  content: [
46
44
  {
@@ -50,21 +48,18 @@ const makeUSyncSocket = (config) => {
50
48
  mode: usyncQuery.mode,
51
49
  sid: generateMessageTag(),
52
50
  last: 'true',
53
- index: '0',
51
+ index: '0'
54
52
  },
55
- content: [
56
- queryNode,
57
- listNode
58
- ]
53
+ content: [queryNode, listNode]
59
54
  }
60
- ],
55
+ ]
61
56
  };
62
57
  const result = await query(iq);
63
58
  return usyncQuery.parseUSyncQueryResult(result);
64
59
  };
65
60
  return {
66
61
  ...sock,
67
- executeUSyncQuery,
62
+ executeUSyncQuery
68
63
  };
69
64
  };
70
65
  exports.makeUSyncSocket = makeUSyncSocket;
@@ -62,7 +62,7 @@ export type AuthenticationCreds = SignalCreds & {
62
62
  };
63
63
  export type SignalDataTypeMap = {
64
64
  'pre-key': KeyPair;
65
- 'session': Uint8Array;
65
+ session: Uint8Array;
66
66
  'sender-key': Uint8Array;
67
67
  'sender-key-memory': {
68
68
  [jid: string]: boolean;
@@ -15,7 +15,7 @@ export type WAPrivacyMessagesValue = 'all' | 'contacts';
15
15
  /** set of statuses visible to other people; see updatePresence() in WhatsAppWeb.Send */
16
16
  export type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
17
17
  export declare const ALL_WA_PATCH_NAMES: readonly ["critical_block", "critical_unblock_low", "regular_high", "regular_low", "regular"];
18
- export type WAPatchName = typeof ALL_WA_PATCH_NAMES[number];
18
+ export type WAPatchName = (typeof ALL_WA_PATCH_NAMES)[number];
19
19
  export interface PresenceData {
20
20
  lastKnownPresence: WAPresence;
21
21
  lastSeen?: number;
package/lib/Types/Chat.js CHANGED
@@ -1,4 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ALL_WA_PATCH_NAMES = void 0;
4
- exports.ALL_WA_PATCH_NAMES = ['critical_block', 'critical_unblock_low', 'regular_high', 'regular_low', 'regular'];
4
+ exports.ALL_WA_PATCH_NAMES = [
5
+ 'critical_block',
6
+ 'critical_unblock_low',
7
+ 'regular_high',
8
+ 'regular_low',
9
+ 'regular'
10
+ ];
@@ -1,6 +1,10 @@
1
1
  export interface Contact {
2
+ /** ID either in lid or jid format **/
2
3
  id: string;
4
+ /** ID in Lid (anonymous) format (@lid) **/
3
5
  lid?: string;
6
+ /** ID in Phone Number format (@s.whatsapp.net) **/
7
+ jid?: string;
4
8
  /** name of the contact, you have saved on your WA */
5
9
  name?: string;
6
10
  /** name of the contact, the contact has set on their own on WA */
@@ -98,7 +98,7 @@ export type BaileysEventMap = {
98
98
  type: 'add' | 'remove';
99
99
  };
100
100
  /** Receive an update on a call, including when the call was received, rejected, accepted */
101
- 'call': WACallEvent[];
101
+ call: WACallEvent[];
102
102
  'labels.edit': Label;
103
103
  'labels.association': {
104
104
  association: LabelAssociation;
@@ -1,26 +1,30 @@
1
1
  import { Contact } from './Contact';
2
- export type GroupParticipant = (Contact & {
2
+ export type GroupParticipant = Contact & {
3
3
  isAdmin?: boolean;
4
4
  isSuperAdmin?: boolean;
5
5
  admin?: 'admin' | 'superadmin' | null;
6
- });
6
+ };
7
7
  export type ParticipantAction = 'add' | 'remove' | 'promote' | 'demote' | 'modify';
8
8
  export type RequestJoinAction = 'created' | 'revoked' | 'rejected';
9
9
  export type RequestJoinMethod = 'invite_link' | 'linked_group_join' | 'non_admin_add' | undefined;
10
10
  export interface GroupMetadata {
11
11
  id: string;
12
12
  /** group uses 'lid' or 'pn' to send messages */
13
- addressingMode: "pn" | "lid";
13
+ addressingMode: 'pn' | 'lid';
14
14
  owner: string | undefined;
15
+ ownerJid?: string | undefined;
15
16
  subject: string;
16
17
  /** group subject owner */
17
18
  subjectOwner?: string;
19
+ subjectOwnerJid?: string;
18
20
  /** group subject modification date */
19
21
  subjectTime?: number;
20
22
  creation?: number;
21
23
  desc?: string;
22
24
  descOwner?: string;
25
+ descOwnerJid?: string;
23
26
  descId?: string;
27
+ descTime?: number;
24
28
  /** if this group is part of a community, it returns the jid of the community to which it belongs */
25
29
  linkedParent?: string;
26
30
  /** is set when the group only allows admins to change group settings */
@@ -11,7 +11,12 @@ export type WAMessage = proto.IWebMessageInfo;
11
11
  export type WAMessageContent = proto.IMessage;
12
12
  export type WAContactMessage = proto.Message.IContactMessage;
13
13
  export type WAContactsArrayMessage = proto.Message.IContactsArrayMessage;
14
- export type WAMessageKey = proto.IMessageKey;
14
+ export type WAMessageKey = proto.IMessageKey & {
15
+ senderLid?: string;
16
+ senderPn?: string;
17
+ participantLid?: string;
18
+ participantPn?: string;
19
+ };
15
20
  export type WATextMessage = proto.Message.IExtendedTextMessage;
16
21
  export type WAContextInfo = proto.IContextInfo;
17
22
  export type WALocationMessage = proto.Message.ILocationMessage;
@@ -217,7 +222,7 @@ export type MiscMessageGenerationOptions = MinimalRelayOptions & {
217
222
  export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions & {
218
223
  userJid: string;
219
224
  };
220
- export type WAMediaUploadFunction = (readStream: Readable, opts: {
225
+ export type WAMediaUploadFunction = (encFilePath: string, opts: {
221
226
  fileEncSha256B64: string;
222
227
  mediaType: MediaType;
223
228
  timeoutMs?: number;
@@ -33,7 +33,7 @@ export type SocketConfig = {
33
33
  keepAliveIntervalMs: number;
34
34
  /** should baileys use the mobile api instead of the multi device api
35
35
  * @deprecated This feature has been removed
36
- */
36
+ */
37
37
  mobile?: boolean;
38
38
  /** proxy agent */
39
39
  agent?: Agent;
@@ -46,8 +46,8 @@ export type SocketConfig = {
46
46
  /** agent used for fetch requests -- uploading/downloading media */
47
47
  fetchAgent?: Agent;
48
48
  /** should the QR be printed in the terminal
49
- * @deprecated This feature has been removed
50
- */
49
+ * @deprecated This feature has been removed
50
+ */
51
51
  printQRInTerminal?: boolean;
52
52
  /** should events be emitted for actions done by this socket connection */
53
53
  emitOwnEvents: boolean;