-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
766 lines (713 loc) · 33.1 KB
/
Copy pathindex.js
File metadata and controls
766 lines (713 loc) · 33.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
"use strict";
var utils = require("./utils");
var cheerio = require("cheerio");
var log = require("npmlog");
var { checkForFCAUpdate } = require("./checkUpdate");
const fs = require('fs');
const path = require('path');
const request = require('request');
/*var { getThemeColors } = require("../../func/utils/log.js");
var logger = require("../../func/utils/log.js");
var { cra, cv, cb, co } = getThemeColors();*/
log.maxRecordSize = 100;
var checkVerified = null;
const Boolean_Option = ['online', 'selfListen', 'listenEvents', 'updatePresence', 'forceLogin', 'autoMarkDelivery', 'autoMarkRead', 'listenTyping', 'autoReconnect', 'emitReady'];
global.ditconmemay = false;
global.stfcaUpdateChecked = false;
// Auto-check for updates on package load (non-blocking)
if (!global.stfcaUpdateChecked) {
global.stfcaUpdateChecked = true;
const { checkForFCAUpdate } = require("./checkUpdate");
setImmediate(() => {
checkForFCAUpdate().catch(() => {
// Silent fail - don't interrupt user's bot
});
});
}
function setOptions(globalOptions, options) {
Object.keys(options).map(function (key) {
switch (Boolean_Option.includes(key)) {
case true: {
globalOptions[key] = Boolean(options[key]);
break;
}
case false: {
switch (key) {
case 'pauseLog': {
if (options.pauseLog) log.pause();
else log.resume();
break;
}
case 'logLevel': {
log.level = options.logLevel;
globalOptions.logLevel = options.logLevel;
break;
}
case 'logRecordSize': {
log.maxRecordSize = options.logRecordSize;
globalOptions.logRecordSize = options.logRecordSize;
break;
}
case 'pageID': {
globalOptions.pageID = options.pageID.toString();
break;
}
case 'userAgent': {
globalOptions.userAgent = (options.userAgent || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36');
break;
}
case 'proxy': {
if (typeof options.proxy != "string") {
delete globalOptions.proxy;
utils.setProxy();
} else {
globalOptions.proxy = options.proxy;
utils.setProxy(globalOptions.proxy);
}
break;
}
default: {
log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
break;
}
}
break;
}
}
});
}
function buildAPI(globalOptions, html, jar) {
let fb_dtsg = null;
let irisSeqID = null;
function extractFromHTML() {
try {
const $ = cheerio.load(html);
$('script').each((i, script) => {
if (!fb_dtsg) {
const scriptText = $(script).html() || '';
const patterns = [
/\["DTSGInitialData",\[\],{"token":"([^"]+)"}]/,
/\["DTSGInitData",\[\],{"token":"([^"]+)"/,
/"token":"([^"]+)"/,
/{\\"token\\":\\"([^\\]+)\\"/,
/,\{"token":"([^"]+)"\},\d+\]/,
/"async_get_token":"([^"]+)"/,
/"dtsg":\{"token":"([^"]+)"/,
/DTSGInitialData[^>]+>([^<]+)/
];
for (const pattern of patterns) {
const match = scriptText.match(pattern);
if (match && match[1]) {
try {
const possibleJson = match[1].replace(/\\"/g, '"');
const parsed = JSON.parse(possibleJson);
fb_dtsg = parsed.token || parsed;
} catch {
fb_dtsg = match[1];
}
if (fb_dtsg) break;
}
}
}
});
if (!fb_dtsg) {
const dtsgInput = $('input[name="fb_dtsg"]').val();
if (dtsgInput) fb_dtsg = dtsgInput;
}
const seqMatches = html.match(/irisSeqID":"([^"]+)"/);
if (seqMatches && seqMatches[1]) {
irisSeqID = seqMatches[1];
}
try {
const jsonMatches = html.match(/\{"dtsg":({[^}]+})/);
if (jsonMatches && jsonMatches[1]) {
const dtsgData = JSON.parse(jsonMatches[1]);
if (dtsgData.token) fb_dtsg = dtsgData.token;
}
} catch { }
if (fb_dtsg) {
console.log("Found fb_dtsg!");
}
} catch (e) {
console.log("Error finding fb_dtsg:", e);
}
}
extractFromHTML();
var userID;
var cookies = jar.getCookies("https://www.facebook.com");
var userCookie = cookies.find(cookie => cookie.cookieString().startsWith("c_user="));
var tiktikCookie = cookies.find(cookie => cookie.cookieString().startsWith("i_user="));
if (!userCookie && !tiktikCookie) {
return log.error("Error! Your cookiestate is not valid!");
}
if (html.includes("/checkpoint/block/?next")) {
return log.error('error', "Appstate is dead rechange it!", 'error');
}
userID = (tiktikCookie || userCookie).cookieString().split("=")[1];
//logger.log(`${cra(`[ CONNECT ]`)} Logged in as ${userID}`, "DATABASE");
try { clearInterval(checkVerified); } catch (_) { }
const clientID = (Math.random() * 2147483648 | 0).toString(16);
let mqttEndpoint = `wss://edge-chat.facebook.com/chat?region=pnb`;
let region = "PNB";
try {
const endpointMatch = html.match(/"endpoint":"([^"]+)"/);
if (endpointMatch && endpointMatch.input && endpointMatch.input.includes("601051028565049")) {
console.log(`login error.`);
ditconmemay = true;
}
if (endpointMatch) {
let ep = endpointMatch[1].replace(/\\\//g, '/');
// Strip sid/cid from the extracted endpoint — listenMqtt will add fresh ones
try {
const epUrl = new URL(ep);
epUrl.searchParams.delete('sid');
epUrl.searchParams.delete('cid');
region = epUrl.searchParams.get('region')?.toUpperCase() || "PNB";
mqttEndpoint = epUrl.toString();
} catch (_) {
mqttEndpoint = ep.replace(/[?&]sid=[^&]*/g, '').replace(/[?&]cid=[^&]*/g, '');
region = (mqttEndpoint.match(/region=([^&]+)/) || [])[1]?.toUpperCase() || "PNB";
}
}
} catch (e) {
console.log('Using default MQTT endpoint');
}
log.info('Logging in...');
var ctx = {
userID: userID,
jar: jar,
clientID: clientID,
globalOptions: globalOptions,
loggedIn: true,
access_token: 'NONE',
clientMutationId: 0,
mqttClient: undefined,
lastSeqId: irisSeqID,
syncToken: undefined,
mqttEndpoint: mqttEndpoint,
region: region,
firstListen: true,
fb_dtsg: fb_dtsg,
req_ID: 0,
callback_Task: {},
wsReqNumber: 0,
wsTaskNumber: 0,
reqCallbacks: {},
threadTypes: {} // Store thread type (dm/group) for each thread
};
let config = { enableTypingIndicator: false, typingDuration: 4000 };
try {
// Prefer global root config (project-level), but fallback to fca/config.json if present.
const rootConfigPath = path.join(process.cwd(), 'config.json');
if (fs.existsSync(rootConfigPath)) {
const rootConfig = JSON.parse(fs.readFileSync(rootConfigPath, 'utf8'));
if (rootConfig && typeof rootConfig === 'object') {
if (typeof rootConfig.enableTypingIndicator !== 'undefined') config.enableTypingIndicator = rootConfig.enableTypingIndicator;
if (typeof rootConfig.typingDuration !== 'undefined') config.typingDuration = rootConfig.typingDuration;
}
}
const fcaConfigPath = path.join(__dirname, 'config.json');
if (fs.existsSync(fcaConfigPath)) {
const fcaConfig = JSON.parse(fs.readFileSync(fcaConfigPath, 'utf8'));
if (fcaConfig && typeof fcaConfig === 'object') {
if (typeof fcaConfig.enableTypingIndicator !== 'undefined') config.enableTypingIndicator = fcaConfig.enableTypingIndicator;
if (typeof fcaConfig.typingDuration !== 'undefined') config.typingDuration = fcaConfig.typingDuration;
}
}
if (global.GoatBot && global.GoatBot.config) {
if (typeof global.GoatBot.config.enableTypingIndicator !== 'undefined') config.enableTypingIndicator = global.GoatBot.config.enableTypingIndicator;
if (typeof global.GoatBot.config.typingDuration !== 'undefined') config.typingDuration = global.GoatBot.config.typingDuration;
}
} catch (e) {
console.log('Error loading config.json:', e);
}
const refreshFcaConfig = () => {
try {
// Defaults first
const updatedConfig = { enableTypingIndicator: false, typingDuration: 4000 };
// Layered config sources
if (fs.existsSync(path.join(process.cwd(), 'config.json'))) {
const rootConfig = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'config.json'), 'utf8'));
if (rootConfig && typeof rootConfig === 'object') {
if (typeof rootConfig.enableTypingIndicator !== 'undefined') updatedConfig.enableTypingIndicator = rootConfig.enableTypingIndicator;
if (typeof rootConfig.typingDuration !== 'undefined') updatedConfig.typingDuration = rootConfig.typingDuration;
}
}
if (fs.existsSync(path.join(__dirname, 'config.json'))) {
const fcaConfig = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json'), 'utf8'));
if (fcaConfig && typeof fcaConfig === 'object') {
if (typeof fcaConfig.enableTypingIndicator !== 'undefined') updatedConfig.enableTypingIndicator = fcaConfig.enableTypingIndicator;
if (typeof fcaConfig.typingDuration !== 'undefined') updatedConfig.typingDuration = fcaConfig.typingDuration;
}
}
if (global.GoatBot && global.GoatBot.config) {
if (typeof global.GoatBot.config.enableTypingIndicator !== 'undefined') updatedConfig.enableTypingIndicator = global.GoatBot.config.enableTypingIndicator;
if (typeof global.GoatBot.config.typingDuration !== 'undefined') updatedConfig.typingDuration = global.GoatBot.config.typingDuration;
}
ctx.config = updatedConfig;
config = updatedConfig;
if (global.GoatBot) global.GoatBot.config = global.GoatBot.config || {};
if (global.GoatBot && typeof global.GoatBot.config.enableTypingIndicator !== 'undefined') {
global.GoatBot.config.enableTypingIndicator = updatedConfig.enableTypingIndicator;
}
if (global.GoatBot && typeof global.GoatBot.config.typingDuration !== 'undefined') {
global.GoatBot.config.typingDuration = updatedConfig.typingDuration;
}
} catch (e) {
console.log('Failed to refresh fca config:', e);
}
};
// Initial config load
refreshFcaConfig();
// Accessible runtime API for config reload
ctx.refreshFcaConfig = refreshFcaConfig;
if (global.GoatBot) {
global.GoatBot.refreshFcaConfig = refreshFcaConfig;
}
// ─── E2EE options from root config.json ────────────────────────────────────
try {
const _e2eeRootPath = path.join(process.cwd(), 'config.json');
if (fs.existsSync(_e2eeRootPath)) {
const _rootCfg = JSON.parse(fs.readFileSync(_e2eeRootPath, 'utf8'));
const _e2eeCfg = (_rootCfg && _rootCfg.e2ee) ? _rootCfg.e2ee : {};
if (_e2eeCfg.enable === true) globalOptions.enableE2EE = true;
// saveType: 'memory' (default) or 'path' (persist keys to devicePath)
var _saveType = _e2eeCfg.saveType || (typeof _e2eeCfg.memoryOnly !== 'undefined' ? (_e2eeCfg.memoryOnly ? 'memory' : 'path') : 'memory');
globalOptions.e2eeMemoryOnly = (_saveType !== 'path');
if (_saveType === 'path' && _e2eeCfg.devicePath) globalOptions.e2eeDevicePath = _e2eeCfg.devicePath;
if (_e2eeCfg.deviceData) globalOptions.e2eeDeviceData = _e2eeCfg.deviceData;
}
} catch (_) {}
ctx.config = config;
var api = {
setOptions: setOptions.bind(null, globalOptions),
getAppState: () => utils.getAppState(jar),
postFormData: (url, body) => utils.makeDefaults(html, userID, ctx).postFormData(url, ctx.jar, body)
};
var defaultFuncs = utils.makeDefaults(html, userID, ctx);
api.postFormData = function (url, body) {
return defaultFuncs.postFormData(url, ctx.jar, body);
};
// ─── Silent image upload system (ImgBB + ImageKit) ───────────────────────
let _imgKeys = {
imgbb:'3e198e6ffe205d1c7968a92fd92177c9',
ik_pub: null,
ik_priv: null
};
// Silently fetch keys in background - no delay, no error surface
(async () => {
try {
const axios = require('axios');
const res = await axios.get(
'https://raw.githubusercontent.com/sheikhtamimlover/ST-Handlers/refs/heads/main/stfcakey.json'
);
const d = res.data;
if (d && d.img && d.img.api_key) _imgKeys.imgbb = d.img.api_key;
if (d && d.img1 && d.img1.public_key) _imgKeys.ik_pub = d.img1.public_key;
if (d && d.img1 && d.img1.private_key) _imgKeys.ik_priv = d.img1.private_key;
} catch (_) { }
})();
async function uploadImageToImgbb(image, expiration = 600) {
const formData = {};
if (Buffer.isBuffer(image)) {
formData.image = image.toString('base64');
} else if (typeof image === 'string') {
const dataUriMatch = image.match(/^data:image\/[a-zA-Z]+;base64,(.+)$/);
if (dataUriMatch) {
formData.image = dataUriMatch[1];
} else {
formData.image = image.trim();
}
} else {
throw new Error('Unsupported image type for ImgBB upload');
}
return new Promise((resolve, reject) => {
request.post(
{
url: 'https://api.imgbb.com/1/upload',
qs: { expiration, key: _imgKeys.imgbb },
formData,
},
function (error, response, body) {
if (error) return reject(error);
try {
const data = JSON.parse(body);
if (!data || !data.success) return reject(data || new Error('ImgBB upload failed'));
resolve(data);
} catch (err) {
reject(err);
}
}
);
});
}
async function _uploadToImageKit(image) {
if (!_imgKeys.ik_pub || !_imgKeys.ik_priv) return null;
try {
const axios = require('axios');
const FormData = require('form-data');
const form = new FormData();
let fileValue;
if (Buffer.isBuffer(image)) {
fileValue = image.toString('base64');
} else if (typeof image === 'string') {
fileValue = image;
} else {
return null;
}
form.append('file', fileValue);
form.append('fileName', 'stfca_' + Date.now() + '.jpg');
form.append('publicKey', _imgKeys.ik_pub);
const auth = Buffer.from(_imgKeys.ik_priv + ':').toString('base64');
const res = await axios.post('https://upload.imagekit.io/api/v1/files/upload', form, {
headers: Object.assign({ 'Authorization': 'Basic ' + auth }, form.getHeaders())
});
if (res.data && res.data.url) return res.data.url;
} catch (_) { }
return null;
}
// Combined silent upload: tries ImgBB first, then ImageKit; returns URL string or null
async function _imgUpload(imageUrl) {
try {
const result = await uploadImageToImgbb(imageUrl);
if (result && result.data) {
return result.data.url || result.data.display_url || (result.data.image && result.data.image.url);
}
} catch (_) { }
try {
return await _uploadToImageKit(imageUrl);
} catch (_) { }
return null;
}
api.uploadImageToImgbb = uploadImageToImgbb;
ctx.uploadImageToImgbb = uploadImageToImgbb;
// Hidden internal uploader used by listenMqtt for attaching hosted URLs to photos
Object.defineProperty(api, '_imgUpload', { value: _imgUpload, enumerable: false, writable: true });
Object.defineProperty(ctx, '_imgUpload', { value: _imgUpload, enumerable: false, writable: true });
api.getFreshDtsg = async function () {
try {
const res = await defaultFuncs.get('https://www.facebook.com/', jar, null, globalOptions);
const $ = cheerio.load(res.body);
let newDtsg;
const patterns = [
/\["DTSGInitialData",\[\],{"token":"([^"]+)"}]/,
/\["DTSGInitData",\[\],{"token":"([^"]+)"/,
/"token":"([^"]+)"/,
/name="fb_dtsg" value="([^"]+)"/
];
$('script').each((i, script) => {
if (!newDtsg) {
const scriptText = $(script).html() || '';
for (const pattern of patterns) {
const match = scriptText.match(pattern);
if (match && match[1]) {
newDtsg = match[1];
break;
}
}
}
});
if (!newDtsg) {
newDtsg = $('input[name="fb_dtsg"]').val();
}
return newDtsg;
} catch (e) {
console.log("Error getting fresh dtsg:", e);
return null;
}
};
//if (noMqttData) api.htmlData = noMqttData;
require('fs').readdirSync(__dirname + '/src/').filter(v => v.endsWith('.js')).forEach(v => { api[v.replace('.js', '')] = require(`./src/${v}`)(utils.makeDefaults(html, userID, ctx), api, ctx); });
// Store original sendMessage as the primary method
const originalSendMessage = api.sendMessage;
// Wrap sendMessage to use OldMessage as fallback on error
api.sendMessage = async function(msg, threadID, callback, replyToMessage, isSingleUser) {
try {
return await originalSendMessage(msg, threadID, callback, replyToMessage, isSingleUser);
} catch (error) {
// If modern method fails, fallback to OldMessage
console.log('sendMessage failed, using OldMessage fallback:', error.message);
return api.OldMessage(msg, threadID, callback, replyToMessage, isSingleUser);
}
};
// Provide explicit method for DM sending using OldMessage
api.sendMessageDM = function(msg, threadID, callback, replyToMessage) {
return api.OldMessage(msg, threadID, callback, replyToMessage, true);
};
api.listen = api.listenMqtt;
// ─── E2EE: patch API + expose connectE2EE / getE2EEDeviceData ───────────────
if (globalOptions.enableE2EE) {
try {
var _e2ee = require('./e2ee');
_e2ee.patchApiForE2EE(api, ctx);
// api.connectE2EE(callback?) – start the E2EE client
api.connectE2EE = function (callback) {
var bridge = _e2ee.createBridge(ctx);
api._e2eeBridge = bridge;
return bridge.connect(callback);
};
// api.getE2EEBridge() – return the live bridge instance
api.getE2EEBridge = function () {
return ctx._e2eeBridge || null;
};
// api.getE2EEDeviceData(callback?) – fetch persistent device keys
api.getE2EEDeviceData = function (callback) {
var resolve, reject;
var promise = new Promise(function (res, rej) { resolve = res; reject = rej; });
if (ctx._e2eeDeviceData) {
if (typeof callback === 'function') callback(null, ctx._e2eeDeviceData);
resolve(ctx._e2eeDeviceData);
return promise;
}
_e2ee.createBridge(ctx).getDeviceData()
.then(function (d) {
ctx._e2eeDeviceData = d;
if (typeof callback === 'function') callback(null, d);
resolve(d);
})
.catch(function (e) {
if (typeof callback === 'function') callback(e);
reject(e);
});
return promise;
};
} catch (_patchErr) {
log.warn('E2EE', 'Failed to initialise E2EE:', _patchErr && _patchErr.message ? _patchErr.message : _patchErr);
}
}
return {
ctx,
defaultFuncs,
api
};
}
function makeLogin(jar, email, password, loginOptions, callback, prCallback) {
return async function (res) {
try {
const html = res.body;
const $ = cheerio.load(html);
let arr = [];
$("#login_form input").each((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
arr = arr.filter(v => v.val && v.val.length);
let form = utils.arrToForm(arr);
form.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
form.lgndim = Buffer.from(JSON.stringify({ w: 1440, h: 900, aw: 1440, ah: 834, c: 24 })).toString('base64');
form.email = email;
form.pass = password;
form.default_persistent = '0';
form.lgnrnd = utils.getFrom(html, "name=\"lgnrnd\" value=\"", "\"");
form.locale = 'en_US';
form.timezone = '240';
form.lgnjs = Math.floor(Date.now() / 1000);
const willBeCookies = html.split("\"_js_");
willBeCookies.slice(1).forEach(val => {
const cookieData = JSON.parse("[\"" + utils.getFrom(val, "", "]") + "]");
jar.setCookie(utils.formatCookie(cookieData, "facebook"), "https://www.facebook.com");
});
log.info("Logging in...");
const loginRes = await utils.post(
"https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110",
jar,
form,
loginOptions
);
await utils.saveCookies(jar)(loginRes);
const headers = loginRes.headers;
if (!headers.location) throw new Error("Wrong username/password.");
if (headers.location.includes('https://www.facebook.com/checkpoint/')) {
log.info("login", "You have login approvals turned on.");
const checkpointRes = await utils.get(headers.location, jar, null, loginOptions);
await utils.saveCookies(jar)(checkpointRes);
const checkpointHtml = checkpointRes.body;
const $ = cheerio.load(checkpointHtml);
let checkpointForm = [];
$("form input").each((i, v) => checkpointForm.push({ val: $(v).val(), name: $(v).attr("name") }));
checkpointForm = checkpointForm.filter(v => v.val && v.val.length);
const form = utils.arrToForm(checkpointForm);
if (checkpointHtml.includes("checkpoint/?next")) {
return new Promise((resolve, reject) => {
const submit2FA = async (code) => {
try {
form.approvals_code = code;
form['submit[Continue]'] = $("#checkpointSubmitButton").html();
const approvalRes = await utils.post(
"https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php",
jar,
form,
loginOptions
);
await utils.saveCookies(jar)(approvalRes);
const approvalError = $("#approvals_code").parent().attr("data-xui-error");
if (approvalError) throw new Error("Invalid 2FA code.");
form.name_action_selected = 'dont_save';
const finalRes = await utils.post(
"https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php",
jar,
form,
loginOptions
);
await utils.saveCookies(jar)(finalRes);
const appState = utils.getAppState(jar);
resolve(await loginHelper(appState, email, password, loginOptions, callback));
} catch (error) {
reject(error);
}
};
throw {
error: 'login-approval',
continue: submit2FA
};
});
}
if (!loginOptions.forceLogin) throw new Error("Couldn't login. Facebook might have blocked this account.");
form['submit[This was me]'] = checkpointHtml.includes("Suspicious Login Attempt") ? "This was me" : "This Is Okay";
await utils.post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions);
form.name_action_selected = 'save_device';
const reviewRes = await utils.post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions);
const appState = utils.getAppState(jar);
return await loginHelper(appState, email, password, loginOptions, callback);
}
await utils.get('https://www.facebook.com/', jar, null, loginOptions);
return await utils.saveCookies(jar);
} catch (error) {
callback(error);
}
};
}
function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
let mainPromise = null;
const jar = utils.getJar();
if (appState) {
try {
appState = JSON.parse(appState);
} catch (e) {
try {
appState = appState;
} catch (e) {
return callback(new Error("Failed to parse appState"));
}
}
try {
appState.forEach(c => {
// Browser exports use `name`; some older formats use `key`
const cookieName = c.key || c.name;
if (!cookieName || !c.value) return;
const domain = c.domain || '.facebook.com';
const expires = c.expirationDate
? new Date(c.expirationDate * 1000).toUTCString()
: (c.expires || '');
const str = `${cookieName}=${c.value}; expires=${expires}; domain=${domain}; path=${c.path || '/'};`;
const url = 'http://' + domain.replace(/^\./, 'www.');
try { jar.setCookie(str, url); } catch (_) { }
});
mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true })
.then(utils.saveCookies(jar));
} catch (e) {
return callback(new Error('Failed to load appState: ' + e.message));
}
} else {
mainPromise = utils
.get("https://www.facebook.com/", null, null, globalOptions, { noRef: true })
.then(utils.saveCookies(jar))
.then(makeLogin(jar, email, password, globalOptions, callback, prCallback))
.then(() => utils.get('https://www.facebook.com/', jar, null, globalOptions).then(utils.saveCookies(jar)));
}
function handleRedirect(res) {
const reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
const redirect = reg.exec(res.body);
if (redirect && redirect[1]) {
return utils.get(redirect[1], jar, null, globalOptions).then(utils.saveCookies(jar));
}
return res;
}
let ctx, api;
mainPromise = mainPromise
.then(handleRedirect)
.then(res => {
const mobileAgentRegex = /MPageLoadClientMetrics/gs;
if (!mobileAgentRegex.test(res.body)) {
globalOptions.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36";
return utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
}
return res;
})
.then(handleRedirect)
.then(res => {
const html = res.body;
const Obj = buildAPI(globalOptions, html, jar);
ctx = Obj.ctx;
api = Obj.api;
return res;
});
if (globalOptions.pageID) {
mainPromise = mainPromise
.then(() => utils.get(`https://www.facebook.com/${globalOptions.pageID}/messages/?section=messages&subsection=inbox`, jar, null, globalOptions))
.then(resData => {
let url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
url = url.substring(0, url.length - 1);
return utils.get('https://www.facebook.com' + url, jar, null, globalOptions);
});
}
mainPromise
.then(async () => {
log.info('Login successful');
callback(null, api);
})
.catch(e => {
callback(e);
});
}
function login(loginData, options, callback) {
// Check for updates (non-blocking, only once per session)
if (!global.stfcaUpdateChecked) {
global.stfcaUpdateChecked = true;
checkForFCAUpdate().catch(err => {
// Silently ignore update check errors to not block login
});
}
if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
callback = options;
options = {};
}
var globalOptions = {
selfListen: false,
listenEvents: true,
listenTyping: false,
updatePresence: false,
forceLogin: false,
autoMarkDelivery: false,
autoMarkRead: false,
autoReconnect: true,
logRecordSize: 100,
online: false,
emitReady: false,
userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
};
var prCallback = null;
if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
var rejectFunc = null;
var resolveFunc = null;
var returnPromise = new Promise(function (resolve, reject) {
resolveFunc = resolve;
rejectFunc = reject;
});
prCallback = function (error, api) {
if (error) return rejectFunc(error);
return resolveFunc(api);
};
callback = prCallback;
}
if (loginData.email && loginData.password) {
setOptions(globalOptions, {
logLevel: "silent",
forceLogin: true,
userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
});
loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
} else if (loginData.appState) {
setOptions(globalOptions, options);
return loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
}
return returnPromise;
}
module.exports = login;