@mrlegendbot/baileys 1.2.5 → 1.2.7

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 (212) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/fix-imports.js +85 -0
  3. package/WAProto/index.d.ts +14017 -0
  4. package/WAProto/index.js +97691 -2
  5. package/lib/Defaults/index.d.ts +75 -0
  6. package/lib/Defaults/index.js +92 -89
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +10 -9
  9. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  10. package/lib/Signal/Group/group-session-builder.js +22 -21
  11. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  12. package/lib/Signal/Group/group_cipher.js +69 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +1 -0
  15. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  16. package/lib/Signal/Group/keyhelper.js +10 -9
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +22 -21
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +60 -51
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +62 -56
  23. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  24. package/lib/Signal/Group/sender-key-name.js +40 -38
  25. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  26. package/lib/Signal/Group/sender-key-record.js +34 -33
  27. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -72
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -22
  31. package/lib/Signal/libsignal.d.ts +5 -0
  32. package/lib/Signal/libsignal.js +405 -506
  33. package/lib/Signal/lid-mapping.d.ts +23 -0
  34. package/lib/Signal/lid-mapping.js +258 -276
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +1 -0
  37. package/lib/Socket/Client/types.d.ts +16 -0
  38. package/lib/Socket/Client/types.js +7 -6
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +49 -48
  41. package/lib/Socket/business.d.ts +217 -0
  42. package/lib/Socket/business.js +369 -349
  43. package/lib/Socket/chats.d.ts +125 -0
  44. package/lib/Socket/chats.js +1148 -1172
  45. package/lib/Socket/communities.d.ts +273 -0
  46. package/lib/Socket/communities.js +413 -473
  47. package/lib/Socket/groups.d.ts +161 -0
  48. package/lib/Socket/groups.js +331 -387
  49. package/lib/Socket/index.d.ts +260 -0
  50. package/lib/Socket/index.js +8 -6
  51. package/lib/Socket/messages-recv.d.ts +203 -0
  52. package/lib/Socket/messages-recv.js +1719 -1782
  53. package/lib/Socket/messages-send.d.ts +200 -0
  54. package/lib/Socket/messages-send.js +2508 -1384
  55. package/lib/Socket/mex.d.ts +3 -0
  56. package/lib/Socket/mex.js +35 -40
  57. package/lib/Socket/newsletter.d.ts +170 -0
  58. package/lib/Socket/newsletter.js +191 -239
  59. package/lib/Socket/socket.d.ts +59 -0
  60. package/lib/Socket/socket.js +923 -992
  61. package/lib/Types/Auth.d.ts +117 -0
  62. package/lib/Types/Auth.js +1 -0
  63. package/lib/Types/Bussines.d.ts +25 -0
  64. package/lib/Types/Bussines.js +1 -0
  65. package/lib/Types/Call.d.ts +15 -0
  66. package/lib/Types/Call.js +1 -0
  67. package/lib/Types/Chat.d.ts +124 -0
  68. package/lib/Types/Chat.js +8 -1
  69. package/lib/Types/Contact.d.ts +26 -0
  70. package/lib/Types/Contact.js +1 -0
  71. package/lib/Types/Events.d.ts +256 -0
  72. package/lib/Types/Events.js +2 -1
  73. package/lib/Types/GroupMetadata.d.ts +71 -0
  74. package/lib/Types/GroupMetadata.js +1 -0
  75. package/lib/Types/Label.d.ts +47 -0
  76. package/lib/Types/Label.js +22 -20
  77. package/lib/Types/LabelAssociation.d.ts +30 -0
  78. package/lib/Types/LabelAssociation.js +4 -2
  79. package/lib/Types/Message.d.ts +320 -0
  80. package/lib/Types/Message.js +5 -3
  81. package/lib/Types/Mex.d.ts +141 -0
  82. package/lib/Types/Mex.js +31 -26
  83. package/lib/Types/Product.d.ts +79 -0
  84. package/lib/Types/Product.js +1 -0
  85. package/lib/Types/Signal.d.ts +87 -0
  86. package/lib/Types/Signal.js +2 -1
  87. package/lib/Types/Socket.d.ts +136 -0
  88. package/lib/Types/Socket.js +3 -2
  89. package/lib/Types/State.d.ts +97 -0
  90. package/lib/Types/State.js +52 -4
  91. package/lib/Types/USync.d.ts +26 -0
  92. package/lib/Types/USync.js +1 -0
  93. package/lib/Types/index.d.ts +66 -0
  94. package/lib/Types/index.js +11 -10
  95. package/lib/Utils/auth-utils.d.ts +24 -0
  96. package/lib/Utils/auth-utils.js +277 -240
  97. package/lib/Utils/browser-utils.d.ts +4 -0
  98. package/lib/Utils/browser-utils.js +23 -20
  99. package/lib/Utils/business.d.ts +23 -0
  100. package/lib/Utils/business.js +204 -200
  101. package/lib/Utils/chat-utils.d.ts +100 -0
  102. package/lib/Utils/chat-utils.js +810 -836
  103. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  104. package/lib/Utils/companion-reg-client-utils.js +25 -23
  105. package/lib/Utils/crypto.d.ts +37 -0
  106. package/lib/Utils/crypto.js +86 -70
  107. package/lib/Utils/decode-wa-message.d.ts +66 -0
  108. package/lib/Utils/decode-wa-message.js +284 -277
  109. package/lib/Utils/event-buffer.d.ts +36 -0
  110. package/lib/Utils/event-buffer.js +595 -592
  111. package/lib/Utils/generics.d.ts +92 -0
  112. package/lib/Utils/generics.js +335 -312
  113. package/lib/Utils/history.d.ts +24 -0
  114. package/lib/Utils/history.js +115 -123
  115. package/lib/Utils/identity-change-handler.d.ts +44 -0
  116. package/lib/Utils/identity-change-handler.js +50 -0
  117. package/lib/Utils/index.d.ts +22 -0
  118. package/lib/Utils/index.js +2 -1
  119. package/lib/Utils/link-preview.d.ts +21 -0
  120. package/lib/Utils/link-preview.js +73 -74
  121. package/lib/Utils/logger.d.ts +12 -0
  122. package/lib/Utils/logger.js +2 -3
  123. package/lib/Utils/lt-hash.d.ts +8 -0
  124. package/lib/Utils/lt-hash.js +6 -0
  125. package/lib/Utils/make-mutex.d.ts +9 -0
  126. package/lib/Utils/make-mutex.js +27 -27
  127. package/lib/Utils/message-retry-manager.d.ts +115 -0
  128. package/lib/Utils/message-retry-manager.js +254 -213
  129. package/lib/Utils/messages-media.d.ts +133 -0
  130. package/lib/Utils/messages-media.js +715 -741
  131. package/lib/Utils/messages.d.ts +91 -0
  132. package/lib/Utils/messages.js +827 -791
  133. package/lib/Utils/noise-handler.d.ts +20 -0
  134. package/lib/Utils/noise-handler.js +187 -215
  135. package/lib/Utils/offline-node-processor.d.ts +17 -0
  136. package/lib/Utils/offline-node-processor.js +40 -0
  137. package/lib/Utils/pre-key-manager.d.ts +28 -0
  138. package/lib/Utils/pre-key-manager.js +98 -69
  139. package/lib/Utils/process-message.d.ts +60 -0
  140. package/lib/Utils/process-message.js +586 -617
  141. package/lib/Utils/reporting-utils.d.ts +11 -0
  142. package/lib/Utils/reporting-utils.js +234 -553
  143. package/lib/Utils/signal.d.ts +47 -0
  144. package/lib/Utils/signal.js +170 -217
  145. package/lib/Utils/stanza-ack.d.ts +11 -0
  146. package/lib/Utils/stanza-ack.js +35 -27
  147. package/lib/Utils/sync-action-utils.d.ts +19 -0
  148. package/lib/Utils/sync-action-utils.js +41 -37
  149. package/lib/Utils/tc-token-utils.d.ts +37 -0
  150. package/lib/Utils/tc-token-utils.js +141 -120
  151. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  152. package/lib/Utils/use-multi-file-auth-state.js +105 -87
  153. package/lib/Utils/validate-connection.d.ts +11 -0
  154. package/lib/Utils/validate-connection.js +188 -190
  155. package/lib/WABinary/constants.d.ts +28 -0
  156. package/lib/WABinary/constants.js +1294 -28
  157. package/lib/WABinary/decode.d.ts +7 -0
  158. package/lib/WABinary/decode.js +249 -245
  159. package/lib/WABinary/encode.d.ts +3 -0
  160. package/lib/WABinary/encode.js +206 -201
  161. package/lib/WABinary/generic-utils.d.ts +15 -0
  162. package/lib/WABinary/generic-utils.js +89 -86
  163. package/lib/WABinary/index.d.ts +6 -0
  164. package/lib/WABinary/index.js +1 -0
  165. package/lib/WABinary/jid-utils.d.ts +48 -0
  166. package/lib/WABinary/jid-utils.js +77 -68
  167. package/lib/WABinary/types.d.ts +19 -0
  168. package/lib/WABinary/types.js +1 -0
  169. package/lib/WAM/BinaryInfo.d.ts +9 -0
  170. package/lib/WAM/BinaryInfo.js +8 -7
  171. package/lib/WAM/constants.d.ts +40 -0
  172. package/lib/WAM/constants.js +22853 -19892
  173. package/lib/WAM/encode.d.ts +3 -0
  174. package/lib/WAM/encode.js +132 -121
  175. package/lib/WAM/index.d.ts +4 -0
  176. package/lib/WAM/index.js +1 -0
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  178. package/lib/WAUSync/Protocols/USyncContactProtocol.js +43 -46
  179. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  180. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -47
  181. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  182. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -22
  183. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  184. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -30
  185. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  186. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +20 -19
  187. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  188. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +44 -53
  189. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  190. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -24
  191. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  192. package/lib/WAUSync/Protocols/index.js +1 -0
  193. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  194. package/lib/WAUSync/USyncQuery.js +88 -79
  195. package/lib/WAUSync/USyncUser.d.ts +17 -0
  196. package/lib/WAUSync/USyncUser.js +29 -28
  197. package/lib/WAUSync/index.d.ts +4 -0
  198. package/lib/WAUSync/index.js +1 -0
  199. package/lib/index.d.ts +12 -0
  200. package/lib/index.js +2 -2
  201. package/package.json +86 -22
  202. package/README.upstream.md +0 -1312
  203. package/WAProto/WAProto.json +0 -1
  204. package/WAProto/WAProto.proto +0 -6275
  205. package/WAProto/compiler.js +0 -550
  206. package/lib/Store/index.js +0 -8
  207. package/lib/Store/keyed-db.js +0 -108
  208. package/lib/Store/make-cache-manager-store.js +0 -70
  209. package/lib/Store/make-in-memory-store.js +0 -417
  210. package/lib/Store/make-ordered-dictionary.js +0 -69
  211. package/lib/Store/object-repository.js +0 -27
  212. package/lib/Utils/use-sqlite-auth-state.js +0 -162
