fca-nx 6.8.6 → 6.8.8

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 (74) hide show
  1. package/func/checkUpdate.js +1 -1
  2. package/func/logAdapter.js +0 -2
  3. package/index.js +0 -3
  4. package/module/config.js +2 -7
  5. package/module/login.js +10 -38
  6. package/module/loginHelper.js +94 -163
  7. package/module/options.js +1 -7
  8. package/package.json +2 -2
  9. package/src/api/action/addfriend.js +3 -9
  10. package/src/api/action/changeAvatar.js +0 -1
  11. package/src/api/action/changeCover.js +1 -3
  12. package/src/api/action/enableAutoSaveAppState.js +5 -18
  13. package/src/api/action/refreshFb_dtsg.js +2 -2
  14. package/src/api/http/httpGet.js +2 -6
  15. package/src/api/http/httpPost.js +2 -7
  16. package/src/api/messaging/createNewGroup.js +1 -1
  17. package/src/api/messaging/deleteMessage.js +1 -1
  18. package/src/api/messaging/forwardMessage.js +1 -9
  19. package/src/api/messaging/getEmojiUrl.js +1 -5
  20. package/src/api/messaging/getMessage.js +2 -4
  21. package/src/api/messaging/getThemePictures.js +0 -7
  22. package/src/api/messaging/markAsRead.js +0 -1
  23. package/src/api/messaging/muteThread.js +1 -1
  24. package/src/api/messaging/pinMessage.js +1 -10
  25. package/src/api/messaging/scheduler.js +4 -71
  26. package/src/api/messaging/sendBroadcast.js +0 -15
  27. package/src/api/messaging/sendMessage.js +1 -10
  28. package/src/api/messaging/sendTypingIndicator.js +2 -2
  29. package/src/api/messaging/sessionGuard.js +9 -45
  30. package/src/api/messaging/setMessageReaction.js +1 -2
  31. package/src/api/messaging/threadColors.js +12 -45
  32. package/src/api/messaging/uploadAttachment.js +3 -37
  33. package/src/api/socket/core/connectMqtt.js +17 -60
  34. package/src/api/socket/core/emitAuth.js +2 -14
  35. package/src/api/socket/core/getSeqID.js +23 -29
  36. package/src/api/socket/core/getTaskResponseData.js +1 -3
  37. package/src/api/socket/core/parseDelta.js +1 -1
  38. package/src/api/socket/detail/buildStream.js +1 -4
  39. package/src/api/socket/detail/constants.js +1 -4
  40. package/src/api/socket/e2ee/crypto.js +2 -40
  41. package/src/api/socket/e2ee/index.js +10 -123
  42. package/src/api/socket/e2ee/protocol.js +1 -32
  43. package/src/api/socket/e2ee/ratchet.js +10 -44
  44. package/src/api/socket/e2ee/store.js +1 -13
  45. package/src/api/socket/listenE2EE.js +1 -25
  46. package/src/api/socket/listenMqtt.js +13 -29
  47. package/src/api/socket/middleware/index.js +7 -61
  48. package/src/api/socket/sendMessage.js +2 -19
  49. package/src/api/threads/getThreadHistory.js +38 -68
  50. package/src/api/threads/getThreadInfo.js +3 -4
  51. package/src/api/threads/getThreadList.js +31 -34
  52. package/src/api/threads/getThreadPictures.js +1 -1
  53. package/src/api/users/getUserInfo.js +2 -5
  54. package/src/api/users/getUserInfoV2.js +3 -9
  55. package/src/core/sendReqMqtt.js +1 -2
  56. package/src/database/helpers.js +0 -12
  57. package/src/database/models/index.js +1 -3
  58. package/src/utils/broadcast.js +1 -1
  59. package/src/utils/clientIdentity.js +3 -50
  60. package/src/utils/cookies.js +2 -4
  61. package/src/utils/format/utils.js +0 -10
  62. package/src/utils/headers.js +12 -26
  63. package/src/utils/instanceLock.js +3 -9
  64. package/src/utils/ipGuard.js +1 -15
  65. package/src/utils/loginParser/autoLogin.js +0 -12
  66. package/src/utils/loginParser/parseAndCheckLogin.js +0 -7
  67. package/src/utils/loginParser/textUtils.js +0 -6
  68. package/src/utils/request/config.js +1 -4
  69. package/src/utils/request/methods.js +1 -4
  70. package/src/utils/request/proxy.js +0 -13
  71. package/src/utils/request/retry.js +0 -1
  72. package/src/utils/request/sanitize.js +1 -1
  73. package/src/utils/sendThrottle.js +1 -14
  74. package/src/utils/utils.js +3 -17
@@ -13,6 +13,18 @@ const { loadConfig } = require("./config");
13
13
  const { createRemoteClient } = require("../src/remote/remoteClient");
14
14
  const { config } = loadConfig();
15
15
 
