@x4r1s3/baileys 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1262 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/audio-feeder.mjs +179 -0
  18. package/lib/Call/audio-recorder.mjs +250 -0
  19. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  20. package/lib/Call/index.mjs +680 -0
  21. package/lib/Call/relay-transport.mjs +563 -0
  22. package/lib/Call/signaling.mjs +641 -0
  23. package/lib/Call/types.mjs +17 -0
  24. package/lib/Call/video-feeder.mjs +94 -0
  25. package/lib/Call/wasm-engine.mjs +1372 -0
  26. package/lib/Call/worker-bootstrap.mjs +1042 -0
  27. package/lib/Defaults/ban-checker.js +56 -0
  28. package/lib/Defaults/index.js +170 -0
  29. package/lib/Signal/Group/ciphertext-message.js +23 -0
  30. package/lib/Signal/Group/group-session-builder.js +41 -0
  31. package/lib/Signal/Group/group_cipher.js +93 -0
  32. package/lib/Signal/Group/index.js +23 -0
  33. package/lib/Signal/Group/keyhelper.js +29 -0
  34. package/lib/Signal/Group/sender-chain-key.js +37 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  36. package/lib/Signal/Group/sender-key-message.js +77 -0
  37. package/lib/Signal/Group/sender-key-name.js +59 -0
  38. package/lib/Signal/Group/sender-key-record.js +52 -0
  39. package/lib/Signal/Group/sender-key-state.js +95 -0
  40. package/lib/Signal/Group/sender-message-key.js +37 -0
  41. package/lib/Signal/libsignal.js +440 -0
  42. package/lib/Signal/lid-mapping.js +292 -0
  43. package/lib/Socket/Client/index.js +14 -0
  44. package/lib/Socket/Client/types.js +22 -0
  45. package/lib/Socket/Client/websocket.js +65 -0
  46. package/lib/Socket/aigroups.js +327 -0
  47. package/lib/Socket/ban-checker.js +165 -0
  48. package/lib/Socket/business.js +419 -0
  49. package/lib/Socket/chats.js +1921 -0
  50. package/lib/Socket/communities.js +443 -0
  51. package/lib/Socket/graphql.js +911 -0
  52. package/lib/Socket/groups.js +561 -0
  53. package/lib/Socket/index.js +49 -0
  54. package/lib/Socket/interactive-handler.js +612 -0
  55. package/lib/Socket/interop.js +575 -0
  56. package/lib/Socket/managed-account.js +220 -0
  57. package/lib/Socket/messages-recv.js +2191 -0
  58. package/lib/Socket/messages-send.js +4104 -0
  59. package/lib/Socket/mex.js +53 -0
  60. package/lib/Socket/newsletter.js +291 -0
  61. package/lib/Socket/privacy.js +458 -0
  62. package/lib/Socket/registration.js +440 -0
  63. package/lib/Socket/socket.js +1029 -0
  64. package/lib/Socket/status-actions.js +287 -0
  65. package/lib/Socket/username.js +241 -0
  66. package/lib/Store/index.js +16 -0
  67. package/lib/Store/make-cache-manager-store.js +101 -0
  68. package/lib/Store/make-in-memory-store.js +432 -0
  69. package/lib/Store/make-ordered-dictionary.js +90 -0
  70. package/lib/Store/object-repository.js +35 -0
  71. package/lib/Types/Auth.js +13 -0
  72. package/lib/Types/Bussines.js +13 -0
  73. package/lib/Types/Call.js +13 -0
  74. package/lib/Types/Chat.js +19 -0
  75. package/lib/Types/Contact.js +13 -0
  76. package/lib/Types/Events.js +13 -0
  77. package/lib/Types/GroupMetadata.js +13 -0
  78. package/lib/Types/Label.js +36 -0
  79. package/lib/Types/LabelAssociation.js +18 -0
  80. package/lib/Types/Message.js +30 -0
  81. package/lib/Types/Mex.js +53 -0
  82. package/lib/Types/Product.js +13 -0
  83. package/lib/Types/RichType.js +34 -0
  84. package/lib/Types/Signal.js +13 -0
  85. package/lib/Types/Socket.js +14 -0
  86. package/lib/Types/State.js +60 -0
  87. package/lib/Types/USync.js +13 -0
  88. package/lib/Types/index.js +37 -0
  89. package/lib/Utils/auth-utils.js +313 -0
  90. package/lib/Utils/ban-checker.js +48 -0
  91. package/lib/Utils/bot-capabilities.js +96 -0
  92. package/lib/Utils/bot-planning-replay.js +177 -0
  93. package/lib/Utils/browser-utils.js +40 -0
  94. package/lib/Utils/business.js +242 -0
  95. package/lib/Utils/c2582.js +147 -0
  96. package/lib/Utils/chat-utils.js +905 -0
  97. package/lib/Utils/companion-reg-client-utils.js +44 -0
  98. package/lib/Utils/consumer-application.js +114 -0
  99. package/lib/Utils/crypto.js +129 -0
  100. package/lib/Utils/decode-wa-message.js +496 -0
  101. package/lib/Utils/direct-chat-theme.js +164 -0
  102. package/lib/Utils/event-buffer.js +601 -0
  103. package/lib/Utils/experimental-proto.js +206 -0
  104. package/lib/Utils/games/miniapp.js +17 -0
  105. package/lib/Utils/games/slot-machine.js +270 -0
  106. package/lib/Utils/games/website-preview.js +306 -0
  107. package/lib/Utils/generics.js +402 -0
  108. package/lib/Utils/group-history.js +68 -0
  109. package/lib/Utils/group-wallpaper.js +168 -0
  110. package/lib/Utils/history.js +162 -0
  111. package/lib/Utils/identity-change-handler.js +60 -0
  112. package/lib/Utils/index.js +61 -0
  113. package/lib/Utils/jid-display-normalization.js +221 -0
  114. package/lib/Utils/link-preview.js +96 -0
  115. package/lib/Utils/logger.js +14 -0
  116. package/lib/Utils/lt-hash.js +19 -0
  117. package/lib/Utils/make-mutex.js +44 -0
  118. package/lib/Utils/message-composer.js +709 -0
  119. package/lib/Utils/message-inspect.js +79 -0
  120. package/lib/Utils/message-retry-manager.js +253 -0
  121. package/lib/Utils/message-security.js +167 -0
  122. package/lib/Utils/messages-media.js +1027 -0
  123. package/lib/Utils/messages.js +2467 -0
  124. package/lib/Utils/meta-ai-msmsg.js +215 -0
  125. package/lib/Utils/meta-compositing.js +239 -0
  126. package/lib/Utils/native-flow.js +158 -0
  127. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  128. package/lib/Utils/newsletter-status-utils.js +152 -0
  129. package/lib/Utils/noise-handler.js +212 -0
  130. package/lib/Utils/offline-node-processor.js +51 -0
  131. package/lib/Utils/poll-manager.js +206 -0
  132. package/lib/Utils/portable-compat.js +12 -0
  133. package/lib/Utils/pre-key-manager.js +117 -0
  134. package/lib/Utils/process-message.js +610 -0
  135. package/lib/Utils/reporting-utils.js +269 -0
  136. package/lib/Utils/rich-message-utils.js +2841 -0
  137. package/lib/Utils/scheduled-message.js +107 -0
  138. package/lib/Utils/signal.js +212 -0
  139. package/lib/Utils/source-grep.js +57 -0
  140. package/lib/Utils/stanza-ack.js +49 -0
  141. package/lib/Utils/sticker-annotation.js +87 -0
  142. package/lib/Utils/sync-action-utils.js +59 -0
  143. package/lib/Utils/tc-token-utils.js +174 -0
  144. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  145. package/lib/Utils/use-single-file-auth-state.js +108 -0
  146. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  147. package/lib/Utils/validate-connection.js +220 -0
  148. package/lib/Utils/view-once-utils.js +218 -0
  149. package/lib/Utils/voip-rekey.js +32 -0
  150. package/lib/Utils/website-preview.js +27 -0
  151. package/lib/Utils/welcome-flow.js +228 -0
  152. package/lib/Utils/x4r1s3.js +144 -0
  153. package/lib/WABinary/constants.js +1475 -0
  154. package/lib/WABinary/decode.js +273 -0
  155. package/lib/WABinary/encode.js +231 -0
  156. package/lib/WABinary/generic-utils.js +242 -0
  157. package/lib/WABinary/index.js +17 -0
  158. package/lib/WABinary/jid-utils.js +107 -0
  159. package/lib/WABinary/types.js +13 -0
  160. package/lib/WAM/BinaryInfo.js +21 -0
  161. package/lib/WAM/constants.js +22864 -0
  162. package/lib/WAM/encode.js +161 -0
  163. package/lib/WAM/index.js +15 -0
  164. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  167. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  168. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  169. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  170. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  172. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  173. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  174. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  176. package/lib/WAUSync/Protocols/index.js +24 -0
  177. package/lib/WAUSync/USyncQuery.js +213 -0
  178. package/lib/WAUSync/USyncUser.js +66 -0
  179. package/lib/WAUSync/index.js +15 -0
  180. package/lib/antiban.cjs +4726 -0
  181. package/lib/index.d.ts +1285 -0
  182. package/lib/index.js +30 -0
  183. package/package.json +125 -4
