@dhilzzkz/baileys 0.0.0-stage → 0.1.1

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 (241) hide show
  1. package/LICENSE +23 -0
  2. package/NOTICE.md +37 -0
  3. package/README.md +2083 -2
  4. package/WAProto/index.d.ts +22220 -0
  5. package/WAProto/index.js +5 -0
  6. package/lib/Addon/http-error.d.ts +18 -0
  7. package/lib/Addon/http-error.js +40 -0
  8. package/lib/Addon/index.d.ts +3 -0
  9. package/lib/Addon/index.js +4 -0
  10. package/lib/Addon/keyed-db.d.ts +14 -0
  11. package/lib/Addon/keyed-db.js +241 -0
  12. package/lib/Addon/link-preview.d.ts +15 -0
  13. package/lib/Addon/link-preview.js +79 -0
  14. package/lib/Defaults/index.d.ts +188 -0
  15. package/lib/Defaults/index.js +185 -0
  16. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  17. package/lib/Signal/Group/ciphertext-message.js +11 -0
  18. package/lib/Signal/Group/group-cipher.d.ts +10 -0
  19. package/lib/Signal/Group/group-cipher.js +81 -0
  20. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/lib/Signal/Group/group-session-builder.js +29 -0
  22. package/lib/Signal/Group/index.d.ts +11 -0
  23. package/lib/Signal/Group/index.js +11 -0
  24. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  25. package/lib/Signal/Group/keyhelper.js +17 -0
  26. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  27. package/lib/Signal/Group/sender-chain-key.js +25 -0
  28. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  29. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  30. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-message.js +65 -0
  32. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  33. package/lib/Signal/Group/sender-key-name.js +47 -0
  34. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  35. package/lib/Signal/Group/sender-key-record.js +40 -0
  36. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  37. package/lib/Signal/Group/sender-key-state.js +83 -0
  38. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  39. package/lib/Signal/Group/sender-message-key.js +25 -0
  40. package/lib/Signal/Protocol/crypto.d.ts +6 -0
  41. package/lib/Signal/Protocol/crypto.js +61 -0
  42. package/lib/Signal/Protocol/curve.d.ts +8 -0
  43. package/lib/Signal/Protocol/curve.js +61 -0
  44. package/lib/Signal/Protocol/index.d.ts +16 -0
  45. package/lib/Signal/Protocol/index.js +9 -0
  46. package/lib/Signal/Protocol/internals.d.ts +57 -0
  47. package/lib/Signal/Protocol/internals.js +155 -0
  48. package/lib/Signal/Protocol/session-builder.d.ts +40 -0
  49. package/lib/Signal/Protocol/session-builder.js +143 -0
  50. package/lib/Signal/Protocol/session-cipher.d.ts +26 -0
  51. package/lib/Signal/Protocol/session-cipher.js +301 -0
  52. package/lib/Signal/Protocol/session-record.d.ts +55 -0
  53. package/lib/Signal/Protocol/session-record.js +272 -0
  54. package/lib/Signal/libsignal.d.ts +54 -0
  55. package/lib/Signal/libsignal.js +426 -0
  56. package/lib/Signal/lid-mapping.d.ts +20 -0
  57. package/lib/Signal/lid-mapping.js +274 -0
  58. package/lib/Socket/Client/index.d.ts +2 -0
  59. package/lib/Socket/Client/index.js +2 -0
  60. package/lib/Socket/Client/types.d.ts +5 -0
  61. package/lib/Socket/Client/types.js +10 -0
  62. package/lib/Socket/Client/websocket.d.ts +12 -0
  63. package/lib/Socket/Client/websocket.js +119 -0
  64. package/lib/Socket/business.d.ts +387 -0
  65. package/lib/Socket/business.js +380 -0
  66. package/lib/Socket/chats.d.ts +144 -0
  67. package/lib/Socket/chats.js +1216 -0
  68. package/lib/Socket/communities.d.ts +554 -0
  69. package/lib/Socket/communities.js +431 -0
  70. package/lib/Socket/groups.d.ts +286 -0
  71. package/lib/Socket/groups.js +347 -0
  72. package/lib/Socket/index.d.ts +522 -0
  73. package/lib/Socket/index.js +11 -0
  74. package/lib/Socket/messages-recv.d.ts +326 -0
  75. package/lib/Socket/messages-recv.js +1822 -0
  76. package/lib/Socket/messages-send.d.ts +321 -0
  77. package/lib/Socket/messages-send.js +1378 -0
  78. package/lib/Socket/mex.d.ts +1 -0
  79. package/lib/Socket/mex.js +41 -0
  80. package/lib/Socket/newsletter.d.ts +283 -0
  81. package/lib/Socket/newsletter.js +225 -0
  82. package/lib/Socket/socket.d.ts +61 -0
  83. package/lib/Socket/socket.js +992 -0
  84. package/lib/Store/index.d.ts +3 -0
  85. package/lib/Store/index.js +3 -0
  86. package/lib/Store/make-in-memory-store.d.ts +63 -0
  87. package/lib/Store/make-in-memory-store.js +418 -0
  88. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  89. package/lib/Store/make-ordered-dictionary.js +78 -0
  90. package/lib/Store/object-repository.d.ts +10 -0
  91. package/lib/Store/object-repository.js +23 -0
  92. package/lib/Types/Auth.d.ts +1 -0
  93. package/lib/Types/Auth.js +1 -0
  94. package/lib/Types/Business.d.ts +1 -0
  95. package/lib/Types/Business.js +1 -0
  96. package/lib/Types/Call.d.ts +1 -0
  97. package/lib/Types/Call.js +1 -0
  98. package/lib/Types/Chat.d.ts +1 -0
  99. package/lib/Types/Chat.js +7 -0
  100. package/lib/Types/Contact.d.ts +1 -0
  101. package/lib/Types/Contact.js +1 -0
  102. package/lib/Types/Events.d.ts +1 -0
  103. package/lib/Types/Events.js +1 -0
  104. package/lib/Types/GroupMetadata.d.ts +1 -0
  105. package/lib/Types/GroupMetadata.js +1 -0
  106. package/lib/Types/Label.d.ts +2 -0
  107. package/lib/Types/Label.js +24 -0
  108. package/lib/Types/LabelAssociation.d.ts +2 -0
  109. package/lib/Types/LabelAssociation.js +6 -0
  110. package/lib/Types/Message.d.ts +11 -0
  111. package/lib/Types/Message.js +17 -0
  112. package/lib/Types/Mex.d.ts +2 -0
  113. package/lib/Types/Mex.js +38 -0
  114. package/lib/Types/Product.d.ts +1 -0
  115. package/lib/Types/Product.js +1 -0
  116. package/lib/Types/RichType.d.ts +2 -0
  117. package/lib/Types/RichType.js +22 -0
  118. package/lib/Types/Signal.d.ts +1 -0
  119. package/lib/Types/Signal.js +1 -0
  120. package/lib/Types/Socket.d.ts +1 -0
  121. package/lib/Types/Socket.js +1 -0
  122. package/lib/Types/State.d.ts +5 -0
  123. package/lib/Types/State.js +54 -0
  124. package/lib/Types/USync.d.ts +1 -0
  125. package/lib/Types/USync.js +1 -0
  126. package/lib/Types/index.d.ts +13 -0
  127. package/lib/Types/index.js +25 -0
  128. package/lib/Utils/Auth/auth-utils.d.ts +58 -0
  129. package/lib/Utils/Auth/auth-utils.js +316 -0
  130. package/lib/Utils/Auth/companion-reg-client-utils.d.ts +4 -0
  131. package/lib/Utils/Auth/companion-reg-client-utils.js +39 -0
  132. package/lib/Utils/Auth/pre-key-manager.d.ts +25 -0
  133. package/lib/Utils/Auth/pre-key-manager.js +105 -0
  134. package/lib/Utils/Auth/use-multi-file-auth-state.d.ts +10 -0
  135. package/lib/Utils/Auth/use-multi-file-auth-state.js +116 -0
  136. package/lib/Utils/Auth/use-single-file-auth-state.d.ts +11 -0
  137. package/lib/Utils/Auth/use-single-file-auth-state.js +94 -0
  138. package/lib/Utils/Auth/use-sqlite-auth-state.d.ts +11 -0
  139. package/lib/Utils/Auth/use-sqlite-auth-state.js +109 -0
  140. package/lib/Utils/Auth/validate-connection.d.ts +44 -0
  141. package/lib/Utils/Auth/validate-connection.js +210 -0
  142. package/lib/Utils/Common/browser-utils.d.ts +9 -0
  143. package/lib/Utils/Common/browser-utils.js +28 -0
  144. package/lib/Utils/Common/generics.d.ts +63 -0
  145. package/lib/Utils/Common/generics.js +392 -0
  146. package/lib/Utils/Common/logger.d.ts +12 -0
  147. package/lib/Utils/Common/logger.js +12 -0
  148. package/lib/Utils/Common/make-mutex.d.ts +6 -0
  149. package/lib/Utils/Common/make-mutex.js +32 -0
  150. package/lib/Utils/Crypto/crypto.d.ts +39 -0
  151. package/lib/Utils/Crypto/crypto.js +117 -0
  152. package/lib/Utils/Crypto/lt-hash.d.ts +6 -0
  153. package/lib/Utils/Crypto/lt-hash.js +7 -0
  154. package/lib/Utils/Crypto/noise-handler.d.ts +20 -0
  155. package/lib/Utils/Crypto/noise-handler.js +200 -0
  156. package/lib/Utils/Crypto/signal.d.ts +82 -0
  157. package/lib/Utils/Crypto/signal.js +200 -0
  158. package/lib/Utils/Message/business.d.ts +49 -0
  159. package/lib/Utils/Message/business.js +230 -0
  160. package/lib/Utils/Message/decode-wa-message.d.ts +83 -0
  161. package/lib/Utils/Message/decode-wa-message.js +316 -0
  162. package/lib/Utils/Message/history.d.ts +75 -0
  163. package/lib/Utils/Message/history.js +133 -0
  164. package/lib/Utils/Message/link-preview.d.ts +13 -0
  165. package/lib/Utils/Message/link-preview.js +73 -0
  166. package/lib/Utils/Message/message-retry-manager.d.ts +79 -0
  167. package/lib/Utils/Message/message-retry-manager.js +259 -0
  168. package/lib/Utils/Message/messages-media.d.ts +134 -0
  169. package/lib/Utils/Message/messages-media.js +802 -0
  170. package/lib/Utils/Message/messages.d.ts +47 -0
  171. package/lib/Utils/Message/messages.js +1907 -0
  172. package/lib/Utils/Message/offline-node-processor.d.ts +10 -0
  173. package/lib/Utils/Message/offline-node-processor.js +40 -0
  174. package/lib/Utils/Message/process-message.d.ts +83 -0
  175. package/lib/Utils/Message/process-message.js +748 -0
  176. package/lib/Utils/Message/reporting-utils.d.ts +12 -0
  177. package/lib/Utils/Message/reporting-utils.js +257 -0
  178. package/lib/Utils/Message/rich-message-utils.d.ts +48 -0
  179. package/lib/Utils/Message/rich-message-utils.js +366 -0
  180. package/lib/Utils/Message/stanza-ack.d.ts +16 -0
  181. package/lib/Utils/Message/stanza-ack.js +37 -0
  182. package/lib/Utils/State/chat-utils.d.ts +408 -0
  183. package/lib/Utils/State/chat-utils.js +871 -0
  184. package/lib/Utils/State/event-buffer.d.ts +12 -0
  185. package/lib/Utils/State/event-buffer.js +621 -0
  186. package/lib/Utils/State/identity-change-handler.d.ts +13 -0
  187. package/lib/Utils/State/identity-change-handler.js +48 -0
  188. package/lib/Utils/State/sync-action-utils.d.ts +2 -0
  189. package/lib/Utils/State/sync-action-utils.js +48 -0
  190. package/lib/Utils/State/tc-token-utils.d.ts +29 -0
  191. package/lib/Utils/State/tc-token-utils.js +163 -0
  192. package/lib/Utils/index.d.ts +24 -0
  193. package/lib/Utils/index.js +24 -0
  194. package/lib/WABinary/constants.d.ts +61 -0
  195. package/lib/WABinary/constants.js +1466 -0
  196. package/lib/WABinary/decode.d.ts +9 -0
  197. package/lib/WABinary/decode.js +261 -0
  198. package/lib/WABinary/encode.d.ts +2 -0
  199. package/lib/WABinary/encode.js +219 -0
  200. package/lib/WABinary/generic-utils.d.ts +79 -0
  201. package/lib/WABinary/generic-utils.js +226 -0
  202. package/lib/WABinary/index.d.ts +5 -0
  203. package/lib/WABinary/index.js +5 -0
  204. package/lib/WABinary/jid-utils.d.ts +28 -0
  205. package/lib/WABinary/jid-utils.js +95 -0
  206. package/lib/WABinary/types.d.ts +1 -0
  207. package/lib/WABinary/types.js +1 -0
  208. package/lib/WAM/BinaryInfo.d.ts +7 -0
  209. package/lib/WAM/BinaryInfo.js +9 -0
  210. package/lib/WAM/constants.d.ts +34926 -0
  211. package/lib/WAM/constants.js +22852 -0
  212. package/lib/WAM/encode.d.ts +1 -0
  213. package/lib/WAM/encode.js +149 -0
  214. package/lib/WAM/index.d.ts +3 -0
  215. package/lib/WAM/index.js +3 -0
  216. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +38 -0
  217. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +50 -0
  218. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  219. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  220. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  221. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  222. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  223. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  224. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +14 -0
  225. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +28 -0
  226. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  227. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  228. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  229. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  230. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  231. package/lib/WAUSync/Protocols/index.js +5 -0
  232. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  233. package/lib/WAUSync/USyncQuery.js +97 -0
  234. package/lib/WAUSync/USyncUser.d.ts +16 -0
  235. package/lib/WAUSync/USyncUser.js +30 -0
  236. package/lib/WAUSync/index.d.ts +3 -0
  237. package/lib/WAUSync/index.js +3 -0
  238. package/lib/index.d.ts +11 -0
  239. package/lib/index.js +11 -0
  240. package/package.json +120 -5
  241. package/scripts/engine-requirements.js +16 -0
