fca-nx 6.8.5 → 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 +3 -5
  5. package/module/login.js +10 -38
  6. package/module/loginHelper.js +121 -206
  7. package/module/options.js +1 -7
  8. package/package.json +3 -3
  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 +9 -8
  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
@@ -12,6 +12,34 @@ const { getFrom } = require("../src/utils/constants");
12
12
  const { loadConfig } = require("./config");
13
13
  const { createRemoteClient } = require("../src/remote/remoteClient");
14
14
  const { config } = loadConfig();
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
+
28
+ function e2eeEnabled() {
29
+ const on = (v) => v === true || v === "true";
30
+ const off = (v) => v === false || v === "false";
31
+ try {
32
+ const botPath = path.join(process.cwd(), "config.json");
33
+ if (fs.existsSync(botPath)) {
34
+ const bot = JSON.parse(fs.readFileSync(botPath, "utf8"));
35
+ if (bot && Object.prototype.hasOwnProperty.call(bot, "e2ee")) {
36
+ return on(bot.e2ee);
37
+ }
38
+ }
39
+ } catch (_) {}
40
+ if (off(config.e2ee)) return false;
41
+ return on(config.e2ee);
42
+ }
15
43
  const axiosBase = require("axios");
16
44
  const regions = [
17
45
  { code: "PRN", name: "Pacific Northwest Region", location: "Khu vực Tây Bắc Thái Bình Dương" },
@@ -50,23 +78,9 @@ function mask(s, keep = 3) {
50
78
  return n <= keep ? "*".repeat(n) : s.slice(0, keep) + "*".repeat(Math.max(0, n - keep));
51
79
  }
52
80
 
53
- /**
54
- * Login via external API endpoint (iOS method)
55
- * @param {string} email - Email hoặc số điện thoại
56
- * @param {string} password - Mật khẩu
57
- * @param {string|null} twoFactor - Secret Base32 cho 2FA (không phải mã 6 số)
58
- * @param {string|null} apiBaseUrl - Base URL của API server (không có mặc định — phải chỉ định rõ ràng)
59
- * @param {string|null} apiKey - API key để xác thực (x-api-key header)
60
- * @returns {Promise<{ok: boolean, uid?: string, access_token?: string, cookies?: Array, cookie?: string, message?: string}>}
61
- */
62
81
  async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null, apiKey = null) {
63
82
  try {
64
- // SECURITY: do not default to a hard-coded third-party domain. Sending
65
- // a plaintext Facebook email/password to an external server should
66
- // require the operator to explicitly opt in (via config.apiServer or
67
- // the apiBaseUrl argument) rather than happening silently the first
68
- // time someone logs in with email+password. If no server is configured,
69
- // fail loudly instead of guessing where to send credentials.
83
+
70
84
  const baseUrl = apiBaseUrl || config.apiServer || null;
71
85
  if (!baseUrl) {
72
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.";
@@ -77,25 +91,21 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
77
91
  const endpoint = `${baseUrl}/api/v1/facebook/login_ios`;
78
92
  const xApiKey = apiKey || config.apiKey || null;
79
93
 
80
- // Build request body
81
94
  const body = {
82
95
  email,
83
96
  password
84
97
  };
85
98
 
86
- // Only include twoFactor if provided (must be Base32 secret, not 6-digit code)
87
99
  if (twoFactor && typeof twoFactor === "string" && twoFactor.trim()) {
88
- // Clean up the secret - remove spaces and convert to uppercase
100
+
89
101
  body.twoFactor = twoFactor.replace(/\s+/g, "").toUpperCase();
90
102
  }
91
103
 
92
- // Build headers
93
104
  const headers = {
94
105
  "Content-Type": "application/json",
95
106
  "Accept": "application/json"
96
107
  };
97
108
 
98
- // Add x-api-key header if provided
99
109
  if (xApiKey) {
100
110
  headers["x-api-key"] = xApiKey;
101
111
  }
@@ -113,13 +123,11 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
113
123
  if (response.status === 200 && response.data) {
114
124
  const data = response.data;
115
125
 
116
- // Check if login was successful
117
126
  if (data.error) {
118
127
  logger(chalk.italic(`❌ API-LOGIN: Login failed - ${data.error}`), "error");
119
128
  return { ok: false, message: data.error };
120
129
  }
121
130
 
122
- // Extract response data
123
131
  const uid = data.uid || data.user_id || data.userId || null;
124
132
  const accessToken = data.access_token || data.accessToken || null;
125
133
  const cookie = data.cookie || data.cookies || null;
@@ -131,10 +139,9 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
131
139
 
132
140
  logger(chalk.italic(`✅ API-LOGIN: Login successful for UID: ${uid || "unknown"}`), "info");
133
141
 
134
- // Parse cookies if provided as string
135
142
  let cookies = [];
136
143
  if (typeof cookie === "string") {
137
- // Parse cookie string format: "key1=value1; key2=value2"
144
+
138
145
  const pairs = cookie.split(";").map(p => p.trim()).filter(Boolean);
139
146
  for (const pair of pairs) {
140
147
  const eq = pair.indexOf("=");
@@ -150,7 +157,7 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
150
157
  }
151
158
  }
152
159
  } else if (Array.isArray(cookie)) {
153
- // Already in array format
160
+
154
161
  cookies = cookie.map(c => ({
155
162
  key: c.key || c.name,
156
163
  value: c.value,
@@ -168,7 +175,6 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
168
175
  };
169
176
  }
170
177
 
171
- // Handle error responses
172
178
  const errorMsg = response.data && response.data.error
173
179
  ? response.data.error
174
180
  : response.data && response.data.message
@@ -185,14 +191,6 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
185
191
  }
186
192
  }
187
193
 
188
- /**
189
- * High-level login function that uses the API endpoint
190
- * @param {string} email - Email hoặc số điện thoại
191
- * @param {string} password - Mật khẩu
192
- * @param {string|null} twoFactor - Secret Base32 cho 2FA (không phải mã 6 số)
193
- * @param {string|null} apiBaseUrl - Base URL của API server
194
- * @returns {Promise<{status: boolean, cookies?: Array, uid?: string, access_token?: string, message?: string}>}
195
- */
196
194
  async function tokensViaAPI(email, password, twoFactor = null, apiBaseUrl = null) {
197
195
  const t0 = process.hrtime.bigint();
198
196
 
@@ -244,7 +242,7 @@ function normalizeCookieHeaderString(s) {
244
242
 
245
243
  function setJarFromPairs(j, pairs, domain) {
246
244
  const expires = new Date(Date.now() + 31536e6).toUTCString();
247
- // URLs to set cookies for - include both desktop and mobile versions
245
+
248
246
  const urls = [
249
247
  "https://www.facebook.com",
250
248
  "https://facebook.com",
@@ -253,10 +251,10 @@ function setJarFromPairs(j, pairs, domain) {
253
251
  "http://facebook.com",
254
252
  "http://m.facebook.com"
255
253
  ];
256
-
254
+
257
255
  for (const kv of pairs) {
258
256
  const cookieStr = `${kv}; expires=${expires}; domain=${domain}; path=/;`;
259
- // Set cookie for all URLs to ensure it works on both desktop and mobile
257
+
260
258
  for (const url of urls) {
261
259
  try {
262
260
  if (typeof j.setCookieSync === "function") {
@@ -265,8 +263,7 @@ function setJarFromPairs(j, pairs, domain) {
265
263
  j.setCookie(cookieStr, url);
266
264
  }
267
265
  } catch (err) {
268
- // Silently ignore domain mismatch errors
269
- // These can happen when setting cookies across different subdomains
266
+
270
267
  }
271
268
  }
272
269
  }
@@ -300,7 +297,6 @@ function getBackupModel() {
300
297
  if (!models || !models.sequelize || !models.Sequelize) return null;
301
298
  const sequelize = models.sequelize;
302
299
 
303
- // Validate that sequelize is a proper Sequelize instance
304
300
  if (!sequelize || typeof sequelize.define !== "function") return null;
305
301
 
306
302
  const { DataTypes } = models.Sequelize;
@@ -321,12 +317,12 @@ function getBackupModel() {
321
317
  );
322
318
  return AppStateBackup;
323
319
  } catch (defineError) {
324
- // If define fails, log and return null
320
+
325
321
  logger(`Failed to define AppStateBackup model: ${defineError && defineError.message ? defineError.message : String(defineError)}`, "warn");
326
322
  return null;
327
323
  }
328
324
  } catch (e) {
329
- // Silently handle any errors in getBackupModel
325
+
330
326
  return null;
331
327
  }
332
328
  }
@@ -391,8 +387,6 @@ async function getLatestBackupAny(type) {
391
387
  }
392
388
  }
393
389
 
394
-
395
-
396
390
  async function setJarCookies(j, appstate) {
397
391
  const tasks = [];
398
392
  for (const c of appstate) {
@@ -404,13 +398,11 @@ async function setJarCookies(j, appstate) {
404
398
  const cookiePath = c.path || "/";
405
399
  const dom = cookieDomain.replace(/^\./, "");
406
400
 
407
- // Handle expirationDate (can be in seconds or milliseconds)
408
401
  let expiresStr = "";
409
402
  if (c.expirationDate !== undefined) {
410
403
  let expiresDate;
411
404
  if (typeof c.expirationDate === "number") {
412
- // If expirationDate is less than a year from now in seconds, treat as seconds
413
- // Otherwise treat as milliseconds
405
+
414
406
  const now = Date.now();
415
407
  const oneYearInMs = 365 * 24 * 60 * 60 * 1000;
416
408
  if (c.expirationDate < (now + oneYearInMs) / 1000) {
@@ -427,24 +419,20 @@ async function setJarCookies(j, appstate) {
427
419
  expiresStr = `; expires=${expiresDate.toUTCString()}`;
428
420
  }
429
421
 
430
- // Helper function to build cookie string
431
422
  const buildCookieString = (domainOverride = null) => {
432
423
  const domain = domainOverride || cookieDomain;
433
424
  let cookieParts = [`${cookieName}=${cookieValue}${expiresStr}`];
434
425
  cookieParts.push(`Domain=${domain}`);
435
426
  cookieParts.push(`Path=${cookiePath}`);
436
427
 
437
- // Add Secure flag if secure is true
438
428
  if (c.secure === true) {
439
429
  cookieParts.push("Secure");
440
430
  }
441
431
 
442
- // Add HttpOnly flag if httpOnly is true
443
432
  if (c.httpOnly === true) {
444
433
  cookieParts.push("HttpOnly");
445
434
  }
446
435
 
447
- // Add SameSite attribute if provided
448
436
  if (c.sameSite) {
449
437
  const sameSiteValue = String(c.sameSite).toLowerCase();
450
438
  if (["strict", "lax", "none"].includes(sameSiteValue)) {
@@ -479,7 +467,6 @@ async function setJarCookies(j, appstate) {
479
467
  await Promise.all(tasks);
480
468
  }
481
469
 
482
- // tokens function - alias to tokensViaAPI for backward compatibility
483
470
  async function tokens(username, password, twofactor = null) {
484
471
  return tokensViaAPI(username, password, twofactor);
485
472
  }
@@ -520,7 +507,10 @@ async function hydrateJarFromDB(userID, jar) {
520
507
  }
521
508
 
522
509
  async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions, ctxRef, hadAppStateInput = false, jar) {
523
- // 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
+
524
514
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
525
515
 
526
516
  const getUID = cs =>
@@ -534,19 +524,17 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
534
524
  };
535
525
 
536
526
  let userID = getUID(currentCookies);
537
- // Also try to extract userID from HTML if cookie userID is invalid
527
+
538
528
  if (!isValidUID(userID)) {
539
529
  userID = htmlUID(currentHtml);
540
530
  }
541
- // If we have a valid userID, return success
531
+
542
532
  if (isValidUID(userID)) {
543
533
  return { html: currentHtml, cookies: currentCookies, userID };
544
534
  }
545
535
 
546
- // No valid userID found - need to try auto-login
547
536
  logger("tryAutoLoginIfNeeded: No valid userID found, attempting recovery...", "warn");
548
537
 
549
- // If appState/Cookie was provided and is not checkpointed, try refresh
550
538
  if (hadAppStateInput) {
551
539
  const isCheckpoint = currentHtml.includes("/checkpoint/block/?next");
552
540
  if (!isCheckpoint) {
@@ -560,7 +548,6 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
560
548
  }
561
549
  }
562
550
 
563
- // Try to hydrate from DB backup
564
551
  const hydrated = await hydrateJarFromDB(null, jar);
565
552
  if (hydrated) {
566
553
  logger("tryAutoLoginIfNeeded: Trying backup from DB...", "info");
@@ -583,12 +570,10 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
583
570
  }
584
571
  }
585
572
 
586
- // Check if auto-login is enabled (support both true and "true")
587
573
  if (config.autoLogin === false || config.autoLogin === "false") {
588
574
  throw new Error("AppState expired — Auto-login is disabled");
589
575
  }
590
576
 
591
- // Try API login
592
577
  const u = config.credentials?.email || config.email;
593
578
  const p = config.credentials?.password || config.password;
594
579
  const tf = (globalOptions && globalOptions.twofactor) || config.credentials?.twofactor || config.twofactor || null;
@@ -607,28 +592,25 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
607
592
 
608
593
  logger(`tryAutoLoginIfNeeded: API login successful! UID: ${r.uid}`, "info");
609
594
 
610
- // Handle cookies - can be array, cookie string header, or both
611
595
  let cookiePairs = [];
612
-
613
- // If cookies is a string (cookie header format), parse it
596
+
614
597
  if (typeof r.cookies === "string") {
615
598
  cookiePairs = normalizeCookieHeaderString(r.cookies);
616
- }
617
- // If cookies is an array, convert to pairs
599
+ }
600
+
618
601
  else if (Array.isArray(r.cookies)) {
619
602
  cookiePairs = r.cookies.map(c => {
620
603
  if (typeof c === "string") {
621
- // Already in "key=value" format
604
+
622
605
  return c;
623
606
  } else if (c && typeof c === "object") {
624
- // Object format {key, value} or {name, value}
607
+
625
608
  return `${c.key || c.name}=${c.value}`;
626
609
  }
627
610
  return null;
628
611
  }).filter(Boolean);
629
612
  }
630
-
631
- // Also check for cookie field (alternative field name)
613
+
632
614
  if (cookiePairs.length === 0 && r.cookie) {
633
615
  if (typeof r.cookie === "string") {
634
616
  cookiePairs = normalizeCookieHeaderString(r.cookie);
@@ -649,11 +631,8 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
649
631
  setJarFromPairs(jar, cookiePairs, ".facebook.com");
650
632
  }
651
633
 
652
- // Wait a bit for cookies to be set
653
634
  await new Promise(resolve => setTimeout(resolve, 500));
654
635
 
655
- // Refresh Facebook page with new cookies - try multiple times if needed
656
- // Try both www.facebook.com and m.facebook.com to ensure session is established
657
636
  let html2 = "";
658
637
  let res2 = null;
659
638
  let retryCount = 0;
@@ -662,10 +641,10 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
662
641
 
663
642
  while (retryCount < maxRetries) {
664
643
  try {
665
- // Try m.facebook.com first (mobile version often works better for API login)
644
+
666
645
  const urlToUse = retryCount === 0 ? urlsToTry[0] : urlsToTry[retryCount % urlsToTry.length];
667
646
  logger(`tryAutoLoginIfNeeded: Refreshing ${urlToUse} (attempt ${retryCount + 1}/${maxRetries})...`, "info");
668
-
647
+
669
648
  const initial2 = await get(urlToUse, jar, null, globalOptions).then(saveCookies(jar));
670
649
  res2 = (await ctxRef.bypassAutomation(initial2, jar)) || initial2;
671
650
  html2 = res2 && res2.data ? res2.data : "";
@@ -674,14 +653,12 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
674
653
  throw new Error("Checkpoint after API login");
675
654
  }
676
655
 
677
- // Check if HTML contains valid USER_ID
678
656
  const htmlUserID = htmlUID(html2);
679
657
  if (isValidUID(htmlUserID)) {
680
658
  logger(`tryAutoLoginIfNeeded: Found valid USER_ID in HTML from ${urlToUse}: ${htmlUserID}`, "info");
681
659
  break;
682
660
  }
683
661
 
684
- // If no valid USER_ID found, wait and retry with different URL
685
662
  if (retryCount < maxRetries - 1) {
686
663
  logger(`tryAutoLoginIfNeeded: No valid USER_ID in HTML from ${urlToUse} (attempt ${retryCount + 1}/${maxRetries}), retrying...`, "warn");
687
664
  await new Promise(resolve => setTimeout(resolve, 1000 * (retryCount + 1)));
@@ -708,7 +685,6 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
708
685
  const uid2 = getUID(cookies2);
709
686
  const htmlUserID2 = htmlUID(html2);
710
687
 
711
- // Prioritize USER_ID from HTML over cookies (more reliable)
712
688
  let finalUID = null;
713
689
  if (isValidUID(htmlUserID2)) {
714
690
  finalUID = htmlUserID2;
@@ -726,7 +702,6 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
726
702
  throw new Error("Login failed - could not get valid userID after API login. HTML may indicate session is not established.");
727
703
  }
728
704
 
729
- // Final validation: ensure HTML shows we're logged in
730
705
  if (!isValidUID(htmlUserID2)) {
731
706
  logger("tryAutoLoginIfNeeded: WARNING - HTML does not show valid USER_ID, but proceeding with cookie-based UID", "warn");
732
707
  }
@@ -736,6 +711,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
736
711
 
737
712
  function makeLogin(j, email, password, globalOptions) {
738
713
  return async function () {
714
+ if (!credentialLoginAllowed()) return;
739
715
  const u = email || config.credentials?.email;
740
716
  const p = password || config.credentials?.password;
741
717
  const tf = (globalOptions && globalOptions.twofactor) || config.credentials?.twofactor || null;
@@ -753,17 +729,10 @@ function makeLogin(j, email, password, globalOptions) {
753
729
 
754
730
  function loginHelper(appState, Cookie, email, password, globalOptions, callback) {
755
731
  try {
756
- // Each call to loginHelper() (i.e. each login()/account) gets its own,
757
- // isolated CookieJar instead of sharing one process-wide singleton.
758
- // Previously this file imported a single module-level `jar` shared by
759
- // every account logged in within the same Node process; logging in a
760
- // second account would silently overwrite/merge cookies with the first
761
- // account's session (c_user/xs swapping mid-session), which is exactly
762
- // the kind of implementation bug that produces "abnormal session" /
763
- // forced logout on Facebook's side. Session isolation now lives here.
732
+
764
733
  const jar = new CookieJar();
765
734
  const domain = ".facebook.com";
766
- // Helper to extract userID from appState input
735
+
767
736
  const extractUIDFromAppState = (appStateInput) => {
768
737
  if (!appStateInput) return null;
769
738
  let parsed = appStateInput;
@@ -785,24 +754,24 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
785
754
  let userIDFromAppState = extractUIDFromAppState(appState);
786
755
  (async () => {
787
756
  try {
788
- // [Hardened4] one live process per account (overlapping deploys / double start = "multiple sessions")
757
+
789
758
  try {
790
759
  const lk = require("../src/utils/instanceLock").acquire(userIDFromAppState);
791
760
  if (!lk.ok) {
792
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."));
793
762
  }
794
763
  } catch (_) {}
795
- // Same-IP/location guard (warn by default, FCA_NX_IP_GUARD=block to refuse).
764
+
796
765
  try {
797
766
  const ipRes = await require("../src/utils/ipGuard").checkLoginIP(require("../src/utils/request").client, userIDFromAppState);
798
767
  if (!ipRes.ok) {
799
768
  return callback(new Error("Login refused: public IP changed (" + ipRes.previous + " -> " + ipRes.ip + ") and FCA_NX_IP_GUARD=block"));
800
769
  }
801
- } catch (_) { /* never let the guard break login */ }
770
+ } catch (_) { }
802
771
  if (appState) {
803
- // Check and convert cookie to appState format
772
+
804
773
  if (Array.isArray(appState) && appState.some(c => c.name)) {
805
- // Convert name to key if needed
774
+
806
775
  appState = appState.map(c => {
807
776
  if (c.name && !c.key) {
808
777
  c.key = c.name;
@@ -811,17 +780,17 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
811
780
  return c;
812
781
  });
813
782
  } else if (typeof appState === "string") {
814
- // Try to parse as JSON first
783
+
815
784
  let parsed = appState;
816
785
  try {
817
786
  parsed = JSON.parse(appState);
818
787
  } catch { }
819
788
 
820
789
  if (Array.isArray(parsed)) {
821
- // Already parsed as array, use it
790
+
822
791
  appState = parsed;
823
792
  } else {
824
- // Parse string cookie format (key=value; key2=value2)
793
+
825
794
  const arrayAppState = [];
826
795
  appState.split(';').forEach(c => {
827
796
  const [key, value] = c.split('=');
@@ -839,7 +808,6 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
839
808
  }
840
809
  }
841
810
 
842
- // Set cookies into jar with individual domain/path
843
811
  if (Array.isArray(appState)) {
844
812
  await setJarCookies(jar, appState);
845
813
  } else {
@@ -979,32 +947,31 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
979
947
  const s = typeof body === "string" ? body : String(body ?? "");
980
948
  return s.match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s.match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
981
949
  };
982
- // Helper to validate UID - must be a non-zero positive number string
950
+
983
951
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
984
952
 
985
953
  let userID = getUIDFromCookies(cookies);
986
- // Also try to extract userID from HTML if not found in cookies
954
+
987
955
  if (!isValidUID(userID)) {
988
956
  userID = getUIDFromHTML(html);
989
957
  }
990
- // If still not found and appState was provided, use userID from appState input as fallback
958
+
991
959
  if (!isValidUID(userID) && userIDFromAppState && isValidUID(userIDFromAppState)) {
992
960
  userID = userIDFromAppState;
993
961
  }
994
- // Trigger auto-login if userID is invalid (missing or "0")
962
+
995
963
  if (!isValidUID(userID)) {
996
964
  logger("Invalid userID detected (missing or 0), attempting auto-login...", "warn");
997
- // Pass hadAppStateInput=true if appState/Cookie was originally provided
965
+
998
966
  const retried = await tryAutoLoginIfNeeded(html, cookies, globalOptions, ctx, !!(appState || Cookie), jar);
999
967
  html = retried.html;
1000
968
  cookies = retried.cookies;
1001
969
  userID = retried.userID;
1002
-
1003
- // Validate HTML after auto-login - ensure it contains valid USER_ID
970
+
1004
971
  const htmlUserIDAfterLogin = getUIDFromHTML(html);
1005
972
  if (!isValidUID(htmlUserIDAfterLogin)) {
1006
973
  logger("After auto-login, HTML still does not contain valid USER_ID. Session may not be established.", "error");
1007
- // Try one more refresh
974
+
1008
975
  try {
1009
976
  const refreshRes = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1010
977
  const refreshedHtml = refreshRes && refreshRes.data ? refreshRes.data : "";
@@ -1020,7 +987,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1020
987
  throw new Error(`Login failed - Could not establish valid session. HTML USER_ID check failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`);
1021
988
  }
1022
989
  } else {
1023
- // Use USER_ID from HTML as it's more reliable
990
+
1024
991
  userID = htmlUserIDAfterLogin;
1025
992
  logger(`After auto-login, using USER_ID from HTML: ${userID}`, "info");
1026
993
  }
@@ -1029,61 +996,57 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1029
996
  logger(chalk.italic("😿 Session expired! Please update your appstate."), "error");
1030
997
  throw new Error("Checkpoint");
1031
998
  }
1032
-
1033
- // Final validation: ensure HTML shows we're logged in before proceeding
999
+
1034
1000
  let finalHtmlUID = getUIDFromHTML(html);
1035
1001
  if (!isValidUID(finalHtmlUID)) {
1036
- // If cookies have valid UID but HTML doesn't, try to "activate" session
1002
+
1037
1003
  if (isValidUID(userID)) {
1038
1004
  logger(`HTML shows USER_ID=${finalHtmlUID || "none"} but cookies have valid UID=${userID}. Attempting to activate session...`, "warn");
1039
-
1040
- // Try making requests to activate the session
1005
+
1041
1006
  try {
1042
- // Wait a bit first for cookies to propagate
1007
+
1043
1008
  await new Promise(resolve => setTimeout(resolve, 1000));
1044
-
1045
- // Try refreshing with m.facebook.com/home.php (mobile home page)
1009
+
1046
1010
  logger("Trying to activate session via m.facebook.com/home.php...", "info");
1047
1011
  const activateRes = await get("https://m.facebook.com/home.php", jar, null, globalOptions).then(saveCookies(jar));
1048
1012
  const activateHtml = activateRes && activateRes.data ? activateRes.data : "";
1049
1013
  const activateUID = getUIDFromHTML(activateHtml);
1050
-
1014
+
1051
1015
  if (isValidUID(activateUID)) {
1052
1016
  html = activateHtml;
1053
1017
  finalHtmlUID = activateUID;
1054
1018
  userID = activateUID;
1055
1019
  logger(`Session activated! Found valid USER_ID in HTML: ${userID}`, "info");
1056
1020
  } else {
1057
- // Try one more time with www.facebook.com/home.php after delay
1021
+
1058
1022
  await new Promise(resolve => setTimeout(resolve, 1500));
1059
1023
  logger("Trying to activate session via www.facebook.com/home.php...", "info");
1060
1024
  const activateRes2 = await get("https://www.facebook.com/home.php", jar, null, globalOptions).then(saveCookies(jar));
1061
1025
  const activateHtml2 = activateRes2 && activateRes2.data ? activateRes2.data : "";
1062
1026
  const activateUID2 = getUIDFromHTML(activateHtml2);
1063
-
1027
+
1064
1028
  if (isValidUID(activateUID2)) {
1065
1029
  html = activateHtml2;
1066
1030
  finalHtmlUID = activateUID2;
1067
1031
  userID = activateUID2;
1068
1032
  logger(`Session activated on second try! Found valid USER_ID in HTML: ${userID}`, "info");
1069
1033
  } else {
1070
- // If cookies have valid UID, we can proceed with cookie-based UID but warn
1034
+
1071
1035
  logger(`WARNING: HTML still shows USER_ID=${finalHtmlUID || "none"} but cookies have valid UID=${userID}. Proceeding with cookie-based UID.`, "warn");
1072
- // Don't throw error, proceed with cookie-based UID
1036
+
1073
1037
  }
1074
1038
  }
1075
1039
  } catch (activateErr) {
1076
1040
  logger(`Failed to activate session: ${activateErr && activateErr.message ? activateErr.message : String(activateErr)}. Proceeding with cookie-based UID.`, "warn");
1077
- // Don't throw error, proceed with cookie-based UID
1041
+
1078
1042
  }
1079
1043
  } else {
1080
- // No valid UID in either cookies or HTML
1044
+
1081
1045
  logger(`Final HTML validation failed - USER_ID from HTML: ${finalHtmlUID || "none"}, from cookies: ${userID || "none"}`, "error");
1082
1046
  throw new Error("Login validation failed - HTML does not contain valid USER_ID. Session may not be properly established.");
1083
1047
  }
1084
1048
  }
1085
-
1086
- // Final check: ensure we have a valid userID (either from HTML or cookies)
1049
+
1087
1050
  if (!isValidUID(userID)) {
1088
1051
  logger(`No valid USER_ID found - HTML: ${finalHtmlUID || "none"}, Cookies: ${userID || "none"}`, "error");
1089
1052
  throw new Error("Login validation failed - No valid USER_ID found in HTML or cookies.");
@@ -1110,15 +1073,14 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1110
1073
  const info = JSON.parse(userDataMatch[1]);
1111
1074
  logger(`✅ Logged in as: ${info.NAME} (${info.USER_ID})`, "info");
1112
1075
 
1113
- // Check if Facebook response shows USER_ID = 0 (session dead)
1114
1076
  if (!isValidUID(info.USER_ID)) {
1115
1077
  logger("Facebook response shows invalid USER_ID (0 or empty), session is dead!", "warn");
1116
- // Force trigger auto-login
1078
+
1117
1079
  const retried = await tryAutoLoginIfNeeded(html, cookies, globalOptions, ctx, !!(appState || Cookie), jar);
1118
1080
  html = retried.html;
1119
1081
  cookies = retried.cookies;
1120
1082
  userID = retried.userID;
1121
- // Re-check after auto-login
1083
+
1122
1084
  if (!isValidUID(userID)) {
1123
1085
  throw new Error("Auto-login failed - could not get valid userID");
1124
1086
  }
@@ -1127,16 +1089,16 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1127
1089
  logger(`ID người dùng: ${userID}`, "info");
1128
1090
  }
1129
1091
  } catch (userDataErr) {
1130
- // If error is from our validation, rethrow it
1092
+
1131
1093
  if (userDataErr && userDataErr.message && userDataErr.message.includes("Auto-login failed")) {
1132
1094
  throw userDataErr;
1133
1095
  }
1134
- // Otherwise ignore parsing errors
1096
+
1135
1097
  }
1136
1098
  const tokenMatch = html.match(/DTSGInitialData.*?token":"(.*?)"/);
1137
1099
  if (tokenMatch) fb_dtsg = tokenMatch[1];
1138
1100
  try {
1139
- if (userID) await backupAppStateSQL(jar, userID);
1101
+ if (userID) backupAppStateSQL(jar, userID).catch(() => {});
1140
1102
  } catch { }
1141
1103
  Promise.resolve()
1142
1104
  .then(function () {
@@ -1150,10 +1112,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1150
1112
  }
1151
1113
  })
1152
1114
  .catch(function (error) {
1153
- // Silently handle database errors - they're not critical for login
1115
+
1154
1116
  const errorMsg = error && error.message ? error.message : String(error);
1155
1117
  if (!errorMsg.includes("No Sequelize instance passed")) {
1156
- // Only log non-Sequelize instance errors
1118
+
1157
1119
  logger(`Database connection failed: ${errorMsg}`, "warn");
1158
1120
  }
1159
1121
  });
@@ -1174,7 +1136,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1174
1136
  firstListen: true,
1175
1137
  fb_dtsg,
1176
1138
  clientID: ((Math.random() * 2147483648) | 0).toString(16),
1177
- // [Hardened5] never leave mqtt device id empty - empty rotates badly across reconnects
1139
+
1178
1140
  clientId: getFrom(html, '["MqttWebDeviceID",[],{"clientID":"', '"}') || ((""+Math.random()).slice(2)+Date.now().toString(16)).slice(0, 16),
1179
1141
  wsReqNumber: 0,
1180
1142
  wsTaskNumber: 0,
@@ -1185,18 +1147,9 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1185
1147
  ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1186
1148
  ctxMain.performAutoLogin = async () => {
1187
1149
  try {
1188
- // [Fixed by xalman] First check whether the existing cookie session is actually
1189
- // still usable. A checkpoint/redirect seen on one request
1190
- // doesn't always mean the whole session is dead (transient FB
1191
- // blips, rate limiting, etc). Cookie/appstate-only logins have
1192
- // no email+password to re-login with, so without this check a
1193
- // single false-positive checkpoint would permanently tear down
1194
- // the bot (via emitAuth) and force a brand new cookie every
1195
- // time instead of just continuing on the still-good session.
1150
+
1196
1151
  try {
1197
- // [Fixed by xalman] retry up to 3x - a transient network
1198
- // hiccup during THIS check alone used to be treated the same
1199
- // as a dead session and fall through to requiring credentials.
1152
+
1200
1153
  let stillCheckpointed = true;
1201
1154
  let uid = null;
1202
1155
  for (let attempt = 0; attempt < 3 && !uid; attempt++) {
@@ -1210,8 +1163,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1210
1163
  break;
1211
1164
  }
1212
1165
  } catch {
1213
- // network hiccup on this attempt - retry below instead of
1214
- // immediately assuming the session is dead
1166
+
1215
1167
  }
1216
1168
  if (!uid && attempt < 2) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
1217
1169
  }
@@ -1220,17 +1172,18 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1220
1172
  return true;
1221
1173
  }
1222
1174
  } catch {
1223
- // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1175
+
1224
1176
  }
1225
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
+ }
1226
1182
  const u = config.credentials?.email || email;
1227
1183
  const p = config.credentials?.password || password;
1228
1184
  const tf = globalOptions.twofactor || config.credentials?.twofactor || null;
1229
1185
  if (!u || !p) return false;
1230
- // [Hardened4] Repeated credential logins are a classic trigger for "automated
1231
- // behaviour"/"multiple sessions" restrictions. At most one per cooldown window
1232
- // (FCA_NX_RELOGIN_COOLDOWN_MIN, default 30), and never while Facebook is showing
1233
- // its scraping warning - re-logging in then only makes it worse.
1186
+
1234
1187
  const cdMs = (Number(process.env.FCA_NX_RELOGIN_COOLDOWN_MIN) || 30) * 60 * 1000;
1235
1188
  const sinceLast = Date.now() - (global.__fcaLastCredLogin || 0);
1236
1189
  if (sinceLast < cdMs) {
@@ -1271,7 +1224,6 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1271
1224
  };
1272
1225
  const defaultFuncs = makeDefaults(html, userID, ctxMain);
1273
1226
 
1274
- // Attach lightweight DB updaters for realtime events (MQTT)
1275
1227
  try {
1276
1228
  const Thread = models && models.Thread;
1277
1229
  if (!Thread) {
@@ -1282,7 +1234,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1282
1234
  try {
1283
1235
  if (!msg || !msg.threadID) return;
1284
1236
  const id = String(msg.threadID);
1285
- // Fast path: increment messageCount column directly
1237
+
1286
1238
  let affected = 0;
1287
1239
  try {
1288
1240
  const res = await Thread.increment("messageCount", { by: 1, where: { threadID: id } });
@@ -1290,14 +1242,14 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1290
1242
  affected = res[0];
1291
1243
  }
1292
1244
  } catch {
1293
- // Ignore increment errors, we'll try to create below
1245
+
1294
1246
  }
1295
- // If no row was updated, ensure a row exists
1247
+
1296
1248
  if (!affected) {
1297
1249
  try {
1298
1250
  await Thread.create({ threadID: id, messageCount: 1, data: { threadID: id } });
1299
1251
  } catch {
1300
- // Ignore create races / duplicates
1252
+
1301
1253
  }
1302
1254
  }
1303
1255
  } catch (e) {
@@ -1306,10 +1258,9 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1306
1258
  }
1307
1259
  };
1308
1260
  } catch {
1309
- // If DB layer is unavailable, skip realtime thread updates
1261
+
1310
1262
  }
1311
1263
 
1312
- // Attach remote control client if enabled in config
1313
1264
  let remote = null;
1314
1265
  try {
1315
1266
  if (config && config.remoteControl && config.remoteControl.enabled) {
@@ -1359,7 +1310,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1359
1310
  api.listen = api.listenMqtt;
1360
1311
  }
1361
1312
  if (api.refreshFb_dtsg) {
1362
- // [Hardened] refresh fb_dtsg every 6h (was 24h) to prevent token-expiry logouts
1313
+
1363
1314
  setInterval(function () {
1364
1315
  api.refreshFb_dtsg().then(function () {
1365
1316
  logger("Successfully refreshed fb_dtsg");
@@ -1367,68 +1318,36 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1367
1318
  logger("An error occurred while refreshing fb_dtsg: " + (e && e.message ? e.message : e), "error");
1368
1319
  });
1369
1320
  }, 6 * 60 * 60 * 1000);
1370
- // [Hardened] light session keepalive every 20 min - hits facebook.com so cookies stay warm
1371
- // [Hardened4] randomised 15-25 min (a perfectly fixed interval looks scripted)
1372
- (function keepaliveLoop() {
1373
- const t = setTimeout(function () {
1374
- try {
1375
- const { get } = require("../src/utils/request");
1376
- const { saveCookies } = require("../src/utils/client");
1377
- if (ctxMain && ctxMain.jar && !ctxMain._ending) {
1378
- get("https://www.facebook.com/", ctxMain.jar, null, ctxMain.globalOptions, ctxMain)
1379
- .then(saveCookies(ctxMain.jar))
1380
- .then(function () { logger("session keepalive ok", "debug"); })
1381
- .catch(function (e) {
1382
- logger("session keepalive failed: " + (e && e.message ? e.message : e), "warn");
1383
- });
1384
- }
1385
- } catch (_) {}
1386
- keepaliveLoop();
1387
- }, (18 + Math.random() * 14) * 60 * 1000); // [Hardened5] 18-32 min irregular keepalive
1388
- if (t.unref) t.unref();
1389
- })();
1390
1321
  }
1391
- // ✅ fca-nx core features register
1322
+
1392
1323
  try {
1324
+ if (!e2eeEnabled()) {
1325
+ logger("E2EE off. Set \"e2ee\": true in config.json or fca-config.json to connect secret chats.", "info");
1326
+ } else {
1393
1327
  const e2eeModule = require("../src/api/socket/e2ee");
1394
1328
  api.e2ee = new e2eeModule.E2EEBridge(ctxMain, api, defaultFuncs);
1395
1329
  ctxMain.e2ee = api.e2ee;
1396
1330
  api.connectE2EE = (deviceStorePath) => api.e2ee.connect(deviceStorePath, ctxMain.userID);
1397
1331
  api.listenE2EE = require("../src/api/socket/listenE2EE")(defaultFuncs, api, ctxMain);
1398
-
1399
- // Auto-connect E2EE and make it the default listener so existing
1400
- // bots calling api.listen() OR api.listenMqtt() directly also
1401
- // receive E2EE (Secret Conversation) messages without any extra
1402
- // setup or changes on the bot side.
1403
- //
1404
- // [Fixed by xalman] IMPORTANT: assign api.listen/api.listenMqtt to the combined
1405
- // listener SYNCHRONOUSLY, before connectE2EE() resolves. Bots
1406
- // commonly call api.listenMqtt(callback) immediately in the login
1407
- // callback - if we waited for the async connectE2EE() promise to
1408
- // swap these over, that call would already have captured the old
1409
- // plain-MQTT-only function, permanently missing E2EE (inbox)
1410
- // messages even after E2EE finished connecting moments later.
1411
1332
  api.listen = api.listenE2EE;
1412
1333
  api.listenMqtt = api.listenE2EE;
1413
-
1414
- // [Fixed by xalman] Retry E2EE auto-connect with backoff instead of
1415
- // giving up forever after one failed attempt - a transient network
1416
- // blip or momentary FB rate-limit on device registration used to
1417
- // leave the bot stuck in group-only mode until a full restart.
1418
1334
  const connectE2EEWithRetry = async (attempt = 0) => {
1419
1335
  try {
1420
1336
  await api.connectE2EE();
1421
1337
  logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
1422
1338
  } catch (e) {
1423
1339
  const msg = e && e.message ? e.message : String(e);
1424
- // [Fixed by xalman] never give up: after 4 attempts the bot used to stay without E2EE
1425
- // (inbox dead) until a manual restart. Keep retrying, backing off up to 5 minutes.
1426
- const delayMs = Math.min(5000 * Math.pow(3, attempt), 300000); // 5s, 15s, 45s, 135s, 300s...
1340
+ if (attempt >= 2) {
1341
+ logger(`E2EE auto-connect stopped after ${attempt + 1} tries: ${msg}`, "warn");
1342
+ return;
1343
+ }
1344
+ const delayMs = 15000 * (attempt + 1);
1427
1345
  logger(`E2EE auto-connect failed (attempt ${attempt + 1}): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
1428
1346
  setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
1429
1347
  }
1430
1348
  };
1431
1349
  connectE2EEWithRetry();
1350
+ }
1432
1351
  } catch (e) {
1433
1352
  logger(`E2EE init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1434
1353
  }
@@ -1445,7 +1364,6 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1445
1364
  logger(`sendBroadcast init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1446
1365
  }
1447
1366
 
1448
- // sendMessage override with fca-nx version (better MQTT + HTTP fallback)
1449
1367
  try {
1450
1368
  const fcanxSendMsg = require("../src/api/socket/sendMessage")(defaultFuncs, api, ctxMain);
1451
1369
  api.sendMessage = fcanxSendMsg;
@@ -1456,15 +1374,11 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1456
1374
  logger(`sendMessage fca-nx override failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1457
1375
  }
1458
1376
 
1459
- // listenMqtt override with fca-nx version (better MQTT stability)
1460
1377
  try {
1461
1378
  const stableListenMqtt = require("../src/api/socket/listenMqtt")(defaultFuncs, api, ctxMain);
1462
- // Keep the raw MQTT listener behind the combined listener. The
1463
- // E2EE bridge is installed above, but replacing api.listenMqtt here
1464
- // used to silently discard it, so only group messages arriving over
1465
- // plain MQTT reached bot handlers.
1379
+
1466
1380
  api._listenMqttRaw = stableListenMqtt;
1467
- if (typeof api.listenE2EE === "function") {
1381
+ if (e2eeEnabled() && typeof api.listenE2EE === "function") {
1468
1382
  api.listenMqtt = api.listen = api.listenE2EE;
1469
1383
  } else {
1470
1384
  api.listenMqtt = api.listen = stableListenMqtt;
@@ -1493,5 +1407,6 @@ module.exports.loginHelper = loginHelper;
1493
1407
  module.exports.tokensViaAPI = tokensViaAPI;
1494
1408
  module.exports.loginViaAPI = loginViaAPI;
1495
1409
  module.exports.tokens = tokens;
1410
+ module.exports.credentialLoginAllowed = credentialLoginAllowed;
1496
1411
  module.exports.normalizeCookieHeaderString = normalizeCookieHeaderString;
1497
1412
  module.exports.setJarFromPairs = setJarFromPairs;