dct-dev-private-baileys 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 (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.MD +110 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5619 -0
  5. package/WAProto/index.js +169661 -0
  6. package/engine-requirements.js +10 -0
  7. package/lib/Api/Internet/growagarden.js +30 -0
  8. package/lib/Api/creator.json +12 -0
  9. package/lib/Api/downloader/tiktokdownload.js +132 -0
  10. package/lib/Api/index.js +38 -0
  11. package/lib/Api/nsfw/loli.js +79 -0
  12. package/lib/Api/stalker/githubstalk.js +46 -0
  13. package/lib/Api/stalker/stalkroblox.js +94 -0
  14. package/lib/Api/stalker/tiktokstalk.js +68 -0
  15. package/lib/Api/tools/ssweb.js +38 -0
  16. package/lib/Defaults/baileys-version.json +3 -0
  17. package/lib/Defaults/index.js +122 -0
  18. package/lib/Defaults/phonenumber_mcc.json +223 -0
  19. package/lib/Signal/Group/ciphertext-message.js +15 -0
  20. package/lib/Signal/Group/group-session-builder.js +64 -0
  21. package/lib/Signal/Group/group_cipher.js +96 -0
  22. package/lib/Signal/Group/index.js +57 -0
  23. package/lib/Signal/Group/keyhelper.js +55 -0
  24. package/lib/Signal/Group/queue-job.js +57 -0
  25. package/lib/Signal/Group/sender-chain-key.js +34 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  27. package/lib/Signal/Group/sender-key-message.js +69 -0
  28. package/lib/Signal/Group/sender-key-name.js +51 -0
  29. package/lib/Signal/Group/sender-key-record.js +53 -0
  30. package/lib/Signal/Group/sender-key-state.js +99 -0
  31. package/lib/Signal/Group/sender-message-key.js +29 -0
  32. package/lib/Signal/libsignal.js +174 -0
  33. package/lib/Socket/Client/index.js +18 -0
  34. package/lib/Socket/Client/types.js +13 -0
  35. package/lib/Socket/Client/websocket.js +111 -0
  36. package/lib/Socket/Thandler.js +501 -0
  37. package/lib/Socket/business.js +266 -0
  38. package/lib/Socket/chats.js +1138 -0
  39. package/lib/Socket/communities.js +441 -0
  40. package/lib/Socket/groups.js +332 -0
  41. package/lib/Socket/index.js +43 -0
  42. package/lib/Socket/messages-recv.js +1538 -0
  43. package/lib/Socket/messages-send.js +1207 -0
  44. package/lib/Socket/newsletter.js +379 -0
  45. package/lib/Socket/socket.js +849 -0
  46. package/lib/Socket/usync.js +70 -0
  47. package/lib/Store/index.js +8 -0
  48. package/lib/Store/make-in-memory-store.js +533 -0
  49. package/lib/Store/make-ordered-dictionary.js +81 -0
  50. package/lib/Store/object-repository.js +27 -0
  51. package/lib/Types/Auth.js +2 -0
  52. package/lib/Types/Call.js +2 -0
  53. package/lib/Types/Chat.js +4 -0
  54. package/lib/Types/Contact.js +2 -0
  55. package/lib/Types/Events.js +2 -0
  56. package/lib/Types/GroupMetadata.js +2 -0
  57. package/lib/Types/Label.js +27 -0
  58. package/lib/Types/LabelAssociation.js +9 -0
  59. package/lib/Types/Message.js +7 -0
  60. package/lib/Types/Newsletter.js +18 -0
  61. package/lib/Types/Product.js +2 -0
  62. package/lib/Types/Signal.js +2 -0
  63. package/lib/Types/Socket.js +2 -0
  64. package/lib/Types/State.js +2 -0
  65. package/lib/Types/USync.js +2 -0
  66. package/lib/Types/index.js +42 -0
  67. package/lib/Utils/async-iterable.js +40 -0
  68. package/lib/Utils/audioToBuffer.js +29 -0
  69. package/lib/Utils/auth-utils.js +200 -0
  70. package/lib/Utils/baileys-event-stream.js +67 -0
  71. package/lib/Utils/browser-utils.js +35 -0
  72. package/lib/Utils/business.js +234 -0
  73. package/lib/Utils/chat-utils.js +730 -0
  74. package/lib/Utils/crypto.js +193 -0
  75. package/lib/Utils/decode-wa-message.js +207 -0
  76. package/lib/Utils/event-buffer.js +565 -0
  77. package/lib/Utils/generics.js +432 -0
  78. package/lib/Utils/history.js +94 -0
  79. package/lib/Utils/index.js +36 -0
  80. package/lib/Utils/link-preview.js +126 -0
  81. package/lib/Utils/logger.js +7 -0
  82. package/lib/Utils/lt-hash.js +51 -0
  83. package/lib/Utils/make-mutex.js +43 -0
  84. package/lib/Utils/message-retry-manager.js +128 -0
  85. package/lib/Utils/messages-media.js +926 -0
  86. package/lib/Utils/messages.js +1105 -0
  87. package/lib/Utils/noise-handler.js +150 -0
  88. package/lib/Utils/process-message.js +404 -0
  89. package/lib/Utils/resolveJid.js +48 -0
  90. package/lib/Utils/signal.js +153 -0
  91. package/lib/Utils/streamToBuffer.js +15 -0
  92. package/lib/Utils/use-multi-file-auth-state.js +122 -0
  93. package/lib/Utils/validate-connection.js +229 -0
  94. package/lib/WABinary/constants.js +1303 -0
  95. package/lib/WABinary/decode.js +265 -0
  96. package/lib/WABinary/encode.js +250 -0
  97. package/lib/WABinary/generic-utils.js +110 -0
  98. package/lib/WABinary/index.js +21 -0
  99. package/lib/WABinary/jid-utils.js +85 -0
  100. package/lib/WABinary/types.js +2 -0
  101. package/lib/WAM/BinaryInfo.js +13 -0
  102. package/lib/WAM/constants.js +15350 -0
  103. package/lib/WAM/encode.js +155 -0
  104. package/lib/WAM/index.js +19 -0
  105. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  106. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  107. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  108. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  109. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  110. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  111. package/lib/WAUSync/Protocols/index.js +20 -0
  112. package/lib/WAUSync/USyncQuery.js +89 -0
  113. package/lib/WAUSync/USyncUser.js +26 -0
  114. package/lib/WAUSync/index.js +19 -0
  115. package/lib/index.js +91 -0
  116. package/package.json +127 -0
@@ -0,0 +1,1538 @@
1
+ "use strict";
2
+ var __importDefault =
3
+ (this && this.__importDefault) ||
4
+ function (mod) {
5
+ return mod && mod.__esModule ? mod : { default: mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.makeMessagesRecvSocket = void 0;
9
+ const boom_1 = require("@hapi/boom");
10
+ const crypto_1 = require("crypto");
11
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
12
+ const WAProto_1 = require("../../WAProto");
13
+ const Defaults_1 = require("../Defaults");
14
+ const Types_1 = require("../Types");
15
+ const Utils_1 = require("../Utils");
16
+ const make_mutex_1 = require("../Utils/make-mutex");
17
+ const WABinary_1 = require("../WABinary");
18
+ const groups_1 = require("./groups");
19
+ const messages_send_1 = require("./messages-send");
20
+ const makeMessagesRecvSocket = (config) => {
21
+ const {
22
+ logger,
23
+ retryRequestDelayMs,
24
+ maxMsgRetryCount,
25
+ getMessage,
26
+ shouldIgnoreJid,
27
+ } = config;
28
+ const sock = (0, messages_send_1.makeMessagesSocket)(config);
29
+ const {
30
+ ev,
31
+ authState,
32
+ ws,
33
+ processingMutex,
34
+ signalRepository,
35
+ query,
36
+ upsertMessage,
37
+ resyncAppState,
38
+ groupMetadata,
39
+ onUnexpectedError,
40
+ assertSessions,
41
+ sendNode,
42
+ relayMessage,
43
+ sendReceipt,
44
+ uploadPreKeys,
45
+ createParticipantNodes,
46
+ getUSyncDevices,
47
+ sendPeerDataOperationMessage,
48
+ } = sock;
49
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
50
+ const retryMutex = (0, make_mutex_1.makeMutex)();
51
+ const msgRetryCache =
52
+ config.msgRetryCounterCache ||
53
+ new node_cache_1.default({
54
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
55
+ useClones: false,
56
+ max: 10000
57
+ });
58
+ const callOfferCache =
59
+ config.callOfferCache ||
60
+ new node_cache_1.default({
61
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
62
+ useClones: false,
63
+ max: 1000
64
+ });
65
+ const placeholderResendCache =
66
+ config.placeholderResendCache ||
67
+ new node_cache_1.default({
68
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
69
+ useClones: false,
70
+ max: 5000
71
+ });
72
+ let sendActiveReceipts = false;
73
+
74
+ // Debounce identity-change session refreshes per JID to avoid bursts
75
+ const identityAssertDebounce = new node_cache_1.default({
76
+ stdTTL: 5,
77
+ useClones: false,
78
+ max: 1000 // Limit to 1k identity assertions to prevent memory leak
79
+ })
80
+
81
+
82
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
83
+ const stanza = {
84
+ tag: "ack",
85
+ attrs: {
86
+ id: attrs.id,
87
+ to: attrs.from,
88
+ class: tag,
89
+ },
90
+ };
91
+ if (!!errorCode) {
92
+ stanza.attrs.error = errorCode.toString();
93
+ }
94
+ if (!!attrs.participant) {
95
+ stanza.attrs.participant = attrs.participant;
96
+ }
97
+ if (!!attrs.recipient) {
98
+ stanza.attrs.recipient = attrs.recipient;
99
+ }
100
+ if (
101
+ !!attrs.type &&
102
+ (tag !== "message" ||
103
+ (0, WABinary_1.getBinaryNodeChild)(
104
+ { tag, attrs, content },
105
+ "unavailable"
106
+ ) ||
107
+ errorCode !== 0)
108
+ ) {
109
+ stanza.attrs.type = attrs.type;
110
+ }
111
+ if (
112
+ tag === "message" &&
113
+ (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, "unavailable")
114
+ ) {
115
+ stanza.attrs.from = authState.creds.me.id;
116
+ }
117
+ logger.debug({ recv: { tag, attrs }, sent: stanza.attrs }, "sent ack");
118
+ await sendNode(stanza);
119
+ };
120
+ const offerCall = async (toJid, isVideo = false) => {
121
+ const callId = (0, crypto_1.randomBytes)(16)
122
+ .toString("hex")
123
+ .toUpperCase()
124
+ .substring(0, 64);
125
+ const offerContent = [];
126
+ offerContent.push({
127
+ tag: "audio",
128
+ attrs: { enc: "opus", rate: "16000" },
129
+ content: undefined,
130
+ });
131
+ offerContent.push({
132
+ tag: "audio",
133
+ attrs: { enc: "opus", rate: "8000" },
134
+ content: undefined,
135
+ });
136
+ if (isVideo) {
137
+ offerContent.push({
138
+ tag: "video",
139
+ attrs: {
140
+ orientation: "0",
141
+ screen_width: "1920",
142
+ screen_height: "1080",
143
+ device_orientation: "0",
144
+ enc: "vp8",
145
+ dec: "vp8",
146
+ },
147
+ });
148
+ }
149
+ offerContent.push({
150
+ tag: "net",
151
+ attrs: { medium: "3" },
152
+ content: undefined,
153
+ });
154
+ offerContent.push({
155
+ tag: "capability",
156
+ attrs: { ver: "1" },
157
+ content: new Uint8Array([1, 4, 255, 131, 207, 4]),
158
+ });
159
+ offerContent.push({
160
+ tag: "encopt",
161
+ attrs: { keygen: "2" },
162
+ content: undefined,
163
+ });
164
+ const encKey = (0, crypto_1.randomBytes)(32);
165
+ const devices = (await getUSyncDevices([toJid], true, false)).map(
166
+ ({ user, device }) =>
167
+ (0, WABinary_1.jidEncode)(user, "s.whatsapp.net", device)
168
+ );
169
+ await assertSessions(devices, true);
170
+ const { nodes: destinations, shouldIncludeDeviceIdentity } =
171
+ await createParticipantNodes(devices, {
172
+ call: {
173
+ callKey: encKey,
174
+ },
175
+ });
176
+ offerContent.push({ tag: "destination", attrs: {}, content: destinations });
177
+ if (shouldIncludeDeviceIdentity) {
178
+ offerContent.push({
179
+ tag: "device-identity",
180
+ attrs: {},
181
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(
182
+ authState.creds.account,
183
+ true
184
+ ),
185
+ });
186
+ }
187
+ const stanza = {
188
+ tag: "call",
189
+ attrs: {
190
+ to: toJid,
191
+ },
192
+ content: [
193
+ {
194
+ tag: "offer",
195
+ attrs: {
196
+ "call-id": callId,
197
+ "call-creator": authState.creds.me.id,
198
+ },
199
+ content: offerContent,
200
+ },
201
+ ],
202
+ };
203
+ await query(stanza);
204
+ return {
205
+ callId,
206
+ toJid,
207
+ isVideo,
208
+ };
209
+ };
210
+ const rejectCall = async (callId, callFrom) => {
211
+ const stanza = {
212
+ tag: "call",
213
+ attrs: {
214
+ from: authState.creds.me.id,
215
+ to: callFrom,
216
+ },
217
+ content: [
218
+ {
219
+ tag: "reject",
220
+ attrs: {
221
+ "call-id": callId,
222
+ "call-creator": callFrom,
223
+ count: "0",
224
+ },
225
+ content: undefined,
226
+ },
227
+ ],
228
+ };
229
+ await query(stanza);
230
+ };
231
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
232
+ const { fullMessage } = (0, Utils_1.decodeMessageNode)(
233
+ node,
234
+ authState.creds.me.id,
235
+ authState.creds.me.lid || ""
236
+ );
237
+ const { key: msgKey } = fullMessage;
238
+ const msgId = msgKey.id;
239
+ const key = `${msgId}:${
240
+ msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant
241
+ }`;
242
+ let retryCount = msgRetryCache.get(key) || 0;
243
+ if (retryCount >= maxMsgRetryCount) {
244
+ logger.debug({ retryCount, msgId }, "reached retry limit, clearing");
245
+ msgRetryCache.del(key);
246
+ return;
247
+ }
248
+ retryCount += 1;
249
+ msgRetryCache.set(key, retryCount);
250
+ const {
251
+ account,
252
+ signedPreKey,
253
+ signedIdentityKey: identityKey,
254
+ } = authState.creds;
255
+ if (retryCount === 1) {
256
+ //request a resend via phone
257
+ const msgId = await requestPlaceholderResend(msgKey);
258
+ logger.debug(
259
+ `sendRetryRequest: requested placeholder resend for message ${msgId}`
260
+ );
261
+ }
262
+ const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(
263
+ account,
264
+ true
265
+ );
266
+ await authState.keys.transaction(async () => {
267
+ const receipt = {
268
+ tag: "receipt",
269
+ attrs: {
270
+ id: msgId,
271
+ type: "retry",
272
+ to: node.attrs.from,
273
+ },
274
+ content: [
275
+ {
276
+ tag: "retry",
277
+ attrs: {
278
+ count: retryCount.toString(),
279
+ id: node.attrs.id,
280
+ t: node.attrs.t,
281
+ v: "1",
282
+ },
283
+ },
284
+ {
285
+ tag: "registration",
286
+ attrs: {},
287
+ content: (0, Utils_1.encodeBigEndian)(
288
+ authState.creds.registrationId
289
+ ),
290
+ },
291
+ ],
292
+ };
293
+ if (node.attrs.recipient) {
294
+ receipt.attrs.recipient = node.attrs.recipient;
295
+ }
296
+ if (node.attrs.participant) {
297
+ receipt.attrs.participant = node.attrs.participant;
298
+ }
299
+ if (retryCount > 1 || forceIncludeKeys) {
300
+ const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(
301
+ authState,
302
+ 1
303
+ );
304
+ const [keyId] = Object.keys(preKeys);
305
+ const key = preKeys[+keyId];
306
+ const content = receipt.content;
307
+ content.push({
308
+ tag: "keys",
309
+ attrs: {},
310
+ content: [
311
+ {
312
+ tag: "type",
313
+ attrs: {},
314
+ content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE),
315
+ },
316
+ { tag: "identity", attrs: {}, content: identityKey.public },
317
+ (0, Utils_1.xmppPreKey)(key, +keyId),
318
+ (0, Utils_1.xmppSignedPreKey)(signedPreKey),
319
+ { tag: "device-identity", attrs: {}, content: deviceIdentity },
320
+ ],
321
+ });
322
+ ev.emit("creds.update", update);
323
+ }
324
+ await sendNode(receipt);
325
+ logger.info({ msgAttrs: node.attrs, retryCount }, "sent retry receipt");
326
+ });
327
+ };
328
+ const handleEncryptNotification = async (node) => {
329
+ const from = node.attrs.from;
330
+ if (from === WABinary_1.S_WHATSAPP_NET) {
331
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(node, "count");
332
+ const count = +countChild.attrs.value;
333
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
334
+ logger.debug({ count, shouldUploadMorePreKeys }, "recv pre-key count");
335
+ if (shouldUploadMorePreKeys) {
336
+ await uploadPreKeys();
337
+ }
338
+ } else {
339
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, "identity");
340
+ if (identityNode) {
341
+ logger.info({ jid: from }, "identity changed");
342
+ // not handling right now
343
+ // signal will override new identity anyway
344
+ } else {
345
+ logger.info({ node }, "unknown encrypt notification");
346
+ }
347
+ }
348
+ };
349
+ const handleGroupNotification = (participant, child, msg) => {
350
+ var _a, _b, _c, _d;
351
+ const participantJid =
352
+ ((_b =
353
+ (_a = (0, WABinary_1.getBinaryNodeChild)(child, "participant")) ===
354
+ null || _a === void 0
355
+ ? void 0
356
+ : _a.attrs) === null || _b === void 0
357
+ ? void 0
358
+ : _b.jid) || participant;
359
+ switch (child === null || child === void 0 ? void 0 : child.tag) {
360
+ case "create":
361
+ const metadata = (0, groups_1.extractGroupMetadata)(child);
362
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
363
+ msg.messageStubParameters = [metadata.subject];
364
+ msg.key = { participant: metadata.owner };
365
+ ev.emit("chats.upsert", [
366
+ {
367
+ id: metadata.id,
368
+ name: metadata.subject,
369
+ conversationTimestamp: metadata.creation,
370
+ },
371
+ ]);
372
+ ev.emit("groups.upsert", [
373
+ {
374
+ ...metadata,
375
+ author: participant,
376
+ },
377
+ ]);
378
+ break;
379
+ case "ephemeral":
380
+ case "not_ephemeral":
381
+ msg.message = {
382
+ protocolMessage: {
383
+ type: WAProto_1.proto.Message.ProtocolMessage.Type
384
+ .EPHEMERAL_SETTING,
385
+ ephemeralExpiration: +(child.attrs.expiration || 0),
386
+ },
387
+ };
388
+ break;
389
+ case "modify":
390
+ const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(
391
+ child,
392
+ "participant"
393
+ ).map((p) => p.attrs.jid);
394
+ msg.messageStubParameters = oldNumber || [];
395
+ msg.messageStubType =
396
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
397
+ break;
398
+ case "promote":
399
+ case "demote":
400
+ case "remove":
401
+ case "add":
402
+ case "leave":
403
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
404
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
405
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(
406
+ child,
407
+ "participant"
408
+ ).map((p) => p.attrs.jid);
409
+ if (
410
+ participants.length === 1 &&
411
+ // if recv. "remove" message and sender removed themselves
412
+ // mark as left
413
+ (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
414
+ child.tag === "remove"
415
+ ) {
416
+ msg.messageStubType =
417
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
418
+ }
419
+ msg.messageStubParameters = participants;
420
+ break;
421
+ case "subject":
422
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
423
+ msg.messageStubParameters = [child.attrs.subject];
424
+ break;
425
+ case "description":
426
+ const description =
427
+ (_d =
428
+ (_c = (0, WABinary_1.getBinaryNodeChild)(child, "body")) === null ||
429
+ _c === void 0
430
+ ? void 0
431
+ : _c.content) === null || _d === void 0
432
+ ? void 0
433
+ : _d.toString();
434
+ msg.messageStubType =
435
+ Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
436
+ msg.messageStubParameters = description ? [description] : undefined;
437
+ break;
438
+ case "announcement":
439
+ case "not_announcement":
440
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
441
+ msg.messageStubParameters = [
442
+ child.tag === "announcement" ? "on" : "off",
443
+ ];
444
+ break;
445
+ case "locked":
446
+ case "unlocked":
447
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
448
+ msg.messageStubParameters = [child.tag === "locked" ? "on" : "off"];
449
+ break;
450
+ case "invite":
451
+ msg.messageStubType =
452
+ Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
453
+ msg.messageStubParameters = [child.attrs.code];
454
+ break;
455
+ case "member_add_mode":
456
+ const addMode = child.content;
457
+ if (addMode) {
458
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
459
+ msg.messageStubParameters = [addMode.toString()];
460
+ }
461
+ break;
462
+ case "membership_approval_mode":
463
+ const approvalMode = (0, WABinary_1.getBinaryNodeChild)(
464
+ child,
465
+ "group_join"
466
+ );
467
+ if (approvalMode) {
468
+ msg.messageStubType =
469
+ Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
470
+ msg.messageStubParameters = [approvalMode.attrs.state];
471
+ }
472
+ break;
473
+ case "created_membership_requests":
474
+ msg.messageStubType =
475
+ Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
476
+ msg.messageStubParameters = [
477
+ participantJid,
478
+ "created",
479
+ child.attrs.request_method,
480
+ ];
481
+ break;
482
+ case "revoked_membership_requests":
483
+ const isDenied = (0, WABinary_1.areJidsSameUser)(
484
+ participantJid,
485
+ participant
486
+ );
487
+ msg.messageStubType =
488
+ Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
489
+ msg.messageStubParameters = [
490
+ participantJid,
491
+ isDenied ? "revoked" : "rejected",
492
+ ];
493
+ break;
494
+ break;
495
+ default:
496
+ // console.log("Thehackingguard-DEBUG:", JSON.stringify({ ...child, content: Buffer.isBuffer(child.content) ? child.content.toString() : child.content, participant }, null, 2))
497
+ }
498
+ };
499
+ const handleNewsletterNotification = (id, node) => {
500
+ const messages = (0, WABinary_1.getBinaryNodeChild)(node, "messages");
501
+ const message = (0, WABinary_1.getBinaryNodeChild)(messages, "message");
502
+ const serverId = message.attrs.server_id;
503
+ const reactionsList = (0, WABinary_1.getBinaryNodeChild)(
504
+ message,
505
+ "reactions"
506
+ );
507
+ const viewsList = (0, WABinary_1.getBinaryNodeChildren)(
508
+ message,
509
+ "views_count"
510
+ );
511
+ if (reactionsList) {
512
+ const reactions = (0, WABinary_1.getBinaryNodeChildren)(
513
+ reactionsList,
514
+ "reaction"
515
+ );
516
+ if (reactions.length === 0) {
517
+ ev.emit("newsletter.reaction", {
518
+ id,
519
+ server_id: serverId,
520
+ reaction: { removed: true },
521
+ });
522
+ }
523
+ reactions.forEach((item) => {
524
+ var _a, _b;
525
+ ev.emit("newsletter.reaction", {
526
+ id,
527
+ server_id: serverId,
528
+ reaction: {
529
+ code:
530
+ (_a = item.attrs) === null || _a === void 0 ? void 0 : _a.code,
531
+ count: +((_b = item.attrs) === null || _b === void 0
532
+ ? void 0
533
+ : _b.count),
534
+ },
535
+ });
536
+ });
537
+ }
538
+ if (viewsList.length) {
539
+ viewsList.forEach((item) => {
540
+ ev.emit("newsletter.view", {
541
+ id,
542
+ server_id: serverId,
543
+ count: +item.attrs.count,
544
+ });
545
+ });
546
+ }
547
+ };
548
+ const handleMexNewsletterNotification = (id, node) => {
549
+ var _a;
550
+ const operation =
551
+ node === null || node === void 0 ? void 0 : node.attrs.op_name;
552
+ const content = JSON.parse(
553
+ (_a = node === null || node === void 0 ? void 0 : node.content) ===
554
+ null || _a === void 0
555
+ ? void 0
556
+ : _a.toString()
557
+ );
558
+ let contentPath;
559
+ if (
560
+ operation === Types_1.MexOperations.PROMOTE ||
561
+ operation === Types_1.MexOperations.DEMOTE
562
+ ) {
563
+ let action;
564
+ if (operation === Types_1.MexOperations.PROMOTE) {
565
+ action = "promote";
566
+ contentPath = content.data[Types_1.XWAPaths.PROMOTE];
567
+ }
568
+ if (operation === Types_1.MexOperations.DEMOTE) {
569
+ action = "demote";
570
+ contentPath = content.data[Types_1.XWAPaths.DEMOTE];
571
+ }
572
+ ev.emit("newsletter-participants.update", {
573
+ id,
574
+ author: contentPath.actor.pn,
575
+ user: contentPath.user.pn,
576
+ new_role: contentPath.user_new_role,
577
+ action,
578
+ });
579
+ }
580
+ if (operation === Types_1.MexOperations.UPDATE) {
581
+ contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE];
582
+ ev.emit("newsletter-settings.update", {
583
+ id,
584
+ update: contentPath.thread_metadata.settings,
585
+ });
586
+ }
587
+ };
588
+ const processNotification = async (node) => {
589
+ var _a, _b;
590
+ const result = {};
591
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
592
+ const nodeType = node.attrs.type;
593
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
594
+ switch (nodeType) {
595
+ case "privacy_token":
596
+ const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, "token");
597
+ for (const { attrs, content } of tokenList) {
598
+ const jid = attrs.jid;
599
+ ev.emit("chats.update", [
600
+ {
601
+ id: jid,
602
+ tcToken: content,
603
+ },
604
+ ]);
605
+ logger.debug({ jid }, "got privacy token update");
606
+ }
607
+ break;
608
+ case "newsletter":
609
+ handleNewsletterNotification(node.attrs.from, child);
610
+ break;
611
+ case "mex":
612
+ handleMexNewsletterNotification(node.attrs.from, child);
613
+ break;
614
+ case "w:gp2":
615
+ handleGroupNotification(node.attrs.participant, child, result);
616
+ break;
617
+ case "mediaretry":
618
+ const event = (0, Utils_1.decodeMediaRetryNode)(node);
619
+ ev.emit("messages.media-update", [event]);
620
+ break;
621
+ case "encrypt":
622
+ await handleEncryptNotification(node);
623
+ break;
624
+ case "devices":
625
+ const devices = (0, WABinary_1.getBinaryNodeChildren)(child, "device");
626
+ if (
627
+ (0, WABinary_1.areJidsSameUser)(
628
+ child.attrs.jid,
629
+ authState.creds.me.id
630
+ )
631
+ ) {
632
+ const deviceJids = devices.map((d) => d.attrs.jid);
633
+ logger.info({ deviceJids }, "got my own devices");
634
+ }
635
+ break;
636
+ case "server_sync":
637
+ const update = (0, WABinary_1.getBinaryNodeChild)(node, "collection");
638
+ if (update) {
639
+ const name = update.attrs.name;
640
+ await resyncAppState([name], false);
641
+ }
642
+ break;
643
+ case "picture":
644
+ const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, "set");
645
+ const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, "delete");
646
+ ev.emit("contacts.update", [
647
+ {
648
+ id:
649
+ from ||
650
+ ((_b =
651
+ (_a = setPicture || delPicture) === null || _a === void 0
652
+ ? void 0
653
+ : _a.attrs) === null || _b === void 0
654
+ ? void 0
655
+ : _b.hash) ||
656
+ "",
657
+ imgUrl: setPicture ? "changed" : "removed",
658
+ },
659
+ ]);
660
+ if ((0, WABinary_1.isJidGroup)(from)) {
661
+ const node = setPicture || delPicture;
662
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
663
+ if (setPicture) {
664
+ result.messageStubParameters = [setPicture.attrs.id];
665
+ }
666
+ result.participant =
667
+ node === null || node === void 0 ? void 0 : node.attrs.author;
668
+ result.key = {
669
+ ...(result.key || {}),
670
+ participant:
671
+ setPicture === null || setPicture === void 0
672
+ ? void 0
673
+ : setPicture.attrs.author,
674
+ };
675
+ }
676
+ break;
677
+ case "account_sync":
678
+ if (child.tag === "disappearing_mode") {
679
+ const newDuration = +child.attrs.duration;
680
+ const timestamp = +child.attrs.t;
681
+ logger.info({ newDuration }, "updated account disappearing mode");
682
+ ev.emit("creds.update", {
683
+ accountSettings: {
684
+ ...authState.creds.accountSettings,
685
+ defaultDisappearingMode: {
686
+ ephemeralExpiration: newDuration,
687
+ ephemeralSettingTimestamp: timestamp,
688
+ },
689
+ },
690
+ });
691
+ } else if (child.tag === "blocklist") {
692
+ const blocklists = (0, WABinary_1.getBinaryNodeChildren)(
693
+ child,
694
+ "item"
695
+ );
696
+ for (const { attrs } of blocklists) {
697
+ const blocklist = [attrs.jid];
698
+ const type = attrs.action === "block" ? "add" : "remove";
699
+ ev.emit("blocklist.update", { blocklist, type });
700
+ }
701
+ }
702
+ break;
703
+ case "link_code_companion_reg":
704
+ const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(
705
+ node,
706
+ "link_code_companion_reg"
707
+ );
708
+ const ref = toRequiredBuffer(
709
+ (0, WABinary_1.getBinaryNodeChildBuffer)(
710
+ linkCodeCompanionReg,
711
+ "link_code_pairing_ref"
712
+ )
713
+ );
714
+ const primaryIdentityPublicKey = toRequiredBuffer(
715
+ (0, WABinary_1.getBinaryNodeChildBuffer)(
716
+ linkCodeCompanionReg,
717
+ "primary_identity_pub"
718
+ )
719
+ );
720
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer(
721
+ (0, WABinary_1.getBinaryNodeChildBuffer)(
722
+ linkCodeCompanionReg,
723
+ "link_code_pairing_wrapped_primary_ephemeral_pub"
724
+ )
725
+ );
726
+ const codePairingPublicKey = await decipherLinkPublicKey(
727
+ primaryEphemeralPublicKeyWrapped
728
+ );
729
+ const companionSharedKey = Utils_1.Curve.sharedKey(
730
+ authState.creds.pairingEphemeralKeyPair.private,
731
+ codePairingPublicKey
732
+ );
733
+ const random = (0, crypto_1.randomBytes)(32);
734
+ const linkCodeSalt = (0, crypto_1.randomBytes)(32);
735
+ const linkCodePairingExpanded = await (0, Utils_1.hkdf)(
736
+ companionSharedKey,
737
+ 32,
738
+ {
739
+ salt: linkCodeSalt,
740
+ info: "link_code_pairing_key_bundle_encryption_key",
741
+ }
742
+ );
743
+ const encryptPayload = Buffer.concat([
744
+ Buffer.from(authState.creds.signedIdentityKey.public),
745
+ primaryIdentityPublicKey,
746
+ random,
747
+ ]);
748
+ const encryptIv = (0, crypto_1.randomBytes)(12);
749
+ const encrypted = (0, Utils_1.aesEncryptGCM)(
750
+ encryptPayload,
751
+ linkCodePairingExpanded,
752
+ encryptIv,
753
+ Buffer.alloc(0)
754
+ );
755
+ const encryptedPayload = Buffer.concat([
756
+ linkCodeSalt,
757
+ encryptIv,
758
+ encrypted,
759
+ ]);
760
+ const identitySharedKey = Utils_1.Curve.sharedKey(
761
+ authState.creds.signedIdentityKey.private,
762
+ primaryIdentityPublicKey
763
+ );
764
+ const identityPayload = Buffer.concat([
765
+ companionSharedKey,
766
+ identitySharedKey,
767
+ random,
768
+ ]);
769
+ authState.creds.advSecretKey = (
770
+ await (0, Utils_1.hkdf)(identityPayload, 32, { info: "adv_secret" })
771
+ ).toString("base64");
772
+ await query({
773
+ tag: "iq",
774
+ attrs: {
775
+ to: WABinary_1.S_WHATSAPP_NET,
776
+ type: "set",
777
+ id: sock.generateMessageTag(),
778
+ xmlns: "md",
779
+ },
780
+ content: [
781
+ {
782
+ tag: "link_code_companion_reg",
783
+ attrs: {
784
+ jid: authState.creds.me.id,
785
+ stage: "companion_finish",
786
+ },
787
+ content: [
788
+ {
789
+ tag: "link_code_pairing_wrapped_key_bundle",
790
+ attrs: {},
791
+ content: encryptedPayload,
792
+ },
793
+ {
794
+ tag: "companion_identity_public",
795
+ attrs: {},
796
+ content: authState.creds.signedIdentityKey.public,
797
+ },
798
+ {
799
+ tag: "link_code_pairing_ref",
800
+ attrs: {},
801
+ content: ref,
802
+ },
803
+ ],
804
+ },
805
+ ],
806
+ });
807
+ authState.creds.registered = true;
808
+ ev.emit("creds.update", authState.creds);
809
+ }
810
+ if (Object.keys(result).length) {
811
+ return result;
812
+ }
813
+ };
814
+ async function decipherLinkPublicKey(data) {
815
+ const buffer = toRequiredBuffer(data);
816
+ const salt = buffer.slice(0, 32);
817
+ const secretKey = await (0, Utils_1.derivePairingCodeKey)(
818
+ authState.creds.pairingCode,
819
+ salt
820
+ );
821
+ const iv = buffer.slice(32, 48);
822
+ const payload = buffer.slice(48, 80);
823
+ return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
824
+ }
825
+ function toRequiredBuffer(data) {
826
+ if (data === undefined) {
827
+ throw new boom_1.Boom("Invalid buffer", { statusCode: 400 });
828
+ }
829
+ return data instanceof Buffer ? data : Buffer.from(data);
830
+ }
831
+ const willSendMessageAgain = (id, participant) => {
832
+ const key = `${id}:${participant}`;
833
+ const retryCount = msgRetryCache.get(key) || 0;
834
+ return retryCount < maxMsgRetryCount;
835
+ };
836
+ const updateSendMessageAgainCount = (id, participant) => {
837
+ const key = `${id}:${participant}`;
838
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
839
+ msgRetryCache.set(key, newValue);
840
+ };
841
+ const sendMessagesAgain = async (key, ids, retryNode) => {
842
+ var _a;
843
+ // todo: implement a cache to store the last 256 sent messages (copy whatsmeow)
844
+ const msgs = await Promise.all(ids.map((id) => getMessage({ ...key, id })));
845
+ const remoteJid = key.remoteJid;
846
+ const participant = key.participant || remoteJid;
847
+ // if it's the primary jid sending the request
848
+ // just re-send the message to everyone
849
+ // prevents the first message decryption failure
850
+ const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) ===
851
+ null || _a === void 0
852
+ ? void 0
853
+ : _a.device);
854
+ await assertSessions([participant], true);
855
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
856
+ await authState.keys.set({ "sender-key-memory": { [remoteJid]: null } });
857
+ }
858
+ logger.debug(
859
+ { participant, sendToAll },
860
+ "forced new session for retry recp"
861
+ );
862
+ for (const [i, msg] of msgs.entries()) {
863
+ if (msg) {
864
+ updateSendMessageAgainCount(ids[i], participant);
865
+ const msgRelayOpts = { messageId: ids[i] };
866
+ if (sendToAll) {
867
+ msgRelayOpts.useUserDevicesCache = false;
868
+ } else {
869
+ msgRelayOpts.participant = {
870
+ jid: participant,
871
+ count: +retryNode.attrs.count,
872
+ };
873
+ }
874
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
875
+ } else {
876
+ logger.debug(
877
+ { jid: key.remoteJid, id: ids[i] },
878
+ "recv retry request, but message not available"
879
+ );
880
+ }
881
+ }
882
+ };
883
+ const handleReceipt = async (node) => {
884
+ var _a, _b;
885
+ const { attrs, content } = node;
886
+ const isLid = attrs.from.includes("lid");
887
+ const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(
888
+ attrs.participant || attrs.from,
889
+ isLid
890
+ ? (_a = authState.creds.me) === null || _a === void 0
891
+ ? void 0
892
+ : _a.lid
893
+ : (_b = authState.creds.me) === null || _b === void 0
894
+ ? void 0
895
+ : _b.id
896
+ );
897
+ const remoteJid =
898
+ !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from)
899
+ ? attrs.from
900
+ : attrs.recipient;
901
+ const fromMe =
902
+ !attrs.recipient ||
903
+ ((attrs.type === "retry" || attrs.type === "sender") && isNodeFromMe);
904
+ const key = {
905
+ remoteJid,
906
+ id: "",
907
+ fromMe,
908
+ participant: attrs.participant,
909
+ };
910
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== "@s.whatsapp.net") {
911
+ logger.debug({ remoteJid }, "ignoring receipt from jid");
912
+ await sendMessageAck(node);
913
+ return;
914
+ }
915
+ const ids = [attrs.id];
916
+ if (Array.isArray(content)) {
917
+ const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], "item");
918
+ ids.push(...items.map((i) => i.attrs.id));
919
+ }
920
+ try {
921
+ await Promise.all([
922
+ processingMutex.mutex(async () => {
923
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
924
+ if (
925
+ typeof status !== "undefined" &&
926
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
927
+ // or another device of ours has read some messages
928
+ (status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
929
+ !isNodeFromMe)
930
+ ) {
931
+ if (
932
+ (0, WABinary_1.isJidGroup)(remoteJid) ||
933
+ (0, WABinary_1.isJidStatusBroadcast)(remoteJid)
934
+ ) {
935
+ if (attrs.participant) {
936
+ const updateKey =
937
+ status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK
938
+ ? "receiptTimestamp"
939
+ : "readTimestamp";
940
+ ev.emit(
941
+ "message-receipt.update",
942
+ ids.map((id) => ({
943
+ key: { ...key, id },
944
+ receipt: {
945
+ userJid: (0, WABinary_1.jidNormalizedUser)(
946
+ attrs.participant
947
+ ),
948
+ [updateKey]: +attrs.t,
949
+ },
950
+ }))
951
+ );
952
+ }
953
+ } else {
954
+ ev.emit(
955
+ "messages.update",
956
+ ids.map((id) => ({
957
+ key: { ...key, id },
958
+ update: { status },
959
+ }))
960
+ );
961
+ }
962
+ }
963
+ if (attrs.type === "retry") {
964
+ // correctly set who is asking for the retry
965
+ key.participant = key.participant || attrs.from;
966
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, "retry");
967
+ if (willSendMessageAgain(ids[0], key.participant)) {
968
+ if (key.fromMe) {
969
+ try {
970
+ logger.debug({ attrs, key }, "recv retry request");
971
+ await sendMessagesAgain(key, ids, retryNode);
972
+ } catch (error) {
973
+ logger.error(
974
+ { key, ids, trace: error.stack },
975
+ "error in sending message again"
976
+ );
977
+ }
978
+ } else {
979
+ logger.info(
980
+ { attrs, key },
981
+ "recv retry for not fromMe message"
982
+ );
983
+ }
984
+ } else {
985
+ logger.info(
986
+ { attrs, key },
987
+ "will not send message again, as sent too many times"
988
+ );
989
+ }
990
+ }
991
+ }),
992
+ ]);
993
+ } finally {
994
+ await sendMessageAck(node);
995
+ }
996
+ };
997
+ const handleNotification = async (node) => {
998
+ const remoteJid = node.attrs.from;
999
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== "@s.whatsapp.net") {
1000
+ logger.debug({ remoteJid, id: node.attrs.id }, "ignored notification");
1001
+ await sendMessageAck(node);
1002
+ return;
1003
+ }
1004
+ try {
1005
+ await Promise.all([
1006
+ processingMutex.mutex(async () => {
1007
+ var _a;
1008
+ const msg = await processNotification(node);
1009
+ if (msg) {
1010
+ const fromMe = (0, WABinary_1.areJidsSameUser)(
1011
+ node.attrs.participant || remoteJid,
1012
+ authState.creds.me.id
1013
+ );
1014
+ msg.key = {
1015
+ remoteJid,
1016
+ fromMe,
1017
+ participant: node.attrs.participant,
1018
+ id: node.attrs.id,
1019
+ ...(msg.key || {}),
1020
+ };
1021
+ (_a = msg.participant) !== null && _a !== void 0
1022
+ ? _a
1023
+ : (msg.participant = node.attrs.participant);
1024
+ msg.messageTimestamp = +node.attrs.t;
1025
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1026
+ await upsertMessage(fullMsg, "append");
1027
+ }
1028
+ }),
1029
+ ]);
1030
+ } finally {
1031
+ await sendMessageAck(node);
1032
+ }
1033
+ };
1034
+ const handleMessage = async (node) => {
1035
+ var _a, _b, _c;
1036
+ if (
1037
+ shouldIgnoreJid(node.attrs.from) &&
1038
+ node.attrs.from !== "@s.whatsapp.net"
1039
+ ) {
1040
+ logger.debug({ key: node.attrs.key }, "ignored message");
1041
+ await sendMessageAck(node);
1042
+ return;
1043
+ }
1044
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, "enc");
1045
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
1046
+ if (encNode && encNode.attrs.type === "msmsg") {
1047
+ logger.debug({ key: node.attrs.key }, "ignored msmsg");
1048
+ await sendMessageAck(node);
1049
+ return;
1050
+ }
1051
+ let response;
1052
+ if ((0, WABinary_1.getBinaryNodeChild)(node, "unavailable") && !encNode) {
1053
+ await sendMessageAck(node);
1054
+ const { key } = (0, Utils_1.decodeMessageNode)(
1055
+ node,
1056
+ authState.creds.me.id,
1057
+ authState.creds.me.lid || ""
1058
+ ).fullMessage;
1059
+ response = await requestPlaceholderResend(key);
1060
+ if (response === "RESOLVED") {
1061
+ return;
1062
+ }
1063
+ logger.debug(
1064
+ "received unavailable message, acked and requested resend from phone"
1065
+ );
1066
+ } else {
1067
+ if (placeholderResendCache.get(node.attrs.id)) {
1068
+ placeholderResendCache.del(node.attrs.id);
1069
+ }
1070
+ }
1071
+ const {
1072
+ fullMessage: msg,
1073
+ category,
1074
+ author,
1075
+ decrypt,
1076
+ } = (0, Utils_1.decryptMessageNode)(
1077
+ node,
1078
+ authState.creds.me.id,
1079
+ authState.creds.me.lid || "",
1080
+ signalRepository,
1081
+ logger
1082
+ );
1083
+ if (
1084
+ response &&
1085
+ ((_a =
1086
+ msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) ===
1087
+ null || _a === void 0
1088
+ ? void 0
1089
+ : _a[0]) === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT
1090
+ ) {
1091
+ msg.messageStubParameters = [
1092
+ Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT,
1093
+ response,
1094
+ ];
1095
+ }
1096
+ if (
1097
+ ((_c =
1098
+ (_b = msg.message) === null || _b === void 0
1099
+ ? void 0
1100
+ : _b.protocolMessage) === null || _c === void 0
1101
+ ? void 0
1102
+ : _c.type) ===
1103
+ WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER &&
1104
+ node.attrs.sender_pn
1105
+ ) {
1106
+ ev.emit("chats.phoneNumberShare", {
1107
+ lid: node.attrs.from,
1108
+ jid: node.attrs.sender_pn,
1109
+ });
1110
+ }
1111
+ try {
1112
+ await Promise.all([
1113
+ processingMutex.mutex(async () => {
1114
+ var _a, _b, _c, _d, _e, _f;
1115
+ try {
1116
+ await decrypt();
1117
+ } catch (err) {
1118
+ const errStr = String(err);
1119
+ if (errStr.includes("Bad MAC") || errStr.includes("Invalid MAC")) {
1120
+ logger.warn(
1121
+ { msgId: node.attrs.id, from: node.attrs.from },
1122
+ "⚠️ Bad MAC detected (Node 20/24 issue) - Forcing Retry..."
1123
+ );
1124
+ msg.messageStubType =
1125
+ WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT;
1126
+ msg.messageStubParameters = [Utils_1.MISSING_KEYS_ERROR_TEXT];
1127
+ } else {
1128
+ throw err;
1129
+ }
1130
+ }
1131
+ if (
1132
+ msg.messageStubType ===
1133
+ WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT
1134
+ ) {
1135
+ if (
1136
+ ((_a =
1137
+ msg === null || msg === void 0
1138
+ ? void 0
1139
+ : msg.messageStubParameters) === null || _a === void 0
1140
+ ? void 0
1141
+ : _a[0]) === Utils_1.MISSING_KEYS_ERROR_TEXT
1142
+ ) {
1143
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
1144
+ }
1145
+ retryMutex.mutex(async () => {
1146
+ if (ws.isOpen) {
1147
+ if ((0, WABinary_1.getBinaryNodeChild)(node, "unavailable")) {
1148
+ return;
1149
+ }
1150
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, "enc");
1151
+ await sendRetryRequest(node, !encNode);
1152
+ if (retryRequestDelayMs) {
1153
+ await (0, Utils_1.delay)(retryRequestDelayMs);
1154
+ }
1155
+ } else {
1156
+ logger.debug({ node }, "connection closed, ignoring retry req");
1157
+ }
1158
+ });
1159
+ } else {
1160
+ // no type in the receipt => message delivered
1161
+ let type = undefined;
1162
+ if (
1163
+ (_b = msg.key.participant) === null || _b === void 0
1164
+ ? void 0
1165
+ : _b.endsWith("@lid")
1166
+ ) {
1167
+ msg.key.participant =
1168
+ node.attrs.participant_pn || authState.creds.me.id;
1169
+ }
1170
+ if (
1171
+ (0, WABinary_1.isJidGroup)(msg.key.remoteJid) &&
1172
+ ((_f =
1173
+ (_e =
1174
+ (_d =
1175
+ (_c = msg.message) === null || _c === void 0
1176
+ ? void 0
1177
+ : _c.extendedTextMessage) === null || _d === void 0
1178
+ ? void 0
1179
+ : _d.contextInfo) === null || _e === void 0
1180
+ ? void 0
1181
+ : _e.participant) === null || _f === void 0
1182
+ ? void 0
1183
+ : _f.endsWith("@lid"))
1184
+ ) {
1185
+ if (msg.message.extendedTextMessage.contextInfo) {
1186
+ const metadata = await groupMetadata(msg.key.remoteJid);
1187
+ const sender =
1188
+ msg.message.extendedTextMessage.contextInfo.participant;
1189
+ const found = metadata.participants.find(
1190
+ (p) => p.id === sender
1191
+ );
1192
+ msg.message.extendedTextMessage.contextInfo.participant =
1193
+ (found === null || found === void 0 ? void 0 : found.jid) ||
1194
+ sender;
1195
+ }
1196
+ }
1197
+ if (
1198
+ !(0, WABinary_1.isJidGroup)(msg.key.remoteJid) &&
1199
+ (0, WABinary_1.isLidUser)(msg.key.remoteJid)
1200
+ ) {
1201
+ msg.key.remoteJid =
1202
+ node.attrs.sender_pn || node.attrs.peer_recipient_pn;
1203
+ }
1204
+ let participant = msg.key.participant;
1205
+ if (category === "peer") {
1206
+ // special peer message
1207
+ type = "peer_msg";
1208
+ } else if (msg.key.fromMe) {
1209
+ // message was sent by us from a different device
1210
+ type = "sender";
1211
+ // need to specially handle this case
1212
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
1213
+ participant = author;
1214
+ }
1215
+ } else if (!sendActiveReceipts) {
1216
+ type = "inactive";
1217
+ }
1218
+ await sendReceipt(
1219
+ msg.key.remoteJid,
1220
+ participant,
1221
+ [msg.key.id],
1222
+ type
1223
+ );
1224
+ // send ack for history message
1225
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
1226
+ if (isAnyHistoryMsg) {
1227
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
1228
+ await sendReceipt(jid, undefined, [msg.key.id], "hist_sync");
1229
+ }
1230
+ }
1231
+ (0, Utils_1.cleanMessage)(msg, authState.creds.me.id);
1232
+ await sendMessageAck(node);
1233
+ await upsertMessage(msg, node.attrs.offline ? "append" : "notify");
1234
+ }),
1235
+ ]);
1236
+ } catch (error) {
1237
+ logger.error({ error, node }, "error in handling message");
1238
+ }
1239
+ };
1240
+ const fetchMessageHistory = async (
1241
+ count,
1242
+ oldestMsgKey,
1243
+ oldestMsgTimestamp
1244
+ ) => {
1245
+ var _a;
1246
+ if (
1247
+ !((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)
1248
+ ) {
1249
+ throw new boom_1.Boom("Not authenticated");
1250
+ }
1251
+ const pdoMessage = {
1252
+ historySyncOnDemandRequest: {
1253
+ chatJid: oldestMsgKey.remoteJid,
1254
+ oldestMsgFromMe: oldestMsgKey.fromMe,
1255
+ oldestMsgId: oldestMsgKey.id,
1256
+ oldestMsgTimestampMs: oldestMsgTimestamp,
1257
+ onDemandMsgCount: count,
1258
+ },
1259
+ peerDataOperationRequestType:
1260
+ WAProto_1.proto.Message.PeerDataOperationRequestType
1261
+ .HISTORY_SYNC_ON_DEMAND,
1262
+ };
1263
+ return sendPeerDataOperationMessage(pdoMessage);
1264
+ };
1265
+ const requestPlaceholderResend = async (messageKey) => {
1266
+ var _a;
1267
+ if (
1268
+ !((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)
1269
+ ) {
1270
+ throw new boom_1.Boom("Not authenticated");
1271
+ }
1272
+ if (
1273
+ placeholderResendCache.get(
1274
+ messageKey === null || messageKey === void 0 ? void 0 : messageKey.id
1275
+ )
1276
+ ) {
1277
+ logger.debug({ messageKey }, "already requested resend");
1278
+ return;
1279
+ } else {
1280
+ placeholderResendCache.set(
1281
+ messageKey === null || messageKey === void 0 ? void 0 : messageKey.id,
1282
+ true
1283
+ );
1284
+ }
1285
+ await (0, Utils_1.delay)(5000);
1286
+ if (
1287
+ !placeholderResendCache.get(
1288
+ messageKey === null || messageKey === void 0 ? void 0 : messageKey.id
1289
+ )
1290
+ ) {
1291
+ logger.debug({ messageKey }, "message received while resend requested");
1292
+ return "RESOLVED";
1293
+ }
1294
+ const pdoMessage = {
1295
+ placeholderMessageResendRequest: [
1296
+ {
1297
+ messageKey,
1298
+ },
1299
+ ],
1300
+ peerDataOperationRequestType:
1301
+ WAProto_1.proto.Message.PeerDataOperationRequestType
1302
+ .PLACEHOLDER_MESSAGE_RESEND,
1303
+ };
1304
+ setTimeout(() => {
1305
+ if (
1306
+ placeholderResendCache.get(
1307
+ messageKey === null || messageKey === void 0 ? void 0 : messageKey.id
1308
+ )
1309
+ ) {
1310
+ logger.debug(
1311
+ { messageKey },
1312
+ "PDO message without response after 15 seconds. Phone possibly offline"
1313
+ );
1314
+ placeholderResendCache.del(
1315
+ messageKey === null || messageKey === void 0 ? void 0 : messageKey.id
1316
+ );
1317
+ }
1318
+ }, 15000);
1319
+ return sendPeerDataOperationMessage(pdoMessage);
1320
+ };
1321
+ const handleCall = async (node) => {
1322
+ const { attrs } = node;
1323
+ const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
1324
+ const callId = infoChild.attrs["call-id"];
1325
+ const from = infoChild.attrs.from || infoChild.attrs["call-creator"];
1326
+ const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
1327
+ const call = {
1328
+ chatId: attrs.from,
1329
+ from,
1330
+ id: callId,
1331
+ date: new Date(+attrs.t * 1000),
1332
+ offline: !!attrs.offline,
1333
+ status,
1334
+ };
1335
+ if (status === "offer") {
1336
+ call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, "video");
1337
+ call.isGroup =
1338
+ infoChild.attrs.type === "group" || !!infoChild.attrs["group-jid"];
1339
+ call.groupJid = infoChild.attrs["group-jid"];
1340
+ callOfferCache.set(call.id, call);
1341
+ }
1342
+ const existingCall = callOfferCache.get(call.id);
1343
+ // use existing call info to populate this event
1344
+ if (existingCall) {
1345
+ call.isVideo = existingCall.isVideo;
1346
+ call.isGroup = existingCall.isGroup;
1347
+ }
1348
+ // delete data once call has ended
1349
+ if (
1350
+ status === "reject" ||
1351
+ status === "accept" ||
1352
+ status === "timeout" ||
1353
+ status === "terminate"
1354
+ ) {
1355
+ callOfferCache.del(call.id);
1356
+ }
1357
+ ev.emit("call", [call]);
1358
+ await sendMessageAck(node);
1359
+ };
1360
+ const handleBadAck = async ({ attrs }) => {
1361
+ const key = {
1362
+ remoteJid: attrs.from,
1363
+ fromMe: true,
1364
+ id: attrs.id,
1365
+ server_id: attrs === null || attrs === void 0 ? void 0 : attrs.server_id,
1366
+ };
1367
+ // current hypothesis is that if pash is sent in the ack
1368
+ // it means -- the message hasn't reached all devices yet
1369
+ // we'll retry sending the message here
1370
+ if (attrs.phash) {
1371
+ logger.info({ attrs }, "received phash in ack, resending message...");
1372
+ const cacheKey = `${key.remoteJid}:${key.id}`;
1373
+ if ((msgRetryCache.get(cacheKey) || 0) >= maxMsgRetryCount) {
1374
+ logger.warn(
1375
+ { attrs },
1376
+ "reached max retry count, not sending message again"
1377
+ );
1378
+ msgRetryCache.del(cacheKey);
1379
+ return;
1380
+ }
1381
+ const retryCount = msgRetryCache.get(cacheKey) || 0;
1382
+ const msg = await getMessage(key);
1383
+ if (msg) {
1384
+ await relayMessage(key.remoteJid, msg, {
1385
+ messageId: key.id,
1386
+ useUserDevicesCache: false,
1387
+ });
1388
+ msgRetryCache.set(cacheKey, retryCount + 1);
1389
+ } else {
1390
+ logger.warn(
1391
+ { attrs },
1392
+ "could not send message again, as it was not found"
1393
+ );
1394
+ }
1395
+ }
1396
+ // error in acknowledgement,
1397
+ // device could not display the message
1398
+ if (attrs.error) {
1399
+ logger.warn({ attrs }, "received error in ack");
1400
+ ev.emit("messages.update", [
1401
+ {
1402
+ key,
1403
+ update: {
1404
+ status: Types_1.WAMessageStatus.ERROR,
1405
+ messageStubParameters: [attrs.error],
1406
+ },
1407
+ },
1408
+ ]);
1409
+ }
1410
+ };
1411
+ /// processes a node with the given function
1412
+ /// and adds the task to the existing buffer if we're buffering events
1413
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1414
+ ev.buffer();
1415
+ await execTask();
1416
+ ev.flush();
1417
+ function execTask() {
1418
+ return exec(node, false).catch((err) =>
1419
+ onUnexpectedError(err, identifier)
1420
+ );
1421
+ }
1422
+ };
1423
+ const makeOfflineNodeProcessor = () => {
1424
+ const nodeProcessorMap = new Map([
1425
+ ["message", handleMessage],
1426
+ ["call", handleCall],
1427
+ ["receipt", handleReceipt],
1428
+ ["notification", handleNotification],
1429
+ ]);
1430
+ const nodes = [];
1431
+ let isProcessing = false;
1432
+ const enqueue = (type, node) => {
1433
+ nodes.push({ type, node });
1434
+ if (isProcessing) {
1435
+ return;
1436
+ }
1437
+ isProcessing = true;
1438
+ const promise = async () => {
1439
+ while (nodes.length && ws.isOpen) {
1440
+ const { type, node } = nodes.shift();
1441
+ const nodeProcessor = nodeProcessorMap.get(type);
1442
+ if (!nodeProcessor) {
1443
+ onUnexpectedError(
1444
+ new Error(`unknown offline node type: ${type}`),
1445
+ "processing offline node"
1446
+ );
1447
+ continue;
1448
+ }
1449
+ await nodeProcessor(node);
1450
+ }
1451
+ isProcessing = false;
1452
+ };
1453
+ promise().catch((error) =>
1454
+ onUnexpectedError(error, "processing offline nodes")
1455
+ );
1456
+ };
1457
+ return { enqueue };
1458
+ };
1459
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
1460
+ const processNode = (type, node, identifier, exec) => {
1461
+ const isOffline = !!node.attrs.offline;
1462
+ if (isOffline) {
1463
+ offlineNodeProcessor.enqueue(type, node);
1464
+ } else {
1465
+ processNodeWithBuffer(node, identifier, exec);
1466
+ }
1467
+ };
1468
+ // recv a message
1469
+ ws.on("CB:message", (node) => {
1470
+ processNode("message", node, "processing message", handleMessage);
1471
+ });
1472
+ ws.on("CB:call", async (node) => {
1473
+ processNode("call", node, "handling call", handleCall);
1474
+ });
1475
+ ws.on("CB:receipt", (node) => {
1476
+ processNode("receipt", node, "handling receipt", handleReceipt);
1477
+ });
1478
+ ws.on("CB:notification", async (node) => {
1479
+ processNode(
1480
+ "notification",
1481
+ node,
1482
+ "handling notification",
1483
+ handleNotification
1484
+ );
1485
+ });
1486
+ ws.on("CB:ack,class:message", (node) => {
1487
+ handleBadAck(node).catch((error) =>
1488
+ onUnexpectedError(error, "handling bad ack")
1489
+ );
1490
+ });
1491
+ ev.on("call", ([call]) => {
1492
+ // missed call + group call notification message generation
1493
+ if (
1494
+ call.status === "timeout" ||
1495
+ (call.status === "offer" && call.isGroup)
1496
+ ) {
1497
+ const msg = {
1498
+ key: {
1499
+ remoteJid: call.chatId,
1500
+ id: call.id,
1501
+ fromMe: false,
1502
+ },
1503
+ messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
1504
+ };
1505
+ if (call.status === "timeout") {
1506
+ if (call.isGroup) {
1507
+ msg.messageStubType = call.isVideo
1508
+ ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO
1509
+ : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1510
+ } else {
1511
+ msg.messageStubType = call.isVideo
1512
+ ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO
1513
+ : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
1514
+ }
1515
+ } else {
1516
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1517
+ }
1518
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1519
+ upsertMessage(protoMsg, call.offline ? "append" : "notify");
1520
+ }
1521
+ });
1522
+ ev.on("connection.update", ({ isOnline }) => {
1523
+ if (typeof isOnline !== "undefined") {
1524
+ sendActiveReceipts = isOnline;
1525
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1526
+ }
1527
+ });
1528
+ return {
1529
+ ...sock,
1530
+ sendMessageAck,
1531
+ sendRetryRequest,
1532
+ rejectCall,
1533
+ offerCall,
1534
+ fetchMessageHistory,
1535
+ requestPlaceholderResend,
1536
+ };
1537
+ };
1538
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;