@rizzxdc/baileys 8.0.10 → 8.1.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 (220) hide show
  1. package/LICENSE +4 -2
  2. package/README.md +107 -245
  3. package/WAProto/index.d.ts +15795 -0
  4. package/WAProto/index.js +25587 -4867
  5. package/lib/Defaults/index.d.ts +147 -0
  6. package/lib/Defaults/index.js +134 -104
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +9 -11
  9. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  10. package/lib/Signal/Group/group-session-builder.js +5 -8
  11. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  12. package/lib/Signal/Group/group_cipher.js +72 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +11 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  16. package/lib/Signal/Group/keyhelper.js +11 -14
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +23 -26
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +58 -61
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +61 -64
  23. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  24. package/lib/Signal/Group/sender-key-name.js +39 -44
  25. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  26. package/lib/Signal/Group/sender-key-record.js +35 -38
  27. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -79
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -26
  31. package/lib/Signal/libsignal.d.ts +55 -0
  32. package/lib/Signal/libsignal.js +414 -308
  33. package/lib/Signal/lid-mapping.d.ts +21 -0
  34. package/lib/Signal/lid-mapping.js +270 -149
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +2 -4
  37. package/lib/Socket/Client/types.d.ts +6 -0
  38. package/lib/Socket/Client/types.js +8 -11
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +51 -50
  41. package/lib/Socket/business.d.ts +395 -0
  42. package/lib/Socket/business.js +357 -355
  43. package/lib/Socket/chats.d.ts +137 -0
  44. package/lib/Socket/chats.js +1195 -867
  45. package/lib/Socket/communities.d.ts +562 -0
  46. package/lib/Socket/communities.js +416 -398
  47. package/lib/Socket/dugong.js +8 -1
  48. package/lib/Socket/groups.d.ts +286 -0
  49. package/lib/Socket/groups.js +336 -301
  50. package/lib/Socket/index.d.ts +530 -0
  51. package/lib/Socket/index.js +8 -13
  52. package/lib/Socket/messages-recv.d.ts +334 -0
  53. package/lib/Socket/messages-recv.js +1729 -1121
  54. package/lib/Socket/messages-send.d.ts +330 -0
  55. package/lib/Socket/messages-send.js +684 -462
  56. package/lib/Socket/mex.d.ts +2 -0
  57. package/lib/Socket/mex.js +36 -40
  58. package/lib/Socket/newsletter.d.ts +284 -0
  59. package/lib/Socket/newsletter.js +247 -237
  60. package/lib/Socket/socket.d.ts +61 -0
  61. package/lib/Socket/socket.js +968 -790
  62. package/lib/Store/index.d.ts +4 -0
  63. package/lib/Store/index.js +4 -6
  64. package/lib/Store/make-cache-manager-store.js +2 -2
  65. package/lib/Store/make-in-memory-store.d.ts +63 -0
  66. package/lib/Store/make-in-memory-store.js +414 -284
  67. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  68. package/lib/Store/make-ordered-dictionary.js +75 -76
  69. package/lib/Store/object-repository.d.ts +11 -0
  70. package/lib/Store/object-repository.js +21 -23
  71. package/lib/Types/Auth.d.ts +2 -0
  72. package/lib/Types/Auth.js +0 -2
  73. package/lib/Types/Bussines.d.ts +2 -0
  74. package/lib/Types/Bussines.js +0 -2
  75. package/lib/Types/Call.d.ts +2 -0
  76. package/lib/Types/Call.js +0 -2
  77. package/lib/Types/Chat.d.ts +2 -0
  78. package/lib/Types/Chat.js +5 -7
  79. package/lib/Types/Contact.d.ts +2 -0
  80. package/lib/Types/Contact.js +0 -2
  81. package/lib/Types/Events.d.ts +2 -0
  82. package/lib/Types/Events.js +1 -3
  83. package/lib/Types/GroupMetadata.d.ts +2 -0
  84. package/lib/Types/GroupMetadata.js +0 -2
  85. package/lib/Types/Label.d.ts +3 -0
  86. package/lib/Types/Label.js +21 -22
  87. package/lib/Types/LabelAssociation.d.ts +3 -0
  88. package/lib/Types/LabelAssociation.js +3 -4
  89. package/lib/Types/Message.d.ts +12 -0
  90. package/lib/Types/Message.js +11 -6
  91. package/lib/Types/Mex.d.ts +3 -0
  92. package/lib/Types/Mex.js +38 -0
  93. package/lib/Types/Product.d.ts +2 -0
  94. package/lib/Types/Product.js +0 -2
  95. package/lib/Types/RichType.d.ts +3 -0
  96. package/lib/Types/RichType.js +22 -0
  97. package/lib/Types/Signal.d.ts +2 -0
  98. package/lib/Types/Signal.js +1 -3
  99. package/lib/Types/Socket.d.ts +2 -0
  100. package/lib/Types/Socket.js +1 -4
  101. package/lib/Types/State.d.ts +6 -0
  102. package/lib/Types/State.js +52 -8
  103. package/lib/Types/USync.d.ts +2 -0
  104. package/lib/Types/USync.js +1 -3
  105. package/lib/Types/index.d.ts +14 -0
  106. package/lib/Types/index.js +22 -25
  107. package/lib/Utils/auth-utils.d.ts +58 -0
  108. package/lib/Utils/auth-utils.js +285 -203
  109. package/lib/Utils/browser-utils.d.ts +9 -0
  110. package/lib/Utils/browser-utils.js +21 -19
  111. package/lib/Utils/business.d.ts +50 -0
  112. package/lib/Utils/business.js +206 -209
  113. package/lib/Utils/chat-utils.d.ts +409 -0
  114. package/lib/Utils/chat-utils.js +825 -706
  115. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  116. package/lib/Utils/companion-reg-client-utils.js +39 -0
  117. package/lib/Utils/crypto.d.ts +40 -0
  118. package/lib/Utils/crypto.js +88 -101
  119. package/lib/Utils/decode-wa-message.d.ts +84 -0
  120. package/lib/Utils/decode-wa-message.js +287 -238
  121. package/lib/Utils/event-buffer.d.ts +13 -0
  122. package/lib/Utils/event-buffer.js +602 -509
  123. package/lib/Utils/generics.d.ts +64 -0
  124. package/lib/Utils/generics.js +334 -295
  125. package/lib/Utils/history.d.ts +76 -0
  126. package/lib/Utils/history.js +125 -79
  127. package/lib/Utils/identity-change-handler.d.ts +14 -0
  128. package/lib/Utils/identity-change-handler.js +49 -0
  129. package/lib/Utils/index.d.ts +25 -0
  130. package/lib/Utils/index.js +25 -21
  131. package/lib/Utils/link-preview.d.ts +13 -0
  132. package/lib/Utils/link-preview.js +73 -70
  133. package/lib/Utils/logger.d.ts +3 -0
  134. package/lib/Utils/logger.js +1 -4
  135. package/lib/Utils/lt-hash.d.ts +7 -0
  136. package/lib/Utils/lt-hash.js +7 -45
  137. package/lib/Utils/make-mutex.d.ts +7 -0
  138. package/lib/Utils/make-mutex.js +27 -31
  139. package/lib/Utils/message-retry-manager.d.ts +80 -0
  140. package/lib/Utils/message-retry-manager.js +165 -14
  141. package/lib/Utils/messages-media.d.ts +137 -0
  142. package/lib/Utils/messages-media.js +768 -572
  143. package/lib/Utils/messages.d.ts +46 -0
  144. package/lib/Utils/messages.js +1082 -130
  145. package/lib/Utils/noise-handler.d.ts +21 -0
  146. package/lib/Utils/noise-handler.js +191 -135
  147. package/lib/Utils/offline-node-processor.d.ts +10 -0
  148. package/lib/Utils/offline-node-processor.js +39 -0
  149. package/lib/Utils/pre-key-manager.d.ts +26 -0
  150. package/lib/Utils/pre-key-manager.js +96 -76
  151. package/lib/Utils/process-message.d.ts +84 -0
  152. package/lib/Utils/process-message.js +718 -311
  153. package/lib/Utils/reporting-utils.d.ts +13 -0
  154. package/lib/Utils/reporting-utils.js +257 -0
  155. package/lib/Utils/rich-message-utils.d.ts +49 -0
  156. package/lib/Utils/rich-message-utils.js +257 -0
  157. package/lib/Utils/signal.d.ts +83 -0
  158. package/lib/Utils/signal.js +174 -135
  159. package/lib/Utils/stanza-ack.d.ts +17 -0
  160. package/lib/Utils/stanza-ack.js +37 -0
  161. package/lib/Utils/sync-action-utils.d.ts +3 -0
  162. package/lib/Utils/sync-action-utils.js +48 -0
  163. package/lib/Utils/tc-token-utils.d.ts +30 -0
  164. package/lib/Utils/tc-token-utils.js +162 -0
  165. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  166. package/lib/Utils/use-multi-file-auth-state.js +104 -95
  167. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  168. package/lib/Utils/use-single-file-auth-state.js +108 -0
  169. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  170. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  171. package/lib/Utils/validate-connection.d.ts +44 -0
  172. package/lib/Utils/validate-connection.js +182 -180
  173. package/lib/WABinary/constants.d.ts +62 -0
  174. package/lib/WABinary/constants.js +1455 -1292
  175. package/lib/WABinary/decode.d.ts +10 -0
  176. package/lib/WABinary/decode.js +249 -228
  177. package/lib/WABinary/encode.d.ts +3 -0
  178. package/lib/WABinary/encode.js +207 -206
  179. package/lib/WABinary/generic-utils.d.ts +77 -0
  180. package/lib/WABinary/generic-utils.js +135 -99
  181. package/lib/WABinary/index.d.ts +6 -0
  182. package/lib/WABinary/index.js +5 -7
  183. package/lib/WABinary/jid-utils.d.ts +29 -0
  184. package/lib/WABinary/jid-utils.js +80 -78
  185. package/lib/WABinary/types.d.ts +2 -0
  186. package/lib/WABinary/types.js +1 -3
  187. package/lib/WAM/BinaryInfo.d.ts +8 -0
  188. package/lib/WAM/BinaryInfo.js +7 -9
  189. package/lib/WAM/constants.d.ts +34927 -0
  190. package/lib/WAM/constants.js +22847 -22848
  191. package/lib/WAM/encode.d.ts +2 -0
  192. package/lib/WAM/encode.js +129 -134
  193. package/lib/WAM/index.d.ts +4 -0
  194. package/lib/WAM/index.js +3 -5
  195. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  196. package/lib/WAUSync/Protocols/USyncContactProtocol.js +48 -27
  197. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  198. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -48
  199. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  200. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -26
  201. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  202. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -35
  203. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  204. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  205. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  206. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +46 -49
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +23 -25
  209. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  210. package/lib/WAUSync/Protocols/index.js +5 -6
  211. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  212. package/lib/WAUSync/USyncQuery.js +92 -85
  213. package/lib/WAUSync/USyncUser.d.ts +17 -0
  214. package/lib/WAUSync/USyncUser.js +28 -22
  215. package/lib/WAUSync/index.d.ts +4 -0
  216. package/lib/WAUSync/index.js +3 -5
  217. package/lib/index.d.ts +12 -0
  218. package/lib/index.js +31 -19
  219. package/package.json +12 -6
  220. package/lib/Types/Newsletter.js +0 -33
