@yannajah/baileys 0.0.0-stage → 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 (145) hide show
  1. package/LICENSE +23 -0
  2. package/LICENSE.jexkcode +21 -0
  3. package/README.md +41 -2
  4. package/THIRD_PARTY_NOTICES.md +15 -0
  5. package/WAProto/index.d.ts +16922 -0
  6. package/WAProto/index.js +122451 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/baileys-version.json +3 -0
  9. package/lib/Defaults/index.js +156 -0
  10. package/lib/Defaults/phonenumber-mcc.json +223 -0
  11. package/lib/Signal/Group/ciphertext-message.js +15 -0
  12. package/lib/Signal/Group/group-session-builder.js +64 -0
  13. package/lib/Signal/Group/group_cipher.js +96 -0
  14. package/lib/Signal/Group/index.js +57 -0
  15. package/lib/Signal/Group/keyhelper.js +55 -0
  16. package/lib/Signal/Group/queue-job.js +57 -0
  17. package/lib/Signal/Group/sender-chain-key.js +34 -0
  18. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  19. package/lib/Signal/Group/sender-key-message.js +69 -0
  20. package/lib/Signal/Group/sender-key-name.js +51 -0
  21. package/lib/Signal/Group/sender-key-record.js +53 -0
  22. package/lib/Signal/Group/sender-key-state.js +99 -0
  23. package/lib/Signal/Group/sender-message-key.js +29 -0
  24. package/lib/Signal/libsignal.js +174 -0
  25. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  26. package/lib/Socket/Client/index.js +19 -0
  27. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  28. package/lib/Socket/Client/web-socket-client.js +87 -0
  29. package/lib/Socket/business.js +260 -0
  30. package/lib/Socket/chats.js +1002 -0
  31. package/lib/Socket/clutch-handler.d.ts +27 -0
  32. package/lib/Socket/clutch-handler.js +880 -0
  33. package/lib/Socket/groups.js +317 -0
  34. package/lib/Socket/index.js +97 -0
  35. package/lib/Socket/messages-recv.js +1154 -0
  36. package/lib/Socket/messages-send.js +946 -0
  37. package/lib/Socket/newsletter.js +411 -0
  38. package/lib/Socket/registration.js +166 -0
  39. package/lib/Socket/socket.js +688 -0
  40. package/lib/Socket/usync.js +70 -0
  41. package/lib/Store/index.js +10 -0
  42. package/lib/Store/make-cache-manager-store.js +83 -0
  43. package/lib/Store/make-in-memory-store.js +457 -0
  44. package/lib/Store/make-ordered-dictionary.js +81 -0
  45. package/lib/Store/object-repository.js +27 -0
  46. package/lib/Types/Auth.js +2 -0
  47. package/lib/Types/Call.js +2 -0
  48. package/lib/Types/Chat.js +4 -0
  49. package/lib/Types/Contact.js +2 -0
  50. package/lib/Types/Events.js +2 -0
  51. package/lib/Types/GroupMetadata.js +2 -0
  52. package/lib/Types/Label.js +27 -0
  53. package/lib/Types/LabelAssociation.js +9 -0
  54. package/lib/Types/Message.js +10 -0
  55. package/lib/Types/Mex.d.ts +2 -0
  56. package/lib/Types/Mex.js +98 -0
  57. package/lib/Types/Newsletter.js +41 -0
  58. package/lib/Types/Product.js +2 -0
  59. package/lib/Types/Signal.js +2 -0
  60. package/lib/Types/Socket.js +2 -0
  61. package/lib/Types/State.js +2 -0
  62. package/lib/Types/USync.js +2 -0
  63. package/lib/Types/index.js +43 -0
  64. package/lib/Utils/MessageBuilder.d.ts +215 -0
  65. package/lib/Utils/MessageBuilder.js +4001 -0
  66. package/lib/Utils/a2ui.d.ts +202 -0
  67. package/lib/Utils/a2ui.js +770 -0
  68. package/lib/Utils/auth-utils.js +206 -0
  69. package/lib/Utils/baileys-event-stream.js +63 -0
  70. package/lib/Utils/bot-signature.d.ts +22 -0
  71. package/lib/Utils/bot-signature.js +125 -0
  72. package/lib/Utils/business.js +234 -0
  73. package/lib/Utils/channel-manager.d.ts +39 -0
  74. package/lib/Utils/channel-manager.js +312 -0
  75. package/lib/Utils/chat-utils.js +729 -0
  76. package/lib/Utils/crypto.js +151 -0
  77. package/lib/Utils/decode-wa-message.js +198 -0
  78. package/lib/Utils/event-buffer.js +514 -0
  79. package/lib/Utils/extras.d.ts +449 -0
  80. package/lib/Utils/extras.js +1377 -0
  81. package/lib/Utils/generics.js +574 -0
  82. package/lib/Utils/history.js +96 -0
  83. package/lib/Utils/html-app.d.ts +39 -0
  84. package/lib/Utils/html-app.js +307 -0
  85. package/lib/Utils/index.d.ts +23 -0
  86. package/lib/Utils/index.js +51 -0
  87. package/lib/Utils/link-preview.js +93 -0
  88. package/lib/Utils/logger.js +7 -0
  89. package/lib/Utils/lt-hash.js +51 -0
  90. package/lib/Utils/make-mutex.js +43 -0
  91. package/lib/Utils/message-retry-manager.d.ts +42 -0
  92. package/lib/Utils/message-retry-manager.js +309 -0
  93. package/lib/Utils/messages-media.js +861 -0
  94. package/lib/Utils/messages.js +1085 -0
  95. package/lib/Utils/metaai.d.ts +438 -0
  96. package/lib/Utils/metaai.js +911 -0
  97. package/lib/Utils/mini-app.d.ts +93 -0
  98. package/lib/Utils/mini-app.js +453 -0
  99. package/lib/Utils/modern-messages.d.ts +150 -0
  100. package/lib/Utils/modern-messages.js +498 -0
  101. package/lib/Utils/native-flow.d.ts +14 -0
  102. package/lib/Utils/native-flow.js +122 -0
  103. package/lib/Utils/newsletter-status.d.ts +163 -0
  104. package/lib/Utils/newsletter-status.js +695 -0
  105. package/lib/Utils/noise-handler.js +155 -0
  106. package/lib/Utils/payment-messages.d.ts +59 -0
  107. package/lib/Utils/payment-messages.js +164 -0
  108. package/lib/Utils/process-message.js +334 -0
  109. package/lib/Utils/reporting-utils.d.ts +12 -0
  110. package/lib/Utils/reporting-utils.js +271 -0
  111. package/lib/Utils/scheduled-message.d.ts +82 -0
  112. package/lib/Utils/scheduled-message.js +126 -0
  113. package/lib/Utils/signal.js +153 -0
  114. package/lib/Utils/spr.d.ts +26 -0
  115. package/lib/Utils/spr.js +525 -0
  116. package/lib/Utils/status-stickers.d.ts +78 -0
  117. package/lib/Utils/status-stickers.js +275 -0
  118. package/lib/Utils/telegram-adapter.d.ts +28 -0
  119. package/lib/Utils/telegram-adapter.js +285 -0
  120. package/lib/Utils/use-multi-file-auth-state.js +153 -0
  121. package/lib/Utils/validate-connection.js +235 -0
  122. package/lib/WABinary/constants.js +40 -0
  123. package/lib/WABinary/decode.js +252 -0
  124. package/lib/WABinary/encode.js +265 -0
  125. package/lib/WABinary/generic-utils.js +178 -0
  126. package/lib/WABinary/index.js +21 -0
  127. package/lib/WABinary/jid-utils.js +81 -0
  128. package/lib/WABinary/types.js +2 -0
  129. package/lib/WAM/BinaryInfo.js +13 -0
  130. package/lib/WAM/constants.js +15350 -0
  131. package/lib/WAM/encode.js +155 -0
  132. package/lib/WAM/index.js +19 -0
  133. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  134. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  135. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  136. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  137. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  138. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  139. package/lib/WAUSync/Protocols/index.js +20 -0
  140. package/lib/WAUSync/USyncQuery.js +89 -0
  141. package/lib/WAUSync/USyncUser.js +26 -0
  142. package/lib/WAUSync/index.js +19 -0
  143. package/lib/index.d.ts +20 -0
  144. package/lib/index.js +99 -0
  145. package/package.json +110 -4
