violetics 7.0.1-alpha → 7.0.2-alpha

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 (114) hide show
  1. package/LICENSE +3 -2
  2. package/README.md +1001 -232
  3. package/WAProto/index.js +75379 -142631
  4. package/engine-requirements.js +11 -8
  5. package/lib/Defaults/index.js +132 -146
  6. package/lib/Signal/Group/ciphertext-message.js +2 -6
  7. package/lib/Signal/Group/group-session-builder.js +7 -42
  8. package/lib/Signal/Group/group_cipher.js +37 -52
  9. package/lib/Signal/Group/index.js +11 -57
  10. package/lib/Signal/Group/keyhelper.js +7 -45
  11. package/lib/Signal/Group/sender-chain-key.js +7 -16
  12. package/lib/Signal/Group/sender-key-distribution-message.js +8 -12
  13. package/lib/Signal/Group/sender-key-message.js +9 -13
  14. package/lib/Signal/Group/sender-key-name.js +2 -6
  15. package/lib/Signal/Group/sender-key-record.js +9 -22
  16. package/lib/Signal/Group/sender-key-state.js +27 -43
  17. package/lib/Signal/Group/sender-message-key.js +4 -8
  18. package/lib/Signal/libsignal.js +319 -94
  19. package/lib/Signal/lid-mapping.js +224 -139
  20. package/lib/Socket/Client/index.js +2 -19
  21. package/lib/Socket/Client/types.js +10 -0
  22. package/lib/Socket/Client/websocket.js +53 -0
  23. package/lib/Socket/business.js +162 -44
  24. package/lib/Socket/chats.js +477 -418
  25. package/lib/Socket/communities.js +430 -0
  26. package/lib/Socket/groups.js +110 -99
  27. package/lib/Socket/index.js +10 -10
  28. package/lib/Socket/messages-recv.js +884 -561
  29. package/lib/Socket/messages-send.js +859 -428
  30. package/lib/Socket/mex.js +41 -0
  31. package/lib/Socket/newsletter.js +195 -390
  32. package/lib/Socket/socket.js +465 -315
  33. package/lib/Store/index.js +3 -10
  34. package/lib/Store/make-in-memory-store.js +73 -79
  35. package/lib/Store/make-ordered-dictionary.js +4 -7
  36. package/lib/Store/object-repository.js +2 -6
  37. package/lib/Types/Auth.js +1 -2
  38. package/lib/Types/Bussines.js +1 -0
  39. package/lib/Types/Call.js +1 -2
  40. package/lib/Types/Chat.js +7 -4
  41. package/lib/Types/Contact.js +1 -2
  42. package/lib/Types/Events.js +1 -2
  43. package/lib/Types/GroupMetadata.js +1 -2
  44. package/lib/Types/Label.js +2 -5
  45. package/lib/Types/LabelAssociation.js +2 -5
  46. package/lib/Types/Message.js +17 -9
  47. package/lib/Types/Newsletter.js +33 -38
  48. package/lib/Types/Product.js +1 -2
  49. package/lib/Types/Signal.js +1 -2
  50. package/lib/Types/Socket.js +2 -2
  51. package/lib/Types/State.js +12 -2
  52. package/lib/Types/USync.js +1 -2
  53. package/lib/Types/index.js +14 -31
  54. package/lib/Utils/auth-utils.js +228 -152
  55. package/lib/Utils/browser-utils.js +28 -0
  56. package/lib/Utils/business.js +66 -70
  57. package/lib/Utils/chat-utils.js +331 -249
  58. package/lib/Utils/crypto.js +57 -91
  59. package/lib/Utils/decode-wa-message.js +168 -84
  60. package/lib/Utils/event-buffer.js +138 -80
  61. package/lib/Utils/generics.js +180 -297
  62. package/lib/Utils/history.js +83 -49
  63. package/lib/Utils/identity-change-handler.js +48 -0
  64. package/lib/Utils/index.js +19 -33
  65. package/lib/Utils/link-preview.js +14 -23
  66. package/lib/Utils/logger.js +2 -7
  67. package/lib/Utils/lt-hash.js +2 -46
  68. package/lib/Utils/make-mutex.js +24 -47
  69. package/lib/Utils/message-retry-manager.js +224 -0
  70. package/lib/Utils/messages-media.js +501 -496
  71. package/lib/Utils/messages.js +1428 -362
  72. package/lib/Utils/noise-handler.js +145 -100
  73. package/lib/Utils/pre-key-manager.js +105 -0
  74. package/lib/Utils/process-message.js +356 -150
  75. package/lib/Utils/reporting-utils.js +257 -0
  76. package/lib/Utils/signal.js +78 -73
  77. package/lib/Utils/sync-action-utils.js +47 -0
  78. package/lib/Utils/tc-token-utils.js +17 -0
  79. package/lib/Utils/use-multi-file-auth-state.js +35 -45
  80. package/lib/Utils/validate-connection.js +91 -107
  81. package/lib/WABinary/constants.js +1300 -1304
  82. package/lib/WABinary/decode.js +26 -48
  83. package/lib/WABinary/encode.js +109 -155
  84. package/lib/WABinary/generic-utils.js +161 -149
  85. package/lib/WABinary/index.js +5 -21
  86. package/lib/WABinary/jid-utils.js +73 -40
  87. package/lib/WABinary/types.js +1 -2
  88. package/lib/WAM/BinaryInfo.js +2 -6
  89. package/lib/WAM/constants.js +19070 -11568
  90. package/lib/WAM/encode.js +17 -23
  91. package/lib/WAM/index.js +3 -19
  92. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -12
  93. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -15
  94. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -13
  95. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -14
  96. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -23
  97. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -9
  98. package/lib/WAUSync/Protocols/index.js +4 -20
  99. package/lib/WAUSync/USyncQuery.js +40 -36
  100. package/lib/WAUSync/USyncUser.js +2 -6
  101. package/lib/WAUSync/index.js +3 -19
  102. package/lib/index.js +11 -44
  103. package/package.json +74 -107
  104. package/lib/Defaults/baileys-version.json +0 -3
  105. package/lib/Defaults/phonenumber-mcc.json +0 -223
  106. package/lib/Signal/Group/queue-job.js +0 -57
  107. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  108. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  109. package/lib/Socket/Client/web-socket-client.js +0 -118
  110. package/lib/Socket/groupStatus.js +0 -637
  111. package/lib/Socket/registration.js +0 -166
  112. package/lib/Socket/usync.js +0 -70
  113. package/lib/Store/make-cache-manager-store.js +0 -83
  114. package/lib/Utils/baileys-event-stream.js +0 -63
