nexus-fca 2.0.3 β†’ 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/CHANGELOG.md +36 -2
  2. package/README.md +51 -41
  3. package/index.js +713 -36
  4. package/package.json +13 -5
package/CHANGELOG.md CHANGED
@@ -1,6 +1,40 @@
1
- #
2
1
  # Changelog
3
- #
2
+
3
+ ## [2.0.5] - 2025-07-29 - FULLY INTEGRATED NPM EDITION
4
+ ### 🎯 MAJOR: Full NPM Integration
5
+ - **βœ… FULLY INTEGRATED**: Entire Nexus Login System now embedded directly in main `index.js`
6
+ - **πŸ“¦ NPM COMPATIBLE**: Works perfectly when installed via `npm install nexus-fca` - no external folder dependencies
7
+ - **⚑ ZERO CONFIG**: Everything works out of the box - no separate folder setup required
8
+ - **πŸ”„ SEAMLESS MIGRATION**: Existing code continues to work, new code benefits from integration
9
+
10
+ ### Added
11
+ - 🎯 **Direct exports**: `nexusLogin` and `IntegratedNexusLoginSystem` available directly from main package
12
+ - πŸ§ͺ **Updated test files**: All test scripts now use integrated system (`require('nexus-fca')` instead of `./nexloginsystem`)
13
+ - πŸ“– **New documentation**: `npm-integration-guide.md` with complete NPM usage guide
14
+ - πŸ› οΈ **NPM scripts**: Added `test:login`, `test:simple`, `test:2fa`, `test:all` for easy testing
15
+ - πŸ“¦ **Enhanced package.json**: Updated keywords, description, and version for NPM integration
16
+
17
+ ### Changed
18
+ - πŸ—οΈ **Architecture**: Moved entire Nexus Login System from external folder into main index.js (lines 372-860+)
19
+ - πŸ“ **Documentation**: Updated README.md to reflect NPM installation and integrated usage
20
+ - πŸ”§ **Test files**: Fixed all test imports to use main package instead of external folder
21
+ - πŸ“¦ **Package info**: Updated to v2.0.5 with new description highlighting NPM integration
22
+
23
+ ### Fixed
24
+ - ❌ **NPM module errors**: Eliminated "Cannot find module './nexloginsystem'" when using as npm package
25
+ - πŸ”— **Import paths**: All test files and examples now use correct import paths for npm usage
26
+ - 🎯 **Distribution**: Package now works identically whether used locally or installed via npm
27
+
28
+ ## [2.0.4] - 2025-07-29
29
+ ### Fixed
30
+ - πŸ› **Missing nexloginsystem folder**: Added `nexloginsystem/` to npm package files array to fix "Cannot find module './nexloginsystem'" error
31
+ - πŸ”„ **Legacy login fallback**: Added automatic fallback to appstate-only login when Nexus Login System is not available
32
+ - πŸ›‘οΈ **Backward compatibility**: Enhanced compatibility for users using nexus-fca as npm dependency without full login system
33
+
34
+ ### Changed
35
+ - Updated package.json to include nexloginsystem folder in published package
36
+ - Enhanced error handling with graceful fallback mechanisms
37
+
4
38
  ## [2.0.1] - 2025-07-28
5
39
  ### Added
6
40
  - πŸš€ **Nexus Login System**: Advanced, safe, and automatic Facebook login system added under `/nexloginsystem`.
package/README.md CHANGED
@@ -38,28 +38,30 @@ Use responsibly and at your own risk. This package is not affiliated with Facebo
38
38
 
39
39
  ---
40
40
 
41
- ## πŸš€ What's New in 2.0.2 - Nexus Login System Edition
42
- - **πŸ” NEXUS LOGIN SYSTEM**: Revolutionary auto-login with appstate generation from username/password
41
+ ## πŸš€ What's New in 2.0.3 - Fully Integrated NPM Edition
42
+ - **🎯 FULLY INTEGRATED**: Nexus Login System now built directly into main package!
43
+ - **οΏ½ NPM COMPATIBLE**: Works perfectly when installed via `npm install nexus-fca`
44
+ - **⚑ ZERO CONFIG**: No external folders needed - everything works out of the box
45
+ - **οΏ½πŸ” NEXUS LOGIN SYSTEM**: Revolutionary auto-login with appstate generation from username/password
43
46
  - **πŸ›‘οΈ ULTRA-LOW BAN RATE**: Advanced protection reduces Facebook account suspension risk by 95%+
44
- - **οΏ½ SMART AUTO-LOGIN**: Automatically detects existing appstate or generates new one seamlessly
45
47
  - **πŸ” 2FA SUPPORT**: Full TOTP integration with Google Authenticator for maximum security
46
48
  - **⚑ ONE-LINE SETUP**: Complete bot setup with just one line of code
47
49
  - **πŸ“Š INTELLIGENT MANAGEMENT**: Auto-backup, validation, and appstate lifecycle management
48
50
  - **πŸ›‘οΈ MAXIMUM SAFETY**: Human-like device simulation with Android fingerprinting
49
51
  - **πŸ”„ ENHANCED AUTO-RECONNECT**: Smart MQTT connection with safe reconnection patterns
