@fer2809fl/baileys 7.0.2 → 7.0.5

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 (267) hide show
  1. package/README.md +409 -32
  2. package/lib/Defaults/index.js +2 -1
  3. package/lib/Modded/message_builder.js +2356 -0
  4. package/lib/Signal/libsignal.js +19 -0
  5. package/lib/Socket/business.d.ts +213 -532
  6. package/lib/Socket/business.js +359 -401
  7. package/lib/Socket/chats.d.ts +30 -2
  8. package/lib/Socket/chats.js +295 -40
  9. package/lib/Socket/groups.d.ts +16 -0
  10. package/lib/Socket/groups.js +101 -18
  11. package/lib/Socket/index.d.ts +17 -0
  12. package/lib/Socket/messages-recv.js +18 -1
  13. package/lib/Socket/messages-send.d.ts +18 -0
  14. package/lib/Socket/messages-send.js +50 -2
  15. package/lib/Socket/newsletter.js +3 -3
  16. package/lib/Socket/socket.js +50 -6
  17. package/lib/Types/Newsletter.d.ts +13 -4
  18. package/lib/Types/Newsletter.js +12 -2
  19. package/lib/Utils/anti-ban.d.ts +41 -0
  20. package/lib/Utils/anti-ban.js +182 -0
  21. package/lib/Utils/banner.d.ts +8 -0
  22. package/lib/Utils/banner.js +76 -0
  23. package/lib/Utils/bot-utils.d.ts +57 -0
  24. package/lib/Utils/bot-utils.js +241 -0
  25. package/lib/Utils/chat-utils.d.ts +34 -4
  26. package/lib/Utils/chat-utils.js +80 -20
  27. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  28. package/lib/Utils/companion-reg-client-utils.js +35 -0
  29. package/lib/Utils/enhanced-cache.d.ts +40 -0
  30. package/lib/Utils/enhanced-cache.js +242 -0
  31. package/lib/Utils/enhanced-logger.d.ts +41 -0
  32. package/lib/Utils/enhanced-logger.js +185 -0
  33. package/lib/Utils/event-buffer.js +49 -1
  34. package/lib/Utils/index.d.ts +14 -0
  35. package/lib/Utils/index.js +14 -0
  36. package/lib/Utils/lid-utils.d.ts +139 -0
  37. package/lib/Utils/lid-utils.js +503 -0
  38. package/lib/Utils/message-queue.d.ts +47 -0
  39. package/lib/Utils/message-queue.js +226 -0
  40. package/lib/Utils/message-retry-manager.js +40 -0
  41. package/lib/Utils/rich-message-utils.d.ts +21 -0
  42. package/lib/Utils/rich-message-utils.js +229 -0
  43. package/lib/Utils/rich-messages.d.ts +52 -0
  44. package/lib/Utils/rich-messages.js +185 -0
  45. package/lib/Utils/scheduled-messages.d.ts +122 -0
  46. package/lib/Utils/scheduled-messages.js +289 -0
  47. package/lib/Utils/smart-reconnect.d.ts +48 -0
  48. package/lib/Utils/smart-reconnect.js +207 -0
  49. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  50. package/lib/Utils/use-sqlite-auth-state.js +95 -0
  51. package/lib/VoIP/audio-feeder.d.ts +15 -0
  52. package/lib/VoIP/audio-feeder.js +132 -0
  53. package/lib/VoIP/index.js +277 -0
  54. package/lib/VoIP/relay-transport.d.ts +43 -0
  55. package/lib/VoIP/relay-transport.js +559 -0
  56. package/lib/VoIP/signaling.js +594 -0
  57. package/lib/VoIP/types.d.ts +69 -0
  58. package/lib/VoIP/types.js +17 -0
  59. package/lib/VoIP/wasm-engine.d.ts +103 -0
  60. package/lib/VoIP/wasm-engine.js +1214 -0
  61. package/lib/VoIP/worker-bootstrap.js +1042 -0
  62. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  63. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  64. package/lib/WAUSync/Protocols/index.js +1 -0
  65. package/lib/WAUSync/USyncQuery.js +5 -1
  66. package/lib/assets/wasm/loader.js +5 -0
  67. package/lib/assets/wasm/whatsapp.wasm +0 -0
  68. package/lib/assets/wasm/worker-modules.js +273 -0
  69. package/lib/index.d.ts +41 -0
  70. package/lib/index.js +3 -0
  71. package/package.json +15 -7
  72. package/lib/Defaults/index.d.ts.map +0 -1
  73. package/lib/Defaults/index.js.map +0 -1
  74. package/lib/Signal/Group/ciphertext-message.d.ts.map +0 -1
  75. package/lib/Signal/Group/ciphertext-message.js.map +0 -1
  76. package/lib/Signal/Group/group-session-builder.d.ts.map +0 -1
  77. package/lib/Signal/Group/group-session-builder.js.map +0 -1
  78. package/lib/Signal/Group/group_cipher.d.ts.map +0 -1
  79. package/lib/Signal/Group/group_cipher.js.map +0 -1
  80. package/lib/Signal/Group/index.d.ts.map +0 -1
  81. package/lib/Signal/Group/index.js.map +0 -1
  82. package/lib/Signal/Group/keyhelper.d.ts.map +0 -1
  83. package/lib/Signal/Group/keyhelper.js.map +0 -1
  84. package/lib/Signal/Group/sender-chain-key.d.ts.map +0 -1
  85. package/lib/Signal/Group/sender-chain-key.js.map +0 -1
  86. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +0 -1
  87. package/lib/Signal/Group/sender-key-distribution-message.js.map +0 -1
  88. package/lib/Signal/Group/sender-key-message.d.ts.map +0 -1
  89. package/lib/Signal/Group/sender-key-message.js.map +0 -1
  90. package/lib/Signal/Group/sender-key-name.d.ts.map +0 -1
  91. package/lib/Signal/Group/sender-key-name.js.map +0 -1
  92. package/lib/Signal/Group/sender-key-record.d.ts.map +0 -1
  93. package/lib/Signal/Group/sender-key-record.js.map +0 -1
  94. package/lib/Signal/Group/sender-key-state.d.ts.map +0 -1
  95. package/lib/Signal/Group/sender-key-state.js.map +0 -1
  96. package/lib/Signal/Group/sender-message-key.d.ts.map +0 -1
  97. package/lib/Signal/Group/sender-message-key.js.map +0 -1
  98. package/lib/Signal/libsignal.d.ts.map +0 -1
  99. package/lib/Signal/libsignal.js.map +0 -1
  100. package/lib/Signal/lid-mapping.d.ts.map +0 -1
  101. package/lib/Signal/lid-mapping.js.map +0 -1
  102. package/lib/Socket/Client/index.d.ts.map +0 -1
  103. package/lib/Socket/Client/index.js.map +0 -1
  104. package/lib/Socket/Client/types.d.ts.map +0 -1
  105. package/lib/Socket/Client/types.js.map +0 -1
  106. package/lib/Socket/Client/websocket.d.ts.map +0 -1
  107. package/lib/Socket/Client/websocket.js.map +0 -1
  108. package/lib/Socket/business.d.ts.map +0 -1
  109. package/lib/Socket/business.js.map +0 -1
  110. package/lib/Socket/chats.d.ts.map +0 -1
  111. package/lib/Socket/chats.js.map +0 -1
  112. package/lib/Socket/communities.d.ts.map +0 -1
  113. package/lib/Socket/communities.js.map +0 -1
  114. package/lib/Socket/dugong.d.ts.map +0 -1
  115. package/lib/Socket/dugong.js.map +0 -1
  116. package/lib/Socket/groups.d.ts.map +0 -1
  117. package/lib/Socket/groups.js.map +0 -1
  118. package/lib/Socket/index.d.ts.map +0 -1
  119. package/lib/Socket/index.js.map +0 -1
  120. package/lib/Socket/messages-recv.d.ts.map +0 -1
  121. package/lib/Socket/messages-recv.js.map +0 -1
  122. package/lib/Socket/messages-send.d.ts.map +0 -1
  123. package/lib/Socket/messages-send.js.map +0 -1
  124. package/lib/Socket/mex.d.ts.map +0 -1
  125. package/lib/Socket/mex.js.map +0 -1
  126. package/lib/Socket/newsletter.d.ts.map +0 -1
  127. package/lib/Socket/newsletter.js.map +0 -1
  128. package/lib/Socket/socket.d.ts.map +0 -1
  129. package/lib/Socket/socket.js.map +0 -1
  130. package/lib/Types/Auth.d.ts.map +0 -1
  131. package/lib/Types/Auth.js.map +0 -1
  132. package/lib/Types/Bussines.d.ts.map +0 -1
  133. package/lib/Types/Bussines.js.map +0 -1
  134. package/lib/Types/Call.d.ts.map +0 -1
  135. package/lib/Types/Call.js.map +0 -1
  136. package/lib/Types/Chat.d.ts.map +0 -1
  137. package/lib/Types/Chat.js.map +0 -1
  138. package/lib/Types/Contact.d.ts.map +0 -1
  139. package/lib/Types/Contact.js.map +0 -1
  140. package/lib/Types/Events.d.ts.map +0 -1
  141. package/lib/Types/Events.js.map +0 -1
  142. package/lib/Types/GroupMetadata.d.ts.map +0 -1
  143. package/lib/Types/GroupMetadata.js.map +0 -1
  144. package/lib/Types/Label.d.ts.map +0 -1
  145. package/lib/Types/Label.js.map +0 -1
  146. package/lib/Types/LabelAssociation.d.ts.map +0 -1
  147. package/lib/Types/LabelAssociation.js.map +0 -1
  148. package/lib/Types/Message.d.ts.map +0 -1
  149. package/lib/Types/Message.js.map +0 -1
  150. package/lib/Types/Newsletter.d.ts.map +0 -1
  151. package/lib/Types/Newsletter.js.map +0 -1
  152. package/lib/Types/Product.d.ts.map +0 -1
  153. package/lib/Types/Product.js.map +0 -1
  154. package/lib/Types/Signal.d.ts.map +0 -1
  155. package/lib/Types/Signal.js.map +0 -1
  156. package/lib/Types/Socket.d.ts.map +0 -1
  157. package/lib/Types/Socket.js.map +0 -1
  158. package/lib/Types/State.d.ts.map +0 -1
  159. package/lib/Types/State.js.map +0 -1
  160. package/lib/Types/USync.d.ts.map +0 -1
  161. package/lib/Types/USync.js.map +0 -1
  162. package/lib/Types/index.d.ts.map +0 -1
  163. package/lib/Types/index.js.map +0 -1
  164. package/lib/Utils/auth-utils.d.ts.map +0 -1
  165. package/lib/Utils/auth-utils.js.map +0 -1
  166. package/lib/Utils/browser-utils.d.ts.map +0 -1
  167. package/lib/Utils/browser-utils.js.map +0 -1
  168. package/lib/Utils/business.d.ts.map +0 -1
  169. package/lib/Utils/business.js.map +0 -1
  170. package/lib/Utils/chat-utils.d.ts.map +0 -1
  171. package/lib/Utils/chat-utils.js.map +0 -1
  172. package/lib/Utils/crypto.d.ts.map +0 -1
  173. package/lib/Utils/crypto.js.map +0 -1
  174. package/lib/Utils/decode-wa-message.d.ts.map +0 -1
  175. package/lib/Utils/decode-wa-message.js.map +0 -1
  176. package/lib/Utils/event-buffer.d.ts.map +0 -1
  177. package/lib/Utils/event-buffer.js.map +0 -1
  178. package/lib/Utils/generics.d.ts.map +0 -1
  179. package/lib/Utils/generics.js.map +0 -1
  180. package/lib/Utils/history.d.ts.map +0 -1
  181. package/lib/Utils/history.js.map +0 -1
  182. package/lib/Utils/identity-change-handler.d.ts.map +0 -1
  183. package/lib/Utils/identity-change-handler.js.map +0 -1
  184. package/lib/Utils/index.d.ts.map +0 -1
  185. package/lib/Utils/index.js.map +0 -1
  186. package/lib/Utils/link-preview.d.ts.map +0 -1
  187. package/lib/Utils/link-preview.js.map +0 -1
  188. package/lib/Utils/logger.d.ts.map +0 -1
  189. package/lib/Utils/logger.js.map +0 -1
  190. package/lib/Utils/lt-hash.d.ts.map +0 -1
  191. package/lib/Utils/lt-hash.js.map +0 -1
  192. package/lib/Utils/make-mutex.d.ts.map +0 -1
  193. package/lib/Utils/make-mutex.js.map +0 -1
  194. package/lib/Utils/message-retry-manager.d.ts.map +0 -1
  195. package/lib/Utils/message-retry-manager.js.map +0 -1
  196. package/lib/Utils/messages-media.d.ts.map +0 -1
  197. package/lib/Utils/messages-media.js.map +0 -1
  198. package/lib/Utils/messages.d.ts.map +0 -1
  199. package/lib/Utils/messages.js.map +0 -1
  200. package/lib/Utils/noise-handler.d.ts.map +0 -1
  201. package/lib/Utils/noise-handler.js.map +0 -1
  202. package/lib/Utils/offline-node-processor.d.ts.map +0 -1
  203. package/lib/Utils/offline-node-processor.js.map +0 -1
  204. package/lib/Utils/pre-key-manager.d.ts.map +0 -1
  205. package/lib/Utils/pre-key-manager.js.map +0 -1
  206. package/lib/Utils/process-message.d.ts.map +0 -1
  207. package/lib/Utils/process-message.js.map +0 -1
  208. package/lib/Utils/reporting-utils.d.ts.map +0 -1
  209. package/lib/Utils/reporting-utils.js.map +0 -1
  210. package/lib/Utils/rich-messages.d.ts.map +0 -1
  211. package/lib/Utils/rich-messages.js.map +0 -1
  212. package/lib/Utils/signal.d.ts.map +0 -1
  213. package/lib/Utils/signal.js.map +0 -1
  214. package/lib/Utils/stanza-ack.d.ts.map +0 -1
  215. package/lib/Utils/stanza-ack.js.map +0 -1
  216. package/lib/Utils/sync-action-utils.d.ts.map +0 -1
  217. package/lib/Utils/sync-action-utils.js.map +0 -1
  218. package/lib/Utils/tc-token-utils.d.ts.map +0 -1
  219. package/lib/Utils/tc-token-utils.js.map +0 -1
  220. package/lib/Utils/use-multi-file-auth-state.d.ts.map +0 -1
  221. package/lib/Utils/use-multi-file-auth-state.js.map +0 -1
  222. package/lib/Utils/validate-connection.d.ts.map +0 -1
  223. package/lib/Utils/validate-connection.js.map +0 -1
  224. package/lib/WABinary/constants.d.ts.map +0 -1
  225. package/lib/WABinary/constants.js.map +0 -1
  226. package/lib/WABinary/decode.d.ts.map +0 -1
  227. package/lib/WABinary/decode.js.map +0 -1
  228. package/lib/WABinary/encode.d.ts.map +0 -1
  229. package/lib/WABinary/encode.js.map +0 -1
  230. package/lib/WABinary/generic-utils.d.ts.map +0 -1
  231. package/lib/WABinary/generic-utils.js.map +0 -1
  232. package/lib/WABinary/index.d.ts.map +0 -1
  233. package/lib/WABinary/index.js.map +0 -1
  234. package/lib/WABinary/jid-utils.d.ts.map +0 -1
  235. package/lib/WABinary/jid-utils.js.map +0 -1
  236. package/lib/WABinary/types.d.ts.map +0 -1
  237. package/lib/WABinary/types.js.map +0 -1
  238. package/lib/WAM/BinaryInfo.d.ts.map +0 -1
  239. package/lib/WAM/BinaryInfo.js.map +0 -1
  240. package/lib/WAM/constants.d.ts.map +0 -1
  241. package/lib/WAM/constants.js.map +0 -1
  242. package/lib/WAM/encode.d.ts.map +0 -1
  243. package/lib/WAM/encode.js.map +0 -1
  244. package/lib/WAM/index.d.ts.map +0 -1
  245. package/lib/WAM/index.js.map +0 -1
  246. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +0 -1
  247. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +0 -1
  248. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +0 -1
  249. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +0 -1
  250. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +0 -1
  251. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +0 -1
  252. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +0 -1
  253. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +0 -1
  254. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +0 -1
  255. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +0 -1
  256. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +0 -1
  257. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +0 -1
  258. package/lib/WAUSync/Protocols/index.d.ts.map +0 -1
  259. package/lib/WAUSync/Protocols/index.js.map +0 -1
  260. package/lib/WAUSync/USyncQuery.d.ts.map +0 -1
  261. package/lib/WAUSync/USyncQuery.js.map +0 -1
  262. package/lib/WAUSync/USyncUser.d.ts.map +0 -1
  263. package/lib/WAUSync/USyncUser.js.map +0 -1
  264. package/lib/WAUSync/index.d.ts.map +0 -1
  265. package/lib/WAUSync/index.js.map +0 -1
  266. package/lib/index.d.ts.map +0 -1
  267. package/lib/index.js.map +0 -1