@@ -1,45 +1,7 @@
1
- //=======================================================//
2
- import { hkdf } from "./crypto.js";
3
- //=======================================================//
4
- const o = 128;
5
- class LTHash {
6
- constructor(e) {
7
- this.salt = e;
8
- }
9
- async add(e, t) {
10
- for (const item of t) {
11
- e = await this._addSingle(e, item);
12
- }
13
- return e;
14
- }
15
- async subtract(e, t) {
16
- for (const item of t) {
17
- e = await this._subtractSingle(e, item);
18
- }
19
- return e;
20
- }
21
- async subtractThenAdd(e, addList, subtractList) {
22
- const subtracted = await this.subtract(e, subtractList);
23
- return this.add(subtracted, addList);
24
- }
25
- async _addSingle(e, t) {
26
- const derived = new Uint8Array(await hkdf(Buffer.from(t), o, { info: this.salt })).buffer;
27
- return this.performPointwiseWithOverflow(e, derived, (a, b) => a + b);
28
- }
29
- async _subtractSingle(e, t) {
30
- const derived = new Uint8Array(await hkdf(Buffer.from(t), o, { info: this.salt })).buffer;
31
- return this.performPointwiseWithOverflow(e, derived, (a, b) => a - b);
32
- }
33
- performPointwiseWithOverflow(e, t, op) {
34
- const n = new DataView(e);
35
- const i = new DataView(t);
36
- const out = new ArrayBuffer(n.byteLength);
37
- const s = new DataView(out);
38
- for (let offset = 0; offset < n.byteLength; offset += 2) {
39
- s.setUint16(offset, op(n.getUint16(offset, true), i.getUint16(offset, true)), true);
40
- }
41
- return out;
42
- }
43
- }
44
- export const LT_HASH_ANTI_TAMPERING = new LTHash("WhatsApp Patch Integrity");
45
- //=======================================================//
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
2
+ /**
3
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
4
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
5
+ * if the same series of mutations was made sequentially.
6
+ */
7
+ export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();
@@ -0,0 +1,7 @@
1
+ export function makeMutex(): {
2
+ mutex(code: any): any;
3
+ };
4
+ export function makeKeyedMutex(): {
5
+ mutex(key: any, task: any): Promise<any>;
6
+ };
7
+ //# sourceMappingURL=make-mutex.d.ts.map
@@ -1,36 +1,32 @@
1
- //=======================================================//
1
+ import { Mutex as AsyncMutex } from 'async-mutex';
2
2
  export const makeMutex = () => {
3
- let task = Promise.resolve();
4
- let taskTimeout;
5
- return {
6
- mutex(code) {
7
- task = (async () => {
8
- try {
9
- await task;
3
+ const mutex = new AsyncMutex();
4
+ return {
5
+ mutex(code) {
6
+ return mutex.runExclusive(code);
10
7
  }
11
- catch { }
12
- try {
13
- const result = await code();
14
- return result;
15
- }
16
- finally {
17
- clearTimeout(taskTimeout);
18
- }
19
- })();
20
- return task;
21
- }
22
- };
8
+ };
23
9
  };
24
- //=======================================================//
25
10
  export const makeKeyedMutex = () => {
26
- const map = {};
27
- return {
28
- mutex(key, task) {
29
- if (!map[key]) {
30
- map[key] = makeMutex();
31
- }
32
- return map[key].mutex(task);
33
- }
34
- };
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
+ }
30
+ }
31
+ };
35
32
  };