16
+ function credentialLoginAllowed() {
17
+ if (process.env.FCA_NX_ALLOW_CREDENTIAL_LOGIN === "1") return true;
18
+ try {
19
+ const botPath = path.join(process.cwd(), "config.json");
20
+ if (fs.existsSync(botPath)) {
21
+ const bot = JSON.parse(fs.readFileSync(botPath, "utf8"));
22
+ if (bot && bot.allowCredentialLogin === true) return true;
23
+ }
24
+ } catch (_) {}
25
+ return false;
26
+ }
27
+
16
28
  function e2eeEnabled() {
17
29
  const on = (v) => v === true || v === "true";
18
30
  const off = (v) => v === false || v === "false";
@@ -66,23 +78,9 @@ function mask(s, keep = 3) {
66
78
  return n <= keep ? "*".repeat(n) : s.slice(0, keep) + "*".repeat(Math.max(0, n - keep));
67
79
  }
68
80
 
69
- /**
70
- * Login via external API endpoint (iOS method)
71
- * @param {string} email - Email hoặc số điện thoại
72
- * @param {string} password - Mật khẩu
73
- * @param {string|null} twoFactor - Secret Base32 cho 2FA (không phải mã 6 số)
74
- * @param {string|null} apiBaseUrl - Base URL của API server (không có mặc định — phải chỉ định rõ ràng)
75
- * @param {string|null} apiKey - API key để xác thực (x-api-key header)
76
- * @returns {Promise<{ok: boolean, uid?: string, access_token?: string, cookies?: Array, cookie?: string, message?: string}>}
77
- */
78
81
  async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null, apiKey = null) {
79
82
  try {
80
- // SECURITY: do not default to a hard-coded third-party domain. Sending
81
- // a plaintext Facebook email/password to an external server should
82
- // require the operator to explicitly opt in (via config.apiServer or
83
- // the apiBaseUrl argument) rather than happening silently the first
84
- // time someone logs in with email+password. If no server is configured,
85
- // fail loudly instead of guessing where to send credentials.
83
+
86
84
  const baseUrl = apiBaseUrl || config.apiServer || null;
87
85
  if (!baseUrl) {
88
86
  const msg = "loginViaAPI: no apiServer configured. Refusing to send credentials to a default third-party endpoint. Set config.apiServer (or pass apiBaseUrl) explicitly, or log in with an appstate/cookie instead of email+password.";
@@ -93,25 +91,21 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
93
91
  const endpoint = `${baseUrl}/api/v1/facebook/login_ios`;
94
92
  const xApiKey = apiKey || config.apiKey || null;
95
93
 
96
- // Build request body
97
94
  const body = {
98
95
  email,
99
96
  password
100
97
  };
101
98
 
102
- // Only include twoFactor if provided (must be Base32 secret, not 6-digit code)
103
99
  if (twoFactor && typeof twoFactor === "string" && twoFactor.trim()) {
104
- // Clean up the secret - remove spaces and convert to uppercase
100
+
105
101
  body.twoFactor = twoFactor.replace(/\s+/g, "").toUpperCase();
106
102
  }
107
103
 
108
- // Build headers
109
104
  const headers = {
110
105
  "Content-Type": "application/json",
111
106
  "Accept": "application/json"
112
107
  };
113
108
 
114
- // Add x-api-key header if provided
115
109
  if (xApiKey) {
116
110
  headers["x-api-key"] = xApiKey;
117
111
  }
@@ -129,13 +123,11 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
129
123
  if (response.status === 200 && response.data) {
130
124
  const data = response.data;
131
125
 
132
- // Check if login was successful
133
126
  if (data.error) {
134
127
  logger(chalk.italic(`❌ API-LOGIN: Login failed - ${data.error}`), "error");
135
128
  return { ok: false, message: data.error };
136
129
  }
137
130
 
138
- // Extract response data
139
131
  const uid = data.uid || data.user_id || data.userId || null;
140
132
  const accessToken = data.access_token || data.accessToken || null;
141
133
  const cookie = data.cookie || data.cookies || null;
@@ -147,10 +139,9 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
147
139
 
148
140
  logger(chalk.italic(`✅ API-LOGIN: Login successful for UID: ${uid || "unknown"}`), "info");
149
141
 
150
- // Parse cookies if provided as string
151
142
  let cookies = [];
152
143
  if (typeof cookie === "string") {
153
- // Parse cookie string format: "key1=value1; key2=value2"
144
+
154
145
  const pairs = cookie.split(";").map(p => p.trim()).filter(Boolean);
155
146
  for (const pair of pairs) {
156
147
  const eq = pair.indexOf("=");
@@ -166,7 +157,7 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
166
157
  }
167
158
  }
168
159
  } else if (Array.isArray(cookie)) {
169
- // Already in array format
160
+
170
161
  cookies = cookie.map(c => ({
171
162
  key: c.key || c.name,
172
163
  value: c.value,
@@ -184,7 +175,6 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
184
175
  };
185
176
  }
186
177
 
187
- // Handle error responses
188
178
  const errorMsg = response.data && response.data.error
189
179
  ? response.data.error
190
180
  : response.data && response.data.message
@@ -201,14 +191,6 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
201
191
  }
202
192
  }
203
193
 
204
- /**
205
- * High-level login function that uses the API endpoint
206
- * @param {string} email - Email hoặc số điện thoại
207
- * @param {string} password - Mật khẩu
208
- * @param {string|null} twoFactor - Secret Base32 cho 2FA (không phải mã 6 số)
209
- * @param {string|null} apiBaseUrl - Base URL của API server
210
- * @returns {Promise<{status: boolean, cookies?: Array, uid?: string, access_token?: string, message?: string}>}
211
- */
212
194
  async function tokensViaAPI(email, password, twoFactor = null, apiBaseUrl = null) {
213
195
  const t0 = process.hrtime.bigint();
214
196
 
@@ -260,7 +242,7 @@ function normalizeCookieHeaderString(s) {
260
242
 
261
243
  function setJarFromPairs(j, pairs, domain) {
262
244
  const expires = new Date(Date.now() + 31536e6).toUTCString();
263
- // URLs to set cookies for - include both desktop and mobile versions
245
+
264
246
  const urls = [
265
247
  "https://www.facebook.com",
266
248
  "https://facebook.com",
@@ -269,10 +251,10 @@ function setJarFromPairs(j, pairs, domain) {
269
251
  "http://facebook.com",
270
252
  "http://m.facebook.com"
271
253
  ];
272
-
254
+
273
255
  for (const kv of pairs) {
274
256
  const cookieStr = `${kv}; expires=${expires}; domain=${domain}; path=/;`;
275
- // Set cookie for all URLs to ensure it works on both desktop and mobile
257
+
276
258
  for (const url of urls) {
277
259
  try {
278
260
  if (typeof j.setCookieSync === "function") {
@@ -281,8 +263,7 @@ function setJarFromPairs(j, pairs, domain) {
281
263
  j.setCookie(cookieStr, url);
282
264
  }
283
265
  } catch (err) {
284
- // Silently ignore domain mismatch errors
285
- // These can happen when setting cookies across different subdomains
266
+
286
267
  }
287
268
  }
288
269
  }
@@ -316,7 +297,6 @@ function getBackupModel() {
316
297
  if (!models || !models.sequelize || !models.Sequelize) return null;
317
298
  const sequelize = models.sequelize;
318
299
 
319
- // Validate that sequelize is a proper Sequelize instance
320
300
  if (!sequelize || typeof sequelize.define !== "function") return null;
321
301
 
322
302
  const { DataTypes } = models.Sequelize;
@@ -337,12 +317,12 @@ function getBackupModel() {
337
317
  );
338
318
  return AppStateBackup;
339
319
  } catch (defineError) {
340
- // If define fails, log and return null
320
+
341
321
  logger(`Failed to define AppStateBackup model: ${defineError && defineError.message ? defineError.message : String(defineError)}`, "warn");
342
322
  return null;
343
323
  }
344
324
  } catch (e) {
345
- // Silently handle any errors in getBackupModel
325
+
346
326
  return null;
347
327
  }
348
328
  }
@@ -407,8 +387,6 @@ async function getLatestBackupAny(type) {
407
387
  }
408
388
  }
409
389
 
410
-
411
-
412
390
  async function setJarCookies(j, appstate) {
413
391
  const tasks = [];
414
392
  for (const c of appstate) {
@@ -420,13 +398,11 @@ async function setJarCookies(j, appstate) {
420
398
  const cookiePath = c.path || "/";
421
399
  const dom = cookieDomain.replace(/^\./, "");
422
400
 
423
- // Handle expirationDate (can be in seconds or milliseconds)
424
401
  let expiresStr = "";
425
402
  if (c.expirationDate !== undefined) {
426
403
  let expiresDate;
427
404
  if (typeof c.expirationDate === "number") {
428
- // If expirationDate is less than a year from now in seconds, treat as seconds
429
- // Otherwise treat as milliseconds
405
+
430
406
  const now = Date.now();
431
407
  const oneYearInMs = 365 * 24 * 60 * 60 * 1000;
432
408
  if (c.expirationDate < (now + oneYearInMs) / 1000) {
@@ -443,24 +419,20 @@ async function setJarCookies(j, appstate) {
443
419
  expiresStr = `; expires=${expiresDate.toUTCString()}`;
444
420
  }
445
421
 
446
- // Helper function to build cookie string
447
422
  const buildCookieString = (domainOverride = null) => {
448
423
  const domain = domainOverride || cookieDomain;
449
424
  let cookieParts = [`${cookieName}=${cookieValue}${expiresStr}`];
450
425
  cookieParts.push(`Domain=${domain}`);
451
426
  cookieParts.push(`Path=${cookiePath}`);
452
427
 
453
- // Add Secure flag if secure is true
454
428
  if (c.secure === true) {
455
429
  cookieParts.push("Secure");
456
430
  }
457
431
 
458
- // Add HttpOnly flag if httpOnly is true
459
432
  if (c.httpOnly === true) {
460
433
  cookieParts.push("HttpOnly");
461
434
  }
462
435
 
463
- // Add SameSite attribute if provided
464
436
  if (c.sameSite) {
465
437
  const sameSiteValue = String(c.sameSite).toLowerCase();
466
438
  if (["strict", "lax", "none"].includes(sameSiteValue)) {
@@ -495,7 +467,6 @@ async function setJarCookies(j, appstate) {
495
467
  await Promise.all(tasks);
496
468
  }
497
469
 
498
- // tokens function - alias to tokensViaAPI for backward compatibility
499
470
  async function tokens(username, password, twofactor = null) {
500
471
  return tokensViaAPI(username, password, twofactor);
501
472
  }
@@ -536,7 +507,10 @@ async function hydrateJarFromDB(userID, jar) {
536
507
  }
537
508
 
538
509
  async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions, ctxRef, hadAppStateInput = false, jar) {
539
- // Helper to validate UID - must be a non-zero positive number string
510
+ if (!credentialLoginAllowed()) {
511
+ throw new Error("Credential login is disabled (6.8.7). Refresh the cookie/appstate instead. Set allowCredentialLogin=true only if you accept new-session logins.");
512
+ }
513
+
540
514
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
541
515
 
542
516
  const getUID = cs =>
@@ -550,19 +524,17 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
550
524
  };
551
525
 
552
526
  let userID = getUID(currentCookies);
553
- // Also try to extract userID from HTML if cookie userID is invalid
527
+
554
528
  if (!isValidUID(userID)) {
555
529
  userID = htmlUID(currentHtml);
556
530
  }
557
- // If we have a valid userID, return success
531
+
558
532
  if (isValidUID(userID)) {
559
533
  return { html: currentHtml, cookies: currentCookies, userID };
560
534
  }
561
535
 
562
- // No valid userID found - need to try auto-login
563
536
  logger("tryAutoLoginIfNeeded: No valid userID found, attempting recovery...", "warn");
564
537
 
565
- // If appState/Cookie was provided and is not checkpointed, try refresh
566
538
  if (hadAppStateInput) {
567
539
  const isCheckpoint = currentHtml.includes("/checkpoint/block/?next");
568
540
  if (!isCheckpoint) {
@@ -576,7 +548,6 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
576
548
  }
577
549
  }
578
550
 
579
- // Try to hydrate from DB backup
580
551
  const hydrated = await hydrateJarFromDB(null, jar);
581
552
  if (hydrated) {
582
553
  logger("tryAutoLoginIfNeeded: Trying backup from DB...", "info");
@@ -599,12 +570,10 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
599
570
  }
600
571
  }
601
572
 
602
- // Check if auto-login is enabled (support both true and "true")
603
573
  if (config.autoLogin === false || config.autoLogin === "false") {
604
574
  throw new Error("AppState expired — Auto-login is disabled");
605
575
  }
606
576
 
607
- // Try API login
608
577
  const u = config.credentials?.email || config.email;
609
578
  const p = config.credentials?.password || config.password;
610
579
  const tf = (globalOptions && globalOptions.twofactor) || config.credentials?.twofactor || config.twofactor || null;
@@ -623,28 +592,25 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
623
592
 
624
593
  logger(`tryAutoLoginIfNeeded: API login successful! UID: ${r.uid}`, "info");
625
594
 
626
- // Handle cookies - can be array, cookie string header, or both
627
595
  let cookiePairs = [];
628
-
629
- // If cookies is a string (cookie header format), parse it
596
+
630
597
  if (typeof r.cookies === "string") {
631
598
  cookiePairs = normalizeCookieHeaderString(r.cookies);
632
- }
633
- // If cookies is an array, convert to pairs
599
+ }
600
+
634
601
  else if (Array.isArray(r.cookies)) {
635
602
  cookiePairs = r.cookies.map(c => {
636
603
  if (typeof c === "string") {
637
- // Already in "key=value" format
604
+
638
605
  return c;
639
606
  } else if (c && typeof c === "object") {
640
- // Object format {key, value} or {name, value}
607
+
641
608
  return `${c.key || c.name}=${c.value}`;
642
609
  }
643
610
  return null;
644
611
  }).filter(Boolean);
645
612
  }
646
-
647
- // Also check for cookie field (alternative field name)
613
+
648
614
  if (cookiePairs.length === 0 && r.cookie) {
649
615
  if (typeof r.cookie === "string") {
650
616
  cookiePairs = normalizeCookieHeaderString(r.cookie);
@@ -665,11 +631,8 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
665
631
  setJarFromPairs(jar, cookiePairs, ".facebook.com");
666
632
  }
667
633
 
668
- // Wait a bit for cookies to be set
669
634
  await new Promise(resolve => setTimeout(resolve, 500));
670
635
 
671
- // Refresh Facebook page with new cookies - try multiple times if needed
672
- // Try both www.facebook.com and m.facebook.com to ensure session is established
673
636
  let html2 = "";
674
637
  let res2 = null;
675
638
  let retryCount = 0;
@@ -678,10 +641,10 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
678
641
 
679
642
  while (retryCount < maxRetries) {
680
643
  try {
681
- // Try m.facebook.com first (mobile version often works better for API login)
644
+
682
645
  const urlToUse = retryCount === 0 ? urlsToTry[0] : urlsToTry[retryCount % urlsToTry.length];
683
646
  logger(`tryAutoLoginIfNeeded: Refreshing ${urlToUse} (attempt ${retryCount + 1}/${maxRetries})...`, "info");
684
-
647
+
685
648
  const initial2 = await get(urlToUse, jar, null, globalOptions).then(saveCookies(jar));
686
649
  res2 = (await ctxRef.bypassAutomation(initial2, jar)) || initial2;
687
650
  html2 = res2 && res2.data ? res2.data : "";
@@ -690,14 +653,12 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
690
653
  throw new Error("Checkpoint after API login");
691
654
  }
692
655
 
693
- // Check if HTML contains valid USER_ID
694
656
  const htmlUserID = htmlUID(html2);
695
657
  if (isValidUID(htmlUserID)) {
696
658
  logger(`tryAutoLoginIfNeeded: Found valid USER_ID in HTML from ${urlToUse}: ${htmlUserID}`, "info");
697
659
  break;
698
660
  }
699
661
 
700
- // If no valid USER_ID found, wait and retry with different URL
701
662
  if (retryCount < maxRetries - 1) {
702
663
  logger(`tryAutoLoginIfNeeded: No valid USER_ID in HTML from ${urlToUse} (attempt ${retryCount + 1}/${maxRetries}), retrying...`, "warn");
703
664
  await new Promise(resolve => setTimeout(resolve, 1000 * (retryCount + 1)));
@@ -724,7 +685,6 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
724
685
  const uid2 = getUID(cookies2);
725
686
  const htmlUserID2 = htmlUID(html2);
726
687
 
727
- // Prioritize USER_ID from HTML over cookies (more reliable)
728
688
  let finalUID = null;
729
689
  if (isValidUID(htmlUserID2)) {
730
690
  finalUID = htmlUserID2;
@@ -742,7 +702,6 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
742
702
  throw new Error("Login failed - could not get valid userID after API login. HTML may indicate session is not established.");
743
703
  }
744
704
 
745
- // Final validation: ensure HTML shows we're logged in
746
705
  if (!isValidUID(htmlUserID2)) {
747
706
  logger("tryAutoLoginIfNeeded: WARNING - HTML does not show valid USER_ID, but proceeding with cookie-based UID", "warn");
748
707
  }
@@ -752,6 +711,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
752
711
 
753
712
  function makeLogin(j, email, password, globalOptions) {
754
713
  return async function () {
714
+ if (!credentialLoginAllowed()) return;
755
715
  const u = email || config.credentials?.email;
756
716
  const p = password || config.credentials?.password;
757
717
  const tf = (globalOptions && globalOptions.twofactor) || config.credentials?.twofactor || null;
@@ -769,17 +729,10 @@ function makeLogin(j, email, password, globalOptions) {
769
729
 
770
730
  function loginHelper(appState, Cookie, email, password, globalOptions, callback) {
771
731
  try {
772
- // Each call to loginHelper() (i.e. each login()/account) gets its own,
773
- // isolated CookieJar instead of sharing one process-wide singleton.
774
- // Previously this file imported a single module-level `jar` shared by
775
- // every account logged in within the same Node process; logging in a
776
- // second account would silently overwrite/merge cookies with the first
777
- // account's session (c_user/xs swapping mid-session), which is exactly
778
- // the kind of implementation bug that produces "abnormal session" /
779
- // forced logout on Facebook's side. Session isolation now lives here.
732
+
780
733
  const jar = new CookieJar();
781
734
  const domain = ".facebook.com";
782
- // Helper to extract userID from appState input
735
+
783
736
  const extractUIDFromAppState = (appStateInput) => {
784
737
  if (!appStateInput) return null;
785
738
  let parsed = appStateInput;
@@ -801,24 +754,24 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
801
754
  let userIDFromAppState = extractUIDFromAppState(appState);
802
755
  (async () => {
803
756
  try {
804
- // [Hardened4] one live process per account (overlapping deploys / double start = "multiple sessions")
757
+
805
758
  try {
806
759
  const lk = require("../src/utils/instanceLock").acquire(userIDFromAppState);
807
760
  if (!lk.ok) {
808
761
  return callback(new Error("Another bot process is already running this account (pid " + lk.pid + "). Refusing to start a second session. Set FCA_NX_INSTANCE_LOCK=off to disable."));
809
762
  }
810
763
  } catch (_) {}
811
- // Same-IP/location guard (warn by default, FCA_NX_IP_GUARD=block to refuse).
764
+
812
765
  try {
813
766
  const ipRes = await require("../src/utils/ipGuard").checkLoginIP(require("../src/utils/request").client, userIDFromAppState);
814
767
  if (!ipRes.ok) {
815
768
  return callback(new Error("Login refused: public IP changed (" + ipRes.previous + " -> " + ipRes.ip + ") and FCA_NX_IP_GUARD=block"));
816
769
  }
817
- } catch (_) { /* never let the guard break login */ }
770
+ } catch (_) { }
818
771
  if (appState) {
819
- // Check and convert cookie to appState format
772
+
820
773
  if (Array.isArray(appState) && appState.some(c => c.name)) {
821
- // Convert name to key if needed
774
+
822
775
  appState = appState.map(c => {
823
776
  if (c.name && !c.key) {
824
777
  c.key = c.name;
@@ -827,17 +780,17 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
827
780
  return c;
828
781
  });
829
782
  } else if (typeof appState === "string") {
830
- // Try to parse as JSON first
783
+
831
784
  let parsed = appState;
832
785
  try {
833
786
  parsed = JSON.parse(appState);
834
787
  } catch { }
835
788
 
836
789
  if (Array.isArray(parsed)) {
837
- // Already parsed as array, use it
790
+
838
791
  appState = parsed;
839
792
  } else {
840
- // Parse string cookie format (key=value; key2=value2)
793
+
841
794
  const arrayAppState = [];
842
795
  appState.split(';').forEach(c => {
843
796
  const [key, value] = c.split('=');
@@ -855,7 +808,6 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
855
808
  }
856
809
  }
857
810
 
858
- // Set cookies into jar with individual domain/path
859
811
  if (Array.isArray(appState)) {
860
812
  await setJarCookies(jar, appState);
861
813
  } else {
@@ -995,32 +947,31 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
995
947
  const s = typeof body === "string" ? body : String(body ?? "");
996
948
  return s.match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s.match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
997
949
  };
998
- // Helper to validate UID - must be a non-zero positive number string
950
+
999
951
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
1000
952
 
1001
953
  let userID = getUIDFromCookies(cookies);
1002
- // Also try to extract userID from HTML if not found in cookies
954
+
1003
955
  if (!isValidUID(userID)) {
1004
956
  userID = getUIDFromHTML(html);
1005
957
  }
1006
- // If still not found and appState was provided, use userID from appState input as fallback
958
+
1007
959
  if (!isValidUID(userID) && userIDFromAppState && isValidUID(userIDFromAppState)) {
1008
960
  userID = userIDFromAppState;
1009
961
  }
1010
- // Trigger auto-login if userID is invalid (missing or "0")
962
+
1011
963
  if (!isValidUID(userID)) {
1012
964
  logger("Invalid userID detected (missing or 0), attempting auto-login...", "warn");
1013
- // Pass hadAppStateInput=true if appState/Cookie was originally provided
965
+
1014
966
  const retried = await tryAutoLoginIfNeeded(html, cookies, globalOptions, ctx, !!(appState || Cookie), jar);
1015
967
  html = retried.html;
1016
968
  cookies = retried.cookies;
1017
969
  userID = retried.userID;
1018
-
1019
- // Validate HTML after auto-login - ensure it contains valid USER_ID
970
+
1020
971
  const htmlUserIDAfterLogin = getUIDFromHTML(html);
1021
972
  if (!isValidUID(htmlUserIDAfterLogin)) {
1022
973
  logger("After auto-login, HTML still does not contain valid USER_ID. Session may not be established.", "error");
1023
- // Try one more refresh
974
+
1024
975
  try {
1025
976
  const refreshRes = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1026
977
  const refreshedHtml = refreshRes && refreshRes.data ? refreshRes.data : "";
@@ -1036,7 +987,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1036
987
  throw new Error(`Login failed - Could not establish valid session. HTML USER_ID check failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`);
1037
988
  }
1038
989
  } else {
1039
- // Use USER_ID from HTML as it's more reliable
990
+
1040
991
  userID = htmlUserIDAfterLogin;
1041
992
  logger(`After auto-login, using USER_ID from HTML: ${userID}`, "info");
1042
993
  }
@@ -1045,61 +996,57 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1045
996
  logger(chalk.italic("😿 Session expired! Please update your appstate."), "error");
1046
997
  throw new Error("Checkpoint");
1047
998
  }
1048
-
1049
- // Final validation: ensure HTML shows we're logged in before proceeding
999
+
1050
1000
  let finalHtmlUID = getUIDFromHTML(html);
1051
1001
  if (!isValidUID(finalHtmlUID)) {
1052
- // If cookies have valid UID but HTML doesn't, try to "activate" session
1002
+
1053
1003
  if (isValidUID(userID)) {
1054
1004
  logger(`HTML shows USER_ID=${finalHtmlUID || "none"} but cookies have valid UID=${userID}. Attempting to activate session...`, "warn");
1055
-
1056
- // Try making requests to activate the session
1005
+
1057
1006
  try {
1058
- // Wait a bit first for cookies to propagate
1007
+
1059
1008
  await new Promise(resolve => setTimeout(resolve, 1000));
1060
-
1061
- // Try refreshing with m.facebook.com/home.php (mobile home page)
1009
+
1062
1010
  logger("Trying to activate session via m.facebook.com/home.php...", "info");
1063
1011
  const activateRes = await get("https://m.facebook.com/home.php", jar, null, globalOptions).then(saveCookies(jar));
1064
1012
  const activateHtml = activateRes && activateRes.data ? activateRes.data : "";
1065
1013
  const activateUID = getUIDFromHTML(activateHtml);
1066
-
1014
+
1067
1015
  if (isValidUID(activateUID)) {
1068
1016
  html = activateHtml;
1069
1017
  finalHtmlUID = activateUID;
1070
1018
  userID = activateUID;
1071
1019
  logger(`Session activated! Found valid USER_ID in HTML: ${userID}`, "info");
1072
1020
  } else {
1073
- // Try one more time with www.facebook.com/home.php after delay
1021
+
1074
1022
  await new Promise(resolve => setTimeout(resolve, 1500));
1075
1023
  logger("Trying to activate session via www.facebook.com/home.php...", "info");
1076
1024
  const activateRes2 = await get("https://www.facebook.com/home.php", jar, null, globalOptions).then(saveCookies(jar));
1077
1025
  const activateHtml2 = activateRes2 && activateRes2.data ? activateRes2.data : "";
1078
1026
  const activateUID2 = getUIDFromHTML(activateHtml2);
1079
-
1027
+
1080
1028
  if (isValidUID(activateUID2)) {
1081
1029
  html = activateHtml2;
1082
1030
  finalHtmlUID = activateUID2;
1083
1031
  userID = activateUID2;
1084
1032
  logger(`Session activated on second try! Found valid USER_ID in HTML: ${userID}`, "info");
1085
1033
  } else {
1086
- // If cookies have valid UID, we can proceed with cookie-based UID but warn
1034
+
1087
1035
  logger(`WARNING: HTML still shows USER_ID=${finalHtmlUID || "none"} but cookies have valid UID=${userID}. Proceeding with cookie-based UID.`, "warn");
1088
- // Don't throw error, proceed with cookie-based UID
1036
+
1089
1037
  }
1090
1038
  }
1091
1039
  } catch (activateErr) {
1092
1040
  logger(`Failed to activate session: ${activateErr && activateErr.message ? activateErr.message : String(activateErr)}. Proceeding with cookie-based UID.`, "warn");
1093
- // Don't throw error, proceed with cookie-based UID
1041
+
1094
1042
  }
1095
1043
  } else {
1096
- // No valid UID in either cookies or HTML
1044
+
1097
1045
  logger(`Final HTML validation failed - USER_ID from HTML: ${finalHtmlUID || "none"}, from cookies: ${userID || "none"}`, "error");
1098
1046
  throw new Error("Login validation failed - HTML does not contain valid USER_ID. Session may not be properly established.");
1099
1047
  }
1100
1048
  }
1101
-
1102
- // Final check: ensure we have a valid userID (either from HTML or cookies)
1049
+
1103
1050
  if (!isValidUID(userID)) {
1104
1051
  logger(`No valid USER_ID found - HTML: ${finalHtmlUID || "none"}, Cookies: ${userID || "none"}`, "error");
1105
1052
  throw new Error("Login validation failed - No valid USER_ID found in HTML or cookies.");
@@ -1126,15 +1073,14 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1126
1073
  const info = JSON.parse(userDataMatch[1]);
1127
1074
  logger(`✅ Logged in as: ${info.NAME} (${info.USER_ID})`, "info");
1128
1075
 
1129
- // Check if Facebook response shows USER_ID = 0 (session dead)
1130
1076
  if (!isValidUID(info.USER_ID)) {
1131
1077
  logger("Facebook response shows invalid USER_ID (0 or empty), session is dead!", "warn");
1132
- // Force trigger auto-login
1078
+
1133
1079
  const retried = await tryAutoLoginIfNeeded(html, cookies, globalOptions, ctx, !!(appState || Cookie), jar);
1134
1080
  html = retried.html;
1135
1081
  cookies = retried.cookies;
1136
1082
  userID = retried.userID;
1137
- // Re-check after auto-login
1083
+
1138
1084
  if (!isValidUID(userID)) {
1139
1085
  throw new Error("Auto-login failed - could not get valid userID");
1140
1086
  }
@@ -1143,11 +1089,11 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1143
1089
  logger(`ID người dùng: ${userID}`, "info");
1144
1090
  }
1145
1091
  } catch (userDataErr) {
1146
- // If error is from our validation, rethrow it
1092
+
1147
1093
  if (userDataErr && userDataErr.message && userDataErr.message.includes("Auto-login failed")) {
1148
1094
  throw userDataErr;
1149
1095
  }
1150
- // Otherwise ignore parsing errors
1096
+
1151
1097
  }
1152
1098
  const tokenMatch = html.match(/DTSGInitialData.*?token":"(.*?)"/);
1153
1099
  if (tokenMatch) fb_dtsg = tokenMatch[1];
@@ -1166,10 +1112,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1166
1112
  }
1167
1113
  })
1168
1114
  .catch(function (error) {
1169
- // Silently handle database errors - they're not critical for login
1115
+
1170
1116
  const errorMsg = error && error.message ? error.message : String(error);
1171
1117
  if (!errorMsg.includes("No Sequelize instance passed")) {
1172
- // Only log non-Sequelize instance errors
1118
+
1173
1119
  logger(`Database connection failed: ${errorMsg}`, "warn");
1174
1120
  }
1175
1121
  });
@@ -1190,7 +1136,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1190
1136
  firstListen: true,
1191
1137
  fb_dtsg,
1192
1138
  clientID: ((Math.random() * 2147483648) | 0).toString(16),
1193
- // [Hardened5] never leave mqtt device id empty - empty rotates badly across reconnects
1139
+
1194
1140
  clientId: getFrom(html, '["MqttWebDeviceID",[],{"clientID":"', '"}') || ((""+Math.random()).slice(2)+Date.now().toString(16)).slice(0, 16),
1195
1141
  wsReqNumber: 0,
1196
1142
  wsTaskNumber: 0,
@@ -1201,18 +1147,9 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1201
1147
  ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1202
1148
  ctxMain.performAutoLogin = async () => {
1203
1149
  try {
1204
- // [Fixed by xalman] First check whether the existing cookie session is actually
1205
- // still usable. A checkpoint/redirect seen on one request
1206
- // doesn't always mean the whole session is dead (transient FB
1207
- // blips, rate limiting, etc). Cookie/appstate-only logins have
1208
- // no email+password to re-login with, so without this check a
1209
- // single false-positive checkpoint would permanently tear down
1210
- // the bot (via emitAuth) and force a brand new cookie every
1211
- // time instead of just continuing on the still-good session.
1150
+
1212
1151
  try {
1213
- // [Fixed by xalman] retry up to 3x - a transient network
1214
- // hiccup during THIS check alone used to be treated the same
1215
- // as a dead session and fall through to requiring credentials.
1152
+
1216
1153
  let stillCheckpointed = true;
1217
1154
  let uid = null;
1218
1155
  for (let attempt = 0; attempt < 3 && !uid; attempt++) {
@@ -1226,8 +1163,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1226
1163
  break;
1227
1164
  }
1228
1165
  } catch {
1229
- // network hiccup on this attempt - retry below instead of
1230
- // immediately assuming the session is dead
1166
+
1231
1167
  }
1232
1168
  if (!uid && attempt < 2) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
1233
1169
  }
@@ -1236,17 +1172,18 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1236
1172
  return true;
1237
1173
  }
1238
1174
  } catch {
1239
- // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1175
+
1240
1176
  }
1241
1177
 
1178
+ if (!credentialLoginAllowed()) {
1179
+ logger("performAutoLogin: cookie session invalid and credential login is disabled (6.8.7). Not logging in with password; replace the appstate.", "error");
1180
+ return false;
1181
+ }
1242
1182
  const u = config.credentials?.email || email;
1243
1183
  const p = config.credentials?.password || password;
1244
1184
  const tf = globalOptions.twofactor || config.credentials?.twofactor || null;
1245
1185
  if (!u || !p) return false;
1246
- // [Hardened4] Repeated credential logins are a classic trigger for "automated
1247
- // behaviour"/"multiple sessions" restrictions. At most one per cooldown window
1248
- // (FCA_NX_RELOGIN_COOLDOWN_MIN, default 30), and never while Facebook is showing
1249
- // its scraping warning - re-logging in then only makes it worse.
1186
+
1250
1187
  const cdMs = (Number(process.env.FCA_NX_RELOGIN_COOLDOWN_MIN) || 30) * 60 * 1000;
1251
1188
  const sinceLast = Date.now() - (global.__fcaLastCredLogin || 0);
1252
1189
  if (sinceLast < cdMs) {
@@ -1287,7 +1224,6 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1287
1224
  };
1288
1225
  const defaultFuncs = makeDefaults(html, userID, ctxMain);
1289
1226
 
1290
- // Attach lightweight DB updaters for realtime events (MQTT)
1291
1227
  try {
1292
1228
  const Thread = models && models.Thread;
1293
1229
  if (!Thread) {
@@ -1298,7 +1234,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1298
1234
  try {
1299
1235
  if (!msg || !msg.threadID) return;
1300
1236
  const id = String(msg.threadID);
1301
- // Fast path: increment messageCount column directly
1237
+
1302
1238
  let affected = 0;
1303
1239
  try {
1304
1240
  const res = await Thread.increment("messageCount", { by: 1, where: { threadID: id } });
@@ -1306,14 +1242,14 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1306
1242
  affected = res[0];
1307
1243
  }
1308
1244
  } catch {
1309
- // Ignore increment errors, we'll try to create below
1245
+
1310
1246
  }
1311
- // If no row was updated, ensure a row exists
1247
+
1312
1248
  if (!affected) {
1313
1249
  try {
1314
1250
  await Thread.create({ threadID: id, messageCount: 1, data: { threadID: id } });
1315
1251
  } catch {
1316
- // Ignore create races / duplicates
1252
+
1317
1253
  }
1318
1254
  }
1319
1255
  } catch (e) {
@@ -1322,10 +1258,9 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1322
1258
  }
1323
1259
  };
1324
1260
  } catch {
1325
- // If DB layer is unavailable, skip realtime thread updates
1261
+
1326
1262
  }
1327
1263
 
1328
- // Attach remote control client if enabled in config
1329
1264
  let remote = null;
1330
1265
  try {
1331
1266
  if (config && config.remoteControl && config.remoteControl.enabled) {
@@ -1375,7 +1310,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1375
1310
  api.listen = api.listenMqtt;
1376
1311
  }
1377
1312
  if (api.refreshFb_dtsg) {
1378
- // [Hardened] refresh fb_dtsg every 6h (was 24h) to prevent token-expiry logouts
1313
+
1379
1314
  setInterval(function () {
1380
1315
  api.refreshFb_dtsg().then(function () {
1381
1316
  logger("Successfully refreshed fb_dtsg");
@@ -1384,7 +1319,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1384
1319
  });
1385
1320
  }, 6 * 60 * 60 * 1000);
1386
1321
  }
1387
- // ✅ fca-nx core features register
1322
+
1388
1323
  try {
1389
1324
  if (!e2eeEnabled()) {
1390
1325
  logger("E2EE off. Set \"e2ee\": true in config.json or fca-config.json to connect secret chats.", "info");
@@ -1429,7 +1364,6 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1429
1364
  logger(`sendBroadcast init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1430
1365
  }
1431
1366
 
1432
- // sendMessage override with fca-nx version (better MQTT + HTTP fallback)
1433
1367
  try {
1434
1368
  const fcanxSendMsg = require("../src/api/socket/sendMessage")(defaultFuncs, api, ctxMain);
1435
1369
  api.sendMessage = fcanxSendMsg;
@@ -1440,13 +1374,9 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1440
1374
  logger(`sendMessage fca-nx override failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1441
1375
  }
1442
1376
 
1443
- // listenMqtt override with fca-nx version (better MQTT stability)
1444
1377
  try {
1445
1378
  const stableListenMqtt = require("../src/api/socket/listenMqtt")(defaultFuncs, api, ctxMain);
1446
- // Keep the raw MQTT listener behind the combined listener. The
1447
- // E2EE bridge is installed above, but replacing api.listenMqtt here
1448
- // used to silently discard it, so only group messages arriving over
1449
- // plain MQTT reached bot handlers.
1379
+
1450
1380
  api._listenMqttRaw = stableListenMqtt;
1451
1381
  if (e2eeEnabled() && typeof api.listenE2EE === "function") {
1452
1382
  api.listenMqtt = api.listen = api.listenE2EE;
@@ -1477,5 +1407,6 @@ module.exports.loginHelper = loginHelper;
1477
1407
  module.exports.tokensViaAPI = tokensViaAPI;
1478
1408
  module.exports.loginViaAPI = loginViaAPI;
1479
1409
  module.exports.tokens = tokens;
1410
+ module.exports.credentialLoginAllowed = credentialLoginAllowed;
1480
1411
  module.exports.normalizeCookieHeaderString = normalizeCookieHeaderString;
1481
1412
  module.exports.setJarFromPairs = setJarFromPairs;