@badzz88/baileys 8.5.7 → 8.5.9

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 (142) hide show
  1. package/README.md +337 -1055
  2. package/WAProto/WAProto.proto +284 -264
  3. package/WAProto/index.js +5 -5
  4. package/engine-requirements.js +7 -15
  5. package/lib/Defaults/index.js +130 -187
  6. package/lib/Signal/Group/ciphertext-message.js +11 -14
  7. package/lib/Signal/Group/group-session-builder.js +29 -91
  8. package/lib/Signal/Group/group_cipher.js +81 -88
  9. package/lib/Signal/Group/index.js +12 -136
  10. package/lib/Signal/Group/keyhelper.js +15 -70
  11. package/lib/Signal/Group/sender-chain-key.js +25 -31
  12. package/lib/Signal/Group/sender-key-distribution-message.js +62 -65
  13. package/lib/Signal/Group/sender-key-message.js +65 -68
  14. package/lib/Signal/Group/sender-key-name.js +41 -43
  15. package/lib/Signal/Group/sender-key-record.js +40 -43
  16. package/lib/Signal/Group/sender-key-state.js +83 -96
  17. package/lib/Signal/Group/sender-message-key.js +25 -29
  18. package/lib/Signal/libsignal.js +425 -453
  19. package/lib/Signal/lid-mapping.js +276 -259
  20. package/lib/Socket/Client/index.js +3 -30
  21. package/lib/Socket/Client/types.js +10 -12
  22. package/lib/Socket/Client/websocket.js +53 -61
  23. package/lib/Socket/business.js +379 -422
  24. package/lib/Socket/chats.js +1193 -1816
  25. package/lib/Socket/communities.js +431 -549
  26. package/lib/Socket/graphql.js +672 -612
  27. package/lib/Socket/groups.js +374 -764
  28. package/lib/Socket/index.js +17 -38
  29. package/lib/Socket/interop.js +417 -503
  30. package/lib/Socket/messages-recv.js +1915 -2441
  31. package/lib/Socket/messages-send.js +1213 -1630
  32. package/lib/Socket/mex.js +9 -15
  33. package/lib/Socket/newsletter.js +746 -808
  34. package/lib/Socket/privacy.js +310 -441
  35. package/lib/Socket/socket.js +1025 -1022
  36. package/lib/Socket/username.js +8 -15
  37. package/lib/Store/index.js +10 -36
  38. package/lib/Store/make-cache-manager-store.js +80 -85
  39. package/lib/Store/make-in-memory-store.js +231 -591
  40. package/lib/Store/make-ordered-dictionary.js +72 -78
  41. package/lib/Store/object-repository.js +28 -25
  42. package/lib/Types/Auth.js +2 -38
  43. package/lib/Types/Bussines.js +2 -2
  44. package/lib/Types/Call.js +2 -2
  45. package/lib/Types/Chat.js +8 -4
  46. package/lib/Types/Contact.js +2 -2
  47. package/lib/Types/Events.js +2 -2
  48. package/lib/Types/GroupMetadata.js +2 -2
  49. package/lib/Types/Label.js +24 -26
  50. package/lib/Types/LabelAssociation.js +6 -8
  51. package/lib/Types/Message.js +11 -95
  52. package/lib/Types/Mex.js +111 -112
  53. package/lib/Types/Product.js +2 -2
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.js +3 -2
  56. package/lib/Types/State.js +56 -70
  57. package/lib/Types/USync.js +2 -2
  58. package/lib/Types/index.js +26 -55
  59. package/lib/Utils/auth-utils.js +288 -292
  60. package/lib/Utils/browser-utils.js +47 -113
  61. package/lib/Utils/business.js +224 -240
  62. package/lib/Utils/chat-utils.js +869 -1205
  63. package/lib/Utils/companion-reg-client-utils.js +34 -41
  64. package/lib/Utils/crypto.js +107 -144
  65. package/lib/Utils/decode-wa-message.js +308 -518
  66. package/lib/Utils/event-buffer.js +611 -596
  67. package/lib/Utils/generics.js +355 -515
  68. package/lib/Utils/history.js +134 -244
  69. package/lib/Utils/identity-change-handler.js +49 -51
  70. package/lib/Utils/index.js +23 -57
  71. package/lib/Utils/link-preview.js +77 -135
  72. package/lib/Utils/logger.js +3 -9
  73. package/lib/Utils/lt-hash.js +6 -37
  74. package/lib/Utils/make-mutex.js +33 -36
  75. package/lib/Utils/message-composer.js +233 -439
  76. package/lib/Utils/message-retry-manager.js +260 -265
  77. package/lib/Utils/messages-media.js +829 -855
  78. package/lib/Utils/messages.js +961 -2528
  79. package/lib/Utils/noise-handler.js +200 -195
  80. package/lib/Utils/offline-node-processor.js +33 -35
  81. package/lib/Utils/pre-key-manager.js +102 -103
  82. package/lib/Utils/process-message.js +560 -978
  83. package/lib/Utils/reporting-utils.js +253 -257
  84. package/lib/Utils/signal.js +195 -218
  85. package/lib/Utils/stanza-ack.js +29 -31
  86. package/lib/Utils/sticker.js +109 -144
  87. package/lib/Utils/sync-action-utils.js +45 -50
  88. package/lib/Utils/tc-token-utils.js +139 -137
  89. package/lib/Utils/use-multi-file-auth-state.js +109 -109
  90. package/lib/Utils/validate-connection.js +202 -218
  91. package/lib/WABinary/constants.js +1299 -1302
  92. package/lib/WABinary/decode.js +262 -343
  93. package/lib/WABinary/encode.js +4 -12
  94. package/lib/WABinary/generic-utils.js +187 -223
  95. package/lib/WABinary/index.js +6 -33
  96. package/lib/WABinary/jid-utils.js +88 -351
  97. package/lib/WABinary/types.js +2 -2
  98. package/lib/WAM/BinaryInfo.js +9 -12
  99. package/lib/WAM/constants.js +22853 -39486
  100. package/lib/WAM/encode.js +140 -132
  101. package/lib/WAM/index.js +4 -31
  102. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +21 -23
  103. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +9 -9
  104. package/lib/WAUSync/Protocols/USyncContactProtocol.js +7 -7
  105. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +10 -10
  106. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +7 -7
  107. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +11 -12
  108. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +4 -5
  109. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +7 -7
  110. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +7 -8
  111. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -7
  112. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +8 -8
  113. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +7 -7
  114. package/lib/WAUSync/Protocols/index.js +12 -39
  115. package/lib/WAUSync/USyncQuery.js +67 -49
  116. package/lib/WAUSync/USyncUser.js +11 -5
  117. package/lib/WAUSync/index.js +3 -31
  118. package/lib/index.js +15 -48
  119. package/package.json +129 -99
  120. package/LICENSE +0 -21
  121. package/lib/Defaults/phonenumber-mcc.json +0 -223
  122. package/lib/Socket/aigroups.js +0 -240
  123. package/lib/Socket/interactive-handler.js +0 -522
  124. package/lib/Socket/managed-account.js +0 -183
  125. package/lib/Socket/registration.js +0 -427
  126. package/lib/Socket/text-router.js +0 -83
  127. package/lib/Types/Newsletter.js +0 -121
  128. package/lib/Utils/command-loader.d.ts +0 -31
  129. package/lib/Utils/command-loader.js +0 -100
  130. package/lib/Utils/consumer-application.js +0 -107
  131. package/lib/Utils/curve25519-js.js +0 -275
  132. package/lib/Utils/group-history.js +0 -60
  133. package/lib/Utils/jid-display-normalization.js +0 -218
  134. package/lib/Utils/meta-ai-msmsg.js +0 -262
  135. package/lib/Utils/native-bridge.js +0 -82
  136. package/lib/Utils/session-pool.d.ts +0 -16
  137. package/lib/Utils/session-pool.js +0 -94
  138. package/lib/Utils/sticker.d.ts +0 -17
  139. package/lib/Utils/view-once-cache.d.ts +0 -9
  140. package/lib/Utils/view-once-cache.js +0 -79
  141. package/lib/Utils/voip-rekey.js +0 -22
  142. package/lib/antiban.js +0 -4637