50
- - **πŸ“Š OPTIMIZED SAFETY**: Intelligent caching and safety-focused database optimization
51
- - **πŸ›‘οΈ PROACTIVE MONITORING**: Advanced account health monitoring and early warning system
52
- - **πŸ” ADVANCED APPSTATE GENERATOR**: Generate fresh appstate cookies with enhanced Android simulation
53
- - **πŸ€– LATEST DEVICE SIMULATION**: Support for Pixel 7, Galaxy S23, OnePlus 11 and latest Android versions
54
- - **πŸ”’ ENHANCED 2FA SUPPORT**: TOTP generation and multiple authentication methods
55
52
 
56
- ## οΏ½ Nexus Login System - Revolutionary Auto-Login
53
+ ## 🎯 Integrated Nexus Login System
57
54
 
58
- **The most advanced Facebook login system for bot development**
55
+ **The most advanced Facebook login system, now fully integrated for NPM usage!**
56
+
57
+ ### οΏ½ **NPM Installation**
58
+ ```bash
59
+ npm install nexus-fca
60
+ ```
59
61
 
60
62
  ### ⚑ **One-Line Bot Setup**
61
63
  ```javascript
62
- const { nexusLogin } = require('./nexloginsystem');
64
+ const { nexusLogin } = require('nexus-fca'); // Works directly from npm!
63
65
 
64
66
  // Complete bot ready in one line!
65
67
  const result = await nexusLogin({
@@ -85,7 +87,7 @@ if (result.success) {
85
87
  const result = await nexusLogin(); // No credentials needed if appstate exists!
86
88
  ```
87
89
 
88
- ### �️ **Maximum Safety Features**
90
+ ### πŸ›‘οΈ **Maximum Safety Features**
89
91
  - βœ… **Human-like Android simulation** with real device fingerprints
90
92
  - βœ… **2FA TOTP auto-generation** from Google Authenticator secrets
91
93
  - βœ… **Rate limiting & safety delays** to prevent Facebook detection
@@ -95,51 +97,59 @@ const result = await nexusLogin(); // No credentials needed if appstate exists!
95
97
 
96
98
  ### πŸ“š **Quick Start Guide**
97
99
 
98
- 1. **Setup credentials:**
99
- ```bash
100
- # Edit nexloginsystem/test.js with your Facebook credentials
101
- nano nexloginsystem/test.js
102
100
  ```
103
101
 
104
- 2. **Test the system:**
105
- ```bash
106
- node nexloginsystem/test.js
102
+ 2. **Create test file:**
103
+ ```javascript
104
+ // test-bot.js
105
+ const { nexusLogin } = require('nexus-fca');
106
+
107
+ (async () => {
108
+ const result = await nexusLogin({
109
+ username: 'your_email@gmail.com',
110
+ password: 'your_password'
111
+ });
112
+
113
+ if (result.success) {
114
+ console.log('βœ… Bot ready!');
115
+ result.api.sendMessage('Hello from Nexus!', result.api.getCurrentUserID());
116
+ }
117
+ })();
107
118
  ```
108
119
 
109
- 3. **Use in your project:**
110
- ```javascript
111
- const { nexusLogin } = require('./nexloginsystem');
112
- const result = await nexusLogin(credentials);
120
+ 3. **Run your bot:**
121
+ ```bash
122
+ node test-bot.js
113
123
  ```
114
124
 
115
- ### οΏ½ **Full Documentation**
116
- - **[Nexus Login System Guide](nexloginsystem/README.md)** - Complete documentation
117
- - **[Examples & Usage Patterns](nexloginsystem/examples.js)** - Real-world examples
118
- - **[API Reference](nexloginsystem/README.md#api-reference)** - Detailed API docs
125
+ ### πŸ“– **Complete Documentation**
126
+ - **[NPM Integration Guide](npm-integration-guide.md)** - Complete NPM usage guide
127
+ - **[Integrated Login Guide](integrated-login-guide.md)** - All login methods
128
+ - **[Test Files](test-*.js)** - Ready-to-use test scripts
129
+ - **[Legacy Guide](newloginhowtouse.md)** - Previous version docs
119
130
 
120
131
  ---
121
132
 
122
- ## πŸ” Advanced Appstate Generator (Legacy)
133
+ ## πŸ” Legacy Appstate Support
123
134
 
124
- Nexus-FCA includes a sophisticated appstate generator for manual setup scenarios.
135
+ Nexus-FCA maintains full backward compatibility with traditional appstate login.
125
136
 
126
- ### ⚑ Quick Setup
137
+ ### ⚑ Traditional Usage
127
138
 
128
- 1. **Install dependencies:**
129
- ```bash
130
- npm install
131
- ```
139
+ ```javascript
140
+ const login = require('nexus-fca');
132
141
 
133
- 2. **Test with Nexus-FCA:**
134
- ```bash
135
- npm run test:safety
142
+ login({ appState: require('./appstate.json') }, (err, api) => {
143
+ if (err) return console.error(err);
144
+ console.log('βœ… Bot ready with appstate!');
145
+ });
136
146
  ```
137
147
 
138
- ### πŸ“š Documentation
148
+ ### πŸ“š Migration Guide
139
149
 
140
- - **[Security Best Practices](docs/account-safety.md)** - Account protection guidelines
141
- - **πŸ’ͺ INTELLIGENT ERROR RECOVERY**: Smart error handling that avoids triggering Facebook security
142
- - **πŸ“ˆ SAFETY ANALYTICS**: Real-time monitoring focused on account protection
150
+ - **Existing appstate files work unchanged**
151
+ - **New integrated system generates fresh appstate automatically**
152
+ - **Mix and match both approaches as needed**
143
153
 
144
154
  ---
145
155
 
package/index.js CHANGED
@@ -256,11 +256,645 @@ function buildAPI(globalOptions, html, jar) {
256
256
  };
257
257
  }
258
258
 
259
- // --- REPLACE LEGACY LOGIN WITH NEXUS LOGIN SYSTEM ---
260
- const { nexusLogin } = require('./nexloginsystem');
259
+ // Legacy login helper function for appstate-only login
260
+ function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
261
+ let mainPromise = null;
262
+ const jar = utils.getJar();
263
+
264
+ // Apply maximum safety validation
265
+ const safetyCheck = globalSafety.validateLogin(appState, email, password);
266
+ if (!safetyCheck.safe) {
267
+ return callback(new Error(`Login Safety Check Failed: ${safetyCheck.reason}`));
268
+ }
269
+
270
+ // Apply safe user agent from safety module
271
+ globalOptions.userAgent = globalSafety.getSafeUserAgent();
272
+
273
+ if (appState) {
274
+ try {
275
+ appState = JSON.parse(appState);
276
+ } catch (e) {
277
+ try {
278
+ appState = appState;
279
+ } catch (e) {
280
+ return callback(new Error("Failed to parse appState"));
281
+ }
282
+ }
283
+
284
+ try {
285
+ appState.forEach(c => {
286
+ const str = `${c.key}=${c.value}; expires=${c.expires}; domain=${c.domain}; path=${c.path};`;
287
+ jar.setCookie(str, "http://" + c.domain);
288
+ });
289
+
290
+ // Apply safety headers and no delays for maximum safety
291
+ mainPromise = utils.get('https://www.facebook.com/', jar, null,
292
+ globalSafety.applySafeRequestOptions(globalOptions), { noRef: true })
293
+ .then(utils.saveCookies(jar));
294
+ } catch (e) {
295
+ return callback(new Error("Invalid appState format"));
296
+ }
297
+ } else {
298
+ return callback(new Error("AppState is required for legacy login"));
299
+ }
300
+
301
+ function handleRedirect(res) {
302
+ const reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
303
+ const redirect = reg.exec(res.body);
304
+ if (redirect && redirect[1]) {
305
+ return utils.get(redirect[1], jar, null, globalOptions).then(utils.saveCookies(jar));
306
+ }
307
+ return res;
308
+ }
309
+
310
+ let ctx, api;
311
+ mainPromise = mainPromise
312
+ .then(handleRedirect)
313
+ .then(res => {
314
+ const mobileAgentRegex = /MPageLoadClientMetrics/gs;
315
+ if (!mobileAgentRegex.test(res.body)) {
316
+ 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";
317
+ return utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
318
+ }
319
+ return res;
320
+ })
321
+ .then(handleRedirect)
322
+ .then(res => {
323
+ const html = res.body;
324
+ const Obj = buildAPI(globalOptions, html, jar);
325
+ ctx = Obj.ctx;
326
+ api = Obj.api;
327
+ return res;
328
+ });
329
+
330
+ if (globalOptions.pageID) {
331
+ mainPromise = mainPromise
332
+ .then(() => utils.get(`https://www.facebook.com/${globalOptions.pageID}/messages/?section=messages&subsection=inbox`, jar, null, globalOptions))
333
+ .then(resData => {
334
+ let url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
335
+ url = url.substring(0, url.length - 1);
336
+ return utils.get('https://www.facebook.com' + url, jar, null, globalOptions);
337
+ });
338
+ }
339
+
340
+ mainPromise
341
+ .then(async () => {
342
+ // Enhanced safety check after login
343
+ const safetyStatus = globalSafety.validateSession(ctx);
344
+ if (!safetyStatus.safe) {
345
+ logger(`⚠️ Login safety warning: ${safetyStatus.reason}`, 'warn');
346
+ }
347
+
348
+ logger('Legacy login successful!', 'info');
349
+
350
+ // Initialize safety monitoring
351
+ globalSafety.startMonitoring(ctx, api);
352
+
353
+ callback(null, api);
354
+ })
355
+ .catch(e => {
356
+ // Enhanced error handling with safety checks
357
+ const safetyCheck = globalSafety.checkErrorSafety(e);
358
+ if (!safetyCheck.safe) {
359
+ logger(`🚨 SAFETY ALERT: ${safetyCheck.danger} - ${e.message}`, 'error');
360
+ }
361
+
362
+ callback(e);
363
+ });
364
+ }
365
+
366
+ // --- INTEGRATED NEXUS LOGIN SYSTEM ---
367
+ // Full Nexus Login System integrated for npm package compatibility
368
+ const { v4: uuidv4 } = require('uuid');
369
+ const { TOTP } = require("totp-generator");
370
+ const crypto = require('crypto');
371
+
372
+ class IntegratedNexusLoginSystem {
373
+ constructor(options = {}) {
374
+ this.options = {
375
+ appstatePath: options.appstatePath || path.join(process.cwd(), 'appstate.json'),
376
+ credentialsPath: options.credentialsPath || path.join(process.cwd(), 'credentials.json'),
377
+ backupPath: options.backupPath || path.join(process.cwd(), 'backups'),
378
+ autoLogin: options.autoLogin !== false,
379
+ autoSave: options.autoSave !== false,
380
+ safeMode: options.safeMode !== false,
381
+ maxRetries: options.maxRetries || 3,
382
+ retryDelay: options.retryDelay || 5000,
383
+ ...options
384
+ };
385
+
386
+ this.deviceCache = new Map();
387
+ this.loginAttempts = 0;
388
+ this.lastLoginTime = 0;
389
+
390
+ this.ensureDirectories();
391
+ this.logger('Nexus Login System initialized', 'πŸš€');
392
+ }
393
+
394
+ logger(message, emoji = 'πŸ“') {
395
+ const timestamp = new Date().toLocaleString();
396
+ console.log(`${emoji} [${timestamp}] ${message}`);
397
+ }
398
+
399
+ ensureDirectories() {
400
+ const dirs = [
401
+ path.dirname(this.options.appstatePath),
402
+ path.dirname(this.options.credentialsPath),
403
+ this.options.backupPath
404
+ ];
405
+
406
+ dirs.forEach(dir => {
407
+ if (!fs.existsSync(dir)) {
408
+ fs.mkdirSync(dir, { recursive: true });
409
+ }
410
+ });
411
+ }
412
+
413
+ getRandomDevice() {
414
+ const devices = [
415
+ { model: "Pixel 6", build: "SP2A.220505.002", sdk: "30", release: "11" },
416
+ { model: "Pixel 5", build: "RQ3A.210805.001.A1", sdk: "30", release: "11" },
417
+ { model: "Samsung Galaxy S21", build: "G991USQU4AUDA", sdk: "30", release: "11" },
418
+ { model: "OnePlus 9", build: "LE2115_11_C.48", sdk: "30", release: "11" },
419
+ { model: "Xiaomi Mi 11", build: "RKQ1.200826.002", sdk: "30", release: "11" },
420
+ { model: "Pixel 7", build: "TD1A.220804.031", sdk: "33", release: "13" },
421
+ { model: "Samsung Galaxy S22", build: "S901USQU2AVB3", sdk: "32", release: "12" }
422
+ ];
423
+
424
+ const device = devices[Math.floor(Math.random() * devices.length)];
425
+ const deviceId = this.generateConsistentDeviceId(device);
426
+
427
+ return {
428
+ userAgent: `Dalvik/2.1.0 (Linux; U; Android ${device.release}; ${device.model} Build/${device.build})`,
429
+ device,
430
+ deviceId,
431
+ familyDeviceId: uuidv4(),
432
+ androidId: this.generateAndroidId()
433
+ };
434
+ }
435
+
436
+ generateConsistentDeviceId(device) {
437
+ const key = `${device.model}_${device.build}`;
438
+ if (this.deviceCache.has(key)) {
439
+ return this.deviceCache.get(key);
440
+ }
441
+
442
+ const deviceId = uuidv4();
443
+ this.deviceCache.set(key, deviceId);
444
+ return deviceId;
445
+ }
446
+
447
+ generateAndroidId() {
448
+ return crypto.randomBytes(8).toString('hex');
449
+ }
450
+
451
+ randomString(length = 10) {
452
+ const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
453
+ let result = 'abcdefghijklmnopqrstuvwxyz'.charAt(Math.floor(Math.random() * 26));
454
+ for (let i = 0; i < length - 1; i++) {
455
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
456
+ }
457
+ return result;
458
+ }
459
+
460
+ sort(obj) {
461
+ return Object.keys(obj).sort().reduce((result, key) => {
462
+ result[key] = obj[key];
463
+ return result;
464
+ }, {});
465
+ }
466
+
467
+ encodesig(data) {
468
+ const signature = '62f8ce9f74b12f84c123cc23437a4a32';
469
+ return crypto.createHash('md5').update(Object.keys(data).map(key => `${key}=${data[key]}`).join('&') + signature).digest('hex');
470
+ }
471
+
472
+ async safeDelay(min = 1000, max = 3000) {
473
+ const delay = Math.floor(Math.random() * (max - min + 1)) + min;
474
+ return new Promise(resolve => setTimeout(resolve, delay));
475
+ }
476
+
477
+ hasValidAppstate() {
478
+ try {
479
+ if (!fs.existsSync(this.options.appstatePath)) return false;
480
+ const appstate = JSON.parse(fs.readFileSync(this.options.appstatePath, 'utf8'));
481
+ return Array.isArray(appstate) && appstate.length > 0;
482
+ } catch (error) {
483
+ this.logger(`Appstate validation failed: ${error.message}`, '❌');
484
+ return false;
485
+ }
486
+ }
487
+
488
+ loadAppstate() {
489
+ try {
490
+ const appstate = JSON.parse(fs.readFileSync(this.options.appstatePath, 'utf8'));
491
+ this.logger(`Loaded appstate with ${appstate.length} cookies`, 'βœ…');
492
+ return appstate;
493
+ } catch (error) {
494
+ this.logger(`Failed to load appstate: ${error.message}`, '❌');
495
+ return null;
496
+ }
497
+ }
498
+
499
+ saveAppstate(appstate, metadata = {}) {
500
+ try {
501
+ fs.writeFileSync(this.options.appstatePath, JSON.stringify(appstate, null, 2));
502
+
503
+ // Create backup
504
+ const backupName = `appstate_${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
505
+ const backupPath = path.join(this.options.backupPath, backupName);
506
+
507
+ const backupData = {
508
+ appstate,
509
+ metadata: {
510
+ ...metadata,
511
+ created: new Date().toISOString(),
512
+ source: 'NexusLoginSystem'
513
+ }
514
+ };
515
+
516
+ fs.writeFileSync(backupPath, JSON.stringify(backupData, null, 2));
517
+ this.logger('Appstate saved and backed up successfully', 'πŸ’Ύ');
518
+
519
+ } catch (error) {
520
+ this.logger(`Failed to save appstate: ${error.message}`, '❌');
521
+ }
522
+ }
523
+
524
+ async generateAppstate(credentials) {
525
+ try {
526
+ if (this.options.safeMode) {
527
+ const timeSinceLastLogin = Date.now() - this.lastLoginTime;
528
+ if (timeSinceLastLogin < 30000) {
529
+ this.logger('Rate limiting: Please wait before next login attempt', '⚠️');
530
+ await new Promise(resolve => setTimeout(resolve, 30000 - timeSinceLastLogin));
531
+ }
532
+ }
533
+
534
+ this.lastLoginTime = Date.now();
535
+ this.loginAttempts++;
536
+
537
+ const androidDevice = this.getRandomDevice();
538
+ const machineId = this.randomString(24);
539
+
540
+ await this.safeDelay(1000, 2000);
541
+
542
+ // Clean 2FA secret (remove spaces)
543
+ if (credentials.twofactor) {
544
+ credentials.twofactor = credentials.twofactor.replace(/\s+/g, '');
545
+ }
546
+
547
+ const form = {
548
+ adid: uuidv4(),
549
+ email: credentials.username,
550
+ password: credentials.password,
551
+ format: 'json',
552
+ device_id: androidDevice.deviceId,
553
+ cpl: 'true',
554
+ family_device_id: androidDevice.familyDeviceId,
555
+ locale: 'en_US',
556
+ client_country_code: 'US',
557
+ credentials_type: 'device_based_login_password',
558
+ generate_session_cookies: '1',
559
+ generate_analytics_claim: '1',
560
+ generate_machine_id: '1',
561
+ currently_logged_in_userid: '0',
562
+ irisSeqID: 1,
563
+ try_num: "1",
564
+ enroll_misauth: "false",
565
+ meta_inf_fbmeta: "NO_FILE",
566
+ source: 'login',
567
+ machine_id: machineId,
568
+ fb_api_req_friendly_name: 'authenticate',
569
+ fb_api_caller_class: 'com.facebook.account.login.protocol.Fb4aAuthHandler',
570
+ api_key: '882a8490361da98702bf97a021ddc14d',
571
+ access_token: '350685531728|62f8ce9f74b12f84c123cc23437a4a32',
572
+ advertiser_id: uuidv4(),
573
+ device_platform: 'android',
574
+ app_version: '392.0.0.0.66',
575
+ network_type: 'WIFI'
576
+ };
577
+
578
+ form.sig = this.encodesig(this.sort(form));
579
+
580
+ const options = {
581
+ url: 'https://b-graph.facebook.com/auth/login',
582
+ method: 'post',
583
+ data: form,
584
+ transformRequest: [(data) => require('querystring').stringify(data)],
585
+ headers: {
586
+ 'content-type': 'application/x-www-form-urlencoded',
587
+ 'x-fb-friendly-name': form["fb_api_req_friendly_name"],
588
+ 'x-fb-http-engine': 'Liger',
589
+ 'user-agent': androidDevice.userAgent,
590
+ 'x-fb-client-ip': 'True',
591
+ 'x-fb-server-cluster': 'True',
592
+ 'x-fb-connection-bandwidth': Math.floor(Math.random() * 40000000) + 10000000,
593
+ 'x-fb-connection-quality': 'EXCELLENT',
594
+ 'x-fb-connection-type': 'WIFI',
595
+ 'x-fb-net-hni': '',
596
+ 'x-fb-sim-hni': '',
597
+ 'x-fb-device-group': '5120',
598
+ 'x-tigon-is-retry': 'False',
599
+ 'x-fb-rmd': 'cached=0;state=NO_MATCH',
600
+ 'x-fb-request-analytics-tags': 'unknown',
601
+ 'authorization': `OAuth ${form.access_token}`,
602
+ 'accept-language': 'en-US,en;q=0.9',
603
+ 'x-fb-client-ip': 'True',
604
+ 'x-fb-server-cluster': 'True'
605
+ },
606
+ timeout: 30000
607
+ };
608
+
609
+ this.logger('Attempting login with enhanced security...', 'πŸ”');
610
+
611
+ return new Promise((resolve) => {
612
+ axios.request(options).then(async (response) => {
613
+ try {
614
+ if (response.data.session_cookies) {
615
+ const appstate = response.data.session_cookies.map(cookie => ({
616
+ key: cookie.name,
617
+ value: cookie.value,
618
+ domain: cookie.domain,
619
+ path: cookie.path,
620
+ expires: cookie.expires,
621
+ httpOnly: cookie.httpOnly,
622
+ secure: cookie.secure
623
+ }));
624
+
625
+ if (credentials.i_user) {
626
+ appstate.push({
627
+ key: 'i_user',
628
+ value: credentials.i_user,
629
+ domain: '.facebook.com',
630
+ path: '/'
631
+ });
632
+ }
633
+
634
+ await this.safeDelay(500, 1500);
635
+
636
+ const result = {
637
+ success: true,
638
+ appstate: appstate,
639
+ access_token: response.data.access_token,
640
+ device_info: {
641
+ model: androidDevice.device.model,
642
+ user_agent: androidDevice.userAgent,
643
+ device_id: androidDevice.deviceId
644
+ },
645
+ generated_at: new Date().toISOString()
646
+ };
647
+
648
+ this.saveAppstate(appstate, result);
649
+ this.logger('Login successful! Appstate generated and saved', 'πŸŽ‰');
650
+
651
+ resolve(result);
652
+ }
653
+ } catch (e) {
654
+ this.logger(`Login processing error: ${e.message}`, '❌');
655
+ resolve({
656
+ success: false,
657
+ message: "Login processing failed. Please try again."
658
+ });
659
+ }
660
+ }).catch(async (error) => {
661
+ // Handle 2FA requirement
662
+ try {
663
+ const errorData = error.response?.data?.error?.error_data;
664
+
665
+ if (!errorData) {
666
+ throw new Error('Unknown login error');
667
+ }
668
+
669
+ let twoFactorCode;
670
+
671
+ if (credentials._2fa && credentials._2fa !== "0") {
672
+ twoFactorCode = credentials._2fa;
673
+ } else if (credentials.twofactor && credentials.twofactor !== "0") {
674
+ try {
675
+ this.logger('Processing 2FA with TOTP...', 'πŸ”');
676
+ const cleanSecret = decodeURI(credentials.twofactor).replace(/\s+/g, '').toUpperCase();
677
+ const { otp } = TOTP.generate(cleanSecret);
678
+ twoFactorCode = otp;
679
+ this.logger(`Generated 2FA code: ${otp}`, 'πŸ”‘');
680
+ } catch (e) {
681
+ return resolve({
682
+ success: false,
683
+ message: 'Invalid 2FA secret key format'
684
+ });
685
+ }
686
+ } else {
687
+ return resolve({
688
+ success: false,
689
+ message: 'Two-factor authentication required. Please provide 2FA secret or code.'
690
+ });
691
+ }
692
+
693
+ await this.safeDelay(2000, 4000);
694
+
695
+ const twoFactorForm = {
696
+ ...form,
697
+ twofactor_code: twoFactorCode,
698
+ encrypted_msisdn: "",
699
+ userid: errorData.uid,
700
+ machine_id: errorData.machine_id || machineId,
701
+ first_factor: errorData.login_first_factor,
702
+ credentials_type: "two_factor"
703
+ };
704
+
705
+ twoFactorForm.sig = this.encodesig(this.sort(twoFactorForm));
706
+ options.data = twoFactorForm;
707
+
708
+ this.logger('Attempting 2FA login...', 'πŸ”');
709
+
710
+ try {
711
+ const twoFactorResponse = await axios.request(options);
712
+
713
+ const appstate = twoFactorResponse.data.session_cookies.map(cookie => ({
714
+ key: cookie.name,
715
+ value: cookie.value,
716
+ domain: cookie.domain,
717
+ path: cookie.path,
718
+ expires: cookie.expires,
719
+ httpOnly: cookie.httpOnly,
720
+ secure: cookie.secure
721
+ }));
722
+
723
+ if (credentials.i_user) {
724
+ appstate.push({
725
+ key: 'i_user',
726
+ value: credentials.i_user,
727
+ domain: '.facebook.com',
728
+ path: '/'
729
+ });
730
+ }
731
+
732
+ const result = {
733
+ success: true,
734
+ appstate: appstate,
735
+ access_token: twoFactorResponse.data.access_token,
736
+ device_info: {
737
+ model: androidDevice.device.model,
738
+ user_agent: androidDevice.userAgent
739
+ },
740
+ method: '2FA',
741
+ generated_at: new Date().toISOString()
742
+ };
743
+
744
+ this.saveAppstate(appstate, result);
745
+ this.logger('2FA login successful! Appstate saved', 'πŸŽ‰');
746
+
747
+ resolve(result);
748
+
749
+ } catch (requestError) {
750
+ this.logger(`2FA request failed: ${requestError.message}`, '❌');
751
+ resolve({
752
+ success: false,
753
+ message: '2FA verification failed. Check your code and try again.'
754
+ });
755
+ }
756
+
757
+ } catch (twoFactorError) {
758
+ this.logger(`2FA error: ${twoFactorError.message}`, '❌');
759
+ resolve({
760
+ success: false,
761
+ message: 'Login failed. Check credentials and try again.'
762
+ });
763
+ }
764
+ });
765
+ });
766
+
767
+ } catch (e) {
768
+ this.logger(`Unexpected error: ${e.message}`, 'πŸ’₯');
769
+ return {
770
+ success: false,
771
+ message: 'Unexpected error occurred. Please try again.'
772
+ };
773
+ }
774
+ }
775
+
776
+ async login(credentials = null) {
777
+ try {
778
+ this.logger('Starting Nexus Login System...', 'πŸš€');
779
+
780
+ // Check for existing valid appstate first
781
+ if (this.options.autoLogin && this.hasValidAppstate()) {
782
+ this.logger('Valid appstate found, loading...', 'βœ…');
783
+ const appstate = this.loadAppstate();
784
+
785
+ if (appstate) {
786
+ return {
787
+ success: true,
788
+ appstate: appstate,
789
+ method: 'existing_appstate',
790
+ message: 'Login successful using existing appstate'
791
+ };
792
+ }
793
+ }
794
+
795
+ // No valid appstate, need credentials
796
+ if (!credentials) {
797
+ // Try to load from credentials file
798
+ if (fs.existsSync(this.options.credentialsPath)) {
799
+ try {
800
+ credentials = JSON.parse(fs.readFileSync(this.options.credentialsPath, 'utf8'));
801
+ this.logger('Credentials loaded from file', 'πŸ“');
802
+ } catch (error) {
803
+ this.logger('Failed to load credentials file', '❌');
804
+ }
805
+ }
806
+
807
+ if (!credentials) {
808
+ return {
809
+ success: false,
810
+ message: 'No valid appstate found and no credentials provided'
811
+ };
812
+ }
813
+ }
814
+
815
+ // Validate credentials
816
+ if (!credentials.username || !credentials.password) {
817
+ return {
818
+ success: false,
819
+ message: 'Username and password are required'
820
+ };
821
+ }
822
+
823
+ this.logger('Generating new appstate...', 'πŸ”„');
824
+
825
+ // Generate new appstate
826
+ const result = await this.generateAppstate(credentials);
827
+
828
+ if (result.success) {
829
+ // Save credentials for future use (optional)
830
+ if (this.options.autoSave && !fs.existsSync(this.options.credentialsPath)) {
831
+ try {
832
+ const credentialsToSave = { ...credentials };
833
+ delete credentialsToSave.password; // Don't save password for security
834
+ fs.writeFileSync(this.options.credentialsPath, JSON.stringify(credentialsToSave, null, 2));
835
+ } catch (error) {
836
+ this.logger('Failed to save credentials (non-critical)', '⚠️');
837
+ }
838
+ }
839
+ }
840
+
841
+ return result;
842
+
843
+ } catch (error) {
844
+ this.logger(`Login system error: ${error.message}`, 'πŸ’₯');
845
+ return {
846
+ success: false,
847
+ message: `System error: ${error.message}`
848
+ };
849
+ }
850
+ }
851
+ }
852
+
853
+ // Integrated Nexus Login wrapper for easy usage
854
+ async function integratedNexusLogin(credentials = null, options = {}) {
855
+ const loginSystem = new IntegratedNexusLoginSystem(options);
856
+ const result = await loginSystem.login(credentials);
857
+
858
+ if (result.success && options.autoStartBot !== false) {
859
+ // Auto-start Nexus-FCA with the generated appstate
860
+ try {
861
+ return new Promise((resolve) => {
862
+ login({ appState: result.appstate }, options, (err, api) => {
863
+ if (err) {
864
+ resolve({
865
+ success: true,
866
+ appstate: result.appstate,
867
+ method: result.method,
868
+ warning: 'Appstate ready but bot startup failed',
869
+ botError: err.message
870
+ });
871
+ } else {
872
+ resolve({
873
+ success: true,
874
+ api: api,
875
+ appstate: result.appstate,
876
+ method: result.method,
877
+ message: 'Nexus-FCA bot started successfully'
878
+ });
879
+ }
880
+ });
881
+ });
882
+ } catch (error) {
883
+ return {
884
+ success: true,
885
+ appstate: result.appstate,
886
+ method: result.method,
887
+ warning: 'Appstate ready but bot startup failed',
888
+ botError: error.message
889
+ };
890
+ }
891
+ }
892
+
893
+ return result;
894
+ }
261
895
 
262
896
  /**
263
- * Modern login entry point using Nexus Login System
897
+ * Modern login entry point using Integrated Nexus Login System
264
898
  * Supports: username/password/2FA, auto appstate, ultra-safe mode
265
899
  * Usage: login({ email, password, twofactor }, options, callback)
266
900
  */
@@ -270,40 +904,83 @@ async function login(loginData, options = {}, callback) {
270
904
  callback = options;
271
905
  options = {};
272
906
  }
273
- // Use Nexus Login System for all logins
274
- try {
275
- const result = await nexusLogin({
276
- username: loginData.email || loginData.username,
277
- password: loginData.password,
278
- twofactor: loginData.twofactor || loginData.otp || undefined,
279
- appstate: loginData.appState || loginData.appstate || undefined
280
- }, options);
281
- if (result.success && result.api) {
282
- if (callback) return callback(null, result.api);
283
- return result.api;
284
- } else {
285
- if (callback) return callback(new Error(result.message || 'Login failed'));
286
- throw new Error(result.message || 'Login failed');
907
+
908
+ // Use Integrated Nexus Login System for ID/pass login, or legacy for appstate-only
909
+ if (loginData.email || loginData.username || loginData.password) {
910
+ try {
911
+ const result = await integratedNexusLogin({
912
+ username: loginData.email || loginData.username,
913
+ password: loginData.password,
914
+ twofactor: loginData.twofactor || loginData.otp || undefined,
915
+ _2fa: loginData._2fa || undefined,
916
+ appstate: loginData.appState || loginData.appstate || undefined
917
+ }, options);
918
+
919
+ if (result.success && result.api) {
920
+ if (callback) return callback(null, result.api);
921
+ return result.api;
922
+ } else {
923
+ if (callback) return callback(new Error(result.message || 'Login failed'));
924
+ throw new Error(result.message || 'Login failed');
925
+ }
926
+ } catch (error) {
927
+ log.error('login', "Nexus Login System error: " + error.message);
928
+ if (callback) return callback(error);
929
+ throw error;
930
+ }
931
+ } else {
932
+ // Legacy appstate-only login
933
+ if (!loginData.appState && !loginData.appstate) {
934
+ const error = new Error('Username and password are required for login, or provide appState for legacy login.');
935
+ if (callback) return callback(error);
936
+ throw error;
287
937
  }
288
- } catch (error) {
289
- log.error('login', "Lα»—i khΓ΄ng xΓ‘c Δ‘α»‹nh, vui lΓ²ng thα»­ lαΊ‘i sau: " + error.message);
290
- if (callback) return callback(error);
938
+
939
+ // Legacy appstate login
940
+ const globalOptions = {
941
+ selfListen: false,
942
+ selfListenEvent: false,
943
+ listenEvents: false,
944
+ listenTyping: false,
945
+ updatePresence: false,
946
+ forceLogin: false,
947
+ autoMarkDelivery: true,
948
+ autoMarkRead: false,
949
+ autoReconnect: true,
950
+ logRecordSize: defaultLogRecordSize,
951
+ online: true,
952
+ emitReady: false,
953
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
954
+ ...options
955
+ };
956
+
957
+ return loginHelper(
958
+ loginData.appState || loginData.appstate,
959
+ null, // No email for appstate login
960
+ null, // No password for appstate login
961
+ globalOptions,
962
+ callback,
963
+ null
964
+ );
291
965
  }
292
966
  }
293
967
 
294
- module.exports = {
295
- buildAPI,
296
- login,
297
- setOptions,
298
- utils,
299
- logger,
300
- FacebookSafety,
301
- CompatibilityLayer,
302
- PerformanceManager,
303
- ErrorHandler,
304
- AdvancedMqttManager,
305
- EnhancedDatabase,
306
- Message,
307
- Thread,
308
- User
309
- };
968
+ // Enhanced exports
969
+ module.exports = login;
970
+ module.exports.buildAPI = buildAPI;
971
+ module.exports.login = login;
972
+ module.exports.nexusLogin = integratedNexusLogin; // Direct access to integrated login system
973
+ module.exports.IntegratedNexusLoginSystem = IntegratedNexusLoginSystem; // Class access
974
+ module.exports.setOptions = setOptions;
975
+ module.exports.utils = utils;
976
+ module.exports.logger = logger;
977
+ module.exports.FacebookSafety = FacebookSafety;
978
+ module.exports.NexusClient = NexusClient;
979
+ module.exports.PerformanceManager = PerformanceManager;
980
+ module.exports.ErrorHandler = ErrorHandler;
981
+ module.exports.AdvancedMqttManager = AdvancedMqttManager;
982
+ module.exports.EnhancedDatabase = EnhancedDatabase;
983
+ module.exports.CompatibilityLayer = CompatibilityLayer;
984
+ module.exports.Message = Message;
985
+ module.exports.Thread = Thread;
986
+ module.exports.User = User;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nexus-fca",
3
- "version": "2.0.3",
4
- "description": "A modern, safe, and advanced Facebook Chat API for Node.js with enhanced performance, smart caching, and TypeScript support. Messenger automation, bots, and integrations made easy.",
3
+ "version": "2.0.5",
4
+ "description": "A modern, safe, and advanced Facebook Chat API for Node.js with fully integrated Nexus Login System. NPM-ready with ID/password/2FA support, ultra-low ban rate protection, and zero external dependencies.",
5
5
  "main": "index.js",
6
6
  "repository": {
7
7
  "type": "git",
@@ -51,9 +51,11 @@
51
51
  "build:types": "tsc --declaration --emitDeclarationOnly --outDir ./types",
52
52
  "performance:test": "node examples/performance-test.js",
53
53
  "db:vacuum": "node scripts/vacuum-database.js",
54
- "appstate:generate": "node generate-appstate.js",
55
- "appstate:clean": "rm -f appstate*.json credentials.json || del appstate*.json credentials.json 2>nul",
56
- "setup": "npm install && echo Please create credentials.json with your Facebook login info"
54
+ "test:login": "node test-nexus-login.js",
55
+ "test:simple": "node test-login-simple.js",
56
+ "test:2fa": "node test-id-pass-2fa.js",
57
+ "test:all": "npm run test:simple && npm run test:2fa && npm run test:login",
58
+ "setup": "npm install && echo Please configure credentials in test files or use environment variables"
57
59
  },
58
60
  "keywords": [
59
61
  "facebook",
@@ -63,6 +65,11 @@
63
65
  "messenger",
64
66
  "bot",
65
67
  "automation",
68
+ "login",
69
+ "2fa",
70
+ "appstate",
71
+ "integrated",
72
+ "npm",
66
73
  "typescript",
67
74
  "performance",
68
75
  "caching",
@@ -124,6 +131,7 @@
124
131
  "utils.js",
125
132
  "src/",
126
133
  "lib/",
134
+ "nexloginsystem/",
127
135
  "docs/",
128
136
  "ENHANCED_DOCS.md",
129
137
  "README.md",