@@ -0,0 +1,75 @@
1
+ export function downloadHistory(msg: any, options: any): Promise<proto.HistorySync & proto.HistorySync.$Shape>;
2
+ export function processHistoryMessage(item: any, logger: any): {
3
+ chats: any[];
4
+ contacts: ({
5
+ id: any;
6
+ name: any;
7
+ username: any;
8
+ lid: any;
9
+ phoneNumber: any;
10
+ verifiedName?: undefined;
11
+ notify?: undefined;
12
+ } | {
13
+ id: any;
14
+ verifiedName: any;
15
+ name?: undefined;
16
+ username?: undefined;
17
+ lid?: undefined;
18
+ phoneNumber?: undefined;
19
+ notify?: undefined;
20
+ } | {
21
+ id: any;
22
+ notify: any;
23
+ name?: undefined;
24
+ username?: undefined;
25
+ lid?: undefined;
26
+ phoneNumber?: undefined;
27
+ verifiedName?: undefined;
28
+ })[];
29
+ messages: any[];
30
+ lidPnMappings: {
31
+ lid: any;
32
+ pn: any;
33
+ }[];
34
+ pastParticipants: any;
35
+ syncType: any;
36
+ progress: any;
37
+ };
38
+ export function downloadAndProcessHistorySyncNotification(msg: any, options: any, logger: any): Promise<{
39
+ chats: any[];
40
+ contacts: ({
41
+ id: any;
42
+ name: any;
43
+ username: any;
44
+ lid: any;
45
+ phoneNumber: any;
46
+ verifiedName?: undefined;
47
+ notify?: undefined;
48
+ } | {
49
+ id: any;
50
+ verifiedName: any;
51
+ name?: undefined;
52
+ username?: undefined;
53
+ lid?: undefined;
54
+ phoneNumber?: undefined;
55
+ notify?: undefined;
56
+ } | {
57
+ id: any;
58
+ notify: any;
59
+ name?: undefined;
60
+ username?: undefined;
61
+ lid?: undefined;
62
+ phoneNumber?: undefined;
63
+ verifiedName?: undefined;
64
+ })[];
65
+ messages: any[];
66
+ lidPnMappings: {
67
+ lid: any;
68
+ pn: any;
69
+ }[];
70
+ pastParticipants: any;
71
+ syncType: any;
72
+ progress: any;
73
+ }>;
74
+ export function getHistoryMsg(message: any): any;
75
+ import { proto } from '../../../WAProto/index.js';
@@ -0,0 +1,133 @@
1
+ import { pipeline } from 'node:stream/promises';
2
+ import { promisify } from 'node:util';
3
+ import { createInflate, inflate } from 'node: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 '../Common/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
+ }
23
+ }
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);
36
+ return syncData;
37
+ };
38
+ export const processHistoryMessage = (item, logger) => {
39
+ const messages = [];
40
+ const contacts = [];
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
+ }
50
+ switch (item.syncType) {
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:
55
+ for (const chat of item.conversations) {
56
+ contacts.push({
57
+ id: chat.id,
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
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
+ }
79
+ const msgs = chat.messages || [];
80
+ delete chat.messages;
81
+ for (const item of msgs) {
82
+ const message = item.message;
83
+ messages.push(message);
84
+ if (!chat.messages?.length) {
85
+ // keep only the most recent message in the chat array
86
+ chat.messages = [{ message }];
87
+ }
88
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
89
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
90
+ }
91
+ if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
92
+ message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
93
+ message.messageStubParameters?.[0]) {
94
+ contacts.push({
95
+ id: message.key.participant || message.key.remoteJid,
96
+ verifiedName: message.messageStubParameters?.[0]
97
+ });
98
+ }
99
+ }
100
+ chats.push(chat);
101
+ }
102
+ break;
103
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
104
+ for (const c of item.pushnames) {
105
+ contacts.push({ id: c.id, notify: c.pushname });
106
+ }
107
+ break;
108
+ }
109
+ return {
110
+ chats,
111
+ contacts,
112
+ messages,
113
+ lidPnMappings,
114
+ pastParticipants: item.pastParticipants,
115
+ syncType: item.syncType,
116
+ progress: item.progress
117
+ };
118
+ };
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);
128
+ };
129
+ export const getHistoryMsg = (message) => {
130
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
131
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
132
+ return anyHistoryMsg;
133
+ };
@@ -0,0 +1,13 @@
1
+ export function getUrlInfo(text: any, opts?: {
2
+ thumbnailWidth: number;
3
+ fetchOpts: {
4
+ timeout: number;
5
+ };
6
+ }): Promise<{
7
+ 'canonical-url': string;
8
+ 'matched-text': any;
9
+ title: any;
10
+ description: any;
11
+ originalThumbnailUrl: any;
12
+ 'preview-type': number;
13
+ } | undefined>;
@@ -0,0 +1,73 @@
1
+ import { getLinkPreview } from '../../Addon/index.js';
2
+ import { prepareWAMessageMedia } from './messages.js';
3
+ import { extractImageThumb, getHttpStream } from './messages-media.js';
4
+ const URL_PROTOCOL_REGEX = /^https?:\/\//;
5
+ const THUMBNAIL_WIDTH_PX = 192;
6
+ /** Fetches an image and generates a thumbnail for it */
7
+ const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
8
+ const stream = await getHttpStream(url, fetchOpts);
9
+ const result = await extractImageThumb(stream, thumbnailWidth);
10
+ return result;
11
+ };
12
+ /**
13
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
14
+ * Return undefined if the fetch failed or no URL was found
15
+ * @param text first matched URL in text
16
+ * @returns the URL info required to generate link preview
17
+ */
18
+ export const getUrlInfo = async (text, opts = {
19
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
20
+ fetchOpts: { timeout: 3000 }
21
+ }) => {
22
+ try {
23
+ const previewLink = URL_PROTOCOL_REGEX.test(text) ? text : 'https://' + text;
24
+ const info = await getLinkPreview(previewLink, opts.fetchOpts.timeout);
25
+ if (info?.title) {
26
+ const urlInfo = {
27
+ 'canonical-url': info.url,
28
+ 'matched-text': text,
29
+ title: info.title,
30
+ description: info.description,
31
+ originalThumbnailUrl: info.image,
32
+ 'preview-type': info.video ? 1 : 0
33
+ };
34
+ if (opts.uploadImage) {
35
+ await Promise.all([
36
+ (async () => {
37
+ const { imageMessage } = await prepareWAMessageMedia({ image: { url: info.image } }, {
38
+ upload: opts.uploadImage,
39
+ mediaTypeOverride: 'thumbnail-link',
40
+ options: opts.fetchOpts
41
+ });
42
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined;
43
+ urlInfo.highQualityThumbnail = imageMessage;
44
+ })(),
45
+ info.favicon
46
+ ? (async () => {
47
+ const { imageMessage } = await prepareWAMessageMedia({ image: { url: info.favicon } }, {
48
+ upload: opts.uploadImage,
49
+ mediaTypeOverride: 'thumbnail-link',
50
+ options: opts.fetchOpts
51
+ });
52
+ urlInfo.favicon = imageMessage;
53
+ })()
54
+ : Promise.resolve()
55
+ ]);
56
+ }
57
+ else {
58
+ try {
59
+ urlInfo.jpegThumbnail = info.image ? (await getCompressedJpegThumbnail(info.image, opts)).buffer : undefined;
60
+ }
61
+ catch (error) {
62
+ opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail');
63
+ }
64
+ }
65
+ return urlInfo;
66
+ }
67
+ }
68
+ catch (error) {
69
+ if (!error.message.includes('receive a valid')) {
70
+ throw error;
71
+ }
72
+ }
73
+ };
@@ -0,0 +1,79 @@
1
+ export const RetryReason: any;
2
+ export class MessageRetryManager {
3
+ constructor(logger: any, maxMsgRetryCount: any);
4
+ logger: any;
5
+ recentMessagesMap: any;
6
+ messageKeyIndex: Map<any, any>;
7
+ sessionRecreateHistory: any;
8
+ retryCounters: any;
9
+ baseKeys: any;
10
+ pendingPhoneRequests: {};
11
+ maxMsgRetryCount: any;
12
+ statistics: {
13
+ totalRetries: number;
14
+ successfulRetries: number;
15
+ failedRetries: number;
16
+ mediaRetries: number;
17
+ sessionRecreations: number;
18
+ phoneRequests: number;
19
+ };
20
+ /**
21
+ * Add a recent message to the cache for retry handling
22
+ */
23
+ addRecentMessage(to: any, id: any, message: any): void;
24
+ /**
25
+ * Get a recent message from the cache
26
+ */
27
+ getRecentMessage(to: any, id: any): any;
28
+ /**
29
+ * Check if a session should be recreated based on retry count, history, and error code.
30
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
31
+ */
32
+ shouldRecreateSession(jid: any, hasSession: any, errorCode: any): {
33
+ reason: string;
34
+ recreate: boolean;
35
+ };
36
+ /**
37
+ * Parse error code from retry receipt's retry node.
38
+ * Returns undefined if no error code is present.
39
+ */
40
+ parseRetryErrorCode(errorAttr: any): any;
41
+ /**
42
+ * Check if an error code indicates a MAC failure
43
+ */
44
+ isMacError(errorCode: any): boolean;
45
+ /**
46
+ * Increment retry counter for a message
47
+ */
48
+ incrementRetryCount(messageId: any): any;
49
+ /**
50
+ * Get retry count for a message
51
+ */
52
+ getRetryCount(messageId: any): any;
53
+ /**
54
+ * Check if message has exceeded maximum retry attempts
55
+ */
56
+ hasExceededMaxRetries(messageId: any): boolean;
57
+ /**
58
+ * Mark retry as successful
59
+ */
60
+ markRetrySuccess(messageId: any): void;
61
+ /**
62
+ * Mark retry as failed
63
+ */
64
+ markRetryFailed(messageId: any): void;
65
+ /**
66
+ * Schedule a phone request with delay
67
+ */
68
+ schedulePhoneRequest(messageId: any, callback: any, delay?: number): void;
69
+ /**
70
+ * Cancel pending phone request
71
+ */
72
+ cancelPendingPhoneRequest(messageId: any): void;
73
+ clear(): void;
74
+ saveBaseKey(addr: any, msgId: any, baseKey: any): void;
75
+ hasSameBaseKey(addr: any, msgId: any, baseKey: any): boolean;
76
+ deleteBaseKey(addr: any, msgId: any): void;
77
+ keyToString(key: any): string;
78
+ removeRecentMessage(messageId: any): void;
79
+ }
@@ -0,0 +1,259 @@
1
+ import { createCache } from '../../Addon/index.js';
2
+ /** Number of sent messages to cache in memory for handling retry receipts */
3
+ const RECENT_MESSAGES_SIZE = 1024;
4
+ const MESSAGE_KEY_SEPARATOR = '\u0000';
5
+ /** Timeout for session recreation - 1 hour */
6
+ const RECREATE_SESSION_TIMEOUT = 60 * 60; // 1 hour in milliseconds
7
+ const PHONE_REQUEST_DELAY = 3000;
8
+ // Retry reason codes matching WhatsApp Web's Signal error codes.
9
+ export var RetryReason;
10
+ (function (RetryReason) {
11
+ RetryReason[RetryReason["UnknownError"] = 0] = "UnknownError";
12
+ RetryReason[RetryReason["SignalErrorNoSession"] = 1] = "SignalErrorNoSession";
13
+ RetryReason[RetryReason["SignalErrorInvalidKey"] = 2] = "SignalErrorInvalidKey";
14
+ RetryReason[RetryReason["SignalErrorInvalidKeyId"] = 3] = "SignalErrorInvalidKeyId";
15
+ /** MAC verification failed - most common cause of decryption failures */
16
+ RetryReason[RetryReason["SignalErrorInvalidMessage"] = 4] = "SignalErrorInvalidMessage";
17
+ RetryReason[RetryReason["SignalErrorInvalidSignature"] = 5] = "SignalErrorInvalidSignature";
18
+ RetryReason[RetryReason["SignalErrorFutureMessage"] = 6] = "SignalErrorFutureMessage";
19
+ /** Explicit MAC failure - session is definitely out of sync */
20
+ RetryReason[RetryReason["SignalErrorBadMac"] = 7] = "SignalErrorBadMac";
21
+ RetryReason[RetryReason["SignalErrorInvalidSession"] = 8] = "SignalErrorInvalidSession";
22
+ RetryReason[RetryReason["SignalErrorInvalidMsgKey"] = 9] = "SignalErrorInvalidMsgKey";
23
+ RetryReason[RetryReason["BadBroadcastEphemeralSetting"] = 10] = "BadBroadcastEphemeralSetting";
24
+ RetryReason[RetryReason["UnknownCompanionNoPrekey"] = 11] = "UnknownCompanionNoPrekey";
25
+ RetryReason[RetryReason["AdvFailure"] = 12] = "AdvFailure";
26
+ RetryReason[RetryReason["StatusRevokeDelay"] = 13] = "StatusRevokeDelay";
27
+ })(RetryReason || (RetryReason = {}));
28
+ /** Error codes that indicate a MAC failure and require immediate session recreation */
29
+ const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac]);
30
+ export class MessageRetryManager {
31
+ constructor(logger, maxMsgRetryCount) {
32
+ this.logger = logger;
33
+ this.recentMessagesMap = createCache({
34
+ max: RECENT_MESSAGES_SIZE,
35
+ ttl: 5 * 60,
36
+ dispose: (_value, key) => {
37
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR);
38
+ if (separatorIndex > -1) {
39
+ const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length);
40
+ this.messageKeyIndex.delete(messageId);
41
+ }
42
+ }
43
+ });
44
+ this.messageKeyIndex = new Map();
45
+ this.sessionRecreateHistory = createCache({
46
+ ttl: RECREATE_SESSION_TIMEOUT * 2
47
+ });
48
+ this.retryCounters = createCache({
49
+ ttl: 15 * 60
50
+ }); // 15 minutes TTL
51
+ this.baseKeys = createCache({
52
+ max: 1024,
53
+ ttl: 15 * 60
54
+ });
55
+ this.pendingPhoneRequests = {};
56
+ this.maxMsgRetryCount = 5;
57
+ this.statistics = {
58
+ totalRetries: 0,
59
+ successfulRetries: 0,
60
+ failedRetries: 0,
61
+ mediaRetries: 0,
62
+ sessionRecreations: 0,
63
+ phoneRequests: 0
64
+ };
65
+ this.maxMsgRetryCount = maxMsgRetryCount;
66
+ }
67
+ /**
68
+ * Add a recent message to the cache for retry handling
69
+ */
70
+ addRecentMessage(to, id, message) {
71
+ const key = { to, id };
72
+ const keyStr = this.keyToString(key);
73
+ // Add new message
74
+ this.recentMessagesMap.set(keyStr, {
75
+ message,
76
+ timestamp: Date.now()
77
+ });
78
+ this.messageKeyIndex.set(id, keyStr);
79
+ this.logger.debug(`Added message to retry cache: ${to}/${id}`);
80
+ }
81
+ /**
82
+ * Get a recent message from the cache
83
+ */
84
+ getRecentMessage(to, id) {
85
+ const key = { to, id };
86
+ const keyStr = this.keyToString(key);
87
+ return this.recentMessagesMap.get(keyStr);
88
+ }
89
+ /**
90
+ * Check if a session should be recreated based on retry count, history, and error code.
91
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
92
+ */
93
+ shouldRecreateSession(jid, hasSession, errorCode) {
94
+ // If we don't have a session, always recreate
95
+ if (!hasSession) {
96
+ this.sessionRecreateHistory.set(jid, Date.now());
97
+ this.statistics.sessionRecreations++;
98
+ return {
99
+ reason: "we don't have a Signal session with them",
100
+ recreate: true
101
+ };
102
+ }
103
+ // IMMEDIATE recreation for MAC errors - session is definitely out of sync
104
+ if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
105
+ this.sessionRecreateHistory.set(jid, Date.now());
106
+ this.statistics.sessionRecreations++;
107
+ this.logger.warn({ jid, errorCode: RetryReason[errorCode] }, 'MAC error detected, forcing immediate session recreation');
108
+ return {
109
+ reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
110
+ recreate: true
111
+ };
112
+ }
113
+ const now = Date.now();
114
+ const prevTime = this.sessionRecreateHistory.get(jid);
115
+ // If no previous recreation or it's been more than an hour
116
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
117
+ this.sessionRecreateHistory.set(jid, now);
118
+ this.statistics.sessionRecreations++;
119
+ return {
120
+ reason: 'retry count > 1 and over an hour since last recreation',
121
+ recreate: true
122
+ };
123
+ }
124
+ return { reason: '', recreate: false };
125
+ }
126
+ /**
127
+ * Parse error code from retry receipt's retry node.
128
+ * Returns undefined if no error code is present.
129
+ */
130
+ parseRetryErrorCode(errorAttr) {
131
+ if (errorAttr === undefined || errorAttr === '') {
132
+ return undefined;
133
+ }
134
+ const code = parseInt(errorAttr, 10);
135
+ if (Number.isNaN(code)) {
136
+ return undefined;
137
+ }
138
+ // Validate it's a known RetryReason
139
+ if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
140
+ return code;
141
+ }
142
+ return RetryReason.UnknownError;
143
+ }
144
+ /**
145
+ * Check if an error code indicates a MAC failure
146
+ */
147
+ isMacError(errorCode) {
148
+ return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode);
149
+ }
150
+ /**
151
+ * Increment retry counter for a message
152
+ */
153
+ incrementRetryCount(messageId) {
154
+ this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
155
+ this.statistics.totalRetries++;
156
+ return this.retryCounters.get(messageId);
157
+ }
158
+ /**
159
+ * Get retry count for a message
160
+ */
161
+ getRetryCount(messageId) {
162
+ return this.retryCounters.get(messageId) || 0;
163
+ }
164
+ /**
165
+ * Check if message has exceeded maximum retry attempts
166
+ */
167
+ hasExceededMaxRetries(messageId) {
168
+ return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
169
+ }
170
+ /**
171
+ * Mark retry as successful
172
+ */
173
+ markRetrySuccess(messageId) {
174
+ this.statistics.successfulRetries++;
175
+ // Clean up retry counter for successful message
176
+ this.retryCounters.del(messageId);
177
+ this.cancelPendingPhoneRequest(messageId);
178
+ this.removeRecentMessage(messageId);
179
+ }
180
+ /**
181
+ * Mark retry as failed
182
+ */
183
+ markRetryFailed(messageId) {
184
+ this.statistics.failedRetries++;
185
+ this.retryCounters.del(messageId);
186
+ this.cancelPendingPhoneRequest(messageId);
187
+ this.removeRecentMessage(messageId);
188
+ }
189
+ /**
190
+ * Schedule a phone request with delay
191
+ */
192
+ schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
193
+ // Cancel any existing request for this message
194
+ this.cancelPendingPhoneRequest(messageId);
195
+ this.pendingPhoneRequests[messageId] = setTimeout(() => {
196
+ delete this.pendingPhoneRequests[messageId];
197
+ this.statistics.phoneRequests++;
198
+ callback();
199
+ }, delay);
200
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
201
+ }
202
+ /**
203
+ * Cancel pending phone request
204
+ */
205
+ cancelPendingPhoneRequest(messageId) {
206
+ const timeout = this.pendingPhoneRequests[messageId];
207
+ if (timeout) {
208
+ clearTimeout(timeout);
209
+ delete this.pendingPhoneRequests[messageId];
210
+ this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
211
+ }
212
+ }
213
+ clear() {
214
+ this.recentMessagesMap.flushAll();
215
+ this.messageKeyIndex.clear();
216
+ this.sessionRecreateHistory.flushAll();
217
+ this.retryCounters.flushAll();
218
+ this.baseKeys.flushAll();
219
+ for (const messageId of Object.keys(this.pendingPhoneRequests)) {
220
+ this.cancelPendingPhoneRequest(messageId);
221
+ }
222
+ this.statistics = {
223
+ totalRetries: 0,
224
+ successfulRetries: 0,
225
+ failedRetries: 0,
226
+ mediaRetries: 0,
227
+ sessionRecreations: 0,
228
+ phoneRequests: 0
229
+ };
230
+ }
231
+ saveBaseKey(addr, msgId, baseKey) {
232
+ this.baseKeys.set(`${addr}:${msgId}`, baseKey);
233
+ }
234
+ hasSameBaseKey(addr, msgId, baseKey) {
235
+ const stored = this.baseKeys.get(`${addr}:${msgId}`);
236
+ if (!stored || stored.length !== baseKey.length) {
237
+ return false;
238
+ }
239
+ for (let i = 0; i < stored.length; i++) {
240
+ if (stored[i] !== baseKey[i])
241
+ return false;
242
+ }
243
+ return true;
244
+ }
245
+ deleteBaseKey(addr, msgId) {
246
+ this.baseKeys.del(`${addr}:${msgId}`);
247
+ }
248
+ keyToString(key) {
249
+ return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
250
+ }
251
+ removeRecentMessage(messageId) {
252
+ const keyStr = this.messageKeyIndex.get(messageId);
253
+ if (!keyStr) {
254
+ return;
255
+ }
256
+ this.recentMessagesMap.del(keyStr);
257
+ this.messageKeyIndex.delete(messageId);
258
+ }
259
+ }