@aseppxyzz12/baileys 1.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +2579 -0
  3. package/WAProto/AICommon/AICommon.js +19396 -0
  4. package/WAProto/AICommon/AICommon.proto +820 -0
  5. package/WAProto/Adv/Adv.js +1137 -0
  6. package/WAProto/Adv/Adv.proto +42 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +8975 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +484 -0
  9. package/WAProto/Cert/Cert.js +893 -0
  10. package/WAProto/Cert/Cert.proto +30 -0
  11. package/WAProto/ChatLockSettings/ChatLockSettings.js +673 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.proto +9 -0
  13. package/WAProto/CompanionReg/CompanionReg.js +2457 -0
  14. package/WAProto/CompanionReg/CompanionReg.proto +103 -0
  15. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +846 -0
  16. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +38 -0
  17. package/WAProto/E2E/E2E.js +78728 -0
  18. package/WAProto/E2E/E2E.proto +1970 -0
  19. package/WAProto/Ephemeral/Ephemeral.js +143 -0
  20. package/WAProto/Ephemeral/Ephemeral.proto +7 -0
  21. package/WAProto/HistorySync/HistorySync.js +95931 -0
  22. package/WAProto/HistorySync/HistorySync.proto +229 -0
  23. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +414 -0
  24. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +13 -0
  25. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +980 -0
  26. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +38 -0
  27. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +81185 -0
  28. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +88 -0
  29. package/WAProto/MmsRetry/MmsRetry.js +310 -0
  30. package/WAProto/MmsRetry/MmsRetry.proto +19 -0
  31. package/WAProto/Protocol/Protocol.js +399 -0
  32. package/WAProto/Protocol/Protocol.proto +22 -0
  33. package/WAProto/Reporting/Reporting.js +535 -0
  34. package/WAProto/Reporting/Reporting.proto +22 -0
  35. package/WAProto/ServerSync/ServerSync.js +1830 -0
  36. package/WAProto/ServerSync/ServerSync.proto +70 -0
  37. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +3267 -0
  38. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +95 -0
  39. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1140 -0
  40. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +44 -0
  41. package/WAProto/StatusAttributions/StatusAttributions.js +1604 -0
  42. package/WAProto/StatusAttributions/StatusAttributions.proto +89 -0
  43. package/WAProto/SyncAction/SyncAction.js +17424 -0
  44. package/WAProto/SyncAction/SyncAction.proto +663 -0
  45. package/WAProto/UserPassword/UserPassword.js +544 -0
  46. package/WAProto/UserPassword/UserPassword.proto +28 -0
  47. package/WAProto/VnameCert/VnameCert.js +1466 -0
  48. package/WAProto/VnameCert/VnameCert.proto +65 -0
  49. package/WAProto/Wa6/Wa6.js +4601 -0
  50. package/WAProto/Wa6/Wa6.proto +241 -0
  51. package/WAProto/Web/Web.js +90819 -0
  52. package/WAProto/Web/Web.proto +605 -0
  53. package/WAProto/index.js +30 -0
  54. package/engine-requirements.js +9 -0
  55. package/lib/Defaults/baileys-version.json +3 -0
  56. package/lib/Defaults/connection.js +39 -0
  57. package/lib/Defaults/constants.js +50 -0
  58. package/lib/Defaults/history.js +13 -0
  59. package/lib/Defaults/index.js +36 -0
  60. package/lib/Defaults/media.js +43 -0
  61. package/lib/Defaults/phonenumber-mcc.json +223 -0
  62. package/lib/Defaults/prefix.js +12 -0
  63. package/lib/Function/Download/tiktok.js +19 -0
  64. package/lib/Function/Tools/bypass.js +19 -0
  65. package/lib/Function/index.js +13 -0
  66. package/lib/Signal/Group/ciphertext-message.js +14 -0
  67. package/lib/Signal/Group/group-session-builder.js +46 -0
  68. package/lib/Signal/Group/group_cipher.js +104 -0
  69. package/lib/Signal/Group/index.js +42 -0
  70. package/lib/Signal/Group/keyhelper.js +21 -0
  71. package/lib/Signal/Group/queue-job.js +57 -0
  72. package/lib/Signal/Group/sender-chain-key.js +34 -0
  73. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  74. package/lib/Signal/Group/sender-key-message.js +78 -0
  75. package/lib/Signal/Group/sender-key-name.js +49 -0
  76. package/lib/Signal/Group/sender-key-record.js +45 -0
  77. package/lib/Signal/Group/sender-key-state.js +100 -0
  78. package/lib/Signal/Group/sender-message-key.js +28 -0
  79. package/lib/Signal/libsignal.js +364 -0
  80. package/lib/Signal/lid-mapping.js +164 -0
  81. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  82. package/lib/Socket/Client/index.js +31 -0
  83. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  84. package/lib/Socket/Client/types.js +12 -0
  85. package/lib/Socket/Client/web-socket-client.js +62 -0
  86. package/lib/Socket/Client/websocket.js +67 -0
  87. package/lib/Socket/business.js +291 -0
  88. package/lib/Socket/chats.js +874 -0
  89. package/lib/Socket/community.js +454 -0
  90. package/lib/Socket/dugong.js +658 -0
  91. package/lib/Socket/groups.js +357 -0
  92. package/lib/Socket/index.js +13 -0
  93. package/lib/Socket/messages-recv.js +1509 -0
  94. package/lib/Socket/messages-send.js +1505 -0
  95. package/lib/Socket/mex.js +54 -0
  96. package/lib/Socket/newsletter.js +171 -0
  97. package/lib/Socket/registration.js +167 -0
  98. package/lib/Socket/rich-content.js +279 -0
  99. package/lib/Socket/socket.js +905 -0
  100. package/lib/Socket/username.js +157 -0
  101. package/lib/Socket/usync.js +70 -0
  102. package/lib/Store/index.js +37 -0
  103. package/lib/Store/keyed-db.js +114 -0
  104. package/lib/Store/make-cache-manager-store.js +77 -0
  105. package/lib/Store/make-in-memory-store.js +423 -0
  106. package/lib/Store/make-ordered-dictionary.js +78 -0
  107. package/lib/Store/object-repository.js +26 -0
  108. package/lib/Types/Auth.js +2 -0
  109. package/lib/Types/Bussines.js +2 -0
  110. package/lib/Types/Call.js +2 -0
  111. package/lib/Types/Chat.js +10 -0
  112. package/lib/Types/Contact.js +2 -0
  113. package/lib/Types/Events.js +2 -0
  114. package/lib/Types/GroupMetadata.js +2 -0
  115. package/lib/Types/Label.js +25 -0
  116. package/lib/Types/LabelAssociation.js +4 -0
  117. package/lib/Types/Message.js +11 -0
  118. package/lib/Types/Mex.js +40 -0
  119. package/lib/Types/MexUpdates.js +15 -0
  120. package/lib/Types/Newsletter.js +32 -0
  121. package/lib/Types/Product.js +2 -0
  122. package/lib/Types/Signal.js +2 -0
  123. package/lib/Types/Socket.js +2 -0
  124. package/lib/Types/State.js +9 -0
  125. package/lib/Types/USync.js +2 -0
  126. package/lib/Types/index.js +60 -0
  127. package/lib/Utils/auth-utils.js +256 -0
  128. package/lib/Utils/baileys-event-stream.js +63 -0
  129. package/lib/Utils/bot-toolkit.js +455 -0
  130. package/lib/Utils/browser-utils.js +29 -0
  131. package/lib/Utils/business.js +233 -0
  132. package/lib/Utils/chat-utils.js +904 -0
  133. package/lib/Utils/companion-reg-client-utils.js +41 -0
  134. package/lib/Utils/crypto.js +144 -0
  135. package/lib/Utils/decode-wa-message.js +305 -0
  136. package/lib/Utils/event-buffer.js +555 -0
  137. package/lib/Utils/generics.js +411 -0
  138. package/lib/Utils/history.js +100 -0
  139. package/lib/Utils/identity-change-handler.js +53 -0
  140. package/lib/Utils/index.js +57 -0
  141. package/lib/Utils/link-preview.js +76 -0
  142. package/lib/Utils/logger.js +4 -0
  143. package/lib/Utils/lt-hash.js +45 -0
  144. package/lib/Utils/make-mutex.js +33 -0
  145. package/lib/Utils/message-composer.js +289 -0
  146. package/lib/Utils/message-retry-manager.js +134 -0
  147. package/lib/Utils/messages-media.js +806 -0
  148. package/lib/Utils/messages.js +1908 -0
  149. package/lib/Utils/noise-handler.js +157 -0
  150. package/lib/Utils/offline-node-processor.js +42 -0
  151. package/lib/Utils/pre-key-manager.js +86 -0
  152. package/lib/Utils/process-message.js +814 -0
  153. package/lib/Utils/reporting-utils.js +264 -0
  154. package/lib/Utils/signal.js +183 -0
  155. package/lib/Utils/stanza-ack.js +36 -0
  156. package/lib/Utils/sync-action-utils.js +52 -0
  157. package/lib/Utils/tc-token-utils.js +167 -0
  158. package/lib/Utils/use-multi-file-auth-state.js +104 -0
  159. package/lib/Utils/validate-connection.js +229 -0
  160. package/lib/Utils/vialeys-event-stream.js +41 -0
  161. package/lib/WABinary/constants.js +1308 -0
  162. package/lib/WABinary/decode.js +233 -0
  163. package/lib/WABinary/encode.js +212 -0
  164. package/lib/WABinary/generic-utils.js +124 -0
  165. package/lib/WABinary/index.js +36 -0
  166. package/lib/WABinary/jid-utils.js +101 -0
  167. package/lib/WABinary/types.js +2 -0
  168. package/lib/WAM/BinaryInfo.js +12 -0
  169. package/lib/WAM/constants.js +20491 -0
  170. package/lib/WAM/encode.js +148 -0
  171. package/lib/WAM/index.js +34 -0
  172. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +62 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.js +38 -0
  174. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +50 -0
  175. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +25 -0
  176. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +24 -0
  177. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +32 -0
  178. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  179. package/lib/WAUSync/Protocols/index.js +38 -0
  180. package/lib/WAUSync/USyncQuery.js +97 -0
  181. package/lib/WAUSync/USyncUser.js +33 -0
  182. package/lib/WAUSync/index.js +34 -0
  183. package/lib/index.js +113 -0
  184. package/lib/messages-send.js +1496 -0
  185. package/package.json +100 -0
