team-atf 0.0.1-security → 1.1.8

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of team-atf might be problematic. Click here for more details.

Files changed (101) hide show
  1. package/.gitattributes +2 -0
  2. package/Extra/Database/index.js +360 -0
  3. package/Extra/ExtraAddons.js +78 -0
  4. package/Extra/ExtraFindUID.js +60 -0
  5. package/Extra/ExtraGetThread.js +118 -0
  6. package/Extra/ExtraScreenShot.js +430 -0
  7. package/Extra/ExtraUptimeRobot.js +26 -0
  8. package/Extra/Html/Classic/script.js +119 -0
  9. package/Extra/Html/Classic/style.css +8 -0
  10. package/Extra/Security/Index.js +146 -0
  11. package/Extra/Security/Step_1.js +11 -0
  12. package/Extra/Security/Step_2.js +20 -0
  13. package/Extra/Security/Step_3.js +20 -0
  14. package/Extra/Src/History.js +115 -0
  15. package/Extra/Src/Last-Run.js +65 -0
  16. package/Extra/Src/Premium.js +84 -0
  17. package/Extra/Src/uuid.js +137 -0
  18. package/Func/AcceptAgreement.js +32 -0
  19. package/Func/ClearCache.js +64 -0
  20. package/Func/ReportV1.js +54 -0
  21. package/LICENSE +24 -0
  22. package/Language/index.json +177 -0
  23. package/README.md +5 -3
  24. package/SECURITY.md +17 -0
  25. package/broadcast.js +38 -0
  26. package/gitattributes +2 -0
  27. package/index.js +1364 -0
  28. package/logger.js +65 -0
  29. package/package.json +88 -3
  30. package/replit +79 -0
  31. package/replit.nix +8 -0
  32. package/src/Dev_Horizon_Data.js +125 -0
  33. package/src/Premium.js +30 -0
  34. package/src/Screenshot.js +85 -0
  35. package/src/addExternalModule.js +16 -0
  36. package/src/addUserToGroup.js +79 -0
  37. package/src/changeAdminStatus.js +79 -0
  38. package/src/changeArchivedStatus.js +41 -0
  39. package/src/changeAvt.js +85 -0
  40. package/src/changeBio.js +65 -0
  41. package/src/changeBlockedStatus.js +36 -0
  42. package/src/changeGroupImage.js +106 -0
  43. package/src/changeNickname.js +45 -0
  44. package/src/changeThreadColor.js +62 -0
  45. package/src/changeThreadEmoji.js +42 -0
  46. package/src/createNewGroup.js +70 -0
  47. package/src/createPoll.js +60 -0
  48. package/src/deleteMessage.js +45 -0
  49. package/src/deleteThread.js +43 -0
  50. package/src/forwardAttachment.js +48 -0
  51. package/src/getAccessToken.js +32 -0
  52. package/src/getCurrentUserID.js +7 -0
  53. package/src/getEmojiUrl.js +27 -0
  54. package/src/getFriendsList.js +73 -0
  55. package/src/getMessage.js +80 -0
  56. package/src/getThreadHistory.js +537 -0
  57. package/src/getThreadInfo.js +348 -0
  58. package/src/getThreadList.js +213 -0
  59. package/src/getThreadMain.js +220 -0
  60. package/src/getThreadPictures.js +59 -0
  61. package/src/getUID.js +59 -0
  62. package/src/getUserID.js +62 -0
  63. package/src/getUserInfo.js +129 -0
  64. package/src/getUserInfoMain.js +65 -0
  65. package/src/getUserInfoV2.js +36 -0
  66. package/src/getUserInfoV3.js +63 -0
  67. package/src/getUserInfoV4.js +55 -0
  68. package/src/getUserInfoV5.js +61 -0
  69. package/src/handleFriendRequest.js +46 -0
  70. package/src/handleMessageRequest.js +49 -0
  71. package/src/httpGet.js +49 -0
  72. package/src/httpPost.js +48 -0
  73. package/src/httpPostFormData.js +41 -0
  74. package/src/listenMqtt.js +702 -0
  75. package/src/logout.js +68 -0
  76. package/src/markAsDelivered.js +48 -0
  77. package/src/markAsRead.js +70 -0
  78. package/src/markAsReadAll.js +43 -0
  79. package/src/markAsSeen.js +51 -0
  80. package/src/muteThread.js +47 -0
  81. package/src/removeUserFromGroup.js +49 -0
  82. package/src/resolvePhotoUrl.js +37 -0
  83. package/src/searchForThread.js +43 -0
  84. package/src/sendMessage.js +334 -0
  85. package/src/sendTypingIndicator.js +80 -0
  86. package/src/setMessageReaction.js +109 -0
  87. package/src/setPostReaction.js +102 -0
  88. package/src/setTitle.js +74 -0
  89. package/src/threadColors.js +39 -0
  90. package/src/unfriend.js +43 -0
  91. package/src/unsendMessage.js +40 -0
  92. package/test/data/shareAttach.js +146 -0
  93. package/test/data/something.mov +0 -0
  94. package/test/data/test.png +0 -0
  95. package/test/data/test.txt +7 -0
  96. package/test/env/.env +0 -0
  97. package/test/example-config.json +18 -0
  98. package/test/test-page.js +140 -0
  99. package/test/test.js +385 -0
  100. package/test/testv2.js +3 -0
  101. package/utils.js +1648 -0
