@x4r1s3/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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1262 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/audio-feeder.mjs +179 -0
  18. package/lib/Call/audio-recorder.mjs +250 -0
  19. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  20. package/lib/Call/index.mjs +680 -0
  21. package/lib/Call/relay-transport.mjs +563 -0
  22. package/lib/Call/signaling.mjs +641 -0
  23. package/lib/Call/types.mjs +17 -0
  24. package/lib/Call/video-feeder.mjs +94 -0
  25. package/lib/Call/wasm-engine.mjs +1372 -0
  26. package/lib/Call/worker-bootstrap.mjs +1042 -0
  27. package/lib/Defaults/ban-checker.js +56 -0
  28. package/lib/Defaults/index.js +170 -0
  29. package/lib/Signal/Group/ciphertext-message.js +23 -0
  30. package/lib/Signal/Group/group-session-builder.js +41 -0
  31. package/lib/Signal/Group/group_cipher.js +93 -0
  32. package/lib/Signal/Group/index.js +23 -0
  33. package/lib/Signal/Group/keyhelper.js +29 -0
  34. package/lib/Signal/Group/sender-chain-key.js +37 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  36. package/lib/Signal/Group/sender-key-message.js +77 -0
  37. package/lib/Signal/Group/sender-key-name.js +59 -0
  38. package/lib/Signal/Group/sender-key-record.js +52 -0
  39. package/lib/Signal/Group/sender-key-state.js +95 -0
  40. package/lib/Signal/Group/sender-message-key.js +37 -0
  41. package/lib/Signal/libsignal.js +440 -0
  42. package/lib/Signal/lid-mapping.js +292 -0
  43. package/lib/Socket/Client/index.js +14 -0
  44. package/lib/Socket/Client/types.js +22 -0
  45. package/lib/Socket/Client/websocket.js +65 -0
  46. package/lib/Socket/aigroups.js +327 -0
  47. package/lib/Socket/ban-checker.js +165 -0
  48. package/lib/Socket/business.js +419 -0
  49. package/lib/Socket/chats.js +1921 -0
  50. package/lib/Socket/communities.js +443 -0
  51. package/lib/Socket/graphql.js +911 -0
  52. package/lib/Socket/groups.js +561 -0
  53. package/lib/Socket/index.js +49 -0
  54. package/lib/Socket/interactive-handler.js +612 -0
  55. package/lib/Socket/interop.js +575 -0
  56. package/lib/Socket/managed-account.js +220 -0
  57. package/lib/Socket/messages-recv.js +2191 -0
  58. package/lib/Socket/messages-send.js +4104 -0
  59. package/lib/Socket/mex.js +53 -0
  60. package/lib/Socket/newsletter.js +291 -0
  61. package/lib/Socket/privacy.js +458 -0
  62. package/lib/Socket/registration.js +440 -0
  63. package/lib/Socket/socket.js +1029 -0
  64. package/lib/Socket/status-actions.js +287 -0
  65. package/lib/Socket/username.js +241 -0
  66. package/lib/Store/index.js +16 -0
  67. package/lib/Store/make-cache-manager-store.js +101 -0
  68. package/lib/Store/make-in-memory-store.js +432 -0
  69. package/lib/Store/make-ordered-dictionary.js +90 -0
  70. package/lib/Store/object-repository.js +35 -0
  71. package/lib/Types/Auth.js +13 -0
  72. package/lib/Types/Bussines.js +13 -0
  73. package/lib/Types/Call.js +13 -0
  74. package/lib/Types/Chat.js +19 -0
  75. package/lib/Types/Contact.js +13 -0
  76. package/lib/Types/Events.js +13 -0
  77. package/lib/Types/GroupMetadata.js +13 -0
  78. package/lib/Types/Label.js +36 -0
  79. package/lib/Types/LabelAssociation.js +18 -0
  80. package/lib/Types/Message.js +30 -0
  81. package/lib/Types/Mex.js +53 -0
  82. package/lib/Types/Product.js +13 -0
  83. package/lib/Types/RichType.js +34 -0
  84. package/lib/Types/Signal.js +13 -0
  85. package/lib/Types/Socket.js +14 -0
  86. package/lib/Types/State.js +60 -0
  87. package/lib/Types/USync.js +13 -0
  88. package/lib/Types/index.js +37 -0
  89. package/lib/Utils/auth-utils.js +313 -0
  90. package/lib/Utils/ban-checker.js +48 -0
  91. package/lib/Utils/bot-capabilities.js +96 -0
  92. package/lib/Utils/bot-planning-replay.js +177 -0
  93. package/lib/Utils/browser-utils.js +40 -0
  94. package/lib/Utils/business.js +242 -0
  95. package/lib/Utils/c2582.js +147 -0
  96. package/lib/Utils/chat-utils.js +905 -0
  97. package/lib/Utils/companion-reg-client-utils.js +44 -0
  98. package/lib/Utils/consumer-application.js +114 -0
  99. package/lib/Utils/crypto.js +129 -0
  100. package/lib/Utils/decode-wa-message.js +496 -0
  101. package/lib/Utils/direct-chat-theme.js +164 -0
  102. package/lib/Utils/event-buffer.js +601 -0
  103. package/lib/Utils/experimental-proto.js +206 -0
  104. package/lib/Utils/games/miniapp.js +17 -0
  105. package/lib/Utils/games/slot-machine.js +270 -0
  106. package/lib/Utils/games/website-preview.js +306 -0
  107. package/lib/Utils/generics.js +402 -0
  108. package/lib/Utils/group-history.js +68 -0
  109. package/lib/Utils/group-wallpaper.js +168 -0
  110. package/lib/Utils/history.js +162 -0
  111. package/lib/Utils/identity-change-handler.js +60 -0
  112. package/lib/Utils/index.js +61 -0
  113. package/lib/Utils/jid-display-normalization.js +221 -0
  114. package/lib/Utils/link-preview.js +96 -0
  115. package/lib/Utils/logger.js +14 -0
  116. package/lib/Utils/lt-hash.js +19 -0
  117. package/lib/Utils/make-mutex.js +44 -0
  118. package/lib/Utils/message-composer.js +709 -0
  119. package/lib/Utils/message-inspect.js +79 -0
  120. package/lib/Utils/message-retry-manager.js +253 -0
  121. package/lib/Utils/message-security.js +167 -0
  122. package/lib/Utils/messages-media.js +1027 -0
  123. package/lib/Utils/messages.js +2467 -0
  124. package/lib/Utils/meta-ai-msmsg.js +215 -0
  125. package/lib/Utils/meta-compositing.js +239 -0
  126. package/lib/Utils/native-flow.js +158 -0
  127. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  128. package/lib/Utils/newsletter-status-utils.js +152 -0
  129. package/lib/Utils/noise-handler.js +212 -0
  130. package/lib/Utils/offline-node-processor.js +51 -0
  131. package/lib/Utils/poll-manager.js +206 -0
  132. package/lib/Utils/portable-compat.js +12 -0
  133. package/lib/Utils/pre-key-manager.js +117 -0
  134. package/lib/Utils/process-message.js +610 -0
  135. package/lib/Utils/reporting-utils.js +269 -0
  136. package/lib/Utils/rich-message-utils.js +2841 -0
  137. package/lib/Utils/scheduled-message.js +107 -0
  138. package/lib/Utils/signal.js +212 -0
  139. package/lib/Utils/source-grep.js +57 -0
  140. package/lib/Utils/stanza-ack.js +49 -0
  141. package/lib/Utils/sticker-annotation.js +87 -0
  142. package/lib/Utils/sync-action-utils.js +59 -0
  143. package/lib/Utils/tc-token-utils.js +174 -0
  144. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  145. package/lib/Utils/use-single-file-auth-state.js +108 -0
  146. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  147. package/lib/Utils/validate-connection.js +220 -0
  148. package/lib/Utils/view-once-utils.js +218 -0
  149. package/lib/Utils/voip-rekey.js +32 -0
  150. package/lib/Utils/website-preview.js +27 -0
  151. package/lib/Utils/welcome-flow.js +228 -0
  152. package/lib/Utils/x4r1s3.js +144 -0
  153. package/lib/WABinary/constants.js +1475 -0
  154. package/lib/WABinary/decode.js +273 -0
  155. package/lib/WABinary/encode.js +231 -0
  156. package/lib/WABinary/generic-utils.js +242 -0
  157. package/lib/WABinary/index.js +17 -0
  158. package/lib/WABinary/jid-utils.js +107 -0
  159. package/lib/WABinary/types.js +13 -0
  160. package/lib/WAM/BinaryInfo.js +21 -0
  161. package/lib/WAM/constants.js +22864 -0
  162. package/lib/WAM/encode.js +161 -0
  163. package/lib/WAM/index.js +15 -0
  164. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  167. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  168. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  169. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  170. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  172. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  173. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  174. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  176. package/lib/WAUSync/Protocols/index.js +24 -0
  177. package/lib/WAUSync/USyncQuery.js +213 -0
  178. package/lib/WAUSync/USyncUser.js +66 -0
  179. package/lib/WAUSync/index.js +15 -0
  180. package/lib/antiban.cjs +4726 -0
  181. package/lib/index.d.ts +1285 -0
  182. package/lib/index.js +30 -0
  183. package/package.json +125 -4