@@ -0,0 +1,182 @@
1
+ import { randomBytes } from 'crypto';
2
+
3
+ const ANTI_BAN_CONFIG = {
4
+ MIN_MESSAGE_DELAY: 300,
5
+ MAX_MESSAGE_DELAY: 800,
6
+ MIN_TYPING_DELAY: 500,
7
+ MAX_TYPING_DELAY: 1500,
8
+ GROUP_MESSAGE_DELAY: 500,
9
+ GROUP_MAX_MESSAGES_PER_MINUTE: 40,
10
+ BROADCAST_DELAY: 1500,
11
+ BROADCAST_MAX_PER_HOUR: 300,
12
+ PRESENCE_UPDATE_INTERVAL: 30000,
13
+ JITTER_PERCENT: 0.3
14
+ };
15
+
16
+ function randomDelay(min, max) {
17
+ const base = Math.floor(Math.random() * (max - min + 1)) + min;
18
+ const jitter = base * ANTI_BAN_CONFIG.JITTER_PERCENT * (Math.random() - 0.5);
19
+ return Math.max(min, Math.floor(base + jitter));
20
+ }
21
+
22
+ async function messageDelay(isGroup = false) {
23
+ const delay = isGroup
24
+ ? randomDelay(ANTI_BAN_CONFIG.GROUP_MESSAGE_DELAY, ANTI_BAN_CONFIG.GROUP_MESSAGE_DELAY * 2)
25
+ : randomDelay(ANTI_BAN_CONFIG.MIN_MESSAGE_DELAY, ANTI_BAN_CONFIG.MAX_MESSAGE_DELAY);
26
+ return new Promise(resolve => setTimeout(resolve, delay));
27
+ }
28
+
29
+ async function typingDelay(messageLength = 50) {
30
+ const wordsPerMinute = 50 + (Math.random() * 20 - 10);
31
+ const avgWordLength = 5;
32
+ const estimatedWords = messageLength / avgWordLength;
33
+ const typingTime = (estimatedWords / wordsPerMinute) * 60 * 1000;
34
+ const minDelay = ANTI_BAN_CONFIG.MIN_TYPING_DELAY;
35
+ const calculatedDelay = Math.max(minDelay, Math.min(typingTime, ANTI_BAN_CONFIG.MAX_TYPING_DELAY));
36
+ return new Promise(resolve => setTimeout(resolve, calculatedDelay));
37
+ }
38
+
39
+ class RateLimiter {
40
+ constructor(maxRequests, windowMs) {
41
+ this.maxRequests = maxRequests;
42
+ this.windowMs = windowMs;
43
+ this.requests = new Map();
44
+ }
45
+
46
+ canSend(jid) {
47
+ const now = Date.now();
48
+ const key = jid || 'global';
49
+ if (!this.requests.has(key)) this.requests.set(key, []);
50
+ const timestamps = this.requests.get(key);
51
+ const validTimestamps = timestamps.filter(ts => now - ts < this.windowMs);
52
+ this.requests.set(key, validTimestamps);
53
+ return validTimestamps.length < this.maxRequests;
54
+ }
55
+
56
+ recordSend(jid) {
57
+ const key = jid || 'global';
58
+ if (!this.requests.has(key)) this.requests.set(key, []);
59
+ this.requests.get(key).push(Date.now());
60
+ }
61
+
62
+ getWaitTime(jid) {
63
+ const key = jid || 'global';
64
+ if (!this.requests.has(key)) return 0;
65
+ const timestamps = this.requests.get(key);
66
+ if (timestamps.length < this.maxRequests) return 0;
67
+ const oldestValid = timestamps[timestamps.length - this.maxRequests];
68
+ const waitTime = this.windowMs - (Date.now() - oldestValid);
69
+ return Math.max(0, waitTime);
70
+ }
71
+
72
+ async waitForSlot(jid) {
73
+ const waitTime = this.getWaitTime(jid);
74
+ if (waitTime > 0) {
75
+ await new Promise(resolve => setTimeout(resolve, waitTime + randomDelay(100, 500)));
76
+ }
77
+ this.recordSend(jid);
78
+ }
79
+
80
+ cleanup() {
81
+ const now = Date.now();
82
+ for (const [key, timestamps] of this.requests.entries()) {
83
+ const valid = timestamps.filter(ts => now - ts < this.windowMs);
84
+ if (valid.length === 0) this.requests.delete(key);
85
+ else this.requests.set(key, valid);
86
+ }
87
+ }
88
+ }
89
+
90
+ class PresenceManager {
91
+ constructor(sock, logger) {
92
+ this.sock = sock;
93
+ this.logger = logger;
94
+ this.activeChats = new Set();
95
+ this.presenceInterval = null;
96
+ }
97
+
98
+ async simulatePresence(jid, action = 'composing') {
99
+ try {
100
+ await this.sock.sendPresenceUpdate(action, jid);
101
+ this.activeChats.add(jid);
102
+ setTimeout(() => {
103
+ this.activeChats.delete(jid);
104
+ this.sock.sendPresenceUpdate('paused', jid).catch(() => {});
105
+ }, randomDelay(3000, 8000));
106
+ } catch (error) {
107
+ this.logger?.debug({ error }, 'Error updating presence');
108
+ }
109
+ }
110
+
111
+ async sendWithPresence(jid, sendFunc, messageContent) {
112
+ await this.simulatePresence(jid, 'composing');
113
+ const length = typeof messageContent === 'string'
114
+ ? messageContent.length
115
+ : JSON.stringify(messageContent).length;
116
+ await typingDelay(length);
117
+ const result = await sendFunc();
118
+ setTimeout(() => {
119
+ this.sock.sendPresenceUpdate('paused', jid).catch(() => {});
120
+ }, randomDelay(500, 1500));
121
+ return result;
122
+ }
123
+
124
+ startPeriodicPresence() {
125
+ if (this.presenceInterval) return;
126
+ this.presenceInterval = setInterval(() => {
127
+ this.sock.sendPresenceUpdate('available').catch(() => {});
128
+ }, ANTI_BAN_CONFIG.PRESENCE_UPDATE_INTERVAL);
129
+ }
130
+
131
+ stopPeriodicPresence() {
132
+ if (this.presenceInterval) {
133
+ clearInterval(this.presenceInterval);
134
+ this.presenceInterval = null;
135
+ }
136
+ }
137
+ }
138
+
139
+ function generateSessionFingerprint() {
140
+ const timestamp = Date.now();
141
+ const random = randomBytes(8).toString('hex');
142
+ return `${timestamp}-${random}`;
143
+ }
144
+
145
+ function isValidJid(jid) {
146
+ if (!jid || typeof jid !== 'string') return false;
147
+ const patterns = [
148
+ /^\d+@s\.whatsapp\.net$/,
149
+ /^\d+-\d+@g\.us$/,
150
+ /^\d+@broadcast$/,
151
+ /^status@broadcast$/,
152
+ /^\d+@lid$/
153
+ ];
154
+ return patterns.some(pattern => pattern.test(jid));
155
+ }
156
+
157
+ function sanitizeMessage(text) {
158
+ if (!text || typeof text !== 'string') return text;
159
+ let sanitized = text.replace(/[\u200B-\u200D\uFEFF]/g, '');
160
+ sanitized = sanitized.replace(/\n{4,}/g, '\n\n\n');
161
+ sanitized = sanitized.replace(/ {3,}/g, ' ');
162
+ return sanitized.trim();
163
+ }
164
+
165
+ const globalRateLimiter = new RateLimiter(100, 60000);
166
+ const groupRateLimiter = new RateLimiter(20, 60000);
167
+ const broadcastRateLimiter = new RateLimiter(200, 3600000);
168
+
169
+ export {
170
+ ANTI_BAN_CONFIG,
171
+ randomDelay,
172
+ messageDelay,
173
+ typingDelay,
174
+ RateLimiter,
175
+ PresenceManager,
176
+ generateSessionFingerprint,
177
+ isValidJid,
178
+ sanitizeMessage,
179
+ globalRateLimiter,
180
+ groupRateLimiter,
181
+ broadcastRateLimiter
182
+ };
@@ -0,0 +1,8 @@
1
+ export declare const BAILEYS_LOGO: string[];
2
+
3
+ export declare function printBanner(options?: {
4
+ stream?: NodeJS.WritableStream;
5
+ frameMs?: number;
6
+ once?: boolean;
7
+ animate?: boolean;
8
+ }): Promise<void>;
@@ -0,0 +1,76 @@
1
+ import { readFileSync } from 'fs';
2
+ import { join } from 'path';
3
+
4
+ const BAILEYS_LOGO = [
5
+ ' ⠠⡀ ⡀',
6
+ ' ⠱⣄⠘⣆',
7
+ ' ⣀ ⢢⣤⣀⣦⣄⡀⠙⣶⡘⢷⣄',
8
+ ' ⣀⣀⣨⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣯⣿⣷⣄',
9
+ ' ⢀⣽⣿⣿⣿⣿⠟⠛⠛⠛⠛⠻⢿⣿⣿⣿⣿⣿⣿⣷⣄',
10
+ ' ⠘⣻⣿⣿⡿⠋ ⠈⠙⢿⣿⣿⣿⣿⢿⣷⡀',
11
+ ' ⣴⣿⣿⣿⡇ ⠙⣿⣿⣿⣷⣽⣷⣄',
12
+ ' ⣾⣿⣿⣇ ⠈⠛⢿⣿⣿⣿⣯⠁',
13
+ ' ⠐⠛⢿⣿⣿⣦⡀ ⠉⠻⣿⣿⣷⣄⡀',
14
+ ' ⠘⠟⠿⣿⣿⣦⣀ ⠈⢿⣿⣿⠇',
15
+ ' ⠈⠙⠻⣿⣷⣦⣄⡀ ⡼⠟⠋',
16
+ ' ⠈⠙⠻⢿⣷⣶⣄',
17
+ ' ⠈⠙⠻⣿⣦⡀',
18
+ ' ⠙⢿⡄',
19
+ ' ⢻⡄',
20
+ ' ⠈⡇'
21
+ ];
22
+
23
+ const GRADIENT_FROM = [167, 85, 247];
24
+ const GRADIENT_TO = [34, 211, 238];
25
+
26
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
27
+
28
+ const supportsColor = stream => {
29
+ if (process.env.NO_COLOR || process.env.NODE_DISABLE_COLORS) return false;
30
+ if (process.env.FORCE_COLOR) return true;
31
+ return !!stream.isTTY;
32
+ };
33
+
34
+ const paint = (text, t) => {
35
+ const [r, g, b] = GRADIENT_FROM.map((from, i) => Math.round(from + (GRADIENT_TO[i] - from) * t));
36
+ return `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
37
+ };
38
+
39
+ const buildLines = version => [
40
+ '',
41
+ ...BAILEYS_LOGO,
42
+ '',
43
+ ` @fer2809fl/baileys v${version}`,
44
+ ' github.com/Fer2809fl/Bail',
45
+ ''
46
+ ];
47
+
48
+ let alreadyPrinted = false;
49
+
50
+ const printBanner = async (options = {}) => {
51
+ let version = '2.0';
52
+ try {
53
+ const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf8'));
54
+ version = pkg.version || version;
55
+ } catch {}
56
+ const {
57
+ stream = process.stdout,
58
+ frameMs = 45,
59
+ once = true
60
+ } = options;
61
+ if (once && alreadyPrinted) return;
62
+ alreadyPrinted = true;
63
+ const animate = options.animate !== undefined ? options.animate : !!stream.isTTY;
64
+ const color = supportsColor(stream);
65
+ const lines = buildLines(version);
66
+ for (let i = 0; i < lines.length; i++) {
67
+ const t = i / (lines.length - 1);
68
+ stream.write((color ? paint(lines[i], t) : lines[i]) + '\n');
69
+ if (animate) await sleep(frameMs);
70
+ }
71
+ };
72
+
73
+ export {
74
+ BAILEYS_LOGO,
75
+ printBanner
76
+ };
@@ -0,0 +1,57 @@
1
+ export declare function parseCommand(text: string, prefix?: string): {
2
+ isCommand: boolean;
3
+ command?: string;
4
+ args?: string[];
5
+ fullArgs?: string;
6
+ flags?: Record<string, string | boolean>;
7
+ raw?: string;
8
+ prefix?: string;
9
+ };
10
+
11
+ export declare function extractMentions(message: any): string[];
12
+ export declare function extractText(message: any): string;
13
+ export declare function extractQuotedMessage(message: any): {
14
+ message: any;
15
+ stanzaId?: string;
16
+ participant?: string;
17
+ remoteJid?: string;
18
+ text: string;
19
+ } | null;
20
+
21
+ export declare function isGroupAdmin(sock: any, jid: string, participantJid: string): Promise<boolean>;
22
+ export declare function isBotAdmin(sock: any, jid: string): Promise<boolean>;
23
+ export declare function getSenderJid(msg: any): string;
24
+ export declare function formatJid(jid: string): string;
25
+ export declare function generateMessageId(): string;
26
+ export declare function truncateText(text: string, maxLength?: number, suffix?: string): string;
27
+ export declare function escapeMarkdown(text: string): string;
28
+ export declare function formatPhoneNumber(jid: string): string;
29
+
30
+ export declare class CooldownManager {
31
+ isOnCooldown(key: string, cooldownMs: number): boolean;
32
+ setCooldown(key: string, cooldownMs: number): void;
33
+ getRemainingTime(key: string): number;
34
+ cleanup(): void;
35
+ }
36
+
37
+ export declare class PermissionManager {
38
+ constructor(config?: { owners?: string[]; admins?: string[]; banned?: string[]; premiums?: string[] });
39
+ isOwner(jid: string): boolean;
40
+ isAdmin(jid: string): boolean;
41
+ isBanned(jid: string): boolean;
42
+ isPremium(jid: string): boolean;
43
+ addOwner(jid: string): void;
44
+ removeOwner(jid: string): void;
45
+ addAdmin(jid: string): void;
46
+ removeAdmin(jid: string): void;
47
+ ban(jid: string): void;
48
+ unban(jid: string): void;
49
+ addPremium(jid: string): void;
50
+ removePremium(jid: string): void;
51
+ toJSON(): { owners: string[]; admins: string[]; banned: string[]; premiums: string[] };
52
+ }
53
+
54
+ export declare function createReply(options: { text: string; mentions?: string[]; quoted?: any }): { text: string; mentions?: string[]; quoted?: any };
55
+ export declare function parseTime(timeStr: string): number;
56
+ export declare function formatDuration(ms: number): string;
57
+ export declare function sendFast(sock: any, jid: string, content: string | object, opts?: { quoted?: any; markRead?: boolean }): Promise<any>;
@@ -0,0 +1,241 @@
1
+ import { isJidGroup, jidDecode, jidNormalizedUser } from '../WABinary/index.js';
2
+ import { randomBytes } from 'crypto';
3
+
4
+ function parseCommand(text, prefix = '.') {
5
+ if (!text || typeof text !== 'string') return { isCommand: false };
6
+ const trimmed = text.trim();
7
+ if (!trimmed.startsWith(prefix)) return { isCommand: false };
8
+ const withoutPrefix = trimmed.slice(prefix.length);
9
+ const parts = withoutPrefix.split(/\s+/);
10
+ const command = parts[0].toLowerCase();
11
+ const args = parts.slice(1);
12
+ const fullArgs = withoutPrefix.slice(command.length).trim();
13
+ const flags = {};
14
+ const cleanArgs = [];
15
+ for (const arg of args) {
16
+ if (arg.startsWith('--')) {
17
+ const [key, value] = arg.slice(2).split('=');
18
+ flags[key] = value || true;
19
+ } else if (arg.startsWith('-') && arg.length === 2) {
20
+ flags[arg.slice(1)] = true;
21
+ } else {
22
+ cleanArgs.push(arg);
23
+ }
24
+ }
25
+ return { isCommand: true, command, args: cleanArgs, fullArgs, flags, raw: text, prefix };
26
+ }
27
+
28
+ function extractMentions(message) {
29
+ const mentions = [];
30
+ const extendedText = message.extendedTextMessage;
31
+ if (extendedText?.contextInfo?.mentionedJid) mentions.push(...extendedText.contextInfo.mentionedJid);
32
+ if (message.mentionedJid) mentions.push(...message.mentionedJid);
33
+ const text = extractText(message);
34
+ if (text) {
35
+ const phoneMatches = text.match(/@(\d+)/g);
36
+ if (phoneMatches) {
37
+ phoneMatches.forEach(match => {
38
+ const phone = match.slice(1);
39
+ const jid = `${phone}@s.whatsapp.net`;
40
+ if (!mentions.includes(jid)) mentions.push(jid);
41
+ });
42
+ }
43
+ }
44
+ return [...new Set(mentions)];
45
+ }
46
+
47
+ function extractText(message) {
48
+ if (!message) return '';
49
+ if (typeof message === 'string') return message;
50
+ const textSources = [
51
+ message.conversation,
52
+ message.extendedTextMessage?.text,
53
+ message.imageMessage?.caption,
54
+ message.videoMessage?.caption,
55
+ message.documentMessage?.caption,
56
+ message.buttonsResponseMessage?.selectedButtonId,
57
+ message.listResponseMessage?.singleSelectReply?.selectedRowId,
58
+ message.templateButtonReplyMessage?.selectedId
59
+ ];
60
+ return textSources.find(t => t) || '';
61
+ }
62
+
63
+ function extractQuotedMessage(message) {
64
+ const contextInfo =
65
+ message.extendedTextMessage?.contextInfo ||
66
+ message.imageMessage?.contextInfo ||
67
+ message.videoMessage?.contextInfo ||
68
+ message.documentMessage?.contextInfo ||
69
+ message.stickerMessage?.contextInfo;
70
+ if (!contextInfo?.quotedMessage) return null;
71
+ return {
72
+ message: contextInfo.quotedMessage,
73
+ stanzaId: contextInfo.stanzaId,
74
+ participant: contextInfo.participant,
75
+ remoteJid: contextInfo.remoteJid,
76
+ text: extractText(contextInfo.quotedMessage)
77
+ };
78
+ }
79
+
80
+ async function isGroupAdmin(sock, jid, participantJid) {
81
+ try {
82
+ if (!isJidGroup(jid)) return false;
83
+ const metadata = await sock.groupMetadata(jid);
84
+ const participant = metadata.participants.find(
85
+ p => jidNormalizedUser(p.id) === jidNormalizedUser(participantJid)
86
+ );
87
+ return participant?.admin === 'admin' || participant?.admin === 'superadmin';
88
+ } catch { return false; }
89
+ }
90
+
91
+ async function isBotAdmin(sock, jid) {
92
+ const botJid = sock.user?.id;
93
+ if (!botJid) return false;
94
+ return isGroupAdmin(sock, jid, botJid);
95
+ }
96
+
97
+ function getSenderJid(msg) {
98
+ const isGroup = isJidGroup(msg.key.remoteJid);
99
+ return isGroup ? msg.key.participant : msg.key.remoteJid;
100
+ }
101
+
102
+ function formatJid(jid) {
103
+ if (!jid) return 'Unknown';
104
+ const decoded = jidDecode(jid);
105
+ return decoded?.user || jid.split('@')[0] || jid;
106
+ }
107
+
108
+ function generateMessageId() {
109
+ const timestamp = Date.now().toString(36);
110
+ const random = randomBytes(8).toString('hex');
111
+ return `${timestamp}-${random}`.toUpperCase();
112
+ }
113
+
114
+ function truncateText(text, maxLength = 100, suffix = '...') {
115
+ if (!text || text.length <= maxLength) return text;
116
+ return text.slice(0, maxLength - suffix.length) + suffix;
117
+ }
118
+
119
+ function escapeMarkdown(text) {
120
+ if (!text) return '';
121
+ return text.replace(/([*_`\[\]()])/g, '\\$1');
122
+ }
123
+
124
+ function formatPhoneNumber(jid) {
125
+ const number = jid.replace(/[^0-9]/g, '');
126
+ if (number.length >= 10) {
127
+ const countryCode = number.slice(0, -10);
128
+ const areaCode = number.slice(-10, -7);
129
+ const first = number.slice(-7, -4);
130
+ const last = number.slice(-4);
131
+ return `+${countryCode} ${areaCode} ${first} ${last}`;
132
+ }
133
+ return number;
134
+ }
135
+
136
+ class CooldownManager {
137
+ constructor() { this.cooldowns = new Map(); }
138
+ isOnCooldown(key, cooldownMs) {
139
+ const expiry = this.cooldowns.get(key);
140
+ if (!expiry) return false;
141
+ if (Date.now() < expiry) return true;
142
+ this.cooldowns.delete(key);
143
+ return false;
144
+ }
145
+ setCooldown(key, cooldownMs) { this.cooldowns.set(key, Date.now() + cooldownMs); }
146
+ getRemainingTime(key) {
147
+ const expiry = this.cooldowns.get(key);
148
+ if (!expiry) return 0;
149
+ return Math.max(0, expiry - Date.now());
150
+ }
151
+ cleanup() {
152
+ const now = Date.now();
153
+ for (const [key, expiry] of this.cooldowns) {
154
+ if (now >= expiry) this.cooldowns.delete(key);
155
+ }
156
+ }
157
+ }
158
+
159
+ class PermissionManager {
160
+ constructor(config = {}) {
161
+ this.owners = new Set(config.owners || []);
162
+ this.admins = new Set(config.admins || []);
163
+ this.banned = new Set(config.banned || []);
164
+ this.premiums = new Set(config.premiums || []);
165
+ }
166
+ isOwner(jid) { return this.owners.has(jidNormalizedUser(jid)); }
167
+ isAdmin(jid) {
168
+ const normalized = jidNormalizedUser(jid);
169
+ return this.admins.has(normalized) || this.owners.has(normalized);
170
+ }
171
+ isBanned(jid) { return this.banned.has(jidNormalizedUser(jid)); }
172
+ isPremium(jid) { return this.premiums.has(jidNormalizedUser(jid)); }
173
+ addOwner(jid) { this.owners.add(jidNormalizedUser(jid)); }
174
+ removeOwner(jid) { this.owners.delete(jidNormalizedUser(jid)); }
175
+ addAdmin(jid) { this.admins.add(jidNormalizedUser(jid)); }
176
+ removeAdmin(jid) { this.admins.delete(jidNormalizedUser(jid)); }
177
+ ban(jid) { this.banned.add(jidNormalizedUser(jid)); }
178
+ unban(jid) { this.banned.delete(jidNormalizedUser(jid)); }
179
+ addPremium(jid) { this.premiums.add(jidNormalizedUser(jid)); }
180
+ removePremium(jid) { this.premiums.delete(jidNormalizedUser(jid)); }
181
+ toJSON() {
182
+ return { owners: [...this.owners], admins: [...this.admins], banned: [...this.banned], premiums: [...this.premiums] };
183
+ }
184
+ }
185
+
186
+ function createReply(options) {
187
+ const { text, mentions = [], quoted = null } = options;
188
+ const message = { text };
189
+ if (mentions.length > 0) message.mentions = mentions;
190
+ if (quoted) message.quoted = quoted;
191
+ return message;
192
+ }
193
+
194
+ function parseTime(timeStr) {
195
+ if (!timeStr || typeof timeStr !== 'string') return 0;
196
+ const units = { s: 1000, m: 60 * 1000, h: 60 * 60 * 1000, d: 24 * 60 * 60 * 1000, w: 7 * 24 * 60 * 60 * 1000 };
197
+ const match = timeStr.match(/^(\d+)([smhdw])$/i);
198
+ if (!match) return 0;
199
+ const value = parseInt(match[1]);
200
+ const unit = match[2].toLowerCase();
201
+ return value * (units[unit] || 0);
202
+ }
203
+
204
+ function formatDuration(ms) {
205
+ const seconds = Math.floor(ms / 1000);
206
+ const minutes = Math.floor(seconds / 60);
207
+ const hours = Math.floor(minutes / 60);
208
+ const days = Math.floor(hours / 24);
209
+ if (days > 0) return `${days}d ${hours % 24}h`;
210
+ if (hours > 0) return `${hours}h ${minutes % 60}m`;
211
+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
212
+ return `${seconds}s`;
213
+ }
214
+
215
+ async function sendFast(sock, jid, content, opts = {}) {
216
+ const { quoted = null, markRead = false } = opts;
217
+ const message = typeof content === 'string' ? { text: content } : content;
218
+ if (markRead && quoted?.key) sock.readMessages([quoted.key]).catch(() => {});
219
+ return sock.sendMessage(jid, message, quoted ? { quoted } : {});
220
+ }
221
+
222
+ export {
223
+ parseCommand,
224
+ extractMentions,
225
+ extractText,
226
+ extractQuotedMessage,
227
+ isGroupAdmin,
228
+ isBotAdmin,
229
+ getSenderJid,
230
+ formatJid,
231
+ generateMessageId,
232
+ truncateText,
233
+ escapeMarkdown,
234
+ formatPhoneNumber,
235
+ CooldownManager,
236
+ PermissionManager,
237
+ createReply,
238
+ parseTime,
239
+ formatDuration,
240
+ sendFast
241
+ };
@@ -6,13 +6,43 @@ type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSy
6
6
  export type ChatMutationMap = {
7
7
  [index: string]: ChatMutation;
8
8
  };
