fca-nx 6.8.8 → 7.0.0
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 -3
- package/module/login.js +38 -13
- package/module/loginHelper.js +207 -148
- 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 +7 -0
- 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 +52 -56
- 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 +123 -10
- package/src/api/socket/e2ee/protocol.js +32 -1
- package/src/api/socket/e2ee/ratchet.js +44 -10
- package/src/api/socket/e2ee/store.js +13 -1
- package/src/api/socket/listenE2EE.js +25 -1
- package/src/api/socket/listenMqtt.js +94 -110
- package/src/api/socket/middleware/index.js +61 -7
- package/src/api/socket/sendMessage.js +19 -2
- 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 +9 -3
- 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/sendThrottle.js +14 -1
- package/src/utils/textEffects.js +92 -0
- package/src/utils/utils.js +17 -3
- package/src/utils/instanceLock.js +0 -35
- package/src/utils/ipGuard.js +0 -58
package/module/loginHelper.js
CHANGED
|
@@ -12,19 +12,25 @@ 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
|
+
const axiosBase = require("axios");
|
|
16
|
+
const regions = [
|
|
17
|
+
{ code: "PRN", name: "Pacific Northwest Region", location: "Khu vực Tây Bắc Thái Bình Dương" },
|
|
18
|
+
{ code: "VLL", name: "Valley Region", location: "Valley" },
|
|
19
|
+
{ code: "ASH", name: "Ashburn Region", location: "Ashburn" },
|
|
20
|
+
{ code: "DFW", name: "Dallas/Fort Worth Region", location: "Dallas/Fort Worth" },
|
|
21
|
+
{ code: "LLA", name: "Los Angeles Region", location: "Los Angeles" },
|
|
22
|
+
{ code: "FRA", name: "Frankfurt", location: "Frankfurt" },
|
|
23
|
+
{ code: "SIN", name: "Singapore", location: "Singapore" },
|
|
24
|
+
{ code: "NRT", name: "Tokyo", location: "Japan" },
|
|
25
|
+
{ code: "HKG", name: "Hong Kong", location: "Hong Kong" },
|
|
26
|
+
{ code: "SYD", name: "Sydney", location: "Sydney" },
|
|
27
|
+
{ code: "PNB", name: "Pacific Northwest - Beta", location: "Pacific Northwest " }
|
|
28
|
+
];
|
|
15
29
|
|
|
16
|
-
|
|
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
|
-
}
|
|
30
|
+
const REGION_MAP = new Map(regions.map(r => [r.code, r]));
|
|
27
31
|
|
|
32
|
+
// E2EE on/off switch. Reads "e2ee" from the bot's config.json (process.cwd()),
|
|
33
|
+
// then from the fca-nx config. Default is OFF so E2EE only starts when asked for.
|
|
28
34
|
function e2eeEnabled() {
|
|
29
35
|
const on = (v) => v === true || v === "true";
|
|
30
36
|
const off = (v) => v === false || v === "false";
|
|
@@ -40,22 +46,6 @@ function e2eeEnabled() {
|
|
|
40
46
|
if (off(config.e2ee)) return false;
|
|
41
47
|
return on(config.e2ee);
|
|
42
48
|
}
|
|
43
|
-
const axiosBase = require("axios");
|
|
44
|
-
const regions = [
|
|
45
|
-
{ code: "PRN", name: "Pacific Northwest Region", location: "Khu vực Tây Bắc Thái Bình Dương" },
|
|
46
|
-
{ code: "VLL", name: "Valley Region", location: "Valley" },
|
|
47
|
-
{ code: "ASH", name: "Ashburn Region", location: "Ashburn" },
|
|
48
|
-
{ code: "DFW", name: "Dallas/Fort Worth Region", location: "Dallas/Fort Worth" },
|
|
49
|
-
{ code: "LLA", name: "Los Angeles Region", location: "Los Angeles" },
|
|
50
|
-
{ code: "FRA", name: "Frankfurt", location: "Frankfurt" },
|
|
51
|
-
{ code: "SIN", name: "Singapore", location: "Singapore" },
|
|
52
|
-
{ code: "NRT", name: "Tokyo", location: "Japan" },
|
|
53
|
-
{ code: "HKG", name: "Hong Kong", location: "Hong Kong" },
|
|
54
|
-
{ code: "SYD", name: "Sydney", location: "Sydney" },
|
|
55
|
-
{ code: "PNB", name: "Pacific Northwest - Beta", location: "Pacific Northwest " }
|
|
56
|
-
];
|
|
57
|
-
|
|
58
|
-
const REGION_MAP = new Map(regions.map(r => [r.code, r]));
|
|
59
49
|
|
|
60
50
|
function parseRegion(html) {
|
|
61
51
|
try {
|
|
@@ -78,9 +68,23 @@ function mask(s, keep = 3) {
|
|
|
78
68
|
return n <= keep ? "*".repeat(n) : s.slice(0, keep) + "*".repeat(Math.max(0, n - keep));
|
|
79
69
|
}
|
|
80
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Login via external API endpoint (iOS method)
|
|
73
|
+
* @param {string} email - Email hoặc số điện thoại
|
|
74
|
+
* @param {string} password - Mật khẩu
|
|
75
|
+
* @param {string|null} twoFactor - Secret Base32 cho 2FA (không phải mã 6 số)
|
|
76
|
+
* @param {string|null} apiBaseUrl - Base URL của API server (không có mặc định — phải chỉ định rõ ràng)
|
|
77
|
+
* @param {string|null} apiKey - API key để xác thực (x-api-key header)
|
|
78
|
+
* @returns {Promise<{ok: boolean, uid?: string, access_token?: string, cookies?: Array, cookie?: string, message?: string}>}
|
|
79
|
+
*/
|
|
81
80
|
async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null, apiKey = null) {
|
|
82
81
|
try {
|
|
83
|
-
|
|
82
|
+
// SECURITY: do not default to a hard-coded third-party domain. Sending
|
|
83
|
+
// a plaintext Facebook email/password to an external server should
|
|
84
|
+
// require the operator to explicitly opt in (via config.apiServer or
|
|
85
|
+
// the apiBaseUrl argument) rather than happening silently the first
|
|
86
|
+
// time someone logs in with email+password. If no server is configured,
|
|
87
|
+
// fail loudly instead of guessing where to send credentials.
|
|
84
88
|
const baseUrl = apiBaseUrl || config.apiServer || null;
|
|
85
89
|
if (!baseUrl) {
|
|
86
90
|
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 +95,25 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
|
|
|
91
95
|
const endpoint = `${baseUrl}/api/v1/facebook/login_ios`;
|
|
92
96
|
const xApiKey = apiKey || config.apiKey || null;
|
|
93
97
|
|
|
98
|
+
// Build request body
|
|
94
99
|
const body = {
|
|
95
100
|
email,
|
|
96
101
|
password
|
|
97
102
|
};
|
|
98
103
|
|
|
104
|
+
// Only include twoFactor if provided (must be Base32 secret, not 6-digit code)
|
|
99
105
|
if (twoFactor && typeof twoFactor === "string" && twoFactor.trim()) {
|
|
100
|
-
|
|
106
|
+
// Clean up the secret - remove spaces and convert to uppercase
|
|
101
107
|
body.twoFactor = twoFactor.replace(/\s+/g, "").toUpperCase();
|
|
102
108
|
}
|
|
103
109
|
|
|
110
|
+
// Build headers
|
|
104
111
|
const headers = {
|
|
105
112
|
"Content-Type": "application/json",
|
|
106
113
|
"Accept": "application/json"
|
|
107
114
|
};
|
|
108
115
|
|
|
116
|
+
// Add x-api-key header if provided
|
|
109
117
|
if (xApiKey) {
|
|
110
118
|
headers["x-api-key"] = xApiKey;
|
|
111
119
|
}
|
|
@@ -123,11 +131,13 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
|
|
|
123
131
|
if (response.status === 200 && response.data) {
|
|
124
132
|
const data = response.data;
|
|
125
133
|
|
|
134
|
+
// Check if login was successful
|
|
126
135
|
if (data.error) {
|
|
127
136
|
logger(chalk.italic(`❌ API-LOGIN: Login failed - ${data.error}`), "error");
|
|
128
137
|
return { ok: false, message: data.error };
|
|
129
138
|
}
|
|
130
139
|
|
|
140
|
+
// Extract response data
|
|
131
141
|
const uid = data.uid || data.user_id || data.userId || null;
|
|
132
142
|
const accessToken = data.access_token || data.accessToken || null;
|
|
133
143
|
const cookie = data.cookie || data.cookies || null;
|
|
@@ -139,9 +149,10 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
|
|
|
139
149
|
|
|
140
150
|
logger(chalk.italic(`✅ API-LOGIN: Login successful for UID: ${uid || "unknown"}`), "info");
|
|
141
151
|
|
|
152
|
+
// Parse cookies if provided as string
|
|
142
153
|
let cookies = [];
|
|
143
154
|
if (typeof cookie === "string") {
|
|
144
|
-
|
|
155
|
+
// Parse cookie string format: "key1=value1; key2=value2"
|
|
145
156
|
const pairs = cookie.split(";").map(p => p.trim()).filter(Boolean);
|
|
146
157
|
for (const pair of pairs) {
|
|
147
158
|
const eq = pair.indexOf("=");
|
|
@@ -157,7 +168,7 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
|
|
|
157
168
|
}
|
|
158
169
|
}
|
|
159
170
|
} else if (Array.isArray(cookie)) {
|
|
160
|
-
|
|
171
|
+
// Already in array format
|
|
161
172
|
cookies = cookie.map(c => ({
|
|
162
173
|
key: c.key || c.name,
|
|
163
174
|
value: c.value,
|
|
@@ -175,6 +186,7 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
|
|
|
175
186
|
};
|
|
176
187
|
}
|
|
177
188
|
|
|
189
|
+
// Handle error responses
|
|
178
190
|
const errorMsg = response.data && response.data.error
|
|
179
191
|
? response.data.error
|
|
180
192
|
: response.data && response.data.message
|
|
@@ -191,6 +203,14 @@ async function loginViaAPI(email, password, twoFactor = null, apiBaseUrl = null,
|
|
|
191
203
|
}
|
|
192
204
|
}
|
|
193
205
|
|
|
206
|
+
/**
|
|
207
|
+
* High-level login function that uses the API endpoint
|
|
208
|
+
* @param {string} email - Email hoặc số điện thoại
|
|
209
|
+
* @param {string} password - Mật khẩu
|
|
210
|
+
* @param {string|null} twoFactor - Secret Base32 cho 2FA (không phải mã 6 số)
|
|
211
|
+
* @param {string|null} apiBaseUrl - Base URL của API server
|
|
212
|
+
* @returns {Promise<{status: boolean, cookies?: Array, uid?: string, access_token?: string, message?: string}>}
|
|
213
|
+
*/
|
|
194
214
|
async function tokensViaAPI(email, password, twoFactor = null, apiBaseUrl = null) {
|
|
195
215
|
const t0 = process.hrtime.bigint();
|
|
196
216
|
|
|
@@ -242,7 +262,7 @@ function normalizeCookieHeaderString(s) {
|
|
|
242
262
|
|
|
243
263
|
function setJarFromPairs(j, pairs, domain) {
|
|
244
264
|
const expires = new Date(Date.now() + 31536e6).toUTCString();
|
|
245
|
-
|
|
265
|
+
// URLs to set cookies for - include both desktop and mobile versions
|
|
246
266
|
const urls = [
|
|
247
267
|
"https://www.facebook.com",
|
|
248
268
|
"https://facebook.com",
|
|
@@ -251,10 +271,10 @@ function setJarFromPairs(j, pairs, domain) {
|
|
|
251
271
|
"http://facebook.com",
|
|
252
272
|
"http://m.facebook.com"
|
|
253
273
|
];
|
|
254
|
-
|
|
274
|
+
|
|
255
275
|
for (const kv of pairs) {
|
|
256
276
|
const cookieStr = `${kv}; expires=${expires}; domain=${domain}; path=/;`;
|
|
257
|
-
|
|
277
|
+
// Set cookie for all URLs to ensure it works on both desktop and mobile
|
|
258
278
|
for (const url of urls) {
|
|
259
279
|
try {
|
|
260
280
|
if (typeof j.setCookieSync === "function") {
|
|
@@ -263,7 +283,8 @@ function setJarFromPairs(j, pairs, domain) {
|
|
|
263
283
|
j.setCookie(cookieStr, url);
|
|
264
284
|
}
|
|
265
285
|
} catch (err) {
|
|
266
|
-
|
|
286
|
+
// Silently ignore domain mismatch errors
|
|
287
|
+
// These can happen when setting cookies across different subdomains
|
|
267
288
|
}
|
|
268
289
|
}
|
|
269
290
|
}
|
|
@@ -297,6 +318,7 @@ function getBackupModel() {
|
|
|
297
318
|
if (!models || !models.sequelize || !models.Sequelize) return null;
|
|
298
319
|
const sequelize = models.sequelize;
|
|
299
320
|
|
|
321
|
+
// Validate that sequelize is a proper Sequelize instance
|
|
300
322
|
if (!sequelize || typeof sequelize.define !== "function") return null;
|
|
301
323
|
|
|
302
324
|
const { DataTypes } = models.Sequelize;
|
|
@@ -317,12 +339,12 @@ function getBackupModel() {
|
|
|
317
339
|
);
|
|
318
340
|
return AppStateBackup;
|
|
319
341
|
} catch (defineError) {
|
|
320
|
-
|
|
342
|
+
// If define fails, log and return null
|
|
321
343
|
logger(`Failed to define AppStateBackup model: ${defineError && defineError.message ? defineError.message : String(defineError)}`, "warn");
|
|
322
344
|
return null;
|
|
323
345
|
}
|
|
324
346
|
} catch (e) {
|
|
325
|
-
|
|
347
|
+
// Silently handle any errors in getBackupModel
|
|
326
348
|
return null;
|
|
327
349
|
}
|
|
328
350
|
}
|
|
@@ -387,6 +409,8 @@ async function getLatestBackupAny(type) {
|
|
|
387
409
|
}
|
|
388
410
|
}
|
|
389
411
|
|
|
412
|
+
|
|
413
|
+
|
|
390
414
|
async function setJarCookies(j, appstate) {
|
|
391
415
|
const tasks = [];
|
|
392
416
|
for (const c of appstate) {
|
|
@@ -398,11 +422,13 @@ async function setJarCookies(j, appstate) {
|
|
|
398
422
|
const cookiePath = c.path || "/";
|
|
399
423
|
const dom = cookieDomain.replace(/^\./, "");
|
|
400
424
|
|
|
425
|
+
// Handle expirationDate (can be in seconds or milliseconds)
|
|
401
426
|
let expiresStr = "";
|
|
402
427
|
if (c.expirationDate !== undefined) {
|
|
403
428
|
let expiresDate;
|
|
404
429
|
if (typeof c.expirationDate === "number") {
|
|
405
|
-
|
|
430
|
+
// If expirationDate is less than a year from now in seconds, treat as seconds
|
|
431
|
+
// Otherwise treat as milliseconds
|
|
406
432
|
const now = Date.now();
|
|
407
433
|
const oneYearInMs = 365 * 24 * 60 * 60 * 1000;
|
|
408
434
|
if (c.expirationDate < (now + oneYearInMs) / 1000) {
|
|
@@ -419,20 +445,24 @@ async function setJarCookies(j, appstate) {
|
|
|
419
445
|
expiresStr = `; expires=${expiresDate.toUTCString()}`;
|
|
420
446
|
}
|
|
421
447
|
|
|
448
|
+
// Helper function to build cookie string
|
|
422
449
|
const buildCookieString = (domainOverride = null) => {
|
|
423
450
|
const domain = domainOverride || cookieDomain;
|
|
424
451
|
let cookieParts = [`${cookieName}=${cookieValue}${expiresStr}`];
|
|
425
452
|
cookieParts.push(`Domain=${domain}`);
|
|
426
453
|
cookieParts.push(`Path=${cookiePath}`);
|
|
427
454
|
|
|
455
|
+
// Add Secure flag if secure is true
|
|
428
456
|
if (c.secure === true) {
|
|
429
457
|
cookieParts.push("Secure");
|
|
430
458
|
}
|
|
431
459
|
|
|
460
|
+
// Add HttpOnly flag if httpOnly is true
|
|
432
461
|
if (c.httpOnly === true) {
|
|
433
462
|
cookieParts.push("HttpOnly");
|
|
434
463
|
}
|
|
435
464
|
|
|
465
|
+
// Add SameSite attribute if provided
|
|
436
466
|
if (c.sameSite) {
|
|
437
467
|
const sameSiteValue = String(c.sameSite).toLowerCase();
|
|
438
468
|
if (["strict", "lax", "none"].includes(sameSiteValue)) {
|
|
@@ -467,6 +497,7 @@ async function setJarCookies(j, appstate) {
|
|
|
467
497
|
await Promise.all(tasks);
|
|
468
498
|
}
|
|
469
499
|
|
|
500
|
+
// tokens function - alias to tokensViaAPI for backward compatibility
|
|
470
501
|
async function tokens(username, password, twofactor = null) {
|
|
471
502
|
return tokensViaAPI(username, password, twofactor);
|
|
472
503
|
}
|
|
@@ -507,10 +538,7 @@ async function hydrateJarFromDB(userID, jar) {
|
|
|
507
538
|
}
|
|
508
539
|
|
|
509
540
|
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
|
-
|
|
541
|
+
// Helper to validate UID - must be a non-zero positive number string
|
|
514
542
|
const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
|
|
515
543
|
|
|
516
544
|
const getUID = cs =>
|
|
@@ -524,17 +552,19 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
524
552
|
};
|
|
525
553
|
|
|
526
554
|
let userID = getUID(currentCookies);
|
|
527
|
-
|
|
555
|
+
// Also try to extract userID from HTML if cookie userID is invalid
|
|
528
556
|
if (!isValidUID(userID)) {
|
|
529
557
|
userID = htmlUID(currentHtml);
|
|
530
558
|
}
|
|
531
|
-
|
|
559
|
+
// If we have a valid userID, return success
|
|
532
560
|
if (isValidUID(userID)) {
|
|
533
561
|
return { html: currentHtml, cookies: currentCookies, userID };
|
|
534
562
|
}
|
|
535
563
|
|
|
564
|
+
// No valid userID found - need to try auto-login
|
|
536
565
|
logger("tryAutoLoginIfNeeded: No valid userID found, attempting recovery...", "warn");
|
|
537
566
|
|
|
567
|
+
// If appState/Cookie was provided and is not checkpointed, try refresh
|
|
538
568
|
if (hadAppStateInput) {
|
|
539
569
|
const isCheckpoint = currentHtml.includes("/checkpoint/block/?next");
|
|
540
570
|
if (!isCheckpoint) {
|
|
@@ -548,6 +578,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
548
578
|
}
|
|
549
579
|
}
|
|
550
580
|
|
|
581
|
+
// Try to hydrate from DB backup
|
|
551
582
|
const hydrated = await hydrateJarFromDB(null, jar);
|
|
552
583
|
if (hydrated) {
|
|
553
584
|
logger("tryAutoLoginIfNeeded: Trying backup from DB...", "info");
|
|
@@ -570,13 +601,15 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
570
601
|
}
|
|
571
602
|
}
|
|
572
603
|
|
|
604
|
+
// Check if auto-login is enabled (support both true and "true")
|
|
573
605
|
if (config.autoLogin === false || config.autoLogin === "false") {
|
|
574
606
|
throw new Error("AppState expired — Auto-login is disabled");
|
|
575
607
|
}
|
|
576
608
|
|
|
609
|
+
// Try API login
|
|
577
610
|
const u = config.credentials?.email || config.email;
|
|
578
611
|
const p = config.credentials?.password || config.password;
|
|
579
|
-
const tf =
|
|
612
|
+
const tf = config.credentials?.twofactor || config.twofactor || null;
|
|
580
613
|
|
|
581
614
|
if (!u || !p) {
|
|
582
615
|
logger("tryAutoLoginIfNeeded: No credentials configured for auto-login!", "error");
|
|
@@ -592,25 +625,28 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
592
625
|
|
|
593
626
|
logger(`tryAutoLoginIfNeeded: API login successful! UID: ${r.uid}`, "info");
|
|
594
627
|
|
|
628
|
+
// Handle cookies - can be array, cookie string header, or both
|
|
595
629
|
let cookiePairs = [];
|
|
596
|
-
|
|
630
|
+
|
|
631
|
+
// If cookies is a string (cookie header format), parse it
|
|
597
632
|
if (typeof r.cookies === "string") {
|
|
598
633
|
cookiePairs = normalizeCookieHeaderString(r.cookies);
|
|
599
|
-
}
|
|
600
|
-
|
|
634
|
+
}
|
|
635
|
+
// If cookies is an array, convert to pairs
|
|
601
636
|
else if (Array.isArray(r.cookies)) {
|
|
602
637
|
cookiePairs = r.cookies.map(c => {
|
|
603
638
|
if (typeof c === "string") {
|
|
604
|
-
|
|
639
|
+
// Already in "key=value" format
|
|
605
640
|
return c;
|
|
606
641
|
} else if (c && typeof c === "object") {
|
|
607
|
-
|
|
642
|
+
// Object format {key, value} or {name, value}
|
|
608
643
|
return `${c.key || c.name}=${c.value}`;
|
|
609
644
|
}
|
|
610
645
|
return null;
|
|
611
646
|
}).filter(Boolean);
|
|
612
647
|
}
|
|
613
|
-
|
|
648
|
+
|
|
649
|
+
// Also check for cookie field (alternative field name)
|
|
614
650
|
if (cookiePairs.length === 0 && r.cookie) {
|
|
615
651
|
if (typeof r.cookie === "string") {
|
|
616
652
|
cookiePairs = normalizeCookieHeaderString(r.cookie);
|
|
@@ -631,8 +667,11 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
631
667
|
setJarFromPairs(jar, cookiePairs, ".facebook.com");
|
|
632
668
|
}
|
|
633
669
|
|
|
670
|
+
// Wait a bit for cookies to be set
|
|
634
671
|
await new Promise(resolve => setTimeout(resolve, 500));
|
|
635
672
|
|
|
673
|
+
// Refresh Facebook page with new cookies - try multiple times if needed
|
|
674
|
+
// Try both www.facebook.com and m.facebook.com to ensure session is established
|
|
636
675
|
let html2 = "";
|
|
637
676
|
let res2 = null;
|
|
638
677
|
let retryCount = 0;
|
|
@@ -641,10 +680,10 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
641
680
|
|
|
642
681
|
while (retryCount < maxRetries) {
|
|
643
682
|
try {
|
|
644
|
-
|
|
683
|
+
// Try m.facebook.com first (mobile version often works better for API login)
|
|
645
684
|
const urlToUse = retryCount === 0 ? urlsToTry[0] : urlsToTry[retryCount % urlsToTry.length];
|
|
646
685
|
logger(`tryAutoLoginIfNeeded: Refreshing ${urlToUse} (attempt ${retryCount + 1}/${maxRetries})...`, "info");
|
|
647
|
-
|
|
686
|
+
|
|
648
687
|
const initial2 = await get(urlToUse, jar, null, globalOptions).then(saveCookies(jar));
|
|
649
688
|
res2 = (await ctxRef.bypassAutomation(initial2, jar)) || initial2;
|
|
650
689
|
html2 = res2 && res2.data ? res2.data : "";
|
|
@@ -653,12 +692,14 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
653
692
|
throw new Error("Checkpoint after API login");
|
|
654
693
|
}
|
|
655
694
|
|
|
695
|
+
// Check if HTML contains valid USER_ID
|
|
656
696
|
const htmlUserID = htmlUID(html2);
|
|
657
697
|
if (isValidUID(htmlUserID)) {
|
|
658
698
|
logger(`tryAutoLoginIfNeeded: Found valid USER_ID in HTML from ${urlToUse}: ${htmlUserID}`, "info");
|
|
659
699
|
break;
|
|
660
700
|
}
|
|
661
701
|
|
|
702
|
+
// If no valid USER_ID found, wait and retry with different URL
|
|
662
703
|
if (retryCount < maxRetries - 1) {
|
|
663
704
|
logger(`tryAutoLoginIfNeeded: No valid USER_ID in HTML from ${urlToUse} (attempt ${retryCount + 1}/${maxRetries}), retrying...`, "warn");
|
|
664
705
|
await new Promise(resolve => setTimeout(resolve, 1000 * (retryCount + 1)));
|
|
@@ -685,6 +726,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
685
726
|
const uid2 = getUID(cookies2);
|
|
686
727
|
const htmlUserID2 = htmlUID(html2);
|
|
687
728
|
|
|
729
|
+
// Prioritize USER_ID from HTML over cookies (more reliable)
|
|
688
730
|
let finalUID = null;
|
|
689
731
|
if (isValidUID(htmlUserID2)) {
|
|
690
732
|
finalUID = htmlUserID2;
|
|
@@ -702,6 +744,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
702
744
|
throw new Error("Login failed - could not get valid userID after API login. HTML may indicate session is not established.");
|
|
703
745
|
}
|
|
704
746
|
|
|
747
|
+
// Final validation: ensure HTML shows we're logged in
|
|
705
748
|
if (!isValidUID(htmlUserID2)) {
|
|
706
749
|
logger("tryAutoLoginIfNeeded: WARNING - HTML does not show valid USER_ID, but proceeding with cookie-based UID", "warn");
|
|
707
750
|
}
|
|
@@ -711,10 +754,9 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
|
|
|
711
754
|
|
|
712
755
|
function makeLogin(j, email, password, globalOptions) {
|
|
713
756
|
return async function () {
|
|
714
|
-
if (!credentialLoginAllowed()) return;
|
|
715
757
|
const u = email || config.credentials?.email;
|
|
716
758
|
const p = password || config.credentials?.password;
|
|
717
|
-
const tf =
|
|
759
|
+
const tf = config.credentials?.twofactor || null;
|
|
718
760
|
if (!u || !p) return;
|
|
719
761
|
const r = await tokens(u, p, tf);
|
|
720
762
|
if (r && r.status && Array.isArray(r.cookies)) {
|
|
@@ -729,10 +771,17 @@ function makeLogin(j, email, password, globalOptions) {
|
|
|
729
771
|
|
|
730
772
|
function loginHelper(appState, Cookie, email, password, globalOptions, callback) {
|
|
731
773
|
try {
|
|
732
|
-
|
|
774
|
+
// Each call to loginHelper() (i.e. each login()/account) gets its own,
|
|
775
|
+
// isolated CookieJar instead of sharing one process-wide singleton.
|
|
776
|
+
// Previously this file imported a single module-level `jar` shared by
|
|
777
|
+
// every account logged in within the same Node process; logging in a
|
|
778
|
+
// second account would silently overwrite/merge cookies with the first
|
|
779
|
+
// account's session (c_user/xs swapping mid-session), which is exactly
|
|
780
|
+
// the kind of implementation bug that produces "abnormal session" /
|
|
781
|
+
// forced logout on Facebook's side. Session isolation now lives here.
|
|
733
782
|
const jar = new CookieJar();
|
|
734
783
|
const domain = ".facebook.com";
|
|
735
|
-
|
|
784
|
+
// Helper to extract userID from appState input
|
|
736
785
|
const extractUIDFromAppState = (appStateInput) => {
|
|
737
786
|
if (!appStateInput) return null;
|
|
738
787
|
let parsed = appStateInput;
|
|
@@ -754,24 +803,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
754
803
|
let userIDFromAppState = extractUIDFromAppState(appState);
|
|
755
804
|
(async () => {
|
|
756
805
|
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
806
|
if (appState) {
|
|
772
|
-
|
|
807
|
+
// Check and convert cookie to appState format
|
|
773
808
|
if (Array.isArray(appState) && appState.some(c => c.name)) {
|
|
774
|
-
|
|
809
|
+
// Convert name to key if needed
|
|
775
810
|
appState = appState.map(c => {
|
|
776
811
|
if (c.name && !c.key) {
|
|
777
812
|
c.key = c.name;
|
|
@@ -780,17 +815,17 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
780
815
|
return c;
|
|
781
816
|
});
|
|
782
817
|
} else if (typeof appState === "string") {
|
|
783
|
-
|
|
818
|
+
// Try to parse as JSON first
|
|
784
819
|
let parsed = appState;
|
|
785
820
|
try {
|
|
786
821
|
parsed = JSON.parse(appState);
|
|
787
822
|
} catch { }
|
|
788
823
|
|
|
789
824
|
if (Array.isArray(parsed)) {
|
|
790
|
-
|
|
825
|
+
// Already parsed as array, use it
|
|
791
826
|
appState = parsed;
|
|
792
827
|
} else {
|
|
793
|
-
|
|
828
|
+
// Parse string cookie format (key=value; key2=value2)
|
|
794
829
|
const arrayAppState = [];
|
|
795
830
|
appState.split(';').forEach(c => {
|
|
796
831
|
const [key, value] = c.split('=');
|
|
@@ -808,6 +843,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
808
843
|
}
|
|
809
844
|
}
|
|
810
845
|
|
|
846
|
+
// Set cookies into jar with individual domain/path
|
|
811
847
|
if (Array.isArray(appState)) {
|
|
812
848
|
await setJarCookies(jar, appState);
|
|
813
849
|
} else {
|
|
@@ -947,31 +983,32 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
947
983
|
const s = typeof body === "string" ? body : String(body ?? "");
|
|
948
984
|
return s.match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s.match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
|
|
949
985
|
};
|
|
950
|
-
|
|
986
|
+
// Helper to validate UID - must be a non-zero positive number string
|
|
951
987
|
const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
|
|
952
988
|
|
|
953
989
|
let userID = getUIDFromCookies(cookies);
|
|
954
|
-
|
|
990
|
+
// Also try to extract userID from HTML if not found in cookies
|
|
955
991
|
if (!isValidUID(userID)) {
|
|
956
992
|
userID = getUIDFromHTML(html);
|
|
957
993
|
}
|
|
958
|
-
|
|
994
|
+
// If still not found and appState was provided, use userID from appState input as fallback
|
|
959
995
|
if (!isValidUID(userID) && userIDFromAppState && isValidUID(userIDFromAppState)) {
|
|
960
996
|
userID = userIDFromAppState;
|
|
961
997
|
}
|
|
962
|
-
|
|
998
|
+
// Trigger auto-login if userID is invalid (missing or "0")
|
|
963
999
|
if (!isValidUID(userID)) {
|
|
964
1000
|
logger("Invalid userID detected (missing or 0), attempting auto-login...", "warn");
|
|
965
|
-
|
|
1001
|
+
// Pass hadAppStateInput=true if appState/Cookie was originally provided
|
|
966
1002
|
const retried = await tryAutoLoginIfNeeded(html, cookies, globalOptions, ctx, !!(appState || Cookie), jar);
|
|
967
1003
|
html = retried.html;
|
|
968
1004
|
cookies = retried.cookies;
|
|
969
1005
|
userID = retried.userID;
|
|
970
|
-
|
|
1006
|
+
|
|
1007
|
+
// Validate HTML after auto-login - ensure it contains valid USER_ID
|
|
971
1008
|
const htmlUserIDAfterLogin = getUIDFromHTML(html);
|
|
972
1009
|
if (!isValidUID(htmlUserIDAfterLogin)) {
|
|
973
1010
|
logger("After auto-login, HTML still does not contain valid USER_ID. Session may not be established.", "error");
|
|
974
|
-
|
|
1011
|
+
// Try one more refresh
|
|
975
1012
|
try {
|
|
976
1013
|
const refreshRes = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
|
|
977
1014
|
const refreshedHtml = refreshRes && refreshRes.data ? refreshRes.data : "";
|
|
@@ -987,7 +1024,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
987
1024
|
throw new Error(`Login failed - Could not establish valid session. HTML USER_ID check failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`);
|
|
988
1025
|
}
|
|
989
1026
|
} else {
|
|
990
|
-
|
|
1027
|
+
// Use USER_ID from HTML as it's more reliable
|
|
991
1028
|
userID = htmlUserIDAfterLogin;
|
|
992
1029
|
logger(`After auto-login, using USER_ID from HTML: ${userID}`, "info");
|
|
993
1030
|
}
|
|
@@ -996,57 +1033,61 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
996
1033
|
logger(chalk.italic("😿 Session expired! Please update your appstate."), "error");
|
|
997
1034
|
throw new Error("Checkpoint");
|
|
998
1035
|
}
|
|
999
|
-
|
|
1036
|
+
|
|
1037
|
+
// Final validation: ensure HTML shows we're logged in before proceeding
|
|
1000
1038
|
let finalHtmlUID = getUIDFromHTML(html);
|
|
1001
1039
|
if (!isValidUID(finalHtmlUID)) {
|
|
1002
|
-
|
|
1040
|
+
// If cookies have valid UID but HTML doesn't, try to "activate" session
|
|
1003
1041
|
if (isValidUID(userID)) {
|
|
1004
1042
|
logger(`HTML shows USER_ID=${finalHtmlUID || "none"} but cookies have valid UID=${userID}. Attempting to activate session...`, "warn");
|
|
1005
|
-
|
|
1043
|
+
|
|
1044
|
+
// Try making requests to activate the session
|
|
1006
1045
|
try {
|
|
1007
|
-
|
|
1046
|
+
// Wait a bit first for cookies to propagate
|
|
1008
1047
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
1009
|
-
|
|
1048
|
+
|
|
1049
|
+
// Try refreshing with m.facebook.com/home.php (mobile home page)
|
|
1010
1050
|
logger("Trying to activate session via m.facebook.com/home.php...", "info");
|
|
1011
1051
|
const activateRes = await get("https://m.facebook.com/home.php", jar, null, globalOptions).then(saveCookies(jar));
|
|
1012
1052
|
const activateHtml = activateRes && activateRes.data ? activateRes.data : "";
|
|
1013
1053
|
const activateUID = getUIDFromHTML(activateHtml);
|
|
1014
|
-
|
|
1054
|
+
|
|
1015
1055
|
if (isValidUID(activateUID)) {
|
|
1016
1056
|
html = activateHtml;
|
|
1017
1057
|
finalHtmlUID = activateUID;
|
|
1018
1058
|
userID = activateUID;
|
|
1019
1059
|
logger(`Session activated! Found valid USER_ID in HTML: ${userID}`, "info");
|
|
1020
1060
|
} else {
|
|
1021
|
-
|
|
1061
|
+
// Try one more time with www.facebook.com/home.php after delay
|
|
1022
1062
|
await new Promise(resolve => setTimeout(resolve, 1500));
|
|
1023
1063
|
logger("Trying to activate session via www.facebook.com/home.php...", "info");
|
|
1024
1064
|
const activateRes2 = await get("https://www.facebook.com/home.php", jar, null, globalOptions).then(saveCookies(jar));
|
|
1025
1065
|
const activateHtml2 = activateRes2 && activateRes2.data ? activateRes2.data : "";
|
|
1026
1066
|
const activateUID2 = getUIDFromHTML(activateHtml2);
|
|
1027
|
-
|
|
1067
|
+
|
|
1028
1068
|
if (isValidUID(activateUID2)) {
|
|
1029
1069
|
html = activateHtml2;
|
|
1030
1070
|
finalHtmlUID = activateUID2;
|
|
1031
1071
|
userID = activateUID2;
|
|
1032
1072
|
logger(`Session activated on second try! Found valid USER_ID in HTML: ${userID}`, "info");
|
|
1033
1073
|
} else {
|
|
1034
|
-
|
|
1074
|
+
// If cookies have valid UID, we can proceed with cookie-based UID but warn
|
|
1035
1075
|
logger(`WARNING: HTML still shows USER_ID=${finalHtmlUID || "none"} but cookies have valid UID=${userID}. Proceeding with cookie-based UID.`, "warn");
|
|
1036
|
-
|
|
1076
|
+
// Don't throw error, proceed with cookie-based UID
|
|
1037
1077
|
}
|
|
1038
1078
|
}
|
|
1039
1079
|
} catch (activateErr) {
|
|
1040
1080
|
logger(`Failed to activate session: ${activateErr && activateErr.message ? activateErr.message : String(activateErr)}. Proceeding with cookie-based UID.`, "warn");
|
|
1041
|
-
|
|
1081
|
+
// Don't throw error, proceed with cookie-based UID
|
|
1042
1082
|
}
|
|
1043
1083
|
} else {
|
|
1044
|
-
|
|
1084
|
+
// No valid UID in either cookies or HTML
|
|
1045
1085
|
logger(`Final HTML validation failed - USER_ID from HTML: ${finalHtmlUID || "none"}, from cookies: ${userID || "none"}`, "error");
|
|
1046
1086
|
throw new Error("Login validation failed - HTML does not contain valid USER_ID. Session may not be properly established.");
|
|
1047
1087
|
}
|
|
1048
1088
|
}
|
|
1049
|
-
|
|
1089
|
+
|
|
1090
|
+
// Final check: ensure we have a valid userID (either from HTML or cookies)
|
|
1050
1091
|
if (!isValidUID(userID)) {
|
|
1051
1092
|
logger(`No valid USER_ID found - HTML: ${finalHtmlUID || "none"}, Cookies: ${userID || "none"}`, "error");
|
|
1052
1093
|
throw new Error("Login validation failed - No valid USER_ID found in HTML or cookies.");
|
|
@@ -1073,14 +1114,15 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1073
1114
|
const info = JSON.parse(userDataMatch[1]);
|
|
1074
1115
|
logger(`✅ Logged in as: ${info.NAME} (${info.USER_ID})`, "info");
|
|
1075
1116
|
|
|
1117
|
+
// Check if Facebook response shows USER_ID = 0 (session dead)
|
|
1076
1118
|
if (!isValidUID(info.USER_ID)) {
|
|
1077
1119
|
logger("Facebook response shows invalid USER_ID (0 or empty), session is dead!", "warn");
|
|
1078
|
-
|
|
1120
|
+
// Force trigger auto-login
|
|
1079
1121
|
const retried = await tryAutoLoginIfNeeded(html, cookies, globalOptions, ctx, !!(appState || Cookie), jar);
|
|
1080
1122
|
html = retried.html;
|
|
1081
1123
|
cookies = retried.cookies;
|
|
1082
1124
|
userID = retried.userID;
|
|
1083
|
-
|
|
1125
|
+
// Re-check after auto-login
|
|
1084
1126
|
if (!isValidUID(userID)) {
|
|
1085
1127
|
throw new Error("Auto-login failed - could not get valid userID");
|
|
1086
1128
|
}
|
|
@@ -1089,16 +1131,16 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1089
1131
|
logger(`ID người dùng: ${userID}`, "info");
|
|
1090
1132
|
}
|
|
1091
1133
|
} catch (userDataErr) {
|
|
1092
|
-
|
|
1134
|
+
// If error is from our validation, rethrow it
|
|
1093
1135
|
if (userDataErr && userDataErr.message && userDataErr.message.includes("Auto-login failed")) {
|
|
1094
1136
|
throw userDataErr;
|
|
1095
1137
|
}
|
|
1096
|
-
|
|
1138
|
+
// Otherwise ignore parsing errors
|
|
1097
1139
|
}
|
|
1098
1140
|
const tokenMatch = html.match(/DTSGInitialData.*?token":"(.*?)"/);
|
|
1099
1141
|
if (tokenMatch) fb_dtsg = tokenMatch[1];
|
|
1100
1142
|
try {
|
|
1101
|
-
if (userID) backupAppStateSQL(jar, userID)
|
|
1143
|
+
if (userID) await backupAppStateSQL(jar, userID);
|
|
1102
1144
|
} catch { }
|
|
1103
1145
|
Promise.resolve()
|
|
1104
1146
|
.then(function () {
|
|
@@ -1112,10 +1154,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1112
1154
|
}
|
|
1113
1155
|
})
|
|
1114
1156
|
.catch(function (error) {
|
|
1115
|
-
|
|
1157
|
+
// Silently handle database errors - they're not critical for login
|
|
1116
1158
|
const errorMsg = error && error.message ? error.message : String(error);
|
|
1117
1159
|
if (!errorMsg.includes("No Sequelize instance passed")) {
|
|
1118
|
-
|
|
1160
|
+
// Only log non-Sequelize instance errors
|
|
1119
1161
|
logger(`Database connection failed: ${errorMsg}`, "warn");
|
|
1120
1162
|
}
|
|
1121
1163
|
});
|
|
@@ -1136,8 +1178,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1136
1178
|
firstListen: true,
|
|
1137
1179
|
fb_dtsg,
|
|
1138
1180
|
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),
|
|
1181
|
+
clientId: getFrom(html, '["MqttWebDeviceID",[],{"clientID":"', '"}') || "",
|
|
1141
1182
|
wsReqNumber: 0,
|
|
1142
1183
|
wsTaskNumber: 0,
|
|
1143
1184
|
tasks: new Map(),
|
|
@@ -1147,9 +1188,18 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1147
1188
|
ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
|
|
1148
1189
|
ctxMain.performAutoLogin = async () => {
|
|
1149
1190
|
try {
|
|
1150
|
-
|
|
1191
|
+
// [Fixed by xalman] First check whether the existing cookie session is actually
|
|
1192
|
+
// still usable. A checkpoint/redirect seen on one request
|
|
1193
|
+
// doesn't always mean the whole session is dead (transient FB
|
|
1194
|
+
// blips, rate limiting, etc). Cookie/appstate-only logins have
|
|
1195
|
+
// no email+password to re-login with, so without this check a
|
|
1196
|
+
// single false-positive checkpoint would permanently tear down
|
|
1197
|
+
// the bot (via emitAuth) and force a brand new cookie every
|
|
1198
|
+
// time instead of just continuing on the still-good session.
|
|
1151
1199
|
try {
|
|
1152
|
-
|
|
1200
|
+
// [Fixed by xalman] retry up to 3x - a transient network
|
|
1201
|
+
// hiccup during THIS check alone used to be treated the same
|
|
1202
|
+
// as a dead session and fall through to requiring credentials.
|
|
1153
1203
|
let stillCheckpointed = true;
|
|
1154
1204
|
let uid = null;
|
|
1155
1205
|
for (let attempt = 0; attempt < 3 && !uid; attempt++) {
|
|
@@ -1163,7 +1213,8 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1163
1213
|
break;
|
|
1164
1214
|
}
|
|
1165
1215
|
} catch {
|
|
1166
|
-
|
|
1216
|
+
// network hiccup on this attempt - retry below instead of
|
|
1217
|
+
// immediately assuming the session is dead
|
|
1167
1218
|
}
|
|
1168
1219
|
if (!uid && attempt < 2) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
|
|
1169
1220
|
}
|
|
@@ -1172,25 +1223,13 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1172
1223
|
return true;
|
|
1173
1224
|
}
|
|
1174
1225
|
} catch {
|
|
1175
|
-
|
|
1226
|
+
// Self-check failed (network hiccup, etc) - fall through to credential-based login below.
|
|
1176
1227
|
}
|
|
1177
1228
|
|
|
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
1229
|
const u = config.credentials?.email || email;
|
|
1183
1230
|
const p = config.credentials?.password || password;
|
|
1184
|
-
const tf =
|
|
1231
|
+
const tf = config.credentials?.twofactor || null;
|
|
1185
1232
|
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
1233
|
const r = await tokens(u, p, tf);
|
|
1195
1234
|
if (!(r && r.status && Array.isArray(r.cookies))) return false;
|
|
1196
1235
|
const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
|
|
@@ -1203,7 +1242,6 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1203
1242
|
};
|
|
1204
1243
|
const api = {
|
|
1205
1244
|
setOptions: require("./options").setOptions.bind(null, globalOptions),
|
|
1206
|
-
setSendDelay: require("../src/utils/sendThrottle").setSendDelay,
|
|
1207
1245
|
getCookies: function () {
|
|
1208
1246
|
return cookieHeaderFromJar(jar);
|
|
1209
1247
|
},
|
|
@@ -1224,6 +1262,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1224
1262
|
};
|
|
1225
1263
|
const defaultFuncs = makeDefaults(html, userID, ctxMain);
|
|
1226
1264
|
|
|
1265
|
+
// Attach lightweight DB updaters for realtime events (MQTT)
|
|
1227
1266
|
try {
|
|
1228
1267
|
const Thread = models && models.Thread;
|
|
1229
1268
|
if (!Thread) {
|
|
@@ -1234,7 +1273,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1234
1273
|
try {
|
|
1235
1274
|
if (!msg || !msg.threadID) return;
|
|
1236
1275
|
const id = String(msg.threadID);
|
|
1237
|
-
|
|
1276
|
+
// Fast path: increment messageCount column directly
|
|
1238
1277
|
let affected = 0;
|
|
1239
1278
|
try {
|
|
1240
1279
|
const res = await Thread.increment("messageCount", { by: 1, where: { threadID: id } });
|
|
@@ -1242,14 +1281,14 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1242
1281
|
affected = res[0];
|
|
1243
1282
|
}
|
|
1244
1283
|
} catch {
|
|
1245
|
-
|
|
1284
|
+
// Ignore increment errors, we'll try to create below
|
|
1246
1285
|
}
|
|
1247
|
-
|
|
1286
|
+
// If no row was updated, ensure a row exists
|
|
1248
1287
|
if (!affected) {
|
|
1249
1288
|
try {
|
|
1250
1289
|
await Thread.create({ threadID: id, messageCount: 1, data: { threadID: id } });
|
|
1251
1290
|
} catch {
|
|
1252
|
-
|
|
1291
|
+
// Ignore create races / duplicates
|
|
1253
1292
|
}
|
|
1254
1293
|
}
|
|
1255
1294
|
} catch (e) {
|
|
@@ -1258,9 +1297,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1258
1297
|
}
|
|
1259
1298
|
};
|
|
1260
1299
|
} catch {
|
|
1261
|
-
|
|
1300
|
+
// If DB layer is unavailable, skip realtime thread updates
|
|
1262
1301
|
}
|
|
1263
1302
|
|
|
1303
|
+
// Attach remote control client if enabled in config
|
|
1264
1304
|
let remote = null;
|
|
1265
1305
|
try {
|
|
1266
1306
|
if (config && config.remoteControl && config.remoteControl.enabled) {
|
|
@@ -1310,44 +1350,59 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1310
1350
|
api.listen = api.listenMqtt;
|
|
1311
1351
|
}
|
|
1312
1352
|
if (api.refreshFb_dtsg) {
|
|
1313
|
-
|
|
1314
1353
|
setInterval(function () {
|
|
1315
1354
|
api.refreshFb_dtsg().then(function () {
|
|
1316
1355
|
logger("Successfully refreshed fb_dtsg");
|
|
1317
|
-
}).catch(function (
|
|
1318
|
-
logger("An error occurred while refreshing fb_dtsg
|
|
1356
|
+
}).catch(function () {
|
|
1357
|
+
logger("An error occurred while refreshing fb_dtsg", "error");
|
|
1319
1358
|
});
|
|
1320
|
-
},
|
|
1359
|
+
}, 86400000);
|
|
1321
1360
|
}
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
} else {
|
|
1361
|
+
// ✅ fca-nx core features register
|
|
1362
|
+
if (!e2eeEnabled()) {
|
|
1363
|
+
logger("E2EE off. Set \"e2ee\": true in config.json to enable it.", "info");
|
|
1364
|
+
} else try {
|
|
1327
1365
|
const e2eeModule = require("../src/api/socket/e2ee");
|
|
1328
1366
|
api.e2ee = new e2eeModule.E2EEBridge(ctxMain, api, defaultFuncs);
|
|
1329
1367
|
ctxMain.e2ee = api.e2ee;
|
|
1330
1368
|
api.connectE2EE = (deviceStorePath) => api.e2ee.connect(deviceStorePath, ctxMain.userID);
|
|
1331
1369
|
api.listenE2EE = require("../src/api/socket/listenE2EE")(defaultFuncs, api, ctxMain);
|
|
1370
|
+
|
|
1371
|
+
// Auto-connect E2EE and make it the default listener so existing
|
|
1372
|
+
// bots calling api.listen() OR api.listenMqtt() directly also
|
|
1373
|
+
// receive E2EE (Secret Conversation) messages without any extra
|
|
1374
|
+
// setup or changes on the bot side.
|
|
1375
|
+
//
|
|
1376
|
+
// [Fixed by xalman] IMPORTANT: assign api.listen/api.listenMqtt to the combined
|
|
1377
|
+
// listener SYNCHRONOUSLY, before connectE2EE() resolves. Bots
|
|
1378
|
+
// commonly call api.listenMqtt(callback) immediately in the login
|
|
1379
|
+
// callback - if we waited for the async connectE2EE() promise to
|
|
1380
|
+
// swap these over, that call would already have captured the old
|
|
1381
|
+
// plain-MQTT-only function, permanently missing E2EE (inbox)
|
|
1382
|
+
// messages even after E2EE finished connecting moments later.
|
|
1332
1383
|
api.listen = api.listenE2EE;
|
|
1333
1384
|
api.listenMqtt = api.listenE2EE;
|
|
1385
|
+
|
|
1386
|
+
// [Fixed by xalman] Retry E2EE auto-connect with backoff instead of
|
|
1387
|
+
// giving up forever after one failed attempt - a transient network
|
|
1388
|
+
// blip or momentary FB rate-limit on device registration used to
|
|
1389
|
+
// leave the bot stuck in group-only mode until a full restart.
|
|
1334
1390
|
const connectE2EEWithRetry = async (attempt = 0) => {
|
|
1335
1391
|
try {
|
|
1336
1392
|
await api.connectE2EE();
|
|
1337
1393
|
logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
|
|
1338
1394
|
} catch (e) {
|
|
1339
1395
|
const msg = e && e.message ? e.message : String(e);
|
|
1340
|
-
if (attempt
|
|
1341
|
-
|
|
1342
|
-
|
|
1396
|
+
if (attempt < 3) {
|
|
1397
|
+
const delayMs = 5000 * Math.pow(3, attempt); // 5s, 15s, 45s
|
|
1398
|
+
logger(`E2EE auto-connect failed (attempt ${attempt + 1}/4): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
|
|
1399
|
+
setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
|
|
1400
|
+
} else {
|
|
1401
|
+
logger(`E2EE auto-connect failed after 4 attempts (non-fatal, continuing without E2EE): ${msg}`, "warn");
|
|
1343
1402
|
}
|
|
1344
|
-
const delayMs = 15000 * (attempt + 1);
|
|
1345
|
-
logger(`E2EE auto-connect failed (attempt ${attempt + 1}): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
|
|
1346
|
-
setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
|
|
1347
1403
|
}
|
|
1348
1404
|
};
|
|
1349
1405
|
connectE2EEWithRetry();
|
|
1350
|
-
}
|
|
1351
1406
|
} catch (e) {
|
|
1352
1407
|
logger(`E2EE init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
|
|
1353
1408
|
}
|
|
@@ -1364,6 +1419,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1364
1419
|
logger(`sendBroadcast init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
|
|
1365
1420
|
}
|
|
1366
1421
|
|
|
1422
|
+
// sendMessage override with fca-nx version (better MQTT + HTTP fallback)
|
|
1367
1423
|
try {
|
|
1368
1424
|
const fcanxSendMsg = require("../src/api/socket/sendMessage")(defaultFuncs, api, ctxMain);
|
|
1369
1425
|
api.sendMessage = fcanxSendMsg;
|
|
@@ -1374,11 +1430,15 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1374
1430
|
logger(`sendMessage fca-nx override failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
|
|
1375
1431
|
}
|
|
1376
1432
|
|
|
1433
|
+
// listenMqtt override with fca-nx version (better MQTT stability)
|
|
1377
1434
|
try {
|
|
1378
1435
|
const stableListenMqtt = require("../src/api/socket/listenMqtt")(defaultFuncs, api, ctxMain);
|
|
1379
|
-
|
|
1436
|
+
// Keep the raw MQTT listener behind the combined listener. The
|
|
1437
|
+
// E2EE bridge is installed above, but replacing api.listenMqtt here
|
|
1438
|
+
// used to silently discard it, so only group messages arriving over
|
|
1439
|
+
// plain MQTT reached bot handlers.
|
|
1380
1440
|
api._listenMqttRaw = stableListenMqtt;
|
|
1381
|
-
if (
|
|
1441
|
+
if (typeof api.listenE2EE === "function") {
|
|
1382
1442
|
api.listenMqtt = api.listen = api.listenE2EE;
|
|
1383
1443
|
} else {
|
|
1384
1444
|
api.listenMqtt = api.listen = stableListenMqtt;
|
|
@@ -1407,6 +1467,5 @@ module.exports.loginHelper = loginHelper;
|
|
|
1407
1467
|
module.exports.tokensViaAPI = tokensViaAPI;
|
|
1408
1468
|
module.exports.loginViaAPI = loginViaAPI;
|
|
1409
1469
|
module.exports.tokens = tokens;
|
|
1410
|
-
module.exports.credentialLoginAllowed = credentialLoginAllowed;
|
|
1411
1470
|
module.exports.normalizeCookieHeaderString = normalizeCookieHeaderString;
|
|
1412
1471
|
module.exports.setJarFromPairs = setJarFromPairs;
|