@badzz88/baileys 8.5.5 → 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 (282) hide show
  1. package/README.md +2 -2
  2. package/WAProto/WAProto.proto +1256 -75
  3. package/WAProto/fix-imports.js +69 -79
  4. package/WAProto/index.d.ts +15254 -71491
  5. package/WAProto/index.js +19816 -126438
  6. package/engine-requirements.js +3 -4
  7. package/package.json +4 -4
  8. package/src/Defaults/index.js +186 -0
  9. package/src/Signal/Group/ciphertext-message.js +15 -0
  10. package/src/Signal/Group/group-session-builder.js +86 -0
  11. package/src/Signal/Group/group_cipher.js +82 -0
  12. package/src/Signal/Group/index.js +140 -0
  13. package/src/Signal/Group/keyhelper.js +77 -0
  14. package/src/Signal/Group/sender-chain-key.js +29 -0
  15. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/src/Signal/Group/sender-key-message.js +69 -0
  17. package/src/Signal/Group/sender-key-name.js +51 -0
  18. package/src/Signal/Group/sender-key-record.js +44 -0
  19. package/src/Signal/Group/sender-key-state.js +87 -0
  20. package/src/Signal/Group/sender-message-key.js +29 -0
  21. package/src/Signal/libsignal.js +455 -0
  22. package/src/Signal/lid-mapping.js +273 -0
  23. package/src/Socket/Client/index.js +31 -0
  24. package/src/Socket/Client/types.js +13 -0
  25. package/src/Socket/Client/websocket.js +61 -0
  26. package/src/Socket/aigroups.js +221 -0
  27. package/src/Socket/business.js +411 -0
  28. package/src/Socket/chats.js +1449 -0
  29. package/src/Socket/communities.js +463 -0
  30. package/src/Socket/graphql.js +523 -0
  31. package/src/Socket/groups.js +516 -0
  32. package/src/Socket/index.js +31 -0
  33. package/src/Socket/interactive-handler.js +527 -0
  34. package/src/Socket/interop.js +339 -0
  35. package/{lib → src}/Socket/luxu.js +82 -120
  36. package/src/Socket/managed-account.js +98 -0
  37. package/src/Socket/messages-recv.js +2685 -0
  38. package/src/Socket/messages-send.js +2047 -0
  39. package/src/Socket/mex.js +57 -0
  40. package/src/Socket/newsletter.js +455 -0
  41. package/src/Socket/privacy.js +125 -0
  42. package/src/Socket/registration.js +236 -0
  43. package/src/Socket/socket.js +983 -0
  44. package/src/Socket/text-router.js +65 -0
  45. package/src/Socket/username.js +130 -0
  46. package/src/Store/index.js +33 -0
  47. package/{lib → src}/Store/keyed-db.js +21 -11
  48. package/src/Store/make-cache-manager-store.js +84 -0
  49. package/src/Store/make-in-memory-store.js +551 -0
  50. package/src/Store/make-ordered-dictionary.js +81 -0
  51. package/src/Store/object-repository.js +26 -0
  52. package/src/Types/Auth.js +31 -0
  53. package/src/Types/Bussines.js +2 -0
  54. package/src/Types/Call.js +2 -0
  55. package/src/Types/Chat.js +4 -0
  56. package/src/Types/Contact.js +2 -0
  57. package/src/Types/Events.js +2 -0
  58. package/src/Types/GroupMetadata.js +2 -0
  59. package/src/Types/Label.js +26 -0
  60. package/src/Types/LabelAssociation.js +8 -0
  61. package/src/Types/Message.js +93 -0
  62. package/src/Types/Mex.js +112 -0
  63. package/src/Types/Newsletter.js +109 -0
  64. package/src/Types/Product.js +2 -0
  65. package/src/Types/Signal.js +2 -0
  66. package/src/Types/Socket.js +2 -0
  67. package/src/Types/State.js +62 -0
  68. package/src/Types/USync.js +2 -0
  69. package/src/Types/index.js +56 -0
  70. package/src/Utils/auth-utils.js +254 -0
  71. package/src/Utils/browser-utils.js +112 -0
  72. package/src/Utils/business.js +240 -0
  73. package/src/Utils/chat-utils.js +1230 -0
  74. package/src/Utils/command-loader.d.ts +27 -0
  75. package/src/Utils/command-loader.js +89 -0
  76. package/src/Utils/companion-reg-client-utils.js +40 -0
  77. package/src/Utils/consumer-application.js +105 -0
  78. package/src/Utils/crypto.js +118 -0
  79. package/src/Utils/curve25519-js.js +242 -0
  80. package/src/Utils/decode-wa-message.js +529 -0
  81. package/src/Utils/event-buffer.js +580 -0
  82. package/src/Utils/generics.js +483 -0
  83. package/src/Utils/group-history.js +44 -0
  84. package/src/Utils/history.js +232 -0
  85. package/src/Utils/identity-change-handler.js +52 -0
  86. package/src/Utils/index.js +58 -0
  87. package/src/Utils/jid-display-normalization.js +195 -0
  88. package/src/Utils/link-preview.js +135 -0
  89. package/src/Utils/logger.js +8 -0
  90. package/src/Utils/lt-hash.js +25 -0
  91. package/src/Utils/make-mutex.js +36 -0
  92. package/src/Utils/message-composer.js +471 -0
  93. package/src/Utils/message-retry-manager.js +217 -0
  94. package/src/Utils/messages-media.js +843 -0
  95. package/src/Utils/messages.js +2817 -0
  96. package/src/Utils/meta-ai-msmsg.js +222 -0
  97. package/src/Utils/native-bridge.js +68 -0
  98. package/src/Utils/noise-handler.js +169 -0
  99. package/src/Utils/offline-node-processor.js +34 -0
  100. package/src/Utils/pre-key-manager.js +90 -0
  101. package/src/Utils/process-message.js +950 -0
  102. package/src/Utils/reporting-utils.js +261 -0
  103. package/src/Utils/session-pool.d.ts +14 -0
  104. package/src/Utils/session-pool.js +70 -0
  105. package/src/Utils/signal.js +217 -0
  106. package/src/Utils/stanza-ack.js +30 -0
  107. package/src/Utils/sticker.d.ts +13 -0
  108. package/src/Utils/sticker.js +123 -0
  109. package/src/Utils/sync-action-utils.js +45 -0
  110. package/src/Utils/tc-token-utils.js +158 -0
  111. package/src/Utils/use-multi-file-auth-state.js +111 -0
  112. package/src/Utils/validate-connection.js +209 -0
  113. package/src/Utils/view-once-cache.d.ts +12 -0
  114. package/src/Utils/view-once-cache.js +63 -0
  115. package/src/Utils/voip-rekey.js +22 -0
  116. package/src/WABinary/constants.js +1304 -0
  117. package/src/WABinary/decode.js +342 -0
  118. package/{lib → src}/WABinary/encode.js +9 -12
  119. package/src/WABinary/generic-utils.js +238 -0
  120. package/src/WABinary/index.js +34 -0
  121. package/src/WABinary/jid-utils.js +351 -0
  122. package/src/WABinary/types.js +2 -0
  123. package/src/WAM/BinaryInfo.js +13 -0
  124. package/src/WAM/constants.js +39484 -0
  125. package/src/WAM/encode.js +149 -0
  126. package/src/WAM/index.js +32 -0
  127. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  128. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +44 -0
  129. package/src/WAUSync/Protocols/USyncContactProtocol.js +55 -0
  130. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +55 -0
  131. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  132. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +54 -0
  133. package/src/WAUSync/Protocols/USyncLIDProtocol.js +32 -0
  134. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +473 -0
  135. package/src/WAUSync/Protocols/USyncPictureProtocol.js +34 -0
  136. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  137. package/src/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  138. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  139. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  140. package/src/WAUSync/Protocols/index.js +40 -0
  141. package/src/WAUSync/USyncQuery.js +126 -0
  142. package/src/WAUSync/USyncUser.js +50 -0
  143. package/src/WAUSync/index.js +32 -0
  144. package/src/antiban.js +4152 -0
  145. package/{lib → src}/index.js +51 -49
  146. package/lib/Defaults/index.js +0 -187
  147. package/lib/Signal/Group/ciphertext-message.js +0 -15
  148. package/lib/Signal/Group/group-session-builder.js +0 -92
  149. package/lib/Signal/Group/group_cipher.js +0 -89
  150. package/lib/Signal/Group/index.js +0 -136
  151. package/lib/Signal/Group/keyhelper.js +0 -73
  152. package/lib/Signal/Group/sender-chain-key.js +0 -32
  153. package/lib/Signal/Group/sender-key-distribution-message.js +0 -66
  154. package/lib/Signal/Group/sender-key-message.js +0 -69
  155. package/lib/Signal/Group/sender-key-name.js +0 -50
  156. package/lib/Signal/Group/sender-key-record.js +0 -44
  157. package/lib/Signal/Group/sender-key-state.js +0 -97
  158. package/lib/Signal/Group/sender-message-key.js +0 -30
  159. package/lib/Signal/libsignal.js +0 -459
  160. package/lib/Signal/lid-mapping.js +0 -260
  161. package/lib/Socket/Client/index.js +0 -30
  162. package/lib/Socket/Client/types.js +0 -13
  163. package/lib/Socket/Client/websocket.js +0 -62
  164. package/lib/Socket/aigroups.js +0 -240
  165. package/lib/Socket/business.js +0 -422
  166. package/lib/Socket/chats.js +0 -1816
  167. package/lib/Socket/communities.js +0 -549
  168. package/lib/Socket/graphql.js +0 -656
  169. package/lib/Socket/groups.js +0 -764
  170. package/lib/Socket/index.js +0 -39
  171. package/lib/Socket/interactive-handler.js +0 -522
  172. package/lib/Socket/interop.js +0 -549
  173. package/lib/Socket/managed-account.js +0 -183
  174. package/lib/Socket/messages-recv.js +0 -2442
  175. package/lib/Socket/messages-send.js +0 -1853
  176. package/lib/Socket/mex.js +0 -60
  177. package/lib/Socket/newsletter.js +0 -818
  178. package/lib/Socket/privacy.js +0 -449
  179. package/lib/Socket/registration.js +0 -427
  180. package/lib/Socket/socket.js +0 -1092
  181. package/lib/Socket/text-router.js +0 -83
  182. package/lib/Socket/username.js +0 -243
  183. package/lib/Store/index.js +0 -36
  184. package/lib/Store/make-cache-manager-store.js +0 -90
  185. package/lib/Store/make-in-memory-store.js +0 -604
  186. package/lib/Store/make-ordered-dictionary.js +0 -81
  187. package/lib/Store/object-repository.js +0 -29
  188. package/lib/Types/Auth.js +0 -38
  189. package/lib/Types/Bussines.js +0 -2
  190. package/lib/Types/Call.js +0 -2
  191. package/lib/Types/Chat.js +0 -4
  192. package/lib/Types/Contact.js +0 -2
  193. package/lib/Types/Events.js +0 -2
  194. package/lib/Types/GroupMetadata.js +0 -2
  195. package/lib/Types/Label.js +0 -27
  196. package/lib/Types/LabelAssociation.js +0 -9
  197. package/lib/Types/Message.js +0 -95
  198. package/lib/Types/Mex.js +0 -112
  199. package/lib/Types/Newsletter.js +0 -121
  200. package/lib/Types/Product.js +0 -2
  201. package/lib/Types/Signal.js +0 -2
  202. package/lib/Types/Socket.js +0 -2
  203. package/lib/Types/State.js +0 -70
  204. package/lib/Types/USync.js +0 -2
  205. package/lib/Types/index.js +0 -55
  206. package/lib/Utils/auth-utils.js +0 -306
  207. package/lib/Utils/browser-utils.js +0 -114
  208. package/lib/Utils/business.js +0 -247
  209. package/lib/Utils/chat-utils.js +0 -1208
  210. package/lib/Utils/command-loader.d.ts +0 -31
  211. package/lib/Utils/command-loader.js +0 -100
  212. package/lib/Utils/companion-reg-client-utils.js +0 -42
  213. package/lib/Utils/consumer-application.js +0 -107
  214. package/lib/Utils/crypto.js +0 -155
  215. package/lib/Utils/curve25519-js.js +0 -275
  216. package/lib/Utils/decode-wa-message.js +0 -560
  217. package/lib/Utils/event-buffer.js +0 -607
  218. package/lib/Utils/generics.js +0 -563
  219. package/lib/Utils/group-history.js +0 -60
  220. package/lib/Utils/history.js +0 -244
  221. package/lib/Utils/identity-change-handler.js +0 -52
  222. package/lib/Utils/index.js +0 -57
  223. package/lib/Utils/jid-display-normalization.js +0 -218
  224. package/lib/Utils/link-preview.js +0 -143
  225. package/lib/Utils/logger.js +0 -9
  226. package/lib/Utils/lt-hash.js +0 -39
  227. package/lib/Utils/make-mutex.js +0 -36
  228. package/lib/Utils/message-composer.js +0 -479
  229. package/lib/Utils/message-inspect.js +0 -393
  230. package/lib/Utils/message-retry-manager.js +0 -270
  231. package/lib/Utils/messages-media.js +0 -896
  232. package/lib/Utils/messages.js +0 -2904
  233. package/lib/Utils/meta-ai-msmsg.js +0 -262
  234. package/lib/Utils/native-bridge.js +0 -82
  235. package/lib/Utils/noise-handler.js +0 -196
  236. package/lib/Utils/offline-node-processor.js +0 -42
  237. package/lib/Utils/pre-key-manager.js +0 -107
  238. package/lib/Utils/process-message.js +0 -1048
  239. package/lib/Utils/reporting-utils.js +0 -262
  240. package/lib/Utils/session-pool.d.ts +0 -16
  241. package/lib/Utils/session-pool.js +0 -94
  242. package/lib/Utils/signal.js +0 -224
  243. package/lib/Utils/stanza-ack.js +0 -40
  244. package/lib/Utils/sticker.d.ts +0 -17
  245. package/lib/Utils/sticker.js +0 -145
  246. package/lib/Utils/sync-action-utils.js +0 -54
  247. package/lib/Utils/tc-token-utils.js +0 -161
  248. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  249. package/lib/Utils/validate-connection.js +0 -219
  250. package/lib/Utils/view-once-cache.d.ts +0 -9
  251. package/lib/Utils/view-once-cache.js +0 -79
  252. package/lib/Utils/voip-rekey.js +0 -22
  253. package/lib/WABinary/constants.js +0 -1304
  254. package/lib/WABinary/decode.js +0 -343
  255. package/lib/WABinary/generic-utils.js +0 -240
  256. package/lib/WABinary/index.js +0 -33
  257. package/lib/WABinary/jid-utils.js +0 -361
  258. package/lib/WABinary/types.js +0 -2
  259. package/lib/WAM/BinaryInfo.js +0 -13
  260. package/lib/WAM/constants.js +0 -39486
  261. package/lib/WAM/encode.js +0 -142
  262. package/lib/WAM/index.js +0 -31
  263. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -55
  264. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +0 -43
  265. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -54
  266. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -57
  267. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -30
  268. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +0 -59
  269. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +0 -31
  270. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -865
  271. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +0 -32
  272. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
  273. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -39
  274. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
  275. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -27
  276. package/lib/WAUSync/Protocols/index.js +0 -39
  277. package/lib/WAUSync/USyncBackoff.js +0 -26
  278. package/lib/WAUSync/USyncQuery.js +0 -133
  279. package/lib/WAUSync/USyncUser.js +0 -50
  280. package/lib/WAUSync/index.js +0 -31
  281. package/lib/antiban.js +0 -4637
  282. /package/{lib → src}/Defaults/phonenumber-mcc.json +0 -0