@@ -1,33 +1,33 @@
1
1
  import { Mutex as AsyncMutex } from 'async-mutex';
2
2
  export const makeMutex = () => {
3
- const mutex = new AsyncMutex();
4
- return {
5
- mutex(code) {
6
- return mutex.runExclusive(code);
7
- }
8
- };
3
+ const mutex = new AsyncMutex();
4
+ return {
5
+ mutex(code) {
6
+ return mutex.runExclusive(code);
7
+ }
8
+ };
9
9
  };
10
10
  export const makeKeyedMutex = () => {
11
- const map = new Map();
12
- return {
13
- async mutex(key, task) {
14
- let entry = map.get(key);
15
- if (!entry) {
16
- entry = {
17
- mutex: new AsyncMutex(),
18
- refCount: 0
19
- };
20
- map.set(key, entry);
21
- }
22
- entry.refCount++;
23
- try {
24
- return await entry.mutex.runExclusive(task);
25
- } finally {
26
- entry.refCount--;
27
- if (entry.refCount === 0 && map.get(key) === entry) {
28
- map.delete(key);
11
+ const map = new Map();
12
+ return {
13
+ async mutex(key, task) {
14
+ let entry = map.get(key);
15
+ if (!entry) {
16
+ entry = { mutex: new AsyncMutex(), refCount: 0 };
17
+ map.set(key, entry);
18
+ }
19
+ entry.refCount++;
20
+ try {
21
+ return await entry.mutex.runExclusive(task);
22
+ }
23
+ finally {
24
+ entry.refCount--;
25
+ // only delete it if this is still the current entry
26
+ if (entry.refCount === 0 && map.get(key) === entry) {
27
+ map.delete(key);
28
+ }
29
+ }
29
30
  }
30
- }
31
- }
32
- };
31
+ };
33
32
  };
33
+ //# sourceMappingURL=make-mutex.js.map
@@ -0,0 +1,115 @@
1
+ import type { proto } from '../../WAProto/index.js';
2
+ import type { ILogger } from './logger.js';
3
+ export interface RecentMessageKey {
4
+ to: string;
5
+ id: string;
6
+ }
7
+ export interface RecentMessage {
8
+ message: proto.IMessage;
9
+ timestamp: number;
10
+ }
11
+ export interface SessionRecreateHistory {
12
+ [jid: string]: number;
13
+ }
14
+ export interface RetryCounter {
15
+ [messageId: string]: number;
16
+ }
17
+ export type PendingPhoneRequest = Record<string, ReturnType<typeof setTimeout>>;
18
+ export interface RetryStatistics {
19
+ totalRetries: number;
20
+ successfulRetries: number;
21
+ failedRetries: number;
22
+ mediaRetries: number;
23
+ sessionRecreations: number;
24
+ phoneRequests: number;
25
+ }
26
+ export declare enum RetryReason {
27
+ UnknownError = 0,
28
+ SignalErrorNoSession = 1,
29
+ SignalErrorInvalidKey = 2,
30
+ SignalErrorInvalidKeyId = 3,
31
+ /** MAC verification failed - most common cause of decryption failures */
32
+ SignalErrorInvalidMessage = 4,
33
+ SignalErrorInvalidSignature = 5,
34
+ SignalErrorFutureMessage = 6,
35
+ /** Explicit MAC failure - session is definitely out of sync */
36
+ SignalErrorBadMac = 7,
37
+ SignalErrorInvalidSession = 8,
38
+ SignalErrorInvalidMsgKey = 9,
39
+ BadBroadcastEphemeralSetting = 10,
40
+ UnknownCompanionNoPrekey = 11,
41
+ AdvFailure = 12,
42
+ StatusRevokeDelay = 13
43
+ }
44
+ export declare class MessageRetryManager {
45
+ private logger;
46
+ private recentMessagesMap;
47
+ private messageKeyIndex;
48
+ private sessionRecreateHistory;
49
+ private retryCounters;
50
+ private baseKeys;
51
+ private pendingPhoneRequests;
52
+ private readonly maxMsgRetryCount;
53
+ private statistics;
54
+ constructor(logger: ILogger, maxMsgRetryCount: number);
55
+ /**
56
+ * Add a recent message to the cache for retry handling
57
+ */
58
+ addRecentMessage(to: string, id: string, message: proto.IMessage): void;
59
+ /**
60
+ * Get a recent message from the cache
61
+ */
62
+ getRecentMessage(to: string, id: string): RecentMessage | undefined;
63
+ /**
64
+ * Check if a session should be recreated based on retry count, history, and error code.
65
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
66
+ */
67
+ shouldRecreateSession(jid: string, hasSession: boolean, errorCode?: RetryReason): {
68
+ reason: string;
69
+ recreate: boolean;
70
+ };
71
+ /**
72
+ * Parse error code from retry receipt's retry node.
73
+ * Returns undefined if no error code is present.
74
+ */
75
+ parseRetryErrorCode(errorAttr: string | undefined): RetryReason | undefined;
76
+ /**
77
+ * Check if an error code indicates a MAC failure
78
+ */
79
+ isMacError(errorCode: RetryReason | undefined): boolean;
80
+ /**
81
+ * Increment retry counter for a message
82
+ */
83
+ incrementRetryCount(messageId: string): number;
84
+ /**
85
+ * Get retry count for a message
86
+ */
87
+ getRetryCount(messageId: string): number;
88
+ /**
89
+ * Check if message has exceeded maximum retry attempts
90
+ */
91
+ hasExceededMaxRetries(messageId: string): boolean;
92
+ /**
93
+ * Mark retry as successful
94
+ */
95
+ markRetrySuccess(messageId: string): void;
96
+ /**
97
+ * Mark retry as failed
98
+ */
99
+ markRetryFailed(messageId: string): void;
100
+ /**
101
+ * Schedule a phone request with delay
102
+ */
103
+ schedulePhoneRequest(messageId: string, callback: () => void, delay?: number): void;
104
+ /**
105
+ * Cancel pending phone request
106
+ */
107
+ cancelPendingPhoneRequest(messageId: string): void;
108
+ clear(): void;
109
+ saveBaseKey(addr: string, msgId: string, baseKey: Uint8Array): void;
110
+ hasSameBaseKey(addr: string, msgId: string, baseKey: Uint8Array): boolean;
111
+ deleteBaseKey(addr: string, msgId: string): void;
112
+ private keyToString;
113
+ private removeRecentMessage;
114
+ }
115
+ //# sourceMappingURL=message-retry-manager.d.ts.map
@@ -1,224 +1,265 @@
1
1
  import { LRUCache } from 'lru-cache';
2
+ /** Number of sent messages to cache in memory for handling retry receipts */
2
3
  const RECENT_MESSAGES_SIZE = 512;
3
4
  const MESSAGE_KEY_SEPARATOR = '\u0000';
4
- const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000;
5
+ /** Timeout for session recreation - 1 hour */
6
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000; // 1 hour in milliseconds
5
7
  const PHONE_REQUEST_DELAY = 3000;
8
+ // Retry reason codes matching WhatsApp Web's Signal error codes.
6
9
  export var RetryReason;
7
10
  (function (RetryReason) {
8
- RetryReason[RetryReason["UnknownError"] = 0] = "UnknownError";
9
- RetryReason[RetryReason["SignalErrorNoSession"] = 1] = "SignalErrorNoSession";
10
- RetryReason[RetryReason["SignalErrorInvalidKey"] = 2] = "SignalErrorInvalidKey";
11
- RetryReason[RetryReason["SignalErrorInvalidKeyId"] = 3] = "SignalErrorInvalidKeyId";
12
- RetryReason[RetryReason["SignalErrorInvalidMessage"] = 4] = "SignalErrorInvalidMessage";
13
- RetryReason[RetryReason["SignalErrorInvalidSignature"] = 5] = "SignalErrorInvalidSignature";
14
- RetryReason[RetryReason["SignalErrorFutureMessage"] = 6] = "SignalErrorFutureMessage";
15
- RetryReason[RetryReason["SignalErrorBadMac"] = 7] = "SignalErrorBadMac";
16
- RetryReason[RetryReason["SignalErrorInvalidSession"] = 8] = "SignalErrorInvalidSession";
17
- RetryReason[RetryReason["SignalErrorInvalidMsgKey"] = 9] = "SignalErrorInvalidMsgKey";
18
- RetryReason[RetryReason["BadBroadcastEphemeralSetting"] = 10] = "BadBroadcastEphemeralSetting";
19
- RetryReason[RetryReason["UnknownCompanionNoPrekey"] = 11] = "UnknownCompanionNoPrekey";
20
- RetryReason[RetryReason["AdvFailure"] = 12] = "AdvFailure";
21
- RetryReason[RetryReason["StatusRevokeDelay"] = 13] = "StatusRevokeDelay";
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";
22
27
  })(RetryReason || (RetryReason = {}));
28
+ /** Error codes that indicate a MAC failure and require immediate session recreation */
23
29
  const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac]);
