@alannxd/baileys 6.0.4 → 6.0.5

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 (234) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +5479 -0
  3. package/WAProto/fix-imports.js +85 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +201 -160
  6. package/engine-requirements.js +1 -1
  7. package/lib/Defaults/index.d.ts +37 -15
  8. package/lib/Defaults/index.js +119 -136
  9. package/lib/Signal/Group/ciphertext-message.d.ts +1 -0
  10. package/lib/Signal/Group/ciphertext-message.js +2 -5
  11. package/lib/Signal/Group/group-session-builder.d.ts +4 -3
  12. package/lib/Signal/Group/group-session-builder.js +7 -41
  13. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  14. package/lib/Signal/Group/group_cipher.js +37 -51
  15. package/lib/Signal/Group/index.d.ts +12 -11
  16. package/lib/Signal/Group/index.js +12 -57
  17. package/lib/Signal/Group/keyhelper.d.ts +2 -1
  18. package/lib/Signal/Group/keyhelper.js +7 -44
  19. package/lib/Signal/Group/sender-chain-key.d.ts +3 -2
  20. package/lib/Signal/Group/sender-chain-key.js +7 -15
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +2 -1
  22. package/lib/Signal/Group/sender-key-distribution-message.js +8 -11
  23. package/lib/Signal/Group/sender-key-message.d.ts +2 -1
  24. package/lib/Signal/Group/sender-key-message.js +9 -12
  25. package/lib/Signal/Group/sender-key-name.d.ts +1 -0
  26. package/lib/Signal/Group/sender-key-name.js +2 -5
  27. package/lib/Signal/Group/sender-key-record.d.ts +3 -2
  28. package/lib/Signal/Group/sender-key-record.js +9 -21
  29. package/lib/Signal/Group/sender-key-state.d.ts +7 -6
  30. package/lib/Signal/Group/sender-key-state.js +27 -42
  31. package/lib/Signal/Group/sender-message-key.d.ts +1 -0
  32. package/lib/Signal/Group/sender-message-key.js +4 -7
  33. package/lib/Signal/libsignal.d.ts +5 -3
  34. package/lib/Signal/libsignal.js +347 -90
  35. package/lib/Signal/lid-mapping.d.ts +23 -0
  36. package/lib/Signal/lid-mapping.js +277 -0
  37. package/lib/Socket/Client/index.d.ts +3 -3
  38. package/lib/Socket/Client/index.js +3 -19
  39. package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +4 -5
  40. package/lib/Socket/Client/types.js +11 -0
  41. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +3 -2
  42. package/lib/Socket/Client/websocket.js +54 -0
  43. package/lib/Socket/business.d.ts +154 -108
  44. package/lib/Socket/business.js +162 -43
  45. package/lib/Socket/chats.d.ts +96 -239
  46. package/lib/Socket/chats.js +627 -427
  47. package/lib/Socket/communities.d.ts +239 -146
  48. package/lib/Socket/communities.js +90 -80
  49. package/lib/Socket/groups.d.ts +104 -57
  50. package/lib/Socket/groups.js +154 -161
  51. package/lib/Socket/index.d.ts +202 -115
  52. package/lib/Socket/index.js +11 -10
  53. package/lib/Socket/luxu.d.ts +22 -266
  54. package/lib/Socket/luxu.js +422 -465
  55. package/lib/Socket/messages-recv.d.ts +136 -84
  56. package/lib/Socket/messages-recv.js +1421 -615
  57. package/lib/Socket/messages-send.d.ts +142 -126
  58. package/lib/Socket/messages-send.js +878 -671
  59. package/lib/Socket/mex.d.ts +3 -0
  60. package/lib/Socket/mex.js +42 -0
  61. package/lib/Socket/newsletter.d.ts +121 -85
  62. package/lib/Socket/newsletter.js +147 -272
  63. package/lib/Socket/socket.d.ts +34 -19
  64. package/lib/Socket/socket.js +544 -313
  65. package/lib/Store/index.d.ts +10 -3
  66. package/lib/Store/index.js +10 -10
  67. package/lib/Store/keyed-db.d.ts +22 -0
  68. package/lib/Store/keyed-db.js +108 -0
  69. package/lib/Store/make-cache-manager-store.d.ts +17 -11
  70. package/lib/Store/make-cache-manager-store.js +43 -41
  71. package/lib/Store/make-in-memory-store.d.ts +39 -118
  72. package/lib/Store/make-in-memory-store.js +112 -341
  73. package/lib/Store/make-ordered-dictionary.d.ts +11 -10
  74. package/lib/Store/make-ordered-dictionary.js +14 -20
  75. package/lib/Store/object-repository.d.ts +10 -9
  76. package/lib/Store/object-repository.js +11 -6
  77. package/lib/Types/Auth.d.ts +19 -12
  78. package/lib/Types/Auth.js +2 -2
  79. package/lib/Types/Bussines.d.ts +25 -0
  80. package/lib/Types/Bussines.js +2 -0
  81. package/lib/Types/Call.d.ts +3 -1
  82. package/lib/Types/Call.js +2 -2
  83. package/lib/Types/Chat.d.ts +35 -13
  84. package/lib/Types/Chat.js +8 -4
  85. package/lib/Types/Contact.d.ts +8 -1
  86. package/lib/Types/Contact.js +2 -2
  87. package/lib/Types/Events.d.ts +116 -17
  88. package/lib/Types/Events.js +2 -2
  89. package/lib/Types/GroupMetadata.d.ts +21 -5
  90. package/lib/Types/GroupMetadata.js +2 -2
  91. package/lib/Types/Label.d.ts +12 -0
  92. package/lib/Types/Label.js +3 -5
  93. package/lib/Types/LabelAssociation.d.ts +1 -0
  94. package/lib/Types/LabelAssociation.js +3 -5
  95. package/lib/Types/Message.d.ts +105 -58
  96. package/lib/Types/Message.js +11 -9
  97. package/lib/Types/Mex.d.ts +141 -0
  98. package/lib/Types/Mex.js +37 -0
  99. package/lib/Types/Product.d.ts +2 -1
  100. package/lib/Types/Product.js +2 -2
  101. package/lib/Types/Signal.d.ts +32 -2
  102. package/lib/Types/Signal.js +2 -2
  103. package/lib/Types/Socket.d.ts +50 -25
  104. package/lib/Types/Socket.js +3 -2
  105. package/lib/Types/State.d.ts +72 -2
  106. package/lib/Types/State.js +56 -2
  107. package/lib/Types/USync.d.ts +3 -2
  108. package/lib/Types/USync.js +2 -2
  109. package/lib/Types/index.d.ts +22 -14
  110. package/lib/Types/index.js +15 -31
  111. package/lib/Utils/auth-utils.d.ts +12 -6
  112. package/lib/Utils/auth-utils.js +239 -143
  113. package/lib/Utils/browser-utils.d.ts +4 -0
  114. package/lib/Utils/browser-utils.js +28 -0
  115. package/lib/Utils/business.d.ts +3 -2
  116. package/lib/Utils/business.js +66 -69
  117. package/lib/Utils/chat-utils.d.ts +52 -23
  118. package/lib/Utils/chat-utils.js +396 -253
  119. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  120. package/lib/Utils/companion-reg-client-utils.js +35 -0
  121. package/lib/Utils/crypto.d.ts +18 -22
  122. package/lib/Utils/crypto.js +57 -90
  123. package/lib/Utils/decode-wa-message.d.ts +55 -8
  124. package/lib/Utils/decode-wa-message.js +203 -84
  125. package/lib/Utils/event-buffer.d.ts +9 -8
  126. package/lib/Utils/event-buffer.js +185 -77
  127. package/lib/Utils/generics.d.ts +28 -29
  128. package/lib/Utils/generics.js +180 -210
  129. package/lib/Utils/history.d.ts +18 -9
  130. package/lib/Utils/history.js +93 -55
  131. package/lib/Utils/identity-change-handler.d.ts +44 -0
  132. package/lib/Utils/identity-change-handler.js +50 -0
  133. package/lib/Utils/index.d.ts +22 -17
  134. package/lib/Utils/index.js +22 -33
  135. package/lib/Utils/link-preview.d.ts +5 -5
  136. package/lib/Utils/link-preview.js +16 -24
  137. package/lib/Utils/logger.d.ts +11 -3
  138. package/lib/Utils/logger.js +3 -7
  139. package/lib/Utils/lt-hash.d.ts +8 -12
  140. package/lib/Utils/lt-hash.js +3 -46
  141. package/lib/Utils/make-mutex.d.ts +4 -2
  142. package/lib/Utils/make-mutex.js +24 -34
  143. package/lib/Utils/message-retry-manager.d.ts +115 -0
  144. package/lib/Utils/message-retry-manager.js +265 -0
  145. package/lib/Utils/messages-media.d.ts +61 -44
  146. package/lib/Utils/messages-media.js +451 -482
  147. package/lib/Utils/messages.d.ts +32 -18
  148. package/lib/Utils/messages.js +458 -369
  149. package/lib/Utils/noise-handler.d.ts +13 -14
  150. package/lib/Utils/noise-handler.js +145 -99
  151. package/lib/Utils/offline-node-processor.d.ts +17 -0
  152. package/lib/Utils/offline-node-processor.js +40 -0
  153. package/lib/Utils/pre-key-manager.d.ts +28 -0
  154. package/lib/Utils/pre-key-manager.js +106 -0
  155. package/lib/Utils/process-message.d.ts +31 -12
  156. package/lib/Utils/process-message.js +459 -150
  157. package/lib/Utils/reporting-utils.d.ts +11 -0
  158. package/lib/Utils/reporting-utils.js +258 -0
  159. package/lib/Utils/signal.d.ts +20 -5
  160. package/lib/Utils/signal.js +120 -72
  161. package/lib/Utils/stanza-ack.d.ts +11 -0
  162. package/lib/Utils/stanza-ack.js +38 -0
  163. package/lib/Utils/sync-action-utils.d.ts +19 -0
  164. package/lib/Utils/sync-action-utils.js +49 -0
  165. package/lib/Utils/tc-token-utils.d.ts +37 -0
  166. package/lib/Utils/tc-token-utils.js +163 -0
  167. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  168. package/lib/Utils/use-multi-file-auth-state.js +29 -27
  169. package/lib/Utils/validate-connection.d.ts +7 -7
  170. package/lib/Utils/validate-connection.js +73 -99
  171. package/lib/WABinary/constants.d.ts +25 -27
  172. package/lib/WABinary/constants.js +1281 -20
  173. package/lib/WABinary/decode.d.ts +5 -5
  174. package/lib/WABinary/decode.js +52 -42
  175. package/lib/WABinary/encode.d.ts +3 -3
  176. package/lib/WABinary/encode.js +110 -155
  177. package/lib/WABinary/generic-utils.d.ts +8 -7
  178. package/lib/WABinary/generic-utils.js +48 -49
  179. package/lib/WABinary/index.d.ts +6 -5
  180. package/lib/WABinary/index.js +6 -21
  181. package/lib/WABinary/jid-utils.d.ts +25 -8
  182. package/lib/WABinary/jid-utils.js +74 -40
  183. package/lib/WABinary/types.d.ts +2 -1
  184. package/lib/WABinary/types.js +2 -2
  185. package/lib/WAM/BinaryInfo.d.ts +3 -11
  186. package/lib/WAM/BinaryInfo.js +2 -5
  187. package/lib/WAM/constants.d.ts +5 -3
  188. package/lib/WAM/constants.js +19071 -11568
  189. package/lib/WAM/encode.d.ts +3 -3
  190. package/lib/WAM/encode.js +17 -22
  191. package/lib/WAM/index.d.ts +4 -3
  192. package/lib/WAM/index.js +4 -19
  193. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +4 -3
  194. package/lib/WAUSync/Protocols/USyncContactProtocol.js +33 -13
  195. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +3 -2
  196. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  197. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +3 -2
  198. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -12
  199. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +3 -2
  200. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  201. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  202. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  203. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +4 -3
  204. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  205. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +5 -3
  206. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -8
  207. package/lib/WAUSync/Protocols/index.d.ts +6 -4
  208. package/lib/WAUSync/Protocols/index.js +6 -20
  209. package/lib/WAUSync/USyncQuery.d.ts +6 -4
  210. package/lib/WAUSync/USyncQuery.js +44 -35
  211. package/lib/WAUSync/USyncUser.d.ts +10 -5
  212. package/lib/WAUSync/USyncUser.js +10 -5
  213. package/lib/WAUSync/index.d.ts +4 -0
  214. package/lib/WAUSync/index.js +4 -19
  215. package/lib/index.d.ts +10 -9
  216. package/lib/index.js +12 -34
  217. package/package.json +84 -51
  218. package/WAProto/fix-import.js +0 -29
  219. package/lib/Defaults/baileys-version.json +0 -3
  220. package/lib/Defaults/phonenumber-mcc.json +0 -223
  221. package/lib/Signal/Group/queue-job.d.ts +0 -1
  222. package/lib/Signal/Group/queue-job.js +0 -57
  223. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  224. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  225. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  226. package/lib/Socket/Client/web-socket-client.js +0 -62
  227. package/lib/Socket/registration.d.ts +0 -267
  228. package/lib/Socket/registration.js +0 -166
  229. package/lib/Socket/usync.d.ts +0 -36
  230. package/lib/Socket/usync.js +0 -70
  231. package/lib/Types/Newsletter.d.ts +0 -103
  232. package/lib/Types/Newsletter.js +0 -38
  233. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  234. package/lib/Utils/baileys-event-stream.js +0 -63
