@realvare/based 2.5.1

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 (195) hide show
  1. package/LICENSE +41 -0
  2. package/README.MD +829 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4775 -0
  5. package/WAProto/index.d.ts +55057 -0
  6. package/WAProto/index.js +169661 -0
  7. package/WAProto/index.ts.ts +53473 -0
  8. package/WAProto/p.html +1 -0
  9. package/engine-requirements.js +10 -0
  10. package/lib/Defaults/baileys-version.json +3 -0
  11. package/lib/Defaults/index.d.ts +51 -0
  12. package/lib/Defaults/index.js +106 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  14. package/lib/Signal/Group/ciphertext-message.js +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  16. package/lib/Signal/Group/group-session-builder.js +64 -0
  17. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  18. package/lib/Signal/Group/group_cipher.js +96 -0
  19. package/lib/Signal/Group/index.d.ts +11 -0
  20. package/lib/Signal/Group/index.js +57 -0
  21. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  22. package/lib/Signal/Group/keyhelper.js +55 -0
  23. package/lib/Signal/Group/queue-job.d.ts +1 -0
  24. package/lib/Signal/Group/queue-job.js +57 -0
  25. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  26. package/lib/Signal/Group/sender-chain-key.js +34 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  28. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  29. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  30. package/lib/Signal/Group/sender-key-message.js +69 -0
  31. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  32. package/lib/Signal/Group/sender-key-name.js +51 -0
  33. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  34. package/lib/Signal/Group/sender-key-record.js +53 -0
  35. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  36. package/lib/Signal/Group/sender-key-state.js +99 -0
  37. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  38. package/lib/Signal/Group/sender-message-key.js +29 -0
  39. package/lib/Signal/libsignal.d.ts +3 -0
  40. package/lib/Signal/libsignal.js +174 -0
  41. package/lib/Socket/Client/index.d.ts +2 -0
  42. package/lib/Socket/Client/index.js +18 -0
  43. package/lib/Socket/Client/types.d.ts +16 -0
  44. package/lib/Socket/Client/types.js +13 -0
  45. package/lib/Socket/Client/websocket.d.ts +13 -0
  46. package/lib/Socket/Client/websocket.js +111 -0
  47. package/lib/Socket/business.d.ts +172 -0
  48. package/lib/Socket/business.js +260 -0
  49. package/lib/Socket/chats.d.ts +82 -0
  50. package/lib/Socket/chats.js +890 -0
  51. package/lib/Socket/groups.d.ts +124 -0
  52. package/lib/Socket/groups.js +332 -0
  53. package/lib/Socket/index.d.ts +172 -0
  54. package/lib/Socket/index.js +10 -0
  55. package/lib/Socket/messages-recv.d.ts +161 -0
  56. package/lib/Socket/messages-recv.js +1054 -0
  57. package/lib/Socket/messages-send.d.ts +151 -0
  58. package/lib/Socket/messages-send.js +900 -0
  59. package/lib/Socket/newsletter.d.ts +136 -0
  60. package/lib/Socket/newsletter.js +250 -0
  61. package/lib/Socket/socket.d.ts +43 -0
  62. package/lib/Socket/socket.js +654 -0
  63. package/lib/Socket/usync.d.ts +36 -0
  64. package/lib/Socket/usync.js +70 -0
  65. package/lib/Store/index.d.ts +2 -0
  66. package/lib/Store/index.js +8 -0
  67. package/lib/Store/make-in-memory-store.d.ts +118 -0
  68. package/lib/Store/make-in-memory-store.js +439 -0
  69. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  70. package/lib/Store/make-ordered-dictionary.js +81 -0
  71. package/lib/Store/object-repository.d.ts +10 -0
  72. package/lib/Store/object-repository.js +27 -0
  73. package/lib/Types/Auth.d.ts +103 -0
  74. package/lib/Types/Auth.js +2 -0
  75. package/lib/Types/Call.d.ts +13 -0
  76. package/lib/Types/Call.js +2 -0
  77. package/lib/Types/Chat.d.ts +109 -0
  78. package/lib/Types/Chat.js +4 -0
  79. package/lib/Types/Contact.d.ts +23 -0
  80. package/lib/Types/Contact.js +2 -0
  81. package/lib/Types/Events.d.ts +199 -0
  82. package/lib/Types/Events.js +2 -0
  83. package/lib/Types/GroupMetadata.d.ts +64 -0
  84. package/lib/Types/GroupMetadata.js +2 -0
  85. package/lib/Types/Label.d.ts +35 -0
  86. package/lib/Types/Label.js +27 -0
  87. package/lib/Types/LabelAssociation.d.ts +29 -0
  88. package/lib/Types/LabelAssociation.js +9 -0
  89. package/lib/Types/Message.d.ts +414 -0
  90. package/lib/Types/Message.js +7 -0
  91. package/lib/Types/Newsletter.d.ts +79 -0
  92. package/lib/Types/Newsletter.js +18 -0
  93. package/lib/Types/Product.d.ts +78 -0
  94. package/lib/Types/Product.js +2 -0
  95. package/lib/Types/Signal.d.ts +57 -0
  96. package/lib/Types/Signal.js +2 -0
  97. package/lib/Types/Socket.d.ts +119 -0
  98. package/lib/Types/Socket.js +2 -0
  99. package/lib/Types/State.d.ts +27 -0
  100. package/lib/Types/State.js +2 -0
  101. package/lib/Types/USync.d.ts +25 -0
  102. package/lib/Types/USync.js +2 -0
  103. package/lib/Types/index.d.ts +64 -0
  104. package/lib/Types/index.js +42 -0
  105. package/lib/Utils/auth-utils.d.ts +18 -0
  106. package/lib/Utils/auth-utils.js +199 -0
  107. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  108. package/lib/Utils/baileys-event-stream.js +63 -0
  109. package/lib/Utils/business.d.ts +22 -0
  110. package/lib/Utils/business.js +234 -0
  111. package/lib/Utils/chat-utils.d.ts +70 -0
  112. package/lib/Utils/chat-utils.js +730 -0
  113. package/lib/Utils/crypto.d.ts +40 -0
  114. package/lib/Utils/crypto.js +193 -0
  115. package/lib/Utils/decode-wa-message.d.ts +35 -0
  116. package/lib/Utils/decode-wa-message.js +207 -0
  117. package/lib/Utils/event-buffer.d.ts +35 -0
  118. package/lib/Utils/event-buffer.js +518 -0
  119. package/lib/Utils/generics.d.ts +89 -0
  120. package/lib/Utils/generics.js +441 -0
  121. package/lib/Utils/history.d.ts +19 -0
  122. package/lib/Utils/history.js +94 -0
  123. package/lib/Utils/index.d.ts +17 -0
  124. package/lib/Utils/index.js +34 -0
  125. package/lib/Utils/link-preview.d.ts +21 -0
  126. package/lib/Utils/link-preview.js +126 -0
  127. package/lib/Utils/logger.d.ts +11 -0
  128. package/lib/Utils/logger.js +7 -0
  129. package/lib/Utils/lt-hash.d.ts +12 -0
  130. package/lib/Utils/lt-hash.js +51 -0
  131. package/lib/Utils/make-mutex.d.ts +7 -0
  132. package/lib/Utils/make-mutex.js +43 -0
  133. package/lib/Utils/messages-media.d.ts +120 -0
  134. package/lib/Utils/messages-media.js +879 -0
  135. package/lib/Utils/messages.d.ts +131 -0
  136. package/lib/Utils/messages.js +1290 -0
  137. package/lib/Utils/noise-handler.d.ts +19 -0
  138. package/lib/Utils/noise-handler.js +150 -0
  139. package/lib/Utils/performance-config.d.ts +60 -0
  140. package/lib/Utils/performance-config.js +150 -0
  141. package/lib/Utils/process-message.d.ts +42 -0
  142. package/lib/Utils/process-message.js +404 -0
  143. package/lib/Utils/retry.js +66 -0
  144. package/lib/Utils/signal.d.ts +33 -0
  145. package/lib/Utils/signal.js +153 -0
  146. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  147. package/lib/Utils/use-multi-file-auth-state.js +125 -0
  148. package/lib/Utils/validate-connection.d.ts +10 -0
  149. package/lib/Utils/validate-connection.js +173 -0
  150. package/lib/WABinary/constants.d.ts +27 -0
  151. package/lib/WABinary/constants.js +1303 -0
  152. package/lib/WABinary/decode.d.ts +6 -0
  153. package/lib/WABinary/decode.js +265 -0
  154. package/lib/WABinary/encode.d.ts +2 -0
  155. package/lib/WABinary/encode.js +250 -0
  156. package/lib/WABinary/generic-utils.d.ts +14 -0
  157. package/lib/WABinary/generic-utils.js +110 -0
  158. package/lib/WABinary/index.d.ts +5 -0
  159. package/lib/WABinary/index.js +21 -0
  160. package/lib/WABinary/jid-utils.d.ts +37 -0
  161. package/lib/WABinary/jid-utils.js +140 -0
  162. package/lib/WABinary/jid-utils.js.bak +83 -0
  163. package/lib/WABinary/types.d.ts +18 -0
  164. package/lib/WABinary/types.js +2 -0
  165. package/lib/WAM/BinaryInfo.d.ts +8 -0
  166. package/lib/WAM/BinaryInfo.js +13 -0
  167. package/lib/WAM/constants.d.ts +38 -0
  168. package/lib/WAM/constants.js +15350 -0
  169. package/lib/WAM/encode.d.ts +2 -0
  170. package/lib/WAM/encode.js +155 -0
  171. package/lib/WAM/index.d.ts +3 -0
  172. package/lib/WAM/index.js +19 -0
  173. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  174. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  175. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  176. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  177. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  178. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  179. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  180. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  181. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  182. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  183. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  184. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  185. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  186. package/lib/WAUSync/Protocols/index.js +20 -0
  187. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  188. package/lib/WAUSync/USyncQuery.js +89 -0
  189. package/lib/WAUSync/USyncUser.d.ts +12 -0
  190. package/lib/WAUSync/USyncUser.js +26 -0
  191. package/lib/WAUSync/index.d.ts +3 -0
  192. package/lib/WAUSync/index.js +19 -0
  193. package/lib/index.d.ts +16 -0
  194. package/lib/index.js +52 -0
  195. package/package.json +111 -0