24
30
  export class MessageRetryManager {
25
- constructor(logger, maxMsgRetryCount) {
26
- this.logger = logger;
27
- this.recentMessagesMap = new LRUCache({
28
- max: RECENT_MESSAGES_SIZE,
29
- ttl: 5 * 60 * 1000,
30
- ttlAutopurge: true,
31
- dispose: (_value, key) => {
32
- const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR);
33
- if (separatorIndex > -1) {
34
- const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length);
35
- this.messageKeyIndex.delete(messageId);
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;
36
142
  }
37
- }
38
- });
39
- this.messageKeyIndex = new Map();
40
- this.sessionRecreateHistory = new LRUCache({
41
- ttl: RECREATE_SESSION_TIMEOUT * 2,
42
- ttlAutopurge: true
43
- });
44
- this.retryCounters = new LRUCache({
45
- ttl: 15 * 60 * 1000,
46
- ttlAutopurge: true,
47
- updateAgeOnGet: true
48
- });
49
- this.baseKeys = new LRUCache({
50
- max: 1024,
51
- ttl: 15 * 60 * 1000,
52
- ttlAutopurge: true
53
- });
54
- this.pendingPhoneRequests = {};
55
- this.maxMsgRetryCount = 5;
56
- this.statistics = {
57
- totalRetries: 0,
58
- successfulRetries: 0,
59
- failedRetries: 0,
60
- mediaRetries: 0,
61
- sessionRecreations: 0,
62
- phoneRequests: 0
63
- };
64
- this.maxMsgRetryCount = maxMsgRetryCount;
65
- }
66
- addRecentMessage(to, id, message) {
67
- const key = {
68
- to,
69
- id
70
- };
71
- const keyStr = this.keyToString(key);
72
- this.recentMessagesMap.set(keyStr, {
73
- message,
74
- timestamp: Date.now()
75
- });
76
- this.messageKeyIndex.set(id, keyStr);
77
- this.logger.debug(`Added message to retry cache: ${to}/${id}`);
78
- }
79
- getRecentMessage(to, id) {
80
- const key = {
81
- to,
82
- id
83
- };
84
- const keyStr = this.keyToString(key);
85
- return this.recentMessagesMap.get(keyStr);
86
- }
87
- shouldRecreateSession(jid, hasSession, errorCode) {
88
- if (!hasSession) {
89
- this.sessionRecreateHistory.set(jid, Date.now());
90
- this.statistics.sessionRecreations++;
91
- return {
92
- reason: "we don't have a Signal session with them",
93
- recreate: true
94
- };
95
- }
96
- if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
97
- this.sessionRecreateHistory.set(jid, Date.now());
98
- this.statistics.sessionRecreations++;
99
- this.logger.warn({
100
- jid,
101
- errorCode: RetryReason[errorCode]
102
- }, 'MAC error detected, forcing immediate session recreation');
103
- return {
104
- reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
105
- recreate: true
106
- };
107
- }
108
- const now = Date.now();
109
- const prevTime = this.sessionRecreateHistory.get(jid);
110
- if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
111
- this.sessionRecreateHistory.set(jid, now);
112
- this.statistics.sessionRecreations++;
113
- return {
114
- reason: 'retry count > 1 and over an hour since last recreation',
115
- recreate: true
116
- };
117
- }
118
- return {
119
- reason: '',
120
- recreate: false
121
- };
122
- }
123
- parseRetryErrorCode(errorAttr) {
124
- if (errorAttr === undefined || errorAttr === '') {
125
- return undefined;
126
- }
127
- const code = parseInt(errorAttr, 10);
128
- if (Number.isNaN(code)) {
129
- return undefined;
130
- }
131
- if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
132
- return code;
133
- }
134
- return RetryReason.UnknownError;
135
- }
136
- isMacError(errorCode) {
137
- return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode);
138
- }
139
- incrementRetryCount(messageId) {
140
- this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
141
- this.statistics.totalRetries++;
142
- return this.retryCounters.get(messageId);
143
- }
144
- getRetryCount(messageId) {
145
- return this.retryCounters.get(messageId) || 0;
146
- }
147
- hasExceededMaxRetries(messageId) {
148
- return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
149
- }
150
- markRetrySuccess(messageId) {
151
- this.statistics.successfulRetries++;
152
- this.retryCounters.delete(messageId);
153
- this.cancelPendingPhoneRequest(messageId);
154
- this.removeRecentMessage(messageId);
155
- }
156
- markRetryFailed(messageId) {
157
- this.statistics.failedRetries++;
158
- this.retryCounters.delete(messageId);
159
- this.cancelPendingPhoneRequest(messageId);
160
- this.removeRecentMessage(messageId);
161
- }
162
- schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
163
- this.cancelPendingPhoneRequest(messageId);
164
- this.pendingPhoneRequests[messageId] = setTimeout(() => {
165
- delete this.pendingPhoneRequests[messageId];
166
- this.statistics.phoneRequests++;
167
- callback();
168
- }, delay);
169
- this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
170
- }
171
- cancelPendingPhoneRequest(messageId) {
172
- const timeout = this.pendingPhoneRequests[messageId];
173
- if (timeout) {
174
- clearTimeout(timeout);
175
- delete this.pendingPhoneRequests[messageId];
176
- this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
177
- }
178
- }
179
- clear() {
180
- this.recentMessagesMap.clear();
181
- this.messageKeyIndex.clear();
182
- this.sessionRecreateHistory.clear();
183
- this.retryCounters.clear();
184
- this.baseKeys.clear();
185
- for (const messageId of Object.keys(this.pendingPhoneRequests)) {
186
- this.cancelPendingPhoneRequest(messageId);
187
- }
188
- this.statistics = {
189
- totalRetries: 0,
190
- successfulRetries: 0,
191
- failedRetries: 0,
192
- mediaRetries: 0,
193
- sessionRecreations: 0,
194
- phoneRequests: 0
195
- };
196
- }
197
- saveBaseKey(addr, msgId, baseKey) {
198
- this.baseKeys.set(`${addr}:${msgId}`, baseKey);
199
- }
200
- hasSameBaseKey(addr, msgId, baseKey) {
201
- const stored = this.baseKeys.get(`${addr}:${msgId}`);
202
- if (!stored || stored.length !== baseKey.length) {
203
- return false;
204
- }
205
- for (let i = 0; i < stored.length; i++) {
206
- if (stored[i] !== baseKey[i]) return false;
207
- }
208
- return true;
209
- }
210
- deleteBaseKey(addr, msgId) {
211
- this.baseKeys.delete(`${addr}:${msgId}`);
212
- }
213
- keyToString(key) {
214
- return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
215
- }
216
- removeRecentMessage(messageId) {
217
- const keyStr = this.messageKeyIndex.get(messageId);
218
- if (!keyStr) {
219
- return;
220
- }
221
- this.recentMessagesMap.delete(keyStr);
222
- this.messageKeyIndex.delete(messageId);
223
- }
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
+ }
224
264
  }
265
+ //# sourceMappingURL=message-retry-manager.js.map