@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,563 @@
1
+ import { getBinaryNodeChild, getBinaryNodeChildren, S_WHATSAPP_NET } from '../WABinary/index.js';
2
+ import { executeWMexQuery } from './mex.js';
3
+
4
+ /**
5
+ * w:mex query IDs for interop group and privacy operations.
6
+ *
7
+ * Source: whatsapp-android-mex_client_persist_ids.json (WA 2.26.26.4 APK assets)
8
+ */
9
+ const INTEROP_MEX_QUERY_IDS = {
10
+ CREATE_GROUP: '25726817620301611', // GroupsCreateInteropGroup
11
+ LEAVE_GROUP: '25346167795013271', // LeaveInteropGroup
12
+ ADD_PARTICIPANTS: '25732168276369451', // AddParticipantsToInteropGroup
13
+ QUERY_GROUP_INFO: '32734144032867938', // QueryInteropGroupInfo
14
+ PRIVACY_SETTINGS_QUERY: '24849123668112654', // InteropPrivacySettingsQuery
15
+ PRIVACY_SETTINGS_UPDATE: '25421856497452763', // InteropPrivacySettingsUpdate
16
+ PRIVACY_SETTINGS_WITH_CONTACT_LIST: '24913399124998598' // InteropPrivacySettingWithContactListUpdate
17
+ };
18
+
19
+ /**
20
+ * Known integrator IDs (assigned by WhatsApp).
21
+ * BirdyChat identifier_type="email"
22
+ * Haiket identifier_type="pn"
23
+ */
24
+ const INTEGRATOR_BIRDYCHAT = 12;
25
+ const INTEGRATOR_HAIKET = 13;
26
+
27
+ /**
28
+ * TOS trackable results sent by WA on first interop opt-in.
29
+ * 105 = TOS shown, 160 = TOS accepted.
30
+ */
31
+ const TOS_TRACKABLE_ID = '20240306';
32
+ const TOS_RESULT_SHOWN = '105';
33
+ const TOS_RESULT_ACCEPTED = '160';
34
+
35
+ /** Maximum users per batch lookup (enforced server-side too). */
36
+ const INTEROP_BATCH_MAX = 256;
37
+
38
+ export const makeInteropSocket = (sock) => {
39
+ const { query, generateMessageTag, logger, signalRepository } = sock;
40
+
41
+ const mexQuery = (variables, queryId, dataPath) =>
42
+ executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag);
43
+
44
+ /**
45
+ * Fetch all available interop integrators from the server.
46
+ * Each integrator carries: id, name, status, icon, identifierType,
47
+ * optedIn, features.groupMessaging.
48
+ * status can be "active" | "onboarding" | "removed".
49
+ */
50
+ const fetchIntegrators = async () => {
51
+ const result = await query({
52
+ tag: 'iq',
53
+ attrs: {
54
+ type: 'get',
55
+ xmlns: 'w:interop',
56
+ to: S_WHATSAPP_NET
57
+ },
58
+ content: [{ tag: 'integrator', attrs: { fetch: 'all' } }]
59
+ });
60
+ const listNode = getBinaryNodeChild(result, 'integrator_list');
61
+ if (!listNode) return [];
62
+ const globalOptedIn = listNode.attrs?.opted_in === 'true';
63
+ return getBinaryNodeChildren(listNode, 'integrator').map(node => {
64
+ const featuresNode = getBinaryNodeChild(node, 'features');
65
+ return {
66
+ id: parseInt(node.attrs.id, 10),
67
+ name: node.attrs.name,
68
+ // "active" | "onboarding" | "removed"
69
+ status: node.attrs.status,
70
+ icon: node.attrs.icon,
71
+ // "email" | "pn" | "username"
72
+ identifierType: node.attrs.identifier_type,
73
+ // Whether we are already opted-in to this integrator
74
+ optedIn: node.attrs.opted_in === 'true' || globalOptedIn,
75
+ features: {
76
+ groupMessaging: featuresNode?.attrs?.group_messaging === 'true'
77
+ }
78
+ };
79
+ });
80
+ };
81
+
82
+ /** Send a single TOS trackable item (shown or accepted). */
83
+ const sendTOSTrackable = async (id, result) => {
84
+ await query({
85
+ tag: 'iq',
86
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'tos' },
87
+ content: [{ tag: 'trackable', attrs: { id, result } }]
88
+ });
89
+ };
90
+
91
+ /**
92
+ * Accept TOS for interop.
93
+ * Sends two trackable items: shown (105) then accepted (160).
94
+ * Must be called before opting in.
95
+ */
96
+ const acceptInteropTOS = async () => {
97
+ await sendTOSTrackable(TOS_TRACKABLE_ID, TOS_RESULT_SHOWN);
98
+ await sendTOSTrackable(TOS_TRACKABLE_ID, TOS_RESULT_ACCEPTED);
99
+ };
100
+
101
+ /**
102
+ * Opt in to a list of integrators (by numeric ID).
103
+ * Defaults to both known integrators (BirdyChat + Haiket).
104
+ */
105
+ const optInIntegrators = async (integratorIds = [INTEGRATOR_BIRDYCHAT, INTEGRATOR_HAIKET]) => {
106
+ await query({
107
+ tag: 'iq',
108
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
109
+ content: [
110
+ {
111
+ tag: 'opt_in_integrators',
112
+ attrs: {},
113
+ content: [
114
+ {
115
+ tag: 'integrator_list',
116
+ attrs: {},
117
+ content: integratorIds.map(id => ({
118
+ tag: 'integrator',
119
+ attrs: { id: id.toString() }
120
+ }))
121
+ }
122
+ ]
123
+ }
124
+ ]
125
+ });
126
+ };
127
+
128
+ /**
129
+ * Opt out of a list of integrators (by numeric ID).
130
+ * Mirror of optInIntegrators uses <opt_out_integrators>.
131
+ */
132
+ const optOutIntegrators = async (integratorIds = [INTEGRATOR_BIRDYCHAT, INTEGRATOR_HAIKET]) => {
133
+ await query({
134
+ tag: 'iq',
135
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
136
+ content: [
137
+ {
138
+ tag: 'opt_out_integrators',
139
+ attrs: {},
140
+ content: [
141
+ {
142
+ tag: 'integrator_list',
143
+ attrs: {},
144
+ content: integratorIds.map(id => ({
145
+ tag: 'integrator',
146
+ attrs: { id: id.toString() }
147
+ }))
148
+ }
149
+ ]
150
+ }
151
+ ]
152
+ });
153
+ };
154
+
155
+ /**
156
+ * Resolve one or more interop users by external ID in a single IQ.
157
+ * Each entry: { externalId, integratorId }
158
+ * - BirdyChat (12): externalId = email address
159
+ * - Haiket (13): externalId = phone number string (e.g. "19146088152")
160
+ *
161
+ * Max 256 entries per call (server limit).
162
+ *
163
+ * Returns an array of results:
164
+ * { jid, externalId, normalizedExternalId, integratorId } on success
165
+ * { externalId, integratorId, error: { code, text } } on failure
166
+ */
167
+ const resolveInteropUsers = async (users) => {
168
+ if (!users || users.length === 0) return [];
169
+ if (users.length > INTEROP_BATCH_MAX) {
170
+ throw new Error(`resolveInteropUsers: max ${INTEROP_BATCH_MAX} users per request`);
171
+ }
172
+ const result = await query({
173
+ tag: 'iq',
174
+ attrs: { type: 'get', xmlns: 'w:interop', to: S_WHATSAPP_NET },
175
+ content: [
176
+ {
177
+ tag: 'users',
178
+ attrs: {},
179
+ content: users.map(({ externalId, integratorId }) => ({
180
+ tag: 'user',
181
+ attrs: {
182
+ external_id: externalId,
183
+ integrator_id: integratorId.toString()
184
+ }
185
+ }))
186
+ }
187
+ ]
188
+ });
189
+ const usersNode = getBinaryNodeChild(result, 'users');
190
+ if (!usersNode) return [];
191
+ return getBinaryNodeChildren(usersNode, 'user').map(userNode => {
192
+ const errorNode = getBinaryNodeChild(userNode, 'error');
193
+ if (errorNode) {
194
+ return {
195
+ externalId: userNode.attrs.external_id,
196
+ integratorId: parseInt(userNode.attrs.integrator_id, 10),
197
+ error: {
198
+ code: parseInt(errorNode.attrs.code, 10),
199
+ text: errorNode.attrs.text
200
+ }
201
+ };
202
+ }
203
+ return {
204
+ jid: userNode.attrs.jid,
205
+ externalId: userNode.attrs.external_id,
206
+ normalizedExternalId: userNode.attrs.normalized_external_id,
207
+ integratorId: parseInt(userNode.attrs.integrator_id, 10)
208
+ };
209
+ });
210
+ };
211
+
212
+ /**
213
+ * Convenience wrapper: resolve a single interop user.
214
+ * Returns the result object or null.
215
+ */
216
+ const resolveInteropUser = async (externalId, integratorId) => {
217
+ const results = await resolveInteropUsers([{ externalId, integratorId }]);
218
+ return results[0] ?? null;
219
+ };
220
+
221
+ /**
222
+ * Get reachability settings for interop contacts.
223
+ * Returns the raw <reachability_settings> node content.
224
+ * WA uses this as the interop presence/subscription mechanism.
225
+ */
226
+ const getReachabilitySettings = async () => {
227
+ const result = await query({
228
+ tag: 'iq',
229
+ attrs: { type: 'get', xmlns: 'w:interop', to: S_WHATSAPP_NET },
230
+ content: [{ tag: 'reachability_settings', attrs: {} }]
231
+ });
232
+ const settingsNode = getBinaryNodeChild(result, 'reachability_settings');
233
+ if (!settingsNode) return null;
234
+ return {
235
+ enabled: settingsNode.attrs?.enabled,
236
+ users: getBinaryNodeChildren(settingsNode, 'user').map(n => ({
237
+ externalId: n.attrs.external_id,
238
+ integratorId: parseInt(n.attrs.integrator_id, 10),
239
+ jid: n.attrs.jid
240
+ }))
241
+ };
242
+ };
243
+
244
+ /**
245
+ * Set reachability settings (subscribe to presence) for interop contacts.
246
+ * users: array of { externalId, integratorId }
247
+ * enabled: "true" | "false"
248
+ */
249
+ const setReachabilitySettings = async (users, enabled = 'true') => {
250
+ await query({
251
+ tag: 'iq',
252
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
253
+ content: [
254
+ {
255
+ tag: 'reachability_settings',
256
+ attrs: { enabled },
257
+ content: users.map(({ externalId, integratorId }) => ({
258
+ tag: 'user',
259
+ attrs: {
260
+ external_id: externalId,
261
+ integrator_id: integratorId.toString()
262
+ }
263
+ }))
264
+ }
265
+ ]
266
+ });
267
+ };
268
+
269
+ /**
270
+ * Block or unblock an interop user via the w:interop blocklist.
271
+ * Different from regular WA block (xmlns=blocklist).
272
+ */
273
+ const updateInteropBlockStatus = async (jid, action) => {
274
+ await query({
275
+ tag: 'iq',
276
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
277
+ content: [
278
+ {
279
+ tag: 'blocklist',
280
+ attrs: {},
281
+ content: [{ tag: 'item', attrs: { action, jid } }]
282
+ }
283
+ ]
284
+ });
285
+ };
286
+
287
+ const blockInteropUser = jid => updateInteropBlockStatus(jid, 'block');
288
+ const unblockInteropUser = jid => updateInteropBlockStatus(jid, 'unblock');
289
+
290
+ /**
291
+ * Report an interop contact as spam.
292
+ * spam_flow="account_info_block" = block + report (WA Web default).
293
+ */
294
+ const reportInteropSpam = async (jid, spamFlow = 'account_info_block') => {
295
+ await query({
296
+ tag: 'iq',
297
+ attrs: { type: 'set', xmlns: 'spam', to: S_WHATSAPP_NET },
298
+ content: [{ tag: 'spam_list', attrs: { jid, spam_flow: spamFlow } }]
299
+ });
300
+ };
301
+
302
+ /**
303
+ * Mark an interop JID as trusted_contact in privacy tokens.
304
+ * WA calls this automatically after the first outgoing message.
305
+ */
306
+ const trustInteropContact = async (jid) => {
307
+ const t = Math.floor(Date.now() / 1000).toString();
308
+ await query({
309
+ tag: 'iq',
310
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'privacy', type: 'set' },
311
+ content: [
312
+ {
313
+ tag: 'tokens',
314
+ attrs: {},
315
+ content: [{ tag: 'token', attrs: { jid, type: 'trusted_contact', t } }]
316
+ }
317
+ ]
318
+ });
319
+ };
320
+
321
+ /**
322
+ * Full interop initialization sequence matching WA Web:
323
+ * 1. Fetch available integrators
324
+ * 2. Accept TOS (shown 105 + accepted 160)
325
+ * 3. Opt-in to all active/onboarding integrators
326
+ *
327
+ * Silently tolerates TOS/opt-in errors.
328
+ * Returns the full integrator list.
329
+ */
330
+ const initInterop = async () => {
331
+ let integrators;
332
+ try {
333
+ integrators = await fetchIntegrators();
334
+ }
335
+ catch (err) {
336
+ logger.warn({ err }, 'interop: failed to fetch integrators');
337
+ return [];
338
+ }
339
+ const toOptIn = integrators.filter(i => i.status === 'active' || i.status === 'onboarding');
340
+ if (toOptIn.length === 0) return integrators;
341
+ try {
342
+ await acceptInteropTOS();
343
+ }
344
+ catch (err) {
345
+ logger.warn({ err }, 'interop: failed to accept TOS');
346
+ }
347
+ try {
348
+ await optInIntegrators(toOptIn.map(i => i.id));
349
+ }
350
+ catch (err) {
351
+ logger.warn({ err }, 'interop: failed to opt-in integrators');
352
+ }
353
+ logger.info({ integrators: toOptIn.map(i => i.name) }, 'interop: opted in');
354
+ logger.warn(
355
+ { integrators: toOptIn.map(i => i.name) },
356
+ 'interop: receiving messages from interop contacts (BirdyChat/Haiket) is NOT YET SUPPORTED. ' +
357
+ 'The interop bridge only delivers to device 0 (primary phone) via a single Signal session ' +
358
+ 'no fan-out to companion devices. Opt-in and sending may work, but inbound messages will not arrive.'
359
+ );
360
+ return integrators;
361
+ };
362
+
363
+ /**
364
+ * Reset the Signal session with an interop contact and force a fresh pkmsg handshake.
365
+ * Call this when incoming messages from an interop contact are not arriving or
366
+ * failing to decrypt it clears the stale session so the next sendMessage
367
+ * generates a new pre-key message and re-establishes both directions.
368
+ */
369
+ const resetInteropSession = async (jid) => {
370
+ await signalRepository.deleteSession([jid]);
371
+ logger.info({ jid }, '[interop] session reset next send will use pkmsg');
372
+ };
373
+
374
+ /**
375
+ * Create an interop group via MEX.
376
+ * Confirmed from C80913Xf.java opcode 15:
377
+ * input: { participants: [{ jid }] }
378
+ * dataPath: xwa2_interop_group_create
379
+ *
380
+ * @param {string[]} participants - Interop JIDs to add
381
+ * @returns {{ gid, creationTime, creator, participants }}
382
+ */
383
+ const createInteropGroup = async (participants) => {
384
+ const result = await mexQuery(
385
+ { input: { participants: participants.map(jid => ({ jid })) } },
386
+ INTEROP_MEX_QUERY_IDS.CREATE_GROUP,
387
+ 'xwa2_interop_group_create'
388
+ );
389
+ logger.info({ participants }, '[interop] group created via MEX');
390
+ return result;
391
+ };
392
+
393
+ /**
394
+ * Leave one or more interop groups via MEX.
395
+ * Confirmed from C80913Xf.java opcode 28:
396
+ * input: { groups_to_leave: [{ gid }] }
397
+ * dataPath: xwa2_interop_group_leave
398
+ *
399
+ * gid is the raw interop group ID (without @g.us suffix).
400
+ * @param {string|string[]} jids - Interop group JID(s)
401
+ */
402
+ const leaveInteropGroup = async (jids) => {
403
+ const ids = Array.isArray(jids) ? jids : [jids];
404
+ const result = await mexQuery(
405
+ { input: { groups_to_leave: ids.map(jid => ({ gid: jid.split('@')[0] })) } },
406
+ INTEROP_MEX_QUERY_IDS.LEAVE_GROUP,
407
+ 'xwa2_interop_group_leave'
408
+ );
409
+ logger.info({ jids: ids }, '[interop] left group(s) via MEX');
410
+ return result;
411
+ };
412
+
413
+ /**
414
+ * Add participants to an existing interop group via MEX.
415
+ * Confirmed from C3Wt.java opcode 9:
416
+ * input: { gid, participants: [{ jid }] }
417
+ * dataPath: xwa2_interop_add_participants_to_group
418
+ *
419
+ * @param {string} groupJid - Interop group JID
420
+ * @param {string[]} participants - Interop JIDs to add
421
+ */
422
+ const addParticipantsToInteropGroup = async (groupJid, participants) => {
423
+ const gid = groupJid.split('@')[0];
424
+ return mexQuery(
425
+ { input: { gid, participants: participants.map(jid => ({ jid })) } },
426
+ INTEROP_MEX_QUERY_IDS.ADD_PARTICIPANTS,
427
+ 'xwa2_interop_add_participants_to_group'
428
+ );
429
+ };
430
+
431
+ /**
432
+ * Query info about an interop group via MEX.
433
+ * Confirmed from C3Wt.java opcode 10:
434
+ * group_input: { gid }
435
+ * dataPath: xwa2_interop_group_query_by_id
436
+ *
437
+ * @param {string} groupJid - Interop group JID
438
+ */
439
+ const queryInteropGroupInfo = async (groupJid) => {
440
+ const gid = groupJid.split('@')[0];
441
+ return mexQuery({ group_input: { gid } }, INTEROP_MEX_QUERY_IDS.QUERY_GROUP_INFO, 'xwa2_interop_group_query_by_id');
442
+ };
443
+
444
+ /**
445
+ * Update an interop privacy setting via MEX.
446
+ * Confirmed from C24385Ak0.java (InteropPrivacySettingsUpdate):
447
+ * feature, setting
448
+ * dataPath: xwa2_interop_privacy_setting_update
449
+ *
450
+ * Known features: "GROUPADD"
451
+ * Known settings: "ALL" | "CONTACTS" | "NONE"
452
+ *
453
+ * @param {string} feature - Privacy feature name
454
+ * @param {string} setting - New value
455
+ */
456
+ const updateInteropPrivacySetting = async (feature, setting) => {
457
+ return mexQuery(
458
+ { feature, setting },
459
+ INTEROP_MEX_QUERY_IDS.PRIVACY_SETTINGS_UPDATE,
460
+ 'xwa2_interop_privacy_setting_update'
461
+ );
462
+ };
463
+
464
+ /**
465
+ * Update an interop privacy setting with an explicit contact list via MEX.
466
+ * Confirmed from C24388Ak8.java (InteropPrivacySettingWithContactListUpdate):
467
+ * feature, setting, contacts[], contact_list_type, dhash
468
+ * dataPath: xwa2_interop_privacy_setting_with_contact_list_update
469
+ *
470
+ * Used when setting is "CONTACTS" and you want to specify exact allowed contacts.
471
+ *
472
+ * @param {string} feature - Privacy feature (e.g. "GROUPADD")
473
+ * @param {string} setting - "CONTACTS"
474
+ * @param {string[]} contacts - List of JIDs to allow
475
+ * @param {string} contactListType - Contact list type string
476
+ * @param {string} [dhash] - Hash of the current contact list (or null/"none")
477
+ */
478
+ const updateInteropPrivacySettingWithContactList = async (
479
+ feature,
480
+ setting,
481
+ contacts,
482
+ contactListType,
483
+ dhash = 'none'
484
+ ) => {
485
+ return mexQuery(
486
+ { feature, setting, contacts, contact_list_type: contactListType, dhash },
487
+ INTEROP_MEX_QUERY_IDS.PRIVACY_SETTINGS_WITH_CONTACT_LIST,
488
+ 'xwa2_interop_privacy_setting_with_contact_list_update'
489
+ );
490
+ };
491
+
492
+ /**
493
+ * Query all interop privacy settings via MEX.
494
+ * Uses InteropPrivacySettingsQuery (doc_id: 24849123668112654).
495
+ * Returns the current value for each privacy feature (e.g. GROUPADD).
496
+ * dataPath: xwa2_interop_privacy_settings
497
+ */
498
+ const queryInteropPrivacySettings = () =>
499
+ mexQuery({}, INTEROP_MEX_QUERY_IDS.PRIVACY_SETTINGS_QUERY, 'xwa2_interop_privacy_settings');
500
+
501
+ /**
502
+ * Check whether an interop user allows being added to groups (GROUPADD privacy).
503
+ * Returns true if the user can be added, false if blocked by their privacy settings.
504
+ *
505
+ * Mirrors InteropPrivacySettingsManager.A01() in the APK which queries
506
+ * the "GROUPADD" feature for the given account.
507
+ */
508
+ const getInteropGroupAddPrivacy = async (jid, integratorId) => {
509
+ const result = await query({
510
+ tag: 'iq',
511
+ attrs: { type: 'get', xmlns: 'w:interop', to: S_WHATSAPP_NET },
512
+ content: [
513
+ {
514
+ tag: 'privacy',
515
+ attrs: { feature: 'GROUPADD' },
516
+ content: [
517
+ {
518
+ tag: 'user',
519
+ attrs: {
520
+ jid,
521
+ integrator_id: integratorId.toString()
522
+ }
523
+ }
524
+ ]
525
+ }
526
+ ]
527
+ });
528
+ const privacyNode = getBinaryNodeChild(result, 'privacy');
529
+ const userNode = getBinaryNodeChild(privacyNode, 'user');
530
+ // "allowed" means the server confirmed the user can be added; any other value or
531
+ // absence of the attribute means the privacy setting blocks the add.
532
+ return userNode?.attrs?.result === 'allowed';
533
+ };
534
+
535
+ return {
536
+ ...sock,
537
+ fetchIntegrators,
538
+ acceptInteropTOS,
539
+ optInIntegrators,
540
+ optOutIntegrators,
541
+ resolveInteropUser,
542
+ resolveInteropUsers,
543
+ getReachabilitySettings,
544
+ setReachabilitySettings,
545
+ blockInteropUser,
546
+ unblockInteropUser,
547
+ reportInteropSpam,
548
+ trustInteropContact,
549
+ initInterop,
550
+ resetInteropSession,
551
+ createInteropGroup,
552
+ leaveInteropGroup,
553
+ addParticipantsToInteropGroup,
554
+ queryInteropGroupInfo,
555
+ queryInteropPrivacySettings,
556
+ updateInteropPrivacySetting,
557
+ updateInteropPrivacySettingWithContactList,
558
+ getInteropGroupAddPrivacy,
559
+ INTEGRATOR_BIRDYCHAT,
560
+ INTEGRATOR_HAIKET,
561
+ INTEROP_MEX_QUERY_IDS
562
+ };
563
+ };