@@ -1,270 +1,265 @@
1
- 'use strict'
2
- Object.defineProperty(exports, '__esModule', { value: true })
3
- exports.MessageRetryManager = exports.RetryReason = void 0
4
- const lru_cache_1 = require('lru-cache')
1
+ import { LRUCache } from 'lru-cache';
5
2
  /** Number of sent messages to cache in memory for handling retry receipts */
6
- const RECENT_MESSAGES_SIZE = 512
7
- const MESSAGE_KEY_SEPARATOR = '\u0000'
3
+ const RECENT_MESSAGES_SIZE = 512;
4
+ const MESSAGE_KEY_SEPARATOR = '\u0000';
8
5
  /** Timeout for session recreation - 1 hour */
9
- const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000 // 1 hour in milliseconds
10
- const PHONE_REQUEST_DELAY = 3000
6
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000; // 1 hour in milliseconds
7
+ const PHONE_REQUEST_DELAY = 3000;
11
8
  // Retry reason codes matching WhatsApp Web's Signal error codes.
12
- var RetryReason
13
- ;(function (RetryReason) {
14
- RetryReason[(RetryReason['UnknownError'] = 0)] = 'UnknownError'
15
- RetryReason[(RetryReason['SignalErrorNoSession'] = 1)] = 'SignalErrorNoSession'
16
- RetryReason[(RetryReason['SignalErrorInvalidKey'] = 2)] = 'SignalErrorInvalidKey'
17
- RetryReason[(RetryReason['SignalErrorInvalidKeyId'] = 3)] = 'SignalErrorInvalidKeyId'
18
- /** MAC verification failed - most common cause of decryption failures */
19
- RetryReason[(RetryReason['SignalErrorInvalidMessage'] = 4)] = 'SignalErrorInvalidMessage'
20
- RetryReason[(RetryReason['SignalErrorInvalidSignature'] = 5)] = 'SignalErrorInvalidSignature'
21
- RetryReason[(RetryReason['SignalErrorFutureMessage'] = 6)] = 'SignalErrorFutureMessage'
22
- /** Explicit MAC failure - session is definitely out of sync */
23
- RetryReason[(RetryReason['SignalErrorBadMac'] = 7)] = 'SignalErrorBadMac'
24
- RetryReason[(RetryReason['SignalErrorInvalidSession'] = 8)] = 'SignalErrorInvalidSession'
25
- RetryReason[(RetryReason['SignalErrorInvalidMsgKey'] = 9)] = 'SignalErrorInvalidMsgKey'
26
- RetryReason[(RetryReason['BadBroadcastEphemeralSetting'] = 10)] = 'BadBroadcastEphemeralSetting'
27
- RetryReason[(RetryReason['UnknownCompanionNoPrekey'] = 11)] = 'UnknownCompanionNoPrekey'
28
- RetryReason[(RetryReason['AdvFailure'] = 12)] = 'AdvFailure'
29
- RetryReason[(RetryReason['StatusRevokeDelay'] = 13)] = 'StatusRevokeDelay'
30
- })(RetryReason || (exports.RetryReason = RetryReason = {}))
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 = {}));
31
28
  /** Error codes that indicate a MAC failure and require immediate session recreation */
