@badzz88/baileys 8.4.6 → 8.4.9

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