jake-chan 0.0.1-security → 2.6.5

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

Potentially problematic release.


This version of jake-chan might be problematic. Click here for more details.

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