@vanzxy/baileys 2.0.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 (281) hide show
  1. package/NOTICE.md +111 -0
  2. package/README.md +830 -0
  3. package/WAProto/index.d.ts +9 -0
  4. package/WAProto/index.js +142036 -0
  5. package/engine-requirements.js +13 -0
  6. package/lib/Defaults/index.d.ts +152 -0
  7. package/lib/Defaults/index.js +179 -0
  8. package/lib/Framework/Bot.js +209 -0
  9. package/lib/Framework/Context.js +90 -0
  10. package/lib/Framework/MediaManager.js +152 -0
  11. package/lib/Framework/SessionManager.js +34 -0
  12. package/lib/Framework/StatsManager.js +120 -0
  13. package/lib/Framework/Store/SQLiteStore.js +74 -0
  14. package/lib/Framework/index.js +11 -0
  15. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  16. package/lib/Signal/Group/ciphertext-message.js +12 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  18. package/lib/Signal/Group/group-session-builder.js +30 -0
  19. package/lib/Signal/Group/group_cipher.d.ts +10 -0
  20. package/lib/Signal/Group/group_cipher.js +82 -0
  21. package/lib/Signal/Group/index.d.ts +11 -0
  22. package/lib/Signal/Group/index.js +12 -0
  23. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  24. package/lib/Signal/Group/keyhelper.js +18 -0
  25. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  26. package/lib/Signal/Group/sender-chain-key.js +26 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  28. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  29. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  30. package/lib/Signal/Group/sender-key-message.js +66 -0
  31. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  32. package/lib/Signal/Group/sender-key-name.js +48 -0
  33. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  34. package/lib/Signal/Group/sender-key-record.js +41 -0
  35. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  36. package/lib/Signal/Group/sender-key-state.js +84 -0
  37. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  38. package/lib/Signal/Group/sender-message-key.js +26 -0
  39. package/lib/Signal/libsignal.d.ts +54 -0
  40. package/lib/Signal/libsignal.js +431 -0
  41. package/lib/Signal/lid-mapping.d.ts +20 -0
  42. package/lib/Signal/lid-mapping.js +277 -0
  43. package/lib/Socket/Client/index.d.ts +2 -0
  44. package/lib/Socket/Client/index.js +3 -0
  45. package/lib/Socket/Client/types.d.ts +5 -0
  46. package/lib/Socket/Client/types.js +11 -0
  47. package/lib/Socket/Client/websocket.d.ts +12 -0
  48. package/lib/Socket/Client/websocket.js +54 -0
  49. package/lib/Socket/business.d.ts +395 -0
  50. package/lib/Socket/business.js +380 -0
  51. package/lib/Socket/chats.d.ts +136 -0
  52. package/lib/Socket/chats.js +1328 -0
  53. package/lib/Socket/communities.d.ts +561 -0
  54. package/lib/Socket/communities.js +434 -0
  55. package/lib/Socket/dugong.d.ts +117 -0
  56. package/lib/Socket/dugong.js +799 -0
  57. package/lib/Socket/groups.d.ts +285 -0
  58. package/lib/Socket/groups.js +355 -0
  59. package/lib/Socket/index.d.ts +531 -0
  60. package/lib/Socket/index.js +34 -0
  61. package/lib/Socket/messages-recv.d.ts +333 -0
  62. package/lib/Socket/messages-recv.js +1782 -0
  63. package/lib/Socket/messages-send.d.ts +329 -0
  64. package/lib/Socket/messages-send.js +1383 -0
  65. package/lib/Socket/mex.d.ts +1 -0
  66. package/lib/Socket/mex.js +42 -0
  67. package/lib/Socket/newsletter.d.ts +281 -0
  68. package/lib/Socket/newsletter.js +321 -0
  69. package/lib/Socket/socket.d.ts +60 -0
  70. package/lib/Socket/socket.js +1001 -0
  71. package/lib/Socket/username.js +153 -0
  72. package/lib/Store/index.d.ts +3 -0
  73. package/lib/Store/index.js +4 -0
  74. package/lib/Store/make-in-memory-store.d.ts +62 -0
  75. package/lib/Store/make-in-memory-store.js +429 -0
  76. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  77. package/lib/Store/make-ordered-dictionary.js +79 -0
  78. package/lib/Store/object-repository.d.ts +10 -0
  79. package/lib/Store/object-repository.js +24 -0
  80. package/lib/Types/Auth.d.ts +117 -0
  81. package/lib/Types/Auth.js +2 -0
  82. package/lib/Types/Bussines.d.ts +25 -0
  83. package/lib/Types/Bussines.js +2 -0
  84. package/lib/Types/Call.d.ts +15 -0
  85. package/lib/Types/Call.js +2 -0
  86. package/lib/Types/Chat.d.ts +124 -0
  87. package/lib/Types/Chat.js +8 -0
  88. package/lib/Types/Contact.d.ts +26 -0
  89. package/lib/Types/Contact.js +2 -0
  90. package/lib/Types/Events.d.ts +256 -0
  91. package/lib/Types/Events.js +2 -0
  92. package/lib/Types/GroupMetadata.d.ts +71 -0
  93. package/lib/Types/GroupMetadata.js +2 -0
  94. package/lib/Types/Label.d.ts +2 -0
  95. package/lib/Types/Label.js +25 -0
  96. package/lib/Types/LabelAssociation.d.ts +2 -0
  97. package/lib/Types/LabelAssociation.js +7 -0
  98. package/lib/Types/Message.d.ts +11 -0
  99. package/lib/Types/Message.js +18 -0
  100. package/lib/Types/Mex.d.ts +2 -0
  101. package/lib/Types/Mex.js +39 -0
  102. package/lib/Types/Product.d.ts +79 -0
  103. package/lib/Types/Product.js +2 -0
  104. package/lib/Types/RichType.d.ts +2 -0
  105. package/lib/Types/RichType.js +23 -0
  106. package/lib/Types/Signal.d.ts +87 -0
  107. package/lib/Types/Signal.js +2 -0
  108. package/lib/Types/Socket.d.ts +136 -0
  109. package/lib/Types/Socket.js +2 -0
  110. package/lib/Types/State.d.ts +5 -0
  111. package/lib/Types/State.js +56 -0
  112. package/lib/Types/USync.d.ts +26 -0
  113. package/lib/Types/USync.js +2 -0
  114. package/lib/Types/index.d.ts +66 -0
  115. package/lib/Types/index.js +26 -0
  116. package/lib/Utils/A2UI.js +277 -0
  117. package/lib/Utils/MessageBuilder.js +4405 -0
  118. package/lib/Utils/MessageBuilder_d.ts +411 -0
  119. package/lib/Utils/PersistentStore.js +592 -0
  120. package/lib/Utils/PersistentStore_d.ts +60 -0
  121. package/lib/Utils/anti-delete.d.ts +74 -0
  122. package/lib/Utils/anti-delete.js +222 -0
  123. package/lib/Utils/auth-utils.d.ts +57 -0
  124. package/lib/Utils/auth-utils.js +307 -0
  125. package/lib/Utils/auto-reply.d.ts +47 -0
  126. package/lib/Utils/auto-reply.js +158 -0
  127. package/lib/Utils/baileys-event-stream.d.ts +8 -0
  128. package/lib/Utils/baileys-event-stream.js +62 -0
  129. package/lib/Utils/browser-utils.d.ts +8 -0
  130. package/lib/Utils/browser-utils.js +28 -0
  131. package/lib/Utils/business.d.ts +49 -0
  132. package/lib/Utils/business.js +240 -0
  133. package/lib/Utils/button-helper-utils.js +314 -0
  134. package/lib/Utils/button-sender.js +824 -0
  135. package/lib/Utils/chat-control.d.ts +159 -0
  136. package/lib/Utils/chat-control.js +232 -0
  137. package/lib/Utils/chat-history-helpers.d.ts +21 -0
  138. package/lib/Utils/chat-history-helpers.js +71 -0
  139. package/lib/Utils/chat-utils.d.ts +407 -0
  140. package/lib/Utils/chat-utils.js +886 -0
  141. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  142. package/lib/Utils/companion-reg-client-utils.js +40 -0
  143. package/lib/Utils/crypto.d.ts +41 -0
  144. package/lib/Utils/crypto.js +148 -0
  145. package/lib/Utils/decode-wa-message.d.ts +83 -0
  146. package/lib/Utils/decode-wa-message.js +317 -0
  147. package/lib/Utils/event-buffer.d.ts +12 -0
  148. package/lib/Utils/event-buffer.js +636 -0
  149. package/lib/Utils/generics.d.ts +69 -0
  150. package/lib/Utils/generics.js +439 -0
  151. package/lib/Utils/history.d.ts +90 -0
  152. package/lib/Utils/history.js +147 -0
  153. package/lib/Utils/identity-change-handler.d.ts +13 -0
  154. package/lib/Utils/identity-change-handler.js +50 -0
  155. package/lib/Utils/index.d.ts +39 -0
  156. package/lib/Utils/index.js +46 -0
  157. package/lib/Utils/link-preview.d.ts +12 -0
  158. package/lib/Utils/link-preview.js +85 -0
  159. package/lib/Utils/logger.d.ts +2 -0
  160. package/lib/Utils/logger.js +3 -0
  161. package/lib/Utils/lt-hash.d.ts +12 -0
  162. package/lib/Utils/lt-hash.js +27 -0
  163. package/lib/Utils/make-mutex.d.ts +6 -0
  164. package/lib/Utils/make-mutex.js +33 -0
  165. package/lib/Utils/media-messages.d.ts +18 -0
  166. package/lib/Utils/media-messages.js +71 -0
  167. package/lib/Utils/media-set.d.ts +13 -0
  168. package/lib/Utils/media-set.js +172 -0
  169. package/lib/Utils/message-kind.js +139 -0
  170. package/lib/Utils/message-retry-manager.d.ts +79 -0
  171. package/lib/Utils/message-retry-manager.js +265 -0
  172. package/lib/Utils/message-search.d.ts +44 -0
  173. package/lib/Utils/message-search.js +189 -0
  174. package/lib/Utils/messages-media.d.ts +135 -0
  175. package/lib/Utils/messages-media.js +869 -0
  176. package/lib/Utils/messages.d.ts +44 -0
  177. package/lib/Utils/messages.js +2155 -0
  178. package/lib/Utils/noise-handler.d.ts +20 -0
  179. package/lib/Utils/noise-handler.js +201 -0
  180. package/lib/Utils/offline-node-processor.d.ts +9 -0
  181. package/lib/Utils/offline-node-processor.js +40 -0
  182. package/lib/Utils/past-participants.d.ts +14 -0
  183. package/lib/Utils/past-participants.js +40 -0
  184. package/lib/Utils/pre-key-manager.d.ts +25 -0
  185. package/lib/Utils/pre-key-manager.js +106 -0
  186. package/lib/Utils/process-message.d.ts +82 -0
  187. package/lib/Utils/process-message.js +809 -0
  188. package/lib/Utils/reporting-utils.d.ts +12 -0
  189. package/lib/Utils/reporting-utils.js +258 -0
  190. package/lib/Utils/rich-message-utils.d.ts +48 -0
  191. package/lib/Utils/rich-message-utils.js +445 -0
  192. package/lib/Utils/scheduling.d.ts +42 -0
  193. package/lib/Utils/scheduling.js +140 -0
  194. package/lib/Utils/signal.d.ts +82 -0
  195. package/lib/Utils/signal.js +201 -0
  196. package/lib/Utils/stanza-ack.d.ts +16 -0
  197. package/lib/Utils/stanza-ack.js +38 -0
  198. package/lib/Utils/status.d.ts +50 -0
  199. package/lib/Utils/status.js +108 -0
  200. package/lib/Utils/stickerpack.d.ts +51 -0
  201. package/lib/Utils/stickerpack.js +275 -0
  202. package/lib/Utils/sync-action-utils.d.ts +2 -0
  203. package/lib/Utils/sync-action-utils.js +49 -0
  204. package/lib/Utils/tc-token-utils.d.ts +29 -0
  205. package/lib/Utils/tc-token-utils.js +163 -0
  206. package/lib/Utils/templates.d.ts +76 -0
  207. package/lib/Utils/templates.js +151 -0
  208. package/lib/Utils/use-cache-manager-auth-state.d.ts +13 -0
  209. package/lib/Utils/use-cache-manager-auth-state.js +82 -0
  210. package/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  211. package/lib/Utils/use-multi-file-auth-state.js +167 -0
  212. package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
  213. package/lib/Utils/use-single-file-auth-state.js +114 -0
  214. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  215. package/lib/Utils/use-sqlite-auth-state.js +170 -0
  216. package/lib/Utils/validate-connection.d.ts +42 -0
  217. package/lib/Utils/validate-connection.js +199 -0
  218. package/lib/Utils/vcard.d.ts +58 -0
  219. package/lib/Utils/vcard.js +105 -0
  220. package/lib/VoIP/audio-feeder.d.ts +15 -0
  221. package/lib/VoIP/audio-feeder.js +132 -0
  222. package/lib/VoIP/index.js +277 -0
  223. package/lib/VoIP/relay-transport.d.ts +43 -0
  224. package/lib/VoIP/relay-transport.js +559 -0
  225. package/lib/VoIP/signaling.js +624 -0
  226. package/lib/VoIP/types.d.ts +69 -0
  227. package/lib/VoIP/types.js +17 -0
  228. package/lib/VoIP/wasm-engine.d.ts +103 -0
  229. package/lib/VoIP/wasm-engine.js +1214 -0
  230. package/lib/VoIP/worker-bootstrap.js +1042 -0
  231. package/lib/WABinary/constants.d.ts +61 -0
  232. package/lib/WABinary/constants.js +1467 -0
  233. package/lib/WABinary/decode.d.ts +9 -0
  234. package/lib/WABinary/decode.js +262 -0
  235. package/lib/WABinary/encode.d.ts +2 -0
  236. package/lib/WABinary/encode.js +220 -0
  237. package/lib/WABinary/generic-utils.d.ts +74 -0
  238. package/lib/WABinary/generic-utils.js +277 -0
  239. package/lib/WABinary/index.d.ts +5 -0
  240. package/lib/WABinary/index.js +6 -0
  241. package/lib/WABinary/jid-utils.d.ts +28 -0
  242. package/lib/WABinary/jid-utils.js +96 -0
  243. package/lib/WABinary/types.d.ts +19 -0
  244. package/lib/WABinary/types.js +2 -0
  245. package/lib/WAM/BinaryInfo.d.ts +7 -0
  246. package/lib/WAM/BinaryInfo.js +10 -0
  247. package/lib/WAM/constants.d.ts +34926 -0
  248. package/lib/WAM/constants.js +22853 -0
  249. package/lib/WAM/encode.d.ts +1 -0
  250. package/lib/WAM/encode.js +150 -0
  251. package/lib/WAM/index.d.ts +3 -0
  252. package/lib/WAM/index.js +4 -0
  253. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  254. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  255. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +29 -0
  256. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +63 -0
  257. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  258. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  259. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  260. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  261. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  262. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  263. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  264. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  265. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  266. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  267. package/lib/WAUSync/Protocols/index.d.ts +7 -0
  268. package/lib/WAUSync/Protocols/index.js +8 -0
  269. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  270. package/lib/WAUSync/USyncQuery.js +122 -0
  271. package/lib/WAUSync/USyncUser.d.ts +16 -0
  272. package/lib/WAUSync/USyncUser.js +31 -0
  273. package/lib/WAUSync/index.d.ts +3 -0
  274. package/lib/WAUSync/index.js +4 -0
  275. package/lib/assets/wasm/loader.js +5 -0
  276. package/lib/assets/wasm/whatsapp.wasm +0 -0
  277. package/lib/assets/wasm/worker-modules.js +273 -0
  278. package/lib/index.d.ts +12 -0
  279. package/lib/index.js +20 -0
  280. package/package.json +175 -0
  281. package/postinstall-banner.js +56 -0