package/index.js ADDED
@@ -0,0 +1,1364 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Developers: @TEAM-ATF - @CHANDU-PAPA
5
+ ** A few words about developer appstate security.
6
+ *! Statement renouncing responsibility for the security of appstate encryption of the following operating systems: windows, Android, Linux operating systems,.. (maybe repl.it?),
7
+ *! because the above operating systems are private (except rep.it if the fraudster does not own your account or invite link to join).
8
+ *! If the intruder owns the computer, these private operating systems,the security of this fca cannot guarantee 100% of the time.
9
+ ** If the grammar is wrong, please understand because I'm just a kid 🍵.
10
+ */
11
+
12
+ /!-[ Global Set ]-!/
13
+
14
+ global.Fca = new Object({
15
+ isThread: new Array(),
16
+ isUser: new Array(),
17
+ startTime: Date.now(),
18
+ Setting: new Map(),
19
+ Version: require('./package.json').version,
20
+ Require: new Object({
21
+ fs: require("fs"),
22
+ Fetch: require('got'),
23
+ log: require("npmlog"),
24
+ utils: require("./utils"),
25
+ logger: require('./logger'),
26
+ languageFile: require('./Language/index.json'),
27
+ Database: require("./Extra/Database"),
28
+ Security: require('./Extra/Src/uuid')
29
+ }),
30
+ getText: function(/** @type {any[]} */...Data) {
31
+ var Main = (Data.splice(0,1)).toString();
32
+ for (let i = 0; i < Data.length; i++) Main = Main.replace(RegExp(`%${i + 1}`, 'g'), Data[i]);
33
+ return Main;
34
+ },
35
+ Data: new Object({
36
+ ObjFastConfig: {
37
+ "Language": "en",
38
+ "PreKey": "",
39
+ "AutoUpdate": false,
40
+ "MainColor": "#9900FF",
41
+ "MainName": "[ FCA-ATF ]",
42
+ "Logo": false,
43
+ "Uptime": true,
44
+ "Config": "default",
45
+ "Login2Fa": false,
46
+ "AutoLogin": false,
47
+ "BroadCast": true,
48
+ "AuthString": "SD4S XQ32 O2JA WXB3 FUX2 OPJ7 Q7JZ 4R6Z | https://i.imgur.com/RAg3rvw.png Please remove this !, Recommend If You Using getUserInfoV2",
49
+ "EncryptFeature": true,
50
+ "ResetDataLogin": false,
51
+ "AutoRestartMinutes": 0,
52
+ "HTML": {
53
+ "HTML": true,
54
+ "UserName": "Guest",
55
+ "MusicLink": "https://drive.google.com/uc?id=1zlAALlxk1TnO7jXtEP_O6yvemtzA2ukA&export=download"
56
+ }
57
+ },
58
+ CountTime: function() {
59
+ var fs = global.Fca.Require.fs;
60
+ if (fs.existsSync(__dirname + '/CountTime.json')) {
61
+ try {
62
+ var data = Number(fs.readFileSync(__dirname + '/CountTime.json', 'utf8')),
63
+ hours = Math.floor(data / (60 * 60));
64
+ }
65
+ catch (e) {
66
+ fs.writeFileSync(__dirname + '/CountTime.json', 0);
67
+ hours = 0;
68
+ }
69
+ }
70
+ else {
71
+ hours = 0;
72
+ }
73
+ return `${hours} Hours`;
74
+ }
75
+ }),
76
+ AutoLogin: async function () {
77
+ var Database = global.Fca.Require.Database;
78
+ var logger = global.Fca.Require.logger;
79
+ var Email = (await global.Fca.Require.Database.get('Account')).replace(RegExp('"', 'g'), ''); //hmm IDK
80
+ var PassWord = (await global.Fca.Require.Database.get('Password')).replace(RegExp('"', 'g'), '');
81
+ login({ email: Email, password: PassWord},async (error, api) => {
82
+ if (error) {
83
+ logger.Error(JSON.stringify(error,null,2), function() { logger.Error("AutoLogin Failed!", function() { process.exit(0); }) });
84
+ }
85
+ try {
86
+ await Database.set("TempState", api.getAppState());
87
+ }
88
+ catch(e) {
89
+ logger.Warning(global.Fca.Require.Language.Index.ErrDatabase);
90
+ logger.Error();
91
+ process.exit(0);
92
+ }
93
+ process.exit(1);
94
+ });
95
+ }
96
+ });
97
+
98
+ /!-[ Check File To Run Process ]-!/
99
+
100
+ let Boolean_Fca = ["AutoUpdate","Uptime","BroadCast","EncryptFeature","AutoLogin","ResetDataLogin","Login2Fa","Logo"];
101
+ let String_Fca = ["MainName","PreKey","Language","AuthString","Config"]
102
+ let Number_Fca = ["AutoRestartMinutes"];
103
+ let All_Variable = Boolean_Fca.concat(String_Fca,Number_Fca);
104
+
105
+ try {
106
+ if (!global.Fca.Require.fs.existsSync(process.cwd() + '/ATF.Config.json')) {
107
+ global.Fca.Require.fs.writeFileSync(process.cwd() + "/ATF.Config.json", JSON.stringify(global.Fca.Data.ObjFastConfig, null, "\t"));
108
+ process.exit(1);
109
+ }
110
+
111
+ try {
112
+ var DataLanguageSetting = require(process.cwd() + "/ATF.Config.json");
113
+ }
114
+ catch (e) {
115
+ global.Fca.Require.logger.Error('Detect Your ATF.Config Settings Invalid!, Carry out default restoration');
116
+ global.Fca.Require.fs.writeFileSync(process.cwd() + "/ATF.Config.json", JSON.stringify(global.Fca.Data.ObjFastConfig, null, "\t"));
117
+ process.exit(1)
118
+ }
119
+ if (global.Fca.Require.fs.existsSync(process.cwd() + '/ATF.Config.json')) {
120
+ try {
121
+ if (DataLanguageSetting.!= undefined) {
122
+ delete DataLanguageSetting.Logo
123
+ global.Fca.Require.fs.writeFileSync(process.cwd() + "/ATF.Config.json", JSON.stringify(DataLanguageSetting, null, "\t"));
124
+ }
125
+ }
126
+ catch (e) {
127
+ console.log(e);
128
+ }
129
+ if (!global.Fca.Require.languageFile.some((/** @type {{ Language: string; }} */i) => i.Language == DataLanguageSetting.Language)) {
130
+ global.Fca.Require.logger.Warning("Not Support Language: " + DataLanguageSetting.Language + " Only 'en' and 'vi'");
131
+ process.exit(0);
132
+ }
133
+ var Language = global.Fca.Require.languageFile.find((/** @type {{ Language: string; }} */i) => i.Language == DataLanguageSetting.Language).Folder.Index;
134
+ global.Fca.Require.Language = global.Fca.Require.languageFile.find((/** @type {{ Language: string; }} */i) => i.Language == DataLanguageSetting.Language).Folder;
135
+ } else process.exit(1);
136
+ for (let i in DataLanguageSetting) {
137
+ if (Boolean_Fca.includes(i)) {
138
+ if (global.Fca.Require.utils.getType(DataLanguageSetting[i]) != "Boolean") return logger.Error(i + " Is Not A Boolean, Need To Be true Or false !", function() { process.exit(0) });
139
+ else continue;
140
+ }
141
+ else if (String_Fca.includes(i)) {
142
+ if (global.Fca.Require.utils.getType(DataLanguageSetting[i]) != "String") return logger.Error(i + " Is Not A String, Need To Be String!", function() { process.exit(0) });
143
+ else continue;
144
+ }
145
+ else if (Number_Fca.includes(i)) {
146
+ if (global.Fca.Require.utils.getType(DataLanguageSetting[i]) != "Number") return logger.Error(i + " Is Not A Number, Need To Be Number !", function() { process.exit(0) });
147
+ else continue;
148
+ }
149
+ }
150
+ for (let i of All_Variable) {
151
+ if (!DataLanguageSetting[All_Variable[i]] == undefined) {
152
+ DataLanguageSetting[All_Variable[i]] = global.Fca.Data.ObjFastConfig[All_Variable[i]];
153
+ global.Fca.Require.fs.writeFileSync(process.cwd() + "/ATF.Config.json", JSON.stringify(DataLanguageSetting, null, "\t"));
154
+ }
155
+ else continue;
156
+ }
157
+ global.Fca.Require.FastConfig = DataLanguageSetting;
158
+ }
159
+ catch (e) {
160
+ console.log(e);
161
+ global.Fca.Require.logger.Error();
162
+ }
163
+
164
+ /!-[ Require config and use ]-!/
165
+
166
+ if (global.Fca.Require.FastConfig.Config != 'default') {
167
+ //do ssth
168
+ }
169
+
170
+ /!-[ Require All Package Need Use ]-!/
171
+
172
+ var utils = global.Fca.Require.utils,
173
+ logger = global.Fca.Require.logger,
174
+ fs = global.Fca.Require.fs,
175
+ getText = global.Fca.getText,
176
+ log = global.Fca.Require.log,
177
+ Fetch = global.Fca.Require.Fetch,
178
+ express = require("express")(),
179
+ { join, resolve } = require('path'),
180
+ cheerio = require("cheerio"),
181
+ StateCrypt = {},
182
+ { readFileSync } = require('fs-extra'),
183
+ Database = require("./Extra/Database"),
184
+ readline = require("readline"),
185
+ chalk = require("chalk"),
186
+ figlet = require("figlet"),
187
+ os = require("os"),
188
+ Security = require("./Extra/Security/Index");
189
+
190
+ /!-[ Set Variable For Process ]-!/
191
+
192
+ log.maxRecordSize = 100;
193
+ var checkVerified = null;
194
+ var Boolean_Option = ['online','selfListen','listenEvents','updatePresence','forceLogin','autoMarkDelivery','autoMarkRead','listenTyping','autoReconnect','emitReady'];
195
+
196
+ /!-[ Set And Check Template HTML ]-!/
197
+
198
+ var css = readFileSync(join(__dirname, 'Extra', 'Html', 'Classic', 'style.css'));
199
+ var js = readFileSync(join(__dirname, 'Extra', 'Html', 'Classic', 'script.js'));
200
+
201
+ /!-[ Function Generate HTML Template ]-!/
202
+
203
+ /**
204
+ * It returns a string of HTML code.
205
+ * @param UserName - The username of the user
206
+ * @param Type - The type of user, either "Free" or "Premium"
207
+ * @param link - The link to the music you want to play
208
+ * @returns A HTML file
209
+ */
210
+
211
+ function ClassicHTML(UserName,Type,link) {
212
+ return `<!DOCTYPE html>
213
+ <html lang="en" >
214
+ <head>
215
+ <meta charset="UTF-8">
216
+ <title>CHAND</title>
217
+ <link rel="stylesheet" href="./style.css">
218
+ </head>
219
+ <body>
220
+ <center>
221
+ <marquee><b>waiting for u :d</b></marquee>
222
+ <h2>CHAND User Infomation</h2>
223
+ <h3>UserName: ${UserName} | Type: ${Type}</h3>
224
+ <canvas id="myCanvas"></canvas>
225
+ <script src="./script.js"></script>
226
+ <footer class="footer">
227
+ <div id="music">
228
+ <audio autoplay="false" controls="true" loop="true" src="${link}" __idm_id__="5070849">Your browser does not support the audio element.</audio>
229
+ <br><b>Session ID:</b> ${global.Fca.Require.Security.create().uuid}<br>
230
+ <br>Thanks For Using <b>team.atf</b> - From <b>Kanzu</b> <3<br>
231
+ </div>
232
+ </footer>
233
+ </div>
234
+ </center>
235
+ </html>
236
+ </body>`
237
+ //lazy to change
238
+ }
239
+
240
+ /!-[ Stating Http Infomation ]-!/
241
+
242
+ express.set('DFP', (process.env.PORT || process.env.port || 1932));
243
+ express.use(function(req, res, next) {
244
+ switch (req.url.split('?')[0]) {
245
+ case '/script.js': {
246
+ res.writeHead(200, { 'Content-Type': 'text/javascript' });
247
+ res.write(js);
248
+ break;
249
+ }
250
+ case '/style.css': {
251
+ res.writeHead(200, { 'Content-Type': 'text/css' });
252
+ res.write(css);
253
+ break;
254
+ }
255
+ // case '/History': {
256
+ // if (req.query.PassWord == process.env.REPL_OWNER) {
257
+ // res.writeHead(200, { 'Content-Type': 'application/json charset=utf-8' });
258
+ // res.write(JSON.stringify(console.history,null,2),'utf8');
259
+ // res.end();
260
+ // }
261
+ // else res.json({
262
+ // Status: false,
263
+ // Error: "Thiếu Params ?PassWord=PassWordCuaBan =))"
264
+ // });
265
+ // break;
266
+ // }
267
+ default: {
268
+ res.writeHead(200, "OK", { "Content-Type": "text/html" });
269
+ res.write(ClassicHTML(global.Fca.Require.FastConfig.HTML.UserName, global.Fca.Data.PremText.includes("Premium") ? "Premium": "Free", global.Fca.Require.FastConfig.HTML.MusicLink));
270
+ }
271
+ }
272
+ res.end();
273
+ })
274
+
275
+ global.Fca.Require.Web = express;
276
+
277
+ /!-[ Function setOptions ]-!/
278
+
279
+ /**
280
+ * @param {{ [x: string]: boolean; selfListen?: boolean; listenEvents?: boolean; listenTyping?: boolean; updatePresence?: boolean; forceLogin?: boolean; autoMarkDelivery?: boolean; autoMarkRead?: boolean; autoReconnect?: boolean; logRecordSize: any; online?: boolean; emitReady?: boolean; userAgent: any; logLevel?: any; pageID?: any; proxy?: any; }} globalOptions
281
+ * @param {{ [x: string]: any; logLevel?: any; forceLogin?: boolean; userAgent?: any; pauseLog?: any; logRecordSize?: any; pageID?: any; proxy?: any; }} options
282
+ */
283
+
284
+ function setOptions(globalOptions, options) {
285
+ Object.keys(options).map(function(key) {
286
+ switch (Boolean_Option.includes(key)) {
287
+ case true: {
288
+ globalOptions[key] = Boolean(options[key]);
289
+ break;
290
+ }
291
+ case false: {
292
+ switch (key) {
293
+ case 'pauseLog': {
294
+ if (options.pauseLog) log.pause();
295
+ else log.resume();
296
+ break;
297
+ }
298
+ case 'logLevel': {
299
+ log.level = options.logLevel;
300
+ globalOptions.logLevel = options.logLevel;
301
+ break;
302
+ }
303
+ case 'logRecordSize': {
304
+ log.maxRecordSize = options.logRecordSize;
305
+ globalOptions.logRecordSize = options.logRecordSize;
306
+ break;
307
+ }
308
+ case 'pageID': {
309
+ globalOptions.pageID = options.pageID.toString();
310
+ break;
311
+ }
312
+ case 'userAgent': {
313
+ globalOptions.userAgent = (options.userAgent || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36');
314
+ break;
315
+ }
316
+ case 'proxy': {
317
+ if (typeof options.proxy != "string") {
318
+ delete globalOptions.proxy;
319
+ utils.setProxy();
320
+ } else {
321
+ globalOptions.proxy = options.proxy;
322
+ utils.setProxy(globalOptions.proxy);
323
+ }
324
+ break;
325
+ }
326
+ default: {
327
+ log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
328
+ break;
329
+ }
330
+ }
331
+ break;
332
+ }
333
+ }
334
+ });
335
+ }
336
+
337
+ /!-[ Function BuildAPI ]-!/
338
+
339
+ /**
340
+ * @param {any} globalOptions
341
+ * @param {string} html
342
+ * @param {{ getCookies: (arg0: string) => any[]; }} jar
343
+ */
344
+
345
+ function buildAPI(globalOptions, html, jar) {
346
+ var maybeCookie = jar.getCookies("https://www.facebook.com").filter(function(/** @type {{ cookieString: () => string; }} */val) { return val.cookieString().split("=")[0] === "c_user"; });
347
+
348
+ if (maybeCookie.length === 0) {
349
+ switch (global.Fca.Require.FastConfig.AutoLogin) {
350
+ case true: {
351
+ global.Fca.Require.logger.Warning(global.Fca.Require.Language.Index.AutoLogin, function() {
352
+ return global.Fca.AutoLogin();
353
+ });
354
+ break;
355
+ }
356
+ case false: {
357
+ throw { error: global.Fca.Require.Language.Index.ErrAppState };
358
+
359
+ }
360
+ }
361
+ }
362
+
363
+ if (html.indexOf("/checkpoint/block/?next") > -1) log.warn("login", Language.CheckPointLevelI);
364
+
365
+ var userID = maybeCookie[0].cookieString().split("=")[1].toString();
366
+ process.env['UID'] = logger.Normal(getText(Language.UID,userID), userID);
367
+
368
+ try {
369
+ clearInterval(checkVerified);
370
+ } catch (e) {
371
+ console.log(e);
372
+ }
373
+
374
+ var clientID = (Math.random() * 2147483648 | 0).toString(16);
375
+
376
+ var CHECK_MQTT = {
377
+ oldFBMQTTMatch: html.match(/irisSeqID:"(.+?)",appID:219994525426954,endpoint:"(.+?)"/),
378
+ newFBMQTTMatch: html.match(/{"app_id":"219994525426954","endpoint":"(.+?)","iris_seq_id":"(.+?)"}/),
379
+ legacyFBMQTTMatch: html.match(/(\["MqttWebConfig",\[\],{fbid:")(.+?)(",appID:219994525426954,endpoint:")(.+?)(",pollingEndpoint:")(.+?)(3790])/)
380
+ }
381
+
382
+ let Slot = Object.keys(CHECK_MQTT);
383
+
384
+ var mqttEndpoint,region,irisSeqID;
385
+ Object.keys(CHECK_MQTT).map(function(MQTT) {
386
+ if (CHECK_MQTT[MQTT] && !region) {
387
+ switch (Slot.indexOf(MQTT)) {
388
+ case 0: {
389
+ irisSeqID = CHECK_MQTT[MQTT][1];
390
+ mqttEndpoint = CHECK_MQTT[MQTT][2];
391
+ region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
392
+ return;
393
+ }
394
+ case 1: {
395
+ irisSeqID = CHECK_MQTT[MQTT][2];
396
+ mqttEndpoint = CHECK_MQTT[MQTT][1].replace(/\\\//g, "/");
397
+ region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
398
+ return;
399
+ }
400
+ case 2: {
401
+ mqttEndpoint = CHECK_MQTT[MQTT][4];
402
+ region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
403
+ return;
404
+ }
405
+ }
406
+ return;
407
+ }
408
+ });
409
+
410
+ var ctx = {
411
+ userID: userID,
412
+ jar: jar,
413
+ clientID: clientID,
414
+ globalOptions: globalOptions,
415
+ loggedIn: true,
416
+ access_token: 'NONE',
417
+ clientMutationId: 0,
418
+ mqttClient: undefined,
419
+ lastSeqId: irisSeqID,
420
+ syncToken: undefined,
421
+ mqttEndpoint: mqttEndpoint,
422
+ region: region,
423
+ firstListen: true
424
+ };
425
+
426
+ var api = {
427
+ setOptions: setOptions.bind(null, globalOptions),
428
+ getAppState: function getAppState() {
429
+ return utils.getAppState(jar);
430
+ }
431
+ };
432
+
433
+ if (region && mqttEndpoint) {
434
+ //do sth
435
+ }
436
+ else {
437
+ log.warn("login", getText(Language.NoAreaData));
438
+ api["htmlData"] = html;
439
+ }
440
+
441
+ var defaultFuncs = utils.makeDefaults(html, userID, ctx);
442
+
443
+ fs.readdirSync(__dirname + "/src").filter((/** @type {string} */File) => File.endsWith(".js") && !File.includes('Dev_')).map((/** @type {string} */File) => api[File.split('.').slice(0, -1).join('.')] = require('./src/' + File)(defaultFuncs, api, ctx));
444
+
445
+ return {
446
+ ctx,
447
+ defaultFuncs,
448
+ api
449
+ };
450
+ }
451
+
452
+ /!-[ Function makeLogin ]-!/
453
+
454
+ /**
455
+ * @param {{ setCookie: (arg0: any, arg1: string) => void; }} jar
456
+ * @param {any} email
457
+ * @param {any} password
458
+ * @param {{ forceLogin: any; }} loginOptions
459
+ * @param {(err: any, api: any) => any} callback
460
+ * @param {any} prCallback
461
+ */
462
+
463
+ function makeLogin(jar, email, password, loginOptions, callback, prCallback) {
464
+ return function(/** @type {{ body: any; }} */res) {
465
+ var html = res.body,$ = cheerio.load(html),arr = [];
466
+
467
+ $("#login_form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
468
+
469
+ arr = arr.filter(function(v) {
470
+ return v.val && v.val.length;
471
+ });
472
+
473
+ var form = utils.arrToForm(arr);
474
+ form.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
475
+ form.lgndim = Buffer.from("{\"w\":1440,\"h\":900,\"aw\":1440,\"ah\":834,\"c\":24}").toString('base64');
476
+ form.email = email;
477
+ form.pass = password;
478
+ form.default_persistent = '0';
479
+ form.locale = 'en_US';
480
+ form.timezone = '240';
481
+ form.lgnjs = ~~(Date.now() / 1000);
482
+
483
+ html.split("\"_js_").slice(1).map((/** @type {any} */val) => {
484
+ jar.setCookie(utils.formatCookie(JSON.parse("[\"" + utils.getFrom(val, "", "]") + "]"), "facebook"),"https://www.facebook.com")
485
+ });
486
+
487
+ logger.Normal(Language.OnLogin);
488
+ return utils
489
+ .post("https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110", jar, form, loginOptions)
490
+ .then(utils.saveCookies(jar))
491
+ .then(function(/** @type {{ headers: any; }} */res) {
492
+ var headers = res.headers;
493
+ if (!headers.location) throw { error: Language.InvaildAccount };
494
+
495
+ // This means the account has login approvals turned on.
496
+ if (headers.location.indexOf('https://www.facebook.com/checkpoint/') > -1) {
497
+ logger.Warning(Language.TwoAuth);
498
+ var nextURL = 'https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php';
499
+
500
+ return utils
501
+ .get(headers.location, jar, null, loginOptions)
502
+ .then(utils.saveCookies(jar))
503
+ .then(async function(/** @type {{ body: any; }} */res) {
504
+ if (!await Database.get('ThroughAcc')) {
505
+ await Database.set('ThroughAcc', email);
506
+ }
507
+ else {
508
+ if (String((await Database.get('ThroughAcc'))).replace(RegExp('"','g'), '') != String(email).replace(RegExp('"','g'), '')) {
509
+ await Database.set('ThroughAcc', email);
510
+ if (await Database.get('Through2Fa')) {
511
+ await Database.delete('Through2Fa');
512
+ }
513
+ }
514
+ }
515
+ var html = res.body,$ = cheerio.load(html), arr = [];
516
+ $("form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
517
+ arr = arr.filter(v => { return v.val && v.val.length });
518
+ var form = utils.arrToForm(arr);
519
+ if (html.indexOf("checkpoint/?next") > -1) {
520
+ setTimeout(() => {
521
+ checkVerified = setInterval((_form) => {}, 5000, {
522
+ fb_dtsg: form.fb_dtsg,
523
+ jazoest: form.jazoest,
524
+ dpr: 1
525
+ });
526
+ }, 2500);
527
+ switch (global.Fca.Require.FastConfig.Login2Fa) {
528
+ case true: {
529
+ try {
530
+ const question = question => {
531
+ const rl = readline.createInterface({
532
+ input: process.stdin,
533
+ output: process.stdout
534
+ });
535
+ return new Promise(resolve => {
536
+ rl.question(question, answer => {
537
+ rl.close();
538
+ return resolve(answer);
539
+ });
540
+ });
541
+ };
542
+ async function EnterSecurityCode() {
543
+ try {
544
+ var Through2Fa = await Database.get('Through2Fa');
545
+ if (Through2Fa) {
546
+ Through2Fa.map(function(/** @type {{ key: string; value: string; expires: string; domain: string; path: string; }} */c) {
547
+ let str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";";
548
+ jar.setCookie(str, "http://" + c.domain);
549
+ })
550
+ var from2 = utils.arrToForm(arr);
551
+ from2.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
552
+ from2.lgndim = Buffer.from("{\"w\":1440,\"h\":900,\"aw\":1440,\"ah\":834,\"c\":24}").toString('base64');
553
+ from2.email = email;
554
+ from2.pass = password;
555
+ from2.default_persistent = '0';
556
+ from2.locale = 'en_US';
557
+ from2.timezone = '240';
558
+ from2.lgnjs = ~~(Date.now() / 1000);
559
+ return utils
560
+ .post("https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110", jar, from2, loginOptions)
561
+ .then(utils.saveCookies(jar))
562
+ .then(function(/** @type {{ headers: any; }} */res) {
563
+ var headers = res.headers;
564
+ if (!headers['set-cookie'][0].includes('deleted')) {
565
+ logger.Warning(Language.ErrThroughCookies, async function() {
566
+ await Database.delete('Through2Fa');
567
+ });
568
+ process.exit(1);
569
+ }
570
+ if (headers.location && headers.location.indexOf('https://www.facebook.com/checkpoint/') > -1) {
571
+ return utils
572
+ .get(headers.location, jar, null, loginOptions)
573
+ .then(utils.saveCookies(jar))
574
+ .then(function(/** @type {{ body: any; }} */res) {
575
+ var html = res.body,$ = cheerio.load(html), arr = [];
576
+ $("form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
577
+ arr = arr.filter(v => { return v.val && v.val.length });
578
+ var from2 = utils.arrToForm(arr);
579
+
580
+ if (html.indexOf("checkpoint/?next") > -1) {
581
+ setTimeout(() => {
582
+ checkVerified = setInterval((_form) => {}, 5000, {
583
+ fb_dtsg: from2.fb_dtsg,
584
+ jazoest: from2.jazoest,
585
+ dpr: 1
586
+ });
587
+ }, 2500);
588
+ if (!res.headers.location && res.headers['set-cookie'][0].includes('checkpoint')) {
589
+ try {
590
+ delete from2.name_action_selected;
591
+ from2['submit[Continue]'] = $("#checkpointSubmitButton").html();
592
+ return utils
593
+ .post(nextURL, jar, from2, loginOptions)
594
+ .then(utils.saveCookies(jar))
595
+ .then(function() {
596
+ from2['submit[This was me]'] = "This was me";
597
+ return utils.post(nextURL, jar, from2, loginOptions).then(utils.saveCookies(jar));
598
+ })
599
+ .then(function() {
600
+ delete from2['submit[This was me]'];
601
+ from2.name_action_selected = 'save_device';
602
+ from2['submit[Continue]'] = $("#checkpointSubmitButton").html();
603
+ return utils.post(nextURL, jar, from2, loginOptions).then(utils.saveCookies(jar));
604
+ })
605
+ .then(async function(/** @type {{ headers: any; body: string | string[]; }} */res) {
606
+ var headers = res.headers;
607
+ if (!headers.location && res.headers['set-cookie'][0].includes('checkpoint')) throw { error: "wtf ??:D" };
608
+ var appState = utils.getAppState(jar,false);
609
+ await Database.set('Through2Fa', appState);
610
+ return loginHelper(appState, email, password, loginOptions, callback);
611
+ })
612
+ .catch((/** @type {any} */e) => callback(e));
613
+ }
614
+ catch (e) {
615
+ console.log(e)
616
+ }
617
+ }
618
+ }
619
+ })
620
+ }
621
+ return utils.get('https://www.facebook.com/', jar, null, loginOptions).then(utils.saveCookies(jar));
622
+ }).catch((/** @type {any} */e) => console.log(e));
623
+ }
624
+ }
625
+ catch (e) {
626
+ await Database.delete('Through2Fa');
627
+ }
628
+ var code = await question(Language.EnterSecurityCode);
629
+ try {
630
+ form.approvals_code = code;
631
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html();
632
+ var prResolve,prReject;
633
+ var rtPromise = new Promise((resolve, reject) => { prResolve = resolve; prReject = reject; });
634
+ if (typeof code == "string") { //always strings
635
+ utils
636
+ .post(nextURL, jar, form, loginOptions)
637
+ .then(utils.saveCookies(jar))
638
+ .then(function(/** @type {{ body: string | Buffer; }} */res) {
639
+ var $ = cheerio.load(res.body);
640
+ var error = $("#approvals_code").parent().attr("data-xui-error");
641
+ if (error) {
642
+ logger.Warning(Language.InvaildTwoAuthCode,function() { EnterSecurityCode(); }); //bruh loop
643
+ };
644
+ })
645
+ .then(function() {
646
+ delete form.no_fido;delete form.approvals_code;
647
+ form.name_action_selected = 'save_device'; //'save_device' || 'dont_save;
648
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
649
+ })
650
+ .then(async function(/** @type {{ headers: any; body: string | string[]; }} */res) {
651
+ var headers = res.headers;
652
+ if (!headers.location && res.headers['set-cookie'][0].includes('checkpoint')) {
653
+ try {
654
+ delete form.name_action_selected;
655
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html();
656
+ return utils
657
+ .post(nextURL, jar, form, loginOptions)
658
+ .then(utils.saveCookies(jar))
659
+ .then(function() {
660
+ form['submit[This was me]'] = "This was me";
661
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
662
+ })
663
+ .then(function() {
664
+ delete form['submit[This was me]'];
665
+ form.name_action_selected = 'save_device';
666
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html();
667
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
668
+ })
669
+ .then(async function(/** @type {{ headers: any; body: string | string[]; }} */res) {
670
+ var headers = res.headers;
671
+ if (!headers.location && res.headers['set-cookie'][0].includes('checkpoint')) throw { error: "wtf ??:D" };
672
+ var appState = utils.getAppState(jar,false);
673
+ await Database.set('Through2Fa', appState);
674
+ return loginHelper(appState, email, password, loginOptions, callback);
675
+ })
676
+ .catch((/** @type {any} */e) => callback(e));
677
+ }
678
+ catch (e) {
679
+ console.log(e)
680
+ }
681
+ }
682
+ var appState = utils.getAppState(jar,false);
683
+ if (callback === prCallback) {
684
+ callback = function(/** @type {any} */err, /** @type {any} */api) {
685
+ if (err) return prReject(err);
686
+ return prResolve(api);
687
+ };
688
+ }
689
+ await Database.set('Through2Fa', appState);
690
+ return loginHelper(appState, email, password, loginOptions, callback);
691
+ })
692
+ .catch(function(/** @type {any} */err) {
693
+ if (callback === prCallback) prReject(err);
694
+ else callback(err);
695
+ });
696
+ } else {
697
+ utils
698
+ .post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions, null, { "Referer": "https://www.facebook.com/checkpoint/?next" })
699
+ .then(utils.saveCookies(jar))
700
+ .then(async function(/** @type {{ body: string; }} */res) {
701
+ try {
702
+ JSON.parse(res.body.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, ""));
703
+ } catch (ex) {
704
+ clearInterval(checkVerified);
705
+ logger.Warning(Language.VerifiedCheck);
706
+ if (callback === prCallback) {
707
+ callback = function(/** @type {any} */err, /** @type {any} */api) {
708
+ if (err) return prReject(err);
709
+ return prResolve(api);
710
+ };
711
+ }
712
+ let appState = utils.getAppState(jar,false);
713
+ return loginHelper(appState, email, password, loginOptions, callback);
714
+ }
715
+ })
716
+ .catch((/** @type {any} */ex) => {
717
+ log.error("login", ex);
718
+ if (callback === prCallback) prReject(ex);
719
+ else callback(ex);
720
+ });
721
+ }
722
+ return rtPromise;
723
+ }
724
+ catch (e) {
725
+ logger.Error(e)
726
+ logger.Error()
727
+ process.exit(0)
728
+ }
729
+ }
730
+ await EnterSecurityCode()
731
+ }
732
+ catch (e) {
733
+ logger.Error(e)
734
+ logger.Error();
735
+ process.exit(0);
736
+ }
737
+ }
738
+ break;
739
+ case false: {
740
+ throw {
741
+ error: 'login-approval',
742
+ continue: function submit2FA(/** @type {any} */code) {
743
+ form.approvals_code = code;
744
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html(); //'Continue';
745
+ var prResolve,prReject;
746
+ var rtPromise = new Promise((resolve, reject) => { prResolve = resolve; prReject = reject; });
747
+ if (typeof code == "string") {
748
+ utils
749
+ .post(nextURL, jar, form, loginOptions)
750
+ .then(utils.saveCookies(jar))
751
+ .then(function(/** @type {{ body: string | Buffer; }} */res) {
752
+ var $ = cheerio.load(res.body);
753
+ var error = $("#approvals_code").parent().attr("data-xui-error");
754
+ if (error) {
755
+ throw {
756
+ error: 'login-approval',
757
+ errordesc: Language.InvaildTwoAuthCode,
758
+ lerror: error,
759
+ continue: submit2FA
760
+ };
761
+ }
762
+ })
763
+ .then(function() {
764
+ delete form.no_fido;delete form.approvals_code;
765
+ form.name_action_selected = 'dont_save'; //'save_device' || 'dont_save;
766
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
767
+ })
768
+ .then(function(/** @type {{ headers: any; body: string | string[]; }} */res) {
769
+ var headers = res.headers;
770
+ if (!headers.location && res.headers['set-cookie'][0].includes('checkpoint')) throw { error: Language.ApprovalsErr };
771
+ var appState = utils.getAppState(jar,false);
772
+ if (callback === prCallback) {
773
+ callback = function(/** @type {any} */err, /** @type {any} */api) {
774
+ if (err) return prReject(err);
775
+ return prResolve(api);
776
+ };
777
+ }
778
+ return loginHelper(appState, email, password, loginOptions, callback);
779
+ })
780
+ .catch(function(/** @type {any} */err) {
781
+ if (callback === prCallback) prReject(err);
782
+ else callback(err);
783
+ });
784
+ } else {
785
+ utils
786
+ .post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions, null, { "Referer": "https://www.facebook.com/checkpoint/?next" })
787
+ .then(utils.saveCookies(jar))
788
+ .then((/** @type {{ body: string; }} */res) => {
789
+ try {
790
+ JSON.parse(res.body.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, ""));
791
+ } catch (ex) {
792
+ clearInterval(checkVerified);
793
+ logger.Warning(Language.VerifiedCheck);
794
+ if (callback === prCallback) {
795
+ callback = function(/** @type {any} */err, /** @type {any} */api) {
796
+ if (err) return prReject(err);
797
+ return prResolve(api);
798
+ };
799
+ }
800
+ return loginHelper(utils.getAppState(jar,false), email, password, loginOptions, callback);
801
+ }
802
+ })
803
+ .catch((/** @type {any} */ex) => {
804
+ log.error("login", ex);
805
+ if (callback === prCallback) prReject(ex);
806
+ else callback(ex);
807
+ });
808
+ }
809
+ return rtPromise;
810
+ }
811
+ };
812
+ }
813
+ }
814
+ } else {
815
+ if (!loginOptions.forceLogin) throw { error: Language.ForceLoginNotEnable };
816
+
817
+ if (html.indexOf("Suspicious Login Attempt") > -1) form['submit[This was me]'] = "This was me";
818
+ else form['submit[This Is Okay]'] = "This Is Okay";
819
+
820
+ return utils
821
+ .post(nextURL, jar, form, loginOptions)
822
+ .then(utils.saveCookies(jar))
823
+ .then(function() {
824
+ form.name_action_selected = 'dont_save';
825
+
826
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
827
+ })
828
+ .then(function(/** @type {{ headers: any; body: string | string[]; }} */res) {
829
+ var headers = res.headers;
830
+
831
+ if (!headers.location && res.body.indexOf('Review Recent Login') > -1) throw { error: "Something went wrong with review recent login." };
832
+
833
+ var appState = utils.getAppState(jar,false);
834
+
835
+ return loginHelper(appState, email, password, loginOptions, callback);
836
+ })
837
+ .catch((/** @type {any} */e) => callback(e));
838
+ }
839
+ });
840
+ }
841
+ return utils.get('https://www.facebook.com/', jar, null, loginOptions).then(utils.saveCookies(jar));
842
+ });
843
+ };
844
+ }
845
+
846
+ /!-[ Function backup ]-!/
847
+
848
+ /**
849
+ * @param {string} data
850
+ * @param {any} globalOptions
851
+ * @param {any} callback
852
+ * @param {any} prCallback
853
+ */
854
+
855
+ function backup(data,globalOptions, callback, prCallback) {
856
+ try {
857
+ var appstate;
858
+ try {
859
+ appstate = JSON.parse(data)
860
+ }
861
+ catch(e) {
862
+ appstate = data;
863
+ }
864
+ logger.Warning(Language.BackupNoti);
865
+ try {
866
+ loginHelper(appstate,null,null,globalOptions, callback, prCallback)
867
+ }
868
+ catch (e) {
869
+ logger.Error(Language.ErrBackup);
870
+ process.exit(0);
871
+ }
872
+ }
873
+ catch (e) {
874
+ return logger.Error();
875
+ }
876
+ }
877
+
878
+ /!-[ async function loginHelper ]-!/
879
+
880
+ /**
881
+ * @param {string | any[]} appState
882
+ * @param {any} email
883
+ * @param {any} password
884
+ * @param {{ selfListen?: boolean; listenEvents?: boolean; listenTyping?: boolean; updatePresence?: boolean; forceLogin?: boolean; autoMarkDelivery?: boolean; autoMarkRead?: boolean; autoReconnect?: boolean; logRecordSize?: number; online?: boolean; emitReady?: boolean; userAgent?: string; pageID?: any; }} globalOptions
885
+ * @param {(arg0: any, arg1: undefined) => void} callback
886
+ * @param {(error: any, api: any) => any} [prCallback]
887
+ */
888
+
889
+ async function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
890
+ var mainPromise = null;
891
+ var jar = utils.getJar();
892
+
893
+ if (fs.existsSync('./backupappstate.json')) {
894
+ fs.unlinkSync('./backupappstate.json');
895
+ }
896
+
897
+ try {
898
+ if (appState) {
899
+ logger.Normal(Language.OnProcess);
900
+ switch (await Database.has("FBKEY")) {
901
+ case true: {
902
+ process.env.FBKEY = await Database.get("FBKEY");
903
+ }
904
+ break;
905
+ case false: {
906
+ const SecurityKey = global.Fca.Require.Security.create().apiKey;
907
+ process.env['FBKEY'] = SecurityKey;
908
+ await Database.set('FBKEY', SecurityKey);
909
+ }
910
+ break;
911
+ default: {
912
+ const SecurityKey = global.Fca.Require.Security.create().apiKey;
913
+ process.env['FBKEY'] = SecurityKey;
914
+ await Database.set('FBKEY', SecurityKey);
915
+ }
916
+ }
917
+ try {
918
+ switch (global.Fca.Require.FastConfig.EncryptFeature) {
919
+ case true: {
920
+ appState = JSON.parse(JSON.stringify(appState, null, "\t"));
921
+ switch (utils.getType(appState)) {
922
+ case "Array": {
923
+ switch (utils.getType(appState[0])) {
924
+ case "Object": {
925
+ logger.Normal(Language.NotReadyToDecrypt);
926
+ }
927
+ break;
928
+ case "String": {
929
+ appState = Security(appState,process.env['FBKEY'],'Decrypt');
930
+ logger.Normal(Language.DecryptSuccess);
931
+ }
932
+ }
933
+ }
934
+ break;
935
+ case "Object": {
936
+ try {
937
+ appState = StateCrypt.decryptState(appState, process.env['FBKEY']);
938
+ logger.Normal(Language.DecryptSuccess);
939
+ }
940
+ catch (e) {
941
+ if (process.env.Backup != undefined && process.env.Backup) {
942
+ await backup(process.env.Backup,globalOptions, callback, prCallback);
943
+ }
944
+ else {
945
+ try {
946
+ if (await Database.has('Backup')) {
947
+ return await backup(await Database.get('Backup'),globalOptions, callback, prCallback);
948
+ }
949
+ else {
950
+ logger.Normal(Language.ErrBackup);
951
+ process.exit(0);
952
+ }
953
+ }
954
+ catch (e) {
955
+ logger.Warning(Language.ErrBackup);
956
+ logger.Error();
957
+ process.exit(0);
958
+ }
959
+ }
960
+ logger.Warning(Language.DecryptFailed);
961
+ return logger.Error();
962
+ }
963
+ }
964
+ break;
965
+ case "String": {
966
+ try {
967
+ appState = StateCrypt.decryptState(appState, process.env['FBKEY']);
968
+ logger.Normal(Language.DecryptSuccess);
969
+ }
970
+ catch (e) {
971
+ if (process.env.Backup != undefined && process.env.Backup) {
972
+ await backup(process.env.Backup,globalOptions, callback, prCallback);
973
+ }
974
+ else {
975
+ try {
976
+ if (await Database.has('Backup')) {
977
+ return await backup(await Database.get('Backup'),globalOptions, callback, prCallback);
978
+ }
979
+ else {
980
+ logger.Normal(Language.ErrBackup);
981
+ process.exit(0);
982
+ }
983
+ }
984
+ catch (e) {
985
+ logger.Warning(Language.ErrBackup);
986
+ logger.Error();
987
+ process.exit(0);
988
+ }
989
+ }
990
+ logger.Warning(Language.DecryptFailed);
991
+ return logger.Error();
992
+ }
993
+ }
994
+ break;
995
+ default: {
996
+ logger.Warning(Language.InvaildAppState);
997
+ process.exit(0)
998
+ }
999
+ }
1000
+ }
1001
+ break;
1002
+ case false: {
1003
+ switch (utils.getType(appState)) {
1004
+ case "Array": {
1005
+ logger.Normal(Language.EncryptStateOff);
1006
+ }
1007
+ break;
1008
+ case "Object": {
1009
+ logger.Normal(Language.EncryptStateOff);
1010
+ try {
1011
+ appState = StateCrypt.decryptState(appState, process.env['FBKEY']);
1012
+ logger.Normal(Language.DecryptSuccess);
1013
+ }
1014
+ catch (e) {
1015
+ if (process.env.Backup != undefined && process.env.Backup) {
1016
+ await backup(process.env.Backup,globalOptions, callback, prCallback);
1017
+ }
1018
+ else {
1019
+ try {
1020
+ if (await Database.has('Backup')) {
1021
+ return await backup(await Database.get('Backup'),globalOptions, callback, prCallback);
1022
+ }
1023
+ else {
1024
+ logger.Warning(Language.ErrBackup);
1025
+ process.exit(0);
1026
+ }
1027
+ }
1028
+ catch (e) {
1029
+ logger.Warning(Language.ErrBackup);
1030
+ logger.Error();
1031
+ process.exit(0);
1032
+ }
1033
+ }
1034
+ logger.Warning(Language.DecryptFailed);
1035
+ return logger.Error();
1036
+ }
1037
+ }
1038
+ break;
1039
+ default: {
1040
+ logger.Warning(Language.InvaildAppState);
1041
+ process.exit(0)
1042
+ }
1043
+ }
1044
+ }
1045
+ break;
1046
+ default: {
1047
+ logger.Warning(getText(Language.IsNotABoolean,global.Fca.Require.FastConfig.EncryptFeature))
1048
+ process.exit(0);
1049
+ }
1050
+ }
1051
+ }
1052
+ catch (e) {
1053
+ console.log(e);
1054
+ }
1055
+
1056
+ try {
1057
+ appState = JSON.parse(appState);
1058
+ }
1059
+ catch (e) {
1060
+ try {
1061
+ appState = appState;
1062
+ }
1063
+ catch (e) {
1064
+ return logger.Error();
1065
+ }
1066
+ }
1067
+ try {
1068
+ global.Fca.Data.AppState = appState;
1069
+ appState.map(function(/** @type {{ key: string; value: string; expires: string; domain: string; path: string; }} */c) {
1070
+ var str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";";
1071
+ jar.setCookie(str, "http://" + c.domain);
1072
+ });
1073
+ process.env.Backup = appState;
1074
+ await Database.set('Backup', appState);
1075
+ mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
1076
+ } catch (e) {
1077
+ console.log(e)
1078
+ if (process.env.Backup != undefined && process.env.Backup) {
1079
+ return await backup(process.env.Backup,globalOptions, callback, prCallback);
1080
+ }
1081
+ try {
1082
+ if (await Database.has('Backup')) {
1083
+ return await backup(await Database.get('Backup'),globalOptions, callback, prCallback);
1084
+ }
1085
+ else {
1086
+ logger.Warning(Language.ErrBackup);
1087
+ process.exit(0);
1088
+ }
1089
+ }
1090
+ catch (e) {
1091
+ logger.Warning(Language.ErrBackup);
1092
+ process.exit(0);
1093
+ }
1094
+ return logger.Warning(Language.ErrBackup); // unreachable 👑
1095
+ }
1096
+ } else {
1097
+ mainPromise = utils
1098
+ .get("https://www.facebook.com/", null, null, globalOptions, { noRef: true })
1099
+ .then(utils.saveCookies(jar))
1100
+ .then(makeLogin(jar, email, password, globalOptions, callback, prCallback))
1101
+ .then(function() {
1102
+ return utils.get('https://www.facebook.com/', jar, null, globalOptions).then(utils.saveCookies(jar));
1103
+ });
1104
+ }
1105
+ } catch (e) {
1106
+ console.log(e);
1107
+ }
1108
+ var ctx,api;
1109
+ mainPromise = mainPromise
1110
+ .then(function(/** @type {{ body: string; }} */res) {
1111
+ var reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/,redirect = reg.exec(res.body);
1112
+ if (redirect && redirect[1]) return utils.get(redirect[1], jar, null, globalOptions).then(utils.saveCookies(jar));
1113
+ return res;
1114
+ })
1115
+ .then(function(/** @type {{ body: any; }} */res) {
1116
+ var html = res.body,Obj = buildAPI(globalOptions, html, jar);
1117
+ ctx = Obj.ctx;
1118
+ api = Obj.api;
1119
+ process.env.api = Obj.api;
1120
+ return res;
1121
+ });
1122
+ if (globalOptions.pageID) {
1123
+ mainPromise = mainPromise
1124
+ .then(function() {
1125
+ return utils.get('https://www.facebook.com/' + ctx.globalOptions.pageID + '/messages/?section=messages&subsection=inbox', ctx.jar, null, globalOptions);
1126
+ })
1127
+ .then(function(/** @type {{ body: any; }} */resData) {
1128
+ var url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
1129
+ url = url.substring(0, url.length - 1);
1130
+ return utils.get('https://www.facebook.com' + url, ctx.jar, null, globalOptions);
1131
+ });
1132
+ }
1133
+ mainPromise
1134
+ .then(function() {
1135
+ const { execSync } = require('child_process');
1136
+ Fetch('https://raw.githubusercontent.com/corazoncary/Fca-ATF/main/package.json').then(async (/** @type {{ body: { toString: () => string; }; }} */res) => {
1137
+ const localVersion = global.Fca.Version;
1138
+ if (Number(localVersion.replace(/\./g,"")) < Number(JSON.parse(res.body.toString()).version.replace(/\./g,"")) ) {
1139
+ log.warn("[ FCA-ATF ] •",getText(Language.NewVersionFound,global.Fca.Version,JSON.parse(res.body.toString()).version));
1140
+ if (global.Fca.Require.FastConfig.AutoUpdate == true) {
1141
+ log.warn("[ FCA-ATF ] •",Language.AutoUpdate);
1142
+ try {
1143
+ execSync('npm install team.atf@latest', { stdio: 'inherit' });
1144
+ logger.Success(Language.UpdateSuccess)
1145
+ logger.Normal(Language.RestartAfterUpdate);
1146
+ await new Promise(resolve => setTimeout(resolve,5*1000));
1147
+ console.clear();process.exit(1);
1148
+ }
1149
+ catch (err) {
1150
+ log.warn('Error Update: ' + err);
1151
+ logger.Normal(Language.UpdateFailed);
1152
+ try {
1153
+ const fs = require('fs-extra')
1154
+ try {
1155
+ logger.Error('Update has failed, proceed with deleting package.');
1156
+ execSync('npm cache clean --force', { stdio: 'ignore'})
1157
+ await new Promise(resolve => setTimeout(resolve, 2*1000))
1158
+ fs.removeSync('../team.atf');
1159
+ // why stdio is not studio :v
1160
+ await new Promise(resolve => setTimeout(resolve, 2*1000))
1161
+ execSync('npm i team.atf@latest', { stdio: 'inherit'})
1162
+ logger.Success("Successful - Restarting");
1163
+ process.exit(1);
1164
+ }
1165
+ catch (e) {
1166
+ logger.Warning("Error occurred. Please enter the following code into the console to fix it!");
1167
+ logger.Warning("rmdir -rf ./node_modules/team.atf && npm i team.atf@latest && npm start");
1168
+ logger.Warning("Please Copy All The Words Above, You Need to Accurately Do It 100%, Otherwise Your File Will Disappear.✨")
1169
+ process.exit(0);
1170
+ }
1171
+ }
1172
+ catch (e) {
1173
+ logger.Error(Language.NotiAfterUseToolFail)
1174
+ logger.Warning("rmdir ./node_modules after type npm i && npm start");
1175
+ process.exit(0);
1176
+ }
1177
+ }
1178
+ }
1179
+ }
1180
+ else {
1181
+ logger.Normal(getText(Language.LocalVersion,localVersion));
1182
+ logger.Normal(getText(Language.CountTime,global.Fca.Data.CountTime()))
1183
+ logger.Normal(Language.WishMessage[Math.floor(Math.random()*Language.WishMessage.length)]);
1184
+ require('./Extra/ExtraUptimeRobot')();
1185
+ DataLanguageSetting.HTML.HTML==true? global.Fca.Require.Web.listen(global.Fca.Require.Web.get('DFP')) : global.Fca.Require.Web = null;
1186
+ callback(null, api);
1187
+ };
1188
+ }).catch(async function(e) {
1189
+ console.log(e)
1190
+ logger.Warning(Language.AutoCheckUpdateFailure)
1191
+ logger.Normal(getText(Language.LocalVersion,global.Fca.Version));
1192
+ logger.Normal(getText(Language.CountTime,global.Fca.Data.CountTime()))
1193
+ logger.Normal(Language.WishMessage[Math.floor(Math.random()*Language.WishMessage.length)]);
1194
+ require('./Extra/ExtraUptimeRobot')();
1195
+ DataLanguageSetting.HTML.HTML==true? global.Fca.Require.Web.listen(global.Fca.Require.Web.get('DFP')) : global.Fca.Require.Web = null;
1196
+ callback(null, api);
1197
+ });
1198
+ }).catch(function(/** @type {{ error: any; }} */e) {
1199
+ log.error("login", e.error || e);
1200
+ callback(e);
1201
+ });
1202
+ }
1203
+
1204
+ /**
1205
+ * It asks the user for their account and password, and then saves it to the database.
1206
+ */
1207
+
1208
+ function setUserNameAndPassWord() {
1209
+ let rl = readline.createInterface({
1210
+ input: process.stdin,
1211
+ output: process.stdout
1212
+ });
1213
+ let localbrand2 = global.Fca.Version
1214
+ console.clear();
1215
+ console.log(figlet.textSync('CHAND', {font: 'ANSI Shadow',horizontalLayout: 'default',verticalLayout: 'default',width: 0,whitespaceBreak: true }));
1216
+ console.log(chalk.bold.hex('#9900FF')("[</>]") + chalk.bold.yellow(' => ') + "Operating System: " + chalk.bold.red(os.type()));
1217
+ console.log(chalk.bold.hex('#9900FF')("[</>]") + chalk.bold.yellow(' => ') + "Machine Version: " + chalk.bold.red(os.version()));
1218
+ console.log(chalk.bold.hex('#9900FF')("[</>]") + chalk.bold.yellow(' => ') + "Fca Version: " + chalk.bold.red(localbrand2) + '\n');
1219
+ try {
1220
+ rl.question(Language.TypeAccount, (Account) => {
1221
+ if (!Account.includes("@") && global.Fca.Require.utils.getType(parseInt(Account)) != "Number") return logger.Normal(Language.TypeAccountError, function () { process.exit(1) }); //Very Human
1222
+ else rl.question(Language.TypePassword,async function (Password) {
1223
+ rl.close();
1224
+ try {
1225
+ await Database.set("Account", Account);
1226
+ await Database.set("Password", Password);
1227
+ }
1228
+ catch (e) {
1229
+ logger.Warning(Language.ErrDataBase);
1230
+ logger.Error();
1231
+ process.exit(0);
1232
+ }
1233
+ if (global.Fca.Require.FastConfig.ResetDataLogin) {
1234
+ global.Fca.Require.FastConfig.ResetDataLogin = false;
1235
+ global.Fca.Require.fs.writeFileSync(process.cwd() + '/ATF.Config.json', JSON.stringify(global.Fca.Require.FastConfig, null, 4));
1236
+ }
1237
+ logger.Success(Language.SuccessSetData);
1238
+ process.exit(1);
1239
+ });
1240
+ })
1241
+ }
1242
+ catch (e) {
1243
+ logger.Error(e)
1244
+ }
1245
+ }
1246
+
1247
+ /**
1248
+ * @param {{ email: any; password: any; appState: any; }} loginData
1249
+ * @param {{}} options
1250
+ * @param {(error: any, api: any) => any} callback
1251
+ */
1252
+
1253
+ function login(loginData, options, callback) {
1254
+
1255
+ if (utils.getType(loginData) == "Array") {
1256
+ if (loginData.length == 3) {
1257
+ options = loginData[1];
1258
+ callback = loginData[2];
1259
+ loginData = loginData[0]
1260
+ }
1261
+ else if (loginData.length == 2) {
1262
+ options = loginData[1];
1263
+ loginData = loginData[0]
1264
+ }
1265
+ else {
1266
+ loginData = loginData[0]
1267
+ }
1268
+ }
1269
+
1270
+ if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
1271
+ callback = options;
1272
+ options = {};
1273
+ }
1274
+
1275
+ var globalOptions = {
1276
+ selfListen: true,
1277
+ listenEvents: true,
1278
+ listenTyping: true,
1279
+ updatePresence: false,
1280
+ forceLogin: false,
1281
+ autoMarkDelivery: true,
1282
+ autoMarkRead: true,
1283
+ autoReconnect: true,
1284
+ logRecordSize: 100,
1285
+ online: true,
1286
+ emitReady: false,
1287
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8"
1288
+ };
1289
+
1290
+ if (loginData.email && loginData.password) {
1291
+ setOptions(globalOptions, {
1292
+ logLevel: "silent",
1293
+ forceLogin: true,
1294
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36"
1295
+ });
1296
+ }
1297
+ else if (loginData.appState) {
1298
+ setOptions(globalOptions, options);
1299
+ }
1300
+
1301
+ var prCallback = null;
1302
+ if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
1303
+ var rejectFunc = null;
1304
+ var resolveFunc = null;
1305
+ var returnPromise = new Promise(function(resolve, reject) {
1306
+ resolveFunc = resolve;
1307
+ rejectFunc = reject;
1308
+ });
1309
+ prCallback = function(/** @type {any} */error, /** @type {any} */api) {
1310
+ if (error) return rejectFunc(error);
1311
+ return resolveFunc(api);
1312
+ };
1313
+ callback = prCallback;
1314
+ }
1315
+
1316
+ (async function() {
1317
+ var Premium = require("./Extra/Src/Premium");
1318
+ global.Fca.Data.PremText = await Premium(global.Fca.Require.Security.create().uuid) || "Bạn Đang Sài Phiên Bản: Free !";
1319
+ if (!loginData.email && !loginData.password) {
1320
+ switch (global.Fca.Require.FastConfig.AutoLogin) {
1321
+ case true: {
1322
+ if (global.Fca.Require.FastConfig.ResetDataLogin) return setUserNameAndPassWord();
1323
+ else {
1324
+ try {
1325
+ if (await Database.get("TempState")) {
1326
+ try {
1327
+ loginData.appState = JSON.parse(await Database.get("TempState"));
1328
+ }
1329
+ catch (_) {
1330
+ loginData.appState = await Database.get("TempState");
1331
+ }
1332
+ await Database.delete("TempState");
1333
+ }
1334
+ }
1335
+ catch (e) {
1336
+ console.log(e)
1337
+ await Database.delete("TempState");
1338
+ logger.Warning(Language.ErrDataBase);
1339
+ logger.Error();
1340
+ process.exit(0);
1341
+ }
1342
+ try {
1343
+ if (await Database.has('Account') && await Database.has('Password')) return loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
1344
+ else return setUserNameAndPassWord();
1345
+ }
1346
+ catch (e) {
1347
+ console.log(e)
1348
+ logger.Warning(Language.ErrDataBase);
1349
+ logger.Error();
1350
+ process.exit(0);
1351
+ }
1352
+ }
1353
+ }
1354
+ case false: {
1355
+ loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
1356
+ }
1357
+ }
1358
+ }
1359
+ else loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
1360
+ })()
1361
+ return returnPromise;
1362
+ }
1363
+
1364
+ module.exports = login;