fca-kemcute 30.8.9

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.

Potentially problematic release.


This version of fca-kemcute might be problematic. Click here for more details.

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