36
- //=======================================================//
@@ -0,0 +1,80 @@
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
+ }
80
+ //# sourceMappingURL=message-retry-manager.d.ts.map
@@ -1,15 +1,48 @@
1
- //=======================================================//
2
- import { LRUCache } from "lru-cache";
3
- //=======================================================//
4
- const RECENT_MESSAGES_SIZE = 512;
5
- const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000;
1
+ import { LRUCache } from 'lru-cache';
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 * 1000; // 1 hour in milliseconds
6
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]);
7
30
  export class MessageRetryManager {
8
31
  constructor(logger, maxMsgRetryCount) {
9
32
  this.logger = logger;
10
33
  this.recentMessagesMap = new LRUCache({
11
- max: RECENT_MESSAGES_SIZE
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
+ }
12
44
  });
45
+ this.messageKeyIndex = new Map();
13
46
  this.sessionRecreateHistory = new LRUCache({
14
47
  ttl: RECREATE_SESSION_TIMEOUT * 2,
15
48
  ttlAutopurge: true
@@ -18,6 +51,11 @@ export class MessageRetryManager {
18
51
  ttl: 15 * 60 * 1000,
19
52
  ttlAutopurge: true,
20
53
  updateAgeOnGet: true
54
+ }); // 15 minutes TTL
55
+ this.baseKeys = new LRUCache({
56
+ max: 1024,
57
+ ttl: 15 * 60 * 1000,
58
+ ttlAutopurge: true
21
59
  });
22
60
  this.pendingPhoneRequests = {};
23
61
  this.maxMsgRetryCount = 5;
@@ -31,65 +69,133 @@ export class MessageRetryManager {
31
69
  };
32
70
  this.maxMsgRetryCount = maxMsgRetryCount;
33
71
  }
72
+ /**
73
+ * Add a recent message to the cache for retry handling
74
+ */
34
75
  addRecentMessage(to, id, message) {
35
76
  const key = { to, id };
36
77
  const keyStr = this.keyToString(key);
78
+ // Add new message
37
79
  this.recentMessagesMap.set(keyStr, {
38
80
  message,
39
81
  timestamp: Date.now()
40
82
  });
83
+ this.messageKeyIndex.set(id, keyStr);
41
84
  this.logger.debug(`Added message to retry cache: ${to}/${id}`);
42
85
  }
86
+ /**
87
+ * Get a recent message from the cache
88
+ */
43
89
  getRecentMessage(to, id) {
44
90
  const key = { to, id };
45
91
  const keyStr = this.keyToString(key);
46
92
  return this.recentMessagesMap.get(keyStr);
47
93
  }
48
- shouldRecreateSession(jid, retryCount, hasSession) {
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
49
100
  if (!hasSession) {
50
101
  this.sessionRecreateHistory.set(jid, Date.now());
51
102
  this.statistics.sessionRecreations++;
52
103
  return {
53
- reason: "we dont have a Signal session with them",
104
+ reason: "we don't have a Signal session with them",
54
105
  recreate: true
55
106
  };
56
107
  }
57
- if (retryCount < 2) {
58
- return { reason: "", recreate: false };
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
+ };
59
117
  }
60
118
  const now = Date.now();
61
119
  const prevTime = this.sessionRecreateHistory.get(jid);
120
+ // If no previous recreation or it's been more than an hour
62
121
  if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
63
122
  this.sessionRecreateHistory.set(jid, now);
64
123
  this.statistics.sessionRecreations++;
65
124
  return {
66
- reason: "retry count > 1 and over an hour since last recreation",
125
+ reason: 'retry count > 1 and over an hour since last recreation',
67
126
  recreate: true
68
127
  };
69
128
  }
