@badzz88/baileys 8.5.4 → 8.5.6

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 (269) hide show
  1. package/README.md +2 -2
  2. package/WAProto/fix-imports.js +69 -79
  3. package/WAProto/index.d.ts +15305 -87935
  4. package/WAProto/index.js +41109 -194076
  5. package/engine-requirements.js +15 -8
  6. package/package.json +23 -19
  7. package/src/Defaults/index.js +186 -0
  8. package/src/Signal/Group/ciphertext-message.js +15 -0
  9. package/src/Signal/Group/group-session-builder.js +86 -0
  10. package/src/Signal/Group/group_cipher.js +82 -0
  11. package/src/Signal/Group/index.js +140 -0
  12. package/src/Signal/Group/keyhelper.js +77 -0
  13. package/src/Signal/Group/sender-chain-key.js +29 -0
  14. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  15. package/src/Signal/Group/sender-key-message.js +69 -0
  16. package/src/Signal/Group/sender-key-name.js +51 -0
  17. package/src/Signal/Group/sender-key-record.js +44 -0
  18. package/src/Signal/Group/sender-key-state.js +87 -0
  19. package/src/Signal/Group/sender-message-key.js +29 -0
  20. package/src/Signal/libsignal.js +455 -0
  21. package/src/Signal/lid-mapping.js +273 -0
  22. package/src/Socket/Client/index.js +31 -0
  23. package/src/Socket/Client/types.js +13 -0
  24. package/src/Socket/Client/websocket.js +61 -0
  25. package/src/Socket/aigroups.js +221 -0
  26. package/src/Socket/business.js +411 -0
  27. package/src/Socket/chats.js +1449 -0
  28. package/src/Socket/communities.js +463 -0
  29. package/src/Socket/graphql.js +523 -0
  30. package/src/Socket/groups.js +516 -0
  31. package/src/Socket/index.js +31 -0
  32. package/src/Socket/interactive-handler.js +527 -0
  33. package/src/Socket/interop.js +339 -0
  34. package/src/Socket/luxu.js +349 -0
  35. package/src/Socket/managed-account.js +98 -0
  36. package/src/Socket/messages-recv.js +2685 -0
  37. package/src/Socket/messages-send.js +2047 -0
  38. package/src/Socket/mex.js +57 -0
  39. package/src/Socket/newsletter.js +455 -0
  40. package/src/Socket/privacy.js +125 -0
  41. package/src/Socket/registration.js +236 -0
  42. package/src/Socket/socket.js +983 -0
  43. package/src/Socket/text-router.js +65 -0
  44. package/src/Socket/username.js +130 -0
  45. package/src/Store/index.js +33 -0
  46. package/src/Store/keyed-db.js +118 -0
  47. package/src/Store/make-cache-manager-store.js +84 -0
  48. package/src/Store/make-in-memory-store.js +551 -0
  49. package/src/Store/make-ordered-dictionary.js +81 -0
  50. package/src/Store/object-repository.js +26 -0
  51. package/src/Types/Auth.js +31 -0
  52. package/src/Types/Bussines.js +2 -0
  53. package/src/Types/Call.js +2 -0
  54. package/src/Types/Chat.js +4 -0
  55. package/src/Types/Contact.js +2 -0
  56. package/src/Types/Events.js +2 -0
  57. package/src/Types/GroupMetadata.js +2 -0
  58. package/src/Types/Label.js +26 -0
  59. package/src/Types/LabelAssociation.js +8 -0
  60. package/src/Types/Message.js +93 -0
  61. package/src/Types/Mex.js +112 -0
  62. package/src/Types/Newsletter.js +109 -0
  63. package/src/Types/Product.js +2 -0
  64. package/src/Types/Signal.js +2 -0
  65. package/src/Types/Socket.js +2 -0
  66. package/src/Types/State.js +62 -0
  67. package/src/Types/USync.js +2 -0
  68. package/src/Types/index.js +56 -0
  69. package/src/Utils/auth-utils.js +254 -0
  70. package/src/Utils/browser-utils.js +112 -0
  71. package/src/Utils/business.js +240 -0
  72. package/src/Utils/chat-utils.js +1230 -0
  73. package/src/Utils/command-loader.d.ts +27 -0
  74. package/src/Utils/command-loader.js +89 -0
  75. package/src/Utils/companion-reg-client-utils.js +40 -0
  76. package/src/Utils/consumer-application.js +105 -0
  77. package/src/Utils/crypto.js +118 -0
  78. package/src/Utils/curve25519-js.js +242 -0
  79. package/src/Utils/decode-wa-message.js +529 -0
  80. package/src/Utils/event-buffer.js +580 -0
  81. package/src/Utils/generics.js +483 -0
  82. package/src/Utils/group-history.js +44 -0
  83. package/src/Utils/history.js +232 -0
  84. package/src/Utils/identity-change-handler.js +52 -0
  85. package/src/Utils/index.js +58 -0
  86. package/src/Utils/jid-display-normalization.js +195 -0
  87. package/src/Utils/link-preview.js +135 -0
  88. package/src/Utils/logger.js +8 -0
  89. package/src/Utils/lt-hash.js +25 -0
  90. package/src/Utils/make-mutex.js +36 -0
  91. package/src/Utils/message-composer.js +471 -0
  92. package/src/Utils/message-retry-manager.js +217 -0
  93. package/src/Utils/messages-media.js +843 -0
  94. package/src/Utils/messages.js +2817 -0
  95. package/src/Utils/meta-ai-msmsg.js +222 -0
  96. package/src/Utils/native-bridge.js +68 -0
  97. package/src/Utils/noise-handler.js +169 -0
  98. package/src/Utils/offline-node-processor.js +34 -0
  99. package/src/Utils/pre-key-manager.js +90 -0
  100. package/src/Utils/process-message.js +950 -0
  101. package/src/Utils/reporting-utils.js +261 -0
  102. package/src/Utils/session-pool.d.ts +14 -0
  103. package/src/Utils/session-pool.js +70 -0
  104. package/src/Utils/signal.js +217 -0
  105. package/src/Utils/stanza-ack.js +30 -0
  106. package/src/Utils/sticker.d.ts +13 -0
  107. package/src/Utils/sticker.js +123 -0
  108. package/src/Utils/sync-action-utils.js +45 -0
  109. package/src/Utils/tc-token-utils.js +158 -0
  110. package/src/Utils/use-multi-file-auth-state.js +111 -0
  111. package/src/Utils/validate-connection.js +209 -0
  112. package/src/Utils/view-once-cache.d.ts +12 -0
  113. package/src/Utils/view-once-cache.js +63 -0
  114. package/src/Utils/voip-rekey.js +22 -0
  115. package/src/WABinary/constants.js +1304 -0
  116. package/src/WABinary/decode.js +342 -0
  117. package/src/WABinary/encode.js +225 -0
  118. package/src/WABinary/generic-utils.js +238 -0
  119. package/src/WABinary/index.js +34 -0
  120. package/src/WABinary/jid-utils.js +351 -0
  121. package/src/WABinary/types.js +2 -0
  122. package/src/WAM/BinaryInfo.js +13 -0
  123. package/src/WAM/constants.js +39484 -0
  124. package/src/WAM/encode.js +149 -0
  125. package/src/WAM/index.js +32 -0
  126. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  127. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +44 -0
  128. package/src/WAUSync/Protocols/USyncContactProtocol.js +55 -0
  129. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +55 -0
  130. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  131. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +54 -0
  132. package/src/WAUSync/Protocols/USyncLIDProtocol.js +32 -0
  133. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +473 -0
  134. package/src/WAUSync/Protocols/USyncPictureProtocol.js +34 -0
  135. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  136. package/src/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  137. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  138. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  139. package/src/WAUSync/Protocols/index.js +40 -0
  140. package/src/WAUSync/USyncQuery.js +126 -0
  141. package/src/WAUSync/USyncUser.js +50 -0
  142. package/src/WAUSync/index.js +32 -0
  143. package/src/antiban.js +4152 -0
  144. package/{lib → src}/index.js +51 -49
  145. package/lib/Defaults/index.js +0 -195
  146. package/lib/Signal/Group/ciphertext-message.js +0 -15
  147. package/lib/Signal/Group/group-session-builder.js +0 -92
  148. package/lib/Signal/Group/group_cipher.js +0 -89
  149. package/lib/Signal/Group/index.js +0 -136
  150. package/lib/Signal/Group/keyhelper.js +0 -73
  151. package/lib/Signal/Group/sender-chain-key.js +0 -32
  152. package/lib/Signal/Group/sender-key-distribution-message.js +0 -66
  153. package/lib/Signal/Group/sender-key-message.js +0 -69
  154. package/lib/Signal/Group/sender-key-name.js +0 -50
  155. package/lib/Signal/Group/sender-key-record.js +0 -44
  156. package/lib/Signal/Group/sender-key-state.js +0 -97
  157. package/lib/Signal/Group/sender-message-key.js +0 -30
  158. package/lib/Signal/libsignal.js +0 -470
  159. package/lib/Signal/lid-mapping.js +0 -280
  160. package/lib/Socket/Client/index.js +0 -30
  161. package/lib/Socket/Client/types.js +0 -13
  162. package/lib/Socket/Client/websocket.js +0 -62
  163. package/lib/Socket/aigroups.js +0 -240
  164. package/lib/Socket/business.js +0 -414
  165. package/lib/Socket/chats.js +0 -2165
  166. package/lib/Socket/communities.js +0 -545
  167. package/lib/Socket/graphql.js +0 -863
  168. package/lib/Socket/groups.js +0 -685
  169. package/lib/Socket/index.js +0 -41
  170. package/lib/Socket/interactive-handler.js +0 -579
  171. package/lib/Socket/interop.js +0 -430
  172. package/lib/Socket/managed-account.js +0 -214
  173. package/lib/Socket/messages-recv.js +0 -3000
  174. package/lib/Socket/messages-send.js +0 -2155
  175. package/lib/Socket/mex.js +0 -47
  176. package/lib/Socket/newsletter.js +0 -814
  177. package/lib/Socket/privacy.js +0 -261
  178. package/lib/Socket/registration.js +0 -434
  179. package/lib/Socket/socket.js +0 -1074
  180. package/lib/Socket/username.js +0 -160
  181. package/lib/Store/index.js +0 -36
  182. package/lib/Store/make-cache-manager-store.js +0 -90
  183. package/lib/Store/make-in-memory-store.js +0 -488
  184. package/lib/Store/make-ordered-dictionary.js +0 -81
  185. package/lib/Store/object-repository.js +0 -29
  186. package/lib/Types/Auth.js +0 -38
  187. package/lib/Types/Bussines.js +0 -2
  188. package/lib/Types/Call.js +0 -2
  189. package/lib/Types/Chat.js +0 -4
  190. package/lib/Types/Contact.js +0 -2
  191. package/lib/Types/Events.js +0 -2
  192. package/lib/Types/GroupMetadata.js +0 -2
  193. package/lib/Types/Label.js +0 -27
  194. package/lib/Types/LabelAssociation.js +0 -9
  195. package/lib/Types/Message.js +0 -95
  196. package/lib/Types/Newsletter.js +0 -152
  197. package/lib/Types/Product.js +0 -2
  198. package/lib/Types/Signal.js +0 -2
  199. package/lib/Types/Socket.js +0 -2
  200. package/lib/Types/State.js +0 -70
  201. package/lib/Types/USync.js +0 -2
  202. package/lib/Types/index.js +0 -55
  203. package/lib/Utils/auth-utils.js +0 -301
  204. package/lib/Utils/browser-utils.js +0 -114
  205. package/lib/Utils/business.js +0 -243
  206. package/lib/Utils/chat-utils.js +0 -1272
  207. package/lib/Utils/consumer-application.js +0 -107
  208. package/lib/Utils/crypto.js +0 -125
  209. package/lib/Utils/decode-wa-message.js +0 -793
  210. package/lib/Utils/event-buffer.js +0 -583
  211. package/lib/Utils/generics.js +0 -617
  212. package/lib/Utils/group-history.js +0 -51
  213. package/lib/Utils/history.js +0 -244
  214. package/lib/Utils/identity-change-handler.js +0 -52
  215. package/lib/Utils/index.js +0 -53
  216. package/lib/Utils/jid-display-normalization.js +0 -218
  217. package/lib/Utils/link-preview.js +0 -138
  218. package/lib/Utils/logger.js +0 -9
  219. package/lib/Utils/lt-hash.js +0 -6
  220. package/lib/Utils/make-mutex.js +0 -36
  221. package/lib/Utils/message-composer.js +0 -479
  222. package/lib/Utils/message-inspect.js +0 -393
  223. package/lib/Utils/message-retry-manager.js +0 -205
  224. package/lib/Utils/messages-media.js +0 -925
  225. package/lib/Utils/messages.js +0 -2482
  226. package/lib/Utils/meta-ai-msmsg.js +0 -122
  227. package/lib/Utils/noise-handler.js +0 -194
  228. package/lib/Utils/offline-node-processor.js +0 -37
  229. package/lib/Utils/pre-key-manager.js +0 -97
  230. package/lib/Utils/process-message.js +0 -1139
  231. package/lib/Utils/reporting-utils.js +0 -262
  232. package/lib/Utils/signal.js +0 -189
  233. package/lib/Utils/stanza-ack.js +0 -67
  234. package/lib/Utils/sync-action-utils.js +0 -51
  235. package/lib/Utils/tc-token-utils.js +0 -156
  236. package/lib/Utils/use-multi-file-auth-state.js +0 -137
  237. package/lib/Utils/validate-connection.js +0 -259
  238. package/lib/Utils/voip-rekey.js +0 -22
  239. package/lib/WABinary/constants.js +0 -1304
  240. package/lib/WABinary/decode.js +0 -377
  241. package/lib/WABinary/encode.js +0 -58
  242. package/lib/WABinary/generic-utils.js +0 -150
  243. package/lib/WABinary/index.js +0 -33
  244. package/lib/WABinary/jid-utils.js +0 -374
  245. package/lib/WABinary/types.js +0 -2
  246. package/lib/WAM/BinaryInfo.js +0 -13
  247. package/lib/WAM/constants.js +0 -39486
  248. package/lib/WAM/encode.js +0 -142
  249. package/lib/WAM/index.js +0 -31
  250. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -55
  251. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +0 -100
  252. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -60
  253. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -65
  254. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  255. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +0 -72
  256. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -31
  257. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -865
  258. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +0 -32
  259. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
  260. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -44
  261. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
  262. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -28
  263. package/lib/WAUSync/Protocols/index.js +0 -40
  264. package/lib/WAUSync/USyncBackoff.js +0 -26
  265. package/lib/WAUSync/USyncQuery.js +0 -204
  266. package/lib/WAUSync/USyncUser.js +0 -58
  267. package/lib/WAUSync/index.js +0 -32
  268. package/lib/antiban.js +0 -4391
  269. /package/{lib → src}/Defaults/phonenumber-mcc.json +0 -0
