@codexverified/baileys 2.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +233 -0
  3. package/WAProto/V +1 -0
  4. package/WAProto/WAProto.proto +8051 -0
  5. package/WAProto/index.js +289292 -0
  6. package/engine-requirements.js +13 -0
  7. package/lib/Defaults/index.js +158 -0
  8. package/lib/Signal/Group/ciphertext-message.js +11 -0
  9. package/lib/Signal/Group/group-session-builder.js +29 -0
  10. package/lib/Signal/Group/group_cipher.js +81 -0
  11. package/lib/Signal/Group/index.js +11 -0
  12. package/lib/Signal/Group/keyhelper.js +17 -0
  13. package/lib/Signal/Group/sender-chain-key.js +25 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  15. package/lib/Signal/Group/sender-key-message.js +65 -0
  16. package/lib/Signal/Group/sender-key-name.js +47 -0
  17. package/lib/Signal/Group/sender-key-record.js +40 -0
  18. package/lib/Signal/Group/sender-key-state.js +83 -0
  19. package/lib/Signal/Group/sender-message-key.js +25 -0
  20. package/lib/Signal/libsignal.js +428 -0
  21. package/lib/Signal/lid-mapping.js +280 -0
  22. package/lib/Socket/Client/index.js +2 -0
  23. package/lib/Socket/Client/types.js +10 -0
  24. package/lib/Socket/Client/websocket.js +53 -0
  25. package/lib/Socket/aigroups.js +315 -0
  26. package/lib/Socket/business.js +407 -0
  27. package/lib/Socket/chats.js +1831 -0
  28. package/lib/Socket/communities.js +431 -0
  29. package/lib/Socket/graphql.js +899 -0
  30. package/lib/Socket/groups.js +549 -0
  31. package/lib/Socket/index.js +79 -0
  32. package/lib/Socket/interactive-handler.js +600 -0
  33. package/lib/Socket/interop.js +563 -0
  34. package/lib/Socket/managed-account.js +208 -0
  35. package/lib/Socket/messages-recv.js +2144 -0
  36. package/lib/Socket/messages-send.js +2030 -0
  37. package/lib/Socket/mex.js +41 -0
  38. package/lib/Socket/newsletter.js +226 -0
  39. package/lib/Socket/privacy.js +446 -0
  40. package/lib/Socket/registration.js +428 -0
  41. package/lib/Socket/socket.js +1017 -0
  42. package/lib/Socket/username.js +229 -0
  43. package/lib/Store/index.js +4 -0
  44. package/lib/Store/make-cache-manager-store.js +89 -0
  45. package/lib/Store/make-in-memory-store.js +420 -0
  46. package/lib/Store/make-ordered-dictionary.js +78 -0
  47. package/lib/Store/object-repository.js +23 -0
  48. package/lib/Types/Auth.js +1 -0
  49. package/lib/Types/Bussines.js +1 -0
  50. package/lib/Types/Call.js +1 -0
  51. package/lib/Types/Chat.js +7 -0
  52. package/lib/Types/Contact.js +1 -0
  53. package/lib/Types/Events.js +1 -0
  54. package/lib/Types/GroupMetadata.js +1 -0
  55. package/lib/Types/Label.js +24 -0
  56. package/lib/Types/LabelAssociation.js +6 -0
  57. package/lib/Types/Message.js +17 -0
  58. package/lib/Types/Mex.js +39 -0
  59. package/lib/Types/Product.js +1 -0
  60. package/lib/Types/RichType.js +22 -0
  61. package/lib/Types/Signal.js +1 -0
  62. package/lib/Types/Socket.js +2 -0
  63. package/lib/Types/State.js +48 -0
  64. package/lib/Types/USync.js +1 -0
  65. package/lib/Types/index.js +25 -0
  66. package/lib/Utils/auth-utils.js +301 -0
  67. package/lib/Utils/bot-planning-replay.js +169 -0
  68. package/lib/Utils/browser-utils.js +28 -0
  69. package/lib/Utils/business.js +230 -0
  70. package/lib/Utils/chat-utils.js +885 -0
  71. package/lib/Utils/companion-reg-client-utils.js +32 -0
  72. package/lib/Utils/consumer-application.js +102 -0
  73. package/lib/Utils/crypto.js +117 -0
  74. package/lib/Utils/decode-wa-message.js +484 -0
  75. package/lib/Utils/event-buffer.js +589 -0
  76. package/lib/Utils/generics.js +388 -0
  77. package/lib/Utils/group-history.js +56 -0
  78. package/lib/Utils/history.js +130 -0
  79. package/lib/Utils/identity-change-handler.js +48 -0
  80. package/lib/Utils/index.js +34 -0
  81. package/lib/Utils/jid-display-normalization.js +209 -0
  82. package/lib/Utils/link-preview.js +84 -0
  83. package/lib/Utils/logger.js +2 -0
  84. package/lib/Utils/lt-hash.js +7 -0
  85. package/lib/Utils/make-mutex.js +32 -0
  86. package/lib/Utils/message-composer.js +467 -0
  87. package/lib/Utils/message-inspect.js +67 -0
  88. package/lib/Utils/message-retry-manager.js +241 -0
  89. package/lib/Utils/messages-media.js +1006 -0
  90. package/lib/Utils/messages.js +1851 -0
  91. package/lib/Utils/meta-ai-msmsg.js +130 -0
  92. package/lib/Utils/meta-compositing.js +194 -0
  93. package/lib/Utils/noise-handler.js +200 -0
  94. package/lib/Utils/offline-node-processor.js +39 -0
  95. package/lib/Utils/pre-key-manager.js +105 -0
  96. package/lib/Utils/process-message.js +527 -0
  97. package/lib/Utils/reporting-utils.js +257 -0
  98. package/lib/Utils/rich-message-utils.js +439 -0
  99. package/lib/Utils/signal.js +200 -0
  100. package/lib/Utils/stanza-ack.js +37 -0
  101. package/lib/Utils/sync-action-utils.js +47 -0
  102. package/lib/Utils/tc-token-utils.js +162 -0
  103. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  104. package/lib/Utils/use-single-file-auth-state.js +96 -0
  105. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  106. package/lib/Utils/validate-connection.js +206 -0
  107. package/lib/Utils/voip-rekey.js +20 -0
  108. package/lib/Utils/welcome-flow.js +217 -0
  109. package/lib/WABinary/constants.js +1463 -0
  110. package/lib/WABinary/decode.js +261 -0
  111. package/lib/WABinary/encode.js +219 -0
  112. package/lib/WABinary/generic-utils.js +227 -0
  113. package/lib/WABinary/index.js +5 -0
  114. package/lib/WABinary/jid-utils.js +95 -0
  115. package/lib/WABinary/types.js +1 -0
  116. package/lib/WAM/BinaryInfo.js +9 -0
  117. package/lib/WAM/constants.js +22852 -0
  118. package/lib/WAM/encode.js +149 -0
  119. package/lib/WAM/index.js +3 -0
  120. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  121. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  122. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  123. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  124. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  125. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  126. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  127. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  128. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  129. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  130. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  131. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  132. package/lib/WAUSync/Protocols/index.js +12 -0
  133. package/lib/WAUSync/USyncQuery.js +201 -0
  134. package/lib/WAUSync/USyncUser.js +54 -0
  135. package/lib/WAUSync/index.js +3 -0
  136. package/lib/antiban.cjs +4726 -0
  137. package/lib/index.d.ts +286 -0
  138. package/lib/index.js +18 -0
  139. package/package.json +121 -0
