fca-nx 6.8.5 → 6.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/func/checkUpdate.js +1 -1
  2. package/func/logAdapter.js +0 -2
  3. package/index.js +0 -3
  4. package/module/config.js +3 -5
  5. package/module/login.js +10 -38
  6. package/module/loginHelper.js +121 -206
  7. package/module/options.js +1 -7
  8. package/package.json +3 -3
  9. package/src/api/action/addfriend.js +3 -9
  10. package/src/api/action/changeAvatar.js +0 -1
  11. package/src/api/action/changeCover.js +1 -3
  12. package/src/api/action/enableAutoSaveAppState.js +5 -18
  13. package/src/api/action/refreshFb_dtsg.js +2 -2
  14. package/src/api/http/httpGet.js +2 -6
  15. package/src/api/http/httpPost.js +2 -7
  16. package/src/api/messaging/createNewGroup.js +1 -1
  17. package/src/api/messaging/deleteMessage.js +1 -1
  18. package/src/api/messaging/forwardMessage.js +1 -9
  19. package/src/api/messaging/getEmojiUrl.js +1 -5
  20. package/src/api/messaging/getMessage.js +2 -4
  21. package/src/api/messaging/getThemePictures.js +0 -7
  22. package/src/api/messaging/markAsRead.js +0 -1
  23. package/src/api/messaging/muteThread.js +1 -1
  24. package/src/api/messaging/pinMessage.js +1 -10
  25. package/src/api/messaging/scheduler.js +4 -71
  26. package/src/api/messaging/sendBroadcast.js +0 -15
  27. package/src/api/messaging/sendMessage.js +1 -10
  28. package/src/api/messaging/sendTypingIndicator.js +2 -2
  29. package/src/api/messaging/sessionGuard.js +9 -45
  30. package/src/api/messaging/setMessageReaction.js +1 -2
  31. package/src/api/messaging/threadColors.js +12 -45
  32. package/src/api/messaging/uploadAttachment.js +3 -37
  33. package/src/api/socket/core/connectMqtt.js +17 -60
  34. package/src/api/socket/core/emitAuth.js +2 -14
  35. package/src/api/socket/core/getSeqID.js +23 -29
  36. package/src/api/socket/core/getTaskResponseData.js +1 -3
  37. package/src/api/socket/core/parseDelta.js +1 -1
  38. package/src/api/socket/detail/buildStream.js +1 -4
  39. package/src/api/socket/detail/constants.js +1 -4
  40. package/src/api/socket/e2ee/crypto.js +2 -40
  41. package/src/api/socket/e2ee/index.js +10 -123
  42. package/src/api/socket/e2ee/protocol.js +1 -32
  43. package/src/api/socket/e2ee/ratchet.js +10 -44
  44. package/src/api/socket/e2ee/store.js +1 -13
  45. package/src/api/socket/listenE2EE.js +1 -25
  46. package/src/api/socket/listenMqtt.js +13 -29
  47. package/src/api/socket/middleware/index.js +7 -61
  48. package/src/api/socket/sendMessage.js +2 -19
  49. package/src/api/threads/getThreadHistory.js +38 -68
  50. package/src/api/threads/getThreadInfo.js +3 -4
  51. package/src/api/threads/getThreadList.js +31 -34
  52. package/src/api/threads/getThreadPictures.js +1 -1
  53. package/src/api/users/getUserInfo.js +2 -5
  54. package/src/api/users/getUserInfoV2.js +3 -9
  55. package/src/core/sendReqMqtt.js +1 -2
  56. package/src/database/helpers.js +0 -12
  57. package/src/database/models/index.js +9 -8
  58. package/src/utils/broadcast.js +1 -1
  59. package/src/utils/clientIdentity.js +3 -50
  60. package/src/utils/cookies.js +2 -4
  61. package/src/utils/format/utils.js +0 -10
  62. package/src/utils/headers.js +12 -26
  63. package/src/utils/instanceLock.js +3 -9
  64. package/src/utils/ipGuard.js +1 -15
  65. package/src/utils/loginParser/autoLogin.js +0 -12
  66. package/src/utils/loginParser/parseAndCheckLogin.js +0 -7
  67. package/src/utils/loginParser/textUtils.js +0 -6
  68. package/src/utils/request/config.js +1 -4
  69. package/src/utils/request/methods.js +1 -4
  70. package/src/utils/request/proxy.js +0 -13
  71. package/src/utils/request/retry.js +0 -1
  72. package/src/utils/request/sanitize.js +1 -1
  73. package/src/utils/sendThrottle.js +1 -14
  74. package/src/utils/utils.js +3 -17
