@lennyyaawa/lannysecx 9.9.18

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 (201) hide show
  1. package/README.md +61 -0
  2. package/WAProto/GenerateStatics.sh +4 -0
  3. package/WAProto/WAProto.proto +3344 -0
  4. package/WAProto/index.d.ts +37016 -0
  5. package/WAProto/index.js +130281 -0
  6. package/lib/Database/mongoAdapter.js +77 -0
  7. package/lib/Defaults/baileys-version.json +3 -0
  8. package/lib/Defaults/index.d.ts +53 -0
  9. package/lib/Defaults/index.js +130 -0
  10. package/lib/Defaults/phonenumber-mcc.json +223 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  14. package/lib/Signal/Group/group-session-builder.js +64 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  16. package/lib/Signal/Group/group_cipher.js +96 -0
  17. package/lib/Signal/Group/index.d.ts +11 -0
  18. package/lib/Signal/Group/index.js +57 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  20. package/lib/Signal/Group/keyhelper.js +55 -0
  21. package/lib/Signal/Group/queue-job.d.ts +1 -0
  22. package/lib/Signal/Group/queue-job.js +57 -0
  23. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  24. package/lib/Signal/Group/sender-chain-key.js +34 -0
  25. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  27. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  28. package/lib/Signal/Group/sender-key-message.js +69 -0
  29. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  30. package/lib/Signal/Group/sender-key-name.js +51 -0
  31. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  32. package/lib/Signal/Group/sender-key-record.js +53 -0
  33. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  34. package/lib/Signal/Group/sender-key-state.js +99 -0
  35. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  36. package/lib/Signal/Group/sender-message-key.js +29 -0
  37. package/lib/Signal/libsignal.d.ts +3 -0
  38. package/lib/Signal/libsignal.js +174 -0
  39. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  40. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  41. package/lib/Socket/Client/index.d.ts +3 -0
  42. package/lib/Socket/Client/index.js +19 -0
  43. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  44. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  45. package/lib/Socket/Client/web-socket-client.d.ts +12 -0
  46. package/lib/Socket/Client/web-socket-client.js +62 -0
  47. package/lib/Socket/PaxHeaders.0/swzesty st 1963.d.ts +1 -0
  48. package/lib/Socket/PaxHeaders.0/swzesty st 1963.js +1 -0
  49. package/lib/Socket/business.d.ts +171 -0
  50. package/lib/Socket/business.js +260 -0
  51. package/lib/Socket/chats.d.ts +84 -0
  52. package/lib/Socket/chats.js +890 -0
  53. package/lib/Socket/groups.d.ts +115 -0
  54. package/lib/Socket/groups.js +317 -0
  55. package/lib/Socket/index.d.ts +173 -0
  56. package/lib/Socket/index.js +10 -0
  57. package/lib/Socket/messages-recv.d.ts +161 -0
  58. package/lib/Socket/messages-recv.js +1110 -0
  59. package/lib/Socket/messages-send.d.ts +149 -0
  60. package/lib/Socket/messages-send.js +805 -0
  61. package/lib/Socket/newsletter.d.ts +134 -0
  62. package/lib/Socket/newsletter.js +236 -0
  63. package/lib/Socket/registration.d.ts +267 -0
  64. package/lib/Socket/registration.js +166 -0
  65. package/lib/Socket/socket.d.ts +43 -0
  66. package/lib/Socket/socket.js +630 -0
  67. package/lib/Socket/sw/303/250zesty /303/250st 1963.d.ts" +220 -0
  68. package/lib/Socket/sw/303/250zesty /303/250st 1963.js" +437 -0
  69. package/lib/Socket/usync.d.ts +36 -0
  70. package/lib/Socket/usync.js +70 -0
  71. package/lib/Store/index.d.ts +3 -0
  72. package/lib/Store/index.js +10 -0
  73. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  74. package/lib/Store/make-cache-manager-store.js +83 -0
  75. package/lib/Store/make-in-memory-store.d.ts +118 -0
  76. package/lib/Store/make-in-memory-store.js +427 -0
  77. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  78. package/lib/Store/make-ordered-dictionary.js +81 -0
  79. package/lib/Store/object-repository.d.ts +10 -0
  80. package/lib/Store/object-repository.js +27 -0
  81. package/lib/Types/Auth.d.ts +110 -0
  82. package/lib/Types/Auth.js +2 -0
  83. package/lib/Types/Call.d.ts +13 -0
  84. package/lib/Types/Call.js +2 -0
  85. package/lib/Types/Chat.d.ts +102 -0
  86. package/lib/Types/Chat.js +4 -0
  87. package/lib/Types/Contact.d.ts +19 -0
  88. package/lib/Types/Contact.js +2 -0
  89. package/lib/Types/Events.d.ts +157 -0
  90. package/lib/Types/Events.js +2 -0
  91. package/lib/Types/GroupMetadata.d.ts +55 -0
  92. package/lib/Types/GroupMetadata.js +2 -0
  93. package/lib/Types/Label.d.ts +35 -0
  94. package/lib/Types/Label.js +27 -0
  95. package/lib/Types/LabelAssociation.d.ts +29 -0
  96. package/lib/Types/LabelAssociation.js +9 -0
  97. package/lib/Types/Message.d.ts +273 -0
  98. package/lib/Types/Message.js +9 -0
  99. package/lib/Types/Newsletter.d.ts +92 -0
  100. package/lib/Types/Newsletter.js +32 -0
  101. package/lib/Types/Product.d.ts +78 -0
  102. package/lib/Types/Product.js +2 -0
  103. package/lib/Types/Signal.d.ts +57 -0
  104. package/lib/Types/Signal.js +2 -0
  105. package/lib/Types/Socket.d.ts +111 -0
  106. package/lib/Types/Socket.js +2 -0
  107. package/lib/Types/State.d.ts +27 -0
  108. package/lib/Types/State.js +2 -0
  109. package/lib/Types/USync.d.ts +25 -0
  110. package/lib/Types/USync.js +2 -0
  111. package/lib/Types/index.d.ts +57 -0
  112. package/lib/Types/index.js +42 -0
  113. package/lib/Utils/auth-utils.d.ts +18 -0
  114. package/lib/Utils/auth-utils.js +206 -0
  115. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  116. package/lib/Utils/baileys-event-stream.js +63 -0
  117. package/lib/Utils/business.d.ts +22 -0
  118. package/lib/Utils/business.js +234 -0
  119. package/lib/Utils/chat-utils.d.ts +71 -0
  120. package/lib/Utils/chat-utils.js +729 -0
  121. package/lib/Utils/crypto.d.ts +41 -0
  122. package/lib/Utils/crypto.js +151 -0
  123. package/lib/Utils/decode-wa-message.d.ts +19 -0
  124. package/lib/Utils/decode-wa-message.js +198 -0
  125. package/lib/Utils/event-buffer.d.ts +35 -0
  126. package/lib/Utils/event-buffer.js +514 -0
  127. package/lib/Utils/generics.d.ts +92 -0
  128. package/lib/Utils/generics.js +391 -0
  129. package/lib/Utils/history.d.ts +15 -0
  130. package/lib/Utils/history.js +96 -0
  131. package/lib/Utils/index.d.ts +17 -0
  132. package/lib/Utils/index.js +33 -0
  133. package/lib/Utils/link-preview.d.ts +21 -0
  134. package/lib/Utils/link-preview.js +93 -0
  135. package/lib/Utils/logger.d.ts +4 -0
  136. package/lib/Utils/logger.js +7 -0
  137. package/lib/Utils/lt-hash.d.ts +12 -0
  138. package/lib/Utils/lt-hash.js +51 -0
  139. package/lib/Utils/make-mutex.d.ts +7 -0
  140. package/lib/Utils/make-mutex.js +43 -0
  141. package/lib/Utils/messages-media.d.ts +116 -0
  142. package/lib/Utils/messages-media.js +731 -0
  143. package/lib/Utils/messages.d.ts +77 -0
  144. package/lib/Utils/messages.js +825 -0
  145. package/lib/Utils/noise-handler.d.ts +21 -0
  146. package/lib/Utils/noise-handler.js +155 -0
  147. package/lib/Utils/process-message.d.ts +41 -0
  148. package/lib/Utils/process-message.js +321 -0
  149. package/lib/Utils/signal.d.ts +32 -0
  150. package/lib/Utils/signal.js +151 -0
  151. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  152. package/lib/Utils/use-multi-file-auth-state.js +81 -0
  153. package/lib/Utils/validate-connection.d.ts +11 -0
  154. package/lib/Utils/validate-connection.js +205 -0
  155. package/lib/WABinary/constants.d.ts +27 -0
  156. package/lib/WABinary/constants.js +40 -0
  157. package/lib/WABinary/decode.d.ts +7 -0
  158. package/lib/WABinary/decode.js +252 -0
  159. package/lib/WABinary/encode.d.ts +3 -0
  160. package/lib/WABinary/encode.js +228 -0
  161. package/lib/WABinary/generic-utils.d.ts +16 -0
  162. package/lib/WABinary/generic-utils.js +199 -0
  163. package/lib/WABinary/index.d.ts +5 -0
  164. package/lib/WABinary/index.js +21 -0
  165. package/lib/WABinary/jid-utils.d.ts +31 -0
  166. package/lib/WABinary/jid-utils.js +62 -0
  167. package/lib/WABinary/types.d.ts +18 -0
  168. package/lib/WABinary/types.js +2 -0
  169. package/lib/WAM/BinaryInfo.d.ts +17 -0
  170. package/lib/WAM/BinaryInfo.js +13 -0
  171. package/lib/WAM/constants.d.ts +38 -0
  172. package/lib/WAM/constants.js +15350 -0
  173. package/lib/WAM/encode.d.ts +3 -0
  174. package/lib/WAM/encode.js +155 -0
  175. package/lib/WAM/index.d.ts +3 -0
  176. package/lib/WAM/index.js +19 -0
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  178. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  179. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  180. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  181. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  182. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  183. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  184. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  185. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  186. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  187. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  188. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  189. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  190. package/lib/WAUSync/Protocols/index.js +20 -0
  191. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  192. package/lib/WAUSync/USyncQuery.js +89 -0
  193. package/lib/WAUSync/USyncUser.d.ts +12 -0
  194. package/lib/WAUSync/USyncUser.js +26 -0
  195. package/lib/WAUSync/index.d.ts +3 -0
  196. package/lib/WAUSync/index.js +19 -0
  197. package/lib/index.d.ts +11 -0
  198. package/lib/index.js +85 -0
  199. package/lib/index.js.bak +44 -0
  200. package/lib/index.js.bak2 +133 -0
  201. package/package.json +108 -0
@@ -0,0 +1,1110 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeMessagesRecvSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const crypto_1 = require("crypto");
9
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
10
+ const WAProto_1 = require("../../WAProto");
11
+ const Defaults_1 = require("../Defaults");
12
+ const Types_1 = require("../Types");
13
+ const Utils_1 = require("../Utils");
14
+ const make_mutex_1 = require("../Utils/make-mutex");
15
+ const WABinary_1 = require("../WABinary");
16
+ const groups_1 = require("./groups");
17
+ const messages_send_1 = require("./messages-send");
18
+ const makeMessagesRecvSocket = (config) => {
19
+ const {
20
+ logger,
21
+ retryRequestDelayMs,
22
+ maxMsgRetryCount,
23
+ getMessage,
24
+ shouldIgnoreJid
25
+ } = config;
26
+ const sock = (0, messages_send_1.makeMessagesSocket)(config);
27
+ const {
28
+ ev,
29
+ authState,
30
+ ws,
31
+ processingMutex,
32
+ signalRepository,
33
+ query,
34
+ upsertMessage,
35
+ resyncAppState,
36
+ groupMetadata,
37
+ onUnexpectedError,
38
+ assertSessions,
39
+ sendNode,
40
+ relayMessage,
41
+ sendReceipt,
42
+ uploadPreKeys,
43
+ createParticipantNodes,
44
+ getUSyncDevices,
45
+ sendPeerDataOperationMessage
46
+ } = sock;
47
+ /** this mutex ensures that each retryRequest will wait for the previous one to finish */
48
+ const retryMutex = (0, make_mutex_1.makeMutex)();
49
+ const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
50
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
51
+ useClones: false
52
+ });
53
+ const callOfferCache = config.callOfferCache || new node_cache_1.default({
54
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.CALL_OFFER, // 5 mins
55
+ useClones: false
56
+ });
57
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
58
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
59
+ useClones: false
60
+ });
61
+ let sendActiveReceipts = false;
62
+ const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
63
+ const stanza = {
64
+ tag: 'ack',
65
+ attrs: {
66
+ id: attrs.id,
67
+ to: attrs.from,
68
+ class: tag
69
+ }
70
+ }
71
+ if (!!errorCode) {
72
+ stanza.attrs.error = errorCode.toString();
73
+ }
74
+ if (!!attrs.participant) {
75
+ stanza.attrs.participant = attrs.participant;
76
+ }
77
+ if (!!attrs.recipient) {
78
+ stanza.attrs.recipient = attrs.recipient;
79
+ }
80
+ if (!!attrs.type && (tag !== 'message' || (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable') || errorCode !== 0)) {
81
+ stanza.attrs.type = attrs.type;
82
+ }
83
+ if (tag === 'message' && (0, WABinary_1.getBinaryNodeChild)({ tag, attrs, content }, 'unavailable')) {
84
+ stanza.attrs.from = authState.creds.me.id;
85
+ }
86
+ logger.debug({
87
+ recv: {
88
+ tag,
89
+ attrs
90
+ },
91
+ sent: stanza.attrs }, 'sent ack');
92
+ await sendNode(stanza);
93
+ };
94
+ const offerCall = async (toJid, isVideo = false) => {
95
+ const callId = (0, crypto_1.randomBytes)(16).toString('hex').toUpperCase().substring(0, 64);
96
+ const offerContent = [];
97
+ offerContent.push({
98
+ tag: 'audio',
99
+ attrs: {
100
+ enc: 'opus',
101
+ rate: '16000'
102
+ }, content: undefined
103
+ });
104
+ offerContent.push({
105
+ tag: 'audio',
106
+ attrs: {
107
+ enc: 'opus',
108
+ rate: '8000'
109
+ }, content: undefined
110
+ });
111
+ if (isVideo) {
112
+ offerContent.push({
113
+ tag: 'video',
114
+ attrs: {
115
+ orientation: '0',
116
+ 'screen_width': '1920',
117
+ 'screen_height': '1080',
118
+ 'device_orientation': '0',
119
+ enc: 'vp8',
120
+ dec: 'vp8',
121
+ }
122
+ });
123
+ }
124
+ offerContent.push({
125
+ tag: 'net',
126
+ attrs: {
127
+ medium: '3'
128
+ }, content: undefined
129
+ });
130
+ offerContent.push({
131
+ tag: 'capability',
132
+ attrs: {
133
+ ver: '1'
134
+ }, content: new Uint8Array([1, 4, 255, 131, 207, 4]) });
135
+ offerContent.push({
136
+ tag: 'encopt',
137
+ attrs: {
138
+ keygen: '2'
139
+ }, content: undefined
140
+ })
141
+ const encKey = (0, crypto_1.randomBytes)(32);
142
+ const devices = (await getUSyncDevices([toJid], true, false)).map(({ user, device }) => (0, WABinary_1.jidEncode)(user, 's.whatsapp.net', device));
143
+ await assertSessions(devices, true);
144
+ const { nodes: destinations, shouldIncludeDeviceIdentity } = await createParticipantNodes(devices, {
145
+ call: {
146
+ callKey: encKey
147
+ }
148
+ });
149
+ offerContent.push({ tag: 'destination', attrs: {}, content: destinations });
150
+ if (shouldIncludeDeviceIdentity) {
151
+ offerContent.push({
152
+ tag: 'device-identity',
153
+ attrs: {},
154
+ content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
155
+ });
156
+ }
157
+ const stanza = ({
158
+ tag: 'call',
159
+ attrs: {
160
+ to: toJid,
161
+ },
162
+ content: [{
163
+ tag: 'offer',
164
+ attrs: {
165
+ 'call-id': callId,
166
+ 'call-creator': authState.creds.me.id,
167
+ },
168
+ content: offerContent,
169
+ }],
170
+ });
171
+ await query(stanza);
172
+ return {
173
+ callId,
174
+ toJid,
175
+ isVideo,
176
+ };
177
+ };
178
+ const rejectCall = async (callId, callFrom) => {
179
+ const stanza = ({
180
+ tag: 'call',
181
+ attrs: {
182
+ from: authState.creds.me.id,
183
+ to: callFrom,
184
+ },
185
+ content: [{
186
+ tag: 'reject',
187
+ attrs: {
188
+ 'call-id': callId,
189
+ 'call-creator': callFrom,
190
+ count: '0',
191
+ },
192
+ content: undefined,
193
+ }],
194
+ });
195
+ await query(stanza);
196
+ };
197
+ const sendRetryRequest = async (node, forceIncludeKeys = false) => {
198
+ const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
199
+ const { key: msgKey } = fullMessage;
200
+ const msgId = msgKey.id;
201
+ const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
202
+ let retryCount = msgRetryCache.get(key) || 0;
203
+ if (retryCount >= maxMsgRetryCount) {
204
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
205
+ msgRetryCache.del(key);
206
+ return;
207
+ }
208
+ retryCount += 1;
209
+ msgRetryCache.set(key, retryCount);
210
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
211
+ if (retryCount === 1) {
212
+ //request a resend via phone
213
+ const msgId = await requestPlaceholderResend(msgKey);
214
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
215
+ }
216
+ const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
217
+ await authState.keys.transaction(async () => {
218
+ const receipt = {
219
+ tag: 'receipt',
220
+ attrs: {
221
+ id: msgId,
222
+ type: 'retry',
223
+ to: node.attrs.from
224
+ },
225
+ content: [
226
+ {
227
+ tag: 'retry',
228
+ attrs: {
229
+ count: retryCount.toString(),
230
+ id: node.attrs.id,
231
+ t: node.attrs.t,
232
+ v: '1'
233
+ }
234
+ },
235
+ {
236
+ tag: 'registration',
237
+ attrs: {},
238
+ content: (0, Utils_1.encodeBigEndian)(authState.creds.registrationId)
239
+ }
240
+ ]
241
+ };
242
+ if (node.attrs.recipient) {
243
+ receipt.attrs.recipient = node.attrs.recipient;
244
+ }
245
+ if (node.attrs.participant) {
246
+ receipt.attrs.participant = node.attrs.participant;
247
+ }
248
+ if (retryCount > 1 || forceIncludeKeys) {
249
+ const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
250
+ const [keyId] = Object.keys(preKeys);
251
+ const key = preKeys[+keyId];
252
+ const content = receipt.content;
253
+ content.push({
254
+ tag: 'keys',
255
+ attrs: {},
256
+ content: [
257
+ { tag: 'type', attrs: {}, content: Buffer.from(Defaults_1.KEY_BUNDLE_TYPE) },
258
+ { tag: 'identity', attrs: {}, content: identityKey.public },
259
+ (0, Utils_1.xmppPreKey)(key, +keyId),
260
+ (0, Utils_1.xmppSignedPreKey)(signedPreKey),
261
+ { tag: 'device-identity', attrs: {}, content: deviceIdentity }
262
+ ]
263
+ });
264
+ ev.emit('creds.update', update);
265
+ }
266
+ await sendNode(receipt);
267
+ logger.info({ msgAttrs: node.attrs, retryCount }, 'sent retry receipt');
268
+ });
269
+ };
270
+ const handleEncryptNotification = async (node) => {
271
+ const from = node.attrs.from;
272
+ if (from === WABinary_1.S_WHATSAPP_NET) {
273
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(node, 'count');
274
+ const count = +countChild.attrs.value;
275
+ const shouldUploadMorePreKeys = count < Defaults_1.MIN_PREKEY_COUNT;
276
+ logger.debug({ count, shouldUploadMorePreKeys }, 'recv pre-key count');
277
+ if (shouldUploadMorePreKeys) {
278
+ await uploadPreKeys();
279
+ }
280
+ }
281
+ else {
282
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
283
+ if (identityNode) {
284
+ logger.info({ jid: from }, 'identity changed');
285
+ // not handling right now
286
+ // signal will override new identity anyway
287
+ }
288
+ else {
289
+ logger.info({ node }, 'unknown encrypt notification');
290
+ }
291
+ }
292
+ };
293
+ const handleGroupNotification = (participant, child, msg) => {
294
+ var _a, _b, _c, _d;
295
+ const participantJid = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(child, 'participant')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.jid) || participant;
296
+ switch (child === null || child === void 0 ? void 0 : child.tag) {
297
+ case 'create':
298
+ const metadata = (0, groups_1.extractGroupMetadata)(child);
299
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
300
+ msg.messageStubParameters = [metadata.subject];
301
+ msg.key = { participant: metadata.owner };
302
+ ev.emit('chats.upsert', [{
303
+ id: metadata.id,
304
+ name: metadata.subject,
305
+ conversationTimestamp: metadata.creation,
306
+ }]);
307
+ ev.emit('groups.upsert', [{
308
+ ...metadata,
309
+ author: participant
310
+ }]);
311
+ break;
312
+ case 'ephemeral':
313
+ case 'not_ephemeral':
314
+ msg.message = {
315
+ protocolMessage: {
316
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
317
+ ephemeralExpiration: +(child.attrs.expiration || 0)
318
+ }
319
+ };
320
+ break;
321
+ case 'modify':
322
+ const oldNumber = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
323
+ msg.messageStubParameters = oldNumber || [];
324
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER;
325
+ break;
326
+ case 'promote':
327
+ case 'demote':
328
+ case 'remove':
329
+ case 'add':
330
+ case 'leave':
331
+ const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
332
+ msg.messageStubType = Types_1.WAMessageStubType[stubType];
333
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
334
+ if (participants.length === 1 &&
335
+ // if recv. "remove" message and sender removed themselves
336
+ // mark as left
337
+ (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
338
+ child.tag === 'remove') {
339
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
340
+ }
341
+ msg.messageStubParameters = participants;
342
+ break;
343
+ case 'subject':
344
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
345
+ msg.messageStubParameters = [child.attrs.subject];
346
+ break;
347
+ case 'description':
348
+ const description = (_d = (_c = (0, WABinary_1.getBinaryNodeChild)(child, 'body')) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.toString();
349
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
350
+ msg.messageStubParameters = description ? [description] : undefined;
351
+ break;
352
+ case 'announcement':
353
+ case 'not_announcement':
354
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE;
355
+ msg.messageStubParameters = [(child.tag === 'announcement') ? 'on' : 'off'];
356
+ break;
357
+ case 'locked':
358
+ case 'unlocked':
359
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT;
360
+ msg.messageStubParameters = [(child.tag === 'locked') ? 'on' : 'off'];
361
+ break;
362
+ case 'invite':
363
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK;
364
+ msg.messageStubParameters = [child.attrs.code];
365
+ break;
366
+ case 'member_add_mode':
367
+ const addMode = child.content;
368
+ if (addMode) {
369
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE;
370
+ msg.messageStubParameters = [addMode.toString()];
371
+ }
372
+ break;
373
+ case 'membership_approval_mode':
374
+ const approvalMode = (0, WABinary_1.getBinaryNodeChild)(child, 'group_join');
375
+ if (approvalMode) {
376
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE;
377
+ msg.messageStubParameters = [approvalMode.attrs.state];
378
+ }
379
+ break;
380
+ case 'created_membership_requests':
381
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
382
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
383
+ break;
384
+ case 'revoked_membership_requests':
385
+ const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
386
+ msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
387
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
388
+ break;
389
+ break;
390
+ default:
391
+ // console.log("BAILEYS-DEBUG:", JSON.stringify({ ...child, content: Buffer.isBuffer(child.content) ? child.content.toString() : child.content, participant }, null, 2))
392
+ }
393
+ };
394
+ const handleNewsletterNotification = (id, node) => {
395
+ const messages = (0, WABinary_1.getBinaryNodeChild)(node, 'messages');
396
+ const message = (0, WABinary_1.getBinaryNodeChild)(messages, 'message');
397
+ const serverId = message.attrs.server_id;
398
+ const reactionsList = (0, WABinary_1.getBinaryNodeChild)(message, 'reactions');
399
+ const viewsList = (0, WABinary_1.getBinaryNodeChildren)(message, 'views_count');
400
+ if (reactionsList) {
401
+ const reactions = (0, WABinary_1.getBinaryNodeChildren)(reactionsList, 'reaction');
402
+ if (reactions.length === 0) {
403
+ ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { removed: true } });
404
+ }
405
+ reactions.forEach(item => {
406
+ var _a, _b;
407
+ ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { code: (_a = item.attrs) === null || _a === void 0 ? void 0 : _a.code, count: +((_b = item.attrs) === null || _b === void 0 ? void 0 : _b.count) } });
408
+ });
409
+ }
410
+ if (viewsList.length) {
411
+ viewsList.forEach(item => {
412
+ ev.emit('newsletter.view', { id, 'server_id': serverId, count: +item.attrs.count });
413
+ });
414
+ }
415
+ };
416
+ const handleMexNewsletterNotification = (id, node) => {
417
+ var _a;
418
+ const operation = node === null || node === void 0 ? void 0 : node.attrs.op_name;
419
+ const content = JSON.parse((_a = node === null || node === void 0 ? void 0 : node.content) === null || _a === void 0 ? void 0 : _a.toString());
420
+ let contentPath;
421
+ if (operation === Types_1.MexOperations.PROMOTE || operation === Types_1.MexOperations.DEMOTE) {
422
+ let action;
423
+ if (operation === Types_1.MexOperations.PROMOTE) {
424
+ action = 'promote';
425
+ contentPath = content.data[Types_1.XWAPaths.PROMOTE];
426
+ }
427
+ if (operation === Types_1.MexOperations.DEMOTE) {
428
+ action = 'demote';
429
+ contentPath = content.data[Types_1.XWAPaths.DEMOTE];
430
+ }
431
+ ev.emit('newsletter-participants.update', { id, author: contentPath.actor.pn, user: contentPath.user.pn, new_role: contentPath.user_new_role, action });
432
+ }
433
+ if (operation === Types_1.MexOperations.UPDATE) {
434
+ contentPath = content.data[Types_1.XWAPaths.METADATA_UPDATE];
435
+ ev.emit('newsletter-settings.update', { id, update: contentPath.thread_metadata.settings });
436
+ }
437
+ };
438
+ const processNotification = async (node) => {
439
+ var _a, _b;
440
+ const result = {};
441
+ const [child] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
442
+ const nodeType = node.attrs.type;
443
+ const from = (0, WABinary_1.jidNormalizedUser)(node.attrs.from);
444
+ switch (nodeType) {
445
+ case 'privacy_token':
446
+ const tokenList = (0, WABinary_1.getBinaryNodeChildren)(child, 'token');
447
+ for (const { attrs, content } of tokenList) {
448
+ const jid = attrs.jid;
449
+ ev.emit('chats.update', [
450
+ {
451
+ id: jid,
452
+ tcToken: content
453
+ }
454
+ ]);
455
+ logger.debug({ jid }, 'got privacy token update');
456
+ }
457
+ break;
458
+ case 'newsletter':
459
+ handleNewsletterNotification(node.attrs.from, child);
460
+ break;
461
+ case 'mex':
462
+ handleMexNewsletterNotification(node.attrs.from, child);
463
+ break;
464
+ case 'w:gp2':
465
+ handleGroupNotification(node.attrs.participant, child, result);
466
+ break;
467
+ case 'mediaretry':
468
+ const event = (0, Utils_1.decodeMediaRetryNode)(node);
469
+ ev.emit('messages.media-update', [event]);
470
+ break;
471
+ case 'encrypt':
472
+ await handleEncryptNotification(node);
473
+ break;
474
+ case 'devices':
475
+ const devices = (0, WABinary_1.getBinaryNodeChildren)(child, 'device');
476
+ if ((0, WABinary_1.areJidsSameUser)(child.attrs.jid, authState.creds.me.id)) {
477
+ const deviceJids = devices.map(d => d.attrs.jid);
478
+ logger.info({ deviceJids }, 'got my own devices');
479
+ }
480
+ break;
481
+ case 'server_sync':
482
+ const update = (0, WABinary_1.getBinaryNodeChild)(node, 'collection');
483
+ if (update) {
484
+ const name = update.attrs.name;
485
+ await resyncAppState([name], false);
486
+ }
487
+ break;
488
+ case 'picture':
489
+ const setPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'set');
490
+ const delPicture = (0, WABinary_1.getBinaryNodeChild)(node, 'delete');
491
+ ev.emit('contacts.update', [{
492
+ id: from || ((_b = (_a = (setPicture || delPicture)) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.hash) || '',
493
+ imgUrl: setPicture ? 'changed' : 'removed'
494
+ }]);
495
+ if ((0, WABinary_1.isJidGroup)(from)) {
496
+ const node = setPicture || delPicture;
497
+ result.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_ICON;
498
+ if (setPicture) {
499
+ result.messageStubParameters = [setPicture.attrs.id];
500
+ }
501
+ result.participant = node === null || node === void 0 ? void 0 : node.attrs.author;
502
+ result.key = {
503
+ ...result.key || {},
504
+ participant: setPicture === null || setPicture === void 0 ? void 0 : setPicture.attrs.author
505
+ };
506
+ }
507
+ break;
508
+ case 'account_sync':
509
+ if (child.tag === 'disappearing_mode') {
510
+ const newDuration = +child.attrs.duration;
511
+ const timestamp = +child.attrs.t;
512
+ logger.info({ newDuration }, 'updated account disappearing mode');
513
+ ev.emit('creds.update', {
514
+ accountSettings: {
515
+ ...authState.creds.accountSettings,
516
+ defaultDisappearingMode: {
517
+ ephemeralExpiration: newDuration,
518
+ ephemeralSettingTimestamp: timestamp,
519
+ },
520
+ }
521
+ });
522
+ }
523
+ else if (child.tag === 'blocklist') {
524
+ const blocklists = (0, WABinary_1.getBinaryNodeChildren)(child, 'item');
525
+ for (const { attrs } of blocklists) {
526
+ const blocklist = [attrs.jid];
527
+ const type = (attrs.action === 'block') ? 'add' : 'remove';
528
+ ev.emit('blocklist.update', { blocklist, type });
529
+ }
530
+ }
531
+ break;
532
+ case 'link_code_companion_reg':
533
+ const linkCodeCompanionReg = (0, WABinary_1.getBinaryNodeChild)(node, 'link_code_companion_reg');
534
+ const ref = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_ref'));
535
+ const primaryIdentityPublicKey = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'primary_identity_pub'));
536
+ const primaryEphemeralPublicKeyWrapped = toRequiredBuffer((0, WABinary_1.getBinaryNodeChildBuffer)(linkCodeCompanionReg, 'link_code_pairing_wrapped_primary_ephemeral_pub'));
537
+ const codePairingPublicKey = await decipherLinkPublicKey(primaryEphemeralPublicKeyWrapped);
538
+ const companionSharedKey = Utils_1.Curve.sharedKey(authState.creds.pairingEphemeralKeyPair.private, codePairingPublicKey);
539
+ const random = (0, crypto_1.randomBytes)(32);
540
+ const linkCodeSalt = (0, crypto_1.randomBytes)(32);
541
+ const linkCodePairingExpanded = await (0, Utils_1.hkdf)(companionSharedKey, 32, {
542
+ salt: linkCodeSalt,
543
+ info: 'link_code_pairing_key_bundle_encryption_key'
544
+ });
545
+ const encryptPayload = Buffer.concat([Buffer.from(authState.creds.signedIdentityKey.public), primaryIdentityPublicKey, random]);
546
+ const encryptIv = (0, crypto_1.randomBytes)(12);
547
+ const encrypted = (0, Utils_1.aesEncryptGCM)(encryptPayload, linkCodePairingExpanded, encryptIv, Buffer.alloc(0));
548
+ const encryptedPayload = Buffer.concat([linkCodeSalt, encryptIv, encrypted]);
549
+ const identitySharedKey = Utils_1.Curve.sharedKey(authState.creds.signedIdentityKey.private, primaryIdentityPublicKey);
550
+ const identityPayload = Buffer.concat([companionSharedKey, identitySharedKey, random]);
551
+ authState.creds.advSecretKey = (await (0, Utils_1.hkdf)(identityPayload, 32, { info: 'adv_secret' })).toString('base64');
552
+ await query({
553
+ tag: 'iq',
554
+ attrs: {
555
+ to: WABinary_1.S_WHATSAPP_NET,
556
+ type: 'set',
557
+ id: sock.generateMessageTag(),
558
+ xmlns: 'md'
559
+ },
560
+ content: [
561
+ {
562
+ tag: 'link_code_companion_reg',
563
+ attrs: {
564
+ jid: authState.creds.me.id,
565
+ stage: 'companion_finish',
566
+ },
567
+ content: [
568
+ {
569
+ tag: 'link_code_pairing_wrapped_key_bundle',
570
+ attrs: {},
571
+ content: encryptedPayload
572
+ },
573
+ {
574
+ tag: 'companion_identity_public',
575
+ attrs: {},
576
+ content: authState.creds.signedIdentityKey.public
577
+ },
578
+ {
579
+ tag: 'link_code_pairing_ref',
580
+ attrs: {},
581
+ content: ref
582
+ }
583
+ ]
584
+ }
585
+ ]
586
+ });
587
+ authState.creds.registered = true;
588
+ ev.emit('creds.update', authState.creds);
589
+ }
590
+ if (Object.keys(result).length) {
591
+ return result;
592
+ }
593
+ };
594
+ async function decipherLinkPublicKey(data) {
595
+ const buffer = toRequiredBuffer(data);
596
+ const salt = buffer.slice(0, 32);
597
+ const secretKey = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
598
+ const iv = buffer.slice(32, 48);
599
+ const payload = buffer.slice(48, 80);
600
+ return (0, Utils_1.aesDecryptCTR)(payload, secretKey, iv);
601
+ }
602
+ function toRequiredBuffer(data) {
603
+ if (data === undefined) {
604
+ throw new boom_1.Boom('Invalid buffer', { statusCode: 400 });
605
+ }
606
+ return data instanceof Buffer ? data : Buffer.from(data);
607
+ }
608
+ const willSendMessageAgain = (id, participant) => {
609
+ const key = `${id}:${participant}`;
610
+ const retryCount = msgRetryCache.get(key) || 0;
611
+ return retryCount < maxMsgRetryCount;
612
+ };
613
+ const updateSendMessageAgainCount = (id, participant) => {
614
+ const key = `${id}:${participant}`;
615
+ const newValue = (msgRetryCache.get(key) || 0) + 1;
616
+ msgRetryCache.set(key, newValue);
617
+ };
618
+ const sendMessagesAgain = async (key, ids, retryNode) => {
619
+ var _a;
620
+ // todo: implement a cache to store the last 256 sent messages (copy whatsmeow)
621
+ const msgs = await Promise.all(ids.map(id => getMessage({ ...key, id })));
622
+ const remoteJid = key.remoteJid;
623
+ const participant = key.participant || remoteJid;
624
+ // if it's the primary jid sending the request
625
+ // just re-send the message to everyone
626
+ // prevents the first message decryption failure
627
+ const sendToAll = !((_a = (0, WABinary_1.jidDecode)(participant)) === null || _a === void 0 ? void 0 : _a.device);
628
+ await assertSessions([participant], true);
629
+ if ((0, WABinary_1.isJidGroup)(remoteJid)) {
630
+ await authState.keys.set({ 'sender-key-memory': { [remoteJid]: null } });
631
+ }
632
+ logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
633
+ for (const [i, msg] of msgs.entries()) {
634
+ if (msg) {
635
+ updateSendMessageAgainCount(ids[i], participant);
636
+ const msgRelayOpts = { messageId: ids[i] };
637
+ if (sendToAll) {
638
+ msgRelayOpts.useUserDevicesCache = false;
639
+ }
640
+ else {
641
+ msgRelayOpts.participant = {
642
+ jid: participant,
643
+ count: +retryNode.attrs.count
644
+ };
645
+ }
646
+ await relayMessage(key.remoteJid, msg, msgRelayOpts);
647
+ }
648
+ else {
649
+ logger.debug({ jid: key.remoteJid, id: ids[i] }, 'recv retry request, but message not available');
650
+ }
651
+ }
652
+ };
653
+ const handleReceipt = async (node) => {
654
+ var _a, _b;
655
+ const { attrs, content } = node;
656
+ const isLid = attrs.from.includes('lid');
657
+ const isNodeFromMe = (0, WABinary_1.areJidsSameUser)(attrs.participant || attrs.from, isLid ? (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.lid : (_b = authState.creds.me) === null || _b === void 0 ? void 0 : _b.id);
658
+ const remoteJid = !isNodeFromMe || (0, WABinary_1.isJidGroup)(attrs.from) ? attrs.from : attrs.recipient;
659
+ const fromMe = !attrs.recipient || ((attrs.type === 'retry' || attrs.type === 'sender') && isNodeFromMe);
660
+ const key = {
661
+ remoteJid,
662
+ id: '',
663
+ fromMe,
664
+ participant: attrs.participant
665
+ };
666
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
667
+ logger.debug({ remoteJid }, 'ignoring receipt from jid');
668
+ await sendMessageAck(node);
669
+ return;
670
+ }
671
+ const ids = [attrs.id];
672
+ if (Array.isArray(content)) {
673
+ const items = (0, WABinary_1.getBinaryNodeChildren)(content[0], 'item');
674
+ ids.push(...items.map(i => i.attrs.id));
675
+ }
676
+ try {
677
+ await Promise.all([
678
+ processingMutex.mutex(async () => {
679
+ const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
680
+ if (typeof status !== 'undefined' &&
681
+ (
682
+ // basically, we only want to know when a message from us has been delivered to/read by the other person
683
+ // or another device of ours has read some messages
684
+ status >= WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK ||
685
+ !isNodeFromMe)) {
686
+ if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
687
+ if (attrs.participant) {
688
+ const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
689
+ ev.emit('message-receipt.update', ids.map(id => ({
690
+ key: { ...key, id },
691
+ receipt: {
692
+ userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
693
+ [updateKey]: +attrs.t
694
+ }
695
+ })));
696
+ }
697
+ }
698
+ else {
699
+ ev.emit('messages.update', ids.map(id => ({
700
+ key: { ...key, id },
701
+ update: { status }
702
+ })));
703
+ }
704
+ }
705
+ if (attrs.type === 'retry') {
706
+ // correctly set who is asking for the retry
707
+ key.participant = key.participant || attrs.from;
708
+ const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
709
+ if (willSendMessageAgain(ids[0], key.participant)) {
710
+ if (key.fromMe) {
711
+ try {
712
+ logger.debug({ attrs, key }, 'recv retry request');
713
+ await sendMessagesAgain(key, ids, retryNode);
714
+ }
715
+ catch (error) {
716
+ logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
717
+ }
718
+ }
719
+ else {
720
+ logger.info({ attrs, key }, 'recv retry for not fromMe message');
721
+ }
722
+ }
723
+ else {
724
+ logger.info({ attrs, key }, 'will not send message again, as sent too many times');
725
+ }
726
+ }
727
+ })
728
+ ]);
729
+ }
730
+ finally {
731
+ await sendMessageAck(node);
732
+ }
733
+ };
734
+ const handleNotification = async (node) => {
735
+ const remoteJid = node.attrs.from;
736
+ if (shouldIgnoreJid(remoteJid) && remoteJid !== '@s.whatsapp.net') {
737
+ logger.debug({ remoteJid, id: node.attrs.id }, 'ignored notification');
738
+ await sendMessageAck(node);
739
+ return;
740
+ }
741
+ try {
742
+ await Promise.all([
743
+ processingMutex.mutex(async () => {
744
+ var _a;
745
+ const msg = await processNotification(node);
746
+ if (msg) {
747
+ const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
748
+ msg.key = {
749
+ remoteJid,
750
+ fromMe,
751
+ participant: node.attrs.participant,
752
+ id: node.attrs.id,
753
+ ...(msg.key || {})
754
+ };
755
+ (_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
756
+ msg.messageTimestamp = +node.attrs.t;
757
+ const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
758
+ await upsertMessage(fullMsg, 'append');
759
+ }
760
+ })
761
+ ]);
762
+ }
763
+ finally {
764
+ await sendMessageAck(node);
765
+ }
766
+ };
767
+ const handleMessage = async (node) => {
768
+ var _a, _b, _c;
769
+ if (shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
770
+ logger.debug({ key: node.attrs.key }, 'ignored message');
771
+ await sendMessageAck(node);
772
+ return;
773
+ }
774
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
775
+ // TODO: temporary fix for crashes and issues resulting of failed msmsg decryption
776
+ if (encNode && encNode.attrs.type === 'msmsg') {
777
+ logger.debug({ key: node.attrs.key }, 'ignored msmsg');
778
+ await sendMessageAck(node);
779
+ return;
780
+ }
781
+ let response;
782
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable') && !encNode) {
783
+ await sendMessageAck(node);
784
+ const { key } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '').fullMessage;
785
+ response = await requestPlaceholderResend(key);
786
+ if (response === 'RESOLVED') {
787
+ return;
788
+ }
789
+ logger.debug('received unavailable message, acked and requested resend from phone');
790
+ }
791
+ else {
792
+ if (placeholderResendCache.get(node.attrs.id)) {
793
+ placeholderResendCache.del(node.attrs.id);
794
+ }
795
+ }
796
+ const { fullMessage: msg, category, author, decrypt } = (0, Utils_1.decryptMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '', signalRepository, logger);
797
+ if (response && ((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT) {
798
+ msg.messageStubParameters = [Utils_1.NO_MESSAGE_FOUND_ERROR_TEXT, response];
799
+ }
800
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER && node.attrs.sender_pn) {
801
+ ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
802
+ }
803
+ try {
804
+ await Promise.all([
805
+ processingMutex.mutex(async () => {
806
+ var _a, _b, _c, _d, _e, _f;
807
+ await decrypt();
808
+ // message failed to decrypt
809
+ if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
810
+ if (((_a = msg === null || msg === void 0 ? void 0 : msg.messageStubParameters) === null || _a === void 0 ? void 0 : _a[0]) === Utils_1.MISSING_KEYS_ERROR_TEXT) {
811
+ return sendMessageAck(node, Utils_1.NACK_REASONS.ParsingError);
812
+ }
813
+ retryMutex.mutex(async () => {
814
+ if (ws.isOpen) {
815
+ if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
816
+ return;
817
+ }
818
+ const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
819
+ await sendRetryRequest(node, !encNode);
820
+ if (retryRequestDelayMs) {
821
+ await (0, Utils_1.delay)(retryRequestDelayMs);
822
+ }
823
+ }
824
+ else {
825
+ logger.debug({ node }, 'connection closed, ignoring retry req');
826
+ }
827
+ });
828
+ }
829
+ else {
830
+ // no type in the receipt => message delivered
831
+ let type = undefined;
832
+ if ((_b = msg.key.participant) === null || _b === void 0 ? void 0 : _b.endsWith('@lid')) {
833
+ msg.key.participant = node.attrs.participant_pn || authState.creds.me.id;
834
+ }
835
+ if ((0, WABinary_1.isJidGroup)(msg.key.remoteJid) && ((_f = (_e = (_d = (_c = msg.message) === null || _c === void 0 ? void 0 : _c.extendedTextMessage) === null || _d === void 0 ? void 0 : _d.contextInfo) === null || _e === void 0 ? void 0 : _e.participant) === null || _f === void 0 ? void 0 : _f.endsWith('@lid'))) {
836
+ if (msg.message.extendedTextMessage.contextInfo) {
837
+ const metadata = await groupMetadata(msg.key.remoteJid);
838
+ const sender = msg.message.extendedTextMessage.contextInfo.participant;
839
+ const found = metadata.participants.find(p => p.id === sender);
840
+ msg.message.extendedTextMessage.contextInfo.participant = (found === null || found === void 0 ? void 0 : found.jid) || sender;
841
+ }
842
+ }
843
+ if (!(0, WABinary_1.isJidGroup)(msg.key.remoteJid) && (0, WABinary_1.isLidUser)(msg.key.remoteJid)) {
844
+ msg.key.remoteJid = node.attrs.sender_pn || node.attrs.peer_recipient_pn;
845
+ }
846
+ let participant = msg.key.participant;
847
+ if (category === 'peer') { // special peer message
848
+ type = 'peer_msg';
849
+ }
850
+ else if (msg.key.fromMe) { // message was sent by us from a different device
851
+ type = 'sender';
852
+ // need to specially handle this case
853
+ if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
854
+ participant = author;
855
+ }
856
+ }
857
+ else if (!sendActiveReceipts) {
858
+ type = 'inactive';
859
+ }
860
+ await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
861
+ // send ack for history message
862
+ const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
863
+ if (isAnyHistoryMsg) {
864
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
865
+ await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
866
+ }
867
+ }
868
+ (0, Utils_1.cleanMessage)(msg, authState.creds.me.id);
869
+ await sendMessageAck(node);
870
+ await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
871
+ })
872
+ ]);
873
+ }
874
+ catch (error) {
875
+ logger.error({ error, node }, 'error in handling message');
876
+ }
877
+ };
878
+ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {
879
+ var _a;
880
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
881
+ throw new boom_1.Boom('Not authenticated');
882
+ }
883
+ const pdoMessage = {
884
+ historySyncOnDemandRequest: {
885
+ chatJid: oldestMsgKey.remoteJid,
886
+ oldestMsgFromMe: oldestMsgKey.fromMe,
887
+ oldestMsgId: oldestMsgKey.id,
888
+ oldestMsgTimestampMs: oldestMsgTimestamp,
889
+ onDemandMsgCount: count
890
+ },
891
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.HISTORY_SYNC_ON_DEMAND
892
+ };
893
+ return sendPeerDataOperationMessage(pdoMessage);
894
+ };
895
+ const requestPlaceholderResend = async (messageKey) => {
896
+ var _a;
897
+ if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
898
+ throw new boom_1.Boom('Not authenticated');
899
+ }
900
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
901
+ logger.debug({ messageKey }, 'already requested resend');
902
+ return;
903
+ }
904
+ else {
905
+ placeholderResendCache.set(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id, true);
906
+ }
907
+ await (0, Utils_1.delay)(5000);
908
+ if (!placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
909
+ logger.debug({ messageKey }, 'message received while resend requested');
910
+ return 'RESOLVED';
911
+ }
912
+ const pdoMessage = {
913
+ placeholderMessageResendRequest: [{
914
+ messageKey
915
+ }],
916
+ peerDataOperationRequestType: WAProto_1.proto.Message.PeerDataOperationRequestType.PLACEHOLDER_MESSAGE_RESEND
917
+ };
918
+ setTimeout(() => {
919
+ if (placeholderResendCache.get(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id)) {
920
+ logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline');
921
+ placeholderResendCache.del(messageKey === null || messageKey === void 0 ? void 0 : messageKey.id);
922
+ }
923
+ }, 15000);
924
+ return sendPeerDataOperationMessage(pdoMessage);
925
+ };
926
+ const handleCall = async (node) => {
927
+ const { attrs } = node;
928
+ const [infoChild] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
929
+ const callId = infoChild.attrs['call-id'];
930
+ const from = infoChild.attrs.from || infoChild.attrs['call-creator'];
931
+ const status = (0, Utils_1.getCallStatusFromNode)(infoChild);
932
+ const call = {
933
+ chatId: attrs.from,
934
+ from,
935
+ id: callId,
936
+ date: new Date(+attrs.t * 1000),
937
+ offline: !!attrs.offline,
938
+ status,
939
+ };
940
+ if (status === 'offer') {
941
+ call.isVideo = !!(0, WABinary_1.getBinaryNodeChild)(infoChild, 'video');
942
+ call.isGroup = infoChild.attrs.type === 'group' || !!infoChild.attrs['group-jid'];
943
+ call.groupJid = infoChild.attrs['group-jid'];
944
+ callOfferCache.set(call.id, call);
945
+ }
946
+ const existingCall = callOfferCache.get(call.id);
947
+ // use existing call info to populate this event
948
+ if (existingCall) {
949
+ call.isVideo = existingCall.isVideo;
950
+ call.isGroup = existingCall.isGroup;
951
+ }
952
+ // delete data once call has ended
953
+ if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
954
+ callOfferCache.del(call.id);
955
+ }
956
+ ev.emit('call', [call]);
957
+ await sendMessageAck(node);
958
+ };
959
+ const handleBadAck = async ({ attrs }) => {
960
+ const key = { remoteJid: attrs.from, fromMe: true, id: attrs.id, 'server_id': attrs === null || attrs === void 0 ? void 0 : attrs.server_id };
961
+ // current hypothesis is that if pash is sent in the ack
962
+ // it means -- the message hasn't reached all devices yet
963
+ // we'll retry sending the message here
964
+ if (attrs.phash) {
965
+ logger.info({ attrs }, 'received phash in ack, resending message...');
966
+ const cacheKey = `${key.remoteJid}:${key.id}`;
967
+ if ((msgRetryCache.get(cacheKey) || 0) >= maxMsgRetryCount) {
968
+ logger.warn({ attrs }, 'reached max retry count, not sending message again');
969
+ msgRetryCache.del(cacheKey);
970
+ return;
971
+ }
972
+ const retryCount = msgRetryCache.get(cacheKey) || 0;
973
+ const msg = await getMessage(key);
974
+ if (msg) {
975
+ await relayMessage(key.remoteJid, msg, { messageId: key.id, useUserDevicesCache: false });
976
+ msgRetryCache.set(cacheKey, retryCount + 1);
977
+ }
978
+ else {
979
+ logger.warn({ attrs }, 'could not send message again, as it was not found');
980
+ }
981
+ }
982
+ // error in acknowledgement,
983
+ // device could not display the message
984
+ if (attrs.error) {
985
+ logger.warn({ attrs }, 'received error in ack');
986
+ ev.emit('messages.update', [
987
+ {
988
+ key,
989
+ update: {
990
+ status: Types_1.WAMessageStatus.ERROR,
991
+ messageStubParameters: [
992
+ attrs.error
993
+ ]
994
+ }
995
+ }
996
+ ]);
997
+ }
998
+ };
999
+ /// processes a node with the given function
1000
+ /// and adds the task to the existing buffer if we're buffering events
1001
+ const processNodeWithBuffer = async (node, identifier, exec) => {
1002
+ ev.buffer();
1003
+ await execTask();
1004
+ ev.flush();
1005
+ function execTask() {
1006
+ return exec(node, false)
1007
+ .catch(err => onUnexpectedError(err, identifier));
1008
+ }
1009
+ };
1010
+ const makeOfflineNodeProcessor = () => {
1011
+ const nodeProcessorMap = new Map([
1012
+ ['message', handleMessage],
1013
+ ['call', handleCall],
1014
+ ['receipt', handleReceipt],
1015
+ ['notification', handleNotification]
1016
+ ]);
1017
+ const nodes = [];
1018
+ let isProcessing = false;
1019
+ const enqueue = (type, node) => {
1020
+ nodes.push({ type, node });
1021
+ if (isProcessing) {
1022
+ return;
1023
+ }
1024
+ isProcessing = true;
1025
+ const promise = async () => {
1026
+ while (nodes.length && ws.isOpen) {
1027
+ const { type, node } = nodes.shift();
1028
+ const nodeProcessor = nodeProcessorMap.get(type);
1029
+ if (!nodeProcessor) {
1030
+ onUnexpectedError(new Error(`unknown offline node type: ${type}`), 'processing offline node');
1031
+ continue;
1032
+ }
1033
+ await nodeProcessor(node);
1034
+ }
1035
+ isProcessing = false;
1036
+ };
1037
+ promise().catch(error => onUnexpectedError(error, 'processing offline nodes'));
1038
+ };
1039
+ return { enqueue };
1040
+ };
1041
+ const offlineNodeProcessor = makeOfflineNodeProcessor();
1042
+ const processNode = (type, node, identifier, exec) => {
1043
+ const isOffline = !!node.attrs.offline;
1044
+ if (isOffline) {
1045
+ offlineNodeProcessor.enqueue(type, node);
1046
+ }
1047
+ else {
1048
+ processNodeWithBuffer(node, identifier, exec);
1049
+ }
1050
+ };
1051
+ // recv a message
1052
+ ws.on('CB:message', (node) => {
1053
+ processNode('message', node, 'processing message', handleMessage);
1054
+ });
1055
+ ws.on('CB:call', async (node) => {
1056
+ processNode('call', node, 'handling call', handleCall);
1057
+ });
1058
+ ws.on('CB:receipt', node => {
1059
+ processNode('receipt', node, 'handling receipt', handleReceipt);
1060
+ });
1061
+ ws.on('CB:notification', async (node) => {
1062
+ processNode('notification', node, 'handling notification', handleNotification);
1063
+ });
1064
+ ws.on('CB:ack,class:message', (node) => {
1065
+ handleBadAck(node)
1066
+ .catch(error => onUnexpectedError(error, 'handling bad ack'));
1067
+ });
1068
+ ev.on('call', ([call]) => {
1069
+ // missed call + group call notification message generation
1070
+ if (call.status === 'timeout' || (call.status === 'offer' && call.isGroup)) {
1071
+ const msg = {
1072
+ key: {
1073
+ remoteJid: call.chatId,
1074
+ id: call.id,
1075
+ fromMe: false
1076
+ },
1077
+ messageTimestamp: (0, Utils_1.unixTimestampSeconds)(call.date),
1078
+ };
1079
+ if (call.status === 'timeout') {
1080
+ if (call.isGroup) {
1081
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE;
1082
+ }
1083
+ else {
1084
+ msg.messageStubType = call.isVideo ? Types_1.WAMessageStubType.CALL_MISSED_VIDEO : Types_1.WAMessageStubType.CALL_MISSED_VOICE;
1085
+ }
1086
+ }
1087
+ else {
1088
+ msg.message = { call: { callKey: Buffer.from(call.id) } };
1089
+ }
1090
+ const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
1091
+ upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
1092
+ }
1093
+ });
1094
+ ev.on('connection.update', ({ isOnline }) => {
1095
+ if (typeof isOnline !== 'undefined') {
1096
+ sendActiveReceipts = isOnline;
1097
+ logger.trace(`sendActiveReceipts set to "${sendActiveReceipts}"`);
1098
+ }
1099
+ });
1100
+ return {
1101
+ ...sock,
1102
+ sendMessageAck,
1103
+ sendRetryRequest,
1104
+ rejectCall,
1105
+ offerCall,
1106
+ fetchMessageHistory,
1107
+ requestPlaceholderResend,
1108
+ };
1109
+ };
1110
+ exports.makeMessagesRecvSocket = makeMessagesRecvSocket;