@@ -0,0 +1,404 @@
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
+ const WAProto_1 = require("../../WAProto");
6
+ const Types_1 = require("../Types");
7
+ const messages_1 = require("../Utils/messages");
8
+ const WABinary_1 = require("../WABinary");
9
+ const crypto_1 = require("./crypto");
10
+ const generics_1 = require("./generics");
11
+ const history_1 = require("./history");
12
+ const REAL_MSG_STUB_TYPES = new Set([
13
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
14
+ Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
15
+ Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
16
+ Types_1.WAMessageStubType.CALL_MISSED_VOICE
17
+ ]);
18
+ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
19
+ Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
20
+ ]);
21
+ /** Cleans a received message to further processing */
22
+ const cleanMessage = (message, meId) => {
23
+ // ensure remoteJid and participant doesn't have device or agent in it
24
+ // normalize JIDs but catch errors to avoid throwing on invalid LIDs/JIDs
25
+ try {
26
+ message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
27
+ }
28
+ catch (_e) {
29
+ // if normalization fails, retain original remoteJid
30
+ }
31
+ if (message.key.participant) {
32
+ try {
33
+ message.key.participant = (0, WABinary_1.jidNormalizedUser)(message.key.participant);
34
+ }
35
+ catch (_e) {
36
+ // ignore if can't normalize participant
37
+ }
38
+ }
39
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
40
+ // if the message has a reaction, ensure fromMe & remoteJid are from our perspective
41
+ if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
42
+ normaliseKey(content.reactionMessage.key);
43
+ }
44
+ if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
45
+ normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
46
+ }
47
+ function normaliseKey(msgKey) {
48
+ // if the reaction is from another user
49
+ // we've to correctly map the key to this user's perspective
50
+ if (!message.key.fromMe) {
51
+ // if the sender believed the message being reacted to is not from them
52
+ // we've to correct the key to be from them, or some other participant
53
+ msgKey.fromMe = !msgKey.fromMe
54
+ ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
55
+ // if the message being reacted to, was from them
56
+ // fromMe automatically becomes false
57
+ : false;
58
+ // set the remoteJid to being the same as the chat the message came from
59
+ msgKey.remoteJid = message.key.remoteJid;
60
+ // set participant of the message
61
+ msgKey.participant = msgKey.participant || message.key.participant;
62
+ }
63
+ }
64
+ };
65
+ exports.cleanMessage = cleanMessage;
66
+ const isRealMessage = (message, meId) => {
67
+ var _a;
68
+ const normalizedContent = (0, messages_1.normalizeMessageContent)(message.message);
69
+ const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
70
+ return (!!normalizedContent
71
+ || REAL_MSG_STUB_TYPES.has(message.messageStubType)
72
+ || (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)
73
+ && ((_a = message.messageStubParameters) === null || _a === void 0 ? void 0 : _a.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))))
74
+ && hasSomeContent
75
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)
76
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)
77
+ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.pollUpdateMessage);
78
+ };
79
+ exports.isRealMessage = isRealMessage;
80
+ const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType);
81
+ exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
82
+ /**
83
+ * Get the ID of the chat from the given key.
84
+ * Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
85
+ */
86
+ const getChatId = ({ remoteJid, participant, fromMe }) => {
87
+ if ((0, WABinary_1.isJidBroadcast)(remoteJid)
88
+ && !(0, WABinary_1.isJidStatusBroadcast)(remoteJid)
89
+ && !fromMe) {
90
+ return participant;
91
+ }
92
+ return remoteJid;
93
+ };
94
+ exports.getChatId = getChatId;
95
+ /**
96
+ * Decrypt a poll vote
97
+ * @param vote encrypted vote
98
+ * @param ctx additional info about the poll required for decryption
99
+ * @returns list of SHA256 options
100
+ */
101
+ function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
102
+ const sign = Buffer.concat([
103
+ toBinary(pollMsgId),
104
+ toBinary(pollCreatorJid),
105
+ toBinary(voterJid),
106
+ toBinary('Poll Vote'),
107
+ new Uint8Array([1])
108
+ ]);
109
+ const key0 = (0, crypto_1.hmacSign)(pollEncKey, new Uint8Array(32), 'sha256');
110
+ const decKey = (0, crypto_1.hmacSign)(sign, key0, 'sha256');
111
+ const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
112
+ const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
113
+ return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
114
+ function toBinary(txt) {
115
+ return Buffer.from(txt);
116
+ }
117
+ }
118
+ const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
119
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
120
+ const meId = creds.me.id;
121
+ const { accountSettings } = creds;
122
+ const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
123
+ const isRealMsg = (0, exports.isRealMessage)(message, meId);
124
+ if (isRealMsg) {
125
+ chat.messages = [{ message }];
126
+ chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
127
+ // only increment unread count if not CIPHERTEXT and from another person
128
+ if ((0, exports.shouldIncrementChatUnread)(message)) {
129
+ chat.unreadCount = (chat.unreadCount || 0) + 1;
130
+ }
131
+ }
132
+ const content = (0, messages_1.normalizeMessageContent)(message.message);
133
+ const senderId = message.key.participant || message.key.remoteJid;
134
+ if ((0, WABinary_1.isLidUser)(senderId)) {
135
+ const jid = (0, WABinary_1.lidToJid)(senderId);
136
+ if (message.key.participant) {
137
+ message.key.participant = jid;
138
+ }
139
+ else {
140
+ message.key.remoteJid = jid;
141
+ }
142
+ }
143
+ const mJids = content && content.contextInfo && content.contextInfo.mentionedJid ? content.contextInfo.mentionedJid : [];
144
+ for (let i = 0; i < mJids.length; i++) {
145
+ if ((0, WABinary_1.isLidUser)(mJids[i])) {
146
+ mJids[i] = (0, WABinary_1.lidToJid)(mJids[i]);
147
+ }
148
+ }
149
+ if (content && content.contextInfo && content.contextInfo.participant && (0, WABinary_1.isLidUser)(content.contextInfo.participant)) {
150
+ content.contextInfo.participant = (0, WABinary_1.lidToJid)(content.contextInfo.participant);
151
+ }
152
+ // unarchive chat if it's a real message, or someone reacted to our message
153
+ // and we've the unarchive chats setting on
154
+ if ((isRealMsg || ((_b = (_a = content === null || content === void 0 ? void 0 : content.reactionMessage) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.fromMe))
155
+ && (accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats)) {
156
+ chat.archived = false;
157
+ chat.readOnly = false;
158
+ }
159
+ const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
160
+ if (protocolMsg) {
161
+ switch (protocolMsg.type) {
162
+ case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
163
+ const histNotification = protocolMsg.historySyncNotification;
164
+ const process = shouldProcessHistoryMsg;
165
+ const isLatest = !((_c = creds.processedHistoryMessages) === null || _c === void 0 ? void 0 : _c.length);
166
+ logger === null || logger === void 0 ? void 0 : logger.info({
167
+ histNotification,
168
+ process,
169
+ id: message.key.id,
170
+ isLatest,
171
+ }, 'got history notification');
172
+ if (process) {
173
+ if (histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
174
+ ev.emit('creds.update', {
175
+ processedHistoryMessages: [
176
+ ...(creds.processedHistoryMessages || []),
177
+ { key: message.key, messageTimestamp: message.messageTimestamp }
178
+ ]
179
+ });
180
+ }
181
+ const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
182
+ ev.emit('messaging-history.set', {
183
+ ...data,
184
+ isLatest: histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND
185
+ ? isLatest
186
+ : undefined,
187
+ peerDataRequestSessionId: histNotification.peerDataRequestSessionId
188
+ });
189
+ }
190
+ break;
191
+ case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
192
+ const keys = protocolMsg.appStateSyncKeyShare.keys;
193
+ if (keys === null || keys === void 0 ? void 0 : keys.length) {
194
+ let newAppStateSyncKeyId = '';
195
+ await keyStore.transaction(async () => {
196
+ const newKeys = [];
197
+ for (const { keyData, keyId } of keys) {
198
+ const strKeyId = Buffer.from(keyId.keyId).toString('base64');
199
+ newKeys.push(strKeyId);
200
+ await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
201
+ newAppStateSyncKeyId = strKeyId;
202
+ }
203
+ logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
204
+ });
205
+ ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
206
+ }
207
+ else {
208
+ logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
209
+ }
210
+ break;
211
+ case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
212
+ ev.emit('messages.update', [
213
+ {
214
+ key: {
215
+ ...message.key,
216
+ id: protocolMsg.key.id
217
+ },
218
+ update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
219
+ }
220
+ ]);
221
+ break;
222
+ case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
223
+ Object.assign(chat, {
224
+ ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
225
+ ephemeralExpiration: protocolMsg.ephemeralExpiration || null
226
+ });
227
+ break;
228
+ case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
229
+ const response = protocolMsg.peerDataOperationRequestResponseMessage;
230
+ if (response) {
231
+ placeholderResendCache === null || placeholderResendCache === void 0 ? void 0 : placeholderResendCache.del(response.stanzaId);
232
+ // TODO: IMPLEMENT HISTORY SYNC ETC (sticker uploads etc.).
233
+ const { peerDataOperationResult } = response;
234
+ for (const result of peerDataOperationResult) {
235
+ const { placeholderMessageResendResponse: retryResponse } = result;
236
+ if (retryResponse) {
237
+ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
238
+ // wait till another upsert event is available, don't want it to be part of the PDO response message
239
+ setTimeout(() => {
240
+ ev.emit('messages.upsert', {
241
+ messages: [webMessageInfo],
242
+ type: 'notify',
243
+ requestId: response.stanzaId
244
+ });
245
+ }, 500);
246
+ }
247
+ }
248
+ }
249
+ case WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
250
+ ev.emit('messages.update', [
251
+ {
252
+ // flip the sender / fromMe properties because they're in the perspective of the sender
253
+ key: { ...message.key, id: (_d = protocolMsg.key) === null || _d === void 0 ? void 0 : _d.id },
254
+ update: {
255
+ message: {
256
+ editedMessage: {
257
+ message: protocolMsg.editedMessage
258
+ }
259
+ },
260
+ messageTimestamp: protocolMsg.timestampMs
261
+ ? Math.floor((0, generics_1.toNumber)(protocolMsg.timestampMs) / 1000)
262
+ : message.messageTimestamp
263
+ }
264
+ }
265
+ ]);
266
+ break;
267
+ }
268
+ }
269
+ else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
270
+ const reaction = {
271
+ ...content.reactionMessage,
272
+ key: message.key,
273
+ };
274
+ ev.emit('messages.reaction', [{
275
+ reaction,
276
+ key: (_e = content.reactionMessage) === null || _e === void 0 ? void 0 : _e.key,
277
+ }]);
278
+ }
279
+ else if (message.messageStubType) {
280
+ const jid = (_f = message.key) === null || _f === void 0 ? void 0 : _f.remoteJid;
281
+ //let actor = whatsappID (message.participant)
282
+ let participants;
283
+ const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author: message.participant, participants, action }));
284
+ const emitGroupUpdate = (update) => {
285
+ var _a;
286
+ ev.emit('groups.update', [{ id: jid, ...update, author: (_a = message.participant) !== null && _a !== void 0 ? _a : undefined }]);
287
+ };
288
+ const emitGroupRequestJoin = (participant, action, method) => {
289
+ ev.emit('group.join-request', { id: jid, author: message.participant, participant, action, method: method });
290
+ };
291
+ const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
292
+ switch (message.messageStubType) {
293
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
294
+ participants = message.messageStubParameters || [];
295
+ emitParticipantsUpdate('modify');
296
+ break;
297
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
298
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
299
+ participants = message.messageStubParameters || [];
300
+ emitParticipantsUpdate('remove');
301
+ // mark the chat read only if you left the group
302
+ if (participantsIncludesMe()) {
303
+ chat.readOnly = true;
304
+ }
305
+ break;
306
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
307
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
308
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
309
+ participants = message.messageStubParameters || [];
310
+ if (participantsIncludesMe()) {
311
+ chat.readOnly = false;
312
+ }
313
+ emitParticipantsUpdate('add');
314
+ break;
315
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
316
+ participants = message.messageStubParameters || [];
317
+ emitParticipantsUpdate('demote');
318
+ break;
319
+ case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
320
+ participants = message.messageStubParameters || [];
321
+ emitParticipantsUpdate('promote');
322
+ break;
323
+ case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
324
+ const announceValue = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
325
+ emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
326
+ break;
327
+ case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
328
+ const restrictValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
329
+ emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
330
+ break;
331
+ case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
332
+ const name = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
333
+ chat.name = name;
334
+ emitGroupUpdate({ subject: name });
335
+ break;
336
+ case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
337
+ const description = (_k = message.messageStubParameters) === null || _k === void 0 ? void 0 : _k[0];
338
+ chat.description = description;
339
+ emitGroupUpdate({ desc: description });
340
+ break;
341
+ case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
342
+ const code = (_l = message.messageStubParameters) === null || _l === void 0 ? void 0 : _l[0];
343
+ emitGroupUpdate({ inviteCode: code });
344
+ break;
345
+ case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
346
+ const memberAddValue = (_m = message.messageStubParameters) === null || _m === void 0 ? void 0 : _m[0];
347
+ emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
348
+ break;
349
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
350
+ const approvalMode = (_o = message.messageStubParameters) === null || _o === void 0 ? void 0 : _o[0];
351
+ emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
352
+ break;
353
+ case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
354
+ const participant = (_p = message.messageStubParameters) === null || _p === void 0 ? void 0 : _p[0];
355
+ const action = (_q = message.messageStubParameters) === null || _q === void 0 ? void 0 : _q[1];
356
+ const method = (_r = message.messageStubParameters) === null || _r === void 0 ? void 0 : _r[2];
357
+ emitGroupRequestJoin(participant, action, method);
358
+ break;
359
+ }
360
+ }
361
+ else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
362
+ const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
363
+ // we need to fetch the poll creation message to get the poll enc key
364
+ const pollMsg = await getMessage(creationMsgKey);
365
+ if (pollMsg) {
366
+ const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
367
+ const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
368
+ const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
369
+ const pollEncKey = (_s = pollMsg.messageContextInfo) === null || _s === void 0 ? void 0 : _s.messageSecret;
370
+ try {
371
+ const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
372
+ pollEncKey,
373
+ pollCreatorJid,
374
+ pollMsgId: creationMsgKey.id,
375
+ voterJid,
376
+ });
377
+ ev.emit('messages.update', [
378
+ {
379
+ key: creationMsgKey,
380
+ update: {
381
+ pollUpdates: [
382
+ {
383
+ pollUpdateMessageKey: message.key,
384
+ vote: voteMsg,
385
+ senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
386
+ }
387
+ ]
388
+ }
389
+ }
390
+ ]);
391
+ }
392
+ catch (err) {
393
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
394
+ }
395
+ }
396
+ else {
397
+ logger === null || logger === void 0 ? void 0 : logger.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
398
+ }
399
+ }
400
+ if (Object.keys(chat).length > 1) {
401
+ ev.emit('chats.update', [chat]);
402
+ }
403
+ };
404
+ exports.default = processMessage;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.retryWithBackoff = void 0;
4
+
5
+ async function sleep(ms, signal) {
6
+ return new Promise((resolve, reject) => {
7
+ const t = setTimeout(resolve, ms);
8
+ if (signal) {
9
+ const onAbort = () => {
10
+ clearTimeout(t);
11
+ reject(Object.assign(new Error('aborted'), { code: 'ABORT_ERR' }));
12
+ };
13
+ if (signal.aborted) {
14
+ onAbort();
15
+ return;
16
+ }
17
+ signal.addEventListener('abort', onAbort, { once: true });
18
+ }
19
+ });
20
+ }
21
+
22
+ function computeDelay(attempt, baseMs, maxMs, jitter) {
23
+ const exp = Math.min(maxMs, baseMs * Math.pow(2, attempt));
24
+ if (!jitter) return exp;
25
+ // full jitter strategy: random between 0 and exp
26
+ const rand = Math.random() * exp;
27
+ return Math.min(maxMs, rand);
28
+ }
29
+
30
+ async function retryWithBackoff(fn, opts = {}) {
31
+ const {
32
+ retries = 3,
33
+ baseMs = 300,
34
+ maxMs = 5000,
35
+ jitter = true,
36
+ timeoutPerAttemptMs,
37
+ signal,
38
+ onRetry,
39
+ shouldRetry
40
+ } = opts;
41
+ let lastErr;
42
+ for (let attempt = 0; attempt <= retries; attempt++) {
43
+ try {
44
+ if (timeoutPerAttemptMs && timeoutPerAttemptMs > 0) {
45
+ const ctrl = new AbortController();
46
+ const timer = setTimeout(() => ctrl.abort(), timeoutPerAttemptMs);
47
+ try {
48
+ return await fn({ signal: ctrl.signal });
49
+ } finally {
50
+ clearTimeout(timer);
51
+ }
52
+ }
53
+ return await fn({ signal });
54
+ } catch (err) {
55
+ lastErr = err;
56
+ if (attempt === retries) break;
57
+ if (shouldRetry && !shouldRetry(err)) break;
58
+ if (onRetry) {
59
+ try { onRetry(err, attempt + 1); } catch {}
60
+ }
61
+ await sleep(computeDelay(attempt, baseMs, maxMs, jitter), signal);
62
+ }
63
+ }
64
+ throw lastErr;
65
+ }
66
+ exports.retryWithBackoff = retryWithBackoff;
@@ -0,0 +1,33 @@
1
+ import { SignalRepository } from '../Types';
2
+ import { AuthenticationCreds, AuthenticationState, KeyPair, SignalIdentity, SignalKeyStore, SignedKeyPair } from '../Types/Auth';
3
+ import { BinaryNode, JidWithDevice } from '../WABinary';
4
+ import { USyncQueryResultList } from '../WAUSync';
5
+ export declare const createSignalIdentity: (wid: string, accountSignatureKey: Uint8Array) => SignalIdentity;
6
+ export declare const getPreKeys: ({ get }: SignalKeyStore, min: number, limit: number) => Promise<{
7
+ [id: string]: KeyPair;
8
+ }>;
9
+ export declare const generateOrGetPreKeys: (creds: AuthenticationCreds, range: number) => {
10
+ newPreKeys: {
11
+ [id: number]: KeyPair;
12
+ };
13
+ lastPreKeyId: number;
14
+ preKeysRange: readonly [number, number];
15
+ };
16
+ export declare const xmppSignedPreKey: (key: SignedKeyPair) => BinaryNode;
17
+ export declare const xmppPreKey: (pair: KeyPair, id: number) => BinaryNode;
18
+ export declare const parseAndInjectE2ESessions: (node: BinaryNode, repository: SignalRepository) => Promise<void>;
19
+ export declare const extractDeviceJids: (result: USyncQueryResultList[], myJid: string, excludeZeroDevices: boolean) => JidWithDevice[];
20
+ /**
21
+ * get the next N keys for upload or processing
22
+ * @param count number of pre-keys to get or generate
23
+ */
24
+ export declare const getNextPreKeys: ({ creds, keys }: AuthenticationState, count: number) => Promise<{
25
+ update: Partial<AuthenticationCreds>;
26
+ preKeys: {
27
+ [id: string]: KeyPair;
28
+ };
29
+ }>;
30
+ export declare const getNextPreKeysNode: (state: AuthenticationState, count: number) => Promise<{
31
+ update: Partial<AuthenticationCreds>;
32
+ node: BinaryNode;
33
+ }>;
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getNextPreKeysNode = exports.getNextPreKeys = exports.extractDeviceJids = exports.parseAndInjectE2ESessions = exports.xmppPreKey = exports.xmppSignedPreKey = exports.generateOrGetPreKeys = exports.getPreKeys = exports.createSignalIdentity = void 0;
4
+ const lodash_1 = require("lodash");
5
+ const Defaults_1 = require("../Defaults");
6
+ const WABinary_1 = require("../WABinary");
7
+ const crypto_1 = require("./crypto");
8
+ const generics_1 = require("./generics");
9
+ const createSignalIdentity = (wid, accountSignatureKey) => {
10
+ return {
11
+ identifier: { name: wid, deviceId: 0 },
12
+ identifierKey: (0, crypto_1.generateSignalPubKey)(accountSignatureKey)
13
+ };
14
+ };
15
+ exports.createSignalIdentity = createSignalIdentity;
16
+ const getPreKeys = async ({ get }, min, limit) => {
17
+ const idList = [];
18
+ for (let id = min; id < limit; id++) {
19
+ idList.push(id.toString());
20
+ }
21
+ return get('pre-key', idList);
22
+ };
23
+ exports.getPreKeys = getPreKeys;
24
+ const generateOrGetPreKeys = (creds, range) => {
25
+ const avaliable = creds.nextPreKeyId - creds.firstUnuploadedPreKeyId;
26
+ const remaining = range - avaliable;
27
+ const lastPreKeyId = creds.nextPreKeyId + remaining - 1;
28
+ const newPreKeys = {};
29
+ if (remaining > 0) {
30
+ for (let i = creds.nextPreKeyId; i <= lastPreKeyId; i++) {
31
+ newPreKeys[i] = crypto_1.Curve.generateKeyPair();
32
+ }
33
+ }
34
+ return {
35
+ newPreKeys,
36
+ lastPreKeyId,
37
+ preKeysRange: [creds.firstUnuploadedPreKeyId, range],
38
+ };
39
+ };
40
+ exports.generateOrGetPreKeys = generateOrGetPreKeys;
41
+ const xmppSignedPreKey = (key) => ({
42
+ tag: 'skey',
43
+ attrs: {},
44
+ content: [
45
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(key.keyId, 3) },
46
+ { tag: 'value', attrs: {}, content: key.keyPair.public },
47
+ { tag: 'signature', attrs: {}, content: key.signature }
48
+ ]
49
+ });
50
+ exports.xmppSignedPreKey = xmppSignedPreKey;
51
+ const xmppPreKey = (pair, id) => ({
52
+ tag: 'key',
53
+ attrs: {},
54
+ content: [
55
+ { tag: 'id', attrs: {}, content: (0, generics_1.encodeBigEndian)(id, 3) },
56
+ { tag: 'value', attrs: {}, content: pair.public }
57
+ ]
58
+ });
59
+ exports.xmppPreKey = xmppPreKey;
60
+ const parseAndInjectE2ESessions = async (node, repository) => {
61
+ const extractKey = (key) => (key ? ({
62
+ keyId: (0, WABinary_1.getBinaryNodeChildUInt)(key, 'id', 3),
63
+ publicKey: (0, crypto_1.generateSignalPubKey)((0, WABinary_1.getBinaryNodeChildBuffer)(key, 'value')),
64
+ signature: (0, WABinary_1.getBinaryNodeChildBuffer)(key, 'signature'),
65
+ }) : undefined);
66
+ const nodes = (0, WABinary_1.getBinaryNodeChildren)((0, WABinary_1.getBinaryNodeChild)(node, 'list'), 'user');
67
+ for (const node of nodes) {
68
+ (0, WABinary_1.assertNodeErrorFree)(node);
69
+ }
70
+ // Most of the work in repository.injectE2ESession is CPU intensive, not IO
71
+ // So Promise.all doesn't really help here,
72
+ // but blocks even loop if we're using it inside keys.transaction, and it makes it "sync" actually
73
+ // This way we chunk it in smaller parts and between those parts we can yield to the event loop
74
+ // It's rare case when you need to E2E sessions for so many users, but it's possible
75
+ const chunkSize = 100;
76
+ const chunks = (0, lodash_1.chunk)(nodes, chunkSize);
77
+ for (const nodesChunk of chunks) {
78
+ await Promise.all(nodesChunk.map(async (node) => {
79
+ const signedKey = (0, WABinary_1.getBinaryNodeChild)(node, 'skey');
80
+ const key = (0, WABinary_1.getBinaryNodeChild)(node, 'key');
81
+ const identity = (0, WABinary_1.getBinaryNodeChildBuffer)(node, 'identity');
82
+ const jid = node.attrs.jid;
83
+ const registrationId = (0, WABinary_1.getBinaryNodeChildUInt)(node, 'registration', 4);
84
+ await repository.injectE2ESession({
85
+ jid,
86
+ session: {
87
+ registrationId: registrationId,
88
+ identityKey: (0, crypto_1.generateSignalPubKey)(identity),
89
+ signedPreKey: extractKey(signedKey),
90
+ preKey: extractKey(key)
91
+ }
92
+ });
93
+ }));
94
+ }
95
+ };
96
+ exports.parseAndInjectE2ESessions = parseAndInjectE2ESessions;
97
+ const extractDeviceJids = (result, myJid, excludeZeroDevices) => {
98
+ const { user: myUser, device: myDevice } = (0, WABinary_1.jidDecode)(myJid);
99
+ const extracted = [];
100
+ for (const userResult of result) {
101
+ const { devices, id } = userResult;
102
+ const { user } = (0, WABinary_1.jidDecode)(id);
103
+ const deviceList = devices === null || devices === void 0 ? void 0 : devices.deviceList;
104
+ if (Array.isArray(deviceList)) {
105
+ for (const { id: device, keyIndex } of deviceList) {
106
+ if ((!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero
107
+ (myUser !== user || myDevice !== device) && // either different user or if me user, not this device
108
+ (device === 0 || !!keyIndex) // ensure that "key-index" is specified for "non-zero" devices, produces a bad req otherwise
109
+ ) {
110
+ extracted.push({ user, device });
111
+ }
112
+ }
113
+ }
114
+ }
115
+ return extracted;
116
+ };
117
+ exports.extractDeviceJids = extractDeviceJids;
118
+ /**
119
+ * get the next N keys for upload or processing
120
+ * @param count number of pre-keys to get or generate
121
+ */
122
+ const getNextPreKeys = async ({ creds, keys }, count) => {
123
+ const { newPreKeys, lastPreKeyId, preKeysRange } = (0, exports.generateOrGetPreKeys)(creds, count);
124
+ const update = {
125
+ nextPreKeyId: Math.max(lastPreKeyId + 1, creds.nextPreKeyId),
126
+ firstUnuploadedPreKeyId: Math.max(creds.firstUnuploadedPreKeyId, lastPreKeyId + 1)
127
+ };
128
+ await keys.set({ 'pre-key': newPreKeys });
129
+ const preKeys = await (0, exports.getPreKeys)(keys, preKeysRange[0], preKeysRange[0] + preKeysRange[1]);
130
+ return { update, preKeys };
131
+ };
132
+ exports.getNextPreKeys = getNextPreKeys;
133
+ const getNextPreKeysNode = async (state, count) => {
134
+ const { creds } = state;
135
+ const { update, preKeys } = await (0, exports.getNextPreKeys)(state, count);
136
+ const node = {
137
+ tag: 'iq',
138
+ attrs: {
139
+ xmlns: 'encrypt',
140
+ type: 'set',
141
+ to: WABinary_1.S_WHATSAPP_NET,
142
+ },
143
+ content: [
144
+ { tag: 'registration', attrs: {}, content: (0, generics_1.encodeBigEndian)(creds.registrationId) },
145
+ { tag: 'type', attrs: {}, content: Defaults_1.KEY_BUNDLE_TYPE },
146
+ { tag: 'identity', attrs: {}, content: creds.signedIdentityKey.public },
147
+ { tag: 'list', attrs: {}, content: Object.keys(preKeys).map(k => (0, exports.xmppPreKey)(preKeys[+k], +k)) },
148
+ (0, exports.xmppSignedPreKey)(creds.signedPreKey)
149
+ ]
150
+ };
151
+ return { update, node };
152
+ };
153
+ exports.getNextPreKeysNode = getNextPreKeysNode;
@@ -0,0 +1,12 @@
1
+ import { AuthenticationState } from '../Types';
2
+ /**
3
+ * stores the full authentication state in a single folder.
4
+ * Far more efficient than singlefileauthstate
5
+ *
6
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
7
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
8
+ * */
9
+ export declare const useMultiFileAuthState: (folder: string) => Promise<{
10
+ state: AuthenticationState;
11
+ saveCreds: () => Promise<void>;
12
+ }>;