@@ -0,0 +1,74 @@
1
+ import type { WAMessage, WAMessageKey } from '../Types/index.js';
2
+ export interface MessageStoreOptions {
3
+ maxMessagesPerChat?: number;
4
+ ttl?: number;
5
+ cleanupInterval?: number;
6
+ }
7
+ export interface StoredMessage {
8
+ message: WAMessage;
9
+ storedAt: number;
10
+ isDeleted: boolean;
11
+ deletedAt?: number;
12
+ deletedBy?: string;
13
+ }
14
+ export interface DeletedMessageInfo {
15
+ originalMessage: WAMessage;
16
+ key: WAMessageKey;
17
+ deletedAt: number;
18
+ deletedBy?: string;
19
+ isRevokedBySender: boolean;
20
+ }
21
+ export declare class MessageStore {
22
+ private store;
23
+ private deletedMessages;
24
+ private cleanupTimer;
25
+ private options;
26
+ constructor(options?: MessageStoreOptions);
27
+ stopCleanup(): void;
28
+ storeMessage(message: WAMessage): void;
29
+ storeMessages(messages: WAMessage[]): void;
30
+ getMessage(key: WAMessageKey): StoredMessage | undefined;
31
+ getOriginalMessage(key: WAMessageKey): WAMessage | undefined;
32
+ markAsDeleted(key: WAMessageKey, deletedBy?: string): DeletedMessageInfo | null;
33
+ getDeletedMessage(key: WAMessageKey): DeletedMessageInfo | undefined;
34
+ getAllDeletedMessages(): DeletedMessageInfo[];
35
+ getDeletedMessagesByChat(chatId: string): DeletedMessageInfo[];
36
+ getChatMessages(chatId: string): WAMessage[];
37
+ getChatIds(): string[];
38
+ getStats(): {
39
+ totalChats: number;
40
+ totalMessages: number;
41
+ totalDeleted: number;
42
+ };
43
+ clear(): void;
44
+ clearChat(chatId: string): void;
45
+ getAllMessages(): Record<string, WAMessage[]>;
46
+ }
47
+ export declare const isDeleteMessage: (message: WAMessage) => boolean;
48
+ export declare const getDeletedMessageKey: (message: WAMessage) => WAMessageKey | null;
49
+ export declare const createAntiDeleteHandler: (store: MessageStore, onDelete?: (info: DeletedMessageInfo) => void) => (updates: Array<{
50
+ key: WAMessageKey;
51
+ update: Partial<WAMessage>;
52
+ }>) => DeletedMessageInfo[];
53
+ export declare const createAntiDeleteUpsertHandler: (store: MessageStore, onDelete?: (info: DeletedMessageInfo) => void) => ({ messages }: {
54
+ messages: WAMessage[];
55
+ }) => DeletedMessageInfo[];
56
+ export declare const createMessageStoreHandler: (store: MessageStore) => ({ messages }: {
57
+ messages: WAMessage[];
58
+ }) => void;
59
+ declare const _default: {
60
+ MessageStore: typeof MessageStore;
61
+ isDeleteMessage: (message: WAMessage) => boolean;
62
+ getDeletedMessageKey: (message: WAMessage) => WAMessageKey | null;
63
+ createAntiDeleteHandler: (store: MessageStore, onDelete?: (info: DeletedMessageInfo) => void) => (updates: Array<{
64
+ key: WAMessageKey;
65
+ update: Partial<WAMessage>;
66
+ }>) => DeletedMessageInfo[];
67
+ createAntiDeleteUpsertHandler: (store: MessageStore, onDelete?: (info: DeletedMessageInfo) => void) => ({ messages }: {
68
+ messages: WAMessage[];
69
+ }) => DeletedMessageInfo[];
70
+ createMessageStoreHandler: (store: MessageStore) => ({ messages }: {
71
+ messages: WAMessage[];
72
+ }) => void;
73
+ };
74
+ export default _default;
@@ -0,0 +1,222 @@
1
+ // Vanz@Add --- ported from Bail-master addons/anti-delete.ts (adapted to lib/ CJS-free ESM
2
+ // runtime style used throughout this fork; type-only annotations dropped, behavior unchanged).
3
+ import { proto } from '../../WAProto/index.js';
4
+ // ── MessageStore ───────────────────────────────────────────────────────────
5
+ /**
6
+ * In-memory, TTL-bounded store of recently seen messages, used to recover the
7
+ * original content of a message after WhatsApp delivers a REVOKE (delete-for-everyone)
8
+ * protocol message, which itself carries no content — only a reference key.
9
+ */
10
+ export class MessageStore {
11
+ store = new Map();
12
+ deletedMessages = new Map();
13
+ cleanupTimer = null;
14
+ options;
15
+ constructor(options = {}) {
16
+ this.options = {
17
+ maxMessagesPerChat: options.maxMessagesPerChat ?? 1000,
18
+ ttl: options.ttl ?? 24 * 60 * 60 * 1000,
19
+ cleanupInterval: options.cleanupInterval ?? 60 * 60 * 1000
20
+ };
21
+ this.startCleanup();
22
+ }
23
+ startCleanup() {
24
+ this.cleanupTimer = setInterval(() => this.cleanup(), this.options.cleanupInterval);
25
+ this.cleanupTimer?.unref?.();
26
+ }
27
+ stopCleanup() {
28
+ if (this.cleanupTimer)
29
+ clearInterval(this.cleanupTimer);
30
+ }
31
+ cleanup() {
32
+ const cutoff = Date.now() - this.options.ttl;
33
+ for (const [chatId, messages] of this.store) {
34
+ for (const [msgId, stored] of messages) {
35
+ if (stored.storedAt < cutoff)
36
+ messages.delete(msgId);
37
+ }
38
+ if (messages.size === 0)
39
+ this.store.delete(chatId);
40
+ }
41
+ for (const [key, info] of this.deletedMessages) {
42
+ if (info.deletedAt < cutoff)
43
+ this.deletedMessages.delete(key);
44
+ }
45
+ }
46
+ getKey(key) {
47
+ return `${key.remoteJid}:${key.id}`;
48
+ }
49
+ storeMessage(message) {
50
+ const chatId = message.key.remoteJid;
51
+ if (!chatId || !message.key.id)
52
+ return;
53
+ let chatMessages = this.store.get(chatId);
54
+ if (!chatMessages) {
55
+ chatMessages = new Map();
56
+ this.store.set(chatId, chatMessages);
57
+ }
58
+ if (chatMessages.size >= this.options.maxMessagesPerChat) {
59
+ const oldestKey = chatMessages.keys().next().value;
60
+ if (oldestKey)
61
+ chatMessages.delete(oldestKey);
62
+ }
63
+ chatMessages.set(message.key.id, { message, storedAt: Date.now(), isDeleted: false });
64
+ }
65
+ storeMessages(messages) {
66
+ for (const msg of messages)
67
+ this.storeMessage(msg);
68
+ }
69
+ getMessage(key) {
70
+ return this.store.get(key.remoteJid)?.get(key.id);
71
+ }
72
+ getOriginalMessage(key) {
73
+ return this.getMessage(key)?.message;
74
+ }
75
+ markAsDeleted(key, deletedBy) {
76
+ const stored = this.getMessage(key);
77
+ if (!stored)
78
+ return null;
79
+ const now = Date.now();
80
+ stored.isDeleted = true;
81
+ stored.deletedAt = now;
82
+ stored.deletedBy = deletedBy;
83
+ // Vanz@Fix (bug 66): the old check (`deletedBy === stored.message.key.participant`)
84
+ // only works in groups, where `participant` identifies who sent/revoked a message.
85
+ // In a private chat `key.participant` is always undefined (it's a group-only field),
86
+ // while `deletedBy` there falls back to `remoteJid` — so the comparison could never
87
+ // match and isRevokedBySender was always false for every DM, even though
88
+ // delete-for-everyone in a DM can only be done by the original sender. Treat a
89
+ // missing `participant` (i.e. not a group message) as "revoked by sender" by definition.
90
+ const isGroupMessage = !!stored.message.key.participant;
91
+ const info = {
92
+ originalMessage: stored.message,
93
+ key,
94
+ deletedAt: now,
95
+ deletedBy,
96
+ isRevokedBySender: !deletedBy || !isGroupMessage || deletedBy === stored.message.key.participant
97
+ };
98
+ this.deletedMessages.set(this.getKey(key), info);
99
+ return info;
100
+ }
101
+ getDeletedMessage(key) {
102
+ return this.deletedMessages.get(this.getKey(key));
103
+ }
104
+ getAllDeletedMessages() {
105
+ return Array.from(this.deletedMessages.values());
106
+ }
107
+ getDeletedMessagesByChat(chatId) {
108
+ return Array.from(this.deletedMessages.values()).filter((i) => i.key.remoteJid === chatId);
109
+ }
110
+ getChatMessages(chatId) {
111
+ return Array.from(this.store.get(chatId)?.values() ?? []).map((s) => s.message);
112
+ }
113
+ getChatIds() {
114
+ return Array.from(this.store.keys());
115
+ }
116
+ getStats() {
117
+ let totalMessages = 0;
118
+ for (const messages of this.store.values())
119
+ totalMessages += messages.size;
120
+ return { totalChats: this.store.size, totalMessages, totalDeleted: this.deletedMessages.size };
121
+ }
122
+ clear() {
123
+ this.store.clear();
124
+ this.deletedMessages.clear();
125
+ }
126
+ clearChat(chatId) {
127
+ this.store.delete(chatId);
128
+ }
129
+ getAllMessages() {
130
+ const all = {};
131
+ for (const [chatId, messages] of this.store) {
132
+ all[chatId] = Array.from(messages.values()).map((s) => s.message);
133
+ }
134
+ return all;
135
+ }
136
+ }
137
+ // ── Helpers ────────────────────────────────────────────────────────────────
138
+ export const isDeleteMessage = (message) => {
139
+ return message.message?.protocolMessage?.type === proto.Message.ProtocolMessage.Type.REVOKE;
140
+ };
141
+ export const getDeletedMessageKey = (message) => {
142
+ const protoMsg = message.message?.protocolMessage;
143
+ if (protoMsg?.type !== proto.Message.ProtocolMessage.Type.REVOKE)
144
+ return null;
145
+ return protoMsg.key ?? null;
146
+ };
147
+ /**
148
+ * Wire this into `sock.ev.on('messages.update', ...)`. Fires `onDelete` for
149
+ * every update in the batch whose stub type is REVOKE, using `store` to look
150
+ * up the original content that WhatsApp's own update payload omits.
151
+ */
152
+ export const createAntiDeleteHandler = (store, onDelete) => {
153
+ return (updates) => {
154
+ const deletedMessages = [];
155
+ for (const { key, update } of updates) {
156
+ if (update.messageStubType === proto.WebMessageInfo.StubType.REVOKE) {
157
+ const info = store.markAsDeleted(key, update.messageStubParameters?.[0]);
158
+ if (info) {
159
+ deletedMessages.push(info);
160
+ onDelete?.(info);
161
+ }
162
+ }
163
+ }
164
+ return deletedMessages;
165
+ };
166
+ };
167
+ /**
168
+ * Vanz@Fix (bug 58): `createAntiDeleteHandler` above only listens on
169
+ * `messages.update` with `messageStubType === REVOKE`. In practice, most
170
+ * delete-for-everyone events actually arrive as a *new* message on
171
+ * `messages.upsert` carrying a `protocolMessage` of type REVOKE (the
172
+ * `isDeleteMessage`/`getDeletedMessageKey` helpers above existed for this but
173
+ * were never wired to anything). Wire this into `sock.ev.on('messages.upsert', ...)`
174
+ * alongside `createMessageStoreHandler` to actually catch those.
175
+ */
176
+ export const createAntiDeleteUpsertHandler = (store, onDelete) => {
177
+ return ({ messages }) => {
178
+ const deletedMessages = [];
179
+ for (const message of messages) {
180
+ if (!isDeleteMessage(message))
181
+ continue;
182
+ const key = getDeletedMessageKey(message);
183
+ if (!key)
184
+ continue;
185
+ const deletedBy = message.key.participant || message.key.remoteJid;
186
+ const info = store.markAsDeleted(key, deletedBy);
187
+ if (info) {
188
+ deletedMessages.push(info);
189
+ onDelete?.(info);
190
+ }
191
+ }
192
+ return deletedMessages;
193
+ };
194
+ };
195
+ /**
196
+ * Wire this into `sock.ev.on('messages.upsert', ...)` to keep `store` populated.
197
+ * Skips protocol/sender-key-distribution messages, which carry no user content.
198
+ */
199
+ export const createMessageStoreHandler = (store) => {
200
+ return ({ messages }) => {
201
+ const regular = messages.filter((msg) => {
202
+ const c = msg.message;
203
+ if (!c)
204
+ return false;
205
+ if (c.protocolMessage)
206
+ return false;
207
+ if (c.senderKeyDistributionMessage)
208
+ return false;
209
+ return true;
210
+ });
211
+ store.storeMessages(regular);
212
+ };
213
+ };
214
+ export default {
215
+ MessageStore,
216
+ isDeleteMessage,
217
+ getDeletedMessageKey,
218
+ createAntiDeleteHandler,
219
+ createAntiDeleteUpsertHandler,
220
+ createMessageStoreHandler
221
+ };
222
+ //# sourceMappingURL=anti-delete.js.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Adds caching capability to a SignalKeyStore
3
+ * @param store the store to add caching to
4
+ * @param logger to log trace events
5
+ * @param _cache cache store to use
6
+ */
7
+ export function makeCacheableSignalKeyStore(store: any, logger: any, _cache: any): {
8
+ get(type: any, ids: any): Promise<any>;
9
+ set(data: any): Promise<any>;
10
+ clear(): Promise<void>;
11
+ };
12
+ export function addTransactionCapability(state: any, logger: any, { maxCommitRetries, delayBetweenTriesMs }: {
13
+ maxCommitRetries: any;
14
+ delayBetweenTriesMs: any;
15
+ }): {
16
+ get: (type: any, ids: any) => Promise<any>;
17
+ set: (data: any) => Promise<void>;
18
+ isInTransaction: () => boolean;
19
+ transaction: (work: any, key: any) => Promise<any>;
20
+ };
21
+ export function assertMeId(creds: any): any;
22
+ export function initAuthCreds(): {
23
+ noiseKey: {
24
+ private: any;
25
+ public: any;
26
+ };
27
+ pairingEphemeralKeyPair: {
28
+ private: any;
29
+ public: any;
30
+ };
31
+ signedIdentityKey: {
32
+ private: any;
33
+ public: any;
34
+ };
35
+ signedPreKey: {
36
+ keyPair: {
37
+ private: any;
38
+ public: any;
39
+ };
40
+ signature: any;
41
+ keyId: any;
42
+ };
43
+ registrationId: number;
44
+ advSecretKey: any;
45
+ processedHistoryMessages: never[];
46
+ nextPreKeyId: number;
47
+ firstUnuploadedPreKeyId: number;
48
+ accountSyncCounter: number;
49
+ accountSettings: {
50
+ unarchiveChats: boolean;
51
+ };
52
+ registered: boolean;
53
+ pairingCode: undefined;
54
+ lastPropHash: undefined;
55
+ routingInfo: undefined;
56
+ additionalData: undefined;
57
+ };
@@ -0,0 +1,307 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { AsyncLocalStorage } from 'async_hooks';
4
+ import { Mutex } from 'async-mutex';
5
+ import { randomBytes } from 'crypto';
6
+ import PQueue from 'p-queue';
7
+ import { DEFAULT_CACHE_TTLS } from '../Defaults/index.js';
8
+ import { Curve, signedKeyPair } from './crypto.js';
9
+ import { delay, generateRegistrationId } from './generics.js';
10
+ import { PreKeyManager } from './pre-key-manager.js';
11
+ /**
12
+ * Adds caching capability to a SignalKeyStore
13
+ * @param store the store to add caching to
14
+ * @param logger to log trace events
15
+ * @param _cache cache store to use
16
+ */
17
+ export function makeCacheableSignalKeyStore(store, logger, _cache) {
18
+ const cache = _cache ||
19
+ new NodeCache({
20
+ stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
21
+ useClones: false,
22
+ deleteOnExpire: true
23
+ });
24
+ // Mutex for protecting cache operations
25
+ const cacheMutex = new Mutex();
26
+ function getUniqueId(type, id) {
27
+ return `${type}.${id}`;
28
+ }
29
+ return {
30
+ async get(type, ids) {
31
+ return cacheMutex.runExclusive(async () => {
32
+ const data = {};
33
+ const idsToFetch = [];
34
+ for (const id of ids) {
35
+ const item = (await cache.get(getUniqueId(type, id)));
36
+ if (typeof item !== 'undefined') {
37
+ data[id] = item;
38
+ }
39
+ else {
40
+ idsToFetch.push(id);
41
+ }
42
+ }
43
+ if (idsToFetch.length) {
44
+ logger?.trace({ items: idsToFetch.length }, 'loading from store');
45
+ const fetched = await store.get(type, idsToFetch);
46
+ for (const id of idsToFetch) {
47
+ const item = fetched[id];
48
+ if (item) {
49
+ data[id] = item;
50
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
51
+ await cache.set(getUniqueId(type, id), item);
52
+ }
53
+ }
54
+ }
55
+ return data;
56
+ });
57
+ },
58
+ async set(data) {
59
+ return cacheMutex.runExclusive(async () => {
60
+ let keys = 0;
61
+ for (const type in data) {
62
+ for (const id in data[type]) {
63
+ await cache.set(getUniqueId(type, id), data[type][id]);
64
+ keys += 1;
65
+ }
66
+ }
67
+ logger?.trace({ keys }, 'updated cache');
68
+ await store.set(data);
69
+ });
70
+ },
71
+ async clear() {
72
+ await cache.flushAll();
73
+ await store.clear?.();
74
+ }
75
+ };
76
+ }
77
+ /**
78
+ * Adds DB-like transaction capability to the SignalKeyStore
79
+ * Uses AsyncLocalStorage for automatic context management
80
+ * @param state the key store to apply this capability to
81
+ * @param logger logger to log events
82
+ * @returns SignalKeyStore with transaction capability
83
+ */
84
+ export const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
85
+ const txStorage = new AsyncLocalStorage();
86
+ // Queues for concurrency control (keyed by signal data type - bounded set)
87
+ const keyQueues = new Map();
88
+ // Transaction mutexes with reference counting for cleanup
89
+ const txMutexes = new Map();
90
+ const txMutexRefCounts = new Map();
91
+ // Pre-key manager for specialized operations
92
+ const preKeyManager = new PreKeyManager(state, logger);
93
+ /**
94
+ * Get or create a queue for a specific key type
95
+ */
96
+ function getQueue(key) {
97
+ if (!keyQueues.has(key)) {
98
+ keyQueues.set(key, new PQueue({ concurrency: 1 }));
99
+ }
100
+ return keyQueues.get(key);
101
+ }
102
+ /**
103
+ * Get or create a transaction mutex
104
+ */
105
+ function getTxMutex(key) {
106
+ if (!txMutexes.has(key)) {
107
+ txMutexes.set(key, new Mutex());
108
+ txMutexRefCounts.set(key, 0);
109
+ }
110
+ return txMutexes.get(key);
111
+ }
112
+ /**
113
+ * Acquire a reference to a transaction mutex
114
+ */
115
+ function acquireTxMutexRef(key) {
116
+ const count = txMutexRefCounts.get(key) ?? 0;
117
+ txMutexRefCounts.set(key, count + 1);
118
+ }
119
+ /**
120
+ * Release a reference to a transaction mutex and cleanup if no longer needed
121
+ */
122
+ function releaseTxMutexRef(key) {
123
+ const count = (txMutexRefCounts.get(key) ?? 1) - 1;
124
+ txMutexRefCounts.set(key, count);
125
+ // Cleanup if no more references and mutex is not locked
126
+ if (count <= 0) {
127
+ const mutex = txMutexes.get(key);
128
+ if (mutex && !mutex.isLocked()) {
129
+ txMutexes.delete(key);
130
+ txMutexRefCounts.delete(key);
131
+ }
132
+ }
133
+ }
134
+ /**
135
+ * Check if currently in a transaction
136
+ */
137
+ function isInTransaction() {
138
+ return !!txStorage.getStore();
139
+ }
140
+ /**
141
+ * Commit transaction with retries
142
+ */
143
+ async function commitWithRetry(mutations) {
144
+ if (Object.keys(mutations).length === 0) {
145
+ logger.trace('no mutations in transaction');
146
+ return;
147
+ }
148
+ logger.trace('committing transaction');
149
+ for (let attempt = 0; attempt < maxCommitRetries; attempt++) {
150
+ try {
151
+ await state.set(mutations);
152
+ logger.trace({ mutationCount: Object.keys(mutations).length }, 'committed transaction');
153
+ return;
154
+ }
155
+ catch (error) {
156
+ const retriesLeft = maxCommitRetries - attempt - 1;
157
+ logger.warn(`failed to commit mutations, retries left=${retriesLeft}`);
158
+ if (retriesLeft === 0) {
159
+ throw error;
160
+ }
161
+ await delay(delayBetweenTriesMs);
162
+ }
163
+ }
164
+ }
165
+ return {
166
+ get: async (type, ids) => {
167
+ const ctx = txStorage.getStore();
168
+ if (!ctx) {
169
+ // No transaction - direct read without exclusive lock for concurrency
170
+ return state.get(type, ids);
171
+ }
172
+ // In transaction - check cache first
173
+ const cached = ctx.cache[type] || {};
174
+ const missing = ids.filter(id => !(id in cached));
175
+ if (missing.length > 0) {
176
+ ctx.dbQueries++;
177
+ logger.trace({ type, count: missing.length }, 'fetching missing keys in transaction');
178
+ const fetched = await getTxMutex(type).runExclusive(() => state.get(type, missing));
179
+ // Update cache
180
+ ctx.cache[type] = ctx.cache[type] || {};
181
+ Object.assign(ctx.cache[type], fetched);
182
+ }
183
+ // Return requested ids from cache
184
+ const result = {};
185
+ for (const id of ids) {
186
+ const value = ctx.cache[type]?.[id];
187
+ if (value !== undefined && value !== null) {
188
+ result[id] = value;
189
+ }
190
+ }
191
+ return result;
192
+ },
193
+ set: async (data) => {
194
+ const ctx = txStorage.getStore();
195
+ if (!ctx) {
196
+ // No transaction - direct write with queue protection
197
+ const types = Object.keys(data);
198
+ // Vanz@Fix (bug 66): validateDeletions() used to run *before* this,
199
+ // serialized only against PreKeyManager's own internal queue —
200
+ // a separate PQueue instance from getQueue(type) below, both keyed
201
+ // 'pre-key' but never synchronized with each other. Two concurrent
202
+ // set() calls for pre-key data could validate against a store state
203
+ // that a still-pending write from the other call hadn't applied yet,
204
+ // letting a stale deletion go through or a just-deleted key get
205
+ // resurrected by data racing back in. Validation now happens inside
206
+ // the same per-type queue job as the write, so it's ordered against
207
+ // any other set() for that type instead of racing it.
208
+ await Promise.all(types.map(type => getQueue(type).add(async () => {
209
+ if (type === 'pre-key') {
210
+ await preKeyManager.validateDeletions(data, type);
211
+ }
212
+ const typeData = { [type]: data[type] };
213
+ await state.set(typeData);
214
+ })));
215
+ return;
216
+ }
217
+ // In transaction - update cache and mutations
218
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction');
219
+ for (const key_ in data) {
220
+ const key = key_;
221
+ // Ensure structures exist
222
+ ctx.cache[key] = ctx.cache[key] || {};
223
+ ctx.mutations[key] = ctx.mutations[key] || {};
224
+ // Special handling for pre-keys
225
+ if (key === 'pre-key') {
226
+ await preKeyManager.processOperations(data, key, ctx.cache, ctx.mutations, true);
227
+ }
228
+ else {
229
+ // Normal key types
230
+ Object.assign(ctx.cache[key], data[key]);
231
+ Object.assign(ctx.mutations[key], data[key]);
232
+ }
233
+ }
234
+ },
235
+ isInTransaction,
236
+ transaction: async (work, key) => {
237
+ const existing = txStorage.getStore();
238
+ // Nested transaction - reuse existing context
239
+ if (existing) {
240
+ logger.trace('reusing existing transaction context');
241
+ return work();
242
+ }
243
+ // New transaction - acquire mutex and create context
244
+ const mutex = getTxMutex(key);
245
+ acquireTxMutexRef(key);
246
+ try {
247
+ return await mutex.runExclusive(async () => {
248
+ const ctx = {
249
+ cache: {},
250
+ mutations: {},
251
+ dbQueries: 0
252
+ };
253
+ logger.trace('entering transaction');
254
+ try {
255
+ const result = await txStorage.run(ctx, work);
256
+ // Commit mutations
257
+ await commitWithRetry(ctx.mutations);
258
+ logger.trace({ dbQueries: ctx.dbQueries }, 'transaction completed');
259
+ return result;
260
+ }
261
+ catch (error) {
262
+ logger.error({ error }, 'transaction failed, rolling back');
263
+ throw error;
264
+ }
265
+ });
266
+ }
267
+ finally {
268
+ releaseTxMutexRef(key);
269
+ }
270
+ }
271
+ };
272
+ };
273
+ /**
274
+ * Returns the authenticated user's JID, or throws a Boom-401 if creds are not yet authenticated.
275
+ * Use this anywhere we'd otherwise reach for `creds.me!.id` to fail fast with a descriptive error.
276
+ */
277
+ export const assertMeId = (creds) => {
278
+ const id = creds.me?.id;
279
+ if (!id) {
280
+ throw new Boom('Cannot proceed: socket is not authenticated yet (creds.me.id is missing)', { statusCode: 401 });
281
+ }
282
+ return id;
283
+ };
284
+ export const initAuthCreds = () => {
285
+ const identityKey = Curve.generateKeyPair();
286
+ return {
287
+ noiseKey: Curve.generateKeyPair(),
288
+ pairingEphemeralKeyPair: Curve.generateKeyPair(),
289
+ signedIdentityKey: identityKey,
290
+ signedPreKey: signedKeyPair(identityKey, 1),
291
+ registrationId: generateRegistrationId(),
292
+ advSecretKey: randomBytes(32).toString('base64'),
293
+ processedHistoryMessages: [],
294
+ nextPreKeyId: 1,
295
+ firstUnuploadedPreKeyId: 1,
296
+ accountSyncCounter: 0,
297
+ accountSettings: {
298
+ unarchiveChats: false
299
+ },
300
+ registered: false,
301
+ pairingCode: undefined,
302
+ lastPropHash: undefined,
303
+ routingInfo: undefined,
304
+ additionalData: undefined
305
+ };
306
+ };
307
+ //# sourceMappingURL=auth-utils.js.map