@@ -0,0 +1,334 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decryptPollVote = exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
4
+ const WAProto_1 = require("../../WAProto");
5
+ const Types_1 = require("../Types");
6
+ const messages_1 = require("../Utils/messages");
7
+ const WABinary_1 = require("../WABinary");
8
+ const crypto_1 = require("./crypto");
9
+ const generics_1 = require("./generics");
10
+ const history_1 = require("./history");
11
+ const REAL_MSG_STUB_TYPES = new Set([
12
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
13
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
14
+ Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
15
+ Types_1.WAMessageStubType.CALL_MISSED_VOICE
16
+ ]);
17
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
18
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
19
+ ]);
20
+ /** Cleans a received message to further processing */
21
+ const cleanMessage = (message, meId) => {
22
+ // ensure remoteJid and participant doesn't have device or agent in it
23
+ message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
24
+ message.key.participant = message.key.participant ? (0, WABinary_1.jidNormalizedUser)(message.key.participant) : undefined;
25
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
26
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
27
+ if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
28
+ normaliseKey(content.reactionMessage.key);
29
+ }
30
+ if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
31
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
32
+ }
33
+ function normaliseKey(msgKey) {
34
+ // if the reaction is from another user
35
+ // we've to correctly map the key to this user's perspective
36
+ if (!message.key.fromMe) {
37
+ // if the sender believed the message being reacted to is not from them
38
+ // we've to correct the key to be from them, or some other participant
39
+ msgKey.fromMe = !msgKey.fromMe
40
+ ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
41
+ // if the message being reacted to, was from them
42
+ // fromMe automatically becomes false
43
+ : false;
44
+ // set the remoteJid to being the same as the chat the message came from
45
+ msgKey.remoteJid = message.key.remoteJid;
46
+ // set participant of the message
47
+ msgKey.participant = msgKey.participant || message.key.participant;
48
+ }
49
+ }
50
+ };
51
+ exports.cleanMessage = cleanMessage;
52
+ const isRealMessage = (message, meId) => {
53
+ var _a;
54
+ const normalizedContent = (0, messages_1.normalizeMessageContent)(message.message);
55
+ const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
56
+ return (!!normalizedContent
57
+ || REAL_MSG_STUB_TYPES.has(message.messageStubType)
58
+ || (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)
59
+ && ((_a = message.messageStubParameters) === null || _a === void 0 ? void 0 : _a.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))))
60
+ && hasSomeContent
61
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)
62
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)
63
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.pollUpdateMessage);
64
+ };
65
+ exports.isRealMessage = isRealMessage;
66
+ const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType);
67
+ exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
68
+ /**
69
+ * Get the ID of the chat from the given key.
70
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
71
+ */
72
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
73
+ if ((0, WABinary_1.isJidBroadcast)(remoteJid)
74
+ && !(0, WABinary_1.isJidStatusBroadcast)(remoteJid)
75
+ && !fromMe) {
76
+ return participant;
77
+ }
78
+ return remoteJid;
79
+ };
80
+ exports.getChatId = getChatId;
81
+ /**
82
+ * Decrypt a poll vote
83
+ * @param vote encrypted vote
84
+ * @param ctx additional info about the poll required for decryption
85
+ * @returns list of SHA256 options
86
+ */
87
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
88
+ const sign = Buffer.concat([
89
+ toBinary(pollMsgId),
90
+ toBinary(pollCreatorJid),
91
+ toBinary(voterJid),
92
+ toBinary('Poll Vote'),
93
+ new Uint8Array([1])
94
+ ]);
95
+ const key0 = (0, crypto_1.hmacSign)(pollEncKey, new Uint8Array(32), 'sha256');
96
+ const decKey = (0, crypto_1.hmacSign)(sign, key0, 'sha256');
97
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
98
+ const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
99
+ return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
100
+ function toBinary(txt) {
101
+ return Buffer.from(txt);
102
+ }
103
+ }
104
+ exports.decryptPollVote = decryptPollVote;
105
+ const processMessage = async (message, { shouldProcessHistoryMsg, ev, creds, keyStore, logger, options, getMessage }) => {
106
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
107
+ const meId = creds.me.id;
108
+ const { accountSettings } = creds;
109
+ const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
110
+ const isRealMsg = (0, exports.isRealMessage)(message, meId);
111
+ if (isRealMsg) {
112
+ chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
113
+ // only increment unread count if not CIPHERTEXT and from another person
114
+ if ((0, exports.shouldIncrementChatUnread)(message)) {
115
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
116
+ }
117
+ }
118
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
119
+ // unarchive chat if it's a real message, or someone reacted to our message
120
+ // and we've the unarchive chats setting on
121
+ if ((isRealMsg || ((_b = (_a = content === null || content === void 0 ? void 0 : content.reactionMessage) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.fromMe))
122
+ && (accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats)) {
123
+ chat.archived = false;
124
+ chat.readOnly = false;
125
+ }
126
+ const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
127
+ if (protocolMsg) {
128
+ const SELF_ONLY_TYPES = new Set([
129
+ WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION,
130
+ WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE,
131
+ WAProto_1.proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC,
132
+ WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE
133
+ ]);
134
+ if (protocolMsg.type !== null &&
135
+ protocolMsg.type !== undefined &&
136
+ SELF_ONLY_TYPES.has(protocolMsg.type) &&
137
+ !message.key.fromMe) {
138
+ logger === null || logger === void 0 ? void 0 : logger.warn({ msgId: message.key.id, type: protocolMsg.type, from: message.key.participant || message.key.remoteJid }, 'dropping spoofed self-only protocolMessage from non-self origin');
139
+ return;
140
+ }
141
+ switch (protocolMsg.type) {
142
+ case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
143
+ const histNotification = protocolMsg.historySyncNotification;
144
+ const process = shouldProcessHistoryMsg;
145
+ const isLatest = !((_c = creds.processedHistoryMessages) === null || _c === void 0 ? void 0 : _c.length);
146
+ logger === null || logger === void 0 ? void 0 : logger.info({
147
+ histNotification,
148
+ process,
149
+ id: message.key.id,
150
+ isLatest,
151
+ }, 'got history notification');
152
+ if (process) {
153
+ ev.emit('creds.update', {
154
+ processedHistoryMessages: [
155
+ ...(creds.processedHistoryMessages || []),
156
+ { key: message.key, messageTimestamp: message.messageTimestamp }
157
+ ]
158
+ });
159
+ const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
160
+ ev.emit('messaging-history.set', { ...data, isLatest });
161
+ }
162
+ break;
163
+ case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
164
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
165
+ if (keys === null || keys === void 0 ? void 0 : keys.length) {
166
+ let newAppStateSyncKeyId = '';
167
+ await keyStore.transaction(async () => {
168
+ const newKeys = [];
169
+ for (const { keyData, keyId } of keys) {
170
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
171
+ newKeys.push(strKeyId);
172
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
173
+ newAppStateSyncKeyId = strKeyId;
174
+ }
175
+ logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
176
+ });
177
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
178
+ }
179
+ else {
180
+ logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
181
+ }
182
+ break;
183
+ case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
184
+ ev.emit('messages.update', [
185
+ {
186
+ key: {
187
+ ...message.key,
188
+ id: protocolMsg.key.id
189
+ },
190
+ update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
191
+ }
192
+ ]);
193
+ break;
194
+ case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
195
+ Object.assign(chat, {
196
+ ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
197
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
198
+ });
199
+ break;
200
+ case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
201
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
202
+ if (response) {
203
+ const { peerDataOperationResult } = response;
204
+ for (const result of peerDataOperationResult) {
205
+ const { placeholderMessageResendResponse: retryResponse } = result;
206
+ if (retryResponse) {
207
+ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
208
+ ev.emit('messages.update', [
209
+ { key: webMessageInfo.key, update: { message: webMessageInfo.message } }
210
+ ]);
211
+ }
212
+ }
213
+ }
214
+ break;
215
+ }
216
+ }
217
+ else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
218
+ const reaction = {
219
+ ...content.reactionMessage,
220
+ key: message.key,
221
+ };
222
+ ev.emit('messages.reaction', [{
223
+ reaction,
224
+ key: content.reactionMessage.key,
225
+ }]);
226
+ }
227
+ else if (message.messageStubType) {
228
+ const jid = message.key.remoteJid;
229
+ //let actor = whatsappID (message.participant)
230
+ let participants;
231
+ const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action }));
232
+ const emitGroupUpdate = (update) => {
233
+ var _a;
234
+ ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
235
+ };
236
+ const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
237
+ switch (message.messageStubType) {
238
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
239
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
240
+ participants = message.messageStubParameters || [];
241
+ emitParticipantsUpdate('remove');
242
+ // mark the chat read only if you left the group
243
+ if (participantsIncludesMe()) {
244
+ chat.readOnly = true;
245
+ }
246
+ break;
247
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
248
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
249
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
250
+ participants = message.messageStubParameters || [];
251
+ if (participantsIncludesMe()) {
252
+ chat.readOnly = false;
253
+ }
254
+ emitParticipantsUpdate('add');
255
+ break;
256
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
257
+ participants = message.messageStubParameters || [];
258
+ emitParticipantsUpdate('demote');
259
+ break;
260
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
261
+ participants = message.messageStubParameters || [];
262
+ emitParticipantsUpdate('promote');
263
+ break;
264
+ case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
265
+ const announceValue = (_d = message.messageStubParameters) === null || _d === void 0 ? void 0 : _d[0];
266
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
267
+ break;
268
+ case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
269
+ const restrictValue = (_e = message.messageStubParameters) === null || _e === void 0 ? void 0 : _e[0];
270
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
271
+ break;
272
+ case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
273
+ const name = (_f = message.messageStubParameters) === null || _f === void 0 ? void 0 : _f[0];
274
+ chat.name = name;
275
+ emitGroupUpdate({ subject: name });
276
+ break;
277
+ case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
278
+ const code = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
279
+ emitGroupUpdate({ inviteCode: code });
280
+ break;
281
+ case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
282
+ const memberAddValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
283
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
284
+ break;
285
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
286
+ const approvalMode = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
287
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
288
+ break;
289
+ }
290
+ }
291
+ else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
292
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
293
+ // we need to fetch the poll creation message to get the poll enc key
294
+ const pollMsg = await getMessage(creationMsgKey);
295
+ if (pollMsg) {
296
+ const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
297
+ const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
298
+ const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
299
+ const pollEncKey = (_k = pollMsg.messageContextInfo) === null || _k === void 0 ? void 0 : _k.messageSecret;
300
+ try {
301
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
302
+ pollEncKey,
303
+ pollCreatorJid,
304
+ pollMsgId: creationMsgKey.id,
305
+ voterJid,
306
+ });
307
+ ev.emit('messages.update', [
308
+ {
309
+ key: creationMsgKey,
310
+ update: {
311
+ pollUpdates: [
312
+ {
313
+ pollUpdateMessageKey: message.key,
314
+ vote: voteMsg,
315
+ senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
316
+ }
317
+ ]
318
+ }
319
+ }
320
+ ]);
321
+ }
322
+ catch (err) {
323
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
324
+ }
325
+ }
326
+ else {
327
+ logger === null || logger === void 0 ? void 0 : logger.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
328
+ }
329
+ }
330
+ if (Object.keys(chat).length > 1) {
331
+ ev.emit('chats.update', [chat]);
332
+ }
333
+ };
334
+ exports.default = processMessage;
@@ -0,0 +1,12 @@
1
+ export const shouldIncludeReportingToken: (message: any) => boolean;
2
+ export const getMessageReportingToken: (msgProtobuf: any, message: any, key: any) => Promise<{
3
+ tag: string;
4
+ attrs: {};
5
+ content: {
6
+ tag: string;
7
+ attrs: {
8
+ v: string;
9
+ };
10
+ content: any;
11
+ }[];
12
+ } | null>;
@@ -0,0 +1,271 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMessageReportingToken = exports.shouldIncludeReportingToken = void 0;
4
+
5
+ const crypto_1 = require("crypto");
6
+ const crypto_2 = require("./crypto");
7
+
8
+ const reportingFields = [
9
+ { f: 1 },
10
+ {
11
+ f: 3,
12
+ s: [{ f: 2 }, { f: 3 }, { f: 8 }, { f: 11 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 25 }]
13
+ },
14
+ { f: 4, s: [{ f: 1 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
15
+ { f: 5, s: [{ f: 3 }, { f: 4 }, { f: 5 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
16
+ { f: 6, s: [{ f: 1 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 30 }] },
17
+ { f: 7, s: [{ f: 2 }, { f: 7 }, { f: 10 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 20 }] },
18
+ { f: 8, s: [{ f: 2 }, { f: 7 }, { f: 9 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 21 }] },
19
+ { f: 9, s: [{ f: 2 }, { f: 6 }, { f: 7 }, { f: 13 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 20 }] },
20
+ { f: 12, s: [{ f: 1 }, { f: 2 }, { f: 14, m: true }, { f: 15 }] },
21
+ { f: 18, s: [{ f: 6 }, { f: 16 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
22
+ { f: 26, s: [{ f: 4 }, { f: 5 }, { f: 8 }, { f: 13 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }] },
23
+ { f: 28, s: [{ f: 1 }, { f: 2 }, { f: 4 }, { f: 5 }, { f: 6 }, { f: 7, s: [{ f: 21 }, { f: 22 }] }] },
24
+ { f: 37, s: [{ f: 1, m: true }] },
25
+ {
26
+ f: 49,
27
+ s: [
28
+ { f: 2 },
29
+ { f: 3, s: [{ f: 1 }, { f: 2 }] },
30
+ { f: 5, s: [{ f: 21 }, { f: 22 }] },
31
+ { f: 8, s: [{ f: 1 }, { f: 2 }] }
32
+ ]
33
+ },
34
+ { f: 53, s: [{ f: 1, m: true }] },
35
+ { f: 55, s: [{ f: 1, m: true }] },
36
+ { f: 58, s: [{ f: 1, m: true }] },
37
+ { f: 59, s: [{ f: 1, m: true }] },
38
+ {
39
+ f: 60,
40
+ s: [
41
+ { f: 2 },
42
+ { f: 3, s: [{ f: 1 }, { f: 2 }] },
43
+ { f: 5, s: [{ f: 21 }, { f: 22 }] },
44
+ { f: 8, s: [{ f: 1 }, { f: 2 }] }
45
+ ]
46
+ },
47
+ {
48
+ f: 64,
49
+ s: [
50
+ { f: 2 },
51
+ { f: 3, s: [{ f: 1 }, { f: 2 }] },
52
+ { f: 5, s: [{ f: 21 }, { f: 22 }] },
53
+ { f: 8, s: [{ f: 1 }, { f: 2 }] }
54
+ ]
55
+ },
56
+ { f: 66, s: [{ f: 2 }, { f: 6 }, { f: 7 }, { f: 13 }, { f: 17, s: [{ f: 21 }, { f: 22 }] }, { f: 20 }] },
57
+ { f: 74, s: [{ f: 1, m: true }] },
58
+ { f: 87, s: [{ f: 1, m: true }] },
59
+ { f: 88, s: [{ f: 1 }, { f: 2, s: [{ f: 1 }] }, { f: 3, s: [{ f: 21 }, { f: 22 }] }] },
60
+ { f: 92, s: [{ f: 1, m: true }] },
61
+ { f: 93, s: [{ f: 1, m: true }] },
62
+ { f: 94, s: [{ f: 1, m: true }] }
63
+ ];
64
+
65
+ const compileReportingFields = (fields) => {
66
+ const map = new Map();
67
+ for (const f of fields) {
68
+ map.set(f.f, {
69
+ m: f.m,
70
+ children: f.s ? compileReportingFields(f.s) : undefined
71
+ });
72
+ }
73
+ return map;
74
+ };
75
+
76
+ const compiledReportingFields = compileReportingFields(reportingFields);
77
+ const EMPTY_MAP = new Map();
78
+ const ENC_SECRET_REPORT_TOKEN = 'Report Token';
79
+ const WIRE = {
80
+ VARINT: 0,
81
+ FIXED64: 1,
82
+ BYTES: 2,
83
+ FIXED32: 5
84
+ };
85
+
86
+ const shouldIncludeReportingToken = (message) => !message.reactionMessage &&
87
+ !message.encReactionMessage &&
88
+ !message.encEventResponseMessage &&
89
+ !message.pollUpdateMessage;
90
+ exports.shouldIncludeReportingToken = shouldIncludeReportingToken;
91
+
92
+ const generateMsgSecretKey = (modificationType, origMsgId, origMsgSender, modificationSender, origMsgSecret) => {
93
+ const useCaseSecret = Buffer.concat([
94
+ Buffer.from(origMsgId, 'utf8'),
95
+ Buffer.from(origMsgSender, 'utf8'),
96
+ Buffer.from(modificationSender, 'utf8'),
97
+ Buffer.from(modificationType, 'utf8')
98
+ ]);
99
+ return (0, crypto_2.hkdf)(origMsgSecret, 32, { info: useCaseSecret.toString('latin1') });
100
+ };
101
+
102
+ const decodeVarint = (buffer, offset) => {
103
+ let value = 0;
104
+ let bytes = 0;
105
+ let shift = 0;
106
+ while (offset + bytes < buffer.length) {
107
+ const current = buffer[offset + bytes];
108
+ value |= (current & 0x7f) << shift;
109
+ bytes++;
110
+ if ((current & 0x80) === 0) {
111
+ return { value, bytes, ok: true };
112
+ }
113
+ shift += 7;
114
+ if (shift > 35) {
115
+ return { value: 0, bytes: 0, ok: false };
116
+ }
117
+ }
118
+ return { value: 0, bytes: 0, ok: false };
119
+ };
120
+
121
+ const encodeVarint = (value) => {
122
+ const parts = [];
123
+ let remaining = value >>> 0;
124
+ while (remaining > 0x7f) {
125
+ parts.push((remaining & 0x7f) | 0x80);
126
+ remaining >>>= 7;
127
+ }
128
+ parts.push(remaining);
129
+ return Buffer.from(parts);
130
+ };
131
+
132
+ const extractReportingTokenContent = (data, cfg) => {
133
+ const out = [];
134
+ let i = 0;
135
+ while (i < data.length) {
136
+ const tag = decodeVarint(data, i);
137
+ if (!tag.ok) {
138
+ return null;
139
+ }
140
+ const fieldNum = tag.value >> 3;
141
+ const wireType = tag.value & 0x7;
142
+ const fieldStart = i;
143
+ i += tag.bytes;
144
+ const fieldCfg = cfg.get(fieldNum);
145
+ const pushSlice = (end) => {
146
+ if (end > data.length) {
147
+ return false;
148
+ }
149
+ out.push({ num: fieldNum, bytes: data.subarray(fieldStart, end) });
150
+ i = end;
151
+ return true;
152
+ };
153
+ const skip = (end) => {
154
+ if (end > data.length) {
155
+ return false;
156
+ }
157
+ i = end;
158
+ return true;
159
+ };
160
+ if (wireType === WIRE.VARINT) {
161
+ const v = decodeVarint(data, i);
162
+ if (!v.ok) {
163
+ return null;
164
+ }
165
+ const end = i + v.bytes;
166
+ if (!fieldCfg) {
167
+ if (!skip(end)) {
168
+ return null;
169
+ }
170
+ continue;
171
+ }
172
+ if (!pushSlice(end)) {
173
+ return null;
174
+ }
175
+ continue;
176
+ }
177
+ if (wireType === WIRE.FIXED64) {
178
+ const end = i + 8;
179
+ if (!fieldCfg) {
180
+ if (!skip(end)) {
181
+ return null;
182
+ }
183
+ continue;
184
+ }
185
+ if (!pushSlice(end)) {
186
+ return null;
187
+ }
188
+ continue;
189
+ }
190
+ if (wireType === WIRE.FIXED32) {
191
+ const end = i + 4;
192
+ if (!fieldCfg) {
193
+ if (!skip(end)) {
194
+ return null;
195
+ }
196
+ continue;
197
+ }
198
+ if (!pushSlice(end)) {
199
+ return null;
200
+ }
201
+ continue;
202
+ }
203
+ if (wireType === WIRE.BYTES) {
204
+ const len = decodeVarint(data, i);
205
+ if (!len.ok) {
206
+ return null;
207
+ }
208
+ const valStart = i + len.bytes;
209
+ const valEnd = valStart + len.value;
210
+ if (valEnd > data.length) {
211
+ return null;
212
+ }
213
+ if (!fieldCfg) {
214
+ i = valEnd;
215
+ continue;
216
+ }
217
+ if (fieldCfg.m || fieldCfg.children) {
218
+ const sub = extractReportingTokenContent(data.subarray(valStart, valEnd), fieldCfg.children ?? EMPTY_MAP);
219
+ if (sub === null) {
220
+ return null;
221
+ }
222
+ if (sub.length > 0) {
223
+ const newTag = encodeVarint(tag.value);
224
+ const newLen = encodeVarint(sub.length);
225
+ out.push({
226
+ num: fieldNum,
227
+ bytes: Buffer.concat([newTag, newLen, sub])
228
+ });
229
+ }
230
+ i = valEnd;
231
+ continue;
232
+ }
233
+ out.push({ num: fieldNum, bytes: data.subarray(fieldStart, valEnd) });
234
+ i = valEnd;
235
+ continue;
236
+ }
237
+ return null;
238
+ }
239
+ if (out.length === 0) {
240
+ return Buffer.alloc(0);
241
+ }
242
+ out.sort((a, b) => a.num - b.num);
243
+ return Buffer.concat(out.map(f => f.bytes));
244
+ };
245
+
246
+ const getMessageReportingToken = async (msgProtobuf, message, key) => {
247
+ const msgSecret = message.messageContextInfo?.messageSecret;
248
+ if (!msgSecret || !key.id) {
249
+ return null;
250
+ }
251
+ const from = key.fromMe ? key.remoteJid : key.participant || key.remoteJid;
252
+ const to = key.fromMe ? key.participant || key.remoteJid : key.remoteJid;
253
+ const reportingSecret = generateMsgSecretKey(ENC_SECRET_REPORT_TOKEN, key.id, from, to, msgSecret);
254
+ const content = extractReportingTokenContent(msgProtobuf, compiledReportingFields);
255
+ if (!content || content.length === 0) {
256
+ return null;
257
+ }
258
+ const reportingToken = (0, crypto_1.createHmac)('sha256', reportingSecret).update(content).digest().subarray(0, 16);
259
+ return {
260
+ tag: 'reporting',
261
+ attrs: {},
262
+ content: [
263
+ {
264
+ tag: 'reporting_token',
265
+ attrs: { v: '2' },
266
+ content: reportingToken
267
+ }
268
+ ]
269
+ };
270
+ };
271
+ exports.getMessageReportingToken = getMessageReportingToken;