fca-nx 6.7.4 → 6.7.6

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.
@@ -1332,13 +1332,28 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1332
1332
  api.listen = api.listenMqtt;
1333
1333
  }
1334
1334
  if (api.refreshFb_dtsg) {
1335
+ // [Hardened] refresh fb_dtsg every 6h (was 24h) to prevent token-expiry logouts
1335
1336
  setInterval(function () {
1336
1337
  api.refreshFb_dtsg().then(function () {
1337
1338
  logger("Successfully refreshed fb_dtsg");
1338
- }).catch(function () {
1339
- logger("An error occurred while refreshing fb_dtsg", "error");
1339
+ }).catch(function (e) {
1340
+ logger("An error occurred while refreshing fb_dtsg: " + (e && e.message ? e.message : e), "error");
1340
1341
  });
1341
- }, 86400000);
1342
+ }, 6 * 60 * 60 * 1000);
1343
+ // [Hardened] light session keepalive every 20 min - hits facebook.com so cookies stay warm
1344
+ setInterval(function () {
1345
+ try {
1346
+ const { get } = require("../src/utils/request");
1347
+ const { saveCookies } = require("../src/utils/client");
1348
+ if (!ctxMain || !ctxMain.jar || ctxMain._ending) return;
1349
+ get("https://www.facebook.com/", ctxMain.jar, null, ctxMain.globalOptions, ctxMain)
1350
+ .then(saveCookies(ctxMain.jar))
1351
+ .then(function () { logger("session keepalive ok", "debug"); })
1352
+ .catch(function (e) {
1353
+ logger("session keepalive failed: " + (e && e.message ? e.message : e), "warn");
1354
+ });
1355
+ } catch (_) {}
1356
+ }, 20 * 60 * 1000);
1342
1357
  }
1343
1358
  // ✅ fca-nx core features register
