fb-anya 0.0.1-security → 9.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 fb-anya might be problematic. Click here for more details.

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