@badzz88/baileys 8.4.7 → 8.5.0

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 (144) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1055 -337
  3. package/WAProto/index.js +5 -5
  4. package/lib/Defaults/index.js +187 -127
  5. package/lib/Defaults/phonenumber-mcc.json +223 -0
  6. package/lib/Signal/Group/ciphertext-message.js +14 -11
  7. package/lib/Signal/Group/group-session-builder.js +91 -29
  8. package/lib/Signal/Group/group_cipher.js +88 -81
  9. package/lib/Signal/Group/index.js +136 -12
  10. package/lib/Signal/Group/keyhelper.js +70 -15
  11. package/lib/Signal/Group/sender-chain-key.js +31 -25
  12. package/lib/Signal/Group/sender-key-distribution-message.js +65 -62
  13. package/lib/Signal/Group/sender-key-message.js +68 -65
  14. package/lib/Signal/Group/sender-key-name.js +43 -41
  15. package/lib/Signal/Group/sender-key-record.js +43 -40
  16. package/lib/Signal/Group/sender-key-state.js +96 -83
  17. package/lib/Signal/Group/sender-message-key.js +29 -25
  18. package/lib/Signal/libsignal.js +483 -424
  19. package/lib/Signal/lid-mapping.js +261 -276
  20. package/lib/Socket/Client/index.js +30 -3
  21. package/lib/Socket/Client/types.js +12 -10
  22. package/lib/Socket/Client/websocket.js +61 -53
  23. package/lib/Socket/aigroups.js +240 -0
  24. package/lib/Socket/business.js +422 -379
  25. package/lib/Socket/chats.js +1816 -1193
  26. package/lib/Socket/communities.js +549 -431
  27. package/lib/Socket/graphql.js +656 -0
  28. package/lib/Socket/groups.js +764 -374
  29. package/lib/Socket/index.js +38 -11
  30. package/lib/Socket/interactive-handler.js +522 -0
  31. package/lib/Socket/interop.js +549 -0
  32. package/lib/Socket/luxu.js +6 -5
  33. package/lib/Socket/managed-account.js +183 -0
  34. package/lib/Socket/messages-recv.js +2439 -1915
  35. package/lib/Socket/messages-send.js +1642 -1242
  36. package/lib/Socket/mex.js +59 -40
  37. package/lib/Socket/newsletter.js +812 -249
  38. package/lib/Socket/privacy.js +449 -0
  39. package/lib/Socket/registration.js +427 -0
  40. package/lib/Socket/socket.js +1077 -965
  41. package/lib/Socket/text-router.js +83 -0
  42. package/lib/Socket/username.js +237 -140
  43. package/lib/Store/index.js +36 -10
  44. package/lib/Store/make-cache-manager-store.js +85 -80
  45. package/lib/Store/make-in-memory-store.js +591 -185
  46. package/lib/Store/make-ordered-dictionary.js +78 -72
  47. package/lib/Store/object-repository.js +25 -28
  48. package/lib/Types/Auth.js +38 -2
  49. package/lib/Types/Bussines.js +2 -2
  50. package/lib/Types/Call.js +2 -2
  51. package/lib/Types/Chat.js +4 -8
  52. package/lib/Types/Contact.js +2 -2
  53. package/lib/Types/Events.js +2 -2
  54. package/lib/Types/GroupMetadata.js +2 -2
  55. package/lib/Types/Label.js +26 -24
  56. package/lib/Types/LabelAssociation.js +8 -6
  57. package/lib/Types/Message.js +95 -11
  58. package/lib/Types/Mex.js +112 -37
  59. package/lib/Types/Newsletter.js +121 -0
  60. package/lib/Types/Product.js +2 -2
  61. package/lib/Types/Signal.js +2 -2
  62. package/lib/Types/Socket.js +2 -3
  63. package/lib/Types/State.js +70 -56
  64. package/lib/Types/USync.js +2 -2
  65. package/lib/Types/index.js +55 -26
  66. package/lib/Utils/auth-utils.js +292 -288
  67. package/lib/Utils/browser-utils.js +113 -48
  68. package/lib/Utils/business.js +240 -224
  69. package/lib/Utils/chat-utils.js +1205 -869
  70. package/lib/Utils/command-loader.d.ts +31 -0
  71. package/lib/Utils/command-loader.js +100 -0
  72. package/lib/Utils/companion-reg-client-utils.js +41 -34
  73. package/lib/Utils/consumer-application.js +107 -0
  74. package/lib/Utils/crypto.js +144 -107
  75. package/lib/Utils/curve25519-js.js +275 -0
  76. package/lib/Utils/decode-wa-message.js +518 -308
  77. package/lib/Utils/event-buffer.js +596 -611
  78. package/lib/Utils/generics.js +514 -354
  79. package/lib/Utils/group-history.js +60 -0
  80. package/lib/Utils/history.js +244 -134
  81. package/lib/Utils/identity-change-handler.js +51 -49
  82. package/lib/Utils/index.js +57 -23
  83. package/lib/Utils/jid-display-normalization.js +218 -0
  84. package/lib/Utils/link-preview.js +135 -77
  85. package/lib/Utils/logger.js +9 -3
  86. package/lib/Utils/lt-hash.js +37 -6
  87. package/lib/Utils/make-mutex.js +36 -33
  88. package/lib/Utils/message-composer.js +439 -233
  89. package/lib/Utils/message-retry-manager.js +265 -260
  90. package/lib/Utils/messages-media.js +855 -747
  91. package/lib/Utils/messages.js +2528 -884
  92. package/lib/Utils/meta-ai-msmsg.js +262 -0
  93. package/lib/Utils/native-bridge.js +82 -0
  94. package/lib/Utils/noise-handler.js +195 -200
  95. package/lib/Utils/offline-node-processor.js +35 -33
  96. package/lib/Utils/pre-key-manager.js +103 -102
  97. package/lib/Utils/process-message.js +978 -560
  98. package/lib/Utils/reporting-utils.js +257 -253
  99. package/lib/Utils/session-pool.d.ts +16 -0
  100. package/lib/Utils/session-pool.js +94 -0
  101. package/lib/Utils/signal.js +218 -195
  102. package/lib/Utils/stanza-ack.js +31 -29
  103. package/lib/Utils/sticker.d.ts +17 -0
  104. package/lib/Utils/sticker.js +145 -0
  105. package/lib/Utils/sync-action-utils.js +50 -45
  106. package/lib/Utils/tc-token-utils.js +137 -139
  107. package/lib/Utils/use-multi-file-auth-state.js +109 -109
  108. package/lib/Utils/validate-connection.js +218 -202
  109. package/lib/Utils/view-once-cache.d.ts +9 -0
  110. package/lib/Utils/view-once-cache.js +79 -0
  111. package/lib/Utils/voip-rekey.js +22 -0
  112. package/lib/WABinary/constants.js +1302 -1299
  113. package/lib/WABinary/decode.js +343 -262
  114. package/lib/WABinary/encode.js +12 -4
  115. package/lib/WABinary/generic-utils.js +223 -187
  116. package/lib/WABinary/index.js +33 -6
  117. package/lib/WABinary/jid-utils.js +351 -88
  118. package/lib/WABinary/types.js +2 -2
  119. package/lib/WAM/BinaryInfo.js +12 -9
  120. package/lib/WAM/constants.js +39486 -22853
  121. package/lib/WAM/encode.js +132 -140
  122. package/lib/WAM/index.js +31 -4
  123. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  124. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  125. package/lib/WAUSync/Protocols/USyncContactProtocol.js +53 -51
  126. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +56 -53
  127. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +29 -26
  128. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  129. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  130. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  131. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  132. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -37
  133. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  134. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +26 -24
  135. package/lib/WAUSync/Protocols/index.js +39 -6
  136. package/lib/WAUSync/USyncQuery.js +132 -97
  137. package/lib/WAUSync/USyncUser.js +49 -30
  138. package/lib/WAUSync/index.js +31 -4
  139. package/lib/antiban.js +4637 -0
  140. package/lib/index.js +48 -15
  141. package/package.json +55 -92
  142. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -263
  143. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  144. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
@@ -1,265 +1,270 @@
1
- import { LRUCache } from 'lru-cache';
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')
2
5
  /** Number of sent messages to cache in memory for handling retry receipts */
3
- const RECENT_MESSAGES_SIZE = 512;
4
- const MESSAGE_KEY_SEPARATOR = '\u0000';
6
+ const RECENT_MESSAGES_SIZE = 512
7
+ const MESSAGE_KEY_SEPARATOR = '\u0000'
5
8
  /** Timeout for session recreation - 1 hour */
6
- const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000; // 1 hour in milliseconds
7
- const PHONE_REQUEST_DELAY = 3000;
9
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000 // 1 hour in milliseconds
10
+ const PHONE_REQUEST_DELAY = 3000
8
11
  // 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 = {}));
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 = {}))
28
31
  /** 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 = 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
- }
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
+ }
264
269
  }
265
- //# sourceMappingURL=message-retry-manager.js.map
270
+ exports.MessageRetryManager = MessageRetryManager