@@ -0,0 +1,814 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const { proto: proto } = require("../../WAProto");
4
+ const { WAMessageStubType: WAMessageStubType } = require("../Types");
5
+ const {
6
+ getDevice: getDevice,
7
+ getContentType: getContentType,
8
+ normalizeMessageContent: normalizeMessageContent,
9
+ } = require("../Utils");
10
+ const {
11
+ areJidsSameUser: areJidsSameUser,
12
+ isHostedLidUser: isHostedLidUser,
13
+ isHostedPnUser: isHostedPnUser,
14
+ isJidBroadcast: isJidBroadcast,
15
+ isJidStatusBroadcast: isJidStatusBroadcast,
16
+ isLidUser: isLidUser,
17
+ jidDecode: jidDecode,
18
+ jidEncode: jidEncode,
19
+ jidNormalizedUser: jidNormalizedUser,
20
+ } = require("../WABinary");
21
+ const { aesDecryptGCM: aesDecryptGCM, hmacSign: hmacSign } = require("./crypto");
22
+ const { getKeyAuthor: getKeyAuthor, toNumber: toNumber } = require("./generics");
23
+ const {
24
+ downloadAndProcessHistorySyncNotification: downloadAndProcessHistorySyncNotification,
25
+ } = require("./history");
26
+ const REAL_MSG_STUB_TYPES = new Set([
27
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
28
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
29
+ WAMessageStubType.CALL_MISSED_VIDEO,
30
+ WAMessageStubType.CALL_MISSED_VOICE,
31
+ ]);
32
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]);
33
+ const cleanMessage = (message, meId, meLid) => {
34
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
35
+ message.key.remoteJid = jidEncode(
36
+ jidDecode(message.key?.remoteJid)?.user,
37
+ isHostedPnUser(message.key.remoteJid) ? "s.whatsapp.net" : "lid"
38
+ );
39
+ } else {
40
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
41
+ }
42
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
43
+ message.key.participant = jidEncode(
44
+ jidDecode(message.key.participant)?.user,
45
+ isHostedPnUser(message.key.participant) ? "s.whatsapp.net" : "lid"
46
+ );
47
+ } else {
48
+ message.key.participant = jidNormalizedUser(message.key.participant);
49
+ }
50
+ const content = normalizeMessageContent(message.message);
51
+ if (content?.reactionMessage) {
52
+ normaliseKey(content.reactionMessage.key);
53
+ }
54
+ if (content?.pollUpdateMessage) {
55
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
56
+ }
57
+ function normaliseKey(msgKey) {
58
+ if (!message.key.fromMe) {
59
+ msgKey.fromMe = !msgKey.fromMe
60
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
61
+ areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
62
+ : false;
63
+ msgKey.remoteJid = message.key.remoteJid;
64
+ msgKey.participant = msgKey.participant || message.key.participant;
65
+ }
66
+ }
67
+ };
68
+ const isRealMessage = (message) => {
69
+ const normalizedContent = normalizeMessageContent(message.message);
70
+ const hasSomeContent = !!getContentType(normalizedContent);
71
+ return (
72
+ (!!normalizedContent ||
73
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
74
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
75
+ hasSomeContent &&
76
+ !normalizedContent?.protocolMessage &&
77
+ !normalizedContent?.reactionMessage &&
78
+ !normalizedContent?.pollUpdateMessage
79
+ );
80
+ };
81
+ const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
82
+ const getChatId = ({ remoteJid: remoteJid, participant: participant, fromMe: fromMe }) => {
83
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
84
+ return participant;
85
+ }
86
+ return remoteJid;
87
+ };
88
+ function decryptPollVote(
89
+ { encPayload: encPayload, encIv: encIv },
90
+ {
91
+ pollCreatorJid: pollCreatorJid,
92
+ pollMsgId: pollMsgId,
93
+ pollEncKey: pollEncKey,
94
+ voterJid: voterJid,
95
+ }
96
+ ) {
97
+ const sign = Buffer.concat([
98
+ toBinary(pollMsgId),
99
+ toBinary(pollCreatorJid),
100
+ toBinary(voterJid),
101
+ toBinary("Poll Vote"),
102
+ new Uint8Array([1]),
103
+ ]);
104
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), "sha256");
105
+ const decKey = hmacSign(sign, key0, "sha256");
106
+ const aad = toBinary(`${pollMsgId}\0${voterJid}`);
107
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
108
+ return proto.Message.PollVoteMessage.decode(decrypted);
109
+ function toBinary(txt) {
110
+ return Buffer.from(txt);
111
+ }
112
+ }
113
+ function decryptEventEdit(
114
+ { encPayload: encPayload, encIv: encIv },
115
+ {
116
+ eventCreatorJid: eventCreatorJid,
117
+ eventMsgId: eventMsgId,
118
+ eventEncKey: eventEncKey,
119
+ responderJid: responderJid,
120
+ }
121
+ ) {
122
+ const sign = Buffer.concat([
123
+ toBinary(eventMsgId),
124
+ toBinary(eventCreatorJid),
125
+ toBinary(responderJid),
126
+ toBinary("Event Edit"),
127
+ new Uint8Array([1]),
128
+ ]);
129
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), "sha256");
130
+ const decKey = hmacSign(sign, key0, "sha256");
131
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, null);
132
+ return proto.Message.decode(decrypted);
133
+ function toBinary(txt) {
134
+ return Buffer.from(txt);
135
+ }
136
+ }
137
+ function decryptEventResponse(
138
+ { encPayload: encPayload, encIv: encIv },
139
+ {
140
+ eventCreatorJid: eventCreatorJid,
141
+ eventMsgId: eventMsgId,
142
+ eventEncKey: eventEncKey,
143
+ responderJid: responderJid,
144
+ }
145
+ ) {
146
+ const sign = Buffer.concat([
147
+ toBinary(eventMsgId),
148
+ toBinary(eventCreatorJid),
149
+ toBinary(responderJid),
150
+ toBinary("Event Response"),
151
+ new Uint8Array([1]),
152
+ ]);
153
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), "sha256");
154
+ const decKey = hmacSign(sign, key0, "sha256");
155
+ const aad = toBinary(`${eventMsgId}\0${responderJid}`);
156
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
157
+ return proto.Message.EventResponseMessage.decode(decrypted);
158
+ function toBinary(txt) {
159
+ return Buffer.from(txt);
160
+ }
161
+ }
162
+ function decryptComment(
163
+ { encPayload: encPayload, encIv: encIv },
164
+ {
165
+ commentCreatorJid: commentCreatorJid,
166
+ commentMsgId: commentMsgId,
167
+ commentEncKey: commentEncKey,
168
+ commentJid: commentJid,
169
+ }
170
+ ) {
171
+ const sign = Buffer.concat([
172
+ toBinary(commentMsgId),
173
+ toBinary(commentCreatorJid),
174
+ toBinary(commentJid),
175
+ toBinary("Enc Comment"),
176
+ new Uint8Array([1]),
177
+ ]);
178
+ const key0 = hmacSign(commentEncKey, new Uint8Array(32), "sha256");
179
+ const decKey = hmacSign(sign, key0, "sha256");
180
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, null);
181
+ return proto.Message.decode(decrypted);
182
+ function toBinary(txt) {
183
+ return Buffer.from(txt);
184
+ }
185
+ }
186
+ function decryptReaction(
187
+ { encPayload: encPayload, encIv: encIv },
188
+ {
189
+ reactionCreatorJid: reactionCreatorJid,
190
+ reactionMsgId: reactionMsgId,
191
+ reactionEncKey: reactionEncKey,
192
+ reactionJid: reactionJid,
193
+ }
194
+ ) {
195
+ const sign = Buffer.concat([
196
+ toBinary(reactionMsgId),
197
+ toBinary(reactionCreatorJid),
198
+ toBinary(reactionJid),
199
+ toBinary("Enc Reaction"),
200
+ new Uint8Array([1]),
201
+ ]);
202
+ const key0 = hmacSign(reactionEncKey, new Uint8Array(32), "sha256");
203
+ const decKey = hmacSign(sign, key0, "sha256");
204
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, null);
205
+ return proto.Message.ReactionMessage.decode(decrypted);
206
+ function toBinary(txt) {
207
+ return Buffer.from(txt);
208
+ }
209
+ }
210
+ const processMessage = async (
211
+ message,
212
+ {
213
+ shouldProcessHistoryMsg: shouldProcessHistoryMsg,
214
+ placeholderResendCache: placeholderResendCache,
215
+ ev: ev,
216
+ creds: creds,
217
+ signalRepository: signalRepository,
218
+ keyStore: keyStore,
219
+ logger: logger,
220
+ options: options,
221
+ getMessage: getMessage,
222
+ }
223
+ ) => {
224
+ const meId = creds.me.id;
225
+ const meLid = creds.me.lid;
226
+ const { accountSettings: accountSettings } = creds;
227
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) };
228
+ const isRealMsg = isRealMessage(message);
229
+ if (isRealMsg) {
230
+ chat.messages = [{ message: message }];
231
+ chat.conversationTimestamp = toNumber(message.messageTimestamp);
232
+ if (shouldIncrementChatUnread(message)) {
233
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
234
+ }
235
+ }
236
+ const content = normalizeMessageContent(message.message);
237
+ if (isRealMsg || (content?.reactionMessage?.key?.fromMe && accountSettings?.unarchiveChats)) {
238
+ chat.archived = false;
239
+ chat.readOnly = false;
240
+ }
241
+ const protocolMsg = content?.protocolMessage;
242
+ if (protocolMsg) {
243
+ switch (protocolMsg.type) {
244
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
245
+ const histNotification = protocolMsg.historySyncNotification;
246
+ const process = shouldProcessHistoryMsg;
247
+ const isLatest = !creds.processedHistoryMessages?.length;
248
+ logger?.info(
249
+ {
250
+ histNotification: histNotification,
251
+ process: process,
252
+ id: message.key.id,
253
+ isLatest: isLatest,
254
+ },
255
+ "got history notification"
256
+ );
257
+ if (process) {
258
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
259
+ ev.emit("creds.update", {
260
+ processedHistoryMessages: [
261
+ ...(creds.processedHistoryMessages || []),
262
+ {
263
+ key: message.key,
264
+ messageTimestamp: message.messageTimestamp,
265
+ },
266
+ ],
267
+ });
268
+ }
269
+ const data = await downloadAndProcessHistorySyncNotification(
270
+ histNotification,
271
+ options
272
+ );
273
+ ev.emit("messaging-history.set", {
274
+ ...data,
275
+ isLatest:
276
+ histNotification.syncType !==
277
+ proto.HistorySync.HistorySyncType.ON_DEMAND
278
+ ? isLatest
279
+ : undefined,
280
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId,
281
+ });
282
+ }
283
+ break;
284
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
285
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
286
+ if (keys?.length) {
287
+ let newAppStateSyncKeyId = "";
288
+ await keyStore.transaction(async () => {
289
+ const newKeys = [];
290
+ for (const { keyData: keyData, keyId: keyId } of keys) {
291
+ const strKeyId = Buffer.from(keyId.keyId).toString("base64");
292
+ newKeys.push(strKeyId);
293
+ await keyStore.set({
294
+ "app-state-sync-key": { [strKeyId]: keyData },
295
+ });
296
+ newAppStateSyncKeyId = strKeyId;
297
+ }
298
+ logger?.info(
299
+ { newAppStateSyncKeyId: newAppStateSyncKeyId, newKeys: newKeys },
300
+ "injecting new app state sync keys"
301
+ );
302
+ }, meId);
303
+ ev.emit("creds.update", { myAppStateKeyId: newAppStateSyncKeyId });
304
+ } else {
305
+ logger?.info({ protocolMsg: protocolMsg }, "recv app state sync with 0 keys");
306
+ }
307
+ break;
308
+ case proto.Message.ProtocolMessage.Type.REVOKE:
309
+ ev.emit("messages.update", [
310
+ {
311
+ key: { ...message.key, id: protocolMsg.key.id },
312
+ update: {
313
+ message: null,
314
+ messageStubType: WAMessageStubType.REVOKE,
315
+ key: message.key,
316
+ },
317
+ },
318
+ ]);
319
+ break;
320
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
321
+ Object.assign(chat, {
322
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
323
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null,
324
+ });
325
+ break;
326
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
327
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
328
+ if (response) {
329
+ await placeholderResendCache?.del(response.stanzaId);
330
+ const { peerDataOperationResult: peerDataOperationResult } = response;
331
+ for (const result of peerDataOperationResult) {
332
+ const { placeholderMessageResendResponse: retryResponse } = result;
333
+ if (retryResponse) {
334
+ const webMessageInfo = proto.WebMessageInfo.decode(
335
+ retryResponse.webMessageInfoBytes
336
+ );
337
+ setTimeout(() => {
338
+ ev.emit("messages.upsert", {
339
+ messages: [webMessageInfo],
340
+ type: "notify",
341
+ requestId: response.stanzaId,
342
+ });
343
+ }, 500);
344
+ }
345
+ }
346
+ }
347
+ break;
348
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
349
+ ev.emit("messages.update", [
350
+ {
351
+ key: { ...message.key, id: protocolMsg.key?.id },
352
+ update: {
353
+ message: {
354
+ editedMessage: { message: protocolMsg.editedMessage },
355
+ },
356
+ messageTimestamp: protocolMsg.timestampMs
357
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1e3)
358
+ : message.messageTimestamp,
359
+ },
360
+ },
361
+ ]);
362
+ break;
363
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
364
+ const labelAssociationMsg = protocolMsg.memberLabel;
365
+ if (labelAssociationMsg?.label) {
366
+ ev.emit("group.member-tag.update", {
367
+ groupId: chat.id,
368
+ label: labelAssociationMsg.label,
369
+ participant: message.key.participant,
370
+ participantAlt: message.key.participantAlt,
371
+ messageTimestamp: Number(message.messageTimestamp),
372
+ });
373
+ }
374
+ break;
375
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
376
+ const encodedPayload =
377
+ protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
378
+ const {
379
+ pnToLidMappings: pnToLidMappings,
380
+ chatDbMigrationTimestamp: chatDbMigrationTimestamp,
381
+ } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
382
+ logger?.debug(
383
+ {
384
+ pnToLidMappings: pnToLidMappings,
385
+ chatDbMigrationTimestamp: chatDbMigrationTimestamp,
386
+ },
387
+ "got lid mappings and chat db migration timestamp"
388
+ );
389
+ const pairs = [];
390
+ for (const {
391
+ pn: pn,
392
+ latestLid: latestLid,
393
+ assignedLid: assignedLid,
394
+ } of pnToLidMappings) {
395
+ const lid = latestLid || assignedLid;
396
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
397
+ }
398
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
399
+ if (pairs.length) {
400
+ for (const { pn: pn, lid: lid } of pairs) {
401
+ await signalRepository.migrateSession(pn, lid);
402
+ }
403
+ }
404
+ break;
405
+ case proto.Message.ProtocolMessage.Type.LIMIT_SHARING:
406
+ ev.emit("limit-sharing.update", {
407
+ id: message.key.remoteJid,
408
+ author: areJidsSameUser(message.key.remoteJid, protocolMsg.key.remoteJid)
409
+ ? jidNormalizedUser(meId)
410
+ : message.key.remoteJid,
411
+ action: `${protocolMsg.limitSharing.sharingLimited ? "on" : "off"}`,
412
+ trigger: protocolMsg.limitSharing.trigger,
413
+ update_time: protocolMsg.limitSharing.limitSharingSettingTimestamp,
414
+ });
415
+ break;
416
+ }
417
+ } else if (content?.reactionMessage) {
418
+ const reaction = { ...content.reactionMessage, key: message.key };
419
+ ev.emit("messages.reaction", [{ reaction: reaction, key: content.reactionMessage?.key }]);
420
+ } else if (message.messageStubType) {
421
+ const jid = message.key?.remoteJid;
422
+ let participants;
423
+ const emitParticipantsUpdate = (action) =>
424
+ ev.emit("group-participants.update", {
425
+ id: jid,
426
+ author: message.key.participant,
427
+ authorPn: message.key.participantAlt,
428
+ participants: participants,
429
+ action: action,
430
+ });
431
+ const emitGroupUpdate = (update) => {
432
+ ev.emit("groups.update", [
433
+ {
434
+ id: jid,
435
+ ...update,
436
+ author: message.key.participant ?? undefined,
437
+ authorPn: message.key.participantAlt,
438
+ },
439
+ ]);
440
+ };
441
+ const emitGroupRequestJoin = (participant, action, method) => {
442
+ ev.emit("group.join-request", {
443
+ id: jid,
444
+ author: message.key.participant,
445
+ authorPn: message.key.participantAlt,
446
+ participant: participant.lid,
447
+ participantPn: participant.pn,
448
+ action: action,
449
+ method: method,
450
+ });
451
+ };
452
+ const participantsIncludesMe = () =>
453
+ participants.find((jid) => areJidsSameUser(meId, jid.phoneNumber));
454
+ switch (message.messageStubType) {
455
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
456
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
457
+ emitParticipantsUpdate("modify");
458
+ break;
459
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
460
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
461
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
462
+ emitParticipantsUpdate("remove");
463
+ if (participantsIncludesMe()) {
464
+ chat.readOnly = true;
465
+ }
466
+ break;
467
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
468
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
469
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
470
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
471
+ if (participantsIncludesMe()) {
472
+ chat.readOnly = false;
473
+ }
474
+ emitParticipantsUpdate("add");
475
+ break;
476
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
477
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
478
+ emitParticipantsUpdate("demote");
479
+ break;
480
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
481
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
482
+ emitParticipantsUpdate("promote");
483
+ break;
484
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
485
+ const announceValue = message.messageStubParameters?.[0];
486
+ emitGroupUpdate({
487
+ announce: announceValue === "true" || announceValue === "on",
488
+ });
489
+ break;
490
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
491
+ const restrictValue = message.messageStubParameters?.[0];
492
+ emitGroupUpdate({
493
+ restrict: restrictValue === "true" || restrictValue === "on",
494
+ });
495
+ break;
496
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT:
497
+ const name = message.messageStubParameters?.[0];
498
+ chat.name = name;
499
+ emitGroupUpdate({ subject: name });
500
+ break;
501
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
502
+ const description = message.messageStubParameters?.[0];
503
+ chat.description = description;
504
+ emitGroupUpdate({ desc: description });
505
+ break;
506
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
507
+ const code = message.messageStubParameters?.[0];
508
+ emitGroupUpdate({ inviteCode: code });
509
+ break;
510
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
511
+ const memberAddValue = message.messageStubParameters?.[0];
512
+ emitGroupUpdate({ memberAddMode: memberAddValue === "all_member_add" });
513
+ break;
514
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
515
+ const approvalMode = message.messageStubParameters?.[0];
516
+ emitGroupUpdate({ joinApprovalMode: approvalMode === "on" });
517
+ break;
518
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
519
+ const participant = JSON.parse(message.messageStubParameters?.[0]);
520
+ const action = message.messageStubParameters?.[1];
521
+ const method = message.messageStubParameters?.[2];
522
+ emitGroupRequestJoin(participant, action, method);
523
+ break;
524
+ }
525
+ } else if (content?.pollUpdateMessage) {
526
+ const pollUpdate = content.pollUpdateMessage;
527
+ const creationMsgKey = pollUpdate.pollCreationMessageKey;
528
+ const pollMsg = await getMessage(creationMsgKey);
529
+ if (pollMsg) {
530
+ try {
531
+ const meLidNormalised = jidNormalizedUser(meLid);
532
+ const deviceType = getDevice(creationMsgKey.id);
533
+ const pollCreationFromMe = deviceType === "baileys" ? true : false;
534
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret;
535
+ const voterJid = getKeyAuthor(message.key, meLidNormalised);
536
+ let pollCreatorJid = getKeyAuthor(creationMsgKey, meLidNormalised);
537
+ if (pollCreationFromMe) {
538
+ pollCreatorJid = meLidNormalised;
539
+ }
540
+ if (!pollEncKey) {
541
+ logger?.warn(
542
+ { vote: pollUpdate.vote, creationMsgKey: creationMsgKey },
543
+ "poll creation: missing messageSecret for decryption"
544
+ );
545
+ } else {
546
+ const voteMsg = decryptPollVote(pollUpdate.vote, {
547
+ pollEncKey: pollEncKey,
548
+ pollCreatorJid: pollCreatorJid,
549
+ pollMsgId: creationMsgKey.id,
550
+ voterJid: voterJid,
551
+ });
552
+ ev.emit("messages.update", [
553
+ {
554
+ key: creationMsgKey,
555
+ update: {
556
+ pollUpdates: [
557
+ {
558
+ pollUpdateMessageKey: message.key,
559
+ vote: voteMsg,
560
+ senderTimestampMs:
561
+ content.pollUpdateMessage.senderTimestampMs.toNumber(),
562
+ },
563
+ ],
564
+ },
565
+ },
566
+ ]);
567
+ }
568
+ } catch (err) {
569
+ logger?.warn(
570
+ { err: err, creationMsgKey: creationMsgKey },
571
+ "failed to decrypt poll vote"
572
+ );
573
+ }
574
+ } else {
575
+ logger?.warn(
576
+ { creationMsgKey: creationMsgKey },
577
+ "poll creation message not found, cannot decrypt update"
578
+ );
579
+ }
580
+ } else if (content?.secretEncryptedMessage) {
581
+ const encEventEdit = content.secretEncryptedMessage;
582
+ const creationMsgKey = encEventEdit.targetMessageKey;
583
+ if (
584
+ proto.Message.SecretEncryptedMessage.SecretEncType[encEventEdit.secretEncType] !==
585
+ "EVENT_EDIT"
586
+ )
587
+ return;
588
+ const eventMsg = await getMessage(creationMsgKey);
589
+ if (eventMsg) {
590
+ try {
591
+ const meLidNormalised = jidNormalizedUser(meLid);
592
+ const eventCreatorJid = getKeyAuthor(message.key, meLidNormalised);
593
+ const responderJid = getKeyAuthor(message.key, meLidNormalised);
594
+ const eventEncKey = eventMsg.messageContextInfo?.messageSecret;
595
+ if (!eventEncKey) {
596
+ logger?.warn(
597
+ { encEventEdit: encEventEdit, creationMsgKey: creationMsgKey },
598
+ "event edit: missing messageSecret for decryption"
599
+ );
600
+ } else {
601
+ const responseMsg = decryptEventEdit(encEventEdit, {
602
+ eventEncKey: eventEncKey,
603
+ eventCreatorJid: eventCreatorJid,
604
+ eventMsgId: creationMsgKey.id,
605
+ responderJid: responderJid,
606
+ });
607
+ const content = normalizeMessageContent(responseMsg);
608
+ const protocolMsg = content?.protocolMessage;
609
+ ev.emit("messages.update", [
610
+ {
611
+ key: { ...message.key, id: protocolMsg.key?.id },
612
+ update: {
613
+ message: {
614
+ messageContextInfo: responseMsg.messageContextInfo,
615
+ editedMessage: { message: protocolMsg.editedMessage },
616
+ },
617
+ messageTimestamp: protocolMsg.timestampMs
618
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1e3)
619
+ : message.messageTimestamp,
620
+ },
621
+ },
622
+ ]);
623
+ }
624
+ } catch (err) {
625
+ logger?.warn(
626
+ {
627
+ err: err,
628
+ creationMsgKey: creationMsgKey,
629
+ encEventEdit: encEventEdit,
630
+ },
631
+ "failed to decrypt event edit"
632
+ );
633
+ }
634
+ } else {
635
+ logger?.warn(
636
+ { encEventEdit: encEventEdit, creationMsgKey: creationMsgKey },
637
+ "event creation message not found, cannot decrypt update"
638
+ );
639
+ }
640
+ } else if (content?.encEventResponseMessage) {
641
+ const encEventResponse = content.encEventResponseMessage;
642
+ const creationMsgKey = encEventResponse.eventCreationMessageKey;
643
+ const eventMsg = await getMessage(creationMsgKey);
644
+ if (eventMsg) {
645
+ try {
646
+ const meLidNormalised = jidNormalizedUser(meLid);
647
+ const eventCreatorJid = getKeyAuthor(creationMsgKey, meLidNormalised);
648
+ const responderJid = getKeyAuthor(message.key, meLidNormalised);
649
+ const eventEncKey = eventMsg.messageContextInfo?.messageSecret;
650
+ if (!eventEncKey) {
651
+ logger?.warn(
652
+ {
653
+ encEventResponse: encEventResponse,
654
+ creationMsgKey: creationMsgKey,
655
+ },
656
+ "event response: missing messageSecret for decryption"
657
+ );
658
+ } else {
659
+ const responseMsg = decryptEventResponse(encEventResponse, {
660
+ eventEncKey: eventEncKey,
661
+ eventCreatorJid: eventCreatorJid,
662
+ eventMsgId: creationMsgKey.id,
663
+ responderJid: responderJid,
664
+ });
665
+ const eventResponse = {
666
+ eventResponseMessageKey: message.key,
667
+ senderTimestampMs: responseMsg.timestampMs,
668
+ response: responseMsg,
669
+ };
670
+ ev.emit("messages.update", [
671
+ {
672
+ key: creationMsgKey,
673
+ update: { eventResponses: [eventResponse] },
674
+ },
675
+ ]);
676
+ }
677
+ } catch (err) {
678
+ logger?.warn(
679
+ {
680
+ err: err,
681
+ creationMsgKey: creationMsgKey,
682
+ encEventResponse: encEventResponse,
683
+ },
684
+ "failed to decrypt event response"
685
+ );
686
+ }
687
+ } else {
688
+ logger?.warn(
689
+ { encEventResponse: encEventResponse, creationMsgKey: creationMsgKey },
690
+ "event creation message not found, cannot decrypt update"
691
+ );
692
+ }
693
+ } else if (content?.encCommentMessage) {
694
+ const encComment = content.encCommentMessage;
695
+ const creationMsgKey = encComment.targetMessageKey;
696
+ const commentMsg = await getMessage(creationMsgKey);
697
+ if (commentMsg) {
698
+ try {
699
+ const meLidNormalised = jidNormalizedUser(meLid);
700
+ const commentCreatorJid = creationMsgKey.participant
701
+ ? creationMsgKey.participant
702
+ : message.key?.participant
703
+ ? message.key.participant
704
+ : meLidNormalised;
705
+ const commentJid = message.key?.participant
706
+ ? message.key.participant
707
+ : creationMsgKey.participant
708
+ ? creationMsgKey.participant
709
+ : meLidNormalised;
710
+ const commentEncKey = commentMsg.messageContextInfo?.messageSecret;
711
+ if (!commentEncKey) {
712
+ logger?.warn(
713
+ { encComment: encComment, creationMsgKey: creationMsgKey },
714
+ "comment message: missing messageSecret for decryption"
715
+ );
716
+ } else {
717
+ const responseMsg = decryptComment(encComment, {
718
+ commentEncKey: commentEncKey,
719
+ commentCreatorJid: commentCreatorJid,
720
+ commentMsgId: creationMsgKey.id,
721
+ commentJid: commentJid,
722
+ });
723
+ ev.emit("messages.upsert", {
724
+ messages: [{ key: message.key, message: responseMsg }],
725
+ type: "append",
726
+ });
727
+ }
728
+ } catch (err) {
729
+ logger?.warn(
730
+ { err: err, creationMsgKey: creationMsgKey, encComment: encComment },
731
+ "failed to decrypt comment message"
732
+ );
733
+ }
734
+ } else {
735
+ logger?.warn(
736
+ { encComment: encComment, creationMsgKey: creationMsgKey },
737
+ "creation message not found, cannot decrypt"
738
+ );
739
+ }
740
+ } else if (content?.encReactionMessage) {
741
+ const encReaction = content.encReactionMessage;
742
+ const creationMsgKey = encReaction.targetMessageKey;
743
+ const reactMsg = await getMessage(creationMsgKey);
744
+ if (reactMsg) {
745
+ try {
746
+ const meLidNormalised = jidNormalizedUser(meLid);
747
+ const reactionCreatorJid = creationMsgKey.participant
748
+ ? creationMsgKey.participant
749
+ : message.key?.participant
750
+ ? message.key.participant
751
+ : meLidNormalised;
752
+ const reactionJid = message.key?.participant
753
+ ? message.key.participant
754
+ : creationMsgKey.participant
755
+ ? creationMsgKey.participant
756
+ : meLidNormalised;
757
+ const reactionEncKey = reactMsg.messageContextInfo?.messageSecret;
758
+ if (!reactionEncKey) {
759
+ logger?.warn(
760
+ { encReaction: encReaction, creationMsgKey: creationMsgKey },
761
+ "reaction: missing messageSecret for decryption"
762
+ );
763
+ } else {
764
+ const responseMsg = decryptReaction(encReaction, {
765
+ reactionEncKey: reactionEncKey,
766
+ reactionCreatorJid: reactionCreatorJid,
767
+ reactionMsgId: creationMsgKey.id,
768
+ reactionJid: reactionJid,
769
+ });
770
+ const Reaction = {
771
+ key: message.key,
772
+ message: {
773
+ reactionMessage: {
774
+ key: creationMsgKey,
775
+ text: responseMsg.text,
776
+ senderTimestampMs: responseMsg.senderTimestampMs,
777
+ },
778
+ },
779
+ };
780
+ ev.emit("messages.upsert", { messages: [Reaction], type: "append" });
781
+ }
782
+ } catch (err) {
783
+ logger?.warn(
784
+ {
785
+ err: err,
786
+ creationMsgKey: creationMsgKey,
787
+ encReaction: encReaction,
788
+ },
789
+ "failed to decrypt reaction"
790
+ );
791
+ }
792
+ } else {
793
+ logger?.warn(
794
+ { encReaction: encReaction, creationMsgKey: creationMsgKey },
795
+ "creation message not found, cannot decrypt"
796
+ );
797
+ }
798
+ }
799
+ if (Object.keys(chat).length > 1) {
800
+ ev.emit("chats.update", [chat]);
801
+ }
802
+ };
803
+ module.exports = {
804
+ cleanMessage: cleanMessage,
805
+ isRealMessage: isRealMessage,
806
+ shouldIncrementChatUnread: shouldIncrementChatUnread,
807
+ getChatId: getChatId,
808
+ decryptPollVote: decryptPollVote,
809
+ decryptEventEdit: decryptEventEdit,
810
+ decryptEventResponse: decryptEventResponse,
811
+ decryptComment: decryptComment,
812
+ decryptReaction: decryptReaction,
813
+ processMessage: processMessage,
814
+ };