@nerxa/socketon 0.0.0-stage → 1.21.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 (289) hide show
  1. package/EXPERIMENTAL.md +350 -0
  2. package/LICENSE +24 -0
  3. package/README.md +6317 -2
  4. package/WAProto/index.d.ts +17301 -0
  5. package/WAProto/index.js +125088 -0
  6. package/engine-requirements.js +14 -0
  7. package/package.json +100 -4
  8. package/src/Defaults/index.d.ts +152 -0
  9. package/src/Defaults/index.js +164 -0
  10. package/src/MessageBuilder/bot-signature.d.ts +22 -0
  11. package/src/MessageBuilder/bot-signature.js +122 -0
  12. package/src/MessageBuilder/extras.d.ts +449 -0
  13. package/src/MessageBuilder/extras.js +1356 -0
  14. package/src/MessageBuilder/index.d.ts +210 -0
  15. package/src/MessageBuilder/index.js +3594 -0
  16. package/src/MessageBuilder/metaai.d.ts +438 -0
  17. package/src/MessageBuilder/metaai.js +890 -0
  18. package/src/Signal/Group/ciphertext-message.d.ts +9 -0
  19. package/src/Signal/Group/ciphertext-message.js +11 -0
  20. package/src/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/src/Signal/Group/group-session-builder.js +27 -0
  22. package/src/Signal/Group/group_cipher.d.ts +11 -0
  23. package/src/Signal/Group/group_cipher.js +78 -0
  24. package/src/Signal/Group/index.d.ts +11 -0
  25. package/src/Signal/Group/index.js +11 -0
  26. package/src/Signal/Group/keyhelper.d.ts +6 -0
  27. package/src/Signal/Group/keyhelper.js +17 -0
  28. package/src/Signal/Group/sender-chain-key.d.ts +13 -0
  29. package/src/Signal/Group/sender-chain-key.js +25 -0
  30. package/src/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  31. package/src/Signal/Group/sender-key-distribution-message.js +62 -0
  32. package/src/Signal/Group/sender-key-message.d.ts +18 -0
  33. package/src/Signal/Group/sender-key-message.js +65 -0
  34. package/src/Signal/Group/sender-key-name.d.ts +11 -0
  35. package/src/Signal/Group/sender-key-name.js +47 -0
  36. package/src/Signal/Group/sender-key-record.d.ts +12 -0
  37. package/src/Signal/Group/sender-key-record.js +40 -0
  38. package/src/Signal/Group/sender-key-state.d.ts +16 -0
  39. package/src/Signal/Group/sender-key-state.js +83 -0
  40. package/src/Signal/Group/sender-message-key.d.ts +11 -0
  41. package/src/Signal/Group/sender-message-key.js +25 -0
  42. package/src/Signal/libsignal.d.ts +54 -0
  43. package/src/Signal/libsignal.js +427 -0
  44. package/src/Signal/lid-mapping.d.ts +20 -0
  45. package/src/Signal/lid-mapping.js +274 -0
  46. package/src/Socket/Client/index.d.ts +2 -0
  47. package/src/Socket/Client/index.js +3 -0
  48. package/src/Socket/Client/tcp.js +177 -0
  49. package/src/Socket/Client/types.d.ts +5 -0
  50. package/src/Socket/Client/types.js +9 -0
  51. package/src/Socket/Client/websocket.d.ts +12 -0
  52. package/src/Socket/Client/websocket.js +53 -0
  53. package/src/Socket/business.d.ts +431 -0
  54. package/src/Socket/business.js +379 -0
  55. package/src/Socket/chats.d.ts +247 -0
  56. package/src/Socket/chats.js +1484 -0
  57. package/src/Socket/communities.d.ts +598 -0
  58. package/src/Socket/communities.js +421 -0
  59. package/src/Socket/email.js +145 -0
  60. package/src/Socket/groups.d.ts +298 -0
  61. package/src/Socket/groups.js +339 -0
  62. package/src/Socket/index.d.ts +581 -0
  63. package/src/Socket/index.js +37 -0
  64. package/src/Socket/messages-recv.d.ts +370 -0
  65. package/src/Socket/messages-recv.js +1864 -0
  66. package/src/Socket/messages-send.d.ts +390 -0
  67. package/src/Socket/messages-send.js +1574 -0
  68. package/src/Socket/mex.d.ts +1 -0
  69. package/src/Socket/mex.js +44 -0
  70. package/src/Socket/mobile-builders.js +72 -0
  71. package/src/Socket/mobile.js +424 -0
  72. package/src/Socket/newsletter.d.ts +468 -0
  73. package/src/Socket/newsletter.js +671 -0
  74. package/src/Socket/socket.d.ts +77 -0
  75. package/src/Socket/socket.js +1106 -0
  76. package/src/Store/index.d.ts +3 -0
  77. package/src/Store/index.js +3 -0
  78. package/src/Store/make-in-memory-store.d.ts +62 -0
  79. package/src/Store/make-in-memory-store.js +396 -0
  80. package/src/Store/make-ordered-dictionary.d.ts +12 -0
  81. package/src/Store/make-ordered-dictionary.js +78 -0
  82. package/src/Store/object-repository.d.ts +10 -0
  83. package/src/Store/object-repository.js +23 -0
  84. package/src/Types/Auth.d.ts +1 -0
  85. package/src/Types/Auth.js +1 -0
  86. package/src/Types/Bussines.d.ts +1 -0
  87. package/src/Types/Bussines.js +1 -0
  88. package/src/Types/Call.d.ts +1 -0
  89. package/src/Types/Call.js +1 -0
  90. package/src/Types/Chat.d.ts +2 -0
  91. package/src/Types/Chat.js +24 -0
  92. package/src/Types/Contact.d.ts +1 -0
  93. package/src/Types/Contact.js +1 -0
  94. package/src/Types/Events.d.ts +1 -0
  95. package/src/Types/Events.js +0 -0
  96. package/src/Types/GroupMetadata.d.ts +5 -0
  97. package/src/Types/GroupMetadata.js +6 -0
  98. package/src/Types/Label.d.ts +2 -0
  99. package/src/Types/Label.js +24 -0
  100. package/src/Types/LabelAssociation.d.ts +2 -0
  101. package/src/Types/LabelAssociation.js +6 -0
  102. package/src/Types/Message.d.ts +13 -0
  103. package/src/Types/Message.js +23 -0
  104. package/src/Types/Mex.d.ts +2 -0
  105. package/src/Types/Mex.js +95 -0
  106. package/src/Types/Product.d.ts +1 -0
  107. package/src/Types/Product.js +1 -0
  108. package/src/Types/Signal.d.ts +1 -0
  109. package/src/Types/Signal.js +0 -0
  110. package/src/Types/Socket.d.ts +1 -0
  111. package/src/Types/Socket.js +0 -0
  112. package/src/Types/State.d.ts +5 -0
  113. package/src/Types/State.js +54 -0
  114. package/src/Types/USync.d.ts +1 -0
  115. package/src/Types/USync.js +0 -0
  116. package/src/Types/index.d.ts +13 -0
  117. package/src/Types/index.js +25 -0
  118. package/src/Utils/auth-store.d.ts +29 -0
  119. package/src/Utils/auth-store.js +76 -0
  120. package/src/Utils/auth-utils.d.ts +58 -0
  121. package/src/Utils/auth-utils.js +273 -0
  122. package/src/Utils/browser-utils.d.ts +9 -0
  123. package/src/Utils/browser-utils.js +28 -0
  124. package/src/Utils/business.d.ts +49 -0
  125. package/src/Utils/business.js +226 -0
  126. package/src/Utils/chat-utils.d.ts +408 -0
  127. package/src/Utils/chat-utils.js +846 -0
  128. package/src/Utils/companion-reg-client-utils.d.ts +4 -0
  129. package/src/Utils/companion-reg-client-utils.js +39 -0
  130. package/src/Utils/crypto.d.ts +39 -0
  131. package/src/Utils/crypto.js +110 -0
  132. package/src/Utils/decode-wa-message.d.ts +99 -0
  133. package/src/Utils/decode-wa-message.js +373 -0
  134. package/src/Utils/event-buffer.d.ts +22 -0
  135. package/src/Utils/event-buffer.js +624 -0
  136. package/src/Utils/generics.d.ts +63 -0
  137. package/src/Utils/generics.js +375 -0
  138. package/src/Utils/group-metadata-cache.d.ts +4 -0
  139. package/src/Utils/group-metadata-cache.js +25 -0
  140. package/src/Utils/history.d.ts +75 -0
  141. package/src/Utils/history.js +131 -0
  142. package/src/Utils/html-app.d.ts +19 -0
  143. package/src/Utils/html-app.js +96 -0
  144. package/src/Utils/html-multiplayer.d.ts +10 -0
  145. package/src/Utils/html-multiplayer.js +94 -0
  146. package/src/Utils/identity-change-handler.d.ts +13 -0
  147. package/src/Utils/identity-change-handler.js +48 -0
  148. package/src/Utils/index.d.ts +44 -0
  149. package/src/Utils/index.js +44 -0
  150. package/src/Utils/link-preview-metadata.d.ts +47 -0
  151. package/src/Utils/link-preview-metadata.js +88 -0
  152. package/src/Utils/link-preview.d.ts +12 -0
  153. package/src/Utils/link-preview.js +79 -0
  154. package/src/Utils/logger.d.ts +2 -0
  155. package/src/Utils/logger.js +2 -0
  156. package/src/Utils/lt-hash.d.ts +6 -0
  157. package/src/Utils/lt-hash.js +3 -0
  158. package/src/Utils/make-mutex.d.ts +6 -0
  159. package/src/Utils/make-mutex.js +32 -0
  160. package/src/Utils/message-retry-manager.d.ts +79 -0
  161. package/src/Utils/message-retry-manager.js +255 -0
  162. package/src/Utils/messages-media.d.ts +136 -0
  163. package/src/Utils/messages-media.js +814 -0
  164. package/src/Utils/messages.d.ts +62 -0
  165. package/src/Utils/messages.js +2223 -0
  166. package/src/Utils/mobile-companion-crypto.js +191 -0
  167. package/src/Utils/modern-messages.d.ts +150 -0
  168. package/src/Utils/modern-messages.js +496 -0
  169. package/src/Utils/native-flow.d.ts +11 -0
  170. package/src/Utils/native-flow.js +115 -0
  171. package/src/Utils/newsletter-status.d.ts +158 -0
  172. package/src/Utils/newsletter-status.js +651 -0
  173. package/src/Utils/noise-handler.d.ts +20 -0
  174. package/src/Utils/noise-handler.js +200 -0
  175. package/src/Utils/offline-node-processor.d.ts +9 -0
  176. package/src/Utils/offline-node-processor.js +33 -0
  177. package/src/Utils/optional-media.d.ts +3 -0
  178. package/src/Utils/optional-media.js +45 -0
  179. package/src/Utils/payment-messages.d.ts +66 -0
  180. package/src/Utils/payment-messages.js +160 -0
  181. package/src/Utils/pre-key-manager.d.ts +25 -0
  182. package/src/Utils/pre-key-manager.js +95 -0
  183. package/src/Utils/process-message.d.ts +60 -0
  184. package/src/Utils/process-message.js +688 -0
  185. package/src/Utils/reporting-utils.d.ts +12 -0
  186. package/src/Utils/reporting-utils.js +256 -0
  187. package/src/Utils/scheduled-message.d.ts +51 -0
  188. package/src/Utils/scheduled-message.js +112 -0
  189. package/src/Utils/sender-key-memory.d.ts +19 -0
  190. package/src/Utils/sender-key-memory.js +51 -0
  191. package/src/Utils/signal.d.ts +82 -0
  192. package/src/Utils/signal.js +193 -0
  193. package/src/Utils/stanza-ack.d.ts +16 -0
  194. package/src/Utils/stanza-ack.js +30 -0
  195. package/src/Utils/status-stickers.d.ts +127 -0
  196. package/src/Utils/status-stickers.js +260 -0
  197. package/src/Utils/sync-action-utils.d.ts +2 -0
  198. package/src/Utils/sync-action-utils.js +44 -0
  199. package/src/Utils/tc-token-utils.d.ts +29 -0
  200. package/src/Utils/tc-token-utils.js +155 -0
  201. package/src/Utils/ttl-cache.d.ts +28 -0
  202. package/src/Utils/ttl-cache.js +120 -0
  203. package/src/Utils/use-mongo-auth-state.d.ts +21 -0
  204. package/src/Utils/use-mongo-auth-state.js +67 -0
  205. package/src/Utils/use-multi-file-auth-state.d.ts +11 -0
  206. package/src/Utils/use-multi-file-auth-state.js +106 -0
  207. package/src/Utils/use-mysql-auth-state.d.ts +19 -0
  208. package/src/Utils/use-mysql-auth-state.js +79 -0
  209. package/src/Utils/use-postgres-auth-state.d.ts +19 -0
  210. package/src/Utils/use-postgres-auth-state.js +79 -0
  211. package/src/Utils/use-redis-auth-state.d.ts +19 -0
  212. package/src/Utils/use-redis-auth-state.js +89 -0
  213. package/src/Utils/use-single-file-auth-state.d.ts +10 -0
  214. package/src/Utils/use-single-file-auth-state.js +108 -0
  215. package/src/Utils/use-sqlite-auth-state.d.ts +12 -0
  216. package/src/Utils/use-sqlite-auth-state.js +120 -0
  217. package/src/Utils/useNekoDBAuth.d.ts +19 -0
  218. package/src/Utils/useNekoDBAuth.js +111 -0
  219. package/src/Utils/username.d.ts +12 -0
  220. package/src/Utils/username.js +58 -0
  221. package/src/Utils/validate-connection.d.ts +43 -0
  222. package/src/Utils/validate-connection.js +277 -0
  223. package/src/Utils/voice-recognition.d.ts +53 -0
  224. package/src/Utils/voice-recognition.js +219 -0
  225. package/src/Voip/audio-feeder.d.ts +24 -0
  226. package/src/Voip/audio-feeder.js +268 -0
  227. package/src/Voip/index.d.ts +88 -0
  228. package/src/Voip/index.js +936 -0
  229. package/src/Voip/relay-transport.d.ts +5 -0
  230. package/src/Voip/relay-transport.js +824 -0
  231. package/src/Voip/signaling.d.ts +11 -0
  232. package/src/Voip/signaling.js +1099 -0
  233. package/src/Voip/types.d.ts +2 -0
  234. package/src/Voip/types.js +12 -0
  235. package/src/Voip/video-feeder.d.ts +24 -0
  236. package/src/Voip/video-feeder.js +268 -0
  237. package/src/Voip/wasm-engine.d.ts +26 -0
  238. package/src/Voip/wasm-engine.js +1307 -0
  239. package/src/Voip/worker-bootstrap.js +1023 -0
  240. package/src/WABinary/constants.d.ts +22 -0
  241. package/src/WABinary/constants.js +1300 -0
  242. package/src/WABinary/decode.d.ts +9 -0
  243. package/src/WABinary/decode.js +261 -0
  244. package/src/WABinary/encode.d.ts +2 -0
  245. package/src/WABinary/encode.js +219 -0
  246. package/src/WABinary/generic-utils.d.ts +76 -0
  247. package/src/WABinary/generic-utils.js +214 -0
  248. package/src/WABinary/index.d.ts +5 -0
  249. package/src/WABinary/index.js +5 -0
  250. package/src/WABinary/jid-utils.d.ts +30 -0
  251. package/src/WABinary/jid-utils.js +97 -0
  252. package/src/WABinary/types.d.ts +1 -0
  253. package/src/WABinary/types.js +0 -0
  254. package/src/WAM/BinaryInfo.d.ts +7 -0
  255. package/src/WAM/BinaryInfo.js +9 -0
  256. package/src/WAM/constants.d.ts +34926 -0
  257. package/src/WAM/constants.js +22852 -0
  258. package/src/WAM/encode.d.ts +1 -0
  259. package/src/WAM/encode.js +148 -0
  260. package/src/WAM/index.d.ts +3 -0
  261. package/src/WAM/index.js +3 -0
  262. package/src/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  263. package/src/WAUSync/Protocols/USyncContactProtocol.js +50 -0
  264. package/src/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  265. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +51 -0
  266. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  267. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  268. package/src/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  269. package/src/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  270. package/src/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  271. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +23 -0
  272. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  273. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  274. package/src/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  275. package/src/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  276. package/src/WAUSync/Protocols/index.d.ts +5 -0
  277. package/src/WAUSync/Protocols/index.js +5 -0
  278. package/src/WAUSync/USyncQuery.d.ts +20 -0
  279. package/src/WAUSync/USyncQuery.js +93 -0
  280. package/src/WAUSync/USyncUser.d.ts +16 -0
  281. package/src/WAUSync/USyncUser.js +30 -0
  282. package/src/WAUSync/index.d.ts +3 -0
  283. package/src/WAUSync/index.js +3 -0
  284. package/src/assets/wasm/README.md +76 -0
  285. package/src/assets/wasm/loader.js +5 -0
  286. package/src/assets/wasm/whatsapp.wasm +0 -0
  287. package/src/assets/wasm/worker-modules.js +273 -0
  288. package/src/index.d.ts +43 -0
  289. package/src/index.js +48 -0