1344
1359
  try {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.4",
4
- "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
3
+ "version": "6.7.6",
4
+ "description": "Facebook Messenger API for Node.js \u2014 anti-logout hardened (soft session recovery, keepalive, safe MQTT)",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "exports": {
@@ -14,7 +14,7 @@ const logger = require("../../../func/logger");
14
14
  module.exports = function (defaultFuncs, api, ctx) {
15
15
  return function enableAutoSaveAppState(options = {}) {
16
16
  const filePath = options.filePath || path.join(process.cwd(), "appstate.json");
17
- const interval = options.interval || 10 * 60 * 1000; // 10 minutes default
17
+ const interval = options.interval || 5 * 60 * 1000; // [Hardened] 5 minutes default - keep session cookies fresh on disk
18
18
  const saveOnLogin = options.saveOnLogin !== false; // default true
19
19
 
20
20
  // Save function
@@ -1,8 +1,35 @@
1
1
  "use strict";
2
2
 
3
3
  const { getFrom } = require("../../utils/constants");
4
- const { get } = require("../../utils/request")
4
+ const { get } = require("../../utils/request");
5
5
  const { getType } = require("../../utils/format");
6
+ const logger = require("../../../func/logger");
7
+
8
+ function extractTokens(html) {
9
+ if (!html || typeof html !== "string") return null;
10
+ const fb_dtsg =
11
+ getFrom(html, '["DTSGInitData",[],{"token":"', '","') ||
12
+ getFrom(html, '"DTSGInitialData",[],{"token":"', '"') ||
13
+ getFrom(html, 'name="fb_dtsg" value="', '"') ||
14
+ getFrom(html, '"fb_dtsg":{"token":"', '"') ||
15
+ getFrom(html, "fb_dtsg\":{\"token\":\"", "\"") ||
16
+ null;
17
+ const jazoest =
18
+ getFrom(html, "jazoest=", '",') ||
19
+ getFrom(html, 'name="jazoest" value="', '"') ||
20
+ getFrom(html, '"jazoest":"', '"') ||
21
+ null;
22
+ if (!fb_dtsg) return null;
23
+ return { fb_dtsg, jazoest: jazoest || (ctxJazoestFallback(fb_dtsg)) };
24
+ }
25
+
26
+ function ctxJazoestFallback(token) {
27
+ // Classic jazoest = 2 + sum of char codes of fb_dtsg
28
+ let sum = 0;
29
+ for (let i = 0; i < token.length; i++) sum += token.charCodeAt(i);
30
+ return "2" + sum;
31
+ }
32
+
6
33
  module.exports = function (defaultFuncs, api, ctx) {
7
34
  return function refreshFb_dtsg(obj, callback) {
8
35
  if (typeof obj === "function") {
@@ -19,29 +46,60 @@ module.exports = function (defaultFuncs, api, ctx) {
19
46
  rejectFunc = reject;
20
47
  });
21
48
  if (!callback) {
22
- callback = (err, data) => err ? rejectFunc(err) : resolveFunc(data);
49
+ callback = (err, data) => (err ? rejectFunc(err) : resolveFunc(data));
23
50
  }
24
- if (Object.keys(obj).length === 0) {
25
- get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, { noRef: true }).then(({ data }) => {
26
- const fb_dtsg = getFrom(data, '["DTSGInitData",[],{"token":"', '","');
27
- const jazoest = getFrom(data, "jazoest=", '",');
28
- if (!fb_dtsg) throw new Error("Could not find fb_dtsg in HTML after requesting Facebook.");
29
- Object.assign(ctx, { fb_dtsg, jazoest });
30
- callback(null, {
31
- data: { fb_dtsg, jazoest },
32
- message: "Refreshed fb_dtsg and jazoest",
33
- });
34
- }).catch(err => {
35
- console.error("refreshFb_dtsg", err);
36
- callback(err);
37
- });
38
- } else {
51
+
52
+ if (Object.keys(obj).length > 0) {
39
53
  Object.assign(ctx, obj);
40
54
  callback(null, {
41
55
  data: obj,
42
- message: `Refreshed ${Object.keys(obj).join(", ")}`,
56
+ message: `Refreshed ${Object.keys(obj).join(", ")}`
43
57
  });
58
+ return returnPromise;
44
59
  }
60
+
61
+ const urls = [
62
+ "https://www.facebook.com/",
63
+ "https://www.facebook.com/messages/",
64
+ "https://www.messenger.com/"
65
+ ];
66
+
67
+ (async () => {
68
+ let lastErr = null;
69
+ for (let attempt = 0; attempt < 3; attempt++) {
70
+ for (const url of urls) {
71
+ try {
72
+ const res = await get(url, ctx.jar, null, ctx.globalOptions, { noRef: true });
73
+ const html = typeof res === "string" ? res : res && res.data;
74
+ const tokens = extractTokens(html);
75
+ if (tokens && tokens.fb_dtsg) {
76
+ Object.assign(ctx, { fb_dtsg: tokens.fb_dtsg, jazoest: tokens.jazoest });
77
+ // Persist cookies from the HTML response if available
78
+ try {
79
+ const { saveCookies } = require("../../utils/client");
80
+ if (res && res.headers) saveCookies(ctx.jar)(res);
81
+ } catch (_) {}
82
+ callback(null, {
83
+ data: { fb_dtsg: tokens.fb_dtsg, jazoest: tokens.jazoest },
84
+ message: "Refreshed fb_dtsg and jazoest"
85
+ });
86
+ return;
87
+ }
88
+ } catch (e) {
89
+ lastErr = e;
90
+ logger(
91
+ `refreshFb_dtsg attempt ${attempt + 1} ${url}: ${e && e.message ? e.message : e}`,
92
+ "warn"
93
+ );
94
+ }
95
+ }
96
+ await new Promise((r) => setTimeout(r, 1000 * (attempt + 1)));
97
+ }
98
+ const err = lastErr || new Error("Could not find fb_dtsg in HTML after multiple attempts.");
99
+ logger(`refreshFb_dtsg failed: ${err.message || err}`, "error");
100
+ callback(err);
101
+ })();
102
+
45
103
  return returnPromise;
46
104
  };
47
105
  };
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+
3
+ // api.bump(threadID, options?, callback?)
4
+ // Bumps a thread by sending a short message (default "👆") then optionally unsending it.
5
+ //
6
+ // options:
7
+ // text: message to send (default "👆")
8
+ // unsend: unsend after sending (default true)
9
+ // delay: ms to wait before unsend (default 1500, clamped 500..10000)
10
+ //
11
+ // Returns: { threadID, messageID, unsent, unsendError? }
12
+ //
13
+ // Safety (hardened):
14
+ // - per-thread cooldown 45s
15
+ // - global cap 8 bumps / 60s
16
+ // - rejects invalid threadID early
17
+ // - never throws on unsend failure (message already bumped the thread)
18
+
19
+ const COOLDOWN_MS = 45 * 1000;
20
+ const WINDOW_MS = 60 * 1000;
21
+ const MAX_PER_WINDOW = 8;
22
+ const MIN_DELAY = 500;
23
+ const MAX_DELAY = 10000;
24
+
25
+ module.exports = function (defaultFuncs, api, ctx) {
26
+ const lastBump = new Map();
27
+ let recent = [];
28
+
29
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
30
+
31
+ const send = (body, threadID) =>
32
+ new Promise((resolve, reject) => {
33
+ if (typeof api.sendMessage !== "function") {
34
+ return reject(new Error("bump: api.sendMessage is not available"));
35
+ }
36
+ api.sendMessage({ body }, threadID, (err, info) => (err ? reject(err) : resolve(info)));
37
+ });
38
+
39
+ const unsend = (messageID, threadID) =>
40
+ new Promise((resolve, reject) => {
41
+ if (typeof api.unsendMessage !== "function") {
42
+ return reject(new Error("bump: api.unsendMessage is not available"));
43
+ }
44
+ // support both (messageID, callback) and (messageID, threadID, callback) styles
45
+ try {
46
+ const ret = api.unsendMessage(messageID, threadID, (err) => (err ? reject(err) : resolve()));
47
+ if (ret && typeof ret.then === "function") {
48
+ ret.then(resolve, reject);
49
+ }
50
+ } catch (e) {
51
+ // fallback single-arg form
52
+ try {
53
+ const ret2 = api.unsendMessage(messageID, (err) => (err ? reject(err) : resolve()));
54
+ if (ret2 && typeof ret2.then === "function") {
55
+ ret2.then(resolve, reject);
56
+ }
57
+ } catch (e2) {
58
+ reject(e2 || e);
59
+ }
60
+ }
61
+ });
62
+
63
+ return function bump(threadID, options, callback) {
64
+ if (typeof options === "function") {
65
+ callback = options;
66
+ options = {};
67
+ }
68
+ options = options || {};
69
+
70
+ const promise = (async () => {
71
+ if (threadID == null || threadID === "") {
72
+ throw new Error("bump: threadID is required");
73
+ }
74
+ const tid = String(threadID).trim();
75
+ if (!tid) throw new Error("bump: threadID is required");
76
+
77
+ const now = Date.now();
78
+
79
+ const last = lastBump.get(tid) || 0;
80
+ if (now - last < COOLDOWN_MS) {
81
+ throw new Error(
82
+ `bump: cooldown active for this thread, wait ${Math.ceil((COOLDOWN_MS - (now - last)) / 1000)}s`
83
+ );
84
+ }
85
+
86
+ recent = recent.filter((t) => now - t < WINDOW_MS);
87
+ if (recent.length >= MAX_PER_WINDOW) {
88
+ throw new Error("bump: global rate limit reached (max 8 / minute), try again shortly");
89
+ }
90
+
91
+ const text = options.text != null ? String(options.text) : "👆";
92
+ const doUnsend = options.unsend !== false;
93
+ let delay = Number.isFinite(options.delay) ? Number(options.delay) : 1500;
94
+ if (delay < MIN_DELAY) delay = MIN_DELAY;
95
+ if (delay > MAX_DELAY) delay = MAX_DELAY;
96
+
97
+ const info = await send(text, tid);
98
+ lastBump.set(tid, Date.now());
99
+ recent.push(Date.now());
100
+
101
+ // prune map if it grows too large (memory safety)
102
+ if (lastBump.size > 5000) {
103
+ const cutoff = Date.now() - COOLDOWN_MS * 2;
104
+ for (const [k, v] of lastBump) {
105
+ if (v < cutoff) lastBump.delete(k);
106
+ }
107
+ }
108
+
109
+ const result = {
110
+ threadID: tid,
111
+ messageID: info && info.messageID ? String(info.messageID) : null,
112
+ unsent: false
113
+ };
114
+
115
+ if (doUnsend && result.messageID) {
116
+ await sleep(delay);
117
+ try {
118
+ await unsend(result.messageID, tid);
119
+ result.unsent = true;
120
+ } catch (e) {
121
+ // Message was still sent (thread is bumped); unsend can fail e.g. in E2EE DMs.
122
+ result.unsendError = e && e.message ? e.message : String(e);
123
+ }
124
+ }
125
+
126
+ return result;
127
+ })();
128
+
129
+ if (typeof callback === "function") {
130
+ promise.then((r) => callback(null, r), (e) => callback(e));
131
+ }
132
+ return promise;
133
+ };
134
+ };
@@ -2,7 +2,10 @@
2
2
 
3
3
  const log = require("../../../func/logAdapter");
4
4
  const { parseAndCheckLogin } = require("../../utils/client");
5
- const { getType } = require("../../utils/format");
5
+
6
+ // api.getThemePictures(themeID, callback?)
7
+ // themeID = the theme_fbid (digits), e.g. from api.getThreadInfo(tid).threadTheme.id
8
+ // or from an api.createThemeAI() result.
6
9
  module.exports = function (defaultFuncs, api, ctx) {
7
10
  return function getThemePictures(id, callback) {
8
11
  let resolveFunc = function () { };
@@ -12,24 +15,24 @@ module.exports = function (defaultFuncs, api, ctx) {
12
15
  rejectFunc = reject;
13
16
  });
14
17
 
15
- if (!callback) {
16
- if (
17
- getType(callback) == "Function" ||
18
- getType(callback) == "AsyncFunction"
19
- ) {
20
- callback = callback;
21
- } else {
22
- callback = function (err, data) {
23
- if (err) {
24
- return rejectFunc(err);
25
- }
26
- resolveFunc(data);
27
- };
28
- }
18
+ if (typeof callback !== "function") {
19
+ callback = function (err, data) {
20
+ if (err) return rejectFunc(err);
21
+ resolveFunc(data);
22
+ };
29
23
  }
30
24
 
31
- if (getType(id) != "String") {
32
- id = "";
25
+ // [Hardened] Accept numbers/bigint too. Previously any non-string id was silently
26
+ // replaced with "" and Facebook answered messenger_thread_theme: null.
27
+ if (typeof id === "number" || typeof id === "bigint") id = String(id);
28
+ id = typeof id === "string" ? id.trim() : "";
29
+
30
+ if (!/^\d+$/.test(id)) {
31
+ const err = {
32
+ error: "getThemePictures: a numeric theme ID is required (theme_fbid), got: " + JSON.stringify(id)
33
+ };
34
+ callback(err);
35
+ return returnPromise;
33
36
  }
34
37
 
35
38
  const form = {
@@ -37,19 +40,30 @@ module.exports = function (defaultFuncs, api, ctx) {
37
40
  fb_api_req_friendly_name: "MWPThreadThemeProviderQuery",
38
41
  doc_id: "9734829906576883",
39
42
  server_timestamps: true,
40
- variables: JSON.stringify({
41
- id
42
- }),
43
+ variables: JSON.stringify({ id }),
43
44
  av: ctx.userID
44
45
  };
46
+
45
47
  defaultFuncs
46
48
  .post("https://www.facebook.com/api/graphql/", ctx.jar, form)
47
49
  .then(parseAndCheckLogin(ctx, defaultFuncs))
48
50
  .then(function (resData) {
49
- if (resData.errors) {
51
+ if (resData && resData.errors) {
50
52
  throw resData;
51
53
  }
52
54
 
55
+ // [Hardened] Request worked but Facebook has no theme with this ID for this account.
56
+ // Report as failure instead of a false "success" with null theme.
57
+ if (!resData || !resData.data || !resData.data.messenger_thread_theme) {
58
+ const notFound = {
59
+ error: "Theme not found: Facebook returned no theme for ID " + id + ". Check the ID (use the theme_fbid of a real theme).",
60
+ themeID: id,
61
+ raw: resData
62
+ };
63
+ log.error("getThemePictures", notFound.error);
64
+ return callback(notFound);
65
+ }
66
+
53
67
  return callback(null, resData);
54
68
  })
55
69
  .catch(function (err) {
@@ -20,12 +20,14 @@ const T_MS_WAIT_TIMEOUT_MS = 5000;
20
20
  // [Fixed by xalman] IMMEDIATE RECONNECT: the first reconnect after a disconnect now happens at
21
21
  // once (0ms) instead of waiting for a scheduled 4-6s delay. Only if that attempt also fails does
22
22
  // the backoff start (1s, 2s, 4s ... capped at 60s) so a real outage still can't hammer Facebook.
23
- // Set env FCA_NX_MQTT_IMMEDIATE_RECONNECT=0 (or mqtt option immediateReconnect:false) to get the
24
- // old scheduled behaviour back.
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
25
  function isImmediateReconnect(ctx) {
26
- if (process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "0") return false;
27
- if (ctx && ctx._mqttOpt && ctx._mqttOpt.immediateReconnect === false) return false;
28
- return true;
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
28
+ if (process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1") return true;
29
+ if (ctx && ctx._mqttOpt && ctx._mqttOpt.immediateReconnect === true) return true;
30
+ return false;
29
31
  }
30
32
 
31
33
  function computeBackoff(ctx, baseMs) {
@@ -188,19 +190,28 @@ module.exports = function createListenMqtt(deps) {
188
190
  mqttClient.end(true);
189
191
  }
190
192
  } catch (_) { }
191
- if (/blocked/i.test(msg)) {
193
+ // [Hardened] Only permanent-logout on explicit "blocked the login"
194
+ if (/blocked the login/i.test(msg)) {
192
195
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
193
196
  }
194
197
 
195
- // Auth responses can race with the shared cookie refresh triggered by
196
- // another request. Treat a plain 401/403/"Not logged in" MQTT error as
197
- // recoverable instead of emitting account_inactive and permanently
198
- // setting ctx._ending. The close handler/scheduler will establish a
199
- // fresh MQTT connection with the refreshed session.
200
- logger(`mqtt transient auth error; reconnecting without logging out: ${msg}`, "warn");
201
- if (!ctx._ending && ctx.globalOptions.autoReconnect) {
202
- scheduleReconnect();
203
- }
198
+ // Plain 401/403/"Not logged in" is often a cookie/token race — recover softly.
199
+ logger(`mqtt transient auth error; refreshing session then reconnecting (no logout): ${msg}`, "warn");
200
+ (async () => {
201
+ try {
202
+ if (api && typeof api.refreshFb_dtsg === "function") {
203
+ await api.refreshFb_dtsg();
204
+ }
205
+ } catch (_) {}
206
+ try {
207
+ const { get } = require("../../../utils/request");
208
+ const { saveCookies } = require("../../../utils/client");
209
+ await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
210
+ } catch (_) {}
211
+ if (!ctx._ending && ctx.globalOptions && ctx.globalOptions.autoReconnect !== false) {
212
+ scheduleReconnect();
213
+ }
214
+ })();
204
215
  return;
205
216
  }
206
217
  logger(`mqtt error: ${msg}`, "error");
@@ -211,7 +222,7 @@ module.exports = function createListenMqtt(deps) {
211
222
  } catch (_) { }
212
223
  if (ctx._ending || ctx._cycling) return;
213
224
 
214
- if (ctx.globalOptions.autoReconnect && !ctx._ending) {
225
+ if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
215
226
  // Let scheduleReconnect() compute the exponential-backoff delay
216
227
  // itself (instead of always passing the same fixed base delay),
217
228
  // so repeated network failures back off instead of retrying every
@@ -228,6 +239,8 @@ module.exports = function createListenMqtt(deps) {
228
239
  process.env.OnStatus = true;
229
240
  }
230
241
  ctx._cycling = false;
242
+ ctx.loggedIn = true;
243
+ ctx._sessionRecovering = false;
231
244
  // A successful connect means the session/identity/network are fine -
232
245
  // reset the backoff counter so a later transient failure starts a
233
246
  // fresh backoff sequence instead of inheriting a long delay from an
@@ -342,7 +355,7 @@ module.exports = function createListenMqtt(deps) {
342
355
  return;
343
356
  }
344
357
  logger("mqtt connection closed", "warn");
345
- if (ctx.globalOptions.autoReconnect && !ctx._ending) {
358
+ if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
346
359
  scheduleReconnect();
347
360
  }
348
361
  });
@@ -353,7 +366,7 @@ module.exports = function createListenMqtt(deps) {
353
366
  return;
354
367
  }
355
368
  logger("mqtt disconnected", "warn");
356
- if (ctx.globalOptions.autoReconnect && !ctx._ending) {
369
+ if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
357
370
  scheduleReconnect();
358
371
  }
359
372
  });
@@ -36,6 +36,9 @@ module.exports = function createEmitAuth({ logger }) {
36
36
 
37
37
  ctx.mqttClient = undefined;
38
38
  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.
39
42
 
40
43
  // Clean up timeout references
41
44
  try {
@@ -193,8 +193,8 @@ module.exports = function createGetSeqID(deps) {
193
193
  const { listenMqtt, logger, emitAuth } = deps;
194
194
 
195
195
  return function getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount = 0) {
196
- const MAX_RETRIES = 3;
197
- const RETRY_DELAY = 2000;
196
+ const MAX_RETRIES = 5;
197
+ const RETRY_DELAY = 3000; // [Hardened] slower + more attempts before any logout decision
198
198
  ctx.t_mqttCalled = false;
199
199
 
200
200
  // Ensure essential tokens are injected into GraphQL Batch Payload
@@ -298,18 +298,25 @@ module.exports = function createGetSeqID(deps) {
298
298
  const delay = RETRY_DELAY * (retryCount + 1);
299
299
  logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (error: ${msg})`, "warn");
300
300
  await new Promise(resolve => setTimeout(resolve, delay));
301
-
302
- if (retryCount === 0 && ctx.loggedIn) {
303
- try {
304
- logger("getSeqID: refreshing session before retry...", "info");
305
- const { get } = require("../../../utils/request");
306
- const { saveCookies } = require("../../../utils/client");
307
- await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
308
- } catch (refreshErr) {
309
- logger(`getSeqID: session refresh failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
301
+
302
+ // [Hardened] Always refresh cookies + fb_dtsg before each auth retry
303
+ try {
304
+ logger("getSeqID: refreshing session (cookies + fb_dtsg) before retry...", "info");
305
+ const { get } = require("../../../utils/request");
306
+ const { saveCookies } = require("../../../utils/client");
307
+ await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
308
+ if (api && typeof api.refreshFb_dtsg === "function") {
309
+ try { await api.refreshFb_dtsg(); } catch (_) {}
310
+ }
311
+ // Keep form tokens in sync with refreshed ctx
312
+ if (form) {
313
+ if (ctx.fb_dtsg) form.fb_dtsg = ctx.fb_dtsg;
314
+ if (ctx.jazoest) form.jazoest = ctx.jazoest;
310
315
  }
316
+ } catch (refreshErr) {
317
+ logger(`getSeqID: session refresh failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
311
318
  }
312
-
319
+
313
320
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
314
321
  }
315
322
 
@@ -323,16 +330,49 @@ module.exports = function createGetSeqID(deps) {
323
330
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, 0);
324
331
  }
325
332
 
326
- if (/blocked/i.test(msg)) {
333
+ // [Hardened] Only permanent-logout on CLEAR blocked signal.
334
+ // Plain "Not logged in" after retries is often a transient cookie race —
335
+ // schedule a long soft-reconnect instead of killing the session forever.
336
+ if (/blocked the login|login_blocked|checkpoint_282|checkpoint_956/i.test(msg)) {
327
337
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
328
338
  }
329
- if (/Not logged in/i.test(msg)) {
330
- return emitAuth(ctx, api, globalCallback, "not_logged_in", msg);
331
- }
339
+
340
+ logger(`getSeqID: auth still failing after retries/auto-login - soft recovery (no permanent logout): ${msg}`, "error");
341
+ // Soft recovery: do NOT set ctx._ending. Notify listener, then retry later.
342
+ try {
343
+ if (typeof globalCallback === "function") {
344
+ globalCallback({
345
+ type: "session_recovering",
346
+ error: msg,
347
+ timestamp: Date.now()
348
+ }, null);
349
+ }
350
+ } catch (_) {}
351
+ // Re-attempt getSeqID after long cooldown without marking account inactive
352
+ const softDelay = Math.min(5 * 60 * 1000, 60000 * (retryCount + 1));
353
+ setTimeout(() => {
354
+ if (ctx._ending) return;
355
+ logger("getSeqID: soft recovery timer fired - retrying getSeqID", "warn");
356
+ try {
357
+ getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0);
358
+ } catch (e) {
359
+ logger(`getSeqID soft recovery error: ${e && e.message ? e.message : e}`, "error");
360
+ }
361
+ }, softDelay);
362
+ return;
332
363
  }
333
364
 
334
- logger(`getSeqID error: ${msg}`, "error");
335
- return emitAuth(ctx, api, globalCallback, "auth_error", msg);
365
+ // Non-auth, non-network: still soft-recover instead of permanent logout
366
+ logger(`getSeqID error (soft recover, no logout): ${msg}`, "error");
367
+ try {
368
+ if (typeof globalCallback === "function") {
369
+ globalCallback({ type: "session_recovering", error: msg, timestamp: Date.now() }, null);
370
+ }
371
+ } catch (_) {}
372
+ setTimeout(() => {
373
+ if (ctx._ending) return;
374
+ try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
375
+ }, 60000);
336
376
  });
337
377
  };
338
378
  };
@@ -20,8 +20,8 @@ const getTaskResponseData = require("./core/getTaskResponseData");
20
20
  const createEmitAuth = require("./core/emitAuth");
21
21
  const createMiddlewareSystem = require("./middleware");
22
22
 
23
- const CYCLE_MS_DEFAULT = 60 * 60 * 1000;
24
- const RECONNECT_DELAY_MS_DEFAULT = 3000;
23
+ const CYCLE_MS_DEFAULT = 2 * 60 * 60 * 1000; // [Hardened] 2h cycle - less session churn / multi-login risk
24
+ const RECONNECT_DELAY_MS_DEFAULT = 5000;
25
25
  const UNSUB_ALL_TIMEOUT_MS = 5000;
26
26
  const MAX_MQTT_RECONNECT_DELAY_MS = 60000;
27
27
  const MAX_MQTT_RECONNECT_COOLDOWN_MS = 10 * 60 * 1000; // long cooldown after exhausting fast retries - never give up permanently
@@ -109,10 +109,10 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
109
109
  let isReconnecting = false;
110
110
 
111
111
  function getReconnectDelay() {
112
- // [Fixed by xalman] immediate first reconnect (see connectMqtt.js computeBackoff). Called with
113
- // reconnectAttempts === 0 for a fresh cycle/disconnect and === 1 for the first retry after a
114
- // failed getSeqID; both go out at once, later ones back off 1s, 2s, 4s ... up to 60s.
115
- const immediate = process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT !== "0" && conf.immediateReconnect !== false;
112
+ // [Hardened] Immediate reconnect is OPT-IN only (FCA_NX_MQTT_IMMEDIATE_RECONNECT=1).
113
+ // Default scheduled backoff avoids overlapping sessions that Facebook treats as multi-login.
114
+ // When enabled: attempts 0/1 fire at once, then 1s, 2s, 4s ... up to 60s.
115
+ const immediate = process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1";
116
116
  if (immediate) {
117
117
  if (reconnectAttempts <= 1) return 0;
118
118
  const fast = Math.min(1000 * Math.pow(2, reconnectAttempts - 2), MAX_MQTT_RECONNECT_DELAY_MS);
@@ -218,7 +218,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
218
218
  }
219
219
 
220
220
  const now = Date.now();
221
- if (now - lastPongTime > (conf.heartbeatTimeout || HEARTBEAT_TIMEOUT_MS) * 3) {
221
+ if (now - lastPongTime > (conf.heartbeatTimeout || HEARTBEAT_TIMEOUT_MS) * 5) { // [Hardened] more tolerant before force cycle
222
222
  logger("mqtt heartbeat: no response, forcing reconnect", "warn");
223
223
  forceCycle();
224
224
  return;
@@ -370,7 +370,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
370
370
  }, d);
371
371
  }
372
372
 
373
- function forceCycle() {
373
+ function forceCycle() /* hardened */ {
374
374
  if (ctx._cycling) {
375
375
  logger("mqtt force cycle already in progress", "warn");
376
376
  return;
@@ -300,6 +300,10 @@ module.exports = function (defaultFuncs, api, ctx) {
300
300
  // in inbox. (Group chats and normal MQTT DMs are unchanged.)
301
301
  if (isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
302
302
  api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected()) {
303
+ // [Hardened] Text effects unsupported on E2EE path — warn once then send plain text
304
+ if (typeof getTextEffectId === "function" && getTextEffectId(msg)) {
305
+ logger.warn("sendMessage", "Text effects are not supported in E2EE DMs - sending plain text. Use a group chat for effects.");
306
+ }
303
307
  try {
304
308
  var e2eeText = await api.e2ee.sendMessage(String(threadID), { body: msg.body != null ? String(msg.body) : "" }, replyToMessage || msg.replyToMessage);
305
309
  var e2eeWrapped = e2eeText && e2eeText.messageId
@@ -90,6 +90,32 @@ function extractPhotoUrl(photo, depth = 0) {
90
90
  return null;
91
91
  }
92
92
 
93
+
94
+ // [Hardened] Fallback: read the cover photo straight from the profile page HTML,
95
+ // used when none of the GraphQL doc_ids returned a cover (doc_ids rotate often).
96
+ function decodeJsonString(raw) {
97
+ try { return JSON.parse('"' + raw + '"'); } catch { return String(raw).replace(/\\\//g, "/"); }
98
+ }
99
+
100
+ function extractCoverFromHTML(html) {
101
+ if (!html || typeof html !== "string") return null;
102
+ const patterns = [
103
+ /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
104
+ /"profile_cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
105
+ /"coverPhoto"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
106
+ /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"url"\s*:\s*"([^"]+)"/,
107
+ /property="og:image"\s+content="(https:\/\/[^"]+fbcdn[^"]+)"/i,
108
+ /content="(https:\/\/[^"]+fbcdn[^"]+)"\s+property="og:image"/i
109
+ ];
110
+ for (const re of patterns) {
111
+ const m = html.match(re);
112
+ if (!m) continue;
113
+ const url = decodeJsonString(m[1]).replace(/&amp;/g, "&");
114
+ if (/^https?:\/\//i.test(url) && /(fbcdn|scontent)/i.test(url)) return url;
115
+ }
116
+ return null;
117
+ }
118
+
93
119
  function pickMeta(user) {
94
120
  let friendshipStatus = null;
95
121
  let gender = null;
@@ -249,6 +275,29 @@ module.exports = function (defaultFuncs, api, ctx) {
249
275
  logger(`getUserInfoV2 ${doc.id}: ${error.message || error}`, "warn");
250
276
  }
251
277
  }
278
+ // [Hardened] GraphQL often omits cover; scrape profile HTML as last resort
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");
299
+ }
300
+ }
252
301
  return bestUser;
253
302
  }
254
303
 
@@ -311,7 +360,7 @@ module.exports = function (defaultFuncs, api, ctx) {
311
360
  if (!ids.length) {
312
361
  const error = new Error("Invalid user ID(s)");
313
362
  callback(error);
314
- returnPromise;
363
+ return returnPromise;
315
364
  }
316
365
  (async () => {
317
366
  try {
@@ -359,12 +408,13 @@ module.exports = function (defaultFuncs, api, ctx) {
359
408
  return callback(null, retObj);
360
409
  }
361
410
  })();
362
- return returnPromise;
411
+ return returnPromise;
363
412
  };
364
413
  };
365
414
 
366
415
  module.exports._private = {
367
416
  extractPhotoUrl,
417
+ extractCoverFromHTML,
368
418
  normalizeUser
369
419
  };
370
420
 
@@ -48,7 +48,8 @@ function createFallbackNamespaces(api) {
48
48
  getEmojiUrl: bindOptionalMethod(api, "getEmojiUrl"),
49
49
  resolvePhotoUrl: bindOptionalMethod(api, "resolvePhotoUrl"),
50
50
  uploadAttachment: bindOptionalMethod(api, "uploadAttachment"),
51
- forwardAttachment: bindOptionalMethod(api, "forwardAttachment")
51
+ forwardAttachment: bindOptionalMethod(api, "forwardAttachment"),
52
+ bump: bindLiveMethod(api, "bump")
52
53
  }),
53
54
  threads: compactNamespace({
54
55
  createGroup: bindOptionalMethod(api, "createNewGroup"),
@@ -65,8 +66,8 @@ function createFallbackNamespaces(api) {
65
66
  setEmoji: bindOptionalMethod(api, "changeThreadEmoji"),
66
67
  setNickname: bindOptionalMethod(api, "changeNickname"),
67
68
  createPoll: bindOptionalMethod(api, "createPoll"),
68
- createThemeAI: bindOptionalMethod(api, "createThemeAI"),
69
- getThemePictures: bindOptionalMethod(api, "getThemePictures"),
69
+ createThemeAI: bindLiveMethod(api, "createThemeAI"),
70
+ getThemePictures: bindLiveMethod(api, "getThemePictures"),
70
71
  delete: bindOptionalMethod(api, "deleteThread"),
71
72
  colors: readOptionalMember(api, "threadColors"),
72
73
  handleMessageRequest: bindOptionalMethod(api, "handleMessageRequest"),