32
- const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac])
33
- class MessageRetryManager {
34
- constructor(logger, maxMsgRetryCount) {
35
- this.logger = logger
36
- this.recentMessagesMap = new lru_cache_1.LRUCache({
37
- max: RECENT_MESSAGES_SIZE,
38
- ttl: 5 * 60 * 1000,
39
- ttlAutopurge: true,
40
- dispose: (_value, key) => {
41
- const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR)
42
- if (separatorIndex > -1) {
43
- const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length)
44
- this.messageKeyIndex.delete(messageId)
45
- }
46
- }
47
- })
48
- this.messageKeyIndex = new Map()
49
- this.sessionRecreateHistory = new lru_cache_1.LRUCache({
50
- ttl: RECREATE_SESSION_TIMEOUT * 2,
51
- ttlAutopurge: true
52
- })
53
- this.retryCounters = new lru_cache_1.LRUCache({
54
- ttl: 15 * 60 * 1000,
55
- ttlAutopurge: true,
56
- updateAgeOnGet: true
57
- }) // 15 minutes TTL
58
- this.baseKeys = new lru_cache_1.LRUCache({
59
- max: 1024,
60
- ttl: 15 * 60 * 1000,
61
- ttlAutopurge: true
62
- })
63
- this.pendingPhoneRequests = {}
64
- this.maxMsgRetryCount = 5
65
- this.statistics = {
66
- totalRetries: 0,
67
- successfulRetries: 0,
68
- failedRetries: 0,
69
- mediaRetries: 0,
70
- sessionRecreations: 0,
71
- phoneRequests: 0
72
- }
73
- this.maxMsgRetryCount = maxMsgRetryCount
74
- }
75
- /**
76
- * Add a recent message to the cache for retry handling
77
- */
78
- addRecentMessage(to, id, message) {
79
- const key = { to, id }
80
- const keyStr = this.keyToString(key)
81
- // Add new message
82
- this.recentMessagesMap.set(keyStr, {
83
- message,
84
- timestamp: Date.now()
85
- })
86
- this.messageKeyIndex.set(id, keyStr)
87
- this.logger.debug(`Added message to retry cache: ${to}/${id}`)
88
- }
89
- /**
90
- * Get a recent message from the cache
91
- */
92
- getRecentMessage(to, id) {
93
- const key = { to, id }
94
- const keyStr = this.keyToString(key)
95
- return this.recentMessagesMap.get(keyStr)
96
- }
97
- /**
98
- * Check if a session should be recreated based on retry count, history, and error code.
99
- * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
100
- */
101
- shouldRecreateSession(jid, hasSession, errorCode) {
102
- // If we don't have a session, always recreate
103
- if (!hasSession) {
104
- this.sessionRecreateHistory.set(jid, Date.now())
105
- this.statistics.sessionRecreations++
106
- return {
107
- reason: "we don't have a Signal session with them",
108
- recreate: true
109
- }
110
- }
111
- // IMMEDIATE recreation for MAC errors - session is definitely out of sync
112
- if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
113
- this.sessionRecreateHistory.set(jid, Date.now())
114
- this.statistics.sessionRecreations++
115
- this.logger.warn(
116
- { jid, errorCode: RetryReason[errorCode] },
117
- 'MAC error detected, forcing immediate session recreation'
118
- )
119
- return {
120
- reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
121
- recreate: true
122
- }
123
- }
124
- const now = Date.now()
125
- const prevTime = this.sessionRecreateHistory.get(jid)
126
- // If no previous recreation or it's been more than an hour
127
- if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
128
- this.sessionRecreateHistory.set(jid, now)
129
- this.statistics.sessionRecreations++
130
- return {
131
- reason: 'retry count > 1 and over an hour since last recreation',
132
- recreate: true
133
- }
134
- }
135
- return { reason: '', recreate: false }
136
- }
137
- /**
138
- * Parse error code from retry receipt's retry node.
139
- * Returns undefined if no error code is present.
140
- */
141
- parseRetryErrorCode(errorAttr) {
142
- if (errorAttr === undefined || errorAttr === '') {
143
- return undefined
144
- }
145
- const code = parseInt(errorAttr, 10)
146
- if (Number.isNaN(code)) {
147
- return undefined
148
- }
149
- // Validate it's a known RetryReason
150
- if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
151
- return code
152
- }
153
- return RetryReason.UnknownError
154
- }
155
- /**
156
- * Check if an error code indicates a MAC failure
157
- */
158
- isMacError(errorCode) {
159
- return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)
160
- }
161
- /**
162
- * Increment retry counter for a message
163
- */
164
- incrementRetryCount(messageId) {
165
- this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1)
166
- this.statistics.totalRetries++
167
- return this.retryCounters.get(messageId)
168
- }
169
- /**
170
- * Get retry count for a message
171
- */
172
- getRetryCount(messageId) {
173
- return this.retryCounters.get(messageId) || 0
174
- }
175
- /**
176
- * Check if message has exceeded maximum retry attempts
177
- */
178
- hasExceededMaxRetries(messageId) {
179
- return this.getRetryCount(messageId) >= this.maxMsgRetryCount
180
- }
181
- /**
182
- * Mark retry as successful
183
- */
184
- markRetrySuccess(messageId) {
185
- this.statistics.successfulRetries++
186
- // Clean up retry counter for successful message
187
- this.retryCounters.delete(messageId)
188
- this.cancelPendingPhoneRequest(messageId)
189
- this.removeRecentMessage(messageId)
190
- }
191
- /**
192
- * Mark retry as failed
193
- */
194
- markRetryFailed(messageId) {
195
- this.statistics.failedRetries++
196
- this.retryCounters.delete(messageId)
197
- this.cancelPendingPhoneRequest(messageId)
198
- this.removeRecentMessage(messageId)
199
- }
200
- /**
201
- * Schedule a phone request with delay
202
- */
203
- schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
204
- // Cancel any existing request for this message
205
- this.cancelPendingPhoneRequest(messageId)
206
- this.pendingPhoneRequests[messageId] = setTimeout(() => {
207
- delete this.pendingPhoneRequests[messageId]
208
- this.statistics.phoneRequests++
209
- callback()
210
- }, delay)
211
- this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`)
212
- }
213
- /**
214
- * Cancel pending phone request
215
- */
216
- cancelPendingPhoneRequest(messageId) {
217
- const timeout = this.pendingPhoneRequests[messageId]
218
- if (timeout) {
219
- clearTimeout(timeout)
220
- delete this.pendingPhoneRequests[messageId]
221
- this.logger.debug(`Cancelled pending phone request for message ${messageId}`)
222
- }
223
- }
224
- clear() {
225
- this.recentMessagesMap.clear()
226
- this.messageKeyIndex.clear()
227
- this.sessionRecreateHistory.clear()
228
- this.retryCounters.clear()
229
- this.baseKeys.clear()
230
- for (const messageId of Object.keys(this.pendingPhoneRequests)) {
231
- this.cancelPendingPhoneRequest(messageId)
232
- }
233
- this.statistics = {
234
- totalRetries: 0,
235
- successfulRetries: 0,
236
- failedRetries: 0,
237
- mediaRetries: 0,
238
- sessionRecreations: 0,
239
- phoneRequests: 0
240
- }
241
- }
242
- saveBaseKey(addr, msgId, baseKey) {
243
- this.baseKeys.set(`${addr}:${msgId}`, baseKey)
244
- }
245
- hasSameBaseKey(addr, msgId, baseKey) {
246
- const stored = this.baseKeys.get(`${addr}:${msgId}`)
247
- if (!stored || stored.length !== baseKey.length) {
248
- return false
249
- }
250
- for (let i = 0; i < stored.length; i++) {
251
- if (stored[i] !== baseKey[i]) return false
252
- }
253
- return true
254
- }
255
- deleteBaseKey(addr, msgId) {
256
- this.baseKeys.delete(`${addr}:${msgId}`)
257
- }
258
- keyToString(key) {
259
- return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`
260
- }
261
- removeRecentMessage(messageId) {
262
- const keyStr = this.messageKeyIndex.get(messageId)
263
- if (!keyStr) {
264
- return
265
- }
266
- this.recentMessagesMap.delete(keyStr)
267
- this.messageKeyIndex.delete(messageId)
268
- }
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 = new LRUCache({
34
+ max: RECENT_MESSAGES_SIZE,
35
+ ttl: 5 * 60 * 1000,
36
+ ttlAutopurge: true,
37
+ dispose: (_value, key) => {
38
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR);
39
+ if (separatorIndex > -1) {
40
+ const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length);
41
+ this.messageKeyIndex.delete(messageId);
42
+ }
43
+ }
44
+ });
45
+ this.messageKeyIndex = new Map();
46
+ this.sessionRecreateHistory = new LRUCache({
47
+ ttl: RECREATE_SESSION_TIMEOUT * 2,
48
+ ttlAutopurge: true
49
+ });
50
+ this.retryCounters = new LRUCache({
51
+ ttl: 15 * 60 * 1000,
52
+ ttlAutopurge: true,
53
+ updateAgeOnGet: true
54
+ }); // 15 minutes TTL
55
+ this.baseKeys = new LRUCache({
56
+ max: 1024,
57
+ ttl: 15 * 60 * 1000,
58
+ ttlAutopurge: true
59
+ });
60
+ this.pendingPhoneRequests = {};
61
+ this.maxMsgRetryCount = 5;
62
+ this.statistics = {
63
+ totalRetries: 0,
64
+ successfulRetries: 0,
65
+ failedRetries: 0,
66
+ mediaRetries: 0,
67
+ sessionRecreations: 0,
68
+ phoneRequests: 0
69
+ };
70
+ this.maxMsgRetryCount = maxMsgRetryCount;
71
+ }
72
+ /**
73
+ * Add a recent message to the cache for retry handling
74
+ */
75
+ addRecentMessage(to, id, message) {
76
+ const key = { to, id };
77
+ const keyStr = this.keyToString(key);
78
+ // Add new message
79
+ this.recentMessagesMap.set(keyStr, {
80
+ message,
81
+ timestamp: Date.now()
82
+ });
83
+ this.messageKeyIndex.set(id, keyStr);
84
+ this.logger.debug(`Added message to retry cache: ${to}/${id}`);
85
+ }
86
+ /**
87
+ * Get a recent message from the cache
88
+ */
89
+ getRecentMessage(to, id) {
90
+ const key = { to, id };
91
+ const keyStr = this.keyToString(key);
92
+ return this.recentMessagesMap.get(keyStr);
93
+ }
94
+ /**
95
+ * Check if a session should be recreated based on retry count, history, and error code.
96
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
97
+ */
98
+ shouldRecreateSession(jid, hasSession, errorCode) {
99
+ // If we don't have a session, always recreate
100
+ if (!hasSession) {
101
+ this.sessionRecreateHistory.set(jid, Date.now());
102
+ this.statistics.sessionRecreations++;
103
+ return {
104
+ reason: "we don't have a Signal session with them",
105
+ recreate: true
106
+ };
107
+ }
108
+ // IMMEDIATE recreation for MAC errors - session is definitely out of sync
109
+ if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
110
+ this.sessionRecreateHistory.set(jid, Date.now());
111
+ this.statistics.sessionRecreations++;
112
+ this.logger.warn({ jid, errorCode: RetryReason[errorCode] }, 'MAC error detected, forcing immediate session recreation');
113
+ return {
114
+ reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
115
+ recreate: true
116
+ };
117
+ }
118
+ const now = Date.now();
119
+ const prevTime = this.sessionRecreateHistory.get(jid);
120
+ // If no previous recreation or it's been more than an hour
121
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
122
+ this.sessionRecreateHistory.set(jid, now);
123
+ this.statistics.sessionRecreations++;
124
+ return {
125
+ reason: 'retry count > 1 and over an hour since last recreation',
126
+ recreate: true
127
+ };
128
+ }
129
+ return { reason: '', recreate: false };
130
+ }
131
+ /**
132
+ * Parse error code from retry receipt's retry node.
133
+ * Returns undefined if no error code is present.
134
+ */
135
+ parseRetryErrorCode(errorAttr) {
136
+ if (errorAttr === undefined || errorAttr === '') {
137
+ return undefined;
138
+ }
139
+ const code = parseInt(errorAttr, 10);
140
+ if (Number.isNaN(code)) {
141
+ return undefined;
142
+ }
143
+ // Validate it's a known RetryReason
144
+ if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
145
+ return code;
146
+ }
147
+ return RetryReason.UnknownError;
148
+ }
149
+ /**
150
+ * Check if an error code indicates a MAC failure
151
+ */
152
+ isMacError(errorCode) {
153
+ return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode);
154
+ }
155
+ /**
156
+ * Increment retry counter for a message
157
+ */
158
+ incrementRetryCount(messageId) {
159
+ this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
160
+ this.statistics.totalRetries++;
161
+ return this.retryCounters.get(messageId);
162
+ }
163
+ /**
164
+ * Get retry count for a message
165
+ */
166
+ getRetryCount(messageId) {
167
+ return this.retryCounters.get(messageId) || 0;
168
+ }
169
+ /**
170
+ * Check if message has exceeded maximum retry attempts
171
+ */
172
+ hasExceededMaxRetries(messageId) {
173
+ return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
174
+ }
175
+ /**
176
+ * Mark retry as successful
177
+ */
178
+ markRetrySuccess(messageId) {
179
+ this.statistics.successfulRetries++;
180
+ // Clean up retry counter for successful message
181
+ this.retryCounters.delete(messageId);
182
+ this.cancelPendingPhoneRequest(messageId);
183
+ this.removeRecentMessage(messageId);
184
+ }
185
+ /**
186
+ * Mark retry as failed
187
+ */
188
+ markRetryFailed(messageId) {
189
+ this.statistics.failedRetries++;
190
+ this.retryCounters.delete(messageId);
191
+ this.cancelPendingPhoneRequest(messageId);
192
+ this.removeRecentMessage(messageId);
193
+ }
194
+ /**
195
+ * Schedule a phone request with delay
196
+ */
197
+ schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
198
+ // Cancel any existing request for this message
199
+ this.cancelPendingPhoneRequest(messageId);
200
+ this.pendingPhoneRequests[messageId] = setTimeout(() => {
201
+ delete this.pendingPhoneRequests[messageId];
202
+ this.statistics.phoneRequests++;
203
+ callback();
204
+ }, delay);
205
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
206
+ }
207
+ /**
208
+ * Cancel pending phone request
209
+ */
210
+ cancelPendingPhoneRequest(messageId) {
211
+ const timeout = this.pendingPhoneRequests[messageId];
212
+ if (timeout) {
213
+ clearTimeout(timeout);
214
+ delete this.pendingPhoneRequests[messageId];
215
+ this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
216
+ }
217
+ }
218
+ clear() {
219
+ this.recentMessagesMap.clear();
220
+ this.messageKeyIndex.clear();
221
+ this.sessionRecreateHistory.clear();
222
+ this.retryCounters.clear();
223
+ this.baseKeys.clear();
224
+ for (const messageId of Object.keys(this.pendingPhoneRequests)) {
225
+ this.cancelPendingPhoneRequest(messageId);
226
+ }
227
+ this.statistics = {
228
+ totalRetries: 0,
229
+ successfulRetries: 0,
230
+ failedRetries: 0,
231
+ mediaRetries: 0,
232
+ sessionRecreations: 0,
233
+ phoneRequests: 0
234
+ };
235
+ }
236
+ saveBaseKey(addr, msgId, baseKey) {
237
+ this.baseKeys.set(`${addr}:${msgId}`, baseKey);
238
+ }
239
+ hasSameBaseKey(addr, msgId, baseKey) {
240
+ const stored = this.baseKeys.get(`${addr}:${msgId}`);
241
+ if (!stored || stored.length !== baseKey.length) {
242
+ return false;
243
+ }
244
+ for (let i = 0; i < stored.length; i++) {
245
+ if (stored[i] !== baseKey[i])
246
+ return false;
247
+ }
248
+ return true;
249
+ }
250
+ deleteBaseKey(addr, msgId) {
251
+ this.baseKeys.delete(`${addr}:${msgId}`);
252
+ }
253
+ keyToString(key) {
254
+ return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
255
+ }
256
+ removeRecentMessage(messageId) {
257
+ const keyStr = this.messageKeyIndex.get(messageId);
258
+ if (!keyStr) {
259
+ return;
260
+ }
261
+ this.recentMessagesMap.delete(keyStr);
262
+ this.messageKeyIndex.delete(messageId);
263
+ }
269
264
  }
270
- exports.MessageRetryManager = MessageRetryManager
265
+ //# sourceMappingURL=message-retry-manager.js.map