@@ -0,0 +1,79 @@
1
+ export const RetryReason: any;
2
+ export class MessageRetryManager {
3
+ constructor(logger: any, maxMsgRetryCount?: number);
4
+ logger: any;
5
+ recentMessagesMap: any;
6
+ messageKeyIndex: Map<string, Set<string>>;
7
+ sessionRecreateHistory: any;
8
+ retryCounters: any;
9
+ baseKeys: any;
10
+ pendingPhoneRequests: {};
11
+ maxMsgRetryCount: any;
12
+ statistics: {
13
+ totalRetries: number;
14
+ successfulRetries: number;
15
+ failedRetries: number;
16
+ mediaRetries: number;
17
+ sessionRecreations: number;
18
+ phoneRequests: number;
19
+ };
20
+ /**
21
+ * Add a recent message to the cache for retry handling
22
+ */
23
+ addRecentMessage(to: any, id: any, message: any): void;
24
+ /**
25
+ * Get a recent message from the cache
26
+ */
27
+ getRecentMessage(to: any, id: any): any;
28
+ /**
29
+ * Check if a session should be recreated based on retry count, history, and error code.
30
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
31
+ */
32
+ shouldRecreateSession(jid: any, hasSession: any, errorCode: any): {
33
+ reason: string;
34
+ recreate: boolean;
35
+ };
36
+ /**
37
+ * Parse error code from retry receipt's retry node.
38
+ * Returns undefined if no error code is present.
39
+ */
40
+ parseRetryErrorCode(errorAttr: any): any;
41
+ /**
42
+ * Check if an error code indicates a MAC failure
43
+ */
44
+ isMacError(errorCode: any): boolean;
45
+ /**
46
+ * Increment retry counter for a message
47
+ */
48
+ incrementRetryCount(messageId: any): any;
49
+ /**
50
+ * Get retry count for a message
51
+ */
52
+ getRetryCount(messageId: any): any;
53
+ /**
54
+ * Check if message has exceeded maximum retry attempts
55
+ */
56
+ hasExceededMaxRetries(messageId: any): boolean;
57
+ /**
58
+ * Mark retry as successful
59
+ */
60
+ markRetrySuccess(messageId: any): void;
61
+ /**
62
+ * Mark retry as failed
63
+ */
64
+ markRetryFailed(messageId: any): void;
65
+ /**
66
+ * Schedule a phone request with delay
67
+ */
68
+ schedulePhoneRequest(messageId: any, callback: any, delay?: number): void;
69
+ /**
70
+ * Cancel pending phone request
71
+ */
72
+ cancelPendingPhoneRequest(messageId: any): void;
73
+ clear(): void;
74
+ saveBaseKey(addr: any, msgId: any, baseKey: any): void;
75
+ hasSameBaseKey(addr: any, msgId: any, baseKey: any): boolean;
76
+ deleteBaseKey(addr: any, msgId: any): void;
77
+ keyToString(key: any): string;
78
+ removeRecentMessage(messageId: any): void;
79
+ }
@@ -0,0 +1,255 @@
1
+ import { LRUCache } from 'lru-cache';
2
+
3
+ const RECENT_MESSAGES_SIZE = 1024;
4
+ const MESSAGE_KEY_SEPARATOR = '\u0000';
5
+
6
+ const DEFAULT_MAX_MSG_RETRY_COUNT = 5;
7
+
8
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000;
9
+ const PHONE_REQUEST_DELAY = 3000;
10
+
11
+ export var RetryReason;
12
+ (function (RetryReason) {
13
+ RetryReason[RetryReason["UnknownError"] = 0] = "UnknownError";
14
+ RetryReason[RetryReason["SignalErrorNoSession"] = 1] = "SignalErrorNoSession";
15
+ RetryReason[RetryReason["SignalErrorInvalidKey"] = 2] = "SignalErrorInvalidKey";
16
+ RetryReason[RetryReason["SignalErrorInvalidKeyId"] = 3] = "SignalErrorInvalidKeyId";
17
+
18
+ RetryReason[RetryReason["SignalErrorInvalidMessage"] = 4] = "SignalErrorInvalidMessage";
19
+ RetryReason[RetryReason["SignalErrorInvalidSignature"] = 5] = "SignalErrorInvalidSignature";
20
+ RetryReason[RetryReason["SignalErrorFutureMessage"] = 6] = "SignalErrorFutureMessage";
21
+
22
+ RetryReason[RetryReason["SignalErrorBadMac"] = 7] = "SignalErrorBadMac";
23
+ RetryReason[RetryReason["SignalErrorInvalidSession"] = 8] = "SignalErrorInvalidSession";
24
+ RetryReason[RetryReason["SignalErrorInvalidMsgKey"] = 9] = "SignalErrorInvalidMsgKey";
25
+ RetryReason[RetryReason["BadBroadcastEphemeralSetting"] = 10] = "BadBroadcastEphemeralSetting";
26
+ RetryReason[RetryReason["UnknownCompanionNoPrekey"] = 11] = "UnknownCompanionNoPrekey";
27
+ RetryReason[RetryReason["AdvFailure"] = 12] = "AdvFailure";
28
+ RetryReason[RetryReason["StatusRevokeDelay"] = 13] = "StatusRevokeDelay";
29
+ })(RetryReason || (RetryReason = {}));
30
+
31
+ const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac]);
32
+ export class MessageRetryManager {
33
+ constructor(logger, maxMsgRetryCount) {
34
+ this.logger = logger;
35
+ this.recentMessagesMap = new LRUCache({
36
+ max: RECENT_MESSAGES_SIZE,
37
+ ttl: 5 * 60 * 1000,
38
+ ttlAutopurge: true,
39
+ dispose: (_value, key) => {
40
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR);
41
+ if (separatorIndex === -1) {
42
+ return;
43
+ }
44
+ const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length);
45
+ const keys = this.messageKeyIndex.get(messageId);
46
+ if (!keys) {
47
+ return;
48
+ }
49
+ keys.delete(key);
50
+ if (!keys.size) {
51
+ this.messageKeyIndex.delete(messageId);
52
+ }
53
+ }
54
+ });
55
+ this.messageKeyIndex = new Map();
56
+ this.sessionRecreateHistory = new LRUCache({
57
+ ttl: RECREATE_SESSION_TIMEOUT * 2,
58
+ ttlAutopurge: true
59
+ });
60
+ this.retryCounters = new LRUCache({
61
+ ttl: 15 * 60 * 1000,
62
+ ttlAutopurge: true,
63
+ updateAgeOnGet: true
64
+ });
65
+ this.baseKeys = new LRUCache({
66
+ max: 1024,
67
+ ttl: 15 * 60 * 1000,
68
+ ttlAutopurge: true
69
+ });
70
+ this.pendingPhoneRequests = {};
71
+ this.statistics = {
72
+ totalRetries: 0,
73
+ successfulRetries: 0,
74
+ failedRetries: 0,
75
+ mediaRetries: 0,
76
+ sessionRecreations: 0,
77
+ phoneRequests: 0
78
+ };
79
+ this.maxMsgRetryCount = Number.isInteger(maxMsgRetryCount) ? maxMsgRetryCount : DEFAULT_MAX_MSG_RETRY_COUNT;
80
+ }
81
+
82
+ addRecentMessage(to, id, message) {
83
+ const key = { to, id };
84
+ const keyStr = this.keyToString(key);
85
+
86
+ this.recentMessagesMap.set(keyStr, {
87
+ message,
88
+ timestamp: Date.now()
89
+ });
90
+ const keys = this.messageKeyIndex.get(id);
91
+ if (keys) {
92
+ keys.add(keyStr);
93
+ }
94
+ else {
95
+ this.messageKeyIndex.set(id, new Set([keyStr]));
96
+ }
97
+ this.logger.debug(`Added message to retry cache: ${to}/${id}`);
98
+ }
99
+
100
+ getRecentMessage(to, id) {
101
+ const key = { to, id };
102
+ const keyStr = this.keyToString(key);
103
+ return this.recentMessagesMap.get(keyStr);
104
+ }
105
+
106
+ shouldRecreateSession(jid, hasSession, errorCode) {
107
+
108
+ if (!hasSession) {
109
+ this.sessionRecreateHistory.set(jid, Date.now());
110
+ this.statistics.sessionRecreations++;
111
+ return {
112
+ reason: "we don't have a Signal session with them",
113
+ recreate: true
114
+ };
115
+ }
116
+
117
+ if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
118
+ this.sessionRecreateHistory.set(jid, Date.now());
119
+ this.statistics.sessionRecreations++;
120
+ this.logger.warn({ jid, errorCode: RetryReason[errorCode] }, 'MAC error detected, forcing immediate session recreation');
121
+ return {
122
+ reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
123
+ recreate: true
124
+ };
125
+ }
126
+ const now = Date.now();
127
+ const prevTime = this.sessionRecreateHistory.get(jid);
128
+
129
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
130
+ this.sessionRecreateHistory.set(jid, now);
131
+ this.statistics.sessionRecreations++;
132
+ return {
133
+ reason: 'retry count > 1 and over an hour since last recreation',
134
+ recreate: true
135
+ };
136
+ }
137
+ return { reason: '', recreate: false };
138
+ }
139
+
140
+ parseRetryErrorCode(errorAttr) {
141
+ if (errorAttr === undefined || errorAttr === '') {
142
+ return undefined;
143
+ }
144
+ const code = parseInt(errorAttr, 10);
145
+ if (Number.isNaN(code)) {
146
+ return undefined;
147
+ }
148
+
149
+ if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
150
+ return code;
151
+ }
152
+ return RetryReason.UnknownError;
153
+ }
154
+
155
+ isMacError(errorCode) {
156
+ return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode);
157
+ }
158
+
159
+ incrementRetryCount(messageId) {
160
+ this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
161
+ this.statistics.totalRetries++;
162
+ return this.retryCounters.get(messageId);
163
+ }
164
+
165
+ getRetryCount(messageId) {
166
+ return this.retryCounters.get(messageId) || 0;
167
+ }
168
+
169
+ hasExceededMaxRetries(messageId) {
170
+ return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
171
+ }
172
+
173
+ markRetrySuccess(messageId) {
174
+ this.statistics.successfulRetries++;
175
+
176
+ this.retryCounters.delete(messageId);
177
+ this.cancelPendingPhoneRequest(messageId);
178
+ this.removeRecentMessage(messageId);
179
+ }
180
+
181
+ markRetryFailed(messageId) {
182
+ this.statistics.failedRetries++;
183
+ this.retryCounters.delete(messageId);
184
+ this.cancelPendingPhoneRequest(messageId);
185
+ this.removeRecentMessage(messageId);
186
+ }
187
+
188
+ schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
189
+
190
+ this.cancelPendingPhoneRequest(messageId);
191
+ this.pendingPhoneRequests[messageId] = setTimeout(() => {
192
+ delete this.pendingPhoneRequests[messageId];
193
+ this.statistics.phoneRequests++;
194
+ callback();
195
+ }, delay);
196
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
197
+ }
198
+
199
+ cancelPendingPhoneRequest(messageId) {
200
+ const timeout = this.pendingPhoneRequests[messageId];
201
+ if (timeout) {
202
+ clearTimeout(timeout);
203
+ delete this.pendingPhoneRequests[messageId];
204
+ this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
205
+ }
206
+ }
207
+ clear() {
208
+ this.recentMessagesMap.clear();
209
+ this.messageKeyIndex.clear();
210
+ this.sessionRecreateHistory.clear();
211
+ this.retryCounters.clear();
212
+ this.baseKeys.clear();
213
+ for (const messageId of Object.keys(this.pendingPhoneRequests)) {
214
+ this.cancelPendingPhoneRequest(messageId);
215
+ }
216
+ this.statistics = {
217
+ totalRetries: 0,
218
+ successfulRetries: 0,
219
+ failedRetries: 0,
220
+ mediaRetries: 0,
221
+ sessionRecreations: 0,
222
+ phoneRequests: 0
223
+ };
224
+ }
225
+ saveBaseKey(addr, msgId, baseKey) {
226
+ this.baseKeys.set(`${addr}:${msgId}`, baseKey);
227
+ }
228
+ hasSameBaseKey(addr, msgId, baseKey) {
229
+ const stored = this.baseKeys.get(`${addr}:${msgId}`);
230
+ if (!stored || stored.length !== baseKey.length) {
231
+ return false;
232
+ }
233
+ for (let i = 0; i < stored.length; i++) {
234
+ if (stored[i] !== baseKey[i])
235
+ return false;
236
+ }
237
+ return true;
238
+ }
239
+ deleteBaseKey(addr, msgId) {
240
+ this.baseKeys.delete(`${addr}:${msgId}`);
241
+ }
242
+ keyToString(key) {
243
+ return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`;
244
+ }
245
+ removeRecentMessage(messageId) {
246
+ const keys = this.messageKeyIndex.get(messageId);
247
+ if (!keys) {
248
+ return;
249
+ }
250
+ for (const keyStr of [...keys]) {
251
+ this.recentMessagesMap.delete(keyStr);
252
+ }
253
+ this.messageKeyIndex.delete(messageId);
254
+ }
255
+ }
@@ -0,0 +1,136 @@
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';