@@ -0,0 +1,273 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ exports.LIDMappingStore = void 0;
4
+ const lru_cache_1 = require('lru-cache');
5
+ const WABinary_1 = require('../WABinary');
6
+ class LIDMappingStore {
7
+ constructor(keys, logger, pnToLIDFunc) {
8
+ this.mappingCache = new lru_cache_1.LRUCache({
9
+ ttl: 3 * 24 * 60 * 60 * 1000,
10
+ ttlAutopurge: true,
11
+ updateAgeOnGet: true
12
+ });
13
+ this.inflightLIDLookups = new Map();
14
+ this.inflightPNLookups = new Map();
15
+ this.keys = keys;
16
+ this.pnToLIDFunc = pnToLIDFunc;
17
+ this.logger = logger;
18
+ }
19
+ async storeLIDPNMappings(pairs) {
20
+ if (pairs.length === 0)
21
+ return;
22
+ const validatedPairs = [];
23
+ for (const { lid, pn } of pairs) {
24
+ if (!(((0, WABinary_1.isLidUser)(lid) && (0, WABinary_1.isPnUser)(pn)) ||
25
+ ((0, WABinary_1.isPnUser)(lid) && (0, WABinary_1.isLidUser)(pn)))) {
26
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
27
+ continue;
28
+ }
29
+ const lidDecoded = (0, WABinary_1.jidDecode)(lid);
30
+ const pnDecoded = (0, WABinary_1.jidDecode)(pn);
31
+ if (!lidDecoded || !pnDecoded)
32
+ continue;
33
+ validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user });
34
+ }
35
+ if (validatedPairs.length === 0)
36
+ return;
37
+ const cacheMissSet = new Set();
38
+ const existingMappings = new Map();
39
+ for (const { pnUser } of validatedPairs) {
40
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
41
+ if (cached) {
42
+ existingMappings.set(pnUser, cached);
43
+ }
44
+ else {
45
+ cacheMissSet.add(pnUser);
46
+ }
47
+ }
48
+ if (cacheMissSet.size > 0) {
49
+ const cacheMisses = [...cacheMissSet];
50
+ this.logger.trace(`Batch fetching ${cacheMisses.length} LID mappings from database`);
51
+ const stored = await this.keys.get('lid-mapping', cacheMisses);
52
+ for (const pnUser of cacheMisses) {
53
+ const existingLidUser = stored[pnUser];
54
+ if (existingLidUser) {
55
+ existingMappings.set(pnUser, existingLidUser);
56
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
57
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
58
+ }
59
+ }
60
+ }
61
+ const pairMap = {};
62
+ for (const { pnUser, lidUser } of validatedPairs) {
63
+ const existingLidUser = existingMappings.get(pnUser);
64
+ if (existingLidUser === lidUser) {
65
+ this.logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping');
66
+ continue;
67
+ }
68
+ pairMap[pnUser] = lidUser;
69
+ }
70
+ if (Object.keys(pairMap).length === 0)
71
+ return;
72
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
73
+ const batchData = {};
74
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
75
+ batchData[pnUser] = lidUser;
76
+ batchData[`${lidUser}_reverse`] = pnUser;
77
+ }
78
+ await this.keys.transaction(async () => {
79
+ await this.keys.set({ 'lid-mapping': batchData });
80
+ }, 'lid-mapping');
81
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
82
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
83
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
84
+ }
85
+ }
86
+ async getLIDForPN(pn) {
87
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
88
+ }
89
+ async getLIDsForPNs(pns) {
90
+ if (pns.length === 0)
91
+ return null;
92
+ const sortedPns = [...new Set(pns)].sort();
93
+ const cacheKey = sortedPns.join(',');
94
+ const inflight = this.inflightLIDLookups.get(cacheKey);
95
+ if (inflight) {
96
+ this.logger.trace(`Coalescing getLIDsForPNs request for ${sortedPns.length} PNs`);
97
+ return inflight;
98
+ }
99
+ const promise = this._getLIDsForPNsImpl(pns);
100
+ this.inflightLIDLookups.set(cacheKey, promise);
101
+ try {
102
+ return await promise;
103
+ }
104
+ finally {
105
+ this.inflightLIDLookups.delete(cacheKey);
106
+ }
107
+ }
108
+ async _getLIDsForPNsImpl(pns) {
109
+ const usyncFetch = {};
110
+ const successfulPairs = {};
111
+ const pending = [];
112
+ const addResolvedPair = (pn, decoded, lidUser) => {
113
+ const normalizedLidUser = lidUser.toString();
114
+ if (!normalizedLidUser) {
115
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
116
+ return false;
117
+ }
118
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0;
119
+ const deviceSpecificLid = `${normalizedLidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`;
120
+ this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
121
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn };
122
+ return true;
123
+ };
124
+ for (const pn of pns) {
125
+ if (!(0, WABinary_1.isPnUser)(pn) && !(0, WABinary_1.isHostedPnUser)(pn))
126
+ continue;
127
+ const decoded = (0, WABinary_1.jidDecode)(pn);
128
+ if (!decoded)
129
+ continue;
130
+ const pnUser = decoded.user;
131
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
132
+ if (cached && typeof cached === 'string') {
133
+ if (!addResolvedPair(pn, decoded, cached)) {
134
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
135
+ continue;
136
+ }
137
+ continue;
138
+ }
139
+ pending.push({ pn, pnUser, decoded });
140
+ }
141
+ if (pending.length) {
142
+ const pnUsers = [...new Set(pending.map(item => item.pnUser))];
143
+ const stored = await this.keys.get('lid-mapping', pnUsers);
144
+ for (const pnUser of pnUsers) {
145
+ const lidUser = stored[pnUser];
146
+ if (lidUser && typeof lidUser === 'string') {
147
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
148
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
149
+ }
150
+ }
151
+ for (const { pn, pnUser, decoded } of pending) {
152
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
153
+ if (cached && typeof cached === 'string') {
154
+ if (!addResolvedPair(pn, decoded, cached)) {
155
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
156
+ continue;
157
+ }
158
+ }
159
+ else {
160
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`);
161
+ const device = decoded.device || 0;
162
+ let normalizedPn = (0, WABinary_1.jidNormalizedUser)(pn);
163
+ if ((0, WABinary_1.isHostedPnUser)(normalizedPn)) {
164
+ normalizedPn = `${pnUser}@s.whatsapp.net`;
165
+ }
166
+ if (!usyncFetch[normalizedPn]) {
167
+ usyncFetch[normalizedPn] = [device];
168
+ }
169
+ else {
170
+ usyncFetch[normalizedPn]?.push(device);
171
+ }
172
+ }
173
+ }
174
+ }
175
+ if (Object.keys(usyncFetch).length > 0) {
176
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch));
177
+ if (result && result.length > 0) {
178
+ await this.storeLIDPNMappings(result);
179
+ for (const pair of result) {
180
+ const pnDecoded = (0, WABinary_1.jidDecode)(pair.pn);
181
+ const pnUser = pnDecoded?.user;
182
+ if (!pnUser)
183
+ continue;
184
+ const lidUser = (0, WABinary_1.jidDecode)(pair.lid)?.user;
185
+ if (!lidUser)
186
+ continue;
187
+ for (const device of usyncFetch[pair.pn]) {
188
+ const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted.lid' : 'lid'}`;
189
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`);
190
+ const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`;
191
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
192
+ }
193
+ }
194
+ }
195
+ else {
196
+ this.logger.warn('USync fetch yielded no results for pending PNs');
197
+ }
198
+ }
199
+ return Object.values(successfulPairs).length > 0 ? Object.values(successfulPairs) : null;
200
+ }
201
+ async getPNForLID(lid) {
202
+ return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null;
203
+ }
204
+ async getPNsForLIDs(lids) {
205
+ if (lids.length === 0)
206
+ return null;
207
+ const sortedLids = [...new Set(lids)].sort();
208
+ const cacheKey = sortedLids.join(',');
209
+ const inflight = this.inflightPNLookups.get(cacheKey);
210
+ if (inflight) {
211
+ this.logger.trace(`Coalescing getPNsForLIDs request for ${sortedLids.length} LIDs`);
212
+ return inflight;
213
+ }
214
+ const promise = this._getPNsForLIDsImpl(lids);
215
+ this.inflightPNLookups.set(cacheKey, promise);
216
+ try {
217
+ return await promise;
218
+ }
219
+ finally {
220
+ this.inflightPNLookups.delete(cacheKey);
221
+ }
222
+ }
223
+ async _getPNsForLIDsImpl(lids) {
224
+ const successfulPairs = {};
225
+ const pending = [];
226
+ const addResolvedPair = (lid, decoded, pnUser) => {
227
+ if (!pnUser || typeof pnUser !== 'string') {
228
+ return false;
229
+ }
230
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0;
231
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === WABinary_1.WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`;
232
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
233
+ successfulPairs[lid] = { lid, pn: pnJid };
234
+ return true;
235
+ };
236
+ for (const lid of lids) {
237
+ if (!(0, WABinary_1.isLidUser)(lid))
238
+ continue;
239
+ const decoded = (0, WABinary_1.jidDecode)(lid);
240
+ if (!decoded)
241
+ continue;
242
+ const lidUser = decoded.user;
243
+ const cached = this.mappingCache.get(`lid:${lidUser}`);
244
+ if (cached && typeof cached === 'string') {
245
+ addResolvedPair(lid, decoded, cached);
246
+ continue;
247
+ }
248
+ pending.push({ lid, lidUser, decoded });
249
+ }
250
+ if (pending.length) {
251
+ const reverseKeys = [...new Set(pending.map(item => `${item.lidUser}_reverse`))];
252
+ const stored = await this.keys.get('lid-mapping', reverseKeys);
253
+ for (const { lid, lidUser, decoded } of pending) {
254
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`);
255
+ if (!pnUser || typeof pnUser !== 'string') {
256
+ pnUser = stored[`${lidUser}_reverse`];
257
+ if (pnUser && typeof pnUser === 'string') {
258
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
259
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
260
+ }
261
+ }
262
+ if (pnUser && typeof pnUser === 'string') {
263
+ addResolvedPair(lid, decoded, pnUser);
264
+ }
265
+ else {
266
+ this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
267
+ }
268
+ }
269
+ }
270
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null;
271
+ }
272
+ }
273
+ exports.LIDMappingStore = LIDMappingStore;
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+ var __createBinding = (this && this.__createBinding) ||
3
+ (Object.create
4
+ ? function (o, m, k, k2) {
5
+ if (k2 === undefined)
6
+ k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = {
10
+ enumerable: true,
11
+ get: function () {
12
+ return m[k];
13
+ }
14
+ };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }
18
+ : function (o, m, k, k2) {
19
+ if (k2 === undefined)
20
+ k2 = k;
21
+ o[k2] = m[k];
22
+ });
23
+ var __exportStar = (this && this.__exportStar) ||
24
+ function (m, exports) {
25
+ for (var p in m)
26
+ if (p !== 'default' && !Object.prototype.hasOwnProperty.call(exports, p))
27
+ __createBinding(exports, m, p);
28
+ };
29
+ Object.defineProperty(exports, '__esModule', { value: true });
30
+ __exportStar(require('./types'), exports);
31
+ __exportStar(require('./websocket'), exports);
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ exports.AbstractSocketClient = void 0;
4
+ const events_1 = require('events');
5
+ class AbstractSocketClient extends events_1.EventEmitter {
6
+ constructor(url, config) {
7
+ super();
8
+ this.url = url;
9
+ this.config = config;
10
+ this.setMaxListeners(0);
11
+ }
12
+ }
13
+ exports.AbstractSocketClient = AbstractSocketClient;
@@ -0,0 +1,61 @@
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
+ exports.WebSocketClient = void 0;
8
+ const ws_1 = __importDefault(require('ws'));
9
+ const Defaults_1 = require('../../Defaults');
10
+ const types_1 = require('./types');
11
+ class WebSocketClient extends types_1.AbstractSocketClient {
12
+ constructor() {
13
+ super(...arguments);
14
+ this.socket = null;
15
+ }
16
+ get isOpen() {
17
+ return this.socket?.readyState === ws_1.default.OPEN;
18
+ }
19
+ get isClosed() {
20
+ return this.socket === null || this.socket?.readyState === ws_1.default.CLOSED;
21
+ }
22
+ get isClosing() {
23
+ return this.socket === null || this.socket?.readyState === ws_1.default.CLOSING;
24
+ }
25
+ get isConnecting() {
26
+ return this.socket?.readyState === ws_1.default.CONNECTING;
27
+ }
28
+ connect() {
29
+ if (this.socket) {
30
+ return;
31
+ }
32
+ this.socket = new ws_1.default(this.url, {
33
+ origin: Defaults_1.DEFAULT_ORIGIN,
34
+ headers: this.config.options?.headers,
35
+ handshakeTimeout: this.config.connectTimeoutMs,
36
+ timeout: this.config.connectTimeoutMs,
37
+ agent: this.config.agent
38
+ });
39
+ this.socket.setMaxListeners(0);
40
+ const events = ['close', 'error', 'upgrade', 'message', 'open', 'ping', 'pong', 'unexpected-response'];
41
+ for (const event of events) {
42
+ this.socket?.on(event, (...args) => this.emit(event, ...args));
43
+ }
44
+ }
45
+ async close() {
46
+ if (!this.socket) {
47
+ return;
48
+ }
49
+ const closePromise = new Promise(resolve => {
50
+ this.socket?.once('close', resolve);
51
+ });
52
+ this.socket.close();
53
+ await closePromise;
54
+ this.socket = null;
55
+ }
56
+ send(str, cb) {
57
+ this.socket?.send(str, cb);
58
+ return Boolean(this.socket);
59
+ }
60
+ }
61
+ exports.WebSocketClient = WebSocketClient;
@@ -0,0 +1,221 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ exports.extractAIGroupMetadata = exports.makeAIGroupsSocket = void 0;
4
+ const Types_1 = require('../Types');
5
+ const Utils_1 = require('../Utils');
6
+ const WABinary_1 = require('../WABinary');
7
+ const groups_1 = require('./groups');
8
+ const makeAIGroupsSocket = config => {
9
+ const sock = (0, groups_1.makeGroupsSocket)(config);
10
+ const { ev, query } = sock;
11
+ const aiGroupQuery = async (jid, type, content) => query({
12
+ tag: 'iq',
13
+ attrs: {
14
+ type,
15
+ xmlns: 'w:g2',
16
+ to: jid
17
+ },
18
+ content
19
+ });
20
+ const aiGroupMetadata = async (jid) => {
21
+ const result = await aiGroupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
22
+ return (0, exports.extractAIGroupMetadata)(result);
23
+ };
24
+ sock.ws.on('CB:notification,w:gp2', async (node) => {
25
+ const { attrs, content } = node;
26
+ if (!Array.isArray(content) || content.length === 0)
27
+ return;
28
+ const inner = content[0];
29
+ const tag = inner.tag;
30
+ const groupId = typeof attrs.from === 'string'
31
+ ? attrs.from
32
+ : attrs.from?.$1?.user
33
+ ? (0, WABinary_1.jidEncode)(attrs.from.$1.user, 'g.us')
34
+ : undefined;
35
+ if (!groupId)
36
+ return;
37
+ if (tag === 'create') {
38
+ try {
39
+ const meta = await aiGroupMetadata(groupId);
40
+ ev.emit('groups.upsert', [meta]);
41
+ }
42
+ catch {
43
+ ev.emit('groups.upsert', [{ id: groupId }]);
44
+ }
45
+ }
46
+ else if (tag === 'promote' || tag === 'demote' || tag === 'remove' || tag === 'add') {
47
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(inner, 'participant')
48
+ .map(p => {
49
+ const jid = p.attrs.jid;
50
+ if (typeof jid === 'string')
51
+ return jid;
52
+ if (jid?.$1) {
53
+ return (0, WABinary_1.jidEncode)(jid.$1.user, jid.$1.server || 's.whatsapp.net');
54
+ }
55
+ return undefined;
56
+ })
57
+ .filter(Boolean);
58
+ ev.emit('group-participants.update', {
59
+ id: groupId,
60
+ participants,
61
+ action: tag
62
+ });
63
+ }
64
+ else if (tag === 'subject') {
65
+ ev.emit('groups.update', [{ id: groupId, subject: inner.attrs?.subject }]);
66
+ }
67
+ await sock.sendMessageAck(node);
68
+ });
69
+ return {
70
+ ...sock,
71
+ aiGroupMetadata,
72
+ aiGroupCreate: async (subject, participants = [], options = {}) => {
73
+ if (!Array.isArray(participants))
74
+ participants = [];
75
+ const key = (0, Utils_1.generateMessageIDV2)();
76
+ const { ephemeralExpiration = 86400, memberAddMode = 'all_member_add', memberShareGroupHistoryMode = 'all_member_share', memberLinkMode = 'all_member_link' } = options;
77
+ const result = await aiGroupQuery('@g.us', 'set', [
78
+ {
79
+ tag: 'create',
80
+ attrs: {
81
+ subject,
82
+ key
83
+ },
84
+ content: participants.map(jid => ({
85
+ tag: 'participant',
86
+ attrs: { jid }
87
+ }))
88
+ }
89
+ ]);
90
+ return (0, exports.extractAIGroupMetadata)(result);
91
+ },
92
+ aiGroupAddBot: async (jid, botUser = '867051314767696') => {
93
+ const result = await aiGroupQuery(jid, 'set', [
94
+ {
95
+ tag: 'add',
96
+ attrs: {},
97
+ content: [
98
+ {
99
+ tag: 'participant',
100
+ attrs: { jid: `${botUser}@bot` }
101
+ }
102
+ ]
103
+ }
104
+ ]);
105
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'add');
106
+ const participantsAffected = (0, WABinary_1.getBinaryNodeChildren)(node, 'participant');
107
+ return participantsAffected.map(p => ({
108
+ status: p.attrs.error || '200',
109
+ jid: p.attrs.jid
110
+ }));
111
+ },
112
+ aiGroupLeave: async (id) => {
113
+ await aiGroupQuery('@g.us', 'set', [
114
+ {
115
+ tag: 'leave',
116
+ attrs: {},
117
+ content: [{ tag: 'group', attrs: { id } }]
118
+ }
119
+ ]);
120
+ },
121
+ aiGroupParticipantsUpdate: async (jid, participants, action) => {
122
+ const result = await aiGroupQuery(jid, 'set', [
123
+ {
124
+ tag: action,
125
+ attrs: {},
126
+ content: participants.map(jid => ({
127
+ tag: 'participant',
128
+ attrs: { jid }
129
+ }))
130
+ }
131
+ ]);
132
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, action);
133
+ const participantsAffected = (0, WABinary_1.getBinaryNodeChildren)(node, 'participant');
134
+ return participantsAffected.map(p => ({
135
+ status: p.attrs.error || '200',
136
+ jid: p.attrs.jid,
137
+ content: p
138
+ }));
139
+ },
140
+ aiGroupUpdateSubject: async (jid, subject) => {
141
+ await aiGroupQuery(jid, 'set', [
142
+ {
143
+ tag: 'subject',
144
+ attrs: {},
145
+ content: Buffer.from(subject, 'utf-8')
146
+ }
147
+ ]);
148
+ },
149
+ aiGroupInviteCode: async (jid) => {
150
+ const result = await aiGroupQuery(jid, 'get', [{ tag: 'invite', attrs: {} }]);
151
+ const inviteNode = (0, WABinary_1.getBinaryNodeChild)(result, 'invite');
152
+ return inviteNode?.attrs.code;
153
+ },
154
+ aiGroupRevokeInvite: async (jid) => {
155
+ const result = await aiGroupQuery(jid, 'set', [{ tag: 'invite', attrs: {} }]);
156
+ const inviteNode = (0, WABinary_1.getBinaryNodeChild)(result, 'invite');
157
+ return inviteNode?.attrs.code;
158
+ },
159
+ aiGroupAcceptInvite: async (code) => {
160
+ const results = await aiGroupQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }]);
161
+ const result = (0, WABinary_1.getBinaryNodeChild)(results, 'group');
162
+ return result?.attrs.jid;
163
+ },
164
+ aiGroupSettingUpdate: async (jid, setting) => {
165
+ await aiGroupQuery(jid, 'set', [{ tag: setting, attrs: {} }]);
166
+ },
167
+ aiGroupToggleEphemeral: async (jid, ephemeralExpiration) => {
168
+ const content = ephemeralExpiration
169
+ ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
170
+ : { tag: 'not_ephemeral', attrs: {} };
171
+ await aiGroupQuery(jid, 'set', [content]);
172
+ }
173
+ };
174
+ };
175
+ exports.makeAIGroupsSocket = makeAIGroupsSocket;
176
+ const extractAIGroupMetadata = result => {
177
+ const createNode = (0, WABinary_1.getBinaryNodeChild)(result, 'create');
178
+ const group = (0, WABinary_1.getBinaryNodeChild)(createNode || result, 'group') ||
179
+ (0, WABinary_1.getBinaryNodeChild)(result, 'group');
180
+ const descChild = (0, WABinary_1.getBinaryNodeChild)(group, 'description');
181
+ let desc, descId, descOwner, descOwnerPn, descTime;
182
+ if (descChild) {
183
+ desc = (0, WABinary_1.getBinaryNodeChildString)(descChild, 'body');
184
+ descOwner = descChild.attrs.participant ? (0, WABinary_1.jidNormalizedUser)(descChild.attrs.participant) : undefined;
185
+ descOwnerPn = descChild.attrs.participant_pn
186
+ ? (0, WABinary_1.jidNormalizedUser)(descChild.attrs.participant_pn)
187
+ : undefined;
188
+ descTime = +descChild.attrs.t;
189
+ descId = descChild.attrs.id;
190
+ }
191
+ const groupId = group.attrs.id.includes('@') ? group.attrs.id : (0, WABinary_1.jidEncode)(group.attrs.id, 'g.us');
192
+ const eph = (0, WABinary_1.getBinaryNodeChild)(group, 'ephemeral')?.attrs.expiration;
193
+ const metadata = {
194
+ id: groupId,
195
+ subject: group.attrs.subject,
196
+ subjectTime: +group.attrs.s_t,
197
+ creation: +group.attrs.creation,
198
+ owner: group.attrs.creator ? (0, WABinary_1.jidNormalizedUser)(group.attrs.creator) : undefined,
199
+ ownerPn: group.attrs.creator_pn ? (0, WABinary_1.jidNormalizedUser)(group.attrs.creator_pn) : undefined,
200
+ owner_country_code: group.attrs.creator_country_code,
201
+ size: group.attrs.size ? +group.attrs.size : (0, WABinary_1.getBinaryNodeChildren)(group, 'participant').length,
202
+ desc,
203
+ descId,
204
+ descOwner,
205
+ descOwnerPn,
206
+ descTime,
207
+ isAIGroup: true,
208
+ addressingMode: group.attrs.addressing_mode === 'lid' ? Types_1.WAMessageAddressingMode.LID : Types_1.WAMessageAddressingMode.PN,
209
+ participants: (0, WABinary_1.getBinaryNodeChildren)(group, 'participant').map(({ attrs }) => ({
210
+ id: attrs.jid,
211
+ phoneNumber: (0, WABinary_1.isLidUser)(attrs.jid) && (0, WABinary_1.isPnUser)(attrs.phone_number)
212
+ ? attrs.phone_number
213
+ : undefined,
214
+ lid: (0, WABinary_1.isPnUser)(attrs.jid) && (0, WABinary_1.isLidUser)(attrs.lid) ? attrs.lid : undefined,
215
+ admin: attrs.type || null
216
+ })),
217
+ ephemeralDuration: eph ? +eph : undefined
218
+ };
219
+ return metadata;
220
+ };
221
+ exports.extractAIGroupMetadata = extractAIGroupMetadata;