70
- return { reason: "", recreate: false };
129
+ return { reason: '', recreate: false };
71
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
+ */
72
158
  incrementRetryCount(messageId) {
73
159
  this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
74
160
  this.statistics.totalRetries++;
75
161
  return this.retryCounters.get(messageId);
76
162
  }
163
+ /**
164
+ * Get retry count for a message
165
+ */
77
166
  getRetryCount(messageId) {
78
167
  return this.retryCounters.get(messageId) || 0;
79
168
  }
169
+ /**
170
+ * Check if message has exceeded maximum retry attempts
171
+ */
80
172
  hasExceededMaxRetries(messageId) {
81
173
  return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
82
174
  }
175
+ /**
176
+ * Mark retry as successful
177
+ */
83
178
  markRetrySuccess(messageId) {
84
179
  this.statistics.successfulRetries++;
180
+ // Clean up retry counter for successful message
85
181
  this.retryCounters.delete(messageId);
86
182
  this.cancelPendingPhoneRequest(messageId);
183
+ this.removeRecentMessage(messageId);
87
184
  }
185
+ /**
186
+ * Mark retry as failed
187
+ */
88
188
  markRetryFailed(messageId) {
89
189
  this.statistics.failedRetries++;
90
190
  this.retryCounters.delete(messageId);
191
+ this.cancelPendingPhoneRequest(messageId);
192
+ this.removeRecentMessage(messageId);
91
193
  }