@@ -0,0 +1,551 @@
1
+ 'use strict';
2
+ var __importDefault = (this && this.__importDefault) ||
3
+ function (mod) {
4
+ return mod && mod.__esModule ? mod : { default: mod };
5
+ };
6
+ Object.defineProperty(exports, '__esModule', { value: true });
7
+ const WAProto_1 = require('../../WAProto');
8
+ const Defaults_1 = require('../Defaults');
9
+ const LabelAssociation_1 = require('../Types/LabelAssociation');
10
+ const Utils_1 = require('../Utils');
11
+ const WABinary_1 = require('../WABinary');
12
+ const Store_1 = require('./make-ordered-dictionary');
13
+ const object_repository_1 = require('./object-repository');
14
+ const waChatKey = pin => ({
15
+ key: c => (pin ? (c.pinned ? '1' : '0') : '') +
16
+ (c.archived ? '0' : '1') +
17
+ (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') +
18
+ c.id,
19
+ compare: (k1, k2) => k2.localeCompare(k1)
20
+ });
21
+ const waMessageID = m => m.key.id || '';
22
+ const waLabelAssociationKey = {
23
+ key: la => la.type === LabelAssociation_1.LabelAssociationType.Chat
24
+ ? la.chatId + la.labelId
25
+ : la.chatId + la.messageId + la.labelId,
26
+ compare: (k1, k2) => k2.localeCompare(k1)
27
+ };
28
+ const makeMessagesDictionary = () => Store_1.makeOrderedDictionary(waMessageID);
29
+ const ENCRYPTED_STORE_MARKER = 'xazbails-store-v1';
30
+ const deriveStoreKey = secret => {
31
+ const { createHash } = require('crypto');
32
+ return createHash('sha256').update(String(secret)).digest();
33
+ };
34
+ const encryptStoreJSON = (jsonStr, secret) => {
35
+ const { createCipheriv, randomBytes } = require('crypto');
36
+ const key = deriveStoreKey(secret);
37
+ const iv = randomBytes(12);
38
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
39
+ const encrypted = Buffer.concat([cipher.update(jsonStr, 'utf-8'), cipher.final()]);
40
+ const authTag = cipher.getAuthTag();
41
+ return JSON.stringify({
42
+ marker: ENCRYPTED_STORE_MARKER,
43
+ iv: iv.toString('base64'),
44
+ authTag: authTag.toString('base64'),
45
+ data: encrypted.toString('base64')
46
+ });
47
+ };
48
+ const decryptStoreJSON = (fileStr, secret) => {
49
+ const parsed = JSON.parse(fileStr);
50
+ if (parsed.marker !== ENCRYPTED_STORE_MARKER) {
51
+ return fileStr;
52
+ }
53
+ const { createDecipheriv } = require('crypto');
54
+ const key = deriveStoreKey(secret);
55
+ const iv = Buffer.from(parsed.iv, 'base64');
56
+ const authTag = Buffer.from(parsed.authTag, 'base64');
57
+ const decipher = createDecipheriv('aes-256-gcm', key, iv);
58
+ decipher.setAuthTag(authTag);
59
+ const decrypted = Buffer.concat([decipher.update(Buffer.from(parsed.data, 'base64')), decipher.final()]);
60
+ return decrypted.toString('utf-8');
61
+ };
62
+ const makeInMemoryStore = config => {
63
+ const socket = config.socket;
64
+ const chatKey = config.chatKey || waChatKey(true);
65
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey;
66
+ const logger = config.logger ||
67
+ Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({
68
+ stream: 'in-mem-store'
69
+ });
70
+ const KeyedDB = require('@adiwajshing/keyed-db').default;
71
+ const chats = new KeyedDB(chatKey, c => c.id);
72
+ const messages = {};
73
+ const contacts = {};
74
+ const groupMetadata = {};
75
+ const presences = {};
76
+ const state = { connection: 'close' };
77
+ const labels = new object_repository_1.ObjectRepository();
78
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
79
+ const maxMessagesPerChat = config.maxMessagesPerChat;
80
+ const trimMessagesIfNeeded = jid => {
81
+ if (!maxMessagesPerChat)
82
+ return;
83
+ const list = messages[jid];
84
+ if (!list || list.array.length <= maxMessagesPerChat)
85
+ return;
86
+ while (list.array.length > maxMessagesPerChat) {
87
+ let oldest = list.array[0];
88
+ for (const m of list.array) {
89
+ if ((m.messageTimestamp || 0) < (oldest.messageTimestamp || 0))
90
+ oldest = m;
91
+ }
92
+ list.remove(oldest);
93
+ }
94
+ };
95
+ const assertMessageList = jid => {
96
+ if (!messages[jid]) {
97
+ messages[jid] = makeMessagesDictionary();
98
+ }
99
+ return messages[jid];
100
+ };
101
+ const contactsUpsert = newContacts => {
102
+ const oldContacts = new Set(Object.keys(contacts));
103
+ for (const contact of newContacts) {
104
+ oldContacts.delete(contact.id);
105
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
106
+ }
107
+ return oldContacts;
108
+ };
109
+ const labelsUpsert = newLabels => {
110
+ for (const label of newLabels) {
111
+ labels.upsertById(label.id, label);
112
+ }
113
+ };
114
+ const bind = ev => {
115
+ ev.on('connection.update', update => {
116
+ Object.assign(state, update);
117
+ });
118
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
119
+ if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
120
+ return;
121
+ }
122
+ if (isLatest) {
123
+ chats.clear();
124
+ for (const id in messages) {
125
+ delete messages[id];
126
+ }
127
+ }
128
+ const chatsAdded = chats.insertIfAbsent(...newChats).length;
129
+ logger.debug({ chatsAdded }, 'synced chats');
130
+ const oldContacts = contactsUpsert(newContacts);
131
+ if (isLatest) {
132
+ for (const jid of oldContacts) {
133
+ delete contacts[jid];
134
+ }
135
+ }
136
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts');
137
+ for (const msg of newMessages) {
138
+ const jid = msg.key.remoteJid;
139
+ const list = assertMessageList(jid);
140
+ list.upsert(msg, 'prepend');
141
+ trimMessagesIfNeeded(jid);
142
+ }
143
+ logger.debug({ messages: newMessages.length }, 'synced messages');
144
+ });
145
+ ev.on('contacts.upsert', contacts => {
146
+ contactsUpsert(contacts);
147
+ });
148
+ ev.on('contacts.update', async (updates) => {
149
+ for (const update of updates) {
150
+ let contact;
151
+ if (contacts[update.id]) {
152
+ contact = contacts[update.id];
153
+ }
154
+ else {
155
+ const contactHashes = await Promise.all(Object.keys(contacts).map(async (contactId) => {
156
+ const { user } = WABinary_1.jidDecode(contactId);
157
+ return [
158
+ contactId,
159
+ (await Utils_1.md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)
160
+ ];
161
+ }));
162
+ contact = contacts[contactHashes.find(([, b]) => b === update.id?.[0]) || ''];
163
+ }
164
+ if (contact) {
165
+ if (update.imgUrl === 'changed') {
166
+ contact.imgUrl = socket ? await socket.profilePictureUrl(contact.id) : undefined;
167
+ }
168
+ else if (update.imgUrl === 'removed') {
169
+ delete contact.imgUrl;
170
+ }
171
+ }
172
+ else {
173
+ return logger.debug({ update }, 'got update for non-existant contact');
174
+ }
175
+ Object.assign(contacts[contact.id], contact);
176
+ }
177
+ });
178
+ ev.on('chats.upsert', newChats => {
179
+ chats.upsert(...newChats);
180
+ });
181
+ ev.on('chats.update', updates => {
182
+ for (let update of updates) {
183
+ const result = chats.update(update.id, chat => {
184
+ if (update.unreadCount > 0) {
185
+ update = { ...update };
186
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
187
+ }
188
+ Object.assign(chat, update);
189
+ });
190
+ if (!result) {
191
+ logger.debug({ update }, 'got update for non-existant chat');
192
+ }
193
+ }
194
+ });
195
+ ev.on('labels.edit', label => {
196
+ if (label.deleted) {
197
+ return labels.deleteById(label.id);
198
+ }
199
+ if (labels.count() < 20) {
200
+ return labels.upsertById(label.id, label);
201
+ }
202
+ logger.error('Labels count exceed');
203
+ });
204
+ ev.on('labels.association', ({ type, association }) => {
205
+ switch (type) {
206
+ case 'add':
207
+ labelAssociations.upsert(association);
208
+ break;
209
+ case 'remove':
210
+ labelAssociations.delete(association);
211
+ break;
212
+ default:
213
+ logger.error({ type }, 'unknown label association operation type');
214
+ }
215
+ });
216
+ ev.on('presence.update', ({ id, presences: update }) => {
217
+ presences[id] = presences[id] || {};
218
+ Object.assign(presences[id], update);
219
+ });
220
+ ev.on('chats.delete', deletions => {
221
+ for (const item of deletions) {
222
+ if (chats.get(item)) {
223
+ chats.deleteById(item);
224
+ }
225
+ }
226
+ });
227
+ ev.on('messages.upsert', ({ messages: newMessages, type }) => {
228
+ switch (type) {
229
+ case 'append':
230
+ case 'notify':
231
+ for (const msg of newMessages) {
232
+ const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid);
233
+ const list = assertMessageList(jid);
234
+ list.upsert(msg, 'append');
235
+ trimMessagesIfNeeded(jid);
236
+ if (type === 'notify' && !chats.get(jid)) {
237
+ ev.emit('chats.upsert', [
238
+ {
239
+ id: jid,
240
+ conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
241
+ unreadCount: 1
242
+ }
243
+ ]);
244
+ }
245
+ }
246
+ break;
247
+ }
248
+ });
249
+ ev.on('messages.update', updates => {
250
+ for (const { update, key } of updates) {
251
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid));
252
+ if (update?.status) {
253
+ const listStatus = list.get(key.id)?.status;
254
+ if (listStatus && update?.status <= listStatus) {
255
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update');
256
+ delete update.status;
257
+ logger.debug({ update }, 'new update object');
258
+ }
259
+ }
260
+ const result = list.updateAssign(key.id, update);
261
+ if (!result) {
262
+ logger.debug({ update }, 'got update for non-existent message');
263
+ }
264
+ }
265
+ });
266
+ ev.on('messages.delete', item => {
267
+ if ('all' in item) {
268
+ const list = messages[item.jid];
269
+ list?.clear();
270
+ }
271
+ else {
272
+ const jid = item.keys[0].remoteJid;
273
+ const list = messages[jid];
274
+ if (list) {
275
+ const idSet = new Set(item.keys.map(k => k.id));
276
+ list.filter(m => !idSet.has(m.key.id));
277
+ }
278
+ }
279
+ });
280
+ ev.on('groups.update', updates => {
281
+ for (const update of updates) {
282
+ const id = update.id;
283
+ if (groupMetadata[id]) {
284
+ Object.assign(groupMetadata[id], update);
285
+ }
286
+ else {
287
+ logger.debug({ update }, 'got update for non-existant group metadata');
288
+ }
289
+ }
290
+ });
291
+ ev.on('group-participants.update', ({ id, participants, action }) => {
292
+ const metadata = groupMetadata[id];
293
+ if (metadata) {
294
+ switch (action) {
295
+ case 'add':
296
+ metadata.participants.push(...participants.map(id => ({
297
+ id,
298
+ isAdmin: false,
299
+ isSuperAdmin: false
300
+ })));
301
+ break;
302
+ case 'demote':
303
+ case 'promote':
304
+ for (const participant of metadata.participants) {
305
+ if (participants.includes(participant.id)) {
306
+ participant.isAdmin = action === 'promote';
307
+ }
308
+ }
309
+ break;
310
+ case 'remove':
311
+ metadata.participants = metadata.participants.filter(p => !participants.includes(p.id));
312
+ break;
313
+ }
314
+ }
315
+ });
316
+ ev.on('message-receipt.update', updates => {
317
+ for (const { key, receipt } of updates) {
318
+ const obj = messages[key.remoteJid];
319
+ const msg = obj?.get(key.id);
320
+ if (msg) {
321
+ Utils_1.updateMessageWithReceipt(msg, receipt);
322
+ }
323
+ }
324
+ });
325
+ ev.on('messages.reaction', reactions => {
326
+ for (const { key, reaction } of reactions) {
327
+ const obj = messages[key.remoteJid];
328
+ const msg = obj?.get(key.id);
329
+ if (msg) {
330
+ Utils_1.updateMessageWithReaction(msg, reaction);
331
+ }
332
+ }
333
+ });
334
+ ev.on('settings.update', ({ setting, value }) => {
335
+ state.settings = state.settings || {};
336
+ state.settings[setting] = value;
337
+ });
338
+ ev.on('labels.reorder', ({ labelIds }) => {
339
+ let order = 0;
340
+ for (const id of labelIds) {
341
+ const label = labels.findById(id);
342
+ if (label) {
343
+ labels.upsertById(id, { ...label, order: order++ });
344
+ }
345
+ order++;
346
+ }
347
+ });
348
+ ev.on('call.scheduled', ({ messageKey, scheduledCall, chatId }) => {
349
+ state.scheduledCalls = state.scheduledCalls || {};
350
+ state.scheduledCalls[messageKey.id] = { key: messageKey, scheduledCall, chatId };
351
+ });
352
+ ev.on('call.schedule-cancelled', ({ messageKey, editedCallKey }) => {
353
+ if (state.scheduledCalls?.[editedCallKey?.id]) {
354
+ delete state.scheduledCalls[editedCallKey.id];
355
+ }
356
+ });
357
+ ev.on('payment.split', ({ messageKey, splitPayment }) => {
358
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(messageKey.remoteJid));
359
+ const msg = list?.get(messageKey.id);
360
+ if (msg) {
361
+ msg.splitPayment = splitPayment;
362
+ }
363
+ });
364
+ ev.on('message.comment', ({ commentKey, comment, targetKey }) => {
365
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(targetKey.remoteJid));
366
+ const msg = list?.get(targetKey.id);
367
+ if (msg) {
368
+ msg.commentCount = (msg.commentCount || 0) + 1;
369
+ }
370
+ });
371
+ ev.on('poll.add-option', ({ pollKey, addedOption }) => {
372
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(pollKey.remoteJid));
373
+ const msg = list?.get(pollKey.id);
374
+ if (msg?.message) {
375
+ const poll = msg.message.pollCreationMessage ||
376
+ msg.message.pollCreationMessageV3 ||
377
+ msg.message.pollCreationMessageV5 ||
378
+ msg.message.pollCreationMessageV6;
379
+ if (poll && addedOption) {
380
+ poll.options = [...(poll.options || []), addedOption];
381
+ }
382
+ }
383
+ });
384
+ ev.on('chats.lock', ({ id, locked }) => {
385
+ const result = chats.update(id, chat => {
386
+ chat.locked = locked;
387
+ });
388
+ if (!result)
389
+ logger.debug({ id }, 'got chats.lock for non-existent chat');
390
+ });
391
+ ev.on('messaging-history.status', ({ syncType, status }) => {
392
+ state.historySyncStatus = state.historySyncStatus || {};
393
+ state.historySyncStatus[syncType] = status;
394
+ });
395
+ };
396
+ const toJSON = () => ({
397
+ chats,
398
+ contacts,
399
+ messages,
400
+ labels,
401
+ labelAssociations,
402
+ groupMetadata,
403
+ presences,
404
+ state
405
+ });
406
+ const fromJSON = json => {
407
+ chats.upsert(...json.chats);
408
+ labelAssociations.upsert(...(json.labelAssociations || []));
409
+ contactsUpsert(Object.values(json.contacts));
410
+ labelsUpsert(Object.values(json.labels || {}));
411
+ for (const jid in json.messages) {
412
+ const list = assertMessageList(jid);
413
+ for (const msg of json.messages[jid]) {
414
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append');
415
+ }
416
+ trimMessagesIfNeeded(jid);
417
+ }
418
+ if (json.groupMetadata) {
419
+ Object.assign(groupMetadata, json.groupMetadata);
420
+ }
421
+ if (json.presences) {
422
+ Object.assign(presences, json.presences);
423
+ }
424
+ if (json.state) {
425
+ Object.assign(state, json.state);
426
+ }
427
+ };
428
+ return {
429
+ chats,
430
+ contacts,
431
+ messages,
432
+ groupMetadata,
433
+ state,
434
+ presences,
435
+ labels,
436
+ labelAssociations,
437
+ bind,
438
+ loadMessages: async (jid, count, cursor) => {
439
+ const list = assertMessageList(jid);
440
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after';
441
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined;
442
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
443
+ let messages;
444
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
445
+ if (cursorValue) {
446
+ const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id);
447
+ messages = list.array.slice(0, msgIdx);
448
+ }
449
+ else {
450
+ messages = list.array;
451
+ }
452
+ const diff = count - messages.length;
453
+ if (diff < 0) {
454
+ messages = messages.slice(-count);
455
+ }
456
+ }
457
+ else {
458
+ messages = [];
459
+ }
460
+ return messages;
461
+ },
462
+ getLabels: () => {
463
+ return labels;
464
+ },
465
+ getChatLabels: chatId => {
466
+ return labelAssociations.filter(la => la.chatId === chatId).all();
467
+ },
468
+ getMessageLabels: messageId => {
469
+ const associations = labelAssociations.filter(la => la.messageId === messageId).all();
470
+ return associations.map(({ labelId }) => labelId);
471
+ },
472
+ loadMessage: async (jid, id) => messages[jid]?.get(id),
473
+ mostRecentMessage: async (jid) => {
474
+ const message = messages[jid]?.array.slice(-1)[0];
475
+ return message;
476
+ },
477
+ fetchImageUrl: async (jid, suki) => {
478
+ const contact = contacts[jid];
479
+ if (!contact) {
480
+ return suki?.profilePictureUrl(jid);
481
+ }
482
+ if (typeof contact.imgUrl === 'undefined') {
483
+ contact.imgUrl = await suki?.profilePictureUrl(jid);
484
+ }
485
+ return contact.imgUrl;
486
+ },
487
+ fetchGroupMetadata: async (jid, suki) => {
488
+ if (!groupMetadata[jid]) {
489
+ const metadata = await suki?.groupMetadata(jid);
490
+ if (metadata) {
491
+ groupMetadata[jid] = metadata;
492
+ }
493
+ }
494
+ return groupMetadata[jid];
495
+ },
496
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
497
+ const list = messages[remoteJid];
498
+ const msg = list?.get(id);
499
+ return msg?.userReceipt;
500
+ },
501
+ toJSON,
502
+ fromJSON,
503
+ writeToFile: path => {
504
+ const { writeFileSync } = require('fs');
505
+ const jsonStr = JSON.stringify(toJSON());
506
+ writeFileSync(path, config.encryptionKey ? encryptStoreJSON(jsonStr, config.encryptionKey) : jsonStr);
507
+ },
508
+ readFromFile: path => {
509
+ const { readFileSync, existsSync } = require('fs');
510
+ if (existsSync(path)) {
511
+ logger.debug({ path }, 'reading from file');
512
+ const fileStr = readFileSync(path, { encoding: 'utf-8' });
513
+ const jsonStr = config.encryptionKey ? decryptStoreJSON(fileStr, config.encryptionKey) : fileStr;
514
+ const json = JSON.parse(jsonStr);
515
+ fromJSON(json);
516
+ }
517
+ },
518
+ startAutoSave: (path, intervalMs = 30000) => {
519
+ const timer = setInterval(() => {
520
+ try {
521
+ const { writeFileSync } = require('fs');
522
+ const jsonStr = JSON.stringify(toJSON());
523
+ writeFileSync(path, config.encryptionKey ? encryptStoreJSON(jsonStr, config.encryptionKey) : jsonStr);
524
+ }
525
+ catch (error) {
526
+ logger.warn({ error, path }, 'failed to auto-save store');
527
+ }
528
+ }, intervalMs);
529
+ if (timer.unref)
530
+ timer.unref();
531
+ if (socket && typeof socket.registerSocketEndHandler === 'function') {
532
+ socket.registerSocketEndHandler(async () => {
533
+ try {
534
+ const { writeFileSync } = require('fs');
535
+ const jsonStr = JSON.stringify(toJSON());
536
+ writeFileSync(path, config.encryptionKey ? encryptStoreJSON(jsonStr, config.encryptionKey) : jsonStr);
537
+ logger.debug({ path }, 'final store flush on socket end');
538
+ }
539
+ catch (error) {
540
+ logger.warn({ error, path }, 'failed to flush store on socket end');
541
+ }
542
+ });
543
+ }
544
+ return () => clearInterval(timer);
545
+ }
546
+ };
547
+ };
548
+ exports.waChatKey = waChatKey;
549
+ exports.waMessageID = waMessageID;
550
+ exports.waLabelAssociationKey = waLabelAssociationKey;
551
+ exports.makeInMemoryStore = makeInMemoryStore;
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ function makeOrderedDictionary(idGetter) {
4
+ const array = [];
5
+ const dict = {};
6
+ const get = id => dict[id];
7
+ const update = item => {
8
+ const id = idGetter(item);
9
+ const idx = array.findIndex(i => idGetter(i) === id);
10
+ if (idx >= 0) {
11
+ array[idx] = item;
12
+ dict[id] = item;
13
+ }
14
+ return false;
15
+ };
16
+ const upsert = (item, mode) => {
17
+ const id = idGetter(item);
18
+ if (get(id)) {
19
+ update(item);
20
+ }
21
+ else {
22
+ if (mode === 'append') {
23
+ array.push(item);
24
+ }
25
+ else {
26
+ array.splice(0, 0, item);
27
+ }
28
+ dict[id] = item;
29
+ }
30
+ };
31
+ const remove = item => {
32
+ const id = idGetter(item);
33
+ const idx = array.findIndex(i => idGetter(i) === id);
34
+ if (idx >= 0) {
35
+ array.splice(idx, 1);
36
+ delete dict[id];
37
+ return true;
38
+ }
39
+ return false;
40
+ };
41
+ return {
42
+ array,
43
+ get,
44
+ upsert,
45
+ update,
46
+ remove,
47
+ updateAssign: (id, update) => {
48
+ const item = get(id);
49
+ if (item) {
50
+ Object.assign(item, update);
51
+ delete dict[id];
52
+ dict[idGetter(item)] = item;
53
+ return true;
54
+ }
55
+ return false;
56
+ },
57
+ clear: () => {
58
+ array.splice(0, array.length);
59
+ for (const key of Object.keys(dict)) {
60
+ delete dict[key];
61
+ }
62
+ },
63
+ filter: contain => {
64
+ let i = 0;
65
+ while (i < array.length) {
66
+ if (!contain(array[i])) {
67
+ delete dict[idGetter(array[i])];
68
+ array.splice(i, 1);
69
+ }
70
+ else {
71
+ i += 1;
72
+ }
73
+ }
74
+ },
75
+ toJSON: () => array,
76
+ fromJSON: newItems => {
77
+ array.splice(0, array.length, ...newItems);
78
+ }
79
+ };
80
+ }
81
+ exports.makeOrderedDictionary = makeOrderedDictionary;
@@ -0,0 +1,26 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ class ObjectRepository {
4
+ constructor(entities = {}) {
5
+ this.entityMap = new Map(Object.entries(entities));
6
+ }
7
+ findById(id) {
8
+ return this.entityMap.get(id);
9
+ }
10
+ findAll() {
11
+ return Array.from(this.entityMap.values());
12
+ }
13
+ upsertById(id, entity) {
14
+ return this.entityMap.set(id, { ...entity });
15
+ }
16
+ deleteById(id) {
17
+ return this.entityMap.delete(id);
18
+ }
19
+ count() {
20
+ return this.entityMap.size;
21
+ }
22
+ toJSON() {
23
+ return this.findAll();
24
+ }
25
+ }
26
+ exports.ObjectRepository = ObjectRepository;
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ function createKeyPair(publicKey, privateKey) {
4
+ return {
5
+ public: publicKey,
6
+ private: privateKey
7
+ };
8
+ }
9
+ function createSignedKeyPair(keyPair, signature, keyId, timestampS) {
10
+ return {
11
+ keyPair,
12
+ signature,
13
+ keyId,
14
+ timestampS
15
+ };
16
+ }
17
+ exports.SignalDataTypeMap = {
18
+ 'pre-key': 'KeyPair',
19
+ session: 'Uint8Array',
20
+ 'sender-key': 'Uint8Array',
21
+ 'sender-key-memory': 'object',
22
+ 'app-state-sync-key': 'proto.Message.IAppStateSyncKeyData',
23
+ 'app-state-sync-version': 'LTHashState',
24
+ 'lid-mapping': 'string',
25
+ 'device-list': 'Array',
26
+ tctoken: 'object'
27
+ };
28
+ exports.SignalDataSet = undefined;
29
+ exports.Awaitable = undefined;
30
+ exports.createKeyPair = createKeyPair;
31
+ exports.createSignedKeyPair = createSignedKeyPair;
@@ -0,0 +1,2 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
@@ -0,0 +1,2 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });