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