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.
Files changed (79) hide show
  1. package/README.md +24 -10
  2. package/func/checkUpdate.js +1 -1
  3. package/func/logAdapter.js +2 -0
  4. package/index.js +3 -0
  5. package/module/config.js +5 -3
  6. package/module/login.js +38 -13
  7. package/module/loginHelper.js +207 -148
  8. package/module/options.js +7 -1
  9. package/package.json +2 -2
  10. package/src/api/action/addfriend.js +9 -3
  11. package/src/api/action/changeAvatar.js +1 -0
  12. package/src/api/action/changeCover.js +3 -1
  13. package/src/api/action/enableAutoSaveAppState.js +18 -5
  14. package/src/api/action/refreshFb_dtsg.js +18 -76
  15. package/src/api/http/httpGet.js +6 -2
  16. package/src/api/http/httpPost.js +7 -2
  17. package/src/api/messaging/createNewGroup.js +1 -1
  18. package/src/api/messaging/deleteMessage.js +1 -1
  19. package/src/api/messaging/forwardMessage.js +9 -1
  20. package/src/api/messaging/getEmojiUrl.js +5 -1
  21. package/src/api/messaging/getMessage.js +4 -2
  22. package/src/api/messaging/getThemePictures.js +7 -0
  23. package/src/api/messaging/markAsRead.js +1 -0
  24. package/src/api/messaging/muteThread.js +1 -1
  25. package/src/api/messaging/pinMessage.js +10 -1
  26. package/src/api/messaging/scheduler.js +71 -4
  27. package/src/api/messaging/sendBroadcast.js +15 -0
  28. package/src/api/messaging/sendMessage.js +23 -1
  29. package/src/api/messaging/sendTypingIndicator.js +0 -15
  30. package/src/api/messaging/sessionGuard.js +45 -9
  31. package/src/api/messaging/setMessageReaction.js +2 -1
  32. package/src/api/messaging/threadColors.js +45 -12
  33. package/src/api/messaging/uploadAttachment.js +37 -3
  34. package/src/api/socket/OldMessage.js +7 -2
  35. package/src/api/socket/core/connectMqtt.js +68 -81
  36. package/src/api/socket/core/emitAuth.js +11 -2
  37. package/src/api/socket/core/getSeqID.js +52 -56
  38. package/src/api/socket/core/getTaskResponseData.js +3 -1
  39. package/src/api/socket/core/parseDelta.js +1 -1
  40. package/src/api/socket/detail/buildStream.js +4 -1
  41. package/src/api/socket/detail/constants.js +4 -1
  42. package/src/api/socket/e2ee/crypto.js +40 -2
  43. package/src/api/socket/e2ee/index.js +123 -10
  44. package/src/api/socket/e2ee/protocol.js +32 -1
  45. package/src/api/socket/e2ee/ratchet.js +44 -10
  46. package/src/api/socket/e2ee/store.js +13 -1
  47. package/src/api/socket/listenE2EE.js +25 -1
  48. package/src/api/socket/listenMqtt.js +94 -110
  49. package/src/api/socket/middleware/index.js +61 -7
  50. package/src/api/socket/sendMessage.js +19 -2
  51. package/src/api/socket/sendMessageMqtt.js +6 -0
  52. package/src/api/threads/getThreadHistory.js +68 -38
  53. package/src/api/threads/getThreadInfo.js +4 -3
  54. package/src/api/threads/getThreadList.js +34 -31
  55. package/src/api/threads/getThreadPictures.js +1 -1
  56. package/src/api/users/getUserInfo.js +5 -2
  57. package/src/api/users/getUserInfoV2.js +9 -3
  58. package/src/app/createFcaClient.js +2 -2
  59. package/src/core/sendReqMqtt.js +2 -1
  60. package/src/database/helpers.js +12 -0
  61. package/src/database/models/index.js +8 -9
  62. package/src/utils/broadcast.js +1 -1
  63. package/src/utils/clientIdentity.js +50 -3
  64. package/src/utils/cookies.js +4 -2
  65. package/src/utils/format/utils.js +10 -0
  66. package/src/utils/headers.js +26 -12
  67. package/src/utils/loginParser/autoLogin.js +12 -0
  68. package/src/utils/loginParser/parseAndCheckLogin.js +7 -0
  69. package/src/utils/loginParser/textUtils.js +6 -0
  70. package/src/utils/request/config.js +4 -1
  71. package/src/utils/request/methods.js +0 -13
  72. package/src/utils/request/proxy.js +13 -0
  73. package/src/utils/request/retry.js +0 -10
  74. package/src/utils/request/sanitize.js +1 -1
  75. package/src/utils/sendThrottle.js +14 -1
  76. package/src/utils/textEffects.js +92 -0
  77. package/src/utils/utils.js +17 -3
  78. package/src/utils/instanceLock.js +0 -35
  79. package/src/utils/ipGuard.js +0 -58
@@ -16,20 +16,21 @@ try {
16
16
  storage: path.join(databasePath, "database.sqlite"),
17
17
  logging: false,
18
18
  pool: {
19
- max: 1,
19
+ max: 5,
20
20
  min: 0,
21
- acquire: 8000,
22
- idle: 5000
21
+ acquire: 30000,
22
+ idle: 10000
23
23
  },
24
24
  retry: {
25
- max: 1
25
+ max: 3
26
26
  },
27
27
  dialectOptions: {
28
- timeout: 8000
28
+ timeout: 5000
29
29
  },
30
30
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
31
31
  });
32
32
 
33
+ // Load models with error handling
33
34
  try {
34
35
  const modelFiles = fs.readdirSync(__dirname)
35
36
  .filter(file => file.endsWith(".js") && file !== "index.js");
@@ -41,11 +42,12 @@ try {
41
42
  models[model.name] = model;
42
43
  }
43
44
  } catch (modelError) {
44
-
45
+ // Log but continue loading other models
45
46
  console.error(`Failed to load model ${file}:`, modelError && modelError.message ? modelError.message : String(modelError));
46
47
  }
47
48
  }
48
49
 
50
+ // Associate models
49
51
  Object.keys(models).forEach(modelName => {
50
52
  try {
51
53
  if (models[modelName].associate) {
@@ -67,9 +69,6 @@ try {
67
69
  if (!sequelize) {
68
70
  throw new Error("Sequelize instance not initialized");
69
71
  }
70
- await sequelize.query("PRAGMA journal_mode=WAL;");
71
- await sequelize.query("PRAGMA synchronous=NORMAL;");
72
- await sequelize.query("PRAGMA busy_timeout=8000;");
73
72
  await sequelize.sync({ force: false });
74
73
  } catch (error) {
75
74
  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
-
39
+ // Skip only this target, continue with others
40
40
  }
41
41
  }
42
42
  if (delayMs > 0) {
@@ -1,11 +1,31 @@
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
+ */
2
21
 
3
- const CHROME_VERSION = "131.0.6778.205";
22
+ // One version pin used everywhere. Bump this in one place when needed.
23
+ const CHROME_VERSION = "139.0.0.0";
4
24
  const CHROME_MAJOR = CHROME_VERSION.split(".")[0];
5
25
 
6
26
  const DEFAULT_IDENTITY = Object.freeze({
7
27
  userAgent: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${CHROME_VERSION} Safari/537.36`,
8
- acceptLanguage: "en-US,en;q=0.9,bn;q=0.8",
28
+ acceptLanguage: "en-US,en;q=0.9",
9
29
  secChUa: `"Chromium";v="${CHROME_MAJOR}", "Not;A=Brand";v="24", "Google Chrome";v="${CHROME_MAJOR}"`,
10
30
  secChUaMobile: "?0",
11
31
  secChUaPlatform: '"Windows"',
@@ -15,6 +35,12 @@ const DEFAULT_IDENTITY = Object.freeze({
15
35
  secChUaPlatformVersion: '"15.0.0"'
16
36
  });
17
37
 
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
+ */
18
44
  function extractChromeVersion(userAgent) {
19
45
  if (typeof userAgent !== "string") return null;
20
46
  const m = userAgent.match(/Chrome\/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
@@ -22,6 +48,19 @@ function extractChromeVersion(userAgent) {
22
48
  return { full: `${m[1]}.${m[2]}.${m[3]}.${m[4]}`, major: m[1] };
23
49
  }
24
50
 
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
+ */
25
64
  function getIdentity(customUserAgent) {
26
65
  if (!customUserAgent || customUserAgent === DEFAULT_IDENTITY.userAgent) {
27
66
  return DEFAULT_IDENTITY;
@@ -29,7 +68,8 @@ function getIdentity(customUserAgent) {
29
68
 
30
69
  const parsed = extractChromeVersion(customUserAgent);
31
70
  if (!parsed) {
32
-
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.
33
73
  return Object.freeze({
34
74
  userAgent: customUserAgent,
35
75
  acceptLanguage: DEFAULT_IDENTITY.acceptLanguage,
@@ -56,6 +96,13 @@ function getIdentity(customUserAgent) {
56
96
  });
57
97
  }
58
98
 
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
+ */
59
106
  function getSessionIdentity(ctx) {
60
107
  if (ctx && ctx._identity) return ctx._identity;
61
108
  const identity = getIdentity(ctx && ctx.globalOptions && ctx.globalOptions.userAgent);
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
 
3
+ // Cookie helpers extracted from client.js
4
+
3
5
  function saveCookies(jar) {
4
6
  return res => {
5
7
  try {
@@ -14,12 +16,12 @@ function saveCookies(jar) {
14
16
  try {
15
17
  jar.setCookieSync(c, url);
16
18
  } catch {
17
-
19
+ // ignore per-cookie errors
18
20
  }
19
21
  }
20
22
  }
21
23
  } catch {
22
-
24
+ // ignore unexpected cookie parsing errors
23
25
  }
24
26
  return res;
25
27
  };
@@ -4,6 +4,9 @@ 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.
7
10
  function formatID(id) {
8
11
  if (id != undefined && id != null) return String(id).replace(/(fb)?id[:.]/, "");
9
12
  else return id;
@@ -35,6 +38,10 @@ function arrToForm(form) {
35
38
  );
36
39
  }
37
40
 
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.
38
45
  function getData_Path(Obj, Arr, Stt) {
39
46
  if (Arr.length === 0 && Obj != undefined) {
40
47
  return Obj;
@@ -49,6 +56,9 @@ function getData_Path(Obj, Arr, Stt) {
49
56
  return getData_Path(Obj[head], tail, Stt);
50
57
  }
51
58
 
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.
52
62
  function setData_Path(obj, path, value) {
53
63
  if (!path.length) {
54
64
  return obj;
@@ -2,37 +2,48 @@
2
2
 
3
3
  const { getIdentity } = require("./clientIdentity");
4
4
 
5
+ // Sanitize header value to remove invalid characters
5
6
  function sanitizeHeaderValue(value) {
6
7
  if (value === null || value === undefined) return "";
7
8
  let str = String(value);
8
9
 
10
+ // Remove array-like strings (e.g., "["performAutoLogin"]")
11
+ // This handles cases where arrays were accidentally stringified
9
12
  if (str.trim().startsWith("[") && str.trim().endsWith("]")) {
10
-
13
+ // Try to detect if it's a stringified array and remove it
11
14
  try {
12
15
  const parsed = JSON.parse(str);
13
16
  if (Array.isArray(parsed)) {
14
-
17
+ // If it's an array, return empty string (invalid header value)
15
18
  return "";
16
19
  }
17
20
  } catch {
18
-
21
+ // Not valid JSON, continue with normal sanitization
19
22
  }
20
23
  }
21
24
 
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)
22
30
  str = str.replace(/[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F\r\n\[\]]/g, "").trim();
23
31
 
24
32
  return str;
25
33
  }
26
34
 
35
+ // Sanitize header name to ensure it's valid
27
36
  function sanitizeHeaderName(name) {
28
37
  if (!name || typeof name !== "string") return "";
29
-
38
+ // Remove invalid characters for HTTP header names
30
39
  return name.replace(/[^\x21-\x7E]/g, "").trim();
31
40
  }
32
41
 
33
42
  function getHeaders(url, options, ctx, customHeader) {
34
43
  const u = new URL(url);
35
-
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.
36
47
  const identity = getIdentity(options?.userAgent);
37
48
  const ua = identity.userAgent;
38
49
  const referer = options?.referer || "https://www.facebook.com/";
@@ -58,7 +69,9 @@ function getHeaders(url, options, ctx, customHeader) {
58
69
  Pragma: "no-cache",
59
70
  "Cache-Control": "no-cache"
60
71
  };
61
-
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).
62
75
  if (identity.secChUa) headers["sec-ch-ua"] = identity.secChUa;
63
76
  if (identity.secChUaMobile) headers["sec-ch-ua-mobile"] = identity.secChUaMobile;
64
77
  if (identity.secChUaPlatform) headers["sec-ch-ua-platform"] = identity.secChUaPlatform;
@@ -71,21 +84,22 @@ function getHeaders(url, options, ctx, customHeader) {
71
84
  if (regionValue) headers["X-MSGR-Region"] = regionValue;
72
85
  }
73
86
  if (customHeader && typeof customHeader === "object") {
74
-
87
+ // Filter customHeader to only include valid HTTP header values (strings, numbers, booleans)
88
+ // Exclude functions, objects, arrays, and other non-serializable values
75
89
  for (const [key, value] of Object.entries(customHeader)) {
76
-
90
+ // Skip null, undefined, functions, objects, and arrays
77
91
  if (value === null || value === undefined || typeof value === "function") {
78
92
  continue;
79
93
  }
80
94
  if (typeof value === "object") {
81
-
95
+ // Arrays are objects in JavaScript, so check for arrays explicitly
82
96
  if (Array.isArray(value)) {
83
97
  continue;
84
98
  }
85
-
99
+ // Skip plain objects (but allow null which is already handled above)
86
100
  continue;
87
101
  }
88
-
102
+ // Only allow strings, numbers, and booleans - convert to string and sanitize
89
103
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
90
104
  const sanitizedKey = sanitizeHeaderName(key);
91
105
  const sanitizedValue = sanitizeHeaderValue(value);
@@ -95,7 +109,7 @@ function getHeaders(url, options, ctx, customHeader) {
95
109
  }
96
110
  }
97
111
  }
98
-
112
+ // Final pass: sanitize all header values to ensure no invalid characters
99
113
  const sanitizedHeaders = {};
100
114
  for (const [key, value] of Object.entries(headers)) {
101
115
  const sanitizedKey = sanitizeHeaderName(key);
@@ -2,6 +2,14 @@
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
+ */
5
13
  function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
6
14
  const { buildUrl, headerOf, formatCookie } = helpers;
7
15
 
@@ -62,6 +70,10 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
62
70
  }
63
71
  };
64
72
 
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.
65
77
  if (ctx._autoLoginPromise) {
66
78
  let ok;
67
79
  try {
@@ -5,6 +5,10 @@ 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
+ */
8
12
  function parseAndCheckLogin(ctx, http, retryCount = 0) {
9
13
  const emit = createEmit(ctx);
10
14
  const helpers = { buildUrl, headerOf, formatCookie };
@@ -13,6 +17,7 @@ function parseAndCheckLogin(ctx, http, retryCount = 0) {
13
17
  return async function handleResponse(res) {
14
18
  const status = res?.status ?? 0;
15
19
 
20
+ // Retry khi 5xx
16
21
  if (status >= 500 && status < 600) {
17
22
  if (retryCount >= 5) {
18
23
  const err = new Error(
@@ -142,6 +147,7 @@ function parseAndCheckLogin(ctx, http, retryCount = 0) {
142
147
  return await parseAndCheckLogin(ctx, http)(redirectRes);
143
148
  }
144
149
 
150
+ // Cookie từ jsmods
145
151
  if (
146
152
  parsed?.jsmods &&
147
153
  parsed.jsmods.require &&
@@ -163,6 +169,7 @@ function parseAndCheckLogin(ctx, http, retryCount = 0) {
163
169
  );
164
170
  }
165
171
 
172
+ // DTSG token
166
173
  if (parsed?.jsmods && Array.isArray(parsed.jsmods.require)) {
167
174
  for (const item of parsed.jsmods.require) {
168
175
  if (item[0] === "DTSG" && item[1] === "setToken") {
@@ -1,5 +1,8 @@
1
1
  "use strict";
2
2
 
3
+ /**
4
+ * Loại bỏ XSSI prefix và ký tự thừa từ chuỗi response.
5
+ */
3
6
  function cleanXssi(t) {
4
7
  if (t == null) return "";
5
8
  let s = String(t);
@@ -9,6 +12,9 @@ function cleanXssi(t) {
9
12
  return s;
10
13
  }
11
14
 
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
+ */
12
18
  function makeParsable(html) {
13
19
  const raw = cleanXssi(String(html || ""));
14
20
  const split = raw.split(/\}\r?\n\s*\{/);
@@ -6,7 +6,10 @@ const { getAgentForProxy } = require("./proxy");
6
6
 
7
7
  function cfg(base = {}) {
8
8
  const { reqJar, headers, params, agent, timeout, proxyUrl } = base;
9
-
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.
10
13
  const resolvedAgent = agent || (proxyUrl !== undefined ? getAgentForProxy(proxyUrl) : undefined);
11
14
  return {
12
15
  headers: sanitizeHeaders(headers),
@@ -14,19 +14,6 @@ const {
14
14
  isPairArrayList,
15
15
  } = require("./helpers");
16
16
 
17
- let __lastFbPostAt = 0;
18
- const __MIN_FB_POST_GAP_MS = 180;
19
- async function __paceFbPost(url) {
20
- try {
21
- const u = String(url || "");
22
- if (!/facebook\.com|messenger\.com/i.test(u)) return;
23
- const now = Date.now();
24
- const wait = __MIN_FB_POST_GAP_MS - (now - __lastFbPostAt);
25
- if (wait > 0) await new Promise(r => setTimeout(r, wait + Math.floor(Math.random() * 80)));
26
- __lastFbPostAt = Date.now();
27
- } catch (_) {}
28
- }
29
-
30
17
  function cleanGet(url, ctx) {
31
18
  return requestWithRetry(() => client.get(url, cfg()), 3, 1000, ctx);
32
19
  }
@@ -3,6 +3,10 @@
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".
6
10
  const agentCache = new Map();
7
11
 
8
12
  function getAgentForProxy(proxyUrl) {
@@ -14,6 +18,15 @@ function getAgentForProxy(proxyUrl) {
14
18
  return agent;
15
19
  }
16
20
 
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.
17
30
  function setProxy(proxyUrl) {
18
31
  if (!proxyUrl) {
19
32
  client.defaults.httpAgent = undefined;
@@ -2,18 +2,8 @@
2
2
 
3
3
  const { delay } = require("./client");
4
4
 
5
- let __lastFbAt = 0;
6
- async function __pace() {
7
- const now = Date.now();
8
- const gap = 150 + Math.floor(Math.random() * 100);
9
- const wait = gap - (now - __lastFbAt);
10
- if (wait > 0) await delay(wait);
11
- __lastFbAt = Date.now();
12
- }
13
-
14
5
  async function requestWithRetry(fn, retries = 3, baseDelay = 1000, ctx) {
15
6
  let lastError;
16
- try { await __pace(); } catch (_) {}
17
7
  const emit = (event, payload) => {
18
8
  try {
19
9
  if (ctx && ctx._emitter && typeof ctx._emitter.emit === "function") {
@@ -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
-
32
+ // continue with normal sanitization
33
33
  }
34
34
  }
35
35
  }
@@ -1,7 +1,19 @@
1
1
  "use strict";
2
2
 
3
- const state = { last: 0, chain: Promise.resolve(), delay: null, jitter: null, stamps: [] };
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
+ */
4
14
 
15
+ 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).
5
17
  function maxPerMin() {
6
18
  const n = Number(process.env.FCA_NX_SEND_MAX_PER_MIN);
7
19
  return Number.isFinite(n) && n >= 0 ? n : 12;
@@ -25,6 +37,7 @@ function setSendDelay(ms, jitterMs) {
25
37
  return { delay: getDelay(), jitter: getJitter() };
26
38
  }
27
39
 
40
+ /** Resolves when it is this caller's turn to send. */
28
41
  function waitTurn() {
29
42
  const delay = getDelay();
30
43
  if (delay <= 0) return Promise.resolve();
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+
3
+ const TEXT_EFFECTS = Object.freeze({
4
+ hearts: "1",
5
+ heart: "1",
6
+ love: "1",
7
+ gift: "2",
8
+ present: "2",
9
+ box: "2",
10
+ giftbox: "2",
11
+ fire: "3",
12
+ flame: "3",
13
+ hot: "3",
14
+ confetti: "4",
15
+ confecti: "4",
16
+ party: "4",
17
+ celebrate: "4",
18
+ celebration: "4",
19
+ sparkles: "5",
20
+ sparkle: "5",
21
+ star: "5",
22
+ stars: "5",
23
+ magic: "5"
24
+ });
25
+
26
+ const EFFECT_PROPERTIES = [
27
+ "textEffect",
28
+ "text_effect",
29
+ "text_effect_id",
30
+ "textEffectId",
31
+ "textEffectID",
32
+ "effect",
33
+ "effect_id",
34
+ "effectID",
35
+ "text_effect_name",
36
+ "effectName",
37
+ "effect_name"
38
+ ];
39
+
40
+ function toTextEffectId(effect) {
41
+ if (effect === null || effect === undefined) return null;
42
+ if (typeof effect === "number" && Number.isFinite(effect)) return String(effect);
43
+ if (typeof effect !== "string") return null;
44
+
45
+ const value = effect.trim();
46
+ if (!value) return null;
47
+ return TEXT_EFFECTS[value.toLowerCase()] || value;
48
+ }
49
+
50
+ function getTextEffectId(message) {
51
+ if (!message || typeof message !== "object") return null;
52
+ for (const property of EFFECT_PROPERTIES) {
53
+ if (message[property] !== undefined && message[property] !== null) {
54
+ const effectID = toTextEffectId(message[property]);
55
+ if (effectID) return effectID;
56
+ }
57
+ }
58
+
59
+ const rawIDs = Array.isArray(message.text_effect_ids)
60
+ ? message.text_effect_ids
61
+ : [message.text_effect_ids];
62
+ for (const rawID of rawIDs) {
63
+ const effectID = toTextEffectId(rawID);
64
+ if (effectID) return effectID;
65
+ }
66
+ return null;
67
+ }
68
+
69
+ function getTextEffectIds(message) {
70
+ if (!message || typeof message !== "object") return [];
71
+ const rawIDs = Array.isArray(message.text_effect_ids)
72
+ ? message.text_effect_ids
73
+ : [message.text_effect_ids];
74
+ const ids = rawIDs
75
+ .map(toTextEffectId)
76
+ .filter(Boolean);
77
+ // [Hardened7] `effect: "fire"` / `textEffect` / `effectName` only produced the single id; the
78
+ // array form (text_effect_ids) stayed empty, and Messenger reads the array. Always send both.
79
+ if (!ids.length) {
80
+ const single = getTextEffectId(message);
81
+ if (single) ids.push(single);
82
+ }
83
+ return ids;
84
+ }
85
+
86
+ module.exports = {
87
+ EFFECT_PROPERTIES,
88
+ TEXT_EFFECTS,
89
+ getTextEffectId,
90
+ getTextEffectIds,
91
+ toTextEffectId
92
+ };
@@ -225,7 +225,13 @@ function decodeClientPayload(payload) {
225
225
 
226
226
  function parseAndCheckLogin(ctx, defaultFuncs) {
227
227
  return function (res) {
228
-
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).
229
235
  var status = res && res.status !== undefined ? res.status : (res && res.statusCode);
230
236
  if (status >= 500 && status < 600) {
231
237
  throw { error: "Facebook internal server error: " + status, res };
@@ -297,7 +303,7 @@ function makeDefaults(html, userID, ctx) {
297
303
 
298
304
  function _formatAttachment(attachment, atch) {
299
305
  atch = atch || attachment.mercury || {};
300
-
306
+ // Also pull in mercuryJSON if mercury was empty
301
307
  if (attachment.mercuryJSON && !atch.attach_type && !atch.blob_attachment && !atch.sticker_attachment) {
302
308
  try { Object.assign(atch, JSON.parse(attachment.mercuryJSON)); } catch (_) {}
303
309
  }
@@ -371,7 +377,8 @@ function _formatAttachment(attachment, atch) {
371
377
  attach.framesPerCol = preview.framesPerCol || atch.frames_per_column;
372
378
  break;
373
379
  default: {
374
-
380
+ // blob_attachment lives inside atch (mercury) for MQTT delta messages.
381
+ // Fall back to attachment.blob_attachment for ForcedFetch / getThreadHistory paths.
375
382
  var blob = atch.blob_attachment || attachment.blob_attachment;
376
383
  if (blob) {
377
384
  var typename = blob.__typename || "";
@@ -414,6 +421,7 @@ function _formatAttachment(attachment, atch) {
414
421
  attach.ID = blob.legacy_attachment_id || blob.message_file_fbid || attach.ID;
415
422
  }
416
423
 
424
+ // sticker_attachment lives inside atch (mercury) in MQTT delta messages
417
425
  if (!blob && atch.sticker_attachment) {
418
426
  var sticker = atch.sticker_attachment;
419
427
  attach.type = "sticker";
@@ -444,6 +452,7 @@ function _extractMentions(delta, body) {
444
452
  var mentions = {};
445
453
  var d = delta.data || {};
446
454
 
455
+ // Strategy 1: prng JSON array [{i, o, l}] — legacy delta format
447
456
  try {
448
457
  if (d.prng) {
449
458
  JSON.parse(d.prng).forEach(function(u) {
@@ -453,6 +462,7 @@ function _extractMentions(delta, body) {
453
462
  }
454
463
  } catch (_) {}
455
464
 
465
+ // Strategy 2: flat CSV fields in data (data.mention_ids / mentions_ids / mentionIds)
456
466
  if (!Object.keys(mentions).length) {
457
467
  var mids = _splitCsv(d.mention_ids || d.mentions_ids || d.mentionIds);
458
468
  var mos = _splitCsv(d.mention_offsets || d.mentions_offsets || d.mentionOffsets);
@@ -463,6 +473,7 @@ function _extractMentions(delta, body) {
463
473
  }
464
474
  }
465
475
 
476
+ // Strategy 3: ranges / profileRanges array (newer delta format)
466
477
  if (!Object.keys(mentions).length) {
467
478
  var ranges = [];
468
479
  if (Array.isArray(delta.ranges)) ranges = delta.ranges;
@@ -478,6 +489,9 @@ function _extractMentions(delta, body) {
478
489
  });
479
490
  }
480
491
 
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+)
481
495
  if (!Object.keys(mentions).length) {
482
496
  try {
483
497
  var md2 = delta.messageMetadata || {};