@x4r1s3/baileys 0.0.0-stage → 1.0.1

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 (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1245 -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/astralena-v3.mjs +96 -0
  18. package/lib/Call/audio-feeder.mjs +201 -0
  19. package/lib/Call/audio-recorder.mjs +250 -0
  20. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  21. package/lib/Call/index.mjs +707 -0
  22. package/lib/Call/relay-transport.mjs +563 -0
  23. package/lib/Call/signaling.mjs +660 -0
  24. package/lib/Call/types.mjs +17 -0
  25. package/lib/Call/video-feeder.mjs +94 -0
  26. package/lib/Call/voip-resources.mjs +259 -0
  27. package/lib/Call/wasm-engine.mjs +1372 -0
  28. package/lib/Call/worker-bootstrap.mjs +1042 -0
  29. package/lib/Defaults/ban-checker.js +56 -0
  30. package/lib/Defaults/index.js +170 -0
  31. package/lib/Signal/Group/ciphertext-message.js +23 -0
  32. package/lib/Signal/Group/group-session-builder.js +41 -0
  33. package/lib/Signal/Group/group_cipher.js +93 -0
  34. package/lib/Signal/Group/index.js +23 -0
  35. package/lib/Signal/Group/keyhelper.js +29 -0
  36. package/lib/Signal/Group/sender-chain-key.js +37 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  38. package/lib/Signal/Group/sender-key-message.js +77 -0
  39. package/lib/Signal/Group/sender-key-name.js +59 -0
  40. package/lib/Signal/Group/sender-key-record.js +52 -0
  41. package/lib/Signal/Group/sender-key-state.js +95 -0
  42. package/lib/Signal/Group/sender-message-key.js +37 -0
  43. package/lib/Signal/libsignal.js +440 -0
  44. package/lib/Signal/lid-mapping.js +292 -0
  45. package/lib/Socket/Client/index.js +14 -0
  46. package/lib/Socket/Client/types.js +22 -0
  47. package/lib/Socket/Client/websocket.js +65 -0
  48. package/lib/Socket/aigroups.js +327 -0
  49. package/lib/Socket/ban-checker.js +165 -0
  50. package/lib/Socket/business.js +419 -0
  51. package/lib/Socket/chats.js +1921 -0
  52. package/lib/Socket/communities.js +443 -0
  53. package/lib/Socket/graphql.js +911 -0
  54. package/lib/Socket/groups.js +561 -0
  55. package/lib/Socket/index.js +49 -0
  56. package/lib/Socket/interactive-handler.js +612 -0
  57. package/lib/Socket/interop.js +575 -0
  58. package/lib/Socket/managed-account.js +220 -0
  59. package/lib/Socket/messages-recv.js +2193 -0
  60. package/lib/Socket/messages-send.js +4141 -0
  61. package/lib/Socket/mex.js +53 -0
  62. package/lib/Socket/newsletter.js +291 -0
  63. package/lib/Socket/privacy.js +458 -0
  64. package/lib/Socket/registration.js +440 -0
  65. package/lib/Socket/socket.js +1042 -0
  66. package/lib/Socket/status-actions.js +287 -0
  67. package/lib/Socket/username.js +241 -0
  68. package/lib/Store/index.js +16 -0
  69. package/lib/Store/make-cache-manager-store.js +101 -0
  70. package/lib/Store/make-in-memory-store.js +432 -0
  71. package/lib/Store/make-ordered-dictionary.js +90 -0
  72. package/lib/Store/object-repository.js +35 -0
  73. package/lib/Types/Auth.js +13 -0
  74. package/lib/Types/Bussines.js +13 -0
  75. package/lib/Types/Call.js +13 -0
  76. package/lib/Types/Chat.js +19 -0
  77. package/lib/Types/Contact.js +13 -0
  78. package/lib/Types/Events.js +13 -0
  79. package/lib/Types/GroupMetadata.js +13 -0
  80. package/lib/Types/Label.js +36 -0
  81. package/lib/Types/LabelAssociation.js +18 -0
  82. package/lib/Types/Message.js +30 -0
  83. package/lib/Types/Mex.js +53 -0
  84. package/lib/Types/Product.js +13 -0
  85. package/lib/Types/RichType.js +34 -0
  86. package/lib/Types/Signal.js +13 -0
  87. package/lib/Types/Socket.js +14 -0
  88. package/lib/Types/State.js +60 -0
  89. package/lib/Types/USync.js +13 -0
  90. package/lib/Types/index.js +37 -0
  91. package/lib/Utils/auth-utils.js +313 -0
  92. package/lib/Utils/ban-checker.js +48 -0
  93. package/lib/Utils/bot-capabilities.js +96 -0
  94. package/lib/Utils/bot-planning-replay.js +177 -0
  95. package/lib/Utils/browser-utils.js +40 -0
  96. package/lib/Utils/business.js +242 -0
  97. package/lib/Utils/c2582.js +147 -0
  98. package/lib/Utils/chat-utils.js +905 -0
  99. package/lib/Utils/companion-reg-client-utils.js +104 -0
  100. package/lib/Utils/consumer-application.js +114 -0
  101. package/lib/Utils/crypto.js +129 -0
  102. package/lib/Utils/decode-wa-message.js +496 -0
  103. package/lib/Utils/direct-chat-theme.js +164 -0
  104. package/lib/Utils/event-buffer.js +601 -0
  105. package/lib/Utils/experimental-proto.js +206 -0
  106. package/lib/Utils/games/miniapp.js +17 -0
  107. package/lib/Utils/games/slot-machine.js +270 -0
  108. package/lib/Utils/games/website-preview.js +306 -0
  109. package/lib/Utils/generics.js +402 -0
  110. package/lib/Utils/group-history.js +68 -0
  111. package/lib/Utils/group-wallpaper.js +168 -0
  112. package/lib/Utils/history.js +162 -0
  113. package/lib/Utils/identity-change-handler.js +60 -0
  114. package/lib/Utils/index.js +61 -0
  115. package/lib/Utils/jid-display-normalization.js +221 -0
  116. package/lib/Utils/link-preview.js +96 -0
  117. package/lib/Utils/logger.js +14 -0
  118. package/lib/Utils/lt-hash.js +19 -0
  119. package/lib/Utils/make-mutex.js +44 -0
  120. package/lib/Utils/message-composer.js +709 -0
  121. package/lib/Utils/message-inspect.js +79 -0
  122. package/lib/Utils/message-retry-manager.js +253 -0
  123. package/lib/Utils/message-security.js +167 -0
  124. package/lib/Utils/messages-media.js +1027 -0
  125. package/lib/Utils/messages.js +2467 -0
  126. package/lib/Utils/meta-ai-msmsg.js +215 -0
  127. package/lib/Utils/meta-compositing.js +239 -0
  128. package/lib/Utils/native-flow.js +158 -0
  129. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  130. package/lib/Utils/newsletter-status-utils.js +152 -0
  131. package/lib/Utils/noise-handler.js +212 -0
  132. package/lib/Utils/offline-node-processor.js +51 -0
  133. package/lib/Utils/poll-manager.js +206 -0
  134. package/lib/Utils/portable-compat.js +12 -0
  135. package/lib/Utils/pre-key-manager.js +117 -0
  136. package/lib/Utils/process-message.js +610 -0
  137. package/lib/Utils/reporting-utils.js +269 -0
  138. package/lib/Utils/rich-message-utils.js +2841 -0
  139. package/lib/Utils/scheduled-message.js +107 -0
  140. package/lib/Utils/signal.js +212 -0
  141. package/lib/Utils/source-grep.js +57 -0
  142. package/lib/Utils/stanza-ack.js +49 -0
  143. package/lib/Utils/sticker-annotation.js +87 -0
  144. package/lib/Utils/sync-action-utils.js +59 -0
  145. package/lib/Utils/tc-token-utils.js +174 -0
  146. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  147. package/lib/Utils/use-single-file-auth-state.js +108 -0
  148. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  149. package/lib/Utils/validate-connection.js +221 -0
  150. package/lib/Utils/view-once-utils.js +218 -0
  151. package/lib/Utils/voip-rekey.js +32 -0
  152. package/lib/Utils/website-preview.js +27 -0
  153. package/lib/Utils/welcome-flow.js +228 -0
  154. package/lib/Utils/x4r1s3.js +144 -0
  155. package/lib/WABinary/constants.js +1475 -0
  156. package/lib/WABinary/decode.js +273 -0
  157. package/lib/WABinary/encode.js +231 -0
  158. package/lib/WABinary/generic-utils.js +242 -0
  159. package/lib/WABinary/index.js +17 -0
  160. package/lib/WABinary/jid-utils.js +107 -0
  161. package/lib/WABinary/types.js +13 -0
  162. package/lib/WAM/BinaryInfo.js +21 -0
  163. package/lib/WAM/constants.js +22864 -0
  164. package/lib/WAM/encode.js +161 -0
  165. package/lib/WAM/index.js +15 -0
  166. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  167. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  168. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  169. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  170. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  171. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  172. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  173. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  174. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  175. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  176. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  177. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  178. package/lib/WAUSync/Protocols/index.js +24 -0
  179. package/lib/WAUSync/USyncQuery.js +213 -0
  180. package/lib/WAUSync/USyncUser.js +66 -0
  181. package/lib/WAUSync/index.js +15 -0
  182. package/lib/antiban.cjs +4726 -0
  183. package/lib/index.d.ts +1895 -0
  184. package/lib/index.js +41 -0
  185. package/package.json +125 -4
@@ -0,0 +1,561 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Socket/groups.js
5
+ * About: Groups module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: buildReportNode, buildGroupStatusRevokeMessage, makeGroupsSocket, extractGroupMetadata
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 { Boom } from '@hapi/boom';
14
+ import { proto } from '../../WAProto/index.js';
15
+ import { WAMessageAddressingMode, WAMessageStubType } from '../Types/index.js';
16
+ import { generateMessageIDV2, unixTimestampSeconds } from '../Utils/index.js';
17
+ import { getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString, isJidGroup, isLidUser, isPnUser, jidEncode, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js';
18
+ import { makeChatsSocket } from './chats.js';
19
+
20
+ export const buildReportNode = (jid, messageKeys = []) => ({
21
+ tag: 'spam_list',
22
+ attrs: {},
23
+ content: [{
24
+ tag: 'spam',
25
+ attrs: { jid },
26
+ content: messageKeys.map(key => {
27
+ if (!key?.id) {
28
+ throw new Boom('Every reported message key must include an id', { statusCode: 400 });
29
+ }
30
+ return {
31
+ tag: 'message',
32
+ attrs: {
33
+ id: key.id,
34
+ ...(key.fromMe !== undefined ? { from_me: key.fromMe ? 'true' : 'false' } : {}),
35
+ ...(key.participant ? { participant: jidNormalizedUser(key.participant) } : {})
36
+ }
37
+ };
38
+ })
39
+ }]
40
+ });
41
+
42
+ export const buildGroupStatusRevokeMessage = (jid, key) => ({
43
+ groupStatusMessageV2: {
44
+ message: {
45
+ protocolMessage: {
46
+ key: {
47
+ remoteJid: jid,
48
+ fromMe: key.fromMe ?? true,
49
+ id: key.id,
50
+ ...(key.participant ? { participant: jidNormalizedUser(key.participant) } : {})
51
+ },
52
+ type: proto.Message.ProtocolMessage.Type.REVOKE
53
+ }
54
+ }
55
+ }
56
+ });
57
+
58
+ export const makeGroupsSocket = (config) => {
59
+ const sock = makeChatsSocket(config);
60
+ const { authState, ev, query, relayMessage, updateBlockStatus, upsertMessage } = sock;
61
+ const reportJid = async (jid, messageKeys = []) => query({
62
+ tag: 'iq',
63
+ attrs: { type: 'set', xmlns: 'spam', to: S_WHATSAPP_NET },
64
+ content: [buildReportNode(jid, messageKeys)]
65
+ });
66
+ const groupQuery = async (jid, type, content) => query({
67
+ tag: 'iq',
68
+ attrs: {
69
+ type,
70
+ xmlns: 'w:g2',
71
+ to: jid
72
+ },
73
+ content
74
+ });
75
+ const persistParticipantLidMappings = async (participantLists) => {
76
+ const pairs = [];
77
+ for (const participants of participantLists) {
78
+ for (const p of participants || []) {
79
+ if (p.phoneNumber)
80
+ pairs.push({ lid: p.id, pn: p.phoneNumber });
81
+ else if (p.lid)
82
+ pairs.push({ lid: p.lid, pn: p.id });
83
+ }
84
+ }
85
+ if (!pairs.length)
86
+ return;
87
+ try {
88
+ await sock.signalRepository.lidMapping.storeLIDPNMappings(pairs);
89
+ }
90
+ catch (error) {
91
+ sock.logger?.warn?.({ error }, 'failed to store LID/PN mappings from group metadata');
92
+ }
93
+ };
94
+ const groupMetadata = async (jid) => {
95
+ const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
96
+ const metadata = extractGroupMetadata(result);
97
+ persistParticipantLidMappings([metadata.participants]).catch(() => { });
98
+ return metadata;
99
+ };
100
+ /**
101
+ * Acknowledge a group. Ported from WhatsApp Web's WASmaxGroupsAcknowledgeGroupRPC
102
+ * (`<iq to=jid xmlns=w:g2 type=set><ack/></iq>`).
103
+ */
104
+ const groupAcknowledge = async (jid) => {
105
+ await groupQuery(jid, 'set', [{ tag: 'ack', attrs: {} }]);
106
+ };
107
+ /**
108
+ * Get the participants of a community's linked/sub groups. Ported from
109
+ * WhatsApp Web's WASmaxGroupsGetLinkedGroupsParticipantsRPC.
110
+ * @returns {Promise<Array<{ jid: string, phoneNumber?: string }>>}
111
+ */
112
+ const groupGetLinkedParticipants = async (jid) => {
113
+ const result = await groupQuery(jid, 'get', [{ tag: 'linked_groups_participants', attrs: {} }]);
114
+ const node = getBinaryNodeChild(result, 'linked_groups_participants');
115
+ return getBinaryNodeChildren(node, 'participant').map(p => ({
116
+ jid: p.attrs.jid,
117
+ phoneNumber: p.attrs.phone_number || p.attrs.pn || undefined
118
+ }));
119
+ };
120
+ /**
121
+ * Join a community's linked/sub group (may raise a membership approval request).
122
+ * Ported from WhatsApp Web's WASmaxGroupsJoinLinkedGroupRPC.
123
+ * @param {string} parentJid community/parent group to address
124
+ * @param {string} linkedGroupJid linked/sub group to join
125
+ * @param {string} [type]
126
+ */
127
+ const groupJoinLinked = async (parentJid, linkedGroupJid, type) => {
128
+ const result = await groupQuery(parentJid, 'set', [
129
+ { tag: 'join_linked_group', attrs: { jid: linkedGroupJid, ...(type ? { type } : {}) } }
130
+ ]);
131
+ return { approvalRequested: !!getBinaryNodeChild(result, 'membership_approval_request') };
132
+ };
133
+ /**
134
+ * Batch-fetch group profile pictures via w:g2. Ported from WhatsApp Web's
135
+ * WASmaxGroupsGetGroupProfilePicturesRPC.
136
+ * @param {string[]} jids group jids
137
+ * @param {'preview' | 'image'} [type]
138
+ */
139
+ const getGroupProfilePictures = async (jids, type = 'preview') => {
140
+ const result = await groupQuery(S_WHATSAPP_NET, 'get', [
141
+ {
142
+ tag: 'pictures',
143
+ attrs: {},
144
+ content: jids.map(id => ({ tag: 'picture', attrs: { id, type } }))
145
+ }
146
+ ]);
147
+ return getBinaryNodeChildren(result, 'picture').map(pic => ({
148
+ jid: pic.attrs.id || pic.attrs.jid,
149
+ type: pic.attrs.type,
150
+ directPath: pic.attrs['direct_path'],
151
+ url: pic.attrs.url
152
+ }));
153
+ };
154
+ /**
155
+ * Create a sub-group suggestion for a community. Ported from WhatsApp Web's
156
+ * WASmaxGroupsCreateSubGroupSuggestionRPC. The suggestion body (new vs existing
157
+ * groups) is caller-provided.
158
+ * @param {string} parentJid community/parent group to address
159
+ * @param {Array<{ tag: string, attrs?: object, content?: any }>} suggestion child node(s)
160
+ */
161
+ const groupCreateSubGroupSuggestion = async (parentJid, suggestion) => {
162
+ await groupQuery(parentJid, 'set', [{ tag: 'sub_group_suggestion', attrs: {}, content: suggestion }]);
163
+ };
164
+ /**
165
+ * Approve, reject, or cancel sub-group suggestions for a community. Ported from
166
+ * WhatsApp Web's WASmaxGroupsSubGroupSuggestionsActionRPC.
167
+ * approve/reject address suggestions by creator jid; cancel addresses them by
168
+ * the suggested group's jid.
169
+ * @param {string} parentJid community/parent group to address
170
+ * @param {'approve' | 'reject' | 'cancel'} action
171
+ * @param {Array<{ creator?: string, jid?: string }>} suggestions
172
+ */
173
+ const groupSubGroupSuggestionsAction = async (parentJid, action, suggestions) => {
174
+ await groupQuery(parentJid, 'set', [
175
+ {
176
+ tag: 'sub_group_suggestions_action',
177
+ attrs: {},
178
+ content: [
179
+ {
180
+ tag: action,
181
+ attrs: {},
182
+ content: suggestions.map(s => ({
183
+ tag: 'sub_group_suggestion',
184
+ attrs: action === 'cancel' ? { jid: s.jid } : { creator: s.creator }
185
+ }))
186
+ }
187
+ ]
188
+ }
189
+ ]);
190
+ };
191
+ const groupFetchAllParticipating = async () => {
192
+ const result = await query({
193
+ tag: 'iq',
194
+ attrs: {
195
+ to: '@g.us',
196
+ xmlns: 'w:g2',
197
+ type: 'get'
198
+ },
199
+ content: [
200
+ {
201
+ tag: 'participating',
202
+ attrs: {},
203
+ content: [
204
+ { tag: 'participants', attrs: {} },
205
+ { tag: 'description', attrs: {} }
206
+ ]
207
+ }
208
+ ]
209
+ });
210
+ const data = {};
211
+ const groupsChild = getBinaryNodeChild(result, 'groups');
212
+ if (groupsChild) {
213
+ const groups = getBinaryNodeChildren(groupsChild, 'group');
214
+ for (const groupNode of groups) {
215
+ const meta = extractGroupMetadata({
216
+ tag: 'result',
217
+ attrs: {},
218
+ content: [groupNode]
219
+ });
220
+ data[meta.id] = meta;
221
+ }
222
+ }
223
+ // TODO: properly parse LID / PN DATA
224
+ sock.ev.emit('groups.update', Object.values(data));
225
+ return data;
226
+ };
227
+ sock.ws.on('CB:ib,,dirty', async (node) => {
228
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
229
+ if (attrs.type !== 'groups') {
230
+ return;
231
+ }
232
+ await groupFetchAllParticipating();
233
+ await sock.cleanDirtyBits('groups');
234
+ });
235
+ return {
236
+ ...sock,
237
+ groupQuery,
238
+ groupMetadata,
239
+ groupAcknowledge,
240
+ groupGetLinkedParticipants,
241
+ groupJoinLinked,
242
+ getGroupProfilePictures,
243
+ groupCreateSubGroupSuggestion,
244
+ groupSubGroupSuggestionsAction,
245
+ groupCreate: async (subject, participants) => {
246
+ const key = generateMessageIDV2();
247
+ const result = await groupQuery('@g.us', 'set', [
248
+ {
249
+ tag: 'create',
250
+ attrs: {
251
+ subject,
252
+ key
253
+ },
254
+ content: participants.map(jid => ({
255
+ tag: 'participant',
256
+ attrs: { jid }
257
+ }))
258
+ }
259
+ ]);
260
+ return extractGroupMetadata(result);
261
+ },
262
+ groupLeave: async (id) => {
263
+ await groupQuery('@g.us', 'set', [
264
+ {
265
+ tag: 'leave',
266
+ attrs: {},
267
+ content: [{ tag: 'group', attrs: { id } }]
268
+ }
269
+ ]);
270
+ },
271
+ groupUpdateSubject: async (jid, subject) => {
272
+ await groupQuery(jid, 'set', [
273
+ {
274
+ tag: 'subject',
275
+ attrs: {},
276
+ content: Buffer.from(subject, 'utf-8')
277
+ }
278
+ ]);
279
+ },
280
+ groupRequestParticipantsList: async (jid) => {
281
+ const result = await groupQuery(jid, 'get', [
282
+ {
283
+ tag: 'membership_approval_requests',
284
+ attrs: {}
285
+ }
286
+ ]);
287
+ const node = getBinaryNodeChild(result, 'membership_approval_requests');
288
+ const participants = getBinaryNodeChildren(node, 'membership_approval_request');
289
+ return participants.map(v => v.attrs);
290
+ },
291
+ groupRequestParticipantsUpdate: async (jid, participants, action) => {
292
+ const result = await groupQuery(jid, 'set', [
293
+ {
294
+ tag: 'membership_requests_action',
295
+ attrs: {},
296
+ content: [
297
+ {
298
+ tag: action,
299
+ attrs: {},
300
+ content: participants.map(jid => ({
301
+ tag: 'participant',
302
+ attrs: { jid }
303
+ }))
304
+ }
305
+ ]
306
+ }
307
+ ]);
308
+ const node = getBinaryNodeChild(result, 'membership_requests_action');
309
+ const nodeAction = getBinaryNodeChild(node, action);
310
+ const participantsAffected = getBinaryNodeChildren(nodeAction, 'participant');
311
+ return participantsAffected.map(p => {
312
+ return { status: p.attrs.error || '200', jid: p.attrs.jid };
313
+ });
314
+ },
315
+ groupParticipantsUpdate: async (jid, participants, action) => {
316
+ const result = await groupQuery(jid, 'set', [
317
+ {
318
+ tag: action,
319
+ attrs: {},
320
+ content: participants.map(jid => ({
321
+ tag: 'participant',
322
+ attrs: { jid }
323
+ }))
324
+ }
325
+ ]);
326
+ const node = getBinaryNodeChild(result, action);
327
+ const participantsAffected = getBinaryNodeChildren(node, 'participant');
328
+ return participantsAffected.map(p => {
329
+ return { status: p.attrs.error || '200', jid: p.attrs.jid, content: p };
330
+ });
331
+ },
332
+ groupUpdateDescription: async (jid, description) => {
333
+ const metadata = await groupMetadata(jid);
334
+ const prev = metadata.descId ?? null;
335
+ await groupQuery(jid, 'set', [
336
+ {
337
+ tag: 'description',
338
+ attrs: {
339
+ ...(description ? { id: generateMessageIDV2() } : { delete: 'true' }),
340
+ ...(prev ? { prev } : {})
341
+ },
342
+ content: description ? [{ tag: 'body', attrs: {}, content: Buffer.from(description, 'utf-8') }] : undefined
343
+ }
344
+ ]);
345
+ },
346
+ groupInviteCode: async (jid) => {
347
+ const result = await groupQuery(jid, 'get', [{ tag: 'invite', attrs: {} }]);
348
+ const inviteNode = getBinaryNodeChild(result, 'invite');
349
+ return inviteNode?.attrs.code;
350
+ },
351
+ groupRevokeInvite: async (jid) => {
352
+ const result = await groupQuery(jid, 'set', [{ tag: 'invite', attrs: {} }]);
353
+ const inviteNode = getBinaryNodeChild(result, 'invite');
354
+ return inviteNode?.attrs.code;
355
+ },
356
+ groupAcceptInvite: async (code) => {
357
+ const results = await groupQuery('@g.us', 'set', [{ tag: 'invite', attrs: { code } }]);
358
+ const result = getBinaryNodeChild(results, 'group');
359
+ return result?.attrs.jid;
360
+ },
361
+ /**
362
+ * revoke a v4 invite for someone
363
+ * @param groupJid group jid
364
+ * @param invitedJid jid of person you invited
365
+ * @returns true if successful
366
+ */
367
+ groupRevokeInviteV4: async (groupJid, invitedJid) => {
368
+ const result = await groupQuery(groupJid, 'set', [
369
+ { tag: 'revoke', attrs: {}, content: [{ tag: 'participant', attrs: { jid: invitedJid } }] }
370
+ ]);
371
+ return !!result;
372
+ },
373
+ /**
374
+ * accept a GroupInviteMessage
375
+ * @param key the key of the invite message, or optionally only provide the jid of the person who sent the invite
376
+ * @param inviteMessage the message to accept
377
+ */
378
+ groupAcceptInviteV4: ev.createBufferedFunction(async (key, inviteMessage) => {
379
+ key = typeof key === 'string' ? { remoteJid: key } : key;
380
+ const results = await groupQuery(inviteMessage.groupJid, 'set', [
381
+ {
382
+ tag: 'accept',
383
+ attrs: {
384
+ code: inviteMessage.inviteCode,
385
+ expiration: inviteMessage.inviteExpiration.toString(),
386
+ admin: key.remoteJid
387
+ }
388
+ }
389
+ ]);
390
+ // if we have the full message key
391
+ // update the invite message to be expired
392
+ if (key.id) {
393
+ // create new invite message that is expired
394
+ inviteMessage = proto.Message.GroupInviteMessage.fromObject(inviteMessage);
395
+ inviteMessage.inviteExpiration = 0;
396
+ inviteMessage.inviteCode = '';
397
+ ev.emit('messages.update', [
398
+ {
399
+ key,
400
+ update: {
401
+ message: {
402
+ groupInviteMessage: inviteMessage
403
+ }
404
+ }
405
+ }
406
+ ]);
407
+ }
408
+ // generate the group add message
409
+ await upsertMessage({
410
+ key: {
411
+ remoteJid: inviteMessage.groupJid,
412
+ id: generateMessageIDV2(sock.user?.id),
413
+ fromMe: false,
414
+ participant: key.remoteJid
415
+ },
416
+ messageStubType: WAMessageStubType.GROUP_PARTICIPANT_ADD,
417
+ messageStubParameters: [JSON.stringify(authState.creds.me)],
418
+ participant: key.remoteJid,
419
+ messageTimestamp: unixTimestampSeconds()
420
+ }, 'notify');
421
+ return results.attrs.from;
422
+ }),
423
+ groupGetInviteInfo: async (code) => {
424
+ const results = await groupQuery('@g.us', 'get', [{ tag: 'invite', attrs: { code } }]);
425
+ return extractGroupMetadata(results);
426
+ },
427
+ groupToggleEphemeral: async (jid, ephemeralExpiration) => {
428
+ const content = ephemeralExpiration
429
+ ? { tag: 'ephemeral', attrs: { expiration: ephemeralExpiration.toString() } }
430
+ : { tag: 'not_ephemeral', attrs: {} };
431
+ await groupQuery(jid, 'set', [content]);
432
+ },
433
+ groupSettingUpdate: async (jid, setting) => {
434
+ await groupQuery(jid, 'set', [{ tag: setting, attrs: {} }]);
435
+ },
436
+ groupMemberAddMode: async (jid, mode) => {
437
+ await groupQuery(jid, 'set', [{ tag: 'member_add_mode', attrs: {}, content: mode }]);
438
+ },
439
+ groupJoinApprovalMode: async (jid, mode) => {
440
+ await groupQuery(jid, 'set', [
441
+ { tag: 'membership_approval_mode', attrs: {}, content: [{ tag: 'group_join', attrs: { state: mode } }] }
442
+ ]);
443
+ },
444
+ groupFetchAllParticipating,
445
+ /** Report a contact to WhatsApp, then block it after the report succeeds. */
446
+ reportContact: async (jid, messageKeys = []) => {
447
+ const normalizedJid = jidNormalizedUser(jid);
448
+ if (!isPnUser(normalizedJid) && !isLidUser(normalizedJid)) {
449
+ throw new Boom('reportContact requires a valid contact JID', { statusCode: 400 });
450
+ }
451
+ const reportResult = await reportJid(normalizedJid, messageKeys);
452
+ await updateBlockStatus(normalizedJid, 'block');
453
+ return reportResult;
454
+ },
455
+ /** Report a group to WhatsApp, then leave it after the report succeeds. */
456
+ reportGroup: async (jid, messageKeys = []) => {
457
+ if (!isJidGroup(jid)) {
458
+ throw new Boom('reportGroup requires a valid group JID', { statusCode: 400 });
459
+ }
460
+ const reportResult = await reportJid(jid, messageKeys);
461
+ await groupQuery('@g.us', 'set', [{
462
+ tag: 'leave',
463
+ attrs: {},
464
+ content: [{ tag: 'group', attrs: { id: jid } }]
465
+ }]);
466
+ return reportResult;
467
+ },
468
+ /** Revoke a previously sent group status using its original message key. */
469
+ deleteGroupStatus: async (jid, key) => {
470
+ if (!isJidGroup(jid)) {
471
+ throw new Boom('deleteGroupStatus requires a valid group JID', { statusCode: 400 });
472
+ }
473
+ if (!key?.id) {
474
+ throw new Boom('deleteGroupStatus requires a message key with an id', { statusCode: 400 });
475
+ }
476
+ if (key.remoteJid && key.remoteJid !== jid) {
477
+ throw new Boom('The group status key does not belong to the target group', { statusCode: 400 });
478
+ }
479
+ return relayMessage(
480
+ jid,
481
+ buildGroupStatusRevokeMessage(jid, key),
482
+ { messageId: generateMessageIDV2(authState.creds.me?.id) }
483
+ );
484
+ }
485
+ };
486
+ };
487
+ export const extractGroupMetadata = (result) => {
488
+ const group = getBinaryNodeChild(result, 'group');
489
+ if (!group) {
490
+ // Mirror WAWeb: surface server/client errors with their code+text instead of crashing.
491
+ const errorNode = getBinaryNodeChild(result, 'error');
492
+ if (errorNode) {
493
+ const code = errorNode.attrs.code ? +errorNode.attrs.code : 500;
494
+ const text = errorNode.attrs.text || 'group metadata query failed';
495
+ throw new Boom(text, { statusCode: code, data: errorNode });
496
+ }
497
+ throw new Boom('Invalid group metadata response: missing <group> node', { data: result });
498
+ }
499
+ if (!group.attrs.id) {
500
+ throw new Boom('Invalid group metadata response: missing group id', { data: group });
501
+ }
502
+ const descChild = getBinaryNodeChild(group, 'description');
503
+ let desc;
504
+ let descId;
505
+ let descOwner;
506
+ let descOwnerPn;
507
+ let descOwnerUsername;
508
+ let descTime;
509
+ if (descChild) {
510
+ desc = getBinaryNodeChildString(descChild, 'body');
511
+ descOwner = descChild.attrs.participant ? jidNormalizedUser(descChild.attrs.participant) : undefined;
512
+ descOwnerPn = descChild.attrs.participant_pn ? jidNormalizedUser(descChild.attrs.participant_pn) : undefined;
513
+ descOwnerUsername = descChild.attrs.participant_username || undefined;
514
+ descTime = +descChild.attrs.t;
515
+ descId = descChild.attrs.id;
516
+ }
517
+ const groupId = group.attrs.id.includes('@') ? group.attrs.id : jidEncode(group.attrs.id, 'g.us');
518
+ const eph = getBinaryNodeChild(group, 'ephemeral')?.attrs.expiration;
519
+ const memberAddMode = getBinaryNodeChildString(group, 'member_add_mode') === 'all_member_add';
520
+ const metadata = {
521
+ id: groupId,
522
+ notify: group.attrs.notify,
523
+ addressingMode: group.attrs.addressing_mode === 'lid' ? WAMessageAddressingMode.LID : WAMessageAddressingMode.PN,
524
+ subject: group.attrs.subject,
525
+ subjectOwner: group.attrs.s_o,
526
+ subjectOwnerPn: group.attrs.s_o_pn,
527
+ subjectOwnerUsername: group.attrs.s_o_username,
528
+ subjectTime: +group.attrs.s_t,
529
+ size: group.attrs.size ? +group.attrs.size : getBinaryNodeChildren(group, 'participant').length,
530
+ creation: +group.attrs.creation,
531
+ owner: group.attrs.creator ? jidNormalizedUser(group.attrs.creator) : undefined,
532
+ ownerPn: group.attrs.creator_pn ? jidNormalizedUser(group.attrs.creator_pn) : undefined,
533
+ ownerUsername: group.attrs.creator_username || undefined,
534
+ owner_country_code: group.attrs.creator_country_code,
535
+ desc,
536
+ descId,
537
+ descOwner,
538
+ descOwnerPn,
539
+ descOwnerUsername,
540
+ descTime,
541
+ linkedParent: getBinaryNodeChild(group, 'linked_parent')?.attrs.jid || undefined,
542
+ restrict: !!getBinaryNodeChild(group, 'locked'),
543
+ announce: !!getBinaryNodeChild(group, 'announcement'),
544
+ isCommunity: !!getBinaryNodeChild(group, 'parent'),
545
+ isCommunityAnnounce: !!getBinaryNodeChild(group, 'default_sub_group'),
546
+ joinApprovalMode: !!getBinaryNodeChild(group, 'membership_approval_mode'),
547
+ memberAddMode,
548
+ participants: getBinaryNodeChildren(group, 'participant').map(({ attrs }) => {
549
+ // TODO: Store LID MAPPINGS
550
+ return {
551
+ id: attrs.jid,
552
+ phoneNumber: isLidUser(attrs.jid) && isPnUser(attrs.phone_number) ? attrs.phone_number : undefined,
553
+ lid: isPnUser(attrs.jid) && isLidUser(attrs.lid) ? attrs.lid : undefined,
554
+ username: attrs.participant_username || attrs.username || undefined,
555
+ admin: (attrs.type || null)
556
+ };
557
+ }),
558
+ ephemeralDuration: eph ? +eph : undefined
559
+ };
560
+ return metadata;
561
+ };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Socket/index.js
5
+ * About: Socket module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: checkStatusWA
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 { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
14
+ import { makeCommunitiesSocket } from './communities.js';
15
+ import { makeInteropSocket } from './interop.js';
16
+ import { makePrivacySocket } from './privacy.js';
17
+ import { makeRegistrationSocket } from './registration.js';
18
+ import { makeManagedAccountSocket } from './managed-account.js';
19
+ import { makeGraphQLSocket } from './graphql.js';
20
+ import { checkStatusWA } from './ban-checker.js';
21
+
22
+ // export the last socket layer
23
+ const makeWASocket = (config) => {
24
+ const userExplicitSyncFlag = typeof config?.syncFullHistory === 'boolean';
25
+ const initialFullSyncDone = !!config?.auth?.creds?.initialFullSyncDone;
26
+ const effectiveSyncFullHistory = userExplicitSyncFlag ? config.syncFullHistory : !initialFullSyncDone;
27
+ const newConfig = {
28
+ ...DEFAULT_CONNECTION_CONFIG,
29
+ ...config,
30
+ syncFullHistory: effectiveSyncFullHistory
31
+ };
32
+ newConfig.logger?.debug?.(
33
+ { initialFullSyncDone, effectiveSyncFullHistory, userExplicitSyncFlag },
34
+ 'computed syncFullHistory policy'
35
+ );
36
+
37
+ const baseSock = makeCommunitiesSocket(newConfig);
38
+ const interopSock = makeInteropSocket(baseSock);
39
+ const privacySock = makePrivacySocket(interopSock);
40
+ const registrationSock = makeRegistrationSocket(privacySock);
41
+ const managedSock = makeManagedAccountSocket(registrationSock);
42
+ const sock = makeGraphQLSocket(managedSock);
43
+ sock.checkStatusWA = checkStatusWA;
44
+
45
+ return sock;
46
+ };
47
+
48
+ export { checkStatusWA };
49
+ export default makeWASocket;