@@ -0,0 +1,610 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/process-message.js
5
+ * About: Process message module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: cleanMessage, isRealMessage, shouldIncrementChatUnread, getChatId, decryptPollVote, decryptEventResponse
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import { proto } from '../../WAProto/index.js';
14
+ import { WAMessageStubType } from '../Types/index.js';
15
+ import { getContentType, normalizeMessageContent } from '../Utils/messages.js';
16
+ import { areJidsSameUser, isHostedLidUser, isHostedPnUser, isJidBroadcast, isJidStatusBroadcast, isLidUser, jidDecode, jidEncode, jidNormalizedUser } from '../WABinary/index.js';
17
+ import { aesDecryptGCM, hmacSign, sha256 } from './crypto.js';
18
+ import { getKeyAuthor, toNumber } from './generics.js';
19
+ import { downloadAndProcessHistorySyncNotification } from './history.js';
20
+ const REAL_MSG_STUB_TYPES = new Set([
21
+ WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
22
+ WAMessageStubType.CALL_MISSED_GROUP_VOICE,
23
+ WAMessageStubType.CALL_MISSED_VIDEO,
24
+ WAMessageStubType.CALL_MISSED_VOICE
25
+ ]);
26
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([WAMessageStubType.GROUP_PARTICIPANT_ADD]);
27
+ /** Cleans a received message to further processing */
28
+ export const cleanMessage = (message, meId, meLid) => {
29
+ // ensure remoteJid and participant doesn't have device or agent in it
30
+ if (isHostedPnUser(message.key.remoteJid) || isHostedLidUser(message.key.remoteJid)) {
31
+ message.key.remoteJid = jidEncode(jidDecode(message.key?.remoteJid)?.user, isHostedPnUser(message.key.remoteJid) ? 's.whatsapp.net' : 'lid');
32
+ }
33
+ else {
34
+ message.key.remoteJid = jidNormalizedUser(message.key.remoteJid);
35
+ }
36
+ if (isHostedPnUser(message.key.participant) || isHostedLidUser(message.key.participant)) {
37
+ message.key.participant = jidEncode(jidDecode(message.key.participant)?.user, isHostedPnUser(message.key.participant) ? 's.whatsapp.net' : 'lid');
38
+ }
39
+ else {
40
+ message.key.participant = jidNormalizedUser(message.key.participant);
41
+ }
42
+ const content = normalizeMessageContent(message.message);
43
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
44
+ if (content?.reactionMessage) {
45
+ normaliseKey(content.reactionMessage.key);
46
+ }
47
+ if (content?.pollUpdateMessage) {
48
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
49
+ }
50
+ function normaliseKey(msgKey) {
51
+ // if the reaction is from another user
52
+ // we've to correctly map the key to this user's perspective
53
+ if (!message.key.fromMe) {
54
+ // if the sender believed the message being reacted to is not from them
55
+ // we've to correct the key to be from them, or some other participant
56
+ msgKey.fromMe = !msgKey.fromMe
57
+ ? areJidsSameUser(msgKey.participant || msgKey.remoteJid, meId) ||
58
+ areJidsSameUser(msgKey.participant || msgKey.remoteJid, meLid)
59
+ : // if the message being reacted to, was from them
60
+ // fromMe automatically becomes false
61
+ false;
62
+ // set the remoteJid to being the same as the chat the message came from
63
+ // TODO: investigate inconsistencies
64
+ msgKey.remoteJid = message.key.remoteJid;
65
+ // set participant of the message
66
+ msgKey.participant = msgKey.participant || message.key.participant;
67
+ }
68
+ }
69
+ };
70
+ // TODO: target:audit AUDIT THIS FUNCTION AGAIN
71
+ export const isRealMessage = (message) => {
72
+ const normalizedContent = normalizeMessageContent(message.message);
73
+ const hasSomeContent = !!getContentType(normalizedContent);
74
+ return ((!!normalizedContent ||
75
+ REAL_MSG_STUB_TYPES.has(message.messageStubType) ||
76
+ REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)) &&
77
+ hasSomeContent &&
78
+ !normalizedContent?.protocolMessage &&
79
+ !normalizedContent?.reactionMessage &&
80
+ !normalizedContent?.pollUpdateMessage);
81
+ };
82
+ export const shouldIncrementChatUnread = (message) => !message.key.fromMe && !message.messageStubType;
83
+ /**
84
+ * Get the ID of the chat from the given key.
85
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
86
+ */
87
+ export const getChatId = ({ remoteJid, participant, fromMe }) => {
88
+ if (isJidBroadcast(remoteJid) && !isJidStatusBroadcast(remoteJid) && !fromMe) {
89
+ return participant;
90
+ }
91
+ return remoteJid;
92
+ };
93
+ /**
94
+ * Decrypt a poll vote
95
+ * @param vote encrypted vote
96
+ * @param ctx additional info about the poll required for decryption
97
+ * @returns list of SHA256 options
98
+ */
99
+ export function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid }) {
100
+ const sign = Buffer.concat([
101
+ toBinary(pollMsgId),
102
+ toBinary(pollCreatorJid),
103
+ toBinary(voterJid),
104
+ toBinary('Poll Vote'),
105
+ new Uint8Array([1])
106
+ ]);
107
+ const key0 = hmacSign(pollEncKey, new Uint8Array(32), 'sha256');
108
+ const decKey = hmacSign(sign, key0, 'sha256');
109
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
110
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
111
+ return proto.Message.PollVoteMessage.decode(decrypted);
112
+ function toBinary(txt) {
113
+ return Buffer.from(txt);
114
+ }
115
+ }
116
+ /**
117
+ * Decrypt an event response
118
+ * @param response encrypted event response
119
+ * @param ctx additional info about the event required for decryption
120
+ * @returns event response message
121
+ */
122
+ export function decryptEventResponse({ encPayload, encIv }, { eventCreatorJid, eventMsgId, eventEncKey, responderJid }) {
123
+ const sign = Buffer.concat([
124
+ toBinary(eventMsgId),
125
+ toBinary(eventCreatorJid),
126
+ toBinary(responderJid),
127
+ toBinary('Event Response'),
128
+ new Uint8Array([1])
129
+ ]);
130
+ const key0 = hmacSign(eventEncKey, new Uint8Array(32), 'sha256');
131
+ const decKey = hmacSign(sign, key0, 'sha256');
132
+ const aad = toBinary(`${eventMsgId}\u0000${responderJid}`);
133
+ const decrypted = aesDecryptGCM(encPayload, decKey, encIv, aad);
134
+ return proto.Message.EventResponseMessage.decode(decrypted);
135
+ function toBinary(txt) {
136
+ return Buffer.from(txt);
137
+ }
138
+ }
139
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, signalRepository, keyStore, logger, options, getMessage, messageSecurityStore }) => {
140
+ const meId = creds.me.id;
141
+ const { accountSettings } = creds;
142
+ const chat = { id: jidNormalizedUser(getChatId(message.key)) };
143
+ const isRealMsg = isRealMessage(message);
144
+ if (isRealMsg) {
145
+ chat.messages = [{ message }];
146
+ chat.conversationTimestamp = toNumber(message.messageTimestamp);
147
+ // only increment unread count if not CIPHERTEXT and from another person
148
+ if (shouldIncrementChatUnread(message)) {
149
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
150
+ }
151
+ }
152
+ const content = normalizeMessageContent(message.message);
153
+ await messageSecurityStore?.rememberMessage(message, creds.me);
154
+ if (content?.acp2SettingMessage) {
155
+ const acp2Setting = message.messageContextInfo?.acp2Setting;
156
+ if (acp2Setting) {
157
+ Object.assign(chat, {
158
+ acp2Enabled: acp2Setting.enabled || false,
159
+ acp2SettingTimestamp: toNumber(acp2Setting.settingTimestamp) || toNumber(message.messageTimestamp),
160
+ acp2Trigger: acp2Setting.trigger,
161
+ acp2InitiatedByMe: acp2Setting.initiatedByMe || false
162
+ });
163
+ }
164
+ }
165
+ // unarchive chat if it's a real message, or someone reacted to our message
166
+ // and we've the unarchive chats setting on
167
+ if ((isRealMsg || content?.reactionMessage?.key?.fromMe) && accountSettings?.unarchiveChats) {
168
+ chat.archived = false;
169
+ chat.readOnly = false;
170
+ }
171
+ const protocolMsg = content?.protocolMessage;
172
+ if (protocolMsg) {
173
+ switch (protocolMsg.type) {
174
+ case proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
175
+ const histNotification = protocolMsg.historySyncNotification;
176
+ const process = shouldProcessHistoryMsg;
177
+ const isLatest = !creds.processedHistoryMessages?.length;
178
+ logger?.info({
179
+ histNotification,
180
+ process,
181
+ id: message.key.id,
182
+ isLatest
183
+ }, 'got history notification');
184
+ if (process) {
185
+ // TODO: investigate
186
+ if (histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND) {
187
+ ev.emit('creds.update', {
188
+ processedHistoryMessages: [
189
+ ...(creds.processedHistoryMessages || []),
190
+ { key: message.key, messageTimestamp: message.messageTimestamp }
191
+ ]
192
+ });
193
+ }
194
+ const data = await downloadAndProcessHistorySyncNotification(histNotification, options, logger);
195
+ if (data.lidPnMappings?.length) {
196
+ logger?.debug({ count: data.lidPnMappings.length }, 'processing LID-PN mappings from history sync');
197
+ await signalRepository.lidMapping
198
+ .storeLIDPNMappings(data.lidPnMappings)
199
+ .catch(err => logger?.warn({ err }, 'failed to store LID-PN mappings from history sync'));
200
+ }
201
+ ev.emit('messaging-history.set', {
202
+ ...data,
203
+ isLatest: histNotification.syncType !== proto.HistorySync.HistorySyncType.ON_DEMAND ? isLatest : undefined,
204
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
205
+ });
206
+ }
207
+ break;
208
+ case proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
209
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
210
+ if (keys?.length) {
211
+ let newAppStateSyncKeyId = '';
212
+ await keyStore.transaction(async () => {
213
+ const newKeys = [];
214
+ for (const { keyData, keyId } of keys) {
215
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
216
+ newKeys.push(strKeyId);
217
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
218
+ newAppStateSyncKeyId = strKeyId;
219
+ }
220
+ logger?.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
221
+ }, meId);
222
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
223
+ }
224
+ else {
225
+ logger?.info({ protocolMsg }, 'recv app state sync with 0 keys');
226
+ }
227
+ break;
228
+ case proto.Message.ProtocolMessage.Type.REVOKE:
229
+ ev.emit('messages.update', [
230
+ {
231
+ key: {
232
+ ...message.key,
233
+ id: protocolMsg.key.id
234
+ },
235
+ update: { message: null, messageStubType: WAMessageStubType.REVOKE, key: message.key }
236
+ }
237
+ ]);
238
+ break;
239
+ case proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
240
+ Object.assign(chat, {
241
+ ephemeralSettingTimestamp: toNumber(message.messageTimestamp),
242
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
243
+ });
244
+ break;
245
+ case proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
246
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
247
+ if (response) {
248
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
249
+ const peerDataOperationResult = response.peerDataOperationResult || [];
250
+ for (const result of peerDataOperationResult) {
251
+ const retryResponse = result?.placeholderMessageResendResponse;
252
+ //eslint-disable-next-line max-depth
253
+ if (!retryResponse?.webMessageInfoBytes) {
254
+ continue;
255
+ }
256
+ //eslint-disable-next-line max-depth
257
+ try {
258
+ const webMessageInfo = proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
259
+ const msgId = webMessageInfo.key?.id;
260
+ // Retrieve cached original message data (preserves LID details,
261
+ // timestamps, etc. that the phone may omit in its PDO response)
262
+ const cachedData = msgId ? await placeholderResendCache?.get(msgId) : undefined;
263
+ //eslint-disable-next-line max-depth
264
+ if (msgId) {
265
+ await placeholderResendCache?.del(msgId);
266
+ }
267
+ let finalMsg;
268
+ //eslint-disable-next-line max-depth
269
+ if (cachedData && typeof cachedData === 'object') {
270
+ // Apply decoded message content onto cached metadata (preserves LID etc.)
271
+ cachedData.message = webMessageInfo.message;
272
+ //eslint-disable-next-line max-depth
273
+ if (webMessageInfo.messageTimestamp) {
274
+ cachedData.messageTimestamp = webMessageInfo.messageTimestamp;
275
+ }
276
+ finalMsg = cachedData;
277
+ }
278
+ else {
279
+ finalMsg = webMessageInfo;
280
+ }
281
+ logger?.debug({ msgId, requestId: response.stanzaId }, 'received placeholder resend');
282
+ ev.emit('messages.upsert', {
283
+ messages: [finalMsg],
284
+ type: 'notify',
285
+ requestId: response.stanzaId
286
+ });
287
+ }
288
+ catch (err) {
289
+ logger?.warn({ err, stanzaId: response.stanzaId }, 'failed to decode placeholder resend response');
290
+ }
291
+ }
292
+ }
293
+ break;
294
+ case proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
295
+ if (messageSecurityStore && !await messageSecurityStore.isEditAuthorized(protocolMsg.key?.id, message, creds.me)) {
296
+ logger?.warn?.({ messageId: message.key?.id, targetId: protocolMsg.key?.id }, 'ignoring message edit without a matching trusted original author');
297
+ break;
298
+ }
299
+ ev.emit('messages.update', [
300
+ {
301
+ // flip the sender / fromMe properties because they're in the perspective of the sender
302
+ key: { ...message.key, id: protocolMsg.key?.id },
303
+ update: {
304
+ message: {
305
+ editedMessage: {
306
+ message: protocolMsg.editedMessage
307
+ }
308
+ },
309
+ messageTimestamp: protocolMsg.timestampMs
310
+ ? Math.floor(toNumber(protocolMsg.timestampMs) / 1000)
311
+ : message.messageTimestamp
312
+ }
313
+ }
314
+ ]);
315
+ break;
316
+ case proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE:
317
+ const labelAssociationMsg = protocolMsg.memberLabel;
318
+ if (labelAssociationMsg?.label) {
319
+ ev.emit('group.member-tag.update', {
320
+ groupId: chat.id,
321
+ label: labelAssociationMsg.label,
322
+ participant: message.key.participant,
323
+ participantAlt: message.key.participantAlt,
324
+ messageTimestamp: Number(message.messageTimestamp)
325
+ });
326
+ }
327
+ break;
328
+ case proto.Message.ProtocolMessage.Type.LID_MIGRATION_MAPPING_SYNC:
329
+ const encodedPayload = protocolMsg.lidMigrationMappingSyncMessage?.encodedMappingPayload;
330
+ const { pnToLidMappings, chatDbMigrationTimestamp } = proto.LIDMigrationMappingSyncPayload.decode(encodedPayload);
331
+ logger?.debug({ pnToLidMappings, chatDbMigrationTimestamp }, 'got lid mappings and chat db migration timestamp');
332
+ const pairs = [];
333
+ for (const { pn, latestLid, assignedLid } of pnToLidMappings) {
334
+ const lid = latestLid || assignedLid;
335
+ pairs.push({ lid: `${lid}@lid`, pn: `${pn}@s.whatsapp.net` });
336
+ }
337
+ await signalRepository.lidMapping.storeLIDPNMappings(pairs);
338
+ if (pairs.length) {
339
+ for (const { pn, lid } of pairs) {
340
+ await signalRepository.migrateSession(pn, lid);
341
+ }
342
+ }
343
+ }
344
+ }
345
+ else if (content?.reactionMessage) {
346
+ const reaction = {
347
+ ...content.reactionMessage,
348
+ key: message.key
349
+ };
350
+ ev.emit('messages.reaction', [
351
+ {
352
+ reaction,
353
+ key: content.reactionMessage?.key
354
+ }
355
+ ]);
356
+ }
357
+ else if (content?.encEventResponseMessage) {
358
+ const encEventResponse = content.encEventResponseMessage;
359
+ const creationMsgKey = encEventResponse.eventCreationMessageKey;
360
+ // we need to fetch the event creation message to get the event enc key
361
+ const eventMsg = getMessage ? await getMessage(creationMsgKey) : undefined;
362
+ if (eventMsg) {
363
+ try {
364
+ const meIdNormalised = jidNormalizedUser(meId);
365
+ // all jids need to be PN
366
+ const eventCreatorKey = creationMsgKey.participant || creationMsgKey.remoteJid;
367
+ const eventCreatorPn = isLidUser(eventCreatorKey)
368
+ ? await signalRepository.lidMapping.getPNForLID(eventCreatorKey)
369
+ : eventCreatorKey;
370
+ const eventCreatorJid = getKeyAuthor({ remoteJid: jidNormalizedUser(eventCreatorPn), fromMe: meIdNormalised === eventCreatorPn }, meIdNormalised);
371
+ const responderJid = getKeyAuthor(message.key, meIdNormalised);
372
+ const eventEncKey = eventMsg?.messageContextInfo?.messageSecret;
373
+ if (!eventEncKey) {
374
+ logger?.warn({ creationMsgKey }, 'event response: missing messageSecret for decryption');
375
+ }
376
+ else {
377
+ const responseMsg = decryptEventResponse(encEventResponse, {
378
+ eventEncKey,
379
+ eventCreatorJid,
380
+ eventMsgId: creationMsgKey.id,
381
+ responderJid
382
+ });
383
+ const eventResponse = {
384
+ eventResponseMessageKey: message.key,
385
+ senderTimestampMs: responseMsg.timestampMs,
386
+ response: responseMsg
387
+ };
388
+ ev.emit('messages.update', [
389
+ {
390
+ key: creationMsgKey,
391
+ update: {
392
+ eventResponses: [eventResponse]
393
+ }
394
+ }
395
+ ]);
396
+ }
397
+ }
398
+ catch (err) {
399
+ logger?.warn({ err, creationMsgKey }, 'failed to decrypt event response');
400
+ }
401
+ }
402
+ else {
403
+ logger?.warn({ creationMsgKey }, 'event creation message not found, cannot decrypt response');
404
+ }
405
+ }
406
+ else if (message.messageStubType) {
407
+ const jid = message.key?.remoteJid;
408
+ //let actor = whatsappID (message.participant)
409
+ let participants;
410
+ const emitParticipantsUpdate = (action) => ev.emit('group-participants.update', {
411
+ id: jid,
412
+ author: message.key.participant,
413
+ authorPn: message.key.participantAlt,
414
+ participants,
415
+ action
416
+ });
417
+ const emitGroupUpdate = (update) => {
418
+ ev.emit('groups.update', [
419
+ { id: jid, ...update, author: message.key.participant ?? undefined, authorPn: message.key.participantAlt }
420
+ ]);
421
+ };
422
+ const emitGroupRequestJoin = (participant, action, method) => {
423
+ ev.emit('group.join-request', {
424
+ id: jid,
425
+ author: message.key.participant,
426
+ authorPn: message.key.participantAlt,
427
+ participant: participant.lid,
428
+ participantPn: participant.pn,
429
+ action,
430
+ method: method
431
+ });
432
+ };
433
+ const participantsIncludesMe = () => participants.find(jid => areJidsSameUser(meId, jid.phoneNumber)); // ADD SUPPORT FOR LID
434
+ switch (message.messageStubType) {
435
+ case WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
436
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
437
+ emitParticipantsUpdate('modify');
438
+ break;
439
+ case WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
440
+ case WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
441
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
442
+ emitParticipantsUpdate('remove');
443
+ // mark the chat read only if you left the group
444
+ if (participantsIncludesMe()) {
445
+ chat.readOnly = true;
446
+ }
447
+ break;
448
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD:
449
+ case WAMessageStubType.GROUP_PARTICIPANT_INVITE:
450
+ case WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
451
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
452
+ if (participantsIncludesMe()) {
453
+ chat.readOnly = false;
454
+ }
455
+ emitParticipantsUpdate('add');
456
+ break;
457
+ case WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
458
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
459
+ emitParticipantsUpdate('demote');
460
+ break;
461
+ case WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
462
+ participants = message.messageStubParameters.map((a) => JSON.parse(a)) || [];
463
+ emitParticipantsUpdate('promote');
464
+ break;
465
+ case WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
466
+ const announceValue = message.messageStubParameters?.[0];
467
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
468
+ break;
469
+ case WAMessageStubType.GROUP_CHANGE_RESTRICT:
470
+ const restrictValue = message.messageStubParameters?.[0];
471
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
472
+ break;
473
+ case WAMessageStubType.GROUP_CHANGE_SUBJECT:
474
+ const name = message.messageStubParameters?.[0];
475
+ chat.name = name;
476
+ emitGroupUpdate({ subject: name });
477
+ break;
478
+ case WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
479
+ const description = message.messageStubParameters?.[0];
480
+ chat.description = description;
481
+ emitGroupUpdate({ desc: description });
482
+ break;
483
+ case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
484
+ const code = message.messageStubParameters?.[0];
485
+ emitGroupUpdate({ inviteCode: code });
486
+ break;
487
+ case WAMessageStubType.GROUP_MEMBER_ADD_MODE:
488
+ const memberAddValue = message.messageStubParameters?.[0];
489
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
490
+ break;
491
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
492
+ const approvalMode = message.messageStubParameters?.[0];
493
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
494
+ break;
495
+ case WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD: // TODO: Add other events
496
+ const participant = JSON.parse(message.messageStubParameters?.[0]);
497
+ const action = message.messageStubParameters?.[1];
498
+ const method = message.messageStubParameters?.[2];
499
+ emitGroupRequestJoin(participant, action, method);
500
+ break;
501
+ }
502
+ }
503
+ else if (content?.pollUpdateMessage) {
504
+ const pollUpdate = content.pollUpdateMessage;
505
+ const creationMsgKey = pollUpdate.pollCreationMessageKey;
506
+ const pollMsg = getMessage ? await getMessage(creationMsgKey) : undefined;
507
+ if (!pollMsg) {
508
+ logger?.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
509
+ }
510
+ else if (!pollUpdate.vote || !creationMsgKey?.id) {
511
+ logger?.warn({ creationMsgKey }, 'poll update is missing encrypted vote data or creation id');
512
+ }
513
+ else {
514
+ const pollContent = normalizeMessageContent(pollMsg.message);
515
+ const pollCreation = pollContent?.pollCreationMessage ||
516
+ pollContent?.pollCreationMessageV2 ||
517
+ pollContent?.pollCreationMessageV3 ||
518
+ pollContent?.pollCreationMessageV4 ||
519
+ pollContent?.pollCreationMessageV5 ||
520
+ pollContent?.pollCreationMessageV6;
521
+ const pollEncKey = pollMsg.messageContextInfo?.messageSecret || pollContent?.messageContextInfo?.messageSecret;
522
+ if (!pollEncKey) {
523
+ logger?.warn({ creationMsgKey }, 'poll vote: missing messageSecret for decryption');
524
+ }
525
+ else {
526
+ const meIdNormalized = jidNormalizedUser(meId);
527
+ const meLidNormalized = creds.me?.lid ? jidNormalizedUser(creds.me.lid) : undefined;
528
+ const creatorKeyJid = creationMsgKey.participant || creationMsgKey.remoteJid;
529
+ const creatorPn = creatorKeyJid && isLidUser(creatorKeyJid)
530
+ ? await signalRepository.lidMapping.getPNForLID(creatorKeyJid).catch(() => undefined)
531
+ : creatorKeyJid;
532
+ const creatorCandidates = [...new Set([
533
+ creationMsgKey.fromMe && meLidNormalized,
534
+ creatorKeyJid && isLidUser(creatorKeyJid) && creatorKeyJid,
535
+ creatorPn && jidNormalizedUser(creatorPn),
536
+ getKeyAuthor(creationMsgKey, meIdNormalized)
537
+ ].filter(Boolean).map(jidNormalizedUser))];
538
+ const voterCandidates = [...new Set([
539
+ message.key.participant,
540
+ message.key.participantAlt,
541
+ message.key.remoteJid,
542
+ getKeyAuthor(message.key, meIdNormalized)
543
+ ].filter(Boolean).map(jidNormalizedUser))];
544
+ let voteMsg;
545
+ let resolvedCreatorJid;
546
+ let resolvedVoterJid;
547
+ for (const pollCreatorJid of creatorCandidates) {
548
+ for (const voterJid of voterCandidates) {
549
+ try {
550
+ voteMsg = decryptPollVote(pollUpdate.vote, {
551
+ pollEncKey,
552
+ pollCreatorJid,
553
+ pollMsgId: creationMsgKey.id,
554
+ voterJid
555
+ });
556
+ resolvedCreatorJid = pollCreatorJid;
557
+ resolvedVoterJid = voterJid;
558
+ break;
559
+ }
560
+ catch {
561
+ // WhatsApp currently mixes LID and PN identities in poll crypto.
562
+ }
563
+ }
564
+ if (voteMsg) {
565
+ break;
566
+ }
567
+ }
568
+ if (!voteMsg) {
569
+ logger?.warn({ creationMsgKey, creatorCandidates, voterCandidates }, 'failed to decrypt poll vote with available LID/PN identities');
570
+ }
571
+ else {
572
+ const options = pollCreation?.options || [];
573
+ const optionByHash = new Map(options.map(option => [
574
+ sha256(Buffer.from(option.optionName || '')).toString(),
575
+ option.optionName || ''
576
+ ]));
577
+ const selectedHashes = (voteMsg.selectedOptions || []).map(option => option.toString());
578
+ const selectedOptions = selectedHashes.map(hash => optionByHash.get(hash) || 'Unknown');
579
+ const unselectedOptions = options
580
+ .map(option => option.optionName || '')
581
+ .filter(optionName => !selectedOptions.includes(optionName));
582
+ const pollVote = {
583
+ pollUpdateMessageKey: message.key,
584
+ pollCreationMessageKey: creationMsgKey,
585
+ vote: voteMsg,
586
+ voterJid: resolvedVoterJid,
587
+ pollCreatorJid: resolvedCreatorJid,
588
+ selectedOptions,
589
+ selectedOptionHashes: selectedHashes,
590
+ unselectedOptions,
591
+ senderTimestampMs: pollUpdate.senderTimestampMs ? toNumber(pollUpdate.senderTimestampMs) : undefined
592
+ };
593
+ ev.emit('messages.update', [
594
+ {
595
+ key: creationMsgKey,
596
+ update: {
597
+ pollUpdates: [pollVote]
598
+ }
599
+ }
600
+ ]);
601
+ ev.emit('poll.vote', pollVote);
602
+ }
603
+ }
604
+ }
605
+ }
606
+ if (Object.keys(chat).length > 1) {
607
+ ev.emit('chats.update', [chat]);
608
+ }
609
+ };
610
+ export default processMessage;