fca-rqzax-remake 0.0.1-security → 4.1.0

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

Potentially problematic release.


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

Files changed (87) hide show
  1. package/.breakpoints +58 -0
  2. package/.cache/replit/__replit_disk_meta.json +1 -0
  3. package/.cache/replit/modules.stamp +1 -0
  4. package/.cache/replit/nix/env.json +1 -0
  5. package/.gitattributes +2 -0
  6. package/.replit +1 -0
  7. package/.travis.yml +6 -0
  8. package/.upm/store.json +1 -0
  9. package/CHANGELOG.md +2 -0
  10. package/DOCS.md +1738 -0
  11. package/GetThreads/GetThreadInfo.js +118 -0
  12. package/LICENSE-MIT +21 -0
  13. package/README.md +126 -3
  14. package/StateCrypt.js +28 -0
  15. package/broadcast.js +1 -0
  16. package/index.js +685 -0
  17. package/languages/index.json +150 -0
  18. package/lib/getInfoNew.js +34 -0
  19. package/lib/getToken.js +44 -0
  20. package/logger.js +24 -0
  21. package/package.json +133 -3
  22. package/replit.nix +9 -0
  23. package/src/ReportV1.js +55 -0
  24. package/src/addExternalModule.js +16 -0
  25. package/src/addUserToGroup.js +78 -0
  26. package/src/changeAdminStatus.js +79 -0
  27. package/src/changeArchivedStatus.js +41 -0
  28. package/src/changeAvt.js +86 -0
  29. package/src/changeBio.js +65 -0
  30. package/src/changeBlockedStatus.js +36 -0
  31. package/src/changeGroupImage.js +106 -0
  32. package/src/changeNickname.js +45 -0
  33. package/src/changeThreadColor.js +62 -0
  34. package/src/changeThreadEmoji.js +42 -0
  35. package/src/createNewGroup.js +70 -0
  36. package/src/createPoll.js +60 -0
  37. package/src/data/getThreadInfo.json +25094 -0
  38. package/src/deleteMessage.js +45 -0
  39. package/src/deleteThread.js +43 -0
  40. package/src/forwardAttachment.js +48 -0
  41. package/src/getAccessToken.js +33 -0
  42. package/src/getCurrentUserID.js +7 -0
  43. package/src/getEmojiUrl.js +27 -0
  44. package/src/getFriendsList.js +73 -0
  45. package/src/getMessage.js +80 -0
  46. package/src/getThreadHistory.js +537 -0
  47. package/src/getThreadHistoryDeprecated.js +71 -0
  48. package/src/getThreadInfo.js +193 -0
  49. package/src/getThreadInfoDeprecated.js +56 -0
  50. package/src/getThreadList.js +213 -0
  51. package/src/getThreadListDeprecated.js +46 -0
  52. package/src/getThreadMain.js +219 -0
  53. package/src/getThreadPictures.js +59 -0
  54. package/src/getUserID.js +62 -0
  55. package/src/getUserInfo.js +66 -0
  56. package/src/getUserInfoMain.js +65 -0
  57. package/src/getUserInfoV2.js +36 -0
  58. package/src/getUserInfoV3.js +63 -0
  59. package/src/getUserInfoV4.js +55 -0
  60. package/src/getUserInfoV5.js +61 -0
  61. package/src/handleFriendRequest.js +46 -0
  62. package/src/handleMessageRequest.js +49 -0
  63. package/src/httpGet.js +49 -0
  64. package/src/httpPost.js +48 -0
  65. package/src/httpPostFormData.js +41 -0
  66. package/src/listenMqtt.js +629 -0
  67. package/src/logout.js +68 -0
  68. package/src/markAsDelivered.js +48 -0
  69. package/src/markAsRead.js +70 -0
  70. package/src/markAsReadAll.js +43 -0
  71. package/src/markAsSeen.js +51 -0
  72. package/src/muteThread.js +47 -0
  73. package/src/removeUserFromGroup.js +49 -0
  74. package/src/resolvePhotoUrl.js +37 -0
  75. package/src/searchForThread.js +43 -0
  76. package/src/sendMessage.js +321 -0
  77. package/src/sendTypingIndicator.js +80 -0
  78. package/src/setMessageReaction.js +109 -0
  79. package/src/setPostReaction.js +102 -0
  80. package/src/setTitle.js +74 -0
  81. package/src/threadColors.js +39 -0
  82. package/src/unfriend.js +43 -0
  83. package/src/unsendMessage.js +40 -0
  84. package/test/example-config.json +18 -0
  85. package/test/test-page.js +140 -0
  86. package/test/test.js +385 -0
  87. package/utils.js +1246 -0