@@ -1,75 +1,106 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getHistoryMsg = exports.downloadAndProcessHistorySyncNotification = exports.processHistoryMessage = exports.downloadHistory = void 0;
4
- const util_1 = require("util");
5
- const zlib_1 = require("zlib");
6
- const WAProto_1 = require("../../WAProto");
7
- const Types_1 = require("../Types");
8
- const WABinary_1 = require("../WABinary");
9
- const generics_1 = require("./generics");
10
- const messages_1 = require("./messages");
11
- const messages_media_1 = require("./messages-media");
12
- const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
13
- const downloadHistory = async (msg, options) => {
14
- const stream = await (0, messages_media_1.downloadContentFromMessage)(msg, 'md-msg-hist', { options });
15
- const bufferArray = [];
16
- for await (const chunk of stream) {
17
- bufferArray.push(chunk);
1
+ import { pipeline } from 'stream/promises';
2
+ import { promisify } from 'util';
3
+ import { createInflate, inflate } from 'zlib';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { WAMessageStubType } from '../Types/index.js';
6
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/index.js';
7
+ import { toNumber } from './generics.js';
8
+ import { normalizeMessageContent } from './messages.js';
9
+ import { downloadContentFromMessage } from './messages-media.js';
10
+ const inflatePromise = promisify(inflate);
11
+ const extractPnFromMessages = (messages) => {
12
+ for (const msgItem of messages) {
13
+ const message = msgItem.message;
14
+ // Only extract from outgoing messages (fromMe: true) in 1:1 chats
15
+ // because userReceipt.userJid is the recipient's JID
16
+ if (!message?.key?.fromMe || !message.userReceipt?.length) {
17
+ continue;
18
+ }
19
+ const userJid = message.userReceipt[0]?.userJid;
20
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
21
+ return userJid;
22
+ }
18
23
  }
19
- let buffer = Buffer.concat(bufferArray);
20
- // decompress buffer
21
- buffer = await inflatePromise(buffer);
22
- const syncData = WAProto_1.proto.HistorySync.decode(buffer);
24
+ return undefined;
25
+ };
26
+ export const downloadHistory = async (msg, options) => {
27
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
28
+ // Pipe decrypted stream directly through zlib inflate
29
+ // This avoids allocating an intermediate buffer for the compressed data
30
+ const inflater = createInflate();
31
+ const chunks = [];
32
+ inflater.on('data', (chunk) => chunks.push(chunk));
33
+ await pipeline(stream, inflater);
34
+ const buffer = Buffer.concat(chunks);
35
+ const syncData = proto.HistorySync.decode(buffer);
23
36
  return syncData;
24
37
  };
25
- exports.downloadHistory = downloadHistory;
26
- const processHistoryMessage = (item) => {
27
- var _a, _b, _c;
38
+ export const processHistoryMessage = (item, logger) => {
28
39
  const messages = [];
29
40
  const contacts = [];
30
41
  const chats = [];
42
+ const lidPnMappings = [];
43
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
44
+ // Extract LID-PN mappings for all sync types
45
+ for (const m of item.phoneNumberToLidMappings || []) {
46
+ if (m.lidJid && m.pnJid) {
47
+ lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
48
+ }
49
+ }
31
50
  switch (item.syncType) {
32
- case WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
33
- case WAProto_1.proto.HistorySync.HistorySyncType.RECENT:
34
- case WAProto_1.proto.HistorySync.HistorySyncType.FULL:
51
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
52
+ case proto.HistorySync.HistorySyncType.RECENT:
53
+ case proto.HistorySync.HistorySyncType.FULL:
54
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
35
55
  for (const chat of item.conversations) {
36
- contacts.push({
56
+ contacts.push({
37
57
  id: chat.id,
38
- name: chat.name || undefined,
39
- lid: chat.lidJid || undefined,
40
- jid: (0, WABinary_1.isJidUser)(chat.id) ? chat.id : undefined
58
+ name: chat.displayName || chat.name || chat.username || undefined,
59
+ username: chat.username || undefined,
60
+ lid: chat.lidJid || chat.accountLid || undefined,
61
+ phoneNumber: chat.pnJid || undefined
41
62
  });
63
+ const chatId = chat.id;
64
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
65
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
66
+ if (isLid && chat.pnJid) {
67
+ lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
68
+ }
69
+ else if (isPn && chat.lidJid) {
70
+ lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
71
+ }
72
+ else if (isLid && !chat.pnJid) {
73
+ // Fallback: extract PN from userReceipt in messages when pnJid is missing
74
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
75
+ if (pnFromReceipt) {
76
+ lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
77
+ }
78
+ }
42
79
  const msgs = chat.messages || [];
43
80
  delete chat.messages;
44
- delete chat.archived;
45
- delete chat.muteEndTime;
46
- delete chat.pinned;
47
81
  for (const item of msgs) {
48
82
  const message = item.message;
49
83
  messages.push(message);
50
- if (!((_a = chat.messages) === null || _a === void 0 ? void 0 : _a.length)) {
84
+ if (!chat.messages?.length) {
51
85
  // keep only the most recent message in the chat array
52
86
  chat.messages = [{ message }];
53
87
  }
54
88
  if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
55
- chat.lastMessageRecvTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
89
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
56
90
  }
57
- if ((message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
58
- || message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB)
59
- && ((_b = message.messageStubParameters) === null || _b === void 0 ? void 0 : _b[0])) {
91
+ if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
92
+ message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
93
+ message.messageStubParameters?.[0]) {
60
94
  contacts.push({
61
95
  id: message.key.participant || message.key.remoteJid,
62
- verifiedName: (_c = message.messageStubParameters) === null || _c === void 0 ? void 0 : _c[0],
96
+ verifiedName: message.messageStubParameters?.[0]
63
97
  });
64
98
  }
65
99
  }
66
- if ((0, WABinary_1.isJidUser)(chat.id) && chat.readOnly && chat.archived) {
67
- delete chat.readOnly;
68
- }
69
- chats.push({ ...chat });
100
+ chats.push(chat);
70
101
  }
71
102
  break;
72
- case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
103
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
73
104
  for (const c of item.pushnames) {
74
105
  contacts.push({ id: c.id, notify: c.pushname });
75
106
  }
@@ -79,18 +110,25 @@ const processHistoryMessage = (item) => {
79
110
  chats,
80
111
  contacts,
81
112
  messages,
113
+ lidPnMappings,
114
+ pastParticipants: item.pastParticipants,
115
+ syncType: item.syncType,
116
+ progress: item.progress
82
117
  };
83
118
  };
84
- exports.processHistoryMessage = processHistoryMessage;
85
- const downloadAndProcessHistorySyncNotification = async (msg, options) => {
86
- const historyMsg = await (0, exports.downloadHistory)(msg, options);
87
- return (0, exports.processHistoryMessage)(historyMsg);
119
+ export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
120
+ let historyMsg;
121
+ if (msg.initialHistBootstrapInlinePayload) {
122
+ historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
123
+ }
124
+ else {
125
+ historyMsg = await downloadHistory(msg, options);
126
+ }
127
+ return processHistoryMessage(historyMsg, logger);
88
128
  };
89
- exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
90
- const getHistoryMsg = (message) => {
91
- var _a;
92
- const normalizedContent = !!message ? (0, messages_1.normalizeMessageContent)(message) : undefined;
93
- const anyHistoryMsg = (_a = normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage) === null || _a === void 0 ? void 0 : _a.historySyncNotification;
129
+ export const getHistoryMsg = (message) => {
130
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
131
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
94
132
  return anyHistoryMsg;
95
133
  };
96
- exports.getHistoryMsg = getHistoryMsg;
134
+ //# sourceMappingURL=history.js.map
@@ -0,0 +1,44 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { type BinaryNode } from '../WABinary/index.js';
3
+ import type { ILogger } from './logger.js';
4
+ export type IdentityChangeResult = {
5
+ action: 'no_identity_node';
6
+ } | {
7
+ action: 'invalid_notification';
8
+ } | {
9
+ action: 'skipped_companion_device';
10
+ device: number;
11
+ } | {
12
+ action: 'skipped_self_primary';
13
+ } | {
14
+ action: 'debounced';
15
+ } | {
16
+ action: 'skipped_offline';
17
+ } | {
18
+ action: 'skipped_no_session';
19
+ } | {
20
+ action: 'session_refreshed';
21
+ } | {
22
+ action: 'session_refresh_failed';
23
+ error: unknown;
24
+ };
25
+ export type IdentityChangeContext = {
26
+ meId: string | undefined;
27
+ meLid: string | undefined;
28
+ validateSession: (jid: string) => Promise<{
29
+ exists: boolean;
30
+ reason?: string;
31
+ }>;
32
+ assertSessions: (jids: string[], force?: boolean) => Promise<boolean>;
33
+ debounceCache: NodeCache<boolean>;
34
+ logger: ILogger;
35
+ /**
36
+ * Invoked right before `assertSessions` is called for an existing-session identity change.
37
+ * Used to kick off fire-and-forget side effects (e.g. tctoken re-issuance) in the same
38
+ * order WA Web does — i.e. before the E2E session is re-established.
39
+ * Must not throw; implementations are responsible for their own error handling.
40
+ */
41
+ onBeforeSessionRefresh?: (jid: string) => void;
42
+ };
43
+ export declare function handleIdentityChange(node: BinaryNode, ctx: IdentityChangeContext): Promise<IdentityChangeResult>;
44
+ //# sourceMappingURL=identity-change-handler.d.ts.map
@@ -0,0 +1,50 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { areJidsSameUser, getBinaryNodeChild, jidDecode } from '../WABinary/index.js';
3
+ import { isStringNullOrEmpty } from './generics.js';
4
+ export async function handleIdentityChange(node, ctx) {
5
+ const from = node.attrs.from;
6
+ if (!from) {
7
+ return { action: 'invalid_notification' };
8
+ }
9
+ const identityNode = getBinaryNodeChild(node, 'identity');
10
+ if (!identityNode) {
11
+ return { action: 'no_identity_node' };
12
+ }
13
+ ctx.logger.info({ jid: from }, 'identity changed');
14
+ const decoded = jidDecode(from);
15
+ if (decoded?.device && decoded.device !== 0) {
16
+ ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device');
17
+ return { action: 'skipped_companion_device', device: decoded.device };
18
+ }
19
+ const isSelfPrimary = ctx.meId && (areJidsSameUser(from, ctx.meId) || (ctx.meLid && areJidsSameUser(from, ctx.meLid)));
20
+ if (isSelfPrimary) {
21
+ ctx.logger.info({ jid: from }, 'self primary identity changed');
22
+ return { action: 'skipped_self_primary' };
23
+ }
24
+ if (ctx.debounceCache.get(from)) {
25
+ ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)');
26
+ return { action: 'debounced' };
27
+ }
28
+ ctx.debounceCache.set(from, true);
29
+ const isOfflineNotification = !isStringNullOrEmpty(node.attrs.offline);
30
+ const hasExistingSession = await ctx.validateSession(from);
31
+ if (!hasExistingSession.exists) {
32
+ ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh');
33
+ return { action: 'skipped_no_session' };
34
+ }
35
+ ctx.logger.debug({ jid: from }, 'old session exists, will refresh session');
36
+ if (isOfflineNotification) {
37
+ ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing');
38
+ return { action: 'skipped_offline' };
39
+ }
40
+ ctx.onBeforeSessionRefresh?.(from);
41
+ try {
42
+ await ctx.assertSessions([from], true);
43
+ return { action: 'session_refreshed' };
44
+ }
45
+ catch (error) {
46
+ ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change');
47
+ return { action: 'session_refresh_failed', error };
48
+ }
49
+ }
50
+ //# sourceMappingURL=identity-change-handler.js.map
@@ -1,17 +1,22 @@
1
- export * from './generics';
2
- export * from './decode-wa-message';
3
- export * from './messages';
4
- export * from './messages-media';
5
- export * from './validate-connection';
6
- export * from './crypto';
7
- export * from './signal';
8
- export * from './noise-handler';
9
- export * from './history';
10
- export * from './chat-utils';
11
- export * from './lt-hash';
12
- export * from './auth-utils';
13
- export * from './baileys-event-stream';
14
- export * from './use-multi-file-auth-state';
15
- export * from './link-preview';
16
- export * from './event-buffer';
17
- export * from './process-message';
1
+ export * from './generics.js';
2
+ export * from './decode-wa-message.js';
3
+ export * from './messages.js';
4
+ export * from './messages-media.js';
5
+ export * from './validate-connection.js';
6
+ export * from './crypto.js';
7
+ export * from './signal.js';
8
+ export * from './noise-handler.js';
9
+ export * from './history.js';
10
+ export * from './chat-utils.js';
11
+ export * from './lt-hash.js';
12
+ export * from './auth-utils.js';
13
+ export * from './use-multi-file-auth-state.js';
14
+ export * from './link-preview.js';
15
+ export * from './event-buffer.js';
16
+ export * from './process-message.js';
17
+ export * from './message-retry-manager.js';
18
+ export * from './browser-utils.js';
19
+ export * from './companion-reg-client-utils.js';
20
+ export * from './identity-change-handler.js';
21
+ export * from './stanza-ack.js';
22
+ //# sourceMappingURL=index.d.ts.map
@@ -1,33 +1,22 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./generics"), exports);
18
- __exportStar(require("./decode-wa-message"), exports);
19
- __exportStar(require("./messages"), exports);
20
- __exportStar(require("./messages-media"), exports);
21
- __exportStar(require("./validate-connection"), exports);
22
- __exportStar(require("./crypto"), exports);
23
- __exportStar(require("./signal"), exports);
24
- __exportStar(require("./noise-handler"), exports);
25
- __exportStar(require("./history"), exports);
26
- __exportStar(require("./chat-utils"), exports);
27
- __exportStar(require("./lt-hash"), exports);
28
- __exportStar(require("./auth-utils"), exports);
29
- __exportStar(require("./baileys-event-stream"), exports);
30
- __exportStar(require("./use-multi-file-auth-state"), exports);
31
- __exportStar(require("./link-preview"), exports);
32
- __exportStar(require("./event-buffer"), exports);
33
- __exportStar(require("./process-message"), exports);
1
+ export * from './generics.js';
2
+ export * from './decode-wa-message.js';
3
+ export * from './messages.js';
4
+ export * from './messages-media.js';
5
+ export * from './validate-connection.js';
6
+ export * from './crypto.js';
7
+ export * from './signal.js';
8
+ export * from './noise-handler.js';
9
+ export * from './history.js';
10
+ export * from './chat-utils.js';
11
+ export * from './lt-hash.js';
12
+ export * from './auth-utils.js';
13
+ export * from './use-multi-file-auth-state.js';
14
+ export * from './link-preview.js';
15
+ export * from './event-buffer.js';
16
+ export * from './process-message.js';
17
+ export * from './message-retry-manager.js';
18
+ export * from './browser-utils.js';
19
+ export * from './companion-reg-client-utils.js';
20
+ export * from './identity-change-handler.js';
21
+ export * from './stanza-ack.js';
22
+ //# sourceMappingURL=index.js.map
@@ -1,16 +1,15 @@
1
- import { AxiosRequestConfig } from 'axios';
2
- import { Logger } from 'pino';
3
- import { WAMediaUploadFunction, WAUrlInfo } from '../Types';
1
+ import type { WAMediaUploadFunction, WAUrlInfo } from '../Types/index.js';
2
+ import type { ILogger } from './logger.js';
4
3
  export type URLGenerationOptions = {
5
4
  thumbnailWidth: number;
6
5
  fetchOpts: {
7
6
  /** Timeout in ms */
8
7
  timeout: number;
9
8
  proxyUrl?: string;
10
- headers?: AxiosRequestConfig<{}>['headers'];
9
+ headers?: HeadersInit;
11
10
  };
12
11
  uploadImage?: WAMediaUploadFunction;
13
- logger?: Logger;
12
+ logger?: ILogger;
14
13
  };
15
14
  /**
16
15
  * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
@@ -19,3 +18,4 @@ export type URLGenerationOptions = {
19
18
  * @returns the URL info required to generate link preview
20
19
  */
21
20
  export declare const getUrlInfo: (text: string, opts?: URLGenerationOptions) => Promise<WAUrlInfo | undefined>;
21
+ //# sourceMappingURL=link-preview.d.ts.map
@@ -1,13 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getUrlInfo = void 0;
4
- const messages_1 = require("./messages");
5
- const messages_media_1 = require("./messages-media");
1
+ import { prepareWAMessageMedia } from './messages.js';
2
+ import { extractImageThumb, getHttpStream } from './messages-media.js';
6
3
  const THUMBNAIL_WIDTH_PX = 192;
7
4
  /** Fetches an image and generates a thumbnail for it */
8
5
  const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
9
- const stream = await (0, messages_media_1.getHttpStream)(url, fetchOpts);
10
- const result = await (0, messages_media_1.extractImageThumb)(stream, thumbnailWidth);
6
+ const stream = await getHttpStream(url, fetchOpts);
7
+ const result = await extractImageThumb(stream, thumbnailWidth);
11
8
  return result;
12
9
  };
13
10
  /**
@@ -16,14 +13,13 @@ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) =>
16
13
  * @param text first matched URL in text
17
14
  * @returns the URL info required to generate link preview
18
15
  */
19
- const getUrlInfo = async (text, opts = {
16
+ export const getUrlInfo = async (text, opts = {
20
17
  thumbnailWidth: THUMBNAIL_WIDTH_PX,
21
18
  fetchOpts: { timeout: 3000 }
22
19
  }) => {
23
- var _a;
24
20
  try {
25
21
  // retries
26
- const retries = 0;
22
+ let retries = 0;
27
23
  const maxRetry = 5;
28
24
  const { getLinkPreview } = await import('link-preview-js');
29
25
  let previewLink = text;
@@ -39,17 +35,17 @@ const getUrlInfo = async (text, opts = {
39
35
  if (retries >= maxRetry) {
40
36
  return false;
41
37
  }
42
- if (forwardedURLObj.hostname === urlObj.hostname
43
- || forwardedURLObj.hostname === 'www.' + urlObj.hostname
44
- || 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
45
- retries + 1;
38
+ if (forwardedURLObj.hostname === urlObj.hostname ||
39
+ forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
40
+ 'www.' + forwardedURLObj.hostname === urlObj.hostname) {
41
+ retries += 1;
46
42
  return true;
47
43
  }
48
44
  else {
49
45
  return false;
50
46
  }
51
47
  },
52
- headers: opts.fetchOpts
48
+ headers: opts.fetchOpts?.headers
53
49
  });
54
50
  if (info && 'title' in info && info.title) {
55
51
  const [image] = info.images;
@@ -61,24 +57,20 @@ const getUrlInfo = async (text, opts = {
61
57
  originalThumbnailUrl: image
62
58
  };
63
59
  if (opts.uploadImage) {
64
- const { imageMessage } = await (0, messages_1.prepareWAMessageMedia)({ image: { url: image } }, {
60
+ const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, {
65
61
  upload: opts.uploadImage,
66
62
  mediaTypeOverride: 'thumbnail-link',
67
63
  options: opts.fetchOpts
68
64
  });
69
- urlInfo.jpegThumbnail = (imageMessage === null || imageMessage === void 0 ? void 0 : imageMessage.jpegThumbnail)
70
- ? Buffer.from(imageMessage.jpegThumbnail)
71
- : undefined;
65
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined;
72
66
  urlInfo.highQualityThumbnail = imageMessage || undefined;
73
67
  }
74
68
  else {
75
69
  try {
76
- urlInfo.jpegThumbnail = image
77
- ? (await getCompressedJpegThumbnail(image, opts)).buffer
78
- : undefined;
70
+ urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined;
79
71
  }
80
72
  catch (error) {
81
- (_a = opts.logger) === null || _a === void 0 ? void 0 : _a.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
73
+ opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
82
74
  }
83
75
  }
84
76
  return urlInfo;
@@ -90,4 +82,4 @@ const getUrlInfo = async (text, opts = {
90
82
  }
91
83
  }
92
84
  };
93
- exports.getUrlInfo = getUrlInfo;
85
+ //# sourceMappingURL=link-preview.js.map
@@ -1,4 +1,12 @@
1
- declare const _default: import("pino").Logger<{
2
- timestamp: () => string;
3
- }>;
1
+ export interface ILogger {
2
+ level: string;
3
+ child(obj: Record<string, unknown>): ILogger;
4
+ trace(obj: unknown, msg?: string): void;
5
+ debug(obj: unknown, msg?: string): void;
6
+ info(obj: unknown, msg?: string): void;
7
+ warn(obj: unknown, msg?: string): void;
8
+ error(obj: unknown, msg?: string): void;
9
+ }
10
+ declare const _default: import("pino").Logger<never, boolean>;
4
11
  export default _default;
12
+ //# sourceMappingURL=logger.d.ts.map
@@ -1,7 +1,3 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const pino_1 = __importDefault(require("pino"));
7
- exports.default = (0, pino_1.default)({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
1
+ import P from 'pino';
2
+ export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
3
+ //# sourceMappingURL=logger.js.map
@@ -1,12 +1,8 @@
1
- declare class d {
2
- salt: string;
3
- constructor(e: string);
4
- add(e: any, t: any): any;
5
- subtract(e: any, t: any): any;
6
- subtractThenAdd(e: any, t: any, r: any): any;
7
- _addSingle(e: any, t: any): ArrayBuffer;
8
- _subtractSingle(e: any, t: any): ArrayBuffer;
9
- performPointwiseWithOverflow(e: any, t: any, r: any): ArrayBuffer;
10
- }
11
- export declare const LT_HASH_ANTI_TAMPERING: d;
12
- export {};
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
2
+ /**
3
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
4
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
5
+ * if the same series of mutations was made sequentially.
6
+ */
7
+ export declare const LT_HASH_ANTI_TAMPERING: LTHashAntiTampering;
8
+ //# sourceMappingURL=lt-hash.d.ts.map
@@ -1,51 +1,8 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LT_HASH_ANTI_TAMPERING = void 0;
4
- const crypto_1 = require("./crypto");
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
5
2
  /**
6
3
  * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
7
4
  * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
8
5
  * if the same series of mutations was made sequentially.
9
6
  */
10
- const o = 128;
11
- class d {
12
- constructor(e) {
13
- this.salt = e;
14
- }
15
- add(e, t) {
16
- var r = this;
17
- for (const item of t) {
18
- e = r._addSingle(e, item);
19
- }
20
- return e;
21
- }
22
- subtract(e, t) {
23
- var r = this;
24
- for (const item of t) {
25
- e = r._subtractSingle(e, item);
26
- }
27
- return e;
28
- }
29
- subtractThenAdd(e, t, r) {
30
- var n = this;
31
- return n.add(n.subtract(e, r), t);
32
- }
33
- _addSingle(e, t) {
34
- var r = this;
35
- const n = new Uint8Array((0, crypto_1.hkdf)(Buffer.from(t), o, { info: r.salt })).buffer;
36
- return r.performPointwiseWithOverflow(e, n, ((e, t) => e + t));
37
- }
38
- _subtractSingle(e, t) {
39
- var r = this;
40
- const n = new Uint8Array((0, crypto_1.hkdf)(Buffer.from(t), o, { info: r.salt })).buffer;
41
- return r.performPointwiseWithOverflow(e, n, ((e, t) => e - t));
42
- }
43
- performPointwiseWithOverflow(e, t, r) {
44
- const n = new DataView(e), i = new DataView(t), a = new ArrayBuffer(n.byteLength), s = new DataView(a);
45
- for (let e = 0; e < n.byteLength; e += 2) {
46
- s.setUint16(e, r(n.getUint16(e, !0), i.getUint16(e, !0)), !0);
47
- }
48
- return a;
49
- }
50
- }
51
- exports.LT_HASH_ANTI_TAMPERING = new d('WhatsApp Patch Integrity');
7
+ export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();
8
+ //# sourceMappingURL=lt-hash.js.map
@@ -1,7 +1,9 @@
1
1
  export declare const makeMutex: () => {
2
- mutex<T>(code: () => T | Promise<T>): Promise<T>;
2
+ mutex<T>(code: () => Promise<T> | T): Promise<T>;
3
3
  };
4
4
  export type Mutex = ReturnType<typeof makeMutex>;
5
5
  export declare const makeKeyedMutex: () => {
6
- mutex<T>(key: string, task: () => T | Promise<T>): Promise<T>;
6
+ mutex<T>(key: string, task: () => Promise<T> | T): Promise<T>;
7
7
  };
8
+ export type KeyedMutex = ReturnType<typeof makeKeyedMutex>;
9
+ //# sourceMappingURL=make-mutex.d.ts.map