9
+ type Mac = {
10
+ indexMac: Uint8Array;
11
+ valueMac: Uint8Array;
12
+ operation: proto.SyncdMutation.SyncdOperation;
13
+ };
14
+ export declare const makeLtHashGenerator: ({ indexValueMap, hash }: Pick<LTHashState, "hash" | "indexValueMap">) => {
15
+ mix: ({ indexMac, valueMac, operation }: Mac) => void;
16
+ finish: () => {
17
+ hash: Buffer<ArrayBuffer>;
18
+ indexValueMap: {
19
+ [indexMacBase64: string]: {
20
+ valueMac: Uint8Array | Buffer;
21
+ };
22
+ };
23
+ };
24
+ };
9
25
  export declare const newLTHashState: () => LTHashState;
26
+ export declare const ensureLTHashStateVersion: (state: LTHashState) => LTHashState;
27
+ export declare const MAX_SYNC_ATTEMPTS = 2;
28
+ /**
29
+ * Check if an error is a missing app state sync key.
30
+ * WA Web treats these as "Blocked" (waits for key arrival), not fatal.
31
+ * In Baileys we retry with a snapshot which may use a different key.
32
+ */
33
+ export declare const isMissingKeyError: (error: any) => boolean;
34
+ /**
35
+ * Determines if an app state sync error is unrecoverable.
36
+ * TypeError indicates a WASM crash; otherwise we give up after MAX_SYNC_ATTEMPTS.
37
+ * Missing keys are NOT checked here — they are handled separately as "Blocked".
38
+ */
39
+ export declare const isAppStateSyncIrrecoverable: (error: any, attempts: number) => boolean;
10
40
  export declare const encodeSyncdPatch: ({ type, index, syncAction, apiVersion, operation }: WAPatchCreate, myAppStateKeyId: string, state: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey) => Promise<{
11
41
  patch: proto.ISyncdPatch;
12
42
  state: LTHashState;
13
43
  }>;