package/index.js ADDED
@@ -0,0 +1,685 @@
1
+ 'use strict';
2
+
3
+ var utils = require("./utils");
4
+ var cheerio = require("cheerio");
5
+ var log = require("npmlog");
6
+ var logger = require('./logger');
7
+ var fs = require("fs-extra");
8
+ var axios = require('axios')
9
+ if (!fs.existsSync("./Kaiser_Config.json")) {
10
+ log.warn("warn", "Không Tìm Thấy Tệp FcaConfig Tiến Hành Tạo Mới")
11
+ global.fca = new Object ({
12
+ data: new Object ({
13
+ languages: "vi",
14
+ mainName: "[ FCA ]",
15
+ autoRestartMinutes: 0,
16
+ encryptSt: false,
17
+ uptime: true
18
+ })
19
+ })
20
+ fs.writeFileSync("./RqzaX_Config.json", JSON.stringify(global.fca.data, null, "\t"))
21
+ return process.exit(1)
22
+ }
23
+ try {
24
+ var langfile = JSON.parse(fs.readFileSync(__dirname + "/languages/index.json", 'utf-8'));
25
+ var lang
26
+ switch (require("../../RqzaX_Config.json").languages) {
27
+ case "vi": lang = langfile.vi.index;
28
+ break;
29
+ case "en": lang = langfile.en.index;
30
+ break;
31
+ case "th": lang = langfile.th.index;
32
+ break;
33
+ case "jp": lang = langfile.jp.index;
34
+ break;
35
+ default: {
36
+ log.warn("warn", "Hiện Chỉ Hỗ Trợ 4 Loại Ngôn Ngữ VI, EN, TH & JP, Tự Fix Bằng Cách Tìm Và Xoá Tệp RqzaX_Config.json")
37
+ process.exit(0)
38
+ }
39
+ }
40
+ } catch(e) {
41
+ console.log(e)
42
+ log.warn("warn", "Không tìm thấy ngôn ngữ phù hợp")
43
+ process.exit(0)
44
+ }
45
+ global.fca = new Object({
46
+ ObjFcaConfig: require("../../RqzaX_Config.json"),
47
+ languages: lang
48
+ })
49
+ if (global.fca.ObjFcaConfig['autoRestartMinutes'] != 0) {
50
+ setInterval(() => {
51
+ return process.exit(1)
52
+ }, global.fca.ObjFcaConfig['autoRestartMinutes'] * 1000)
53
+ }
54
+ if (global.fca.ObjFcaConfig['uptime']) {
55
+ var UrlRepl = `https://${process.env.REPL_SLUG}.${process.env.REPL_OWNER}.repl.co`;
56
+ try {
57
+ axios.get(`https://Sever-Uptime.abcdz1238.repl.co?add=${UrlRepl}`)
58
+ logger(global.fca.languages.uptime + UrlRepl, '[ FCA ]');
59
+ }
60
+ catch {
61
+ logger(global.fca.languages.erroUptime, '[ FCA ]');
62
+ }
63
+ }
64
+ var checkVerified = null;
65
+
66
+ var defaultLogRecordSize = 100;
67
+ log.maxRecordSize = defaultLogRecordSize;
68
+ function setOptions(globalOptions, options) {
69
+ Object.keys(options).map(function(key) {
70
+ switch (key) {
71
+ case 'pauseLog':
72
+ if (options.pauseLog) log.pause();
73
+ break;
74
+ case 'online':
75
+ globalOptions.online = Boolean(options.online);
76
+ break;
77
+ case 'logLevel':
78
+ log.level = options.logLevel;
79
+ globalOptions.logLevel = options.logLevel;
80
+ break;
81
+ case 'logRecordSize':
82
+ log.maxRecordSize = options.logRecordSize;
83
+ globalOptions.logRecordSize = options.logRecordSize;
84
+ break;
85
+ case 'selfListen':
86
+ globalOptions.selfListen = Boolean(options.selfListen);
87
+ break;
88
+ case 'listenEvents':
89
+ globalOptions.listenEvents = Boolean(options.listenEvents);
90
+ break;
91
+ case 'pageID':
92
+ globalOptions.pageID = options.pageID.toString();
93
+ break;
94
+ case 'updatePresence':
95
+ globalOptions.updatePresence = Boolean(options.updatePresence);
96
+ break;
97
+ case 'forceLogin':
98
+ globalOptions.forceLogin = Boolean(options.forceLogin);
99
+ break;
100
+ case 'userAgent':
101
+ globalOptions.userAgent = options.userAgent;
102
+ break;
103
+ case 'autoMarkDelivery':
104
+ globalOptions.autoMarkDelivery = Boolean(options.autoMarkDelivery);
105
+ break;
106
+ case 'autoMarkRead':
107
+ globalOptions.autoMarkRead = Boolean(options.autoMarkRead);
108
+ break;
109
+ case 'listenTyping':
110
+ globalOptions.listenTyping = Boolean(options.listenTyping);
111
+ break;
112
+ case 'proxy':
113
+ if (typeof options.proxy != "string") {
114
+ delete globalOptions.proxy;
115
+ utils.setProxy();
116
+ } else {
117
+ globalOptions.proxy = options.proxy;
118
+ utils.setProxy(globalOptions.proxy);
119
+ }
120
+ break;
121
+ case 'autoReconnect':
122
+ globalOptions.autoReconnect = Boolean(options.autoReconnect);
123
+ break;
124
+ case 'emitReady':
125
+ globalOptions.emitReady = Boolean(options.emitReady);
126
+ break;
127
+ default:
128
+ log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
129
+ break;
130
+ }
131
+ });
132
+ }
133
+ function buildAPI(globalOptions, html, jar) {
134
+ var maybeCookie = jar.getCookies("https://www.facebook.com").filter(function(val) {
135
+ return val.cookieString().split("=")[0] === "c_user";
136
+ });
137
+
138
+ if (maybeCookie.length === 0) throw { error: global.fca.languages.errorLogin };
139
+
140
+ if (html.indexOf("/checkpoint/block/?next") > -1) log.warn("login", global.fca.languages.checkpoint);
141
+
142
+ var userID = maybeCookie[0].cookieString().split("=")[1].toString();
143
+ console.log(chalk.bold.hex(randomColor()).bold(`${global.fca.languages.loginSu}${userID}`, "[ FCA - KAISER ]"));
144
+
145
+ try {
146
+ clearInterval(checkVerified);
147
+ } catch (e) {
148
+ console.log(e);
149
+ }
150
+
151
+ var clientID = (Math.random() * 2147483648 | 0).toString(16);
152
+
153
+ let oldFBMQTTMatch = html.match(/irisSeqID:"(.+?)",appID:219994525426954,endpoint:"(.+?)"/);
154
+ let mqttEndpoint = null;
155
+ let region = null;
156
+ let irisSeqID = null;
157
+ var noMqttData = null;
158
+
159
+ if (oldFBMQTTMatch) {
160
+ irisSeqID = oldFBMQTTMatch[1];
161
+ mqttEndpoint = oldFBMQTTMatch[2];
162
+ region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
163
+ console.log(chalk.bold.hex(randomColor()).bold(`${global.fca.languages.region}${region}`, "[ FCA - KAISER ]"));
164
+ } else {
165
+ let newFBMQTTMatch = html.match(/{"app_id":"219994525426954","endpoint":"(.+?)","iris_seq_id":"(.+?)"}/);
166
+ if (newFBMQTTMatch) {
167
+ irisSeqID = newFBMQTTMatch[2];
168
+ mqttEndpoint = newFBMQTTMatch[1].replace(/\\\//g, "/");
169
+ region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
170
+ console.log(chalk.bold.hex(randomColor()).bold(`${global.fca.languages.region}${region}`, "[ FCA - KAISER ]"));
171
+ } else {
172
+ let legacyFBMQTTMatch = html.match(/(\["MqttWebConfig",\[\],{fbid:")(.+?)(",appID:219994525426954,endpoint:")(.+?)(",pollingEndpoint:")(.+?)(3790])/);
173
+ if (legacyFBMQTTMatch) {
174
+ mqttEndpoint = legacyFBMQTTMatch[4];
175
+ region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
176
+ log.warn("login", `Cannot get sequence ID with new RegExp. Fallback to old RegExp (without seqID)...`);
177
+ console.log(chalk.bold.hex(randomColor()).bold(`${global.fca.languages.region}${region}`, "[ FCA ]"));
178
+ console.log(chalk.bold.hex(randomColor()).bold("login", `[ Unused ] Polling endpoint: ${legacyFBMQTTMatch[6]}`));
179
+ } else {
180
+ log.warn("login", global.fca.languages.errorUid);
181
+ noMqttData = html;
182
+ }
183
+ }
184
+ }
185
+ // All data available to api functions
186
+ var ctx = {
187
+ userID: userID,
188
+ jar: jar,
189
+ clientID: clientID,
190
+ globalOptions: globalOptions,
191
+ loggedIn: true,
192
+ access_token: 'NONE',
193
+ clientMutationId: 0,
194
+ mqttClient: undefined,
195
+ lastSeqId: irisSeqID,
196
+ syncToken: undefined,
197
+ mqttEndpoint,
198
+ region,
199
+ firstListen: true
200
+ };
201
+ var api = {
202
+ setOptions: setOptions.bind(null, globalOptions),
203
+ getAppState: function getAppState() {
204
+ return utils.getAppState(jar);
205
+ }
206
+ };
207
+ if (noMqttData) api["htmlData"] = noMqttData;
208
+ const apiFuncNames = [
209
+ 'addExternalModule',
210
+ 'addUserToGroup',
211
+ 'changeAdminStatus',
212
+ 'changeArchivedStatus',
213
+ 'changeAvt',
214
+ 'changeBio',
215
+ 'changeBlockedStatus',
216
+ 'changeGroupImage',
217
+ 'changeNickname',
218
+ 'changeThreadColor',
219
+ 'changeThreadEmoji',
220
+ 'createNewGroup',
221
+ 'createPoll',
222
+ 'deleteMessage',
223
+ 'deleteThread',
224
+ 'forwardAttachment',
225
+ 'getAccessToken',
226
+ 'getCurrentUserID',
227
+ 'getEmojiUrl',
228
+ 'getFriendsList',
229
+ 'getThreadHistory',
230
+ 'getThreadInfo',
231
+ 'getThreadList',
232
+ 'getThreadPictures',
233
+ 'getUserID',
234
+ 'getUserInfo',
235
+ 'getUserInfoV2',
236
+ 'getUserInfoV3',
237
+ 'getUserInfoV4',
238
+ 'getUserInfoV5',
239
+ 'handleMessageRequest',
240
+ 'listenMqtt',
241
+ 'logout',
242
+ 'markAsDelivered',
243
+ 'markAsRead',
244
+ 'markAsReadAll',
245
+ 'markAsSeen',
246
+ 'muteThread',
247
+ 'removeUserFromGroup',
248
+ 'resolvePhotoUrl',
249
+ 'ReportV1',
250
+ 'searchForThread',
251
+ 'sendMessage',
252
+ 'sendTypingIndicator',
253
+ 'setMessageReaction',
254
+ 'setTitle',
255
+ 'threadColors',
256
+ 'unsendMessage',
257
+ 'unfriend',
258
+ 'setPostReaction',
259
+ // HTTP
260
+ 'httpGet',
261
+ 'httpPost',
262
+ 'httpPostFormData',
263
+ // Deprecated features
264
+ "getThreadListDeprecated",
265
+ 'getThreadHistoryDeprecated',
266
+ 'getThreadInfoDeprecated'
267
+ ];
268
+ var defaultFuncs = utils.makeDefaults(html, userID, ctx);
269
+
270
+ // Load all api functions in a loop
271
+ apiFuncNames.map(v => api[v] = require('./src/' + v)(defaultFuncs, api, ctx));
272
+
273
+ return [ctx, defaultFuncs, api];
274
+ }
275
+ function makeLogin(jar, email, password, loginOptions, callback, prCallback) {
276
+ return function(res) {
277
+ var html = res.body;
278
+ var $ = cheerio.load(html);
279
+ var arr = [];
280
+
281
+ // This will be empty, but just to be sure we leave it
282
+ $("#login_form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
283
+
284
+ arr = arr.filter(function(v) {
285
+ return v.val && v.val.length;
286
+ });
287
+ var form = utils.arrToForm(arr);
288
+ form.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
289
+ form.lgndim = Buffer.from("{\"w\":1440,\"h\":900,\"aw\":1440,\"ah\":834,\"c\":24}").toString('base64');
290
+ form.email = email;
291
+ form.pass = password;
292
+ form.default_persistent = '0';
293
+ form.lgnrnd = utils.getFrom(html, "name=\"lgnrnd\" value=\"", "\"");
294
+ form.locale = 'en_US';
295
+ form.timezone = '240';
296
+ form.lgnjs = ~~(Date.now() / 1000);
297
+ // Getting cookies from the HTML page... (kill me now plz)
298
+ // we used to get a bunch of cookies in the headers of the response of the
299
+ // request, but FB changed and they now send those cookies inside the JS.
300
+ // They run the JS which then injects the cookies in the page.
301
+ // The "solution" is to parse through the html and find those cookies
302
+ // which happen to be conveniently indicated with a _js_ in front of their
303
+ // variable name.
304
+ //
305
+ // ---------- Very Hacky Part Starts -----------------
306
+ var willBeCookies = html.split("\"_js_");
307
+ willBeCookies.slice(1).map(function(val) {
308
+ var cookieData = JSON.parse("[\"" + utils.getFrom(val, "", "]") + "]");
309
+ jar.setCookie(utils.formatCookie(cookieData, "facebook"), "https://www.facebook.com");
310
+ });
311
+ // ---------- Very Hacky Part Ends -----------------
312
+ logger(global.fca.languages.login, "[ FCA - KAISER ]");
313
+ return utils
314
+ .post("https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110", jar, form, loginOptions)
315
+ .then(utils.saveCookies(jar))
316
+ .then(function(res) {
317
+ var headers = res.headers;
318
+ if (!headers.location) throw { error: global.fca.languages.loginError };
319
+
320
+ // This means the account has login approvals turned on.
321
+ if (headers.location.indexOf('https://www.facebook.com/checkpoint/') > -1) {
322
+ logger(global.fca.languages.errorFa, "[ FCA - KAISER ]");
323
+ var nextURL = 'https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php';
324
+
325
+ return utils
326
+ .get(headers.location, jar, null, loginOptions)
327
+ .then(utils.saveCookies(jar))
328
+ .then(function(res) {
329
+ var html = res.body;
330
+ // Make the form in advance which will contain the fb_dtsg and nh
331
+ var $ = cheerio.load(html);
332
+ var arr = [];
333
+ $("form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
334
+
335
+ arr = arr.filter(function(v) {
336
+ return v.val && v.val.length;
337
+ });
338
+
339
+ var form = utils.arrToForm(arr);
340
+ if (html.indexOf("checkpoint/?next") > -1) {
341
+ setTimeout(() => {
342
+ checkVerified = setInterval((_form) => {}, 5000, {
343
+ fb_dtsg: form.fb_dtsg,
344
+ jazoest: form.jazoest,
345
+ dpr: 1
346
+ });
347
+ }, 2500);
348
+ throw {
349
+ error: 'login-approval',
350
+ continue: function submit2FA(code) {
351
+ form.approvals_code = code;
352
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html(); //'Continue';
353
+ var prResolve = null;
354
+ var prReject = null;
355
+ var rtPromise = new Promise(function(resolve, reject) {
356
+ prResolve = resolve;
357
+ prReject = reject;
358
+ });
359
+ if (typeof code == "string") {
360
+ utils
361
+ .post(nextURL, jar, form, loginOptions)
362
+ .then(utils.saveCookies(jar))
363
+ .then(function(res) {
364
+ var $ = cheerio.load(res.body);
365
+ var error = $("#approvals_code").parent().attr("data-xui-error");
366
+ if (error) {
367
+ throw {
368
+ error: 'login-approval',
369
+ errordesc: "Invalid 2FA code.",
370
+ lerror: error,
371
+ continue: submit2FA
372
+ };
373
+ }
374
+ })
375
+ .then(function() {
376
+ // Use the same form (safe I hope)
377
+ delete form.no_fido;
378
+ delete form.approvals_code;
379
+ form.name_action_selected = 'dont_save'; //'save_device';
380
+
381
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
382
+ })
383
+ .then(function(res) {
384
+ var headers = res.headers;
385
+ if (!headers.location && res.body.indexOf('Review Recent Login') > -1) throw { error: "Something went wrong with login approvals." };
386
+
387
+ var appState = utils.getAppState(jar);
388
+
389
+ if (callback === prCallback) {
390
+ callback = function(err, api) {
391
+ if (err) return prReject(err);
392
+ return prResolve(api);
393
+ };
394
+ }
395
+
396
+ // Simply call loginHelper because all it needs is the jar
397
+ // and will then complete the login process
398
+ return loginHelper(appState, email, password, loginOptions, callback);
399
+ })
400
+ .catch(function(err) {
401
+ // Check if using Promise instead of callback
402
+ if (callback === prCallback) prReject(err);
403
+ else callback(err);
404
+ });
405
+ } else {
406
+ utils
407
+ .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" })
408
+ .then(utils.saveCookies(jar))
409
+ .then(res => {
410
+ try {
411
+ JSON.parse(res.body.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, ""));
412
+ } catch (ex) {
413
+ clearInterval(checkVerified);
414
+ logger(global.fca.languages.okweb, "[ FCA - KAISER ]");
415
+ if (callback === prCallback) {
416
+ callback = function(err, api) {
417
+ if (err) return prReject(err);
418
+ return prResolve(api);
419
+ };
420
+ }
421
+ return loginHelper(utils.getAppState(jar), email, password, loginOptions, callback);
422
+ }
423
+ })
424
+ .catch(ex => {
425
+ log.error("login", ex);
426
+ if (callback === prCallback) prReject(ex);
427
+ else callback(ex);
428
+ });
429
+ }
430
+ return rtPromise;
431
+ }
432
+ };
433
+ } else {
434
+ if (!loginOptions.forceLogin) throw { error: "Couldn't login. Facebook might have blocked this account. Please login with a browser or enable the option 'forceLogin' and try again." };
435
+
436
+ if (html.indexOf("Suspicious Login Attempt") > -1) form['submit[This was me]'] = "This was me";
437
+ else form['submit[This Is Okay]'] = "This Is Okay";
438
+
439
+ return utils
440
+ .post(nextURL, jar, form, loginOptions)
441
+ .then(utils.saveCookies(jar))
442
+ .then(function() {
443
+ // Use the same form (safe I hope)
444
+ form.name_action_selected = 'save_device';
445
+
446
+ return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
447
+ })
448
+ .then(function(res) {
449
+ var headers = res.headers;
450
+
451
+ if (!headers.location && res.body.indexOf('Review Recent Login') > -1) throw { error: "Something went wrong with review recent login." };
452
+
453
+ var appState = utils.getAppState(jar);
454
+
455
+ // Simply call loginHelper because all it needs is the jar
456
+ // and will then complete the login process
457
+ return loginHelper(appState, email, password, loginOptions, callback);
458
+ })
459
+ .catch(e => callback(e));
460
+ }
461
+ });
462
+ }
463
+
464
+ return utils.get('https://www.facebook.com/', jar, null, loginOptions).then(utils.saveCookies(jar));
465
+ });
466
+ };
467
+ }
468
+ function makeid(length) {
469
+ var result = '';
470
+ var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
471
+ var charactersLength = characters.length;
472
+ for ( var i = 0; i < length; i++ ) {
473
+ result += characters.charAt(Math.floor(Math.random() *
474
+ charactersLength));
475
+ }
476
+ return result;
477
+ }
478
+ // Helps the login
479
+ function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
480
+ var mainPromise = null;
481
+ var jar = utils.getJar();
482
+
483
+ // If we're given an appState we loop through it and save each cookie
484
+ // back into the jar.
485
+ try {
486
+ if (appState) {
487
+ if (global.fca.ObjFcaConfig['encryptSt']) {
488
+ try {
489
+ if (fs.existsSync('./../.env')) {
490
+ require('dotenv').config({ path: './../.env' });
491
+ }
492
+ else {
493
+ fs.writeFileSync('./../.env', ``);
494
+ require('dotenv').config({ path: './../.env' });
495
+ }
496
+ }
497
+ catch (e) {
498
+ console.log(e);
499
+ process.exit(1);
500
+ }
501
+ if (!process.env['FBKEY']) {
502
+ try {
503
+ var ans = makeid(49)
504
+ process.env["FBKEY"] = ans;
505
+ fs.writeFile('./../.env', `FBKEY=${ans}`, function (err) {
506
+ if (err) {
507
+ console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.errorEnv, "[ FCA ]"));
508
+ }
509
+ else console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.env,"[ FCA ]"))
510
+ });
511
+ }
512
+ catch (e) {
513
+ console.log(e);
514
+ console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.errorPassRandom, "[ FCA ]"));
515
+ }
516
+ }
517
+
518
+ if (process.env['FBKEY']) {
519
+ try {
520
+ appState = JSON.stringify(appState);
521
+ if (appState.includes('[')) {
522
+ console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.appstateDec, '[ FCA ]'));
523
+ } else {
524
+ try {
525
+ appState = JSON.parse(appState);
526
+ var StateCrypt = require('./StateCrypt');
527
+ appState = StateCrypt.decryptState(appState, process.env['FBKEY']);
528
+ console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.appstate, '[ FCA ]'));
529
+ }
530
+ catch (e) {
531
+ console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.appstateError, '[ FCA ]'));
532
+ }
533
+ }
534
+ }
535
+ catch (e) {
536
+ console.log(e);
537
+ }
538
+ }
539
+ try {
540
+ appState = JSON.parse(appState);
541
+ }
542
+ catch (e) {
543
+ try {
544
+ appState = appState;
545
+ }
546
+ catch (e) {
547
+ return console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.appstateError, '[ FCA ]'))
548
+ }
549
+ }
550
+ }
551
+ try {
552
+ appState.map(function(c) {
553
+ var str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";";
554
+ jar.setCookie(str, "http://" + c.domain);
555
+ });
556
+
557
+ // Load the main page.
558
+ mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
559
+ } catch (e) {
560
+ return console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.appstateError, '[ FCA ]'))
561
+ }
562
+ } else {
563
+ // Open the main page, then we login with the given credentials and finally
564
+ // load the main page again (it'll give us some IDs that we need)
565
+ mainPromise = utils
566
+ .get("https://www.facebook.com/", null, null, globalOptions, { noRef: true })
567
+ .then(utils.saveCookies(jar))
568
+ .then(makeLogin(jar, email, password, globalOptions, callback, prCallback))
569
+ .then(function() {
570
+ return utils.get('https://www.facebook.com/', jar, null, globalOptions).then(utils.saveCookies(jar));
571
+ });
572
+ }
573
+ } catch (e) {
574
+ console.log(e);
575
+ }
576
+ var ctx = null;
577
+ var _defaultFuncs = null;
578
+ var api = null;
579
+
580
+ mainPromise = mainPromise
581
+ .then(function(res) {
582
+ // Hacky check for the redirection that happens on some ISPs, which doesn't return statusCode 3xx
583
+ var reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
584
+ var redirect = reg.exec(res.body);
585
+ if (redirect && redirect[1]) return utils.get(redirect[1], jar, null, globalOptions).then(utils.saveCookies(jar));
586
+ return res;
587
+ })
588
+ .then(function(res) {
589
+ var html = res.body;
590
+ var stuff = buildAPI(globalOptions, html, jar);
591
+ ctx = stuff[0];
592
+ _defaultFuncs = stuff[1];
593
+ api = stuff[2];
594
+ return res;
595
+ });
596
+
597
+ // given a pageID we log in as a page
598
+ if (globalOptions.pageID) {
599
+ mainPromise = mainPromise
600
+ .then(function() {
601
+ return utils.get('https://www.facebook.com/' + ctx.globalOptions.pageID + '/messages/?section=messages&subsection=inbox', ctx.jar, null, globalOptions);
602
+ })
603
+ .then(function(resData) {
604
+ var url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
605
+ url = url.substring(0, url.length - 1);
606
+ return utils.get('https://www.facebook.com' + url, ctx.jar, null, globalOptions);
607
+ });
608
+ }
609
+ // At the end we call the callback or catch an exception
610
+ mainPromise
611
+ .then(function() {
612
+ logger(global.fca.languages.oklogin, "[ FCA - KAISER ]");
613
+ //!---------- Auto Check, Update START -----------------!//
614
+ var axios = require('axios');
615
+ var { readFileSync } = require('fs-extra');
616
+ const { execSync } = require('child_process');
617
+ axios.get('https://raw.githubusercontent.com/RqzaX040/Fca-Hokai-Remake/main/package.json').then(async (res) => {
618
+ const localbrand = JSON.parse(readFileSync('./node_modules/fca-rqzax-remake/package.json')).version;
619
+ if (localbrand != res.data.version) {
620
+ console.log(chalk.bold.hex(randomColor()).bold("UPDATE > ",`${global.fca.languages.newVersion}${JSON.parse(readFileSync('./node_modules/fca-rqzax-remake/package.json')).version} => ${res.data.version}`));
621
+ console.log(chalk.bold.hex(randomColor()).bold("UPDATE > ",`${global.fca.languages.autoUpdate}`));
622
+ try {
623
+ execSync('npm install fca-rqzax-remake@latest', { stdio: 'inherit' });
624
+ console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.okUpdate,"UPDATE"))
625
+ console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.restart, '[ FCA ]'));
626
+ await new Promise(resolve => setTimeout(resolve,5*1000));
627
+ console.clear();process.exit(1);
628
+ }
629
+ catch (err) {
630
+ log.warn(global.fca.languages.errorUpdate + err);
631
+ }
632
+ }
633
+ else {
634
+ console.log(chalk.bold.hex(randomColor()).bold(`${global.fca.languages.checkVersion}` + localbrand + ' !', "[ FCA ]"));
635
+ console.log(chalk.bold.hex(randomColor()).bold(global.fca.languages.chucAdmin, "[ FCA ]"));
636
+ await new Promise(resolve => setTimeout(resolve, 3*1000));
637
+ callback(null, api);
638
+ }
639
+ });
640
+ }).catch(function(e) {
641
+ log.error("login", e.error || e);
642
+ callback(e);
643
+ });
644
+ //!---------- Auto Check, Update END -----------------!//
645
+ }
646
+ function login(loginData, options, callback) {
647
+ if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
648
+ callback = options;
649
+ options = {};
650
+ }
651
+ var globalOptions = {
652
+ selfListen: false,
653
+ listenEvents: true,
654
+ listenTyping: false,
655
+ updatePresence: false,
656
+ forceLogin: false,
657
+ autoMarkDelivery: false,
658
+ autoMarkRead: false,
659
+ autoReconnect: true,
660
+ logRecordSize: defaultLogRecordSize,
661
+ online: false,
662
+ emitReady: false,
663
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.18"
664
+ };
665
+ //! bằng 1 cách nào đó tắt online sẽ đánh lừa được facebook :v
666
+ //! phải có that có this chứ :v
667
+ setOptions(globalOptions, options);
668
+ var prCallback = null;
669
+ if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
670
+ var rejectFunc = null;
671
+ var resolveFunc = null;
672
+ var returnPromise = new Promise(function(resolve, reject) {
673
+ resolveFunc = resolve;
674
+ rejectFunc = reject;
675
+ });
676
+ prCallback = function(error, api) {
677
+ if (error) return rejectFunc(error);
678
+ return resolveFunc(api);
679
+ };
680
+ callback = prCallback;
681
+ }
682
+ loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
683
+ return returnPromise;
684
+ }
685
+ module.exports = login;