mid-baileys 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.MD +1 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +6214 -0
  5. package/WAProto/index.js +216001 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/index.js +119 -0
  9. package/lib/Defaults/version.json +3 -0
  10. package/lib/Signal/Group/ciphertext-message.js +15 -0
  11. package/lib/Signal/Group/group-session-builder.js +64 -0
  12. package/lib/Signal/Group/group_cipher.js +96 -0
  13. package/lib/Signal/Group/index.js +57 -0
  14. package/lib/Signal/Group/keyhelper.js +55 -0
  15. package/lib/Signal/Group/queue-job.js +57 -0
  16. package/lib/Signal/Group/sender-chain-key.js +34 -0
  17. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  18. package/lib/Signal/Group/sender-key-message.js +69 -0
  19. package/lib/Signal/Group/sender-key-name.js +51 -0
  20. package/lib/Signal/Group/sender-key-record.js +53 -0
  21. package/lib/Signal/Group/sender-key-state.js +99 -0
  22. package/lib/Signal/Group/sender-message-key.js +29 -0
  23. package/lib/Signal/libsignal.js +174 -0
  24. package/lib/Socket/Client/index.js +18 -0
  25. package/lib/Socket/Client/types.js +13 -0
  26. package/lib/Socket/Client/websocket.js +111 -0
  27. package/lib/Socket/business.js +261 -0
  28. package/lib/Socket/chats.js +1007 -0
  29. package/lib/Socket/groups.js +333 -0
  30. package/lib/Socket/index.js +10 -0
  31. package/lib/Socket/messages-recv.js +1165 -0
  32. package/lib/Socket/messages-send.js +1058 -0
  33. package/lib/Socket/messages-send.js.bak +866 -0
  34. package/lib/Socket/newsletter.js +252 -0
  35. package/lib/Socket/socket.js +654 -0
  36. package/lib/Socket/usync.js +70 -0
  37. package/lib/Store/index.js +8 -0
  38. package/lib/Store/make-in-memory-store.js +439 -0
  39. package/lib/Store/make-ordered-dictionary.js +81 -0
  40. package/lib/Store/object-repository.js +27 -0
  41. package/lib/Types/Auth.js +2 -0
  42. package/lib/Types/Call.js +2 -0
  43. package/lib/Types/Chat.js +4 -0
  44. package/lib/Types/Contact.js +2 -0
  45. package/lib/Types/Events.js +2 -0
  46. package/lib/Types/GroupMetadata.js +2 -0
  47. package/lib/Types/Label.js +27 -0
  48. package/lib/Types/LabelAssociation.js +9 -0
  49. package/lib/Types/Message.js +7 -0
  50. package/lib/Types/Newsletter.js +18 -0
  51. package/lib/Types/Product.js +2 -0
  52. package/lib/Types/Signal.js +2 -0
  53. package/lib/Types/Socket.js +2 -0
  54. package/lib/Types/State.js +2 -0
  55. package/lib/Types/USync.js +2 -0
  56. package/lib/Types/index.js +42 -0
  57. package/lib/Utils/auth-utils.js +199 -0
  58. package/lib/Utils/browser-utils.js +35 -0
  59. package/lib/Utils/business.js +234 -0
  60. package/lib/Utils/chat-utils.js +730 -0
  61. package/lib/Utils/crypto.js +193 -0
  62. package/lib/Utils/decode-wa-message.js +315 -0
  63. package/lib/Utils/event-buffer.js +518 -0
  64. package/lib/Utils/event-stream.js +63 -0
  65. package/lib/Utils/generics.js +459 -0
  66. package/lib/Utils/history.js +94 -0
  67. package/lib/Utils/index.js +35 -0
  68. package/lib/Utils/link-preview.js +126 -0
  69. package/lib/Utils/logger.js +7 -0
  70. package/lib/Utils/lt-hash.js +51 -0
  71. package/lib/Utils/make-mutex.js +43 -0
  72. package/lib/Utils/message-retry-manager.js +128 -0
  73. package/lib/Utils/messages-media.js +877 -0
  74. package/lib/Utils/messages.js +1227 -0
  75. package/lib/Utils/noise-handler.js +150 -0
  76. package/lib/Utils/process-message.js +418 -0
  77. package/lib/Utils/rich.js +377 -0
  78. package/lib/Utils/signal.js +153 -0
  79. package/lib/Utils/use-multi-file-auth-state.js +122 -0
  80. package/lib/Utils/validate-connection.js +229 -0
  81. package/lib/WABinary/constants.js +1304 -0
  82. package/lib/WABinary/decode.js +265 -0
  83. package/lib/WABinary/encode.js +250 -0
  84. package/lib/WABinary/generic-utils.js +110 -0
  85. package/lib/WABinary/index.js +21 -0
  86. package/lib/WABinary/jid-utils.js +97 -0
  87. package/lib/WABinary/types.js +2 -0
  88. package/lib/WAM/BinaryInfo.js +13 -0
  89. package/lib/WAM/constants.js +15350 -0
  90. package/lib/WAM/encode.js +155 -0
  91. package/lib/WAM/index.js +19 -0
  92. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  93. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  94. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  95. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  96. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  97. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  98. package/lib/WAUSync/Protocols/index.js +20 -0
  99. package/lib/WAUSync/USyncQuery.js +89 -0
  100. package/lib/WAUSync/USyncUser.js +26 -0
  101. package/lib/WAUSync/index.js +19 -0
  102. package/lib/index.js +39 -0
  103. package/package.json +105 -0