@@ -0,0 +1,280 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, WAJIDDomains } from '../WABinary/index.js';
3
+ export class LIDMappingStore {
4
+ constructor(keys, logger, pnToLIDFunc) {
5
+ this.mappingCache = new LRUCache({
6
+ ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
7
+ ttlAutopurge: true,
8
+ updateAgeOnGet: true
9
+ });
10
+ this.inflightLIDLookups = new Map();
11
+ this.inflightPNLookups = new Map();
12
+ this.keys = keys;
13
+ this.pnToLIDFunc = pnToLIDFunc;
14
+ this.logger = logger;
15
+ }
16
+ async storeLIDPNMappings(pairs) {
17
+ if (pairs.length === 0)
18
+ return;
19
+ const validatedPairs = [];
20
+ for (const { lid, pn } of pairs) {
21
+ if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
22
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
23
+ continue;
24
+ }
25
+ const lidDecoded = jidDecode(lid);
26
+ const pnDecoded = jidDecode(pn);
27
+ if (!lidDecoded || !pnDecoded)
28
+ continue;
29
+ validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user });
30
+ }
31
+ if (validatedPairs.length === 0)
32
+ return;
33
+ const cacheMissSet = new Set();
34
+ const existingMappings = new Map();
35
+ for (const { pnUser } of validatedPairs) {
36
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
37
+ if (cached) {
38
+ existingMappings.set(pnUser, cached);
39
+ }
40
+ else {
41
+ cacheMissSet.add(pnUser);
42
+ }
43
+ }
44
+ if (cacheMissSet.size > 0) {
45
+ const cacheMisses = [...cacheMissSet];
46
+ this.logger.trace(`Batch fetching ${cacheMisses.length} LID mappings from database`);
47
+ const stored = await this.keys.get('lid-mapping', cacheMisses);
48
+ for (const pnUser of cacheMisses) {
49
+ const existingLidUser = stored[pnUser];
50
+ if (existingLidUser) {
51
+ existingMappings.set(pnUser, existingLidUser);
52
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
53
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
54
+ }
55
+ }
56
+ }
57
+ const pairMap = {};
58
+ for (const { pnUser, lidUser } of validatedPairs) {
59
+ const existingLidUser = existingMappings.get(pnUser);
60
+ if (existingLidUser === lidUser) {
61
+ this.logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping');
62
+ continue;
63
+ }
64
+ pairMap[pnUser] = lidUser;
65
+ }
66
+ if (Object.keys(pairMap).length === 0)
67
+ return;
68
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
69
+ const batchData = {};
70
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
71
+ batchData[pnUser] = lidUser;
72
+ batchData[`${lidUser}_reverse`] = pnUser;
73
+ }
74
+ await this.keys.transaction(async () => {
75
+ await this.keys.set({ 'lid-mapping': batchData });
76
+ }, 'lid-mapping');
77
+ // Update cache after successful DB write
78
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
79
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
80
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
81
+ }
82
+ }
83
+ async getLIDForPN(pn) {
84
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
85
+ }
86
+ async getLIDsForPNs(pns) {
87
+ if (pns.length === 0)
88
+ return null;
89
+ const sortedPns = [...new Set(pns)].sort();
90
+ const cacheKey = sortedPns.join(',');
91
+ const inflight = this.inflightLIDLookups.get(cacheKey);
92
+ if (inflight) {
93
+ this.logger.trace(`Coalescing getLIDsForPNs request for ${sortedPns.length} PNs`);
94
+ return inflight;
95
+ }
96
+ const promise = this._getLIDsForPNsImpl(pns);
97
+ this.inflightLIDLookups.set(cacheKey, promise);
98
+ try {
99
+ return await promise;
100
+ }
101
+ finally {
102
+ this.inflightLIDLookups.delete(cacheKey);
103
+ }
104
+ }
105
+ async _getLIDsForPNsImpl(pns) {
106
+ const usyncFetch = {};
107
+ const successfulPairs = {};
108
+ const pending = [];
109
+ const addResolvedPair = (pn, decoded, lidUser) => {
110
+ const normalizedLidUser = lidUser.toString();
111
+ if (!normalizedLidUser) {
112
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
113
+ return false;
114
+ }
115
+ // Push the PN device ID to the LID to maintain device separation
116
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0;
117
+ const deviceSpecificLid = `${normalizedLidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`;
118
+ this.logger.trace(`getLIDForPN: ${pn} ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
119
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn };
120
+ return true;
121
+ };
122
+ for (const pn of pns) {
123
+ if (!isPnUser(pn) && !isHostedPnUser(pn))
124
+ continue;
125
+ const decoded = jidDecode(pn);
126
+ if (!decoded)
127
+ continue;
128
+ const pnUser = decoded.user;
129
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
130
+ if (cached && typeof cached === 'string') {
131
+ if (!addResolvedPair(pn, decoded, cached)) {
132
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
133
+ continue;
134
+ }
135
+ continue;
136
+ }
137
+ pending.push({ pn, pnUser, decoded });
138
+ }
139
+ if (pending.length) {
140
+ const pnUsers = [...new Set(pending.map(item => item.pnUser))];
141
+ const stored = await this.keys.get('lid-mapping', pnUsers);
142
+ for (const pnUser of pnUsers) {
143
+ const lidUser = stored[pnUser];
144
+ if (lidUser && typeof lidUser === 'string') {
145
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
146
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
147
+ }
148
+ }
149
+ for (const { pn, pnUser, decoded } of pending) {
150
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
151
+ if (cached && typeof cached === 'string') {
152
+ if (!addResolvedPair(pn, decoded, cached)) {
153
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
154
+ continue;
155
+ }
156
+ }
157
+ else {
158
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`);
159
+ const device = decoded.device || 0;
160
+ let normalizedPn = jidNormalizedUser(pn);
161
+ if (isHostedPnUser(normalizedPn)) {
162
+ normalizedPn = `${pnUser}@s.whatsapp.net`;
163
+ }
164
+ if (!usyncFetch[normalizedPn]) {
165
+ usyncFetch[normalizedPn] = [device];
166
+ }
167
+ else {
168
+ usyncFetch[normalizedPn]?.push(device);
169
+ }
170
+ }
171
+ }
172
+ }
173
+ if (Object.keys(usyncFetch).length > 0) {
174
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch)); // this function already adds LIDs to mapping
175
+ if (result && result.length > 0) {
176
+ await this.storeLIDPNMappings(result);
177
+ for (const pair of result) {
178
+ const pnDecoded = jidDecode(pair.pn);
179
+ const pnUser = pnDecoded?.user;
180
+ if (!pnUser)
181
+ continue;
182
+ const lidUser = jidDecode(pair.lid)?.user;
183
+ if (!lidUser)
184
+ continue;
185
+ for (const device of usyncFetch[pair.pn]) {
186
+ const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted.lid' : 'lid'}`;
187
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} ${deviceSpecificLid} (user mapping with device ${device})`);
188
+ const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`;
189
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
190
+ }
191
+ }
192
+ }
193
+ else {
194
+ this.logger.warn('USync fetch yielded no results for pending PNs');
195
+ }
196
+ }
197
+ return Object.values(successfulPairs).length > 0 ? Object.values(successfulPairs) : null;
198
+ }
199
+ async getPNForLID(lid) {
200
+ return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null;
201
+ }
202
+ async getPNsForLIDs(lids) {
203
+ if (lids.length === 0)
204
+ return null;
205
+ const sortedLids = [...new Set(lids)].sort();
206
+ const cacheKey = sortedLids.join(',');
207
+ const inflight = this.inflightPNLookups.get(cacheKey);
208
+ if (inflight) {
209
+ this.logger.trace(`Coalescing getPNsForLIDs request for ${sortedLids.length} LIDs`);
210
+ return inflight;
211
+ }
212
+ const promise = this._getPNsForLIDsImpl(lids);
213
+ this.inflightPNLookups.set(cacheKey, promise);
214
+ try {
215
+ return await promise;
216
+ }
217
+ finally {
218
+ this.inflightPNLookups.delete(cacheKey);
219
+ }
220
+ }
221
+ async _getPNsForLIDsImpl(lids) {
222
+ const successfulPairs = {};
223
+ const pending = [];
224
+ const addResolvedPair = (lid, decoded, pnUser) => {
225
+ if (!pnUser || typeof pnUser !== 'string') {
226
+ return false;
227
+ }
228
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0;
229
+ const deviceSuffix = lidDevice ? `:${lidDevice}` : '';
230
+ const pnServer = decoded.domainType === WAJIDDomains.HOSTED_LID || decoded.server === 'hosted.lid'
231
+ ? 'hosted'
232
+ : 's.whatsapp.net';
233
+ const pnJid = `${pnUser}${deviceSuffix}@${pnServer}`;
234
+ this.logger.trace(`Found reverse mapping: ${lid} ${pnJid}`);
235
+ successfulPairs[lid] = { lid, pn: pnJid };
236
+ return true;
237
+ };
238
+ for (const lid of lids) {
239
+ if (!isLidUser(lid) && !isHostedLidUser(lid))
240
+ continue;
241
+ const decoded = jidDecode(lid);
242
+ if (!decoded)
243
+ continue;
244
+ const lidUser = decoded.user;
245
+ const cached = this.mappingCache.get(`lid:${lidUser}`);
246
+ if (cached && typeof cached === 'string') {
247
+ addResolvedPair(lid, decoded, cached);
248
+ continue;
249
+ }
250
+ pending.push({ lid, lidUser, decoded });
251
+ }
252
+ if (pending.length) {
253
+ const reverseKeys = [...new Set(pending.map(item => `${item.lidUser}_reverse`))];
254
+ const stored = await this.keys.get('lid-mapping', reverseKeys);
255
+ for (const { lid, lidUser, decoded } of pending) {
256
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`);
257
+ if (!pnUser || typeof pnUser !== 'string') {
258
+ pnUser = stored[`${lidUser}_reverse`];
259
+ if (pnUser && typeof pnUser === 'string') {
260
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
261
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
262
+ }
263
+ }
264
+ if (pnUser && typeof pnUser === 'string') {
265
+ addResolvedPair(lid, decoded, pnUser);
266
+ }
267
+ else {
268
+ this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
269
+ }
270
+ }
271
+ }
272
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null;
273
+ }
274
+ /**
275
+ * Close the cache and release resources
276
+ */
277
+ close() {
278
+ this.mappingCache.clear();
279
+ }
280
+ }
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export * from './websocket.js';
@@ -0,0 +1,10 @@
1
+ import { EventEmitter } from 'events';
2
+ import { URL } from 'url';
3
+ export class AbstractSocketClient extends EventEmitter {
4
+ constructor(url, config) {
5
+ super();
6
+ this.url = url;
7
+ this.config = config;
8
+ this.setMaxListeners(0);
9
+ }
10
+ }
@@ -0,0 +1,53 @@
1
+ import WebSocket from 'ws';
2
+ import { DEFAULT_ORIGIN } from '../../Defaults/index.js';
3
+ import { AbstractSocketClient } from './types.js';
4
+ export class WebSocketClient extends AbstractSocketClient {
5
+ constructor() {
6
+ super(...arguments);
7
+ this.socket = null;
8
+ }
9
+ get isOpen() {
10
+ return this.socket?.readyState === WebSocket.OPEN;
11
+ }
12
+ get isClosed() {
13
+ return this.socket === null || this.socket?.readyState === WebSocket.CLOSED;
14
+ }
15
+ get isClosing() {
16
+ return this.socket === null || this.socket?.readyState === WebSocket.CLOSING;
17
+ }
18
+ get isConnecting() {
19
+ return this.socket?.readyState === WebSocket.CONNECTING;
20
+ }
21
+ connect() {
22
+ if (this.socket) {
23
+ return;
24
+ }
25
+ this.socket = new WebSocket(this.url, {
26
+ origin: DEFAULT_ORIGIN,
27
+ headers: this.config.options?.headers,
28
+ handshakeTimeout: this.config.connectTimeoutMs,
29
+ timeout: this.config.connectTimeoutMs,
30
+ agent: this.config.agent
31
+ });
32
+ this.socket.setMaxListeners(0);
33
+ const events = ['close', 'error', 'upgrade', 'message', 'open', 'ping', 'pong', 'unexpected-response'];
34
+ for (const event of events) {
35
+ this.socket?.on(event, (...args) => this.emit(event, ...args));
36
+ }
37
+ }
38
+ async close() {
39
+ if (!this.socket) {
40
+ return;
41
+ }
42
+ const closePromise = new Promise(resolve => {
43
+ this.socket?.once('close', resolve);
44
+ });
45
+ this.socket.close();
46
+ await closePromise;
47
+ this.socket = null;
48
+ }
49
+ send(str, cb) {
50
+ this.socket?.send(str, cb);
51
+ return Boolean(this.socket);
52
+ }
53
+ }
@@ -0,0 +1,315 @@
1
+ import { WAMessageAddressingMode } from '../Types/index.js';
2
+ import { generateMessageIDV2, normalizeMessageContent } from '../Utils/index.js';
3
+ import { getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidEncode, jidNormalizedUser } from '../WABinary/index.js';
4
+ import { makeGroupsSocket } from './groups.js';
5
+
6
+ /** Default Meta AI bot JID used inside AI groups. */
7
+ export const META_AI_BOT_JID = '867051314767696@bot';
8
+
9
+ // `@bot` JIDs carry their device as a trailing suffix (`bot:1`), which
10
+ // jidNormalizedUser does not strip normalize it before comparing.
11
+ const stripDeviceSuffix = (jid) => String(jid || '').replace(/:\d+$/, '');
12
+ const sameBotJid = (a, b) => {
13
+ if (!a || !b) {
14
+ return false;
15
+ }
16
+ return jidNormalizedUser(stripDeviceSuffix(a)) === jidNormalizedUser(stripDeviceSuffix(b));
17
+ };
18
+
19
+ // Pull the reply stanzaId out of a message: normalizeMessageContent returns the
20
+ // type-keyed wrapper (`{ extendedTextMessage: { ... } }`), so unwrap one level.
21
+ const extractReplyStanzaId = (message) => {
22
+ const content = message ? normalizeMessageContent(message) : undefined;
23
+ const inner = content && typeof content === 'object'
24
+ ? content[Object.keys(content)[0]]
25
+ : undefined;
26
+ return inner?.contextInfo?.stanzaId || content?.contextInfo?.stanzaId || message?.messageContextInfo?.stanzaId;
27
+ };
28
+
29
+ /**
30
+ * Pure matcher: is `message` a Meta AI bot response in `chatJid`?
31
+ *
32
+ * A message is treated as a bot response when ALL of these hold:
33
+ * 1. it is not from me, and its remoteJid is the chat we prompted in;
34
+ * 2. the sender is a known bot JID (`@bot` suffix or one of `botJids`); OR
35
+ * its reply context (`contextInfo.stanzaId`) references the prompt we sent.
36
+ *
37
+ * The `botJids` fallback lets callers pass the bot's LID participant JID
38
+ * (resolved from group metadata) so LID-addressed AI groups match too.
39
+ */
40
+ export const isMetaAIBotResponse = (message, chatJid, promptId, botJids = []) => {
41
+ if (!message || !message.key || message.key.fromMe) {
42
+ return false;
43
+ }
44
+ if (message.key.remoteJid !== chatJid) {
45
+ return false;
46
+ }
47
+ const sender = stripDeviceSuffix(message.key.participant || message.key.remoteJid);
48
+ if (isJidMetaAI(sender)) {
49
+ return true;
50
+ }
51
+ for (const botJid of botJids) {
52
+ if (sameBotJid(botJid, sender)) {
53
+ return true;
54
+ }
55
+ }
56
+ if (promptId && extractReplyStanzaId(message.message) === promptId) {
57
+ return true;
58
+ }
59
+ return false;
60
+ };
61
+
62
+ // Resolve the bot's real participant JID(s) inside an AI group so the response
63
+ // matcher can recognize LID-addressed bot messages. Falls back to the canonical
64
+ // `@bot` JID when metadata is unavailable.
65
+ export const collectMetaAIBotParticipantJids = async (sock, jid, botUser) => {
66
+ const candidates = new Set([botUser]);
67
+ if (!isJidGroup(jid)) {
68
+ return candidates;
69
+ }
70
+ const botNumber = jidNormalizedUser(botUser).split('@')[0];
71
+ try {
72
+ const meta = await sock.groupMetadata(jid);
73
+ for (const participant of meta.participants || []) {
74
+ const pn = participant.phoneNumber
75
+ ? jidNormalizedUser(participant.phoneNumber).split('@')[0]
76
+ : undefined;
77
+ const idNumber = jidNormalizedUser(participant.id).split('@')[0];
78
+ if (pn === botNumber || idNumber === botNumber || isJidMetaAI(participant.id)) {
79
+ candidates.add(participant.id);
80
+ }
81
+ }
82
+ }
83
+ catch {
84
+ // metadata unavailable the canonical @bot JID is already in the set
85
+ }
86
+ return candidates;
87
+ };
88
+
89
+ export const makeAIGroupsSocket = (config) => {
90
+ const sock = makeGroupsSocket(config);
91
+ const { ev, query } = sock;
92
+
93
+ /** Query helper for AI groups (w:gp2 namespace) */
94
+ const aiGroupQuery = async (jid, type, content) => query({
95
+ tag: 'iq',
96
+ attrs: {
97
+ type,
98
+ xmlns: 'w:g2',
99
+ to: jid
100
+ },
101
+ content
102
+ });
103
+
104
+ const aiGroupMetadata = async (jid) => {
105
+ const result = await aiGroupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
106
+ return extractAIGroupMetadata(result);
107
+ };
108
+
109
+ // Handle incoming w:gp2 notifications (create, promote, remove, add)
110
+ sock.ws.on('CB:notification,w:gp2', async (node) => {
111
+ const { attrs, content } = node;
112
+ if (!Array.isArray(content) || content.length === 0) return;
113
+
114
+ const inner = content[0];
115
+ const tag = inner.tag;
116
+ const groupId = typeof attrs.from === 'string'
117
+ ? attrs.from
118
+ : attrs.from?.$1?.user
119
+ ? jidEncode(attrs.from.$1.user, 'g.us')
120
+ : undefined;
121
+
122
+ if (!groupId) return;
123
+
124
+ if (tag === 'create') {
125
+ // New AI group created emit groups.upsert
126
+ try {
127
+ const meta = await aiGroupMetadata(groupId);
128
+ ev.emit('groups.upsert', [meta]);
129
+ }
130
+ catch {
131
+ // metadata fetch may fail; emit minimal info
132
+ ev.emit('groups.upsert', [{ id: groupId }]);
133
+ }
134
+ }
135
+ else if (tag === 'promote' || tag === 'demote' || tag === 'remove' || tag === 'add') {
136
+ const participants = getBinaryNodeChildren(inner, 'participant')
137
+ .map(p => {
138
+ const jid = p.attrs.jid;
139
+ if (typeof jid === 'string') return jid;
140
+ if (jid?.$1) {
141
+ return jidEncode(jid.$1.user, jid.$1.server || 's.whatsapp.net');
142
+ }
143
+ return undefined;
144
+ })
145
+ .filter(Boolean);
146
+
147
+ ev.emit('group-participants.update', {
148
+ id: groupId,
149
+ participants,
150
+ action: tag
151
+ });
152
+ }
153
+ else if (tag === 'subject') {
154
+ ev.emit('groups.update', [{ id: groupId, subject: inner.attrs?.subject }]);
155
+ }
156
+
157
+ await sock.sendMessageAck(node);
158
+ });
159
+
160
+ return {
161
+ ...sock,
162
+ aiGroupMetadata,
163
+ aiGroupCreate: async (subject, participants = [], options = {}) => {
164
+ if (!Array.isArray(participants)) participants = [];
165
+ const key = generateMessageIDV2();
166
+ const {
167
+ ephemeralExpiration = 86400,
168
+ memberAddMode = 'all_member_add',
169
+ memberShareGroupHistoryMode = 'all_member_share',
170
+ memberLinkMode = 'all_member_link'
171
+ } = options;
172
+ const result = await aiGroupQuery('@g.us', 'set', [
173
+ {
174
+ tag: 'create',
175
+ attrs: {
176
+ subject,
177
+ key
178
+ },
179
+ content: participants.map(jid => ({
180
+ tag: 'participant',
181
+ attrs: { jid }
182
+ }))
183
+ }
184
+ ]);
185
+ return extractAIGroupMetadata(result);
186
+ },
187
+ aiGroupAddBot: async (jid, botUser = '867051314767696') => {
188
+ const result = await aiGroupQuery(jid, 'set', [
189
+ {
190
+ tag: 'add',
191
+ attrs: {},
192
+ content: [
193
+ {
194
+ tag: 'participant',
195
+ attrs: { jid: `${botUser}@bot` }
196
+ }
197
+ ]
198
+ }
199
+ ]);
200
+ const node = getBinaryNodeChild(result, 'add');
201
+ const participantsAffected = getBinaryNodeChildren(node, 'participant');
202
+ return participantsAffected.map(p => ({
203
+ status: p.attrs.error || '200',
204
+ jid: p.attrs.jid
205
+ }));
206
+ },
207
+ aiGroupLeave: async (id) => {
208
+ await aiGroupQuery('@g.us', 'set', [
209
+ {
210
+ tag: 'leave',
211
+ attrs: {},
212
+ content: [{ tag: 'group', attrs: { id } }]
213
+ }
214
+ ]);
215
+ },
216
+ aiGroupParticipantsUpdate: async (jid, participants, action) => {
217
+ const result = await aiGroupQuery(jid, 'set', [
218
+ {
219
+ tag: action,
220
+ attrs: {},
221
+ content: participants.map(jid => ({
222
+ tag: 'participant',
223
+ attrs: { jid }
224
+ }))
225
+ }
226
+ ]);
227
+ const node = getBinaryNodeChild(result, action);
228
+ const participantsAffected = getBinaryNodeChildren(node, 'participant');
229
+ return participantsAffected.map(p => ({
230
+ status: p.attrs.error || '200',
231
+ jid: p.attrs.jid,
232
+ content: p
233
+ }));
234
+ },
235
+ aiGroupUpdateSubject: async (jid, subject) => {
236
+ await aiGroupQuery(jid, 'set', [
237
+ {
238
+ tag: 'subject',
239
+ attrs: {},
240
+ content: Buffer.from(subject, 'utf-8')
241
+ }
242
+ ]);
243
+ },
244
+ aiGroupInviteCode: async (jid) => {
245
+ const result = await aiGroupQuery(jid, 'get', [{ tag: 'invite', attrs: {} }]);
246
+ const inviteNode = getBinaryNodeChild(result, 'invite');
247
+ return inviteNode?.attrs.code;
248
+ },
249
+ aiGroupRevokeInvite: async (jid) => {
250
+ const result = await aiGroupQuery(jid, 'set', [{ tag: 'invite', attrs: {} }]);
251
+ const inviteNode = getBinaryNodeChild(result, 'invite');
252
+ return inviteNode?.attrs.code;
253
+ },
254
+ aiGroupAcceptInvite: async (code) => {
255
+ const results = await aiGroupQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }]);
256
+ const result = getBinaryNodeChild(results, 'group');
257
+ return result?.attrs.jid;
258
+ },
259
+ aiGroupSettingUpdate: async (jid, setting) => {
260
+ await aiGroupQuery(jid, 'set', [{ tag: setting, attrs: {} }]);
261
+ },
262
+ aiGroupToggleEphemeral: async (jid, ephemeralExpiration) => {
263
+ const content = ephemeralExpiration
264
+ ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
265
+ : { tag: 'not_ephemeral', attrs: {} };
266
+ await aiGroupQuery(jid, 'set', [content]);
267
+ }
268
+ };
269
+ };
270
+
271
+ export const extractAIGroupMetadata = (result) => {
272
+ // IQ response nests group inside create node: result create group
273
+ const createNode = getBinaryNodeChild(result, 'create');
274
+ const group =
275
+ getBinaryNodeChild(createNode || result, 'group') ||
276
+ getBinaryNodeChild(result, 'group');
277
+ const descChild = getBinaryNodeChild(group, 'description');
278
+ let desc, descId, descOwner, descOwnerPn, descTime;
279
+ if (descChild) {
280
+ desc = getBinaryNodeChildString(descChild, 'body');
281
+ descOwner = descChild.attrs.participant ? jidNormalizedUser(descChild.attrs.participant) : undefined;
282
+ descOwnerPn = descChild.attrs.participant_pn
283
+ ? jidNormalizedUser(descChild.attrs.participant_pn)
284
+ : undefined;
285
+ descTime = +descChild.attrs.t;
286
+ descId = descChild.attrs.id;
287
+ }
288
+ const groupId = group.attrs.id.includes('@') ? group.attrs.id : jidEncode(group.attrs.id, 'g.us');
289
+ const eph = getBinaryNodeChild(group, 'ephemeral')?.attrs.expiration;
290
+ const metadata = {
291
+ id: groupId,
292
+ subject: group.attrs.subject,
293
+ subjectTime: +group.attrs.s_t,
294
+ creation: +group.attrs.creation,
295
+ owner: group.attrs.creator ? jidNormalizedUser(group.attrs.creator) : undefined,
296
+ ownerPn: group.attrs.creator_pn ? jidNormalizedUser(group.attrs.creator_pn) : undefined,
297
+ owner_country_code: group.attrs.creator_country_code,
298
+ size: group.attrs.size ? +group.attrs.size : getBinaryNodeChildren(group, 'participant').length,
299
+ desc,
300
+ descId,
301
+ descOwner,
302
+ descOwnerPn,
303
+ descTime,
304
+ isAIGroup: true,
305
+ addressingMode: group.attrs.addressing_mode === 'lid' ? WAMessageAddressingMode.LID : WAMessageAddressingMode.PN,
306
+ participants: getBinaryNodeChildren(group, 'participant').map(({ attrs }) => ({
307
+ id: attrs.jid,
308
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
309
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
310
+ admin: attrs.type || null
311
+ })),
312
+ ephemeralDuration: eph ? +eph : undefined
313
+ };
314
+ return metadata;
315
+ };