astrabail 1.0.6

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