@@ -0,0 +1,377 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ const crypto_1 = require("crypto");
5
+ const WAProto_1 = require("../../WAProto");
6
+ const generics_js_1 = require("./generics");
7
+
8
+ const JS_KEYWORDS = new Set([
9
+ 'import', 'export', 'from', 'default', 'as',
10
+ 'const', 'let', 'var', 'function', 'class', 'extends', 'new',
11
+ 'return', 'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'break', 'continue',
12
+ 'try', 'catch', 'finally', 'throw',
13
+ 'async', 'await', 'yield',
14
+ 'typeof', 'instanceof', 'in', 'of', 'delete', 'void',
15
+ 'true', 'false', 'null', 'undefined', 'NaN', 'Infinity',
16
+ 'this', 'super', 'static', 'get', 'set',
17
+ 'debugger', 'with'
18
+ ]);
19
+
20
+ const LANGUAGE_KEYWORDS = {
21
+ javascript: JS_KEYWORDS,
22
+ typescript: JS_KEYWORDS,
23
+ js: JS_KEYWORDS,
24
+ ts: JS_KEYWORDS
25
+ };
26
+
27
+ const DONATE_URL = 'https://www.instagram.com/midsoune_';
28
+ const LEXER_REGEX = /(\/\/.*|\/\*[\s\S]*?\*\/|#.*)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[\s\S]*?`)|(\b[a-zA-Z_]\w*\b)(?=\s*\()|(\b[a-zA-Z_]\w*\b)|(\b\d+(?:\.\d+)?\b)|(\s+|[^\w\s]+)/g;
29
+ const BOT_RENDERING_CONFIG_METADATA = { bloksVersioningId: '0903aa5f7f47de66789d5f4c86d3bd6e05e4bc3ff85e454a9f907d5ed7fef97c', pixelDensity: 2.75 };
30
+ const textEncoder = new TextEncoder();
31
+ const NOOP = new Set([]);
32
+
33
+ var CodeHighlightType;
34
+ (function (CodeHighlightType) {
35
+ CodeHighlightType[CodeHighlightType["DEFAULT"] = 0] = "DEFAULT";
36
+ CodeHighlightType[CodeHighlightType["KEYWORD"] = 1] = "KEYWORD";
37
+ CodeHighlightType[CodeHighlightType["METHOD"] = 2] = "METHOD";
38
+ CodeHighlightType[CodeHighlightType["STRING"] = 3] = "STRING";
39
+ CodeHighlightType[CodeHighlightType["NUMBER"] = 4] = "NUMBER";
40
+ CodeHighlightType[CodeHighlightType["COMMENT"] = 5] = "COMMENT";
41
+ })(CodeHighlightType || (CodeHighlightType = {}));
42
+
43
+ var RichSubMessageType;
44
+ (function (RichSubMessageType) {
45
+ RichSubMessageType[RichSubMessageType["UNKNOWN"] = 0] = "UNKNOWN";
46
+ RichSubMessageType[RichSubMessageType["GRID_IMAGE"] = 1] = "GRID_IMAGE";
47
+ RichSubMessageType[RichSubMessageType["TEXT"] = 2] = "TEXT";
48
+ RichSubMessageType[RichSubMessageType["INLINE_IMAGE"] = 3] = "INLINE_IMAGE";
49
+ RichSubMessageType[RichSubMessageType["TABLE"] = 4] = "TABLE";
50
+ RichSubMessageType[RichSubMessageType["CODE"] = 5] = "CODE";
51
+ RichSubMessageType[RichSubMessageType["DYNAMIC"] = 6] = "DYNAMIC";
52
+ RichSubMessageType[RichSubMessageType["MAP"] = 7] = "MAP";
53
+ RichSubMessageType[RichSubMessageType["LATEX"] = 8] = "LATEX";
54
+ RichSubMessageType[RichSubMessageType["CONTENT_ITEMS"] = 9] = "CONTENT_ITEMS";
55
+ })(RichSubMessageType || (RichSubMessageType = {}));
56
+
57
+ const tokenizeCode = (code, language = 'javascript') => {
58
+ const keywords = LANGUAGE_KEYWORDS[language] || NOOP;
59
+ const blocks = [];
60
+ LEXER_REGEX.lastIndex = 0;
61
+ let match;
62
+ while ((match = LEXER_REGEX.exec(code)) !== null) {
63
+ if (match[1]) {
64
+ blocks.push({ highlightType: CodeHighlightType.COMMENT, codeContent: match[1] });
65
+ }
66
+ else if (match[2]) {
67
+ blocks.push({ highlightType: CodeHighlightType.STRING, codeContent: match[2] });
68
+ }
69
+ else if (match[3]) {
70
+ blocks.push({
71
+ highlightType: keywords.has(match[3]) ? CodeHighlightType.KEYWORD : CodeHighlightType.METHOD,
72
+ codeContent: match[3],
73
+ });
74
+ }
75
+ else if (match[4]) {
76
+ blocks.push({
77
+ highlightType: keywords.has(match[4]) ? CodeHighlightType.KEYWORD : CodeHighlightType.DEFAULT,
78
+ codeContent: match[4],
79
+ });
80
+ }
81
+ else if (match[5]) {
82
+ blocks.push({ highlightType: CodeHighlightType.NUMBER, codeContent: match[5] });
83
+ }
84
+ else {
85
+ blocks.push({ highlightType: CodeHighlightType.DEFAULT, codeContent: match[6] || match[0] });
86
+ }
87
+ }
88
+ return blocks;
89
+ };
90
+ exports.tokenizeCode = tokenizeCode;
91
+
92
+ const toUnified = (submessages) => ({
93
+ response_id: (0, crypto_1.randomUUID)(),
94
+ sections: submessages.map((submessage, index) => {
95
+ switch (submessage.messageType) {
96
+ case RichSubMessageType.CODE:
97
+ const codeMetadata = submessage.codeMetadata;
98
+ return {
99
+ view_model: {
100
+ primitive: {
101
+ language: codeMetadata.codeLanguage,
102
+ code_blocks: codeMetadata.codeBlocks.map((block) => ({ content: block.codeContent, type: CodeHighlightType[block.highlightType] })),
103
+ __typename: 'GenAICodeUXPrimitive'
104
+ },
105
+ __typename: 'GenAISingleLayoutViewModel'
106
+ }
107
+ };
108
+ case RichSubMessageType.CONTENT_ITEMS:
109
+ return {
110
+ view_model: {
111
+ primitives: submessage.contentItemsMetadata.itemsMetadata.map((item) => {
112
+ const reelItem = item.reelItem;
113
+ return {
114
+ reels_url: reelItem.videoUrl,
115
+ thumbnail_url: reelItem.thumbnailUrl,
116
+ creator: reelItem.creator || '@midsoune/mbaileys',
117
+ avatar_url: reelItem.profileIconUrl,
118
+ reels_title: reelItem.title,
119
+ likes_count: reelItem.likesCount || 0,
120
+ shares_count: reelItem.sharesCount || 0,
121
+ view_count: reelItem.viewCount || 0,
122
+ reel_source: reelItem.reelSource || 'IG',
123
+ is_verified: reelItem.isVerified || false,
124
+ __typename: 'GenAIReelPrimitive'
125
+ };
126
+ }),
127
+ __typename: 'GenAIHScrollLayoutViewModel'
128
+ }
129
+ };
130
+ case RichSubMessageType.LATEX:
131
+ const latexMetadata = submessage.latexMetadata;
132
+ const item = {
133
+ latex_expression: latexMetadata.expressions[0]?.latexExpression,
134
+ font_height: latexMetadata.expressions[0]?.fontHeight,
135
+ padding: 15,
136
+ latex_image: {
137
+ url: latexMetadata.expressions[0]?.url,
138
+ width: latexMetadata.expressions[0]?.width || 388,
139
+ height: latexMetadata.expressions[0]?.height || 160
140
+ }
141
+ };
142
+ return {
143
+ view_model: {
144
+ primitive: {
145
+ item,
146
+ ...item,
147
+ __typename: 'GenAILatexUXPrimitive'
148
+ },
149
+ __typename: 'GenAISingleLayoutViewModel'
150
+ }
151
+ };
152
+ case RichSubMessageType.TABLE:
153
+ const tableMetadata = submessage.tableMetadata;
154
+ return {
155
+ view_model: {
156
+ primitive: {
157
+ title: tableMetadata.title,
158
+ rows: tableMetadata.rows.map((row) => ({ is_header: row.isHeading, cells: row.items, markdown_cells: [] })),
159
+ __typename: 'GenATableUXPrimitive'
160
+ },
161
+ __typename: 'GenAISingleLayoutViewModel'
162
+ }
163
+ };
164
+ case RichSubMessageType.TEXT:
165
+ const shouldAddInlineEntity = true;
166
+ const inlineEntity = [{
167
+ key: 'MidSoune',
168
+ metadata: {
169
+ reference_id: 1,
170
+ reference_url: DONATE_URL,
171
+ reference_title: 'Visite Instagram Profile',
172
+ reference_display_name: 'Visite',
173
+ sources: [{
174
+ source_type: 'THIRD_PARTY',
175
+ source_display_name: 'Visite',
176
+ source_url: DONATE_URL
177
+ }],
178
+ __typename: 'GenAISearchCitationItem'
179
+ }
180
+ }];
181
+
182
+ const textEntity = shouldAddInlineEntity ? '{{MidSoune}}¹{{/MidSoune}}' : '';
183
+
184
+ return {
185
+ view_model: {
186
+ primitive: {
187
+ text: submessage.messageText + textEntity,
188
+ inline_entities: shouldAddInlineEntity ? inlineEntity : [],
189
+
190
+ // 🔥 هنا فين كاتزيد لون الخلفية والتكست:
191
+ // واتساب كيستعمل هاد الستيل ف الـ Meta AI للون الأصفر الدافئ
192
+ custom_attributes: {
193
+ theme: "YELLOW_WARNING", // أو "YELLOW" على حسب نسخة الـ Protobuf اللي عندك
194
+ background_color: "0xFFFFF9E6", // كود اللون Hex شفاف (ARBG) للأصفر
195
+ text_color: "0xFF000000" // لون التكست كحل باش يجي باين فوق الأصفر
196
+ },
197
+
198
+ __typename: 'GenAIMarkdownTextUXPrimitive'
199
+ },
200
+ __typename: 'GenAISingleLayoutViewModel'
201
+ }
202
+ };
203
+ }
204
+ return submessage;
205
+ })
206
+ });
207
+ exports.toUnified = toUnified;
208
+
209
+ const buildAdditionalBotMetadataContext = (submessages) => {
210
+ const sources = [];
211
+ const mediaDetailsMetadataList = [];
212
+ for (let i = 0; i < submessages.length; i++) {
213
+ const submessage = submessages[i];
214
+ switch (submessage.messageType) {
215
+ case RichSubMessageType.CONTENT_ITEMS:
216
+ const itemsMetadata = submessage.contentItemsMetadata.itemsMetadata;
217
+ for (let n = 0; n < itemsMetadata.length; n++) {
218
+ const reelItem = itemsMetadata[n].reelItem;
219
+ sources.push({
220
+ provider: 0,
221
+ thumbnailCdnUrl: reelItem.thumbnailUrl,
222
+ sourceProviderUrl: reelItem.videoUrl,
223
+ sourceQuery: '',
224
+ faviconCdnUrl: '',
225
+ citationNumber: i + 1,
226
+ sourceTitle: reelItem.title
227
+ });
228
+ mediaDetailsMetadataList.push({
229
+ id: (0, crypto_1.randomBytes)(32).toString('hex'),
230
+ previewMedia: {
231
+ fileSha256: '',
232
+ mediaKey: '',
233
+ fileEncSha256: '',
234
+ directPath: '',
235
+ mediaKeyTimestamp: (0, generics_js_1.unixTimestampSeconds)(),
236
+ mimetype: 'image/jpeg'
237
+ }
238
+ });
239
+ }
240
+ break;
241
+ case RichSubMessageType.LATEX:
242
+ const expressions = submessage.latexMetadata.expressions;
243
+ for (let n = 0; n < expressions.length; n++) {
244
+ mediaDetailsMetadataList.push({
245
+ id: (0, crypto_1.randomBytes)(32).toString('hex'),
246
+ previewMedia: {
247
+ fileSha256: '',
248
+ mediaKey: '',
249
+ fileEncSha256: '',
250
+ directPath: '',
251
+ mediaKeyTimestamp: (0, generics_js_1.unixTimestampSeconds)(),
252
+ mimetype: 'image/jpeg'
253
+ }
254
+ });
255
+ }
256
+ break;
257
+ }
258
+ }
259
+ return { sources, mediaDetailsMetadataList };
260
+ };
261
+ exports.buildAdditionalBotMetadataContext = buildAdditionalBotMetadataContext;
262
+
263
+ const prepareRichResponseMessage = (content) => {
264
+ const { code, contentText, expressions, footerText, headerText, items, language, table, text, title } = content;
265
+ let submessages = [];
266
+
267
+ if (headerText) {
268
+ submessages.push({ messageType: RichSubMessageType.TEXT, messageText: headerText });
269
+ }
270
+ if (contentText) {
271
+ submessages.push({ messageType: RichSubMessageType.TEXT, messageText: contentText });
272
+ }
273
+
274
+ // ✅ تصحيح: حيدنا الـ Else باش يقبل العناصر كاملين مدموجين إيلا صيفطتيهم دقة وحدة
275
+ if (code) {
276
+ let lang = language || 'javascript'; // ✅ تصحيح: كياخد الـ language الممررة ديريكت
277
+ submessages.push({
278
+ messageType: RichSubMessageType.CODE,
279
+ codeMetadata: { codeLanguage: lang, codeBlocks: (0, exports.tokenizeCode)(code, lang) }
280
+ });
281
+ }
282
+ if (expressions) {
283
+ submessages.push({
284
+ messageType: RichSubMessageType.LATEX,
285
+ latexMetadata: { text, expressions }
286
+ });
287
+ }
288
+ if (items) {
289
+ submessages.push({
290
+ messageType: RichSubMessageType.CONTENT_ITEMS,
291
+ contentItemsMetadata: {
292
+ itemsMetadata: items.map((item) => ({ reelItem: item })),
293
+ contentType: WAProto_1.proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL
294
+ }
295
+ });
296
+ }
297
+ if (table) {
298
+ const tableRows = table.map((items, index) => ({ isHeading: index == 0, items }));
299
+ submessages.push({
300
+ messageType: RichSubMessageType.TABLE,
301
+ tableMetadata: { title, rows: tableRows }
302
+ });
303
+ }
304
+ if (footerText) {
305
+ submessages.push({ messageType: RichSubMessageType.TEXT, messageText: footerText });
306
+ }
307
+
308
+ const unified = (0, exports.toUnified)(submessages);
309
+ const message = (0, exports.wrapToBotForwardedMessage)({
310
+ submessages,
311
+ messageType: WAProto_1.proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD,
312
+ unifiedResponse: {
313
+ data: textEncoder.encode(JSON.stringify(unified))
314
+ },
315
+ contextInfo: {
316
+ isForwarded: true,
317
+ forwardingScore: 1,
318
+ forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' },
319
+ forwardOrigin: 4
320
+ }
321
+ });
322
+
323
+ const { sources, mediaDetailsMetadataList } = (0, exports.buildAdditionalBotMetadataContext)(submessages);
324
+ const botMetadata = message.messageContextInfo.botMetadata;
325
+ if (sources.length > 0) {
326
+ botMetadata.richResponseSourcesMetadata = { sources };
327
+ }
328
+ if (mediaDetailsMetadataList.length > 0) {
329
+ botMetadata.unifiedResponseMutation = { mediaDetailsMetadataList };
330
+ }
331
+ return message;
332
+ };
333
+ exports.prepareRichResponseMessage = prepareRichResponseMessage;
334
+
335
+ const botMetadataSignature = () => {
336
+ const signature = new Uint8Array(64);
337
+ // ✅ تصحيح: استعمال الـ webcrypto الآمن ف بيئة Node.js
338
+ crypto_1.webcrypto.getRandomValues(signature);
339
+ return signature;
340
+ };
341
+ exports.botMetadataSignature = botMetadataSignature;
342
+
343
+ const botMetadataCertificate = (length = 700) => {
344
+ const certificate = new Uint8Array(length);
345
+ certificate[0] = 48;
346
+ certificate[1] = 130;
347
+ // ✅ تصحيح: استعمال الـ webcrypto الآمن هنا أيضاً
348
+ crypto_1.webcrypto.getRandomValues(certificate.subarray(2));
349
+ return certificate;
350
+ };
351
+ exports.botMetadataCertificate = botMetadataCertificate;
352
+
353
+ const wrapToBotForwardedMessage = (richResponseMessage) => ({
354
+ messageContextInfo: {
355
+ botMetadata: {
356
+ pluginMetadata: {},
357
+ verificationMetadata: {
358
+ proofs: [
359
+ {
360
+ certificateChain: [
361
+ (0, exports.botMetadataCertificate)(684),
362
+ (0, exports.botMetadataCertificate)(892)
363
+ ],
364
+ version: 1,
365
+ useCase: 1,
366
+ signature: (0, exports.botMetadataSignature)()
367
+ }
368
+ ]
369
+ },
370
+ botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA
371
+ }
372
+ },
373
+ botForwardedMessage: {
374
+ message: { richResponseMessage }
375
+ }
376
+ });
377
+ exports.wrapToBotForwardedMessage = wrapToBotForwardedMessage;
@@ -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,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useMultiFileAuthState = void 0;
4
+ const async_mutex_1 = require("async-mutex");
5
+ const promises_1 = require("fs/promises");
6
+ const path_1 = require("path");
7
+ const WAProto_1 = require("../../WAProto");
8
+ const auth_utils_1 = require("./auth-utils");
9
+ const generics_1 = require("./generics");
10
+
11
+ const fileLocks = new Map();
12
+ // Get or create a mutex for a specific file path
13
+ const getFileLock = (path) => {
14
+ let mutex = fileLocks.get(path);
15
+ if (!mutex) {
16
+ mutex = new async_mutex_1.Mutex();
17
+ fileLocks.set(path, mutex);
18
+ }
19
+ return mutex;
20
+ };
21
+ /**
22
+ * stores the full authentication state in a single folder.
23
+ * Far more efficient than singlefileauthstate
24
+ *
25
+ * Again, I wouldn't endorse this for any production level use other than perhaps a bot.
26
+ * Would recommend writing an auth state for use with a proper SQL or No-SQL DB
27
+ * */
28
+ const useMultiFileAuthState = async (folder) => {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ const writeData = async (data, file) => {
31
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
32
+ const mutex = getFileLock(filePath);
33
+ return mutex.acquire().then(async (release) => {
34
+ try {
35
+ await (0, promises_1.writeFile)(filePath, JSON.stringify(data, generics_1.BufferJSON.replacer));
36
+ }
37
+ finally {
38
+ release();
39
+ }
40
+ });
41
+ };
42
+ const readData = async (file) => {
43
+ try {
44
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
45
+ const mutex = getFileLock(filePath);
46
+ return await mutex.acquire().then(async (release) => {
47
+ try {
48
+ const data = await (0, promises_1.readFile)(filePath, { encoding: 'utf-8' });
49
+ return JSON.parse(data, generics_1.BufferJSON.reviver);
50
+ }
51
+ finally {
52
+ release();
53
+ }
54
+ });
55
+ }
56
+ catch (error) {
57
+ return null;
58
+ }
59
+ };
60
+ const removeData = async (file) => {
61
+ try {
62
+ const filePath = (0, path_1.join)(folder, fixFileName(file));
63
+ const mutex = getFileLock(filePath);
64
+ return mutex.acquire().then(async (release) => {
65
+ try {
66
+ await (0, promises_1.unlink)(filePath);
67
+ }
68
+ catch (_a) {
69
+ }
70
+ finally {
71
+ release();
72
+ }
73
+ });
74
+ }
75
+ catch (_a) {
76
+ }
77
+ };
78
+ const folderInfo = await (0, promises_1.stat)(folder).catch(() => { });
79
+ if (folderInfo) {
80
+ if (!folderInfo.isDirectory()) {
81
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`);
82
+ }
83
+ }
84
+ else {
85
+ await (0, promises_1.mkdir)(folder, { recursive: true });
86
+ }
87
+ const fixFileName = (file) => { var _a; return (_a = file === null || file === void 0 ? void 0 : file.replace(/\//g, '__')) === null || _a === void 0 ? void 0 : _a.replace(/:/g, '-'); };
88
+ const creds = await readData('creds.json') || (0, auth_utils_1.initAuthCreds)();
89
+ return {
90
+ state: {
91
+ creds,
92
+ keys: {
93
+ get: async (type, ids) => {
94
+ const data = {};
95
+ await Promise.all(ids.map(async (id) => {
96
+ let value = await readData(`${type}-${id}.json`);
97
+ if (type === 'app-state-sync-key' && value) {
98
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
99
+ }
100
+ data[id] = value;
101
+ }));
102
+ return data;
103
+ },
104
+ set: async (data) => {
105
+ const tasks = [];
106
+ for (const category in data) {
107
+ for (const id in data[category]) {
108
+ const value = data[category][id];
109
+ const file = `${category}-${id}.json`;
110
+ tasks.push(value ? writeData(value, file) : removeData(file));
111
+ }
112
+ }
113
+ await Promise.all(tasks);
114
+ }
115
+ }
116
+ },
117
+ saveCreds: async () => {
118
+ return writeData(creds, 'creds.json');
119
+ }
120
+ };
121
+ };
122
+ exports.useMultiFileAuthState = useMultiFileAuthState;