14
44
  export declare const decodeSyncdMutations: (msgMutations: (proto.ISyncdMutation | proto.ISyncdRecord)[], initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
15
- hash: Buffer;
45
+ hash: Buffer<ArrayBuffer>;
16
46
  indexValueMap: {
17
47
  [indexMacBase64: string]: {
18
48
  valueMac: Uint8Array | Buffer;
@@ -20,7 +50,7 @@ export declare const decodeSyncdMutations: (msgMutations: (proto.ISyncdMutation
20
50
  };
21
51
  }>;
22
52
  export declare const decodeSyncdPatch: (msg: proto.ISyncdPatch, name: WAPatchName, initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
23
- hash: Buffer;
53
+ hash: Buffer<ArrayBuffer>;
24
54
  indexValueMap: {
25
55
  [indexMacBase64: string]: {
26
56
  valueMac: Uint8Array | Buffer;
@@ -54,9 +84,9 @@ export declare const extractSyncdPatches: (result: BinaryNode, options: RequestI
54
84
  snapshot?: proto.ISyncdSnapshot;
55
85
  };
56
86
  }>;
57
- export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: RequestInit) => Promise<Buffer>;
87
+ export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: RequestInit) => Promise<Buffer<ArrayBuffer>>;
58
88
  export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: RequestInit) => Promise<proto.SyncdMutations>;
59
- export declare const decodeSyncdSnapshot: (name: WAPatchName, snapshot: proto.ISyncdSnapshot, getAppStateSyncKey: FetchAppStateSyncKey, minimumVersionNumber: number | undefined, validateMacs?: boolean) => Promise<{
89
+ export declare const decodeSyncdSnapshot: (name: WAPatchName, snapshot: proto.ISyncdSnapshot, getAppStateSyncKey: FetchAppStateSyncKey, minimumVersionNumber: number | undefined, validateMacs?: boolean, logger?: ILogger) => Promise<{
60
90
  state: LTHashState;
61
91
  mutationMap: ChatMutationMap;
62
92
  }>;