@@ -0,0 +1,575 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Socket/interop.js
5
+ * About: Interop module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: makeInteropSocket
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import { getBinaryNodeChild, getBinaryNodeChildren, S_WHATSAPP_NET } from '../WABinary/index.js';
14
+ import { executeWMexQuery } from './mex.js';
15
+
16
+ /**
17
+ * w:mex query IDs for interop group and privacy operations.
18
+ *
19
+ * Source: whatsapp-android-mex_client_persist_ids.json (WA 2.26.26.4 APK assets)
20
+ */
21
+ const INTEROP_MEX_QUERY_IDS = {
22
+ CREATE_GROUP: '25726817620301611', // GroupsCreateInteropGroup
23
+ LEAVE_GROUP: '25346167795013271', // LeaveInteropGroup
24
+ ADD_PARTICIPANTS: '25732168276369451', // AddParticipantsToInteropGroup
25
+ QUERY_GROUP_INFO: '32734144032867938', // QueryInteropGroupInfo
26
+ PRIVACY_SETTINGS_QUERY: '24849123668112654', // InteropPrivacySettingsQuery
27
+ PRIVACY_SETTINGS_UPDATE: '25421856497452763', // InteropPrivacySettingsUpdate
28
+ PRIVACY_SETTINGS_WITH_CONTACT_LIST: '24913399124998598' // InteropPrivacySettingWithContactListUpdate
29
+ };
30
+
31
+ /**
32
+ * Known integrator IDs (assigned by WhatsApp).
33
+ * BirdyChat → identifier_type="email"
34
+ * Haiket → identifier_type="pn"
35
+ */
36
+ const INTEGRATOR_BIRDYCHAT = 12;
37
+ const INTEGRATOR_HAIKET = 13;
38
+
39
+ /**
40
+ * TOS trackable results sent by WA on first interop opt-in.
41
+ * 105 = TOS shown, 160 = TOS accepted.
42
+ */
43
+ const TOS_TRACKABLE_ID = '20240306';
44
+ const TOS_RESULT_SHOWN = '105';
45
+ const TOS_RESULT_ACCEPTED = '160';
46
+
47
+ /** Maximum users per batch lookup (enforced server-side too). */
48
+ const INTEROP_BATCH_MAX = 256;
49
+
50
+ export const makeInteropSocket = (sock) => {
51
+ const { query, generateMessageTag, logger, signalRepository } = sock;
52
+
53
+ const mexQuery = (variables, queryId, dataPath) =>
54
+ executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag);
55
+
56
+ /**
57
+ * Fetch all available interop integrators from the server.
58
+ * Each integrator carries: id, name, status, icon, identifierType,
59
+ * optedIn, features.groupMessaging.
60
+ * status can be "active" | "onboarding" | "removed".
61
+ */
62
+ const fetchIntegrators = async () => {
63
+ const result = await query({
64
+ tag: 'iq',
65
+ attrs: {
66
+ type: 'get',
67
+ xmlns: 'w:interop',
68
+ to: S_WHATSAPP_NET
69
+ },
70
+ content: [{ tag: 'integrator', attrs: { fetch: 'all' } }]
71
+ });
72
+ const listNode = getBinaryNodeChild(result, 'integrator_list');
73
+ if (!listNode) return [];
74
+ const globalOptedIn = listNode.attrs?.opted_in === 'true';
75
+ return getBinaryNodeChildren(listNode, 'integrator').map(node => {
76
+ const featuresNode = getBinaryNodeChild(node, 'features');
77
+ return {
78
+ id: parseInt(node.attrs.id, 10),
79
+ name: node.attrs.name,
80
+ // "active" | "onboarding" | "removed"
81
+ status: node.attrs.status,
82
+ icon: node.attrs.icon,
83
+ // "email" | "pn" | "username"
84
+ identifierType: node.attrs.identifier_type,
85
+ // Whether we are already opted-in to this integrator
86
+ optedIn: node.attrs.opted_in === 'true' || globalOptedIn,
87
+ features: {
88
+ groupMessaging: featuresNode?.attrs?.group_messaging === 'true'
89
+ }
90
+ };
91
+ });
92
+ };
93
+
94
+ /** Send a single TOS trackable item (shown or accepted). */
95
+ const sendTOSTrackable = async (id, result) => {
96
+ await query({
97
+ tag: 'iq',
98
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'tos' },
99
+ content: [{ tag: 'trackable', attrs: { id, result } }]
100
+ });
101
+ };
102
+
103
+ /**
104
+ * Accept TOS for interop.
105
+ * Sends two trackable items: shown (105) then accepted (160).
106
+ * Must be called before opting in.
107
+ */
108
+ const acceptInteropTOS = async () => {
109
+ await sendTOSTrackable(TOS_TRACKABLE_ID, TOS_RESULT_SHOWN);
110
+ await sendTOSTrackable(TOS_TRACKABLE_ID, TOS_RESULT_ACCEPTED);
111
+ };
112
+
113
+ /**
114
+ * Opt in to a list of integrators (by numeric ID).
115
+ * Defaults to both known integrators (BirdyChat + Haiket).
116
+ */
117
+ const optInIntegrators = async (integratorIds = [INTEGRATOR_BIRDYCHAT, INTEGRATOR_HAIKET]) => {
118
+ await query({
119
+ tag: 'iq',
120
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
121
+ content: [
122
+ {
123
+ tag: 'opt_in_integrators',
124
+ attrs: {},
125
+ content: [
126
+ {
127
+ tag: 'integrator_list',
128
+ attrs: {},
129
+ content: integratorIds.map(id => ({
130
+ tag: 'integrator',
131
+ attrs: { id: id.toString() }
132
+ }))
133
+ }
134
+ ]
135
+ }
136
+ ]
137
+ });
138
+ };
139
+
140
+ /**
141
+ * Opt out of a list of integrators (by numeric ID).
142
+ * Mirror of optInIntegrators — uses <opt_out_integrators>.
143
+ */
144
+ const optOutIntegrators = async (integratorIds = [INTEGRATOR_BIRDYCHAT, INTEGRATOR_HAIKET]) => {
145
+ await query({
146
+ tag: 'iq',
147
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
148
+ content: [
149
+ {
150
+ tag: 'opt_out_integrators',
151
+ attrs: {},
152
+ content: [
153
+ {
154
+ tag: 'integrator_list',
155
+ attrs: {},
156
+ content: integratorIds.map(id => ({
157
+ tag: 'integrator',
158
+ attrs: { id: id.toString() }
159
+ }))
160
+ }
161
+ ]
162
+ }
163
+ ]
164
+ });
165
+ };
166
+
167
+ /**
168
+ * Resolve one or more interop users by external ID in a single IQ.
169
+ * Each entry: { externalId, integratorId }
170
+ * - BirdyChat (12): externalId = email address
171
+ * - Haiket (13): externalId = phone number string (e.g. "19146088152")
172
+ *
173
+ * Max 256 entries per call (server limit).
174
+ *
175
+ * Returns an array of results:
176
+ * { jid, externalId, normalizedExternalId, integratorId } on success
177
+ * { externalId, integratorId, error: { code, text } } on failure
178
+ */
179
+ const resolveInteropUsers = async (users) => {
180
+ if (!users || users.length === 0) return [];
181
+ if (users.length > INTEROP_BATCH_MAX) {
182
+ throw new Error(`resolveInteropUsers: max ${INTEROP_BATCH_MAX} users per request`);
183
+ }
184
+ const result = await query({
185
+ tag: 'iq',
186
+ attrs: { type: 'get', xmlns: 'w:interop', to: S_WHATSAPP_NET },
187
+ content: [
188
+ {
189
+ tag: 'users',
190
+ attrs: {},
191
+ content: users.map(({ externalId, integratorId }) => ({
192
+ tag: 'user',
193
+ attrs: {
194
+ external_id: externalId,
195
+ integrator_id: integratorId.toString()
196
+ }
197
+ }))
198
+ }
199
+ ]
200
+ });
201
+ const usersNode = getBinaryNodeChild(result, 'users');
202
+ if (!usersNode) return [];
203
+ return getBinaryNodeChildren(usersNode, 'user').map(userNode => {
204
+ const errorNode = getBinaryNodeChild(userNode, 'error');
205
+ if (errorNode) {
206
+ return {
207
+ externalId: userNode.attrs.external_id,
208
+ integratorId: parseInt(userNode.attrs.integrator_id, 10),
209
+ error: {
210
+ code: parseInt(errorNode.attrs.code, 10),
211
+ text: errorNode.attrs.text
212
+ }
213
+ };
214
+ }
215
+ return {
216
+ jid: userNode.attrs.jid,
217
+ externalId: userNode.attrs.external_id,
218
+ normalizedExternalId: userNode.attrs.normalized_external_id,
219
+ integratorId: parseInt(userNode.attrs.integrator_id, 10)
220
+ };
221
+ });
222
+ };
223
+
224
+ /**
225
+ * Convenience wrapper: resolve a single interop user.
226
+ * Returns the result object or null.
227
+ */
228
+ const resolveInteropUser = async (externalId, integratorId) => {
229
+ const results = await resolveInteropUsers([{ externalId, integratorId }]);
230
+ return results[0] ?? null;
231
+ };
232
+
233
+ /**
234
+ * Get reachability settings for interop contacts.
235
+ * Returns the raw <reachability_settings> node content.
236
+ * WA uses this as the interop presence/subscription mechanism.
237
+ */
238
+ const getReachabilitySettings = async () => {
239
+ const result = await query({
240
+ tag: 'iq',
241
+ attrs: { type: 'get', xmlns: 'w:interop', to: S_WHATSAPP_NET },
242
+ content: [{ tag: 'reachability_settings', attrs: {} }]
243
+ });
244
+ const settingsNode = getBinaryNodeChild(result, 'reachability_settings');
245
+ if (!settingsNode) return null;
246
+ return {
247
+ enabled: settingsNode.attrs?.enabled,
248
+ users: getBinaryNodeChildren(settingsNode, 'user').map(n => ({
249
+ externalId: n.attrs.external_id,
250
+ integratorId: parseInt(n.attrs.integrator_id, 10),
251
+ jid: n.attrs.jid
252
+ }))
253
+ };
254
+ };
255
+
256
+ /**
257
+ * Set reachability settings (subscribe to presence) for interop contacts.
258
+ * users: array of { externalId, integratorId }
259
+ * enabled: "true" | "false"
260
+ */
261
+ const setReachabilitySettings = async (users, enabled = 'true') => {
262
+ await query({
263
+ tag: 'iq',
264
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
265
+ content: [
266
+ {
267
+ tag: 'reachability_settings',
268
+ attrs: { enabled },
269
+ content: users.map(({ externalId, integratorId }) => ({
270
+ tag: 'user',
271
+ attrs: {
272
+ external_id: externalId,
273
+ integrator_id: integratorId.toString()
274
+ }
275
+ }))
276
+ }
277
+ ]
278
+ });
279
+ };
280
+
281
+ /**
282
+ * Block or unblock an interop user via the w:interop blocklist.
283
+ * Different from regular WA block (xmlns=blocklist).
284
+ */
285
+ const updateInteropBlockStatus = async (jid, action) => {
286
+ await query({
287
+ tag: 'iq',
288
+ attrs: { type: 'set', xmlns: 'w:interop', to: S_WHATSAPP_NET },
289
+ content: [
290
+ {
291
+ tag: 'blocklist',
292
+ attrs: {},
293
+ content: [{ tag: 'item', attrs: { action, jid } }]
294
+ }
295
+ ]
296
+ });
297
+ };
298
+
299
+ const blockInteropUser = jid => updateInteropBlockStatus(jid, 'block');
300
+ const unblockInteropUser = jid => updateInteropBlockStatus(jid, 'unblock');
301
+
302
+ /**
303
+ * Report an interop contact as spam.
304
+ * spam_flow="account_info_block" = block + report (WA Web default).
305
+ */
306
+ const reportInteropSpam = async (jid, spamFlow = 'account_info_block') => {
307
+ await query({
308
+ tag: 'iq',
309
+ attrs: { type: 'set', xmlns: 'spam', to: S_WHATSAPP_NET },
310
+ content: [{ tag: 'spam_list', attrs: { jid, spam_flow: spamFlow } }]
311
+ });
312
+ };
313
+
314
+ /**
315
+ * Mark an interop JID as trusted_contact in privacy tokens.
316
+ * WA calls this automatically after the first outgoing message.
317
+ */
318
+ const trustInteropContact = async (jid) => {
319
+ const t = Math.floor(Date.now() / 1000).toString();
320
+ await query({
321
+ tag: 'iq',
322
+ attrs: { to: S_WHATSAPP_NET, xmlns: 'privacy', type: 'set' },
323
+ content: [
324
+ {
325
+ tag: 'tokens',
326
+ attrs: {},
327
+ content: [{ tag: 'token', attrs: { jid, type: 'trusted_contact', t } }]
328
+ }
329
+ ]
330
+ });
331
+ };
332
+
333
+ /**
334
+ * Full interop initialization sequence matching WA Web:
335
+ * 1. Fetch available integrators
336
+ * 2. Accept TOS (shown 105 + accepted 160)
337
+ * 3. Opt-in to all active/onboarding integrators
338
+ *
339
+ * Silently tolerates TOS/opt-in errors.
340
+ * Returns the full integrator list.
341
+ */
342
+ const initInterop = async () => {
343
+ let integrators;
344
+ try {
345
+ integrators = await fetchIntegrators();
346
+ }
347
+ catch (err) {
348
+ logger.warn({ err }, 'interop: failed to fetch integrators');
349
+ return [];
350
+ }
351
+ const toOptIn = integrators.filter(i => i.status === 'active' || i.status === 'onboarding');
352
+ if (toOptIn.length === 0) return integrators;
353
+ try {
354
+ await acceptInteropTOS();
355
+ }
356
+ catch (err) {
357
+ logger.warn({ err }, 'interop: failed to accept TOS');
358
+ }
359
+ try {
360
+ await optInIntegrators(toOptIn.map(i => i.id));
361
+ }
362
+ catch (err) {
363
+ logger.warn({ err }, 'interop: failed to opt-in integrators');
364
+ }
365
+ logger.info({ integrators: toOptIn.map(i => i.name) }, 'interop: opted in');
366
+ logger.warn(
367
+ { integrators: toOptIn.map(i => i.name) },
368
+ 'interop: receiving messages from interop contacts (BirdyChat/Haiket) is NOT YET SUPPORTED. ' +
369
+ 'The interop bridge only delivers to device 0 (primary phone) via a single Signal session — ' +
370
+ 'no fan-out to companion devices. Opt-in and sending may work, but inbound messages will not arrive.'
371
+ );
372
+ return integrators;
373
+ };
374
+
375
+ /**
376
+ * Reset the Signal session with an interop contact and force a fresh pkmsg handshake.
377
+ * Call this when incoming messages from an interop contact are not arriving or
378
+ * failing to decrypt — it clears the stale session so the next sendMessage
379
+ * generates a new pre-key message and re-establishes both directions.
380
+ */
381
+ const resetInteropSession = async (jid) => {
382
+ await signalRepository.deleteSession([jid]);
383
+ logger.info({ jid }, '[interop] session reset — next send will use pkmsg');
384
+ };
385
+
386
+ /**
387
+ * Create an interop group via MEX.
388
+ * Confirmed from C80913Xf.java opcode 15:
389
+ * input: { participants: [{ jid }] }
390
+ * dataPath: xwa2_interop_group_create
391
+ *
392
+ * @param {string[]} participants - Interop JIDs to add
393
+ * @returns {{ gid, creationTime, creator, participants }}
394
+ */
395
+ const createInteropGroup = async (participants) => {
396
+ const result = await mexQuery(
397
+ { input: { participants: participants.map(jid => ({ jid })) } },
398
+ INTEROP_MEX_QUERY_IDS.CREATE_GROUP,
399
+ 'xwa2_interop_group_create'
400
+ );
401
+ logger.info({ participants }, '[interop] group created via MEX');
402
+ return result;
403
+ };
404
+
405
+ /**
406
+ * Leave one or more interop groups via MEX.
407
+ * Confirmed from C80913Xf.java opcode 28:
408
+ * input: { groups_to_leave: [{ gid }] }
409
+ * dataPath: xwa2_interop_group_leave
410
+ *
411
+ * gid is the raw interop group ID (without @g.us suffix).
412
+ * @param {string|string[]} jids - Interop group JID(s)
413
+ */
414
+ const leaveInteropGroup = async (jids) => {
415
+ const ids = Array.isArray(jids) ? jids : [jids];
416
+ const result = await mexQuery(
417
+ { input: { groups_to_leave: ids.map(jid => ({ gid: jid.split('@')[0] })) } },
418
+ INTEROP_MEX_QUERY_IDS.LEAVE_GROUP,
419
+ 'xwa2_interop_group_leave'
420
+ );
421
+ logger.info({ jids: ids }, '[interop] left group(s) via MEX');
422
+ return result;
423
+ };
424
+
425
+ /**
426
+ * Add participants to an existing interop group via MEX.
427
+ * Confirmed from C3Wt.java opcode 9:
428
+ * input: { gid, participants: [{ jid }] }
429
+ * dataPath: xwa2_interop_add_participants_to_group
430
+ *
431
+ * @param {string} groupJid - Interop group JID
432
+ * @param {string[]} participants - Interop JIDs to add
433
+ */
434
+ const addParticipantsToInteropGroup = async (groupJid, participants) => {
435
+ const gid = groupJid.split('@')[0];
436
+ return mexQuery(
437
+ { input: { gid, participants: participants.map(jid => ({ jid })) } },
438
+ INTEROP_MEX_QUERY_IDS.ADD_PARTICIPANTS,
439
+ 'xwa2_interop_add_participants_to_group'
440
+ );
441
+ };
442
+
443
+ /**
444
+ * Query info about an interop group via MEX.
445
+ * Confirmed from C3Wt.java opcode 10:
446
+ * group_input: { gid }
447
+ * dataPath: xwa2_interop_group_query_by_id
448
+ *
449
+ * @param {string} groupJid - Interop group JID
450
+ */
451
+ const queryInteropGroupInfo = async (groupJid) => {
452
+ const gid = groupJid.split('@')[0];
453
+ return mexQuery({ group_input: { gid } }, INTEROP_MEX_QUERY_IDS.QUERY_GROUP_INFO, 'xwa2_interop_group_query_by_id');
454
+ };
455
+
456
+ /**
457
+ * Update an interop privacy setting via MEX.
458
+ * Confirmed from C24385Ak0.java (InteropPrivacySettingsUpdate):
459
+ * feature, setting
460
+ * dataPath: xwa2_interop_privacy_setting_update
461
+ *
462
+ * Known features: "GROUPADD"
463
+ * Known settings: "ALL" | "CONTACTS" | "NONE"
464
+ *
465
+ * @param {string} feature - Privacy feature name
466
+ * @param {string} setting - New value
467
+ */
468
+ const updateInteropPrivacySetting = async (feature, setting) => {
469
+ return mexQuery(
470
+ { feature, setting },
471
+ INTEROP_MEX_QUERY_IDS.PRIVACY_SETTINGS_UPDATE,
472
+ 'xwa2_interop_privacy_setting_update'
473
+ );
474
+ };
475
+
476
+ /**
477
+ * Update an interop privacy setting with an explicit contact list via MEX.
478
+ * Confirmed from C24388Ak8.java (InteropPrivacySettingWithContactListUpdate):
479
+ * feature, setting, contacts[], contact_list_type, dhash
480
+ * dataPath: xwa2_interop_privacy_setting_with_contact_list_update
481
+ *
482
+ * Used when setting is "CONTACTS" and you want to specify exact allowed contacts.
483
+ *
484
+ * @param {string} feature - Privacy feature (e.g. "GROUPADD")
485
+ * @param {string} setting - "CONTACTS"
486
+ * @param {string[]} contacts - List of JIDs to allow
487
+ * @param {string} contactListType - Contact list type string
488
+ * @param {string} [dhash] - Hash of the current contact list (or null/"none")
489
+ */
490
+ const updateInteropPrivacySettingWithContactList = async (
491
+ feature,
492
+ setting,
493
+ contacts,
494
+ contactListType,
495
+ dhash = 'none'
496
+ ) => {
497
+ return mexQuery(
498
+ { feature, setting, contacts, contact_list_type: contactListType, dhash },
499
+ INTEROP_MEX_QUERY_IDS.PRIVACY_SETTINGS_WITH_CONTACT_LIST,
500
+ 'xwa2_interop_privacy_setting_with_contact_list_update'
501
+ );
502
+ };
503
+
504
+ /**
505
+ * Query all interop privacy settings via MEX.
506
+ * Uses InteropPrivacySettingsQuery (doc_id: 24849123668112654).
507
+ * Returns the current value for each privacy feature (e.g. GROUPADD).
508
+ * dataPath: xwa2_interop_privacy_settings
509
+ */
510
+ const queryInteropPrivacySettings = () =>
511
+ mexQuery({}, INTEROP_MEX_QUERY_IDS.PRIVACY_SETTINGS_QUERY, 'xwa2_interop_privacy_settings');
512
+
513
+ /**
514
+ * Check whether an interop user allows being added to groups (GROUPADD privacy).
515
+ * Returns true if the user can be added, false if blocked by their privacy settings.
516
+ *
517
+ * Mirrors InteropPrivacySettingsManager.A01() in the APK which queries
518
+ * the "GROUPADD" feature for the given account.
519
+ */
520
+ const getInteropGroupAddPrivacy = async (jid, integratorId) => {
521
+ const result = await query({
522
+ tag: 'iq',
523
+ attrs: { type: 'get', xmlns: 'w:interop', to: S_WHATSAPP_NET },
524
+ content: [
525
+ {
526
+ tag: 'privacy',
527
+ attrs: { feature: 'GROUPADD' },
528
+ content: [
529
+ {
530
+ tag: 'user',
531
+ attrs: {
532
+ jid,
533
+ integrator_id: integratorId.toString()
534
+ }
535
+ }
536
+ ]
537
+ }
538
+ ]
539
+ });
540
+ const privacyNode = getBinaryNodeChild(result, 'privacy');
541
+ const userNode = getBinaryNodeChild(privacyNode, 'user');
542
+ // "allowed" means the server confirmed the user can be added; any other value or
543
+ // absence of the attribute means the privacy setting blocks the add.
544
+ return userNode?.attrs?.result === 'allowed';
545
+ };
546
+
547
+ return {
548
+ ...sock,
549
+ fetchIntegrators,
550
+ acceptInteropTOS,
551
+ optInIntegrators,
552
+ optOutIntegrators,
553
+ resolveInteropUser,
554
+ resolveInteropUsers,
555
+ getReachabilitySettings,
556
+ setReachabilitySettings,
557
+ blockInteropUser,
558
+ unblockInteropUser,
559
+ reportInteropSpam,
560
+ trustInteropContact,
561
+ initInterop,
562
+ resetInteropSession,
563
+ createInteropGroup,
564
+ leaveInteropGroup,
565
+ addParticipantsToInteropGroup,
566
+ queryInteropGroupInfo,
567
+ queryInteropPrivacySettings,
568
+ updateInteropPrivacySetting,
569
+ updateInteropPrivacySettingWithContactList,
570
+ getInteropGroupAddPrivacy,
571
+ INTEGRATOR_BIRDYCHAT,
572
+ INTEGRATOR_HAIKET,
573
+ INTEROP_MEX_QUERY_IDS
574
+ };
575
+ };