fca-nx 6.8.8 → 7.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) 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 -2
  6. package/module/login.js +38 -13
  7. package/module/loginHelper.js +164 -127
  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 +21 -28
  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 +28 -36
  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 +124 -73
  44. package/src/api/socket/e2ee/protocol.js +40 -32
  45. package/src/api/socket/e2ee/ratchet.js +43 -37
  46. package/src/api/socket/e2ee/store.js +47 -133
  47. package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +18 -140
  48. package/src/api/socket/listenE2EE.js +23 -12
  49. package/src/api/socket/listenMqtt.js +94 -110
  50. package/src/api/socket/middleware/index.js +61 -7
  51. package/src/api/socket/sendMessage.js +78 -170
  52. package/src/api/socket/sendMessageMqtt.js +6 -0
  53. package/src/api/threads/getThreadHistory.js +68 -38
  54. package/src/api/threads/getThreadInfo.js +4 -3
  55. package/src/api/threads/getThreadList.js +34 -31
  56. package/src/api/threads/getThreadPictures.js +1 -1
  57. package/src/api/users/getUserInfo.js +5 -2
  58. package/src/api/users/getUserInfoV2.js +65 -59
  59. package/src/app/createFcaClient.js +2 -2
  60. package/src/core/sendReqMqtt.js +2 -1
  61. package/src/database/helpers.js +12 -0
  62. package/src/database/models/index.js +8 -9
  63. package/src/utils/broadcast.js +1 -1
  64. package/src/utils/clientIdentity.js +50 -3
  65. package/src/utils/cookies.js +4 -2
  66. package/src/utils/format/utils.js +10 -0
  67. package/src/utils/headers.js +26 -12
  68. package/src/utils/loginParser/autoLogin.js +12 -0
  69. package/src/utils/loginParser/parseAndCheckLogin.js +7 -0
  70. package/src/utils/loginParser/textUtils.js +6 -0
  71. package/src/utils/request/config.js +4 -1
  72. package/src/utils/request/methods.js +0 -13
  73. package/src/utils/request/proxy.js +13 -0
  74. package/src/utils/request/retry.js +0 -10
  75. package/src/utils/request/sanitize.js +1 -1
  76. package/src/utils/textEffects.js +85 -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
  80. package/src/utils/sendThrottle.js +0 -51
@@ -71,13 +71,14 @@ function extractPhotoUrl(photo, depth = 0) {
71
71
  }
72
72
  if (typeof photo !== "object") return null;
73
73
 
74
+ // Facebook has returned direct URLs as well as nested image/photo objects
75
+ // from Comet hovercards. Walk only the known media keys and prefer direct
76
+ // URL fields before descending into nested containers.
74
77
  for (const key of [
75
78
  "source",
76
79
  "uri",
77
80
  "url",
78
81
  "image",
79
- "full_image",
80
- "viewer_image",
81
82
  "photo",
82
83
  "media",
83
84
  "cover_photo",
@@ -89,29 +90,6 @@ function extractPhotoUrl(photo, depth = 0) {
89
90
  return null;
90
91
  }
91
92
 
92
- function decodeJsonString(raw) {
93
- try { return JSON.parse('"' + raw + '"'); } catch { return String(raw).replace(/\\\//g, "/"); }
94
- }
95
-
96
- function extractCoverFromHTML(html) {
97
- if (!html || typeof html !== "string") return null;
98
- const patterns = [
99
- /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
100
- /"profile_cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
101
- /"coverPhoto"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
102
- /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"url"\s*:\s*"([^"]+)"/,
103
- /property="og:image"\s+content="(https:\/\/[^"]+fbcdn[^"]+)"/i,
104
- /content="(https:\/\/[^"]+fbcdn[^"]+)"\s+property="og:image"/i
105
- ];
106
- for (const re of patterns) {
107
- const m = html.match(re);
108
- if (!m) continue;
109
- const url = decodeJsonString(m[1]).replace(/&/g, "&");
110
- if (/^https?:\/\//i.test(url) && /(fbcdn|scontent)/i.test(url)) return url;
111
- }
112
- return null;
113
- }
114
-
115
93
  function pickMeta(user) {
116
94
  let friendshipStatus = null;
117
95
  let gender = null;
@@ -136,6 +114,38 @@ function pickMeta(user) {
136
114
  return { friendshipStatus, gender, shortName };
137
115
  }
138
116
 
117
+
118
+ function findCoverUri(node, depth = 0) {
119
+ if (!node || depth > 12) return null;
120
+ if (typeof node === "string" || typeof node !== "object") return null;
121
+ for (const key of ["cover_photo", "coverPhoto", "profile_cover_photo", "timeline_cover_photo", "cover"]) {
122
+ if (node[key] != null) {
123
+ const direct = extractPhotoUrl(node[key]);
124
+ if (direct) return direct;
125
+ }
126
+ }
127
+ const list = Array.isArray(node) ? node : Object.keys(node).filter(k => k !== "extensions" && k !== "errors").map(k => node[k]);
128
+ for (const child of list) {
129
+ const found = findCoverUri(child, depth + 1);
130
+ if (found) return found;
131
+ }
132
+ return null;
133
+ }
134
+
135
+ function coverFromHtml(html) {
136
+ const text = String(html || "");
137
+ const patterns = [
138
+ /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
139
+ /"profile_cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
140
+ /"timeline_cover_photo"\s*:\s*\{[\s\S]{0,400}?"uri"\s*:\s*"([^"]+)"/
141
+ ];
142
+ for (const re of patterns) {
143
+ const match = text.match(re);
144
+ if (match && match[1]) return match[1].replace(/\\\//g, "/").replace(/\\u0026/g, "&");
145
+ }
146
+ return null;
147
+ }
148
+
139
149
  function extractCoverPhoto(user) {
140
150
  const cover = user?.cover_photo;
141
151
  if (!cover) return null;
@@ -160,13 +170,9 @@ function normalizeUser(user) {
160
170
  firstName: meta.shortName || null,
161
171
  vanity,
162
172
  thumbSrc: extractProfilePicture(user),
163
- coverPhoto:
164
- extractPhotoUrl(user.cover_photo) ||
165
- extractPhotoUrl(user.coverPhoto) ||
166
- extractPhotoUrl(user.profile_cover_photo) ||
167
- extractPhotoUrl(user.cover_photo_renderer) ||
168
- extractCoverPhoto(user) ||
169
- null,
173
+ coverPhoto: extractPhotoUrl(
174
+ user.cover_photo || user.coverPhoto || user.profile_cover_photo
175
+ ),
170
176
  profileUrl: user.profile_url || user.url || null,
171
177
  gender: meta.gender || null,
172
178
  type: user.__typename || "User",
@@ -190,7 +196,7 @@ function createDefaultUser(id) {
190
196
  vanity: String(id),
191
197
  thumbSrc: `https://graph.facebook.com/${id}/picture?width=720&height=720`,
192
198
  profilePicUrl: `https://graph.facebook.com/${id}/picture?width=720&height=720`,
193
- coverPhoto: null,
199
+ coverPhoto: null, // FIX: default e null
194
200
  profileUrl: `https://www.facebook.com/profile.php?id=${id}`,
195
201
  gender: "no specific gender",
196
202
  type: "User",
@@ -217,7 +223,7 @@ function formatUser(user, id) {
217
223
  lastName: nameParts.length > 1? nameParts.slice(1).join(" ") : null,
218
224
  vanity: user.vanity || String(id),
219
225
  profilePicUrl: user.thumbSrc || `https://graph.facebook.com/${id}/picture?width=720&height=720`,
220
- coverPhoto: user.coverPhoto || null,
226
+ coverPhoto: user.coverPhoto || null, // FIX: cover photo pass
221
227
  profileUrl: user.profileUrl || `https://www.facebook.com/profile.php?id=${id}`,
222
228
  gender: user.gender || "no specific gender",
223
229
  type: user.type || "User",
@@ -260,6 +266,8 @@ module.exports = function (defaultFuncs, api, ctx) {
260
266
  const parsed = toJSONMaybe(response) || response;
261
267
  const root = Array.isArray(parsed) ? parsed[0] : parsed;
262
268
  const normalized = normalizeUser(findUser(root));
269
+ const cover = findCoverUri(parsed) || findCoverUri(root);
270
+ if (normalized && cover && !normalized.coverPhoto) normalized.coverPhoto = cover;
263
271
  if (!normalized?.id) continue;
264
272
  if (!bestUser) {
265
273
  bestUser = normalized;
@@ -275,30 +283,25 @@ module.exports = function (defaultFuncs, api, ctx) {
275
283
  logger(`getUserInfoV2 ${doc.id}: ${error.message || error}`, "warn");
276
284
  }
277
285
  }
286
+ return bestUser;
287
+ }
278
288
 
279
- if (bestUser && !bestUser.coverPhoto) {
280
- const pages = [`https://www.facebook.com/profile.php?id=${id}`];
281
- if (bestUser.vanity && bestUser.vanity !== id) {
282
- pages.push(`https://www.facebook.com/${bestUser.vanity}`);
283
- }
284
- for (const url of pages) {
285
- try {
286
- const res = await defaultFuncs.get(url, ctx.jar, null, ctx);
287
- const html = typeof res === "string" ? res : (res && res.data);
288
- const cover = extractCoverFromHTML(html);
289
- if (cover) {
290
- bestUser.coverPhoto = cover;
291
- break;
292
- }
293
- } catch (error) {
294
- logger(`getUserInfoV2 cover html ${id}: ${error.message || error}`, "warn");
295
- }
296
- }
297
- if (!bestUser.coverPhoto && process.env.FCA_COVER_DEBUG === "1") {
298
- logger(`getUserInfoV2 cover ${id}: no cover found in GraphQL or profile HTML`, "warn");
289
+ async function fetchCoverFromProfile(userID) {
290
+ const urls = [
291
+ `https://www.facebook.com/profile.php?id=${userID}`,
292
+ `https://mbasic.facebook.com/profile.php?id=${userID}`
293
+ ];
294
+ for (const url of urls) {
295
+ try {
296
+ const response = await defaultFuncs.get(url, ctx.jar);
297
+ const html = typeof response === "string" ? response : (response && (response.body || response.data)) || "";
298
+ const cover = coverFromHtml(html);
299
+ if (cover) return cover;
300
+ } catch (error) {
301
+ logger(`getUserInfoV2 cover page: ${error.message || error}`, "warn");
299
302
  }
300
303
  }
301
- return bestUser;
304
+ return null;
302
305
  }
303
306
 
304
307
  async function fetchLegacy(userIDs) {
@@ -323,7 +326,7 @@ module.exports = function (defaultFuncs, api, ctx) {
323
326
  lastName: nameParts.length > 1? nameParts.slice(1).join(" ") : null,
324
327
  vanity: profile.vanity || null,
325
328
  thumbSrc: null,
326
- coverPhoto: extractPhotoUrl(profile.cover_photo),
329
+ coverPhoto: extractPhotoUrl(profile.cover_photo || profile.coverPhoto || profile.cover || profile.profile_cover_photo),
327
330
  profileUrl: profile.uri || `https://www.facebook.com/profile.php?id=${id}`,
328
331
  gender: profile.gender === 1? "male" : profile.gender === 2? "female" : "no specific gender",
329
332
  type: profile.type || "User",
@@ -370,7 +373,11 @@ module.exports = function (defaultFuncs, api, ctx) {
370
373
  for (let i = 0; i < ids.length; i++) {
371
374
  const id = ids[i];
372
375
  if (results[i].status === "fulfilled" && results[i].value?.id) {
373
- retObj[id] = formatUser(results[i].value, id);
376
+ const user = results[i].value;
377
+ if (!user.coverPhoto) {
378
+ user.coverPhoto = await fetchCoverFromProfile(id);
379
+ }
380
+ retObj[id] = formatUser(user, id);
374
381
  } else {
375
382
  needFallback.push(id);
376
383
  }
@@ -408,13 +415,12 @@ module.exports = function (defaultFuncs, api, ctx) {
408
415
  return callback(null, retObj);
409
416
  }
410
417
  })();
411
- return returnPromise;
418
+ return returnPromise;
412
419
  };
413
420
  };
414
421
 
415
422
  module.exports._private = {
416
423
  extractPhotoUrl,
417
- extractCoverFromHTML,
418
424
  normalizeUser
419
425
  };
420
426
 
@@ -65,8 +65,8 @@ function createFallbackNamespaces(api) {
65
65
  setEmoji: bindOptionalMethod(api, "changeThreadEmoji"),
66
66
  setNickname: bindOptionalMethod(api, "changeNickname"),
67
67
  createPoll: bindOptionalMethod(api, "createPoll"),
68
- createThemeAI: bindLiveMethod(api, "createThemeAI"),
69
- getThemePictures: bindLiveMethod(api, "getThemePictures"),
68
+ createThemeAI: bindOptionalMethod(api, "createThemeAI"),
69
+ getThemePictures: bindOptionalMethod(api, "getThemePictures"),
70
70
  delete: bindOptionalMethod(api, "deleteThread"),
71
71
  colors: readOptionalMember(api, "threadColors"),
72
72
  handleMessageRequest: bindOptionalMethod(api, "handleMessageRequest"),
@@ -25,6 +25,7 @@ function sendReqMqtt(ctx, payload, options, callback) {
25
25
  let timer = null;
26
26
  let cleaned = false;
27
27
 
28
+ // Cleanup function to ensure listeners and timers are always removed
28
29
  const cleanup = () => {
29
30
  if (cleaned) return;
30
31
  cleaned = true;
@@ -37,7 +38,7 @@ function sendReqMqtt(ctx, payload, options, callback) {
37
38
  ctx.mqttClient.removeListener("message", handleRes);
38
39
  }
39
40
  } catch (err) {
40
-
41
+ // Ignore cleanup errors
41
42
  }
42
43
  };
43
44
 
@@ -1,5 +1,10 @@
1
1
  "use strict";
2
2
 
3
+ /**
4
+ * Shared helpers for database layer (userData, threadData).
5
+ * Keeps validation and payload normalization in one place.
6
+ */
7
+
3
8
  const DB_NOT_INIT = "Database not initialized";
4
9
 
5
10
  function validateId(value, fieldName = "id") {
@@ -18,11 +23,18 @@ function validateData(data) {
18
23
  }
19
24
  }
20
25
 
26
+ /**
27
+ * @param {string|string[]|null} keys - "userID" | ["userID","data"] | null
28
+ * @returns {string[]|undefined}
29
+ */
21
30
  function normalizeAttributes(keys) {
22
31
  if (keys == null) return undefined;
23
32
  return typeof keys === "string" ? [keys] : Array.isArray(keys) ? keys : undefined;
24
33
  }
25
34
 
35
+ /**
36
+ * Normalize payload: accept either { data } or raw object.
37
+ */
26
38
  function normalizePayload(data, key = "data") {
27
39
  return Object.prototype.hasOwnProperty.call(data, key) ? data : { [key]: data };
28
40
  }
@@ -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),