@@ -16,21 +16,20 @@ try {
16
16
  storage: path.join(databasePath, "database.sqlite"),
17
17
  logging: false,
18
18
  pool: {
19
- max: 5,
19
+ max: 1,
20
20
  min: 0,
21
- acquire: 30000,
22
- idle: 10000
21
+ acquire: 8000,
22
+ idle: 5000
23
23
  },
24
24
  retry: {
25
- max: 3
25
+ max: 1
26
26
  },
27
27
  dialectOptions: {
28
- timeout: 5000
28
+ timeout: 8000
29
29
  },
30
30
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
31
31
  });
32
32
 
33
- // Load models with error handling
34
33
  try {
35
34
  const modelFiles = fs.readdirSync(__dirname)
36
35
  .filter(file => file.endsWith(".js") && file !== "index.js");
@@ -42,12 +41,11 @@ try {
42
41
  models[model.name] = model;
43
42
  }
44
43
  } catch (modelError) {
45
- // Log but continue loading other models
44
+
46
45
  console.error(`Failed to load model ${file}:`, modelError && modelError.message ? modelError.message : String(modelError));
47
46
  }
48
47
  }
49
48
 
50
- // Associate models
51
49
  Object.keys(models).forEach(modelName => {
52
50
  try {
53
51
  if (models[modelName].associate) {
@@ -69,6 +67,9 @@ try {
69
67
  if (!sequelize) {
70
68
  throw new Error("Sequelize instance not initialized");
71
69
  }
70
+ await sequelize.query("PRAGMA journal_mode=WAL;");
71
+ await sequelize.query("PRAGMA synchronous=NORMAL;");
72
+ await sequelize.query("PRAGMA busy_timeout=8000;");
72
73
  await sequelize.sync({ force: false });
73
74
  } catch (error) {
74
75
  console.error("Failed to synchronize models:", error && error.message ? error.message : String(error));
@@ -36,7 +36,7 @@ async function broadcast(api, threadIDs, message, options) {
36
36
  skipBlocked &&
37
37
  /permission|blocked|not allowed|cannot send message|not authorized/i.test(msg)
38
38
  ) {
39
- // Skip only this target, continue with others
39
+
40
40
  }
41
41
  }
42
42
  if (delayMs > 0) {
@@ -1,31 +1,11 @@
1
1
  "use strict";
2
- /**
3
- * Centralized client-identity configuration.
4
- *
5
- * Problem this solves:
6
- * Previously, User-Agent / sec-ch-ua / platform / arch / Accept-Language were
7
- * hard-coded independently in several files (headers.js, connectMqtt.js,
8
- * uploadAttachment.js, module/login.js, module/options.js) with DIFFERENT
9
- * Chrome versions (121 / 125 / 139 / 143) and mismatched client hints.
10
- * A single HTTP session that claims to be Chrome 121 in one request and
11
- * Chrome 143 (with matching sec-ch-ua) in the next is internally
12
- * inconsistent - it looks like two different browsers sharing one cookie
13
- * jar, which is exactly the kind of implementation bug that produces
14
- * "abnormal session" / forced logout behavior server-side.
15
- *
16
- * This module is the SINGLE source of truth for what a session claims to be.
17
- * It does not rotate, randomize, or otherwise try to evade detection - it
18
- * simply makes sure every subsystem (HTTP, MQTT/WebSocket, file upload)
19
- * agrees on one coherent, stable identity for the lifetime of a session.
20
- */
21
2
 
22
- // One version pin used everywhere. Bump this in one place when needed.
23
- const CHROME_VERSION = "131.0.6778.205"; // [Hardened5] realistic build, not x.0.0.0 (bot-looking)
3
+ const CHROME_VERSION = "131.0.6778.205";
24
4
  const CHROME_MAJOR = CHROME_VERSION.split(".")[0];
25
5
 
26
6
  const DEFAULT_IDENTITY = Object.freeze({
27
7
  userAgent: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${CHROME_VERSION} Safari/537.36`,
28
- acceptLanguage: "en-US,en;q=0.9,bn;q=0.8", // mild secondary locale is common in BD/SA users
8
+ acceptLanguage: "en-US,en;q=0.9,bn;q=0.8",
29
9
  secChUa: `"Chromium";v="${CHROME_MAJOR}", "Not;A=Brand";v="24", "Google Chrome";v="${CHROME_MAJOR}"`,
30
10
  secChUaMobile: "?0",
31
11
  secChUaPlatform: '"Windows"',
@@ -35,12 +15,6 @@ const DEFAULT_IDENTITY = Object.freeze({
35
15
  secChUaPlatformVersion: '"15.0.0"'
36
16
  });
37
17
 
38
- /**
39
- * Derive a Chrome major version from a User-Agent string, if it looks like
40
- * one of our own default UAs. Used so that if a caller supplies a custom
41
- * Chrome UA via options, the client-hint headers we generate still line up
42
- * with it instead of silently claiming a different version.
43
- */
44
18
  function extractChromeVersion(userAgent) {
45
19
  if (typeof userAgent !== "string") return null;
46
20
  const m = userAgent.match(/Chrome\/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
@@ -48,19 +22,6 @@ function extractChromeVersion(userAgent) {
48
22
  return { full: `${m[1]}.${m[2]}.${m[3]}.${m[4]}`, major: m[1] };
49
23
  }
50
24
 
51
- /**
52
- * Build one internally-consistent identity object for a session.
53
- * - No arguments: returns the stable default identity.
54
- * - customUserAgent: if it's a recognizable Chrome UA, the sec-ch-ua/
55
- * full-version-list are regenerated to match that exact version instead
56
- * of contradicting it. Non-Chrome UAs get the UA respected as-is but no
57
- * Chromium client hints are attached (since claiming Chromium hints next
58
- * to a non-Chromium UA is itself a contradiction).
59
- *
60
- * This function is pure - it never mutates process-wide state and never
61
- * changes its answer for the same input, so it is safe to call repeatedly
62
- * for the same session without identity drift.
63
- */
64
25
  function getIdentity(customUserAgent) {
65
26
  if (!customUserAgent || customUserAgent === DEFAULT_IDENTITY.userAgent) {
66
27
  return DEFAULT_IDENTITY;
@@ -68,8 +29,7 @@ function getIdentity(customUserAgent) {
68
29
 
69
30
  const parsed = extractChromeVersion(customUserAgent);
70
31
  if (!parsed) {
71
- // Unknown / non-Chrome UA supplied explicitly by the caller: respect it,
72
- // but do not attach Chromium-specific client hints that would contradict it.
32
+
73
33
  return Object.freeze({
74
34
  userAgent: customUserAgent,
75
35
  acceptLanguage: DEFAULT_IDENTITY.acceptLanguage,
@@ -96,13 +56,6 @@ function getIdentity(customUserAgent) {
96
56
  });
97
57
  }
98
58
 
99
- /**
100
- * Resolve the identity that should be used for a given session context.
101
- * Caches the resolved identity on the context object so it stays stable
102
- * (does not get recomputed / drift) for the lifetime of that session, per
103
- * requirement: "keep the identity stable for the lifetime of one
104
- * authenticated session".
105
- */
106
59
  function getSessionIdentity(ctx) {
107
60
  if (ctx && ctx._identity) return ctx._identity;
108
61
  const identity = getIdentity(ctx && ctx.globalOptions && ctx.globalOptions.userAgent);
@@ -1,7 +1,5 @@
1
1
  "use strict";
2
2
 
3
- // Cookie helpers extracted from client.js
4
-
5
3
  function saveCookies(jar) {
6
4
  return res => {
7
5
  try {
@@ -16,12 +14,12 @@ function saveCookies(jar) {
16
14
  try {
17
15
  jar.setCookieSync(c, url);
18
16
  } catch {
19
- // ignore per-cookie errors
17
+
20
18
  }
21
19
  }
22
20
  }
23
21
  } catch {
24
- // ignore unexpected cookie parsing errors
22
+
25
23
  }
26
24
  return res;
27
25
  };
@@ -4,9 +4,6 @@ function getType(obj) {
4
4
  return Object.prototype.toString.call(obj).slice(8, -1);
5
5
  }
6
6
 
7
- // [Fixed by xalman] formatID now coerces id to String before .replace() -
8
- // previously crashed with "id.replace is not a function" whenever a numeric
9
- // userID was passed (e.g. addFriend), since Number has no .replace method.
10
7
  function formatID(id) {
11
8
  if (id != undefined && id != null) return String(id).replace(/(fb)?id[:.]/, "");
12
9
  else return id;
@@ -38,10 +35,6 @@ function arrToForm(form) {
38
35
  );
39
36
  }
40
37
 
41
- // [Fixed by xalman] Stt was previously incremented ("Stt++") on every
42
- // recursive call, which silently coerced any non-numeric default value
43
- // (string/null/object - the normal case) to NaN one level deep. It's a
44
- // static fallback value, so it's now passed through unchanged.
45
38
  function getData_Path(Obj, Arr, Stt) {
46
39
  if (Arr.length === 0 && Obj != undefined) {
47
40
  return Obj;
@@ -56,9 +49,6 @@ function getData_Path(Obj, Arr, Stt) {
56
49
  return getData_Path(Obj[head], tail, Stt);
57
50
  }
58
51
 
59
- // [Fixed by xalman] Rewritten - the old version reassigned a local variable
60
- // instead of the actual object property, so updating an EXISTING truthy
61
- // value silently did nothing. Also stopped mutating the caller's path array.
62
52
  function setData_Path(obj, path, value) {
63
53
  if (!path.length) {
64
54
  return obj;
@@ -2,48 +2,37 @@
2
2
 
3
3
  const { getIdentity } = require("./clientIdentity");
4
4
 
5
- // Sanitize header value to remove invalid characters
6
5
  function sanitizeHeaderValue(value) {
7
6
  if (value === null || value === undefined) return "";
8
7
  let str = String(value);
9
8
 
10
- // Remove array-like strings (e.g., "["performAutoLogin"]")
11
- // This handles cases where arrays were accidentally stringified
12
9
  if (str.trim().startsWith("[") && str.trim().endsWith("]")) {
13
- // Try to detect if it's a stringified array and remove it
10
+
14
11
  try {
15
12
  const parsed = JSON.parse(str);
16
13
  if (Array.isArray(parsed)) {
17
- // If it's an array, return empty string (invalid header value)
14
+
18
15
  return "";
19
16
  }
20
17
  } catch {
21
- // Not valid JSON, continue with normal sanitization
18
+
22
19
  }
23
20
  }
24
21
 
25
- // Remove invalid characters for HTTP headers:
26
- // - Control characters (0x00-0x1F, except HTAB 0x09)
27
- // - DEL character (0x7F)
28
- // - Newlines and carriage returns
29
- // - Square brackets (often indicate array stringification issues)
30
22
  str = str.replace(/[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F\r\n\[\]]/g, "").trim();
31
23
 
32
24
  return str;
33
25
  }
34
26
 
35
- // Sanitize header name to ensure it's valid
36
27
  function sanitizeHeaderName(name) {
37
28
  if (!name || typeof name !== "string") return "";
38
- // Remove invalid characters for HTTP header names
29
+
39
30
  return name.replace(/[^\x21-\x7E]/g, "").trim();
40
31
  }
41
32
 
42
33
  function getHeaders(url, options, ctx, customHeader) {
43
34
  const u = new URL(url);
44
- // Resolve one internally-consistent identity (UA + matching client hints)
45
- // instead of hard-coding a browser version here that could contradict
46
- // what other subsystems (MQTT, upload) claim to be.
35
+
47
36
  const identity = getIdentity(options?.userAgent);
48
37
  const ua = identity.userAgent;
49
38
  const referer = options?.referer || "https://www.facebook.com/";
@@ -69,9 +58,7 @@ function getHeaders(url, options, ctx, customHeader) {
69
58
  Pragma: "no-cache",
70
59
  "Cache-Control": "no-cache"
71
60
  };
72
- // Only attach Chromium client hints when the identity actually has them
73
- // (a non-Chrome UA supplied by the caller intentionally omits these, so we
74
- // never claim client hints that contradict the User-Agent string).
61
+
75
62
  if (identity.secChUa) headers["sec-ch-ua"] = identity.secChUa;
76
63
  if (identity.secChUaMobile) headers["sec-ch-ua-mobile"] = identity.secChUaMobile;
77
64
  if (identity.secChUaPlatform) headers["sec-ch-ua-platform"] = identity.secChUaPlatform;
@@ -84,22 +71,21 @@ function getHeaders(url, options, ctx, customHeader) {
84
71
  if (regionValue) headers["X-MSGR-Region"] = regionValue;
85
72
  }
86
73
  if (customHeader && typeof customHeader === "object") {
87
- // Filter customHeader to only include valid HTTP header values (strings, numbers, booleans)
88
- // Exclude functions, objects, arrays, and other non-serializable values
74
+
89
75
  for (const [key, value] of Object.entries(customHeader)) {
90
- // Skip null, undefined, functions, objects, and arrays
76
+
91
77
  if (value === null || value === undefined || typeof value === "function") {
92
78
  continue;
93
79
  }
94
80
  if (typeof value === "object") {
95
- // Arrays are objects in JavaScript, so check for arrays explicitly
81
+
96
82
  if (Array.isArray(value)) {
97
83
  continue;
98
84
  }
99
- // Skip plain objects (but allow null which is already handled above)
85
+
100
86
  continue;
101
87
  }
102
- // Only allow strings, numbers, and booleans - convert to string and sanitize
88
+
103
89
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
104
90
  const sanitizedKey = sanitizeHeaderName(key);
105
91
  const sanitizedValue = sanitizeHeaderValue(value);
@@ -109,7 +95,7 @@ function getHeaders(url, options, ctx, customHeader) {
109
95
  }
110
96
  }
111
97
  }
112
- // Final pass: sanitize all header values to ensure no invalid characters
98
+
113
99
  const sanitizedHeaders = {};
114
100
  for (const [key, value] of Object.entries(headers)) {
115
101
  const sanitizedKey = sanitizeHeaderName(key);
@@ -1,11 +1,5 @@
1
1
  "use strict";
2
- /**
3
- * Single-instance lock per account. Two processes logged into the same account at the same time
4
- * (overlapping Railway deploys, a forgotten second start) produce Facebook's
5
- * "You can't create multiple sessions" restriction. The lock file lives in FCA_NX_STATE_DIR and is
6
- * refreshed every 30s; a lock not refreshed for 120s (crashed process) is considered stale.
7
- * FCA_NX_INSTANCE_LOCK=off disables it.
8
- */
2
+
9
3
  const fs = require("fs");
10
4
  const path = require("path");
11
5
  const STALE_MS = 120000;
@@ -22,7 +16,7 @@ function acquire(userID) {
22
16
  if (cur && cur.pid !== process.pid && Date.now() - cur.at < STALE_MS) {
23
17
  let alive = true;
24
18
  try { process.kill(cur.pid, 0); } catch (e) { alive = e.code === "EPERM"; }
25
- // pid namespaces differ between containers, so trust a fresh heartbeat over kill(0)
19
+
26
20
  if (alive || Date.now() - cur.at < 45000) return { ok: false, pid: cur.pid };
27
21
  }
28
22
  } catch (_) {}
@@ -34,7 +28,7 @@ function acquire(userID) {
34
28
  const release = () => { try { const c = JSON.parse(fs.readFileSync(file, "utf8")); if (c.pid === process.pid) fs.unlinkSync(file); } catch (_) {} };
35
29
  process.once("exit", release);
36
30
  for (const sig of ["SIGINT", "SIGTERM"]) process.once(sig, () => { release(); process.exit(0); });
37
- } catch (_) { /* never block login because of the lock itself */ }
31
+ } catch (_) { }
38
32
  return { ok: true };
39
33
  }
40
34
 
@@ -1,18 +1,5 @@
1
1
  "use strict";
2
2
 
3
- /**
4
- * Login-location consistency guard.
5
- *
6
- * Facebook flags accounts that are logged in from many different IPs/locations. Before a
7
- * cookie login we look up the public IP this process uses (through the same proxy/agent the
8
- * bot uses for Facebook), compare it with the IP of the previous login (stored on disk) and:
9
- * - warn loudly when it changed (default), or
10
- * - refuse to log in when FCA_NX_IP_GUARD=block (use with a static proxy / fixed-IP host).
11
- *
12
- * FCA_NX_IP_GUARD=off disables it. FCA_NX_STATE_DIR (default ./.fca-nx) holds the state file;
13
- * on Railway point it at a Volume so it survives deploys.
14
- */
15
-
16
3
  const fs = require("fs");
17
4
  const path = require("path");
18
5
  const logger = require("../../func/logger");
@@ -33,12 +20,11 @@ async function lookupIP(client) {
33
20
  const res = await client.get(url, { timeout: 5000, headers: { Accept: "application/json" } });
34
21
  const ip = res && res.data && (res.data.ip || res.data.query);
35
22
  if (typeof ip === "string" && ip) return { ip, country: res.data.country || null, region: res.data.region || null };
36
- } catch (_) { /* try next */ }
23
+ } catch (_) { }
37
24
  }
38
25
  return null;
39
26
  }
40
27
 
41
- /** @returns {Promise<{ok:boolean, changed:boolean, ip:string|null, previous:string|null}>} */
42
28
  async function checkLoginIP(client, userID) {
43
29
  const mode = String(process.env.FCA_NX_IP_GUARD || "warn").toLowerCase();
44
30
  if (mode === "off" || mode === "0" || mode === "false") return { ok: true, changed: false, ip: null, previous: null };
@@ -2,14 +2,6 @@
2
2
 
3
3
  const logger = require("../../../func/logger");
4
4
 
5
- /**
6
- * Tạo hàm maybeAutoLogin: khi session hết hạn thì thử đăng nhập lại và retry request.
7
- * @param {Object} ctx - Context (jar, performAutoLogin, globalOptions, ...)
8
- * @param {Object} http - HTTP client (get, post, postFormData)
9
- * @param {Object} helpers - { buildUrl, headerOf, formatCookie }
10
- * @param {Function} emit - createEmit(ctx)
11
- * @param {Function} parseAndCheckLogin - Hàm parse chính để retry sau khi auto login thành công
12
- */
13
5
  function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
14
6
  const { buildUrl, headerOf, formatCookie } = helpers;
15
7
 
@@ -70,10 +62,6 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
70
62
  }
71
63
  };
72
64
 
73
- // Several requests can discover an expired session at the same time when
74
- // many users interact with the bot. They must share one recovery attempt;
75
- // rejecting all followers as "already in progress" creates an auth storm
76
- // and can make the MQTT session look logged out.
77
65
  if (ctx._autoLoginPromise) {
78
66
  let ok;
79
67
  try {
@@ -5,10 +5,6 @@ const { makeParsable } = require("./textUtils");
5
5
  const { delay, createEmit, headerOf, buildUrl, formatCookie } = require("./helpers");
6
6
  const { createMaybeAutoLogin } = require("./autoLogin");
7
7
 
8
- /**
9
- * Trả về hàm async (res) => parsed | throw.
10
- * Xử lý: retry 5xx, parse JSON, redirect, cookie/DTSG, checkpoint và auto login.
11
- */
12
8
  function parseAndCheckLogin(ctx, http, retryCount = 0) {
13
9
  const emit = createEmit(ctx);
14
10
  const helpers = { buildUrl, headerOf, formatCookie };
@@ -17,7 +13,6 @@ function parseAndCheckLogin(ctx, http, retryCount = 0) {
17
13
  return async function handleResponse(res) {
18
14
  const status = res?.status ?? 0;
19
15
 
20
- // Retry khi 5xx
21
16
  if (status >= 500 && status < 600) {
22
17
  if (retryCount >= 5) {
23
18
  const err = new Error(
@@ -147,7 +142,6 @@ function parseAndCheckLogin(ctx, http, retryCount = 0) {
147
142
  return await parseAndCheckLogin(ctx, http)(redirectRes);
148
143
  }
149
144
 
150
- // Cookie từ jsmods
151
145
  if (
152
146
  parsed?.jsmods &&
153
147
  parsed.jsmods.require &&
@@ -169,7 +163,6 @@ function parseAndCheckLogin(ctx, http, retryCount = 0) {
169
163
  );
170
164
  }
171
165
 
172
- // DTSG token
173
166
  if (parsed?.jsmods && Array.isArray(parsed.jsmods.require)) {
174
167
  for (const item of parsed.jsmods.require) {
175
168
  if (item[0] === "DTSG" && item[1] === "setToken") {
@@ -1,8 +1,5 @@
1
1
  "use strict";
2
2
 
3
- /**
4
- * Loại bỏ XSSI prefix và ký tự thừa từ chuỗi response.
5
- */
6
3
  function cleanXssi(t) {
7
4
  if (t == null) return "";
8
5
  let s = String(t);
@@ -12,9 +9,6 @@ function cleanXssi(t) {
12
9
  return s;
13
10
  }
14
11
 
15
- /**
16
- * Chuẩn hóa HTML/JSON response thành chuỗi có thể parse (nối nhiều object thành array).
17
- */
18
12
  function makeParsable(html) {
19
13
  const raw = cleanXssi(String(html || ""));
20
14
  const split = raw.split(/\}\r?\n\s*\{/);
@@ -6,10 +6,7 @@ const { getAgentForProxy } = require("./proxy");
6
6
 
7
7
  function cfg(base = {}) {
8
8
  const { reqJar, headers, params, agent, timeout, proxyUrl } = base;
9
- // Prefer an explicit per-session proxy (ctx.globalOptions.proxy, threaded
10
- // in from methods.js) over the process-wide default set by setProxy().
11
- // This keeps one account's proxy/IP change from silently affecting
12
- // another account's in-flight session in the same process.
9
+
13
10
  const resolvedAgent = agent || (proxyUrl !== undefined ? getAgentForProxy(proxyUrl) : undefined);
14
11
  return {
15
12
  headers: sanitizeHeaders(headers),
@@ -14,11 +14,8 @@ const {
14
14
  isPairArrayList,
15
15
  } = require("./helpers");
16
16
 
17
-
18
- // [Hardened5] mild global spacing between FB Graph/API posts to avoid bursty bot patterns.
19
- // Does NOT block forever - only adds a small delay when calls are very close together.
20
17
  let __lastFbPostAt = 0;
21
- const __MIN_FB_POST_GAP_MS = 180; // ~5-6 req/s max sustained, still fast enough for bots
18
+ const __MIN_FB_POST_GAP_MS = 180;
22
19
  async function __paceFbPost(url) {
23
20
  try {
24
21
  const u = String(url || "");
@@ -3,10 +3,6 @@
3
3
  const { HttpsProxyAgent } = require("https-proxy-agent");
4
4
  const { client } = require("./client");
5
5
 
6
- // Per-proxy-URL agent cache so we don't create a new agent (and socket pool)
7
- // on every single request, while still letting different sessions in the
8
- // same process use different proxies (or no proxy) without stepping on each
9
- // other. Keyed by the proxy URL string; "" represents "no proxy".
10
6
  const agentCache = new Map();
11
7
 
12
8
  function getAgentForProxy(proxyUrl) {
@@ -18,15 +14,6 @@ function getAgentForProxy(proxyUrl) {
18
14
  return agent;
19
15
  }
20
16
 
21
- // Global default proxy setter, kept for backward compatibility with
22
- // existing callers (api.setOptions({ proxy })) and single-account use.
23
- // NOTE: this changes the DEFAULT used only when a request doesn't specify
24
- // its own per-session proxy (see cfg() in ./config.js, which now prefers
25
- // ctx.globalOptions.proxy when present). In a multi-account process, each
26
- // account's requests should carry their own ctx.globalOptions.proxy so
27
- // calling setProxy() for one account can no longer change another running
28
- // account's outbound IP mid-session - that accidental cross-session proxy
29
- // change was flagged as a real risk for "abnormal session" detection.
30
17
  function setProxy(proxyUrl) {
31
18
  if (!proxyUrl) {
32
19
  client.defaults.httpAgent = undefined;
@@ -2,7 +2,6 @@
2
2
 
3
3
  const { delay } = require("./client");
4
4
 
5
- // [Hardened5] light spacing for FB hosts to reduce burst fingerprints
6
5
  let __lastFbAt = 0;
7
6
  async function __pace() {
8
7
  const now = Date.now();
@@ -29,7 +29,7 @@ function sanitizeHeaders(headers) {
29
29
  const parsed = JSON.parse(trimmed);
30
30
  if (Array.isArray(parsed)) continue;
31
31
  } catch {
32
- // continue with normal sanitization
32
+
33
33
  }
34
34
  }
35
35
  }
@@ -1,19 +1,7 @@
1
1
  "use strict";
2
2
 
3
- /**
4
- * Outgoing-message pacing.
5
- *
6
- * Every outgoing message (MQTT, OldMessage and E2EE) is serialised through one queue and is
7
- * released no sooner than `delay` ms after the previous one. This avoids sending bursts that
8
- * look like a script and that Facebook's rate limiting reacts to.
9
- *
10
- * FCA_NX_SEND_DELAY_MS base gap between sends, default 1500 (set 0 to disable)
11
- * FCA_NX_SEND_JITTER_MS extra random 0..N ms added to each gap, default 600
12
- * or at runtime: api.setSendDelay(ms, jitterMs)
13
- */
14
-
15
3
  const state = { last: 0, chain: Promise.resolve(), delay: null, jitter: null, stamps: [] };
16
- // Hard ceiling per rolling minute (FCA_NX_SEND_MAX_PER_MIN, default 12, 0 = off).
4
+
17
5
  function maxPerMin() {
18
6
  const n = Number(process.env.FCA_NX_SEND_MAX_PER_MIN);
19
7
  return Number.isFinite(n) && n >= 0 ? n : 12;
@@ -37,7 +25,6 @@ function setSendDelay(ms, jitterMs) {
37
25
  return { delay: getDelay(), jitter: getJitter() };
38
26
  }
39
27
 
40
- /** Resolves when it is this caller's turn to send. */
41
28
  function waitTurn() {
42
29
  const delay = getDelay();
43
30
  if (delay <= 0) return Promise.resolve();
@@ -225,13 +225,7 @@ function decodeClientPayload(payload) {
225
225
 
226
226
  function parseAndCheckLogin(ctx, defaultFuncs) {
227
227
  return function (res) {
228
- // [Fixed by xalman] this used to read res.statusCode/res.body, which are the old
229
- // `request`/`request-promise` library's property names. The actual
230
- // HTTP client here (src/utils/request) is axios-based, whose
231
- // responses use res.status/res.data instead - res.body was always
232
- // undefined, so this threw "Empty response body" on every single
233
- // call. That silently broke OldMessage.js (used for DM attachments,
234
- // and as the fallback whenever an MQTT send fails).
228
+
235
229
  var status = res && res.status !== undefined ? res.status : (res && res.statusCode);
236
230
  if (status >= 500 && status < 600) {
237
231
  throw { error: "Facebook internal server error: " + status, res };
@@ -303,7 +297,7 @@ function makeDefaults(html, userID, ctx) {
303
297
 
304
298
  function _formatAttachment(attachment, atch) {
305
299
  atch = atch || attachment.mercury || {};
306
- // Also pull in mercuryJSON if mercury was empty
300
+
307
301
  if (attachment.mercuryJSON && !atch.attach_type && !atch.blob_attachment && !atch.sticker_attachment) {
308
302
  try { Object.assign(atch, JSON.parse(attachment.mercuryJSON)); } catch (_) {}
309
303
  }
@@ -377,8 +371,7 @@ function _formatAttachment(attachment, atch) {
377
371
  attach.framesPerCol = preview.framesPerCol || atch.frames_per_column;
378
372
  break;
379
373
  default: {
380
- // blob_attachment lives inside atch (mercury) for MQTT delta messages.
381
- // Fall back to attachment.blob_attachment for ForcedFetch / getThreadHistory paths.
374
+
382
375
  var blob = atch.blob_attachment || attachment.blob_attachment;
383
376
  if (blob) {
384
377
  var typename = blob.__typename || "";
@@ -421,7 +414,6 @@ function _formatAttachment(attachment, atch) {
421
414
  attach.ID = blob.legacy_attachment_id || blob.message_file_fbid || attach.ID;
422
415
  }
423
416
 
424
- // sticker_attachment lives inside atch (mercury) in MQTT delta messages
425
417
  if (!blob && atch.sticker_attachment) {
426
418
  var sticker = atch.sticker_attachment;
427
419
  attach.type = "sticker";
@@ -452,7 +444,6 @@ function _extractMentions(delta, body) {
452
444
  var mentions = {};
453
445
  var d = delta.data || {};
454
446
 
455
- // Strategy 1: prng JSON array [{i, o, l}] — legacy delta format
456
447
  try {
457
448
  if (d.prng) {
458
449
  JSON.parse(d.prng).forEach(function(u) {
@@ -462,7 +453,6 @@ function _extractMentions(delta, body) {
462
453
  }
463
454
  } catch (_) {}
464
455
 
465
- // Strategy 2: flat CSV fields in data (data.mention_ids / mentions_ids / mentionIds)
466
456
  if (!Object.keys(mentions).length) {
467
457
  var mids = _splitCsv(d.mention_ids || d.mentions_ids || d.mentionIds);
468
458
  var mos = _splitCsv(d.mention_offsets || d.mentions_offsets || d.mentionOffsets);
@@ -473,7 +463,6 @@ function _extractMentions(delta, body) {
473
463
  }
474
464
  }
475
465
 
476
- // Strategy 3: ranges / profileRanges array (newer delta format)
477
466
  if (!Object.keys(mentions).length) {
478
467
  var ranges = [];
479
468
  if (Array.isArray(delta.ranges)) ranges = delta.ranges;
@@ -489,9 +478,6 @@ function _extractMentions(delta, body) {
489
478
  });
490
479
  }
491
480
 
492
- // Strategy 4: Gb protobuf nested format — Facebook encodes mentions inside
493
- // messageMetadata.data.data.Gb.asMap.data when sending via the newer Gb path.
494
- // Reference: stfca formatDeltaMessage (confirmed working in v1.3.2+)
495
481
  if (!Object.keys(mentions).length) {
496
482
  try {
497
483
  var md2 = delta.messageMetadata || {};