queenruva-sockets 5.6.23

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