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