@@ -0,0 +1,224 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ /** Number of sent messages to cache in memory for handling retry receipts */
3
+ const RECENT_MESSAGES_SIZE = 512;
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
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]);
30
+ export class MessageRetryManager {
31
+ constructor(logger, maxMsgRetryCount) {
32
+ this.logger = logger;
33
+ this.recentMessagesMap = new LRUCache({
34
+ max: RECENT_MESSAGES_SIZE,
35
+ ttl: 5 * 60 * 1000,
36
+ ttlAutopurge: true,
37
+ dispose: (_value, key) => {
38
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR);
39
+ if (separatorIndex > -1) {
40
+ const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length);
41
+ this.messageKeyIndex.delete(messageId);
42
+ }
43
+ }
44
+ });
45
+ this.messageKeyIndex = new Map();
46
+ this.sessionRecreateHistory = new LRUCache({
47
+ ttl: RECREATE_SESSION_TIMEOUT * 2,
48
+ ttlAutopurge: true
49
+ });
50
+ this.retryCounters = new LRUCache({
51
+ ttl: 15 * 60 * 1000,
52
+ ttlAutopurge: true,
53
+ updateAgeOnGet: true
54
+ }); // 15 minutes TTL
55
+ this.pendingPhoneRequests = {};
56
+ this.maxMsgRetryCount = 5;
57
+ this.statistics = {
58
+ totalRetries: 0,
59
+ successfulRetries: 0,
60
+ failedRetries: 0,
61
+ mediaRetries: 0,
62
+ sessionRecreations: 0,
63
+ phoneRequests: 0
64
+ };
65
+ this.maxMsgRetryCount = maxMsgRetryCount;
66
+ }
67
+ /**
68
+ * Add a recent message to the cache for retry handling
69
+ */
70
+ addRecentMessage(to, id, message) {
71
+ const key = { to, id };
72
+ const keyStr = this.keyToString(key);
73
+ // Add new message
74
+ this.recentMessagesMap.set(keyStr, {
75
+ message,
76
+ timestamp: Date.now()
77
+ });
78
+ this.messageKeyIndex.set(id, keyStr);
79
+ this.logger.debug(`Added message to retry cache: ${to}/${id}`);
80
+ }
81
+ /**
82
+ * Get a recent message from the cache
83
+ */
84
+ getRecentMessage(to, id) {
85
+ const key = { to, id };
86
+ const keyStr = this.keyToString(key);
87
+ return this.recentMessagesMap.get(keyStr);
88
+ }
89
+ /**
90
+ * Check if a session should be recreated based on retry count, history, and error code.
91
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
92
+ */
93
+ shouldRecreateSession(jid, hasSession, errorCode) {
94
+ // If we don't have a session, always recreate
95
+ if (!hasSession) {
96
+ this.sessionRecreateHistory.set(jid, Date.now());
97
+ this.statistics.sessionRecreations++;
98
+ return {
99
+ reason: "we don't have a Signal session with them",
100
+ recreate: true
101
+ };
102
+ }
103
+ // IMMEDIATE recreation for MAC errors - session is definitely out of sync
104
+ if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
105
+ this.sessionRecreateHistory.set(jid, Date.now());
106
+ this.statistics.sessionRecreations++;
107
+ this.logger.warn({ jid, errorCode: RetryReason[errorCode] }, 'MAC error detected, forcing immediate session recreation');
108
+ return {
109
+ reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
110
+ recreate: true
111
+ };
112
+ }
113
+ const now = Date.now();
114
+ const prevTime = this.sessionRecreateHistory.get(jid);
115
+ // If no previous recreation or it's been more than an hour
116
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
117
+ this.sessionRecreateHistory.set(jid, now);
118
+ this.statistics.sessionRecreations++;
119
+ return {
120
+ reason: 'retry count > 1 and over an hour since last recreation',
121
+ recreate: true
122
+ };
123
+ }
124
+ return { reason: '', recreate: false };
125
+ }
126
+ /**
127
+ * Parse error code from retry receipt's retry node.
128
+ * Returns undefined if no error code is present.
129
+ */
130
+ parseRetryErrorCode(errorAttr) {
131
+ if (errorAttr === undefined || errorAttr === '') {
132
+ return undefined;
133
+ }
134
+ const code = parseInt(errorAttr, 10);
135
+ if (Number.isNaN(code)) {
136
+ return undefined;
137
+ }
138
+ // Validate it's a known RetryReason
139
+ if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
140
+ return code;
141
+ }
142
+ return RetryReason.UnknownError;
143
+ }
144
+ /**
145
+ * Check if an error code indicates a MAC failure
146
+ */
147
+ isMacError(errorCode) {
148
+ return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode);
149
+ }
150
+ /**
151
+ * Increment retry counter for a message
152
+ */
153
+ incrementRetryCount(messageId) {
154
+ this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1);
155
+ this.statistics.totalRetries++;
156
+ return this.retryCounters.get(messageId);
157
+ }
158
+ /**
159
+ * Get retry count for a message
160
+ */
161
+ getRetryCount(messageId) {
162
+ return this.retryCounters.get(messageId) || 0;
163
+ }
164
+ /**
165
+ * Check if message has exceeded maximum retry attempts
166
+ */
167
+ hasExceededMaxRetries(messageId) {
168
+ return this.getRetryCount(messageId) >= this.maxMsgRetryCount;
169
+ }
170
+ /**
171
+ * Mark retry as successful
172
+ */
173
+ markRetrySuccess(messageId) {
174
+ this.statistics.successfulRetries++;
175
+ // Clean up retry counter for successful message
176
+ this.retryCounters.delete(messageId);
177
+ this.cancelPendingPhoneRequest(messageId);
178
+ this.removeRecentMessage(messageId);
179
+ }
180
+ /**
181
+ * Mark retry as failed
182
+ */
183
+ markRetryFailed(messageId) {
184
+ this.statistics.failedRetries++;
185
+ this.retryCounters.delete(messageId);
186
+ this.cancelPendingPhoneRequest(messageId);
187
+ this.removeRecentMessage(messageId);
188
+ }
189
+ /**
190
+ * Schedule a phone request with delay
191
+ */
192
+ schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
193
+ // Cancel any existing request for this message
194
+ this.cancelPendingPhoneRequest(messageId);
195
+ this.pendingPhoneRequests[messageId] = setTimeout(() => {
196
+ delete this.pendingPhoneRequests[messageId];
197
+ this.statistics.phoneRequests++;
198
+ callback();
199
+ }, delay);
200
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`);
201
+ }
202
+ /**
203
+ * Cancel pending phone request
204
+ */
205
+ cancelPendingPhoneRequest(messageId) {
206
+ const timeout = this.pendingPhoneRequests[messageId];
207
+ if (timeout) {
208
+ clearTimeout(timeout);
209
+ delete this.pendingPhoneRequests[messageId];
210
+ this.logger.debug(`Cancelled pending phone request for message ${messageId}`);
211
+ }
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
+ }
224
+ }