194
+ /**
195
+ * Schedule a phone request with delay
196
+ */
92
197
  schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
198
+ // Cancel any existing request for this message
93
199
  this.cancelPendingPhoneRequest(messageId);
94
200
  this.pendingPhoneRequests[messageId] = setTimeout(() => {
95
201
  delete this.pendingPhoneRequests[messageId];
@@ -98,6 +204,9 @@ export class MessageRetryManager {
98
204
  }, delay);
99
205
  this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
100
206
  }
207
+ /**
208
+ * Cancel pending phone request
209
+ */
101
210
  cancelPendingPhoneRequest(messageId) {
102
211
  const timeout = this.pendingPhoneRequests[messageId];
103
212
  if (timeout) {
@@ -106,8 +215,50 @@ export class MessageRetryManager {
106
215
  this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
107
216
  }
108
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
+ }
109
253
  keyToString(key) {
110
- return `${key.to}:${key.id}`;
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);
111
263
  }
112
264
  }
113
- //=======================================================//
@@ -0,0 +1,137 @@
1
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
2
+ export function getMediaKeys(buffer: any, mediaType: any): Promise<{
3
+ iv: any;
4
+ cipherKey: any;
5
+ macKey: any;
6
+ }>;
7
+ export function getAudioDuration(buffer: any): Promise<any>;
8
+ /**
9
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
10
+ */
11
+ export function getAudioWaveform(buffer: any, logger: any): Promise<Uint8Array<ArrayBuffer> | undefined>;
12
+ /** generates a thumbnail for a given media, if required */
13
+ export function generateThumbnail(file: any, mediaType: any, options: any): Promise<{
14
+ thumbnail: any;
15
+ originalImageDimensions: {
16
+ width: any;
17
+ height: any;
18
+ } | undefined;
19
+ }>;
20
+ export function extensionForMediaMessage(message: any): any;
21
+ export function getImageProcessingLibrary(): Promise<any>;
22
+ export function hkdfInfoKey(type: any): string;
23
+ export function getRawMediaUploadData(media: any, mediaType: any, logger: any): Promise<{
24
+ filePath: any;
25
+ fileSha256: any;
26
+ fileLength: number;
27
+ }>;
28
+ export function extractVideoThumb(path: any, time: any, size: any): Promise<any>;
29
+ export function extractImageThumb(bufferOrFilePath: any, width?: number): Promise<{
30
+ buffer: any;
31
+ original: {
32
+ width: any;
33
+ height: any;
34
+ };
35
+ }>;
36
+ export function encodeBase64EncodedStringForUpload(b64: any): string;
37
+ export function generateProfilePicture(mediaUpload: any, dimensions: any): Promise<{
38
+ img: any;
39
+ }>;
40
+ export function mediaMessageSHA256B64(message: any): any;
41
+ export function toReadable(buffer: any): any;
42
+ export function toBuffer(stream: any): Promise<any>;
43
+ export function getStream(item: any, opts: any): Promise<{
44
+ stream: any;
45
+ type: string;
46
+ }>;
47
+ export function getHttpStream(url: any, options?: {}): Promise<any>;
48
+ export function encryptedStream(media: any, mediaType: any, { logger, saveOriginalFileIfRequired, opts }?: {}): Promise<{
49
+ mediaKey: any;
50
+ originalFilePath: any;
51
+ encFilePath: any;
52
+ mac: any;
53
+ fileEncSha256: any;
54
+ fileSha256: any;
55
+ fileLength: number;
56
+ }>;
57
+ export const DEF_MEDIA_HOST: "mmg.whatsapp.net";
58
+ export function getUrlFromDirectPath(directPath: any, host?: string): string;
59
+ export function downloadContentFromMessage({ mediaKey, directPath, url }: {
60
+ mediaKey: any;
61
+ directPath: any;
62
+ url: any;
63
+ }, type: any, opts?: {}): Promise<any>;
64
+ export function downloadEncryptedContent(downloadUrl: any, { cipherKey, iv }: {
65
+ cipherKey: any;
66
+ iv: any;
67
+ }, { startByte, endByte, options }?: {}): Promise<any>;
68
+ export function uploadWithNodeHttp({ url, filePath, headers, timeoutMs, agent }: {
69
+ url: any;
70
+ filePath: any;
71
+ headers: any;
72
+ timeoutMs: any;
73
+ agent: any;
74
+ }, redirectCount?: number): Promise<any>;
75
+ export function getWAUploadToServer({ customUploadHosts, fetchAgent, logger, options }: {
76
+ customUploadHosts: any;
77
+ fetchAgent: any;
78
+ logger: any;
79
+ options: any;
80
+ }, refreshMediaConn: any): (filePath: any, { mediaType, fileEncSha256B64, timeoutMs, newsletter }: {
81
+ mediaType: any;
82
+ fileEncSha256B64: any;
83
+ timeoutMs: any;
84
+ newsletter: any;
85
+ }) => Promise<{
86
+ mediaUrl: any;
87
+ directPath: any;
88
+ meta_hmac: any;
89
+ fbid: any;
90
+ ts: any;
91
+ thumbnailDirectPath: any;
92
+ thumbnailSha256: any;
93
+ }>;
94
+ export function encryptMediaRetryRequest(key: any, mediaKey: any, meId: any): {
95
+ tag: string;
96
+ attrs: {
97
+ id: any;
98
+ to: string;
99
+ type: string;
100
+ };
101
+ content: ({
102
+ tag: string;
103
+ attrs: {
104
+ jid?: undefined;
105
+ from_me?: undefined;
106
+ participant?: undefined;
107
+ };
108
+ content: {
109
+ tag: string;
110
+ attrs: {};
111
+ content: any;
112
+ }[];
113
+ } | {
114
+ tag: string;
115
+ attrs: {
116
+ jid: any;
117
+ from_me: string;
118
+ participant: any;
119
+ };
120
+ content?: undefined;
121
+ })[];
122
+ };
123
+ export function decodeMediaRetryNode(node: any): {
124
+ key: {
125
+ id: any;
126
+ remoteJid: any;
127
+ fromMe: boolean;
128
+ participant: any;
129
+ };
130
+ };
131
+ export function decryptMediaRetryData({ ciphertext, iv }: {
132
+ ciphertext: any;
133
+ iv: any;
134
+ }, mediaKey: any, msgId: any): proto.MediaRetryNotification;
135
+ export function getStatusCodeForMediaRetry(code: any): any;
136
+ import { proto } from '../../WAProto/index.js';
137
+ //# sourceMappingURL=messages-media.d.ts.map