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
@@ -1,30 +1,14 @@
1
1
  "use strict";
2
2
 
3
- /**
4
- * SessionGuard — Protects the appstate (session) from corruption and silent logouts.
5
- *
6
- * Features:
7
- * • Auto-saves appstate to disk periodically (default every 5 min)
8
- * • Saves on every successful message send (debounced, 30s cooldown)
9
- * • Backs up the previous appstate before overwriting (.bak file)
10
- * • Detects logout/checkpoint events from listen stream and alerts
11
- * • Provides api.saveSession([path]) for manual save at any time
12
- * • Never overwrites with a shorter/smaller appstate (corruption guard)
13
- */
14
-
15
3
  var fs = require("fs");
16
4
  var path = require("path");
17
5
  var logger = require("../../utils/logger");
18
6
 
19
- var SAVE_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
20
- var DEBOUNCE_MS = 30 * 1000; // 30 seconds cooldown between auto-saves
21
- var MIN_COOKIES = 5; // minimum cookie count we consider "valid"
22
- var REQUIRED_COOKIE_KEYS = ["c_user", "xs"]; // a session isn't usable without these
7
+ var SAVE_INTERVAL_MS = 5 * 60 * 1000;
8
+ var DEBOUNCE_MS = 30 * 1000;
9
+ var MIN_COOKIES = 5;
10
+ var REQUIRED_COOKIE_KEYS = ["c_user", "xs"];
23
11
 
24
- // Validate that an appstate array actually looks like a usable, well-formed
25
- // Facebook session before it's allowed to overwrite anything on disk.
26
- // Guards against persisting a partial/corrupt state (e.g. captured mid-logout)
27
- // that would replace a good appstate with a broken one.
28
12
  function isValidAppState(state) {
29
13
  if (!state || !Array.isArray(state) || state.length < MIN_COOKIES) return false;
30
14
  var keys = {};
@@ -43,11 +27,6 @@ function isValidAppState(state) {
43
27
 
44
28
  module.exports = function (defaultFuncs, api, ctx) {
45
29
 
46
- // sessionGuard() attaches by monkey-patching api.sendMessage. If it's
47
- // invoked more than once for the same api instance (e.g. accidentally
48
- // called twice), that patch would stack, causing double-saves and,
49
- // eventually, wrapping api.sendMessage in itself repeatedly. Guard
50
- // against that here instead of relying on callers not to do it.
51
30
  if (ctx._sessionGuardAttached) {
52
31
  logger.warn("SessionGuard", "Already active for this session — ignoring duplicate init.");
53
32
  return function alreadyActive() {
@@ -64,10 +43,6 @@ module.exports = function (defaultFuncs, api, ctx) {
64
43
  try { return api.getAppState(); } catch (_) { return null; }
65
44
  }
66
45
 
67
- // Serializes all writes to a given path so a periodic save and a
68
- // debounced on-send save can never interleave their writes to the same
69
- // file (the previous version had no such lock, so two concurrent
70
- // fs.writeFileSync calls to the same path could race).
71
46
  var writeLocks = Object.create(null);
72
47
 
73
48
  function withWriteLock(filePath, fn) {
@@ -78,10 +53,7 @@ module.exports = function (defaultFuncs, api, ctx) {
78
53
  }
79
54
 
80
55
  function atomicWriteFileSync(filePath, data) {
81
- // Write to a temp file in the same directory, then rename. rename()
82
- // is atomic on the same filesystem, so a crash/kill mid-write can
83
- // never leave a partially-written, corrupt appstate.json behind -
84
- // readers either see the old complete file or the new complete file.
56
+
85
57
  var dir = path.dirname(filePath);
86
58
  var tmpPath = path.join(dir, "." + path.basename(filePath) + "." + process.pid + "." + Date.now() + ".tmp");
87
59
  fs.writeFileSync(tmpPath, data, "utf8");
@@ -95,7 +67,6 @@ module.exports = function (defaultFuncs, api, ctx) {
95
67
  return false;
96
68
  }
97
69
 
98
- // Corruption guard: never write a smaller appstate than what's already on disk
99
70
  if (fs.existsSync(filePath)) {
100
71
  try {
101
72
  var existing = JSON.parse(fs.readFileSync(filePath, "utf8"));
@@ -103,7 +74,7 @@ module.exports = function (defaultFuncs, api, ctx) {
103
74
  logger.warn("SessionGuard", "Skipped save — new state has " + state.length + " cookies vs " + existing.length + " on disk (possible truncation).");
104
75
  return false;
105
76
  }
106
- // Backup the current valid state before overwriting (also atomic).
77
+
107
78
  atomicWriteFileSync(filePath + ".bak", JSON.stringify(existing, null, 2));
108
79
  } catch (_) {}
109
80
  }
@@ -114,8 +85,7 @@ module.exports = function (defaultFuncs, api, ctx) {
114
85
  }
115
86
 
116
87
  function saveToDisk(filePath) {
117
- // Run the actual save inside the per-path lock so concurrent callers
118
- // (periodic timer vs. post-send debounce) are serialized.
88
+
119
89
  var result;
120
90
  return withWriteLock(filePath, function () {
121
91
  try {
@@ -138,22 +108,19 @@ module.exports = function (defaultFuncs, api, ctx) {
138
108
  var lastSave = 0;
139
109
  var intervalRef = null;
140
110
 
141
- // Periodic save
142
111
  if (interval > 0) {
143
112
  intervalRef = setInterval(function () {
144
113
  logger.info("SessionGuard", "Periodic save...");
145
114
  saveToDisk(appStatePath);
146
115
  lastSave = Date.now();
147
116
  }, interval);
148
- if (intervalRef.unref) intervalRef.unref(); // don't block process exit
117
+ if (intervalRef.unref) intervalRef.unref();
149
118
  }
150
119
 
151
- // Debounced on-send save
152
- // Patch sendMessage to auto-save appstate after a successful send
153
120
  var originalSendMessage = api.sendMessage;
154
121
  api.sendMessage = function () {
155
122
  var result = originalSendMessage.apply(this, arguments);
156
- // After send, debounce-save
123
+
157
124
  Promise.resolve(result).then(function () {
158
125
  if (Date.now() - lastSave > debounce) {
159
126
  saveToDisk(appStatePath);
@@ -163,12 +130,10 @@ module.exports = function (defaultFuncs, api, ctx) {
163
130
  return result;
164
131
  };
165
132
 
166
- // Expose manual save
167
133
  api.saveSession = function (customPath) {
168
134
  return saveToDisk(customPath || appStatePath);
169
135
  };
170
136
 
171
- // Expose restore from backup
172
137
  api.restoreSessionBackup = function (customPath) {
173
138
  var bakPath = (customPath || appStatePath) + ".bak";
174
139
  if (!fs.existsSync(bakPath)) {
@@ -186,7 +151,6 @@ module.exports = function (defaultFuncs, api, ctx) {
186
151
  }
187
152
  };
188
153
 
189
- // Expose stop
190
154
  api.stopSessionGuard = function () {
191
155
  if (intervalRef) clearInterval(intervalRef);
192
156
  api.sendMessage = originalSendMessage;
@@ -5,7 +5,7 @@ const { generateOfflineThreadingID, getCurrentTimestamp } = require("../../utils
5
5
 
6
6
  module.exports = function (defaultFuncs, api, ctx) {
7
7
  return function setMessageReaction(reaction, messageID, threadID, callback, forceCustomReaction) {
8
- // ✅ MueidMursalinRifat Fix: threadID is now optional (backward compatible)
8
+
9
9
  if (typeof threadID === "function") {
10
10
  forceCustomReaction = callback;
11
11
  callback = threadID;
@@ -20,7 +20,6 @@ module.exports = function (defaultFuncs, api, ctx) {
20
20
  }
21
21
  const cb = typeof callback === "function" ? callback : undefined;
22
22
 
23
- // threadID না থাকলে ctx থেকে নেওয়ার চেষ্টা
24
23
  const finalThreadID = threadID || ctx.lastThreadID || "0";
25
24
 
26
25
  return new Promise((resolve, reject) => {
@@ -1,38 +1,20 @@
1
1
  "use strict";
2
2
 
3
3
  module.exports = function(_defaultFuncs, _api, _ctx) {
4
- // Currently the only colors that can be passed to api.changeThreadColor(); may change if Facebook adds more
4
+
5
5
  return {
6
- //Old hex colors.
7
- ////MessengerBlue: null,
8
- ////Viking: "#44bec7",
9
- ////GoldenPoppy: "#ffc300",
10
- ////RadicalRed: "#fa3c4c",
11
- ////Shocking: "#d696bb",
12
- ////PictonBlue: "#6699cc",
13
- ////FreeSpeechGreen: "#13cf13",
14
- ////Pumpkin: "#ff7e29",
15
- ////LightCoral: "#e68585",
16
- ////MediumSlateBlue: "#7646ff",
17
- ////DeepSkyBlue: "#20cef5",
18
- ////Fern: "#67b868",
19
- ////Cameo: "#d4a88c",
20
- ////BrilliantRose: "#ff5ca1",
21
- ////BilobaFlower: "#a695c7"
22
6
 
23
- //#region This part is for backward compatibly
24
- //trying to match the color one-by-one. kill me plz
25
- MessengerBlue: "196241301102133", //DefaultBlue
26
- Viking: "1928399724138152", //TealBlue
27
- GoldenPoppy: "174636906462322", //Yellow
28
- RadicalRed: "2129984390566328", //Red
29
- Shocking: "2058653964378557", //LavenderPurple
30
- FreeSpeechGreen: "2136751179887052", //Green
31
- Pumpkin: "175615189761153", //Orange
32
- LightCoral: "980963458735625", //CoralPink
33
- MediumSlateBlue: "234137870477637", //BrightPurple
34
- DeepSkyBlue: "2442142322678320", //AquaBlue
35
- BrilliantRose: "169463077092846", //HotPink
7
+ MessengerBlue: "196241301102133",
8
+ Viking: "1928399724138152",
9
+ GoldenPoppy: "174636906462322",
10
+ RadicalRed: "2129984390566328",
11
+ Shocking: "2058653964378557",
12
+ FreeSpeechGreen: "2136751179887052",
13
+ Pumpkin: "175615189761153",
14
+ LightCoral: "980963458735625",
15
+ MediumSlateBlue: "234137870477637",
16
+ DeepSkyBlue: "2442142322678320",
17
+ BrilliantRose: "169463077092846",
36
18
  DefaultBlue: "196241301102133",
37
19
  HotPink: "169463077092846",
38
20
  AquaBlue: "2442142322678320",
@@ -50,10 +32,6 @@ module.exports = function(_defaultFuncs, _api, _ctx) {
50
32
  Citrus: "370940413392601",
51
33
  Candy: "205488546921017",
52
34
 
53
- /**
54
- * July 06, 2022
55
- * added by @NTKhang
56
- */
57
35
  Earth: "1833559466821043",
58
36
  Support: "365557122117011",
59
37
  Music: "339021464972092",
@@ -95,16 +73,8 @@ module.exports = function(_defaultFuncs, _api, _ctx) {
95
73
  Kiwi: "3151463484918004",
96
74
  Grape: "193497045377796",
97
75
 
98
- /**
99
- * July 15, 2022
100
- * added by @NTKhang
101
- */
102
76
  NonBinary: "737761000603635",
103
77
 
104
- /**
105
- * November 25, 2022
106
- * added by @NTKhang
107
- */
108
78
  ThankfulForFriends: "1318983195536293",
109
79
  Transgender: "504518465021637",
110
80
  TaylorSwift: "769129927636836",
@@ -112,9 +82,6 @@ module.exports = function(_defaultFuncs, _api, _ctx) {
112
82
  Autumn: "822549609168155",
113
83
  Cyberpunk2077: "780962576430091",
114
84
 
115
- /**
116
- * May 13, 2023
117
- */
118
85
  MothersDay: "1288506208402340",
119
86
  APAHM: "121771470870245",
120
87
  Parenthood: "810978360551741",
@@ -11,32 +11,11 @@ const { URL } = require("url");
11
11
  const log = require("../../../func/logAdapter");
12
12
  const { getIdentity } = require("../../utils/clientIdentity");
13
13
 
14
- // Resolved from the same centralized identity as every other subsystem
15
- // (HTTP requests, MQTT) so upload requests never claim a different Chrome
16
- // version/sec-ch-ua than the rest of the session. Do not hard-code a
17
- // separate browser version here. This part is stateless/pure, so it's safe
18
- // to keep at module scope - it's read-only and identical for every session
19
- // using the default identity.
20
14
  const DEFAULT_IDENTITY = getIdentity();
21
15
  const DEFAULT_UA = DEFAULT_IDENTITY.userAgent;
22
16
 
23
17
  const TOKEN_CACHE_TTL = 5 * 60 * 1000;
24
18
 
25
- // NOTE ON SESSION ISOLATION:
26
- // Previously `http` (the axios instance), `cookieJar`, and `tokenCache` were
27
- // module-level `let` variables. Since a Node `require()` cache is a
28
- // singleton, every account/session that called this module's exported
29
- // factory in the same process was silently sharing (and overwriting) the
30
- // SAME axios instance, cookie jar, and cached fb_dtsg/lsd tokens. Logging in
31
- // a second account would clobber the first account's cookie jar and token
32
- // cache mid-session - the same class of bug as the shared CookieJar issue
33
- // fixed in module/loginHelper.js, but specific to the upload path.
34
- //
35
- // Fix: every piece of session-scoped state now lives on a `sess` object
36
- // created fresh inside the exported factory (one per login()/session) and
37
- // is passed explicitly to the helper functions below instead of being read
38
- // from module scope.
39
-
40
19
  function cleanJSON(x) {
41
20
  if (typeof x !== "string") return x;
42
21
  const s = x.replace(/^for\s*\(;;\);\s*/i, "");
@@ -61,9 +40,7 @@ function respFinalUrl(res) {
61
40
  }
62
41
 
63
42
  function detectCheckpoint(res) {
64
- // [Fixed by xalman] res.body -> res.data (axios response shape), same
65
- // root cause as the parseAndCheckLogin fix in src/utils/utils.js - this
66
- // was silently always reading undefined and never detecting checkpoints.
43
+
67
44
  const url = String(respFinalUrl(res) || "");
68
45
  const body = typeof res?.data === "string" ? res.data : "";
69
46
  const hit =
@@ -137,7 +114,7 @@ async function getTokens(sess, ua, forceRefresh = false) {
137
114
  const rev = pick(/"__rev":(\d+)/, html) || "";
138
115
 
139
116
  if (!fb_dtsg || !lsd) {
140
- // Cố gắng fallback nếu regex fail, nhưng thường là do cookie die
117
+
141
118
  if (!cache.data) throw new Error("Failed to fetch fb_dtsg or LSD from Facebook");
142
119
  }
143
120
 
@@ -293,10 +270,9 @@ function pLimit(n) {
293
270
  });
294
271
  }
295
272
 
296
- // Hàm upload core xử lý request
297
273
  async function singleUpload(sess, urlBase, file, ua, tokens, retries = 2) {
298
274
  const form = new FormData();
299
- // QUAN TRỌNG: Chỉ append file, KHÔNG append fb_dtsg vào body nữa
275
+
300
276
  form.append("farr", file.stream, { filename: file.filename, contentType: file.contentType });
301
277
 
302
278
  const headers = {
@@ -330,7 +306,6 @@ async function singleUpload(sess, urlBase, file, ua, tokens, retries = 2) {
330
306
  Connection: "keep-alive"
331
307
  };
332
308
 
333
- // Build URL với query string tokens
334
309
  const finalUrl = new URL(urlBase);
335
310
  finalUrl.searchParams.set("fb_dtsg", tokens.fb_dtsg);
336
311
  finalUrl.searchParams.set("jazoest", tokens.jazoest);
@@ -361,19 +336,12 @@ async function singleUpload(sess, urlBase, file, ua, tokens, retries = 2) {
361
336
  module.exports = function (defaultFuncs, api, ctx) {
362
337
  const ua = ctx?.options?.userAgent || DEFAULT_UA;
363
338
 
364
- // One session object per factory call (i.e. per login()/account), instead
365
- // of the old module-level `http`/`cookieJar`/`tokenCache` singletons that
366
- // every session in the process used to share and clobber. `ctx.jar` is
367
- // itself already per-session (see module/loginHelper.js), so reusing it
368
- // here (instead of creating yet another jar) also keeps upload requests
369
- // and the rest of the session's HTTP traffic consistent with each other.
370
339
  const sessionJar = ctx.jar instanceof CookieJar ? ctx.jar : new CookieJar();
371
340
  const sess = {
372
341
  http: null,
373
342
  tokenCache: { data: null, time: 0 }
374
343
  };
375
344
 
376
- // Axios instance
377
345
  sess.http = wrapper(axios.create({
378
346
  timeout: 60000,
379
347
  headers: {
@@ -420,7 +388,6 @@ module.exports = function (defaultFuncs, api, ctx) {
420
388
  let tokens = await getTokens(sess, ua);
421
389
  const normAll = await Promise.all(inputsArr.map(x => normalizeOne(sess, x, ua)));
422
390
 
423
- // Base QS setup
424
391
  const qs = [];
425
392
  const userId = (ctx && (ctx.userID || ctx.userId)) ? String(ctx.userID || ctx.userId) : "";
426
393
  if (userId) qs.push(`__user=${encodeURIComponent(userId)}`);
@@ -458,7 +425,6 @@ module.exports = function (defaultFuncs, api, ctx) {
458
425
  return;
459
426
  }
460
427
 
461
- // Parallel mode
462
428
  const limit = pLimit(options.concurrency);
463
429
  const tasks = normAll.map(f => () => singleUpload(sess, baseUrl, f, ua, tokens));
464
430
  const results = await Promise.all(tasks.map(t => limit(t)));
@@ -1,8 +1,5 @@
1
1
  "use strict";
2
- /**
3
- * MQTT/WebSocket listener for Facebook Messenger real-time events.
4
- * Connects to edge-chat.facebook.com, subscribes to topics, parses deltas and typing/presence.
5
- */
2
+
6
3
  const { formatID } = require("../../../utils/format");
7
4
  const { getSessionIdentity } = require("../../../utils/clientIdentity");
8
5
 
@@ -12,19 +9,8 @@ const MAX_RECONNECT_ATTEMPTS = 6
12
9
  const MAX_RECONNECT_COOLDOWN_MS = 45 * 60 * 1000;
13
10
  const T_MS_WAIT_TIMEOUT_MS = 20000;
14
11
 
15
- // Exponential backoff with jitter, based on how many *consecutive* reconnect
16
- // attempts have happened for this session (reset to 0 on a successful
17
- // "connect" event). This replaces the old fixed 2s-every-time behavior,
18
- // which could hammer the endpoint in a tight loop during real outages.
19
- //
20
- // [Fixed by xalman] IMMEDIATE RECONNECT: the first reconnect after a disconnect now happens at
21
- // once (0ms) instead of waiting for a scheduled 4-6s delay. Only if that attempt also fails does
22
- // the backoff start (1s, 2s, 4s ... capped at 60s) so a real outage still can't hammer Facebook.
23
- // Default is scheduled reconnect (safer). Set FCA_NX_MQTT_IMMEDIATE_RECONNECT=1
24
- // (or mqtt option immediateReconnect:true) only if you need the old instant behaviour.
25
12
  function isImmediateReconnect(ctx) {
26
- // [Hardened] opt-in only: instant reconnects can create overlapping sessions / checkpoint risk
27
- // Enable with FCA_NX_MQTT_IMMEDIATE_RECONNECT=1 or mqtt option immediateReconnect:true
13
+
28
14
  if (process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1") return true;
29
15
  if (ctx && ctx._mqttOpt && ctx._mqttOpt.immediateReconnect === true) return true;
30
16
  return false;
@@ -33,13 +19,13 @@ function isImmediateReconnect(ctx) {
33
19
  function computeBackoff(ctx, baseMs) {
34
20
  const attempt = (ctx._reconnectAttempts || 0);
35
21
  if (isImmediateReconnect(ctx)) {
36
- if (attempt <= 1) return 0; // first reconnect: right now
22
+ if (attempt <= 1) return 0;
37
23
  const fast = Math.min(1000 * Math.pow(2, attempt - 2), MAX_RECONNECT_DELAY_MS);
38
24
  const j = Math.floor(Math.random() * Math.min(500, fast * 0.2));
39
25
  return Math.min(fast + j, MAX_RECONNECT_DELAY_MS);
40
26
  }
41
27
  const exp = Math.min(baseMs * Math.pow(2, attempt), MAX_RECONNECT_DELAY_MS);
42
- const jitter = Math.floor(Math.random() * Math.min(4000, exp * 0.4)); // [Hardened5]
28
+ const jitter = Math.floor(Math.random() * Math.min(4000, exp * 0.4));
43
29
  return Math.min(exp + jitter, MAX_RECONNECT_DELAY_MS);
44
30
  }
45
31
 
@@ -55,21 +41,16 @@ module.exports = function createListenMqtt(deps) {
55
41
  const base = (ctx._mqttOpt && ctx._mqttOpt.reconnectDelayMs) || DEFAULT_RECONNECT_DELAY_MS;
56
42
  if (ctx._reconnectTimer) {
57
43
  logger("mqtt reconnect already scheduled", "warn");
58
- return; // debounce
44
+ return;
59
45
  }
60
46
  if (ctx._ending) {
61
- // Covers confirmed logout/checkpoint/blocked-login/invalid-session:
62
- // emitAuth() sets ctx._ending = true before this is ever reached for
63
- // those cases, so we never auto-reconnect after a confirmed auth failure.
47
+
64
48
  logger("mqtt reconnect skipped - ending", "warn");
65
49
  return;
66
50
  }
67
51
  ctx._reconnectAttempts = (ctx._reconnectAttempts || 0) + 1;
68
52
  if (ctx._reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
69
- // [Fixed by xalman] Don't give up forever - a run of consecutive failures is usually a
70
- // temporary outage (hosting network blip, FB-side hiccup), not a
71
- // dead account. Back off to a long, FB-friendly cooldown and reset
72
- // the counter so normal exponential backoff resumes after that.
53
+
73
54
  const cooldownMs = MAX_RECONNECT_COOLDOWN_MS;
74
55
  logger(`mqtt reconnect attempts exceeded (${MAX_RECONNECT_ATTEMPTS}); backing off ${Math.round(cooldownMs / 60000)}min before trying again (not giving up)`, "error");
75
56
  globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded - will retry after cooldown" }, null);
@@ -105,12 +86,6 @@ module.exports = function createListenMqtt(deps) {
105
86
  }
106
87
  ctx._mqttConnecting = true;
107
88
 
108
- // Ensure only one MQTT connection exists for this session, and that any
109
- // previous connection is fully closed (listeners removed, socket ended)
110
- // before a new one is opened. Without this, a reconnect racing with a
111
- // still-live prior connection could leave two live sockets publishing/
112
- // subscribing under the same session, which looks like an invalid/
113
- // duplicate session to the server.
114
89
  if (ctx.mqttClient) {
115
90
  try {
116
91
  ctx.mqttClient.removeAllListeners();
@@ -119,19 +94,14 @@ module.exports = function createListenMqtt(deps) {
119
94
  ctx.mqttClient = undefined;
120
95
  }
121
96
 
122
- // Resolve the identity ONCE per session (cached on ctx) so MQTT and HTTP
123
- // never disagree about User-Agent / Accept-Language mid-session.
124
97
  const identity = getSessionIdentity(ctx);
125
98
 
126
- // [Hardened5] stable device id for the whole process lifetime
127
99
  if (!ctx.clientId || ctx.clientId === "") {
128
100
  ctx.clientId = ctx.clientID || ((""+Math.random()).slice(2) + Date.now()).slice(0, 16);
129
101
  }
130
- // Online while this session is actually connected. Offline only if the
131
- // caller set online:false. A running Messenger tab is online.
102
+
132
103
  const chatOn = ctx.globalOptions.online !== false;
133
- // Same browser tab for the life of the process. A new sid on every
134
- // reconnect looks like a new login and is a common suspend trigger.
104
+
135
105
  if (!ctx._edgeSid) {
136
106
  ctx._edgeSid = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
137
107
  }
@@ -167,10 +137,7 @@ module.exports = function createListenMqtt(deps) {
167
137
  Upgrade: "websocket",
168
138
  "Sec-WebSocket-Version": "13",
169
139
  "Accept-Encoding": "gzip, deflate, br",
170
- // Must match the Accept-Language used for HTTP requests in this same
171
- // session (src/utils/headers.js) - it previously hard-coded "vi,en;q=0.9"
172
- // here while HTTP requests defaulted to "en-US,en;q=0.9,vi;q=0.8",
173
- // which is a contradictory-client signal between the two channels.
140
+
174
141
  "Accept-Language": identity.acceptLanguage,
175
142
  "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits"
176
143
  },
@@ -207,19 +174,17 @@ module.exports = function createListenMqtt(deps) {
207
174
  return;
208
175
  }
209
176
 
210
- if (/Not logged in|Not logged in.|blocked the login|401|403/i.test(msg)) {
177
+ if (/Not logged in|blocked the login|checkpoint|\b(?:401|403)\b/i.test(msg)) {
211
178
  try {
212
179
  if (mqttClient && mqttClient.connected) {
213
180
  mqttClient.end(true);
214
181
  }
215
182
  } catch (_) { }
216
- // [Hardened] Only permanent-logout on explicit "blocked the login"
183
+
217
184
  if (/blocked the login/i.test(msg)) {
218
185
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
219
186
  }
220
187
 
221
- // Plain 401/403/"Not logged in" is often a cookie race. Do not hit
222
- // facebook.com (that is a fresh login). Wait, then open one socket.
223
188
  logger(`mqtt transient auth error; one delayed reconnect (no homepage login): ${msg}`, "warn");
224
189
  if (!ctx._ending && ctx.globalOptions && ctx.globalOptions.autoReconnect !== false) {
225
190
  scheduleReconnect(30000);
@@ -235,10 +200,7 @@ module.exports = function createListenMqtt(deps) {
235
200
  if (ctx._ending || ctx._cycling) return;
236
201
 
237
202
  if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
238
- // Let scheduleReconnect() compute the exponential-backoff delay
239
- // itself (instead of always passing the same fixed base delay),
240
- // so repeated network failures back off instead of retrying every
241
- // ~2s indefinitely.
203
+
242
204
  scheduleReconnect();
243
205
  } else {
244
206
  globalCallback({ type: "stop_listen", error: msg || "Connection refused" }, null);
@@ -255,15 +217,11 @@ module.exports = function createListenMqtt(deps) {
255
217
  ctx._sessionRecovering = false;
256
218
  ctx._mqttConnecting = false;
257
219
  ctx._tmsMisses = 0;
258
- // A successful connect means the session/identity/network are fine -
259
- // reset the backoff counter so a later transient failure starts a
260
- // fresh backoff sequence instead of inheriting a long delay from an
261
- // unrelated earlier outage.
220
+
262
221
  ctx._reconnectAttempts = 0;
263
222
 
264
223
  topics.forEach(t => mqttClient.subscribe(t));
265
224
 
266
-
267
225
  const queue = {
268
226
  sync_api_version: 11, max_deltas_able_to_process: 100, delta_batch_size: 500,
269
227
  encoding: "JSON", entity_fbid: ctx.userID, initial_titan_sequence_id: ctx.lastSeqId, device_params: null
@@ -271,7 +229,7 @@ module.exports = function createListenMqtt(deps) {
271
229
  const topic = ctx.syncToken ? "/messenger_sync_get_diffs" : "/messenger_sync_create_queue";
272
230
  if (ctx.syncToken) { queue.last_seq_id = ctx.lastSeqId; queue.sync_token = ctx.syncToken; }
273
231
  mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
274
- // [Hardened5] only claim foreground/available when online:true
232
+
275
233
  mqttClient.publish("/foreground_state", JSON.stringify({ foreground: !!chatOn }), { qos: 1 });
276
234
  if (chatOn) {
277
235
  mqttClient.publish("/set_client_settings", JSON.stringify({ make_user_available_when_in_foreground: true }), { qos: 1 });
@@ -298,7 +256,6 @@ module.exports = function createListenMqtt(deps) {
298
256
  scheduleReconnect();
299
257
  }, T_MS_WAIT_TIMEOUT_MS);
300
258
 
301
- // Store timeout reference for cleanup
302
259
  ctx._rTimeout = rTimeout;
303
260
 
304
261
  ctx.tmsWait = function () {
@@ -315,7 +272,7 @@ module.exports = function createListenMqtt(deps) {
315
272
  });
316
273
 
317
274
  mqttClient.on("message", function (topic, message) {
318
- if (ctx._ending) return; // Ignore messages if ending
275
+ if (ctx._ending) return;
319
276
  try {
320
277
  let jsonMessage = Buffer.isBuffer(message) ? Buffer.from(message).toString() : message;
321
278
  try {
@@ -369,7 +326,7 @@ module.exports = function createListenMqtt(deps) {
369
326
  } catch (ex) {
370
327
  const errMsg = ex && ex.message ? ex.message : String(ex || "Unknown error");
371
328
  logger(`mqtt message handler error: ${errMsg}`, "error");
372
- // Don't crash on message parsing errors, just log and continue
329
+
373
330
  }
374
331
  });
375
332
 
@@ -1,11 +1,8 @@
1
1
  "use strict";
2
- /**
3
- * Emits account_inactive to the global callback and cleans up MQTT/timers/scheduler.
4
- * Used when login is invalid, blocked, or session is lost.
5
- */
2
+
6
3
  module.exports = function createEmitAuth({ logger }) {
7
4
  return function emitAuth(ctx, api, globalCallback, reason, detail) {
8
- // Clean up all timers
5
+
9
6
  try {
10
7
  if (ctx._autoCycleTimer) {
11
8
  clearInterval(ctx._autoCycleTimer);
@@ -24,7 +21,6 @@ module.exports = function createEmitAuth({ logger }) {
24
21
  ctx._cycling = false;
25
22
  } catch (_) { }
26
23
 
27
- // Clean up MQTT client
28
24
  try {
29
25
  if (ctx.mqttClient) {
30
26
  ctx.mqttClient.removeAllListeners();
@@ -36,11 +32,7 @@ module.exports = function createEmitAuth({ logger }) {
36
32
 
37
33
  ctx.mqttClient = undefined;
38
34
  ctx.loggedIn = false;
39
- // [Hardened] cookies / jar intentionally preserved so auto-relogin or
40
- // soft recovery can reuse the session without full credential login.
41
- // Only MQTT + timers are torn down.
42
35
 
43
- // Clean up timeout references
44
36
  try {
45
37
  if (ctx._rTimeout) {
46
38
  clearTimeout(ctx._rTimeout);
@@ -48,14 +40,12 @@ module.exports = function createEmitAuth({ logger }) {
48
40
  }
49
41
  } catch (_) { }
50
42
 
51
- // Clean up tasks Map to prevent memory leak
52
43
  try {
53
44
  if (ctx.tasks && ctx.tasks instanceof Map) {
54
45
  ctx.tasks.clear();
55
46
  }
56
47
  } catch (_) { }
57
48
 
58
- // Clean up userInfo intervals
59
49
  try {
60
50
  if (ctx._userInfoIntervals && Array.isArray(ctx._userInfoIntervals)) {
61
51
  ctx._userInfoIntervals.forEach(interval => {
@@ -67,7 +57,6 @@ module.exports = function createEmitAuth({ logger }) {
67
57
  }
68
58
  } catch (_) { }
69
59
 
70
- // Clean up autoSave intervals
71
60
  try {
72
61
  if (ctx._autoSaveInterval && Array.isArray(ctx._autoSaveInterval)) {
73
62
  ctx._autoSaveInterval.forEach(interval => {
@@ -79,7 +68,6 @@ module.exports = function createEmitAuth({ logger }) {
79
68
  }
80
69
  } catch (_) { }
81
70
 
82
- // Clean up scheduler
83
71
  try {
84
72
  if (ctx._scheduler && typeof ctx._scheduler.destroy === "function") {
85
73
  ctx._scheduler.destroy();