fca-nx 6.7.5 → 6.7.7

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.
package/README.md CHANGED
@@ -380,6 +380,12 @@ login(
380
380
 
381
381
  ```
382
382
  > Email/password authentication may require additional verification.
383
+
384
+ If Facebook returns a checkpoint, security challenge, robot verification, or
385
+ suspension notice, FCA-NX stops automatic login and reconnect attempts and
386
+ returns a `SESSION_VERIFICATION_REQUIRED` error. Complete any account review
387
+ through Facebook directly before starting a new session. This safe-stop behavior
388
+ does not guarantee that an account will avoid restrictions.
383
389
  >
384
390
  # 🧩 API Architecture
385
391
  ```text
@@ -5,11 +5,16 @@ const chalk = require("chalk");
5
5
  const EventEmitter = require("events");
6
6
  const models = require("../src/database/models");
7
7
  const logger = require("../func/logger");
8
- const { get, post, makeDefaults } = require("../src/utils/request");
8
+ const { get, makeDefaults } = require("../src/utils/request");
9
9
  const { CookieJar } = require("tough-cookie");
10
10
  const { saveCookies, getAppState } = require("../src/utils/client");
11
11
  const { getFrom } = require("../src/utils/constants");
12
12
  const { loadConfig } = require("./config");
13
+ const {
14
+ isSessionEnforcement,
15
+ createSessionEnforcementError,
16
+ isSessionEnforcementError
17
+ } = require("../src/utils/sessionStatus");
13
18
  const { createRemoteClient } = require("../src/remote/remoteClient");
14
19
  const { config } = loadConfig();
15
20
  const axiosBase = require("axios");
@@ -44,6 +49,17 @@ function parseRegion(html) {
44
49
  }
45
50
  }
46
51
 
52
+ function guardSessionResponse(response) {
53
+ if (isSessionEnforcement(response)) {
54
+ logger(
55
+ chalk.italic("Facebook requires manual verification; automatic login and recovery stopped."),
56
+ "error"
57
+ );
58
+ throw createSessionEnforcementError();
59
+ }
60
+ return response;
61
+ }
62
+
47
63
  function mask(s, keep = 3) {
48
64
  if (!s) return "";
49
65
  const n = s.length;
@@ -520,6 +536,8 @@ async function hydrateJarFromDB(userID, jar) {
520
536
  }
521
537
 
522
538
  async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions, ctxRef, hadAppStateInput = false, jar) {
539
+ guardSessionResponse(currentHtml);
540
+
523
541
  // Helper to validate UID - must be a non-zero positive number string
524
542
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
525
543
 
@@ -566,19 +584,18 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
566
584
  logger("tryAutoLoginIfNeeded: Trying backup from DB...", "info");
567
585
  try {
568
586
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
569
- const resB = (await ctxRef.bypassAutomation(initial, jar)) || initial;
587
+ const resB = (await ctxRef.guardSessionResponse(initial)) || initial;
570
588
  const htmlB = resB && resB.data ? resB.data : "";
571
- if (!htmlB.includes("/checkpoint/block/?next")) {
572
- const htmlUserID = htmlUID(htmlB);
573
- if (isValidUID(htmlUserID)) {
574
- const cookiesB = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
575
- logger(`tryAutoLoginIfNeeded: DB backup session valid, USER_ID=${htmlUserID}`, "info");
576
- return { html: htmlB, cookies: cookiesB, userID: htmlUserID };
577
- } else {
578
- logger(`tryAutoLoginIfNeeded: DB backup session dead (HTML USER_ID=${htmlUserID || "empty"}), will try API login...`, "warn");
579
- }
589
+ const htmlUserID = htmlUID(htmlB);
590
+ if (isValidUID(htmlUserID)) {
591
+ const cookiesB = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
592
+ logger(`tryAutoLoginIfNeeded: DB backup session valid, USER_ID=${htmlUserID}`, "info");
593
+ return { html: htmlB, cookies: cookiesB, userID: htmlUserID };
594
+ } else {
595
+ logger(`tryAutoLoginIfNeeded: DB backup session dead (HTML USER_ID=${htmlUserID || "empty"}), will try API login...`, "warn");
580
596
  }
581
597
  } catch (dbErr) {
598
+ if (isSessionEnforcementError(dbErr)) throw dbErr;
582
599
  logger(`tryAutoLoginIfNeeded: DB backup failed - ${dbErr && dbErr.message ? dbErr.message : String(dbErr)}`, "warn");
583
600
  }
584
601
  }
@@ -601,6 +618,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
601
618
  logger(`tryAutoLoginIfNeeded: Attempting API login for ${u.slice(0, 3)}***...`, "info");
602
619
 
603
620
  const r = await tokens(u, p, tf);
621
+ guardSessionResponse(r);
604
622
  if (!r || !r.status) {
605
623
  throw new Error(r && r.message ? r.message : "API Login failed");
606
624
  }
@@ -667,7 +685,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
667
685
  logger(`tryAutoLoginIfNeeded: Refreshing ${urlToUse} (attempt ${retryCount + 1}/${maxRetries})...`, "info");
668
686
 
669
687
  const initial2 = await get(urlToUse, jar, null, globalOptions).then(saveCookies(jar));
670
- res2 = (await ctxRef.bypassAutomation(initial2, jar)) || initial2;
688
+ res2 = (await ctxRef.guardSessionResponse(initial2)) || initial2;
671
689
  html2 = res2 && res2.data ? res2.data : "";
672
690
 
673
691
  if (html2.includes("/checkpoint/block/?next")) {
@@ -691,7 +709,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
691
709
  break;
692
710
  }
693
711
  } catch (err) {
694
- if (err.message && err.message.includes("Checkpoint")) {
712
+ if (isSessionEnforcementError(err) || (err.message && err.message.includes("Checkpoint"))) {
695
713
  throw err;
696
714
  }
697
715
  if (retryCount < maxRetries - 1) {
@@ -741,10 +759,12 @@ function makeLogin(j, email, password, globalOptions) {
741
759
  const tf = config.credentials?.twofactor || null;
742
760
  if (!u || !p) return;
743
761
  const r = await tokens(u, p, tf);
762
+ guardSessionResponse(r);
744
763
  if (r && r.status && Array.isArray(r.cookies)) {
745
764
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
746
765
  setJarFromPairs(j, pairs, ".facebook.com");
747
- await get("https://www.facebook.com/", j, null, globalOptions).then(saveCookies(j));
766
+ const response = await get("https://www.facebook.com/", j, null, globalOptions).then(saveCookies(j));
767
+ guardSessionResponse(response);
748
768
  } else {
749
769
  throw new Error(r && r.message ? r.message : "Login failed");
750
770
  }
@@ -843,66 +863,18 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
843
863
  return callback(e);
844
864
  }
845
865
  const ctx = { globalOptions, options: globalOptions, reconnectAttempts: 0 };
846
- ctx.bypassAutomation = async function (resp, j) {
847
- global.fca = global.fca || {};
848
- global.fca.BypassAutomationNotification = this.bypassAutomation.bind(this);
849
- const s = x => (typeof x === "string" ? x : String(x ?? ""));
850
- const u = r => r?.request?.res?.responseUrl || (r?.config?.baseURL ? new URL(r.config.url || "/", r.config.baseURL).toString() : r?.config?.url || "");
851
- const isCp = r => typeof u(r) === "string" && u(r).includes("checkpoint/601051028565049");
852
- const cookieUID = async () => {
853
- try {
854
- const cookies = typeof j?.getCookies === "function" ? await j.getCookies("https://www.facebook.com") : [];
855
- return cookies.find(c => c.key === "i_user")?.value || cookies.find(c => c.key === "c_user")?.value;
856
- } catch { return undefined; }
857
- };
858
- const htmlUID = body => s(body).match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s(body).match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
859
- const getUID = async body => (await cookieUID()) || htmlUID(body);
860
- const refreshJar = async () => get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
861
- const bypass = async body => {
862
- const b = s(body);
863
- const UID = await getUID(b);
864
- const fb_dtsg = getFrom(b, '"DTSGInitData",[],{"token":"', '",') || b.match(/name="fb_dtsg"\s+value="([^"]+)"/)?.[1];
865
- const jazoest = getFrom(b, 'name="jazoest" value="', '"') || getFrom(b, "jazoest=", '",') || b.match(/name="jazoest"\s+value="([^"]+)"/)?.[1];
866
- const lsd = getFrom(b, '["LSD",[],{"token":"', '"}') || b.match(/name="lsd"\s+value="([^"]+)"/)?.[1];
867
- const form = { av: UID, fb_dtsg, jazoest, lsd, fb_api_caller_class: "RelayModern", fb_api_req_friendly_name: "FBScrapingWarningMutation", variables: "{}", server_timestamps: true, doc_id: 6339492849481770 };
868
- await post("https://www.facebook.com/api/graphql/", j, form, null, this.options).then(saveCookies(j));
869
- logger("⚠️ Facebook automation detected — bypassing...", "warn");
870
- this.reconnectAttempts = 0;
871
- };
872
- try {
873
- if (resp) {
874
- if (isCp(resp)) {
875
- await bypass(s(resp.data));
876
- const refreshed = await refreshJar();
877
- if (isCp(refreshed)) logger("Checkpoint still present after refresh", "warn");
878
- else logger("✅ Bypass complete — session restored.", "info");
879
- return refreshed;
880
- }
881
- return resp;
882
- }
883
- const first = await get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
884
- if (isCp(first)) {
885
- await bypass(s(first.data));
886
- const refreshed = await refreshJar();
887
- if (!isCp(refreshed)) logger("✅ Bypass complete — session restored.", "info");
888
- else logger("Checkpoint still present after refresh", "warn");
889
- return refreshed;
890
- }
891
- return first;
892
- } catch (e) {
893
- logger(`Bypass automation error: ${e && e.message ? e.message : String(e)}`, "error");
894
- return resp;
895
- }
866
+ ctx.guardSessionResponse = async function (response) {
867
+ return guardSessionResponse(response);
896
868
  };
897
869
  if (appState || Cookie) {
898
870
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
899
- return (await ctx.bypassAutomation(initial, jar)) || initial;
871
+ return (await ctx.guardSessionResponse(initial, jar)) || initial;
900
872
  }
901
873
  const hydrated = await hydrateJarFromDB(null, jar);
902
874
  if (hydrated) {
903
875
  logger(chalk.italic("🔄 AppState backup found — restoring session..."), "info");
904
876
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
905
- return (await ctx.bypassAutomation(initial, jar)) || initial;
877
+ return (await ctx.guardSessionResponse(initial, jar)) || initial;
906
878
  }
907
879
  logger(chalk.italic("😐 AppState expired — logging in with credentials..."), "warn");
908
880
  return get("https://www.facebook.com/", null, null, globalOptions)
@@ -915,45 +887,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
915
887
  .then(async function (res) {
916
888
  const ctx = {};
917
889
  ctx.options = globalOptions;
918
- ctx.bypassAutomation = async function (resp, j) {
919
- global.fca = global.fca || {};
920
- global.fca.BypassAutomationNotification = this.bypassAutomation.bind(this);
921
- const s = x => (typeof x === "string" ? x : String(x ?? ""));
922
- const u = r => r?.request?.res?.responseUrl || (r?.config?.baseURL ? new URL(r.config.url || "/", r.config.baseURL).toString() : r?.config?.url || "");
923
- const isCp = r => typeof u(r) === "string" && u(r).includes("checkpoint/601051028565049");
924
- const cookieUID = async () => {
925
- try {
926
- const cookies = typeof j?.getCookies === "function" ? await j.getCookies("https://www.facebook.com") : [];
927
- return cookies.find(c => c.key === "i_user")?.value || cookies.find(c => c.key === "c_user")?.value;
928
- } catch { return undefined; }
929
- };
930
- const htmlUID = body => s(body).match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s(body).match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
931
- const getUID = async body => (await cookieUID()) || htmlUID(body);
932
- const refreshJar = async () => get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
933
- const bypass = async body => {
934
- const b = s(body);
935
- const UID = await getUID(b);
936
- const fb_dtsg = getFrom(b, '"DTSGInitData",[],{"token":"', '",') || b.match(/name="fb_dtsg"\s+value="([^"]+)"/)?.[1];
937
- const jazoest = getFrom(b, 'name="jazoest" value="', '"') || getFrom(b, "jazoest=", '",') || b.match(/name="jazoest"\s+value="([^"]+)"/)?.[1];
938
- const lsd = getFrom(b, '["LSD",[],{"token":"', '"}') || b.match(/name="lsd"\s+value="([^"]+)"/)?.[1];
939
- const form = { av: UID, fb_dtsg, jazoest, lsd, fb_api_caller_class: "RelayModern", fb_api_req_friendly_name: "FBScrapingWarningMutation", variables: "{}", server_timestamps: true, doc_id: 6339492849481770 };
940
- await post("https://www.facebook.com/api/graphql/", j, form, null, this.options).then(saveCookies(j));
941
- logger("⚠️ Facebook automation detected — bypassing...", "warn");
942
- };
943
- try {
944
- if (res && isCp(res)) {
945
- await bypass(s(res.data));
946
- const refreshed = await refreshJar();
947
- if (!isCp(refreshed)) logger("✅ Bypass complete — session restored.", "info");
948
- return refreshed;
949
- }
950
- logger("✅ No checkpoint detected — session is clean.", "info");
951
- return res;
952
- } catch {
953
- return res;
954
- }
890
+ ctx.guardSessionResponse = async function (response) {
891
+ return guardSessionResponse(response);
955
892
  };
956
- const processed = (await ctx.bypassAutomation(res, jar)) || res;
893
+ const processed = (await ctx.guardSessionResponse(res)) || res;
957
894
  let html = processed && processed.data ? processed.data : "";
958
895
  let cookies = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
959
896
  const getUIDFromCookies = cs =>
@@ -1167,7 +1104,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1167
1104
  _emitter: emitter
1168
1105
  };
1169
1106
  ctxMain.options = globalOptions;
1170
- ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1107
+ ctxMain.guardSessionResponse = ctx.guardSessionResponse;
1171
1108
  ctxMain.performAutoLogin = async () => {
1172
1109
  try {
1173
1110
  // [Fixed by xalman] First check whether the existing cookie session is actually
@@ -1187,6 +1124,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1187
1124
  for (let attempt = 0; attempt < 3 && !uid; attempt++) {
1188
1125
  try {
1189
1126
  const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1127
+ guardSessionResponse(check);
1190
1128
  const html = check && check.data ? String(check.data) : "";
1191
1129
  stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1192
1130
  const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
@@ -1194,7 +1132,8 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1194
1132
  uid = uidMatch[1];
1195
1133
  break;
1196
1134
  }
1197
- } catch {
1135
+ } catch (checkErr) {
1136
+ if (isSessionEnforcementError(checkErr)) throw checkErr;
1198
1137
  // network hiccup on this attempt - retry below instead of
1199
1138
  // immediately assuming the session is dead
1200
1139
  }
@@ -1204,7 +1143,8 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1204
1143
  logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1205
1144
  return true;
1206
1145
  }
1207
- } catch {
1146
+ } catch (checkErr) {
1147
+ if (isSessionEnforcementError(checkErr)) throw checkErr;
1208
1148
  // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1209
1149
  }
1210
1150
 
@@ -1213,12 +1153,15 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1213
1153
  const tf = config.credentials?.twofactor || null;
1214
1154
  if (!u || !p) return false;
1215
1155
  const r = await tokens(u, p, tf);
1156
+ guardSessionResponse(r);
1216
1157
  if (!(r && r.status && Array.isArray(r.cookies))) return false;
1217
1158
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
1218
1159
  setJarFromPairs(jar, pairs, ".facebook.com");
1219
- await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1160
+ const response = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1161
+ guardSessionResponse(response);
1220
1162
  return true;
1221
- } catch {
1163
+ } catch (loginErr) {
1164
+ if (isSessionEnforcementError(loginErr)) throw loginErr;
1222
1165
  return false;
1223
1166
  }
1224
1167
  };
@@ -1332,13 +1275,28 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1332
1275
  api.listen = api.listenMqtt;
1333
1276
  }
1334
1277
  if (api.refreshFb_dtsg) {
1278
+ // [Hardened] refresh fb_dtsg every 6h (was 24h) to prevent token-expiry logouts
1335
1279
  setInterval(function () {
1336
1280
  api.refreshFb_dtsg().then(function () {
1337
1281
  logger("Successfully refreshed fb_dtsg");
1338
- }).catch(function () {
1339
- logger("An error occurred while refreshing fb_dtsg", "error");
1282
+ }).catch(function (e) {
1283
+ logger("An error occurred while refreshing fb_dtsg: " + (e && e.message ? e.message : e), "error");
1340
1284
  });
1341
- }, 86400000);
1285
+ }, 6 * 60 * 60 * 1000);
1286
+ // [Hardened] light session keepalive every 20 min - hits facebook.com so cookies stay warm
1287
+ setInterval(function () {
1288
+ try {
1289
+ const { get } = require("../src/utils/request");
1290
+ const { saveCookies } = require("../src/utils/client");
1291
+ if (!ctxMain || !ctxMain.jar || ctxMain._ending) return;
1292
+ get("https://www.facebook.com/", ctxMain.jar, null, ctxMain.globalOptions, ctxMain)
1293
+ .then(saveCookies(ctxMain.jar))
1294
+ .then(function () { logger("session keepalive ok", "debug"); })
1295
+ .catch(function (e) {
1296
+ logger("session keepalive failed: " + (e && e.message ? e.message : e), "warn");
1297
+ });
1298
+ } catch (_) {}
1299
+ }, 20 * 60 * 1000);
1342
1300
  }
1343
1301
  // ✅ fca-nx core features register
1344
1302
  try {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.5",
4
- "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
3
+ "version": "6.7.7",
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
+ };
@@ -22,13 +22,16 @@ module.exports = function (defaultFuncs, api, ctx) {
22
22
  };
23
23
  }
24
24
 
25
- // [Fixed by xalman] Accept numbers too. Before, any non-string id was silently
25
+ // [Hardened] Accept numbers/bigint too. Previously any non-string id was silently
26
26
  // replaced with "" and Facebook answered messenger_thread_theme: null.
27
27
  if (typeof id === "number" || typeof id === "bigint") id = String(id);
28
28
  id = typeof id === "string" ? id.trim() : "";
29
29
 
30
30
  if (!/^\d+$/.test(id)) {
31
- callback({ error: "getThemePictures: a numeric theme ID is required (theme_fbid), got: " + JSON.stringify(id) });
31
+ const err = {
32
+ error: "getThemePictures: a numeric theme ID is required (theme_fbid), got: " + JSON.stringify(id)
33
+ };
34
+ callback(err);
32
35
  return returnPromise;
33
36
  }
34
37
 
@@ -49,8 +52,8 @@ module.exports = function (defaultFuncs, api, ctx) {
49
52
  throw resData;
50
53
  }
51
54
 
52
- // [Fixed by xalman] The request itself worked (doc_id is valid) but Facebook has
53
- // no theme with this ID for this account. Report it as a failure instead of "success".
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.
54
57
  if (!resData || !resData.data || !resData.data.messenger_thread_theme) {
55
58
  const notFound = {
56
59
  error: "Theme not found: Facebook returned no theme for ID " + id + ". Check the ID (use the theme_fbid of a real theme).",
@@ -5,6 +5,7 @@
5
5
  */
6
6
  const { formatID } = require("../../../utils/format");
7
7
  const { getSessionIdentity } = require("../../../utils/clientIdentity");
8
+ const { isSessionEnforcement } = require("../../../utils/sessionStatus");
8
9
 
9
10
  const DEFAULT_RECONNECT_DELAY_MS = 2000;
10
11
  const MAX_RECONNECT_DELAY_MS = 60000;
@@ -20,11 +21,14 @@ const T_MS_WAIT_TIMEOUT_MS = 5000;
20
21
  // [Fixed by xalman] IMMEDIATE RECONNECT: the first reconnect after a disconnect now happens at
21
22
  // once (0ms) instead of waiting for a scheduled 4-6s delay. Only if that attempt also fails does
22
23
  // 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.
24
+ // Default is scheduled reconnect (safer). Set FCA_NX_MQTT_IMMEDIATE_RECONNECT=1
25
+ // (or mqtt option immediateReconnect:true) only if you need the old instant behaviour.
25
26
  function isImmediateReconnect(ctx) {
26
- // [Fixed by xalman] opt-in only: instant reconnects can create overlapping sessions
27
- return process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1";
27
+ // [Hardened] opt-in only: instant reconnects can create overlapping sessions / checkpoint risk
28
+ // Enable with FCA_NX_MQTT_IMMEDIATE_RECONNECT=1 or mqtt option immediateReconnect:true
29
+ if (process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1") return true;
30
+ if (ctx && ctx._mqttOpt && ctx._mqttOpt.immediateReconnect === true) return true;
31
+ return false;
28
32
  }
29
33
 
30
34
  function computeBackoff(ctx, baseMs) {
@@ -181,25 +185,44 @@ module.exports = function createListenMqtt(deps) {
181
185
  return;
182
186
  }
183
187
 
188
+ if (isSessionEnforcement(err)) {
189
+ return emitAuth(
190
+ ctx,
191
+ api,
192
+ globalCallback,
193
+ "verification_required",
194
+ "Facebook requires manual account verification; automatic reconnect stopped."
195
+ );
196
+ }
197
+
184
198
  if (/Not logged in|Not logged in.|blocked the login|401|403/i.test(msg)) {
185
199
  try {
186
200
  if (mqttClient && mqttClient.connected) {
187
201
  mqttClient.end(true);
188
202
  }
189
203
  } catch (_) { }
190
- if (/blocked/i.test(msg)) {
204
+ // [Hardened] Only permanent-logout on explicit "blocked the login"
205
+ if (/blocked the login/i.test(msg)) {
191
206
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
192
207
  }
193
208
 
194
- // Auth responses can race with the shared cookie refresh triggered by
195
- // another request. Treat a plain 401/403/"Not logged in" MQTT error as
196
- // recoverable instead of emitting account_inactive and permanently
197
- // setting ctx._ending. The close handler/scheduler will establish a
198
- // fresh MQTT connection with the refreshed session.
199
- logger(`mqtt transient auth error; reconnecting without logging out: ${msg}`, "warn");
200
- if (!ctx._ending && ctx.globalOptions.autoReconnect) {
201
- scheduleReconnect();
202
- }
209
+ // Plain 401/403/"Not logged in" is often a cookie/token race — recover softly.
210
+ logger(`mqtt transient auth error; refreshing session then reconnecting (no logout): ${msg}`, "warn");
211
+ (async () => {
212
+ try {
213
+ if (api && typeof api.refreshFb_dtsg === "function") {
214
+ await api.refreshFb_dtsg();
215
+ }
216
+ } catch (_) {}
217
+ try {
218
+ const { get } = require("../../../utils/request");
219
+ const { saveCookies } = require("../../../utils/client");
220
+ await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
221
+ } catch (_) {}
222
+ if (!ctx._ending && ctx.globalOptions && ctx.globalOptions.autoReconnect !== false) {
223
+ scheduleReconnect();
224
+ }
225
+ })();
203
226
  return;
204
227
  }
205
228
  logger(`mqtt error: ${msg}`, "error");
@@ -210,7 +233,7 @@ module.exports = function createListenMqtt(deps) {
210
233
  } catch (_) { }
211
234
  if (ctx._ending || ctx._cycling) return;
212
235
 
213
- if (ctx.globalOptions.autoReconnect && !ctx._ending) {
236
+ if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
214
237
  // Let scheduleReconnect() compute the exponential-backoff delay
215
238
  // itself (instead of always passing the same fixed base delay),
216
239
  // so repeated network failures back off instead of retrying every
@@ -227,6 +250,8 @@ module.exports = function createListenMqtt(deps) {
227
250
  process.env.OnStatus = true;
228
251
  }
229
252
  ctx._cycling = false;
253
+ ctx.loggedIn = true;
254
+ ctx._sessionRecovering = false;
230
255
  // A successful connect means the session/identity/network are fine -
231
256
  // reset the backoff counter so a later transient failure starts a
232
257
  // fresh backoff sequence instead of inheriting a long delay from an
@@ -341,7 +366,7 @@ module.exports = function createListenMqtt(deps) {
341
366
  return;
342
367
  }
343
368
  logger("mqtt connection closed", "warn");
344
- if (ctx.globalOptions.autoReconnect && !ctx._ending) {
369
+ if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
345
370
  scheduleReconnect();
346
371
  }
347
372
  });
@@ -352,7 +377,7 @@ module.exports = function createListenMqtt(deps) {
352
377
  return;
353
378
  }
354
379
  logger("mqtt disconnected", "warn");
355
- if (ctx.globalOptions.autoReconnect && !ctx._ending) {
380
+ if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
356
381
  scheduleReconnect();
357
382
  }
358
383
  });
@@ -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 {
@@ -8,6 +8,11 @@ const { getType } = require("../../../utils/format");
8
8
  const { parseAndCheckLogin } = require("../../../utils/client");
9
9
  const path = require("path");
10
10
  const loginHelper = require("../../../../module/loginHelper");
11
+ const {
12
+ isSessionEnforcement,
13
+ createSessionEnforcementError,
14
+ isSessionEnforcementError
15
+ } = require("../../../utils/sessionStatus");
11
16
 
12
17
  function getConfig() {
13
18
  try {
@@ -62,6 +67,9 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
62
67
  twofactor,
63
68
  config.apiServer || null
64
69
  );
70
+ if (isSessionEnforcement(result)) {
71
+ throw createSessionEnforcementError();
72
+ }
65
73
 
66
74
  if (result && result.status) {
67
75
  const normalizeCookieHeaderString = loginHelper.normalizeCookieHeaderString;
@@ -130,6 +138,9 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
130
138
  logger(`getSeqID: Refreshing ${urlToUse} (attempt ${attempt + 1}/3)...`, "info");
131
139
 
132
140
  webResponse = await get(urlToUse, ctx.jar, null, ctx.globalOptions, ctx);
141
+ if (isSessionEnforcement(webResponse)) {
142
+ throw createSessionEnforcementError();
143
+ }
133
144
  if (webResponse && webResponse.data) {
134
145
  await saveWebCookies(ctx.jar)(webResponse);
135
146
  htmlContent = typeof webResponse.data === "string" ? webResponse.data : String(webResponse.data || "");
@@ -183,6 +194,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
183
194
 
184
195
  logger(`getSeqID: auto re-login failed - ${result && result.message ? result.message : "unknown error"}`, "error");
185
196
  } catch (loginErr) {
197
+ if (isSessionEnforcementError(loginErr)) throw loginErr;
186
198
  logger(`getSeqID: auto re-login error - ${loginErr && loginErr.message ? loginErr.message : String(loginErr)}`, "error");
187
199
  }
188
200
 
@@ -193,8 +205,8 @@ module.exports = function createGetSeqID(deps) {
193
205
  const { listenMqtt, logger, emitAuth } = deps;
194
206
 
195
207
  return function getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount = 0) {
196
- const MAX_RETRIES = 3;
197
- const RETRY_DELAY = 2000;
208
+ const MAX_RETRIES = 5;
209
+ const RETRY_DELAY = 3000; // [Hardened] slower + more attempts before any logout decision
198
210
  ctx.t_mqttCalled = false;
199
211
 
200
212
  // Ensure essential tokens are injected into GraphQL Batch Payload
@@ -225,6 +237,16 @@ module.exports = function createGetSeqID(deps) {
225
237
  .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
226
238
  .then(parseAndCheckLogin(ctx, defaultFuncs))
227
239
  .then(async resData => {
240
+ if (isSessionEnforcement(resData)) {
241
+ return emitAuth(
242
+ ctx,
243
+ api,
244
+ globalCallback,
245
+ "verification_required",
246
+ "Facebook requires manual account verification; automatic recovery stopped."
247
+ );
248
+ }
249
+
228
250
  // Safe check for non-array responses (such as Error Objects from FB)
229
251
  if (getType(resData) !== "Array") {
230
252
  logger(`getSeqID: Response is not Array, received: ${getType(resData)}`, "warn");
@@ -267,6 +289,21 @@ module.exports = function createGetSeqID(deps) {
267
289
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
268
290
  })
269
291
  .catch(async err => {
292
+ if (
293
+ isSessionEnforcementError(err) ||
294
+ isSessionEnforcement(err) ||
295
+ isSessionEnforcement(err && err.originalResponse) ||
296
+ isSessionEnforcement(err && err.response)
297
+ ) {
298
+ return emitAuth(
299
+ ctx,
300
+ api,
301
+ globalCallback,
302
+ "verification_required",
303
+ "Facebook requires manual account verification; automatic recovery stopped."
304
+ );
305
+ }
306
+
270
307
  const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
271
308
  const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
272
309
 
@@ -298,18 +335,25 @@ module.exports = function createGetSeqID(deps) {
298
335
  const delay = RETRY_DELAY * (retryCount + 1);
299
336
  logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (error: ${msg})`, "warn");
300
337
  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");
338
+
339
+ // [Hardened] Always refresh cookies + fb_dtsg before each auth retry
340
+ try {
341
+ logger("getSeqID: refreshing session (cookies + fb_dtsg) before retry...", "info");
342
+ const { get } = require("../../../utils/request");
343
+ const { saveCookies } = require("../../../utils/client");
344
+ await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
345
+ if (api && typeof api.refreshFb_dtsg === "function") {
346
+ try { await api.refreshFb_dtsg(); } catch (_) {}
310
347
  }
348
+ // Keep form tokens in sync with refreshed ctx
349
+ if (form) {
350
+ if (ctx.fb_dtsg) form.fb_dtsg = ctx.fb_dtsg;
351
+ if (ctx.jazoest) form.jazoest = ctx.jazoest;
352
+ }
353
+ } catch (refreshErr) {
354
+ logger(`getSeqID: session refresh failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
311
355
  }
312
-
356
+
313
357
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
314
358
  }
315
359
 
@@ -323,16 +367,49 @@ module.exports = function createGetSeqID(deps) {
323
367
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, 0);
324
368
  }
325
369
 
326
- if (/blocked/i.test(msg)) {
370
+ // [Hardened] Only permanent-logout on CLEAR blocked signal.
371
+ // Plain "Not logged in" after retries is often a transient cookie race —
372
+ // schedule a long soft-reconnect instead of killing the session forever.
373
+ if (/blocked the login|login_blocked|checkpoint_282|checkpoint_956/i.test(msg)) {
327
374
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
328
375
  }
329
- if (/Not logged in/i.test(msg)) {
330
- return emitAuth(ctx, api, globalCallback, "not_logged_in", msg);
331
- }
376
+
377
+ logger(`getSeqID: auth still failing after retries/auto-login - soft recovery (no permanent logout): ${msg}`, "error");
378
+ // Soft recovery: do NOT set ctx._ending. Notify listener, then retry later.
379
+ try {
380
+ if (typeof globalCallback === "function") {
381
+ globalCallback({
382
+ type: "session_recovering",
383
+ error: msg,
384
+ timestamp: Date.now()
385
+ }, null);
386
+ }
387
+ } catch (_) {}
388
+ // Re-attempt getSeqID after long cooldown without marking account inactive
389
+ const softDelay = Math.min(5 * 60 * 1000, 60000 * (retryCount + 1));
390
+ setTimeout(() => {
391
+ if (ctx._ending) return;
392
+ logger("getSeqID: soft recovery timer fired - retrying getSeqID", "warn");
393
+ try {
394
+ getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0);
395
+ } catch (e) {
396
+ logger(`getSeqID soft recovery error: ${e && e.message ? e.message : e}`, "error");
397
+ }
398
+ }, softDelay);
399
+ return;
332
400
  }
333
401
 
334
- logger(`getSeqID error: ${msg}`, "error");
335
- return emitAuth(ctx, api, globalCallback, "auth_error", msg);
402
+ // Non-auth, non-network: still soft-recover instead of permanent logout
403
+ logger(`getSeqID error (soft recover, no logout): ${msg}`, "error");
404
+ try {
405
+ if (typeof globalCallback === "function") {
406
+ globalCallback({ type: "session_recovering", error: msg, timestamp: Date.now() }, null);
407
+ }
408
+ } catch (_) {}
409
+ setTimeout(() => {
410
+ if (ctx._ending) return;
411
+ try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
412
+ }, 60000);
336
413
  });
337
414
  };
338
415
  };
@@ -20,7 +20,7 @@ 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;
23
+ const CYCLE_MS_DEFAULT = 2 * 60 * 60 * 1000; // [Hardened] 2h cycle - less session churn / multi-login risk
24
24
  const RECONNECT_DELAY_MS_DEFAULT = 5000;
25
25
  const UNSUB_ALL_TIMEOUT_MS = 5000;
26
26
  const MAX_MQTT_RECONNECT_DELAY_MS = 60000;
@@ -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 === "1"; // [Fixed by xalman] off by default: instant reconnect loops look like multiple sessions
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,7 +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
- if (getTextEffectId(msg)) logger.warn("sendMessage", "Text effects are not supported in E2EE DMs - sending plain text. Use a group chat for effects.");
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
+ }
304
307
  try {
305
308
  var e2eeText = await api.e2ee.sendMessage(String(threadID), { body: msg.body != null ? String(msg.body) : "" }, replyToMessage || msg.replyToMessage);
306
309
  var e2eeWrapped = e2eeText && e2eeText.messageId
@@ -337,4 +340,4 @@ module.exports = function (defaultFuncs, api, ctx) {
337
340
 
338
341
  return promise;
339
342
  };
340
- };
343
+ };
@@ -91,10 +91,10 @@ function extractPhotoUrl(photo, depth = 0) {
91
91
  }
92
92
 
93
93
 
94
- // [Fixed by xalman] Fallback: read the cover photo straight from the profile page HTML,
94
+ // [Hardened] Fallback: read the cover photo straight from the profile page HTML,
95
95
  // used when none of the GraphQL doc_ids returned a cover (doc_ids rotate often).
96
96
  function decodeJsonString(raw) {
97
- try { return JSON.parse('"' + raw + '"'); } catch { return raw.replace(/\\\//g, "/"); }
97
+ try { return JSON.parse('"' + raw + '"'); } catch { return String(raw).replace(/\\\//g, "/"); }
98
98
  }
99
99
 
100
100
  function extractCoverFromHTML(html) {
@@ -103,7 +103,9 @@ function extractCoverFromHTML(html) {
103
103
  /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
104
104
  /"profile_cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
105
105
  /"coverPhoto"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
106
- /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"url"\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
107
109
  ];
108
110
  for (const re of patterns) {
109
111
  const m = html.match(re);
@@ -273,21 +275,27 @@ module.exports = function (defaultFuncs, api, ctx) {
273
275
  logger(`getUserInfoV2 ${doc.id}: ${error.message || error}`, "warn");
274
276
  }
275
277
  }
278
+ // [Hardened] GraphQL often omits cover; scrape profile HTML as last resort
276
279
  if (bestUser && !bestUser.coverPhoto) {
277
280
  const pages = [`https://www.facebook.com/profile.php?id=${id}`];
278
- if (bestUser.vanity && bestUser.vanity !== id) pages.push(`https://www.facebook.com/${bestUser.vanity}`);
281
+ if (bestUser.vanity && bestUser.vanity !== id) {
282
+ pages.push(`https://www.facebook.com/${bestUser.vanity}`);
283
+ }
279
284
  for (const url of pages) {
280
285
  try {
281
286
  const res = await defaultFuncs.get(url, ctx.jar, null, ctx);
282
- const html = typeof res === "string" ? res : res?.data;
287
+ const html = typeof res === "string" ? res : (res && res.data);
283
288
  const cover = extractCoverFromHTML(html);
284
- if (cover) { bestUser.coverPhoto = cover; break; }
289
+ if (cover) {
290
+ bestUser.coverPhoto = cover;
291
+ break;
292
+ }
285
293
  } catch (error) {
286
294
  logger(`getUserInfoV2 cover html ${id}: ${error.message || error}`, "warn");
287
295
  }
288
296
  }
289
297
  if (!bestUser.coverPhoto && process.env.FCA_COVER_DEBUG === "1") {
290
- logger(`getUserInfoV2 cover ${id}: no cover found in GraphQL or profile HTML (account may have no cover photo)`, "warn");
298
+ logger(`getUserInfoV2 cover ${id}: no cover found in GraphQL or profile HTML`, "warn");
291
299
  }
292
300
  }
293
301
  return bestUser;
@@ -400,7 +408,7 @@ module.exports = function (defaultFuncs, api, ctx) {
400
408
  return callback(null, retObj);
401
409
  }
402
410
  })();
403
- return returnPromise;
411
+ return returnPromise;
404
412
  };
405
413
  };
406
414
 
@@ -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"),
@@ -1,6 +1,11 @@
1
1
  "use strict";
2
2
 
3
3
  const logger = require("../../../func/logger");
4
+ const {
5
+ isSessionEnforcement,
6
+ createSessionEnforcementError,
7
+ isSessionEnforcementError
8
+ } = require("../sessionStatus");
4
9
 
5
10
  /**
6
11
  * Tạo hàm maybeAutoLogin: khi session hết hạn thì thử đăng nhập lại và retry request.
@@ -14,6 +19,23 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
14
19
  const { buildUrl, headerOf, formatCookie } = helpers;
15
20
 
16
21
  return async function maybeAutoLogin(resData, resConfig) {
22
+ if (ctx._sessionEnforcement) {
23
+ throw createSessionEnforcementError();
24
+ }
25
+
26
+ const responseUrl = resConfig ? buildUrl(resConfig) : "";
27
+ if (isSessionEnforcement(resData) || isSessionEnforcement(responseUrl)) {
28
+ ctx._sessionEnforcement = true;
29
+ const error = createSessionEnforcementError();
30
+ if (typeof emit === "function") {
31
+ emit("verificationRequired", {
32
+ code: error.code,
33
+ message: error.message
34
+ });
35
+ }
36
+ throw error;
37
+ }
38
+
17
39
  const retryAfterLogin = async function () {
18
40
  if (!resConfig) {
19
41
  const e = new Error(
@@ -42,6 +64,10 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
42
64
  }
43
65
  return await parseAndCheckLogin(ctx, http)(newData);
44
66
  } catch (retryErr) {
67
+ if (isSessionEnforcementError(retryErr)) {
68
+ ctx._sessionEnforcement = true;
69
+ throw retryErr;
70
+ }
45
71
  if (
46
72
  retryErr?.code === "ERR_INVALID_CHAR" ||
47
73
  (retryErr?.message && retryErr.message.includes("Invalid character in header"))
@@ -79,6 +105,10 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
79
105
  try {
80
106
  ok = await ctx._autoLoginPromise;
81
107
  } catch (autoLoginErr) {
108
+ if (isSessionEnforcementError(autoLoginErr)) {
109
+ ctx._sessionEnforcement = true;
110
+ throw autoLoginErr;
111
+ }
82
112
  const e = new Error("Not logged in. Auto login failed.");
83
113
  e.error = "Not logged in.";
84
114
  e.res = resData;
@@ -122,6 +152,14 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
122
152
  throw e;
123
153
  }
124
154
  } catch (autoLoginErr) {
155
+ if (isSessionEnforcementError(autoLoginErr)) {
156
+ ctx._sessionEnforcement = true;
157
+ emit("verificationRequired", {
158
+ code: autoLoginErr.code,
159
+ message: autoLoginErr.message
160
+ });
161
+ throw autoLoginErr;
162
+ }
125
163
  if (autoLoginErr.error === "Not logged in.") {
126
164
  throw autoLoginErr;
127
165
  }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+
3
+ const RESPONSE_FIELDS = [
4
+ "url",
5
+ "responseUrl",
6
+ "location",
7
+ "redirect",
8
+ "config",
9
+ "message",
10
+ "error",
11
+ "errorSummary",
12
+ "errorDescription",
13
+ "reason",
14
+ "data",
15
+ "body",
16
+ "text",
17
+ "response",
18
+ "originalResponse",
19
+ "request",
20
+ "res"
21
+ ];
22
+
23
+ const ENFORCEMENT_MARKER =
24
+ /(?:\/checkpoint(?:\/|[?#])|XCheckpointFBScrapingWarningController|checkpoint_(?:282|956)\b|blocked the login|manual account verification|(?:account|profile)\b[\s\S]{0,50}\b(?:suspended|disabled)\b|\b(?:suspended|disabled)\s+(?:your|this|the)\s+(?:account|profile)\b|robot verification|security check required|confirm (?:that )?you(?:'re| are) (?:a human|not a robot))/i;
25
+
26
+ function collectResponseText(value, seen = new Set(), depth = 0) {
27
+ if (value === null || value === undefined || depth > 4) return "";
28
+ if (typeof value === "string") return value;
29
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
30
+ if (Buffer.isBuffer(value)) return value.toString("utf8");
31
+ if (typeof value !== "object" || seen.has(value)) return "";
32
+
33
+ seen.add(value);
34
+ if (Array.isArray(value)) {
35
+ return value
36
+ .slice(0, 20)
37
+ .map(item => collectResponseText(item, seen, depth + 1))
38
+ .join("\n");
39
+ }
40
+
41
+ return RESPONSE_FIELDS
42
+ .filter(key => Object.prototype.hasOwnProperty.call(value, key))
43
+ .map(key => collectResponseText(value[key], seen, depth + 1))
44
+ .join("\n");
45
+ }
46
+
47
+ function isSessionEnforcement(value) {
48
+ return ENFORCEMENT_MARKER.test(collectResponseText(value));
49
+ }
50
+
51
+ function createSessionEnforcementError() {
52
+ const error = new Error(
53
+ "Facebook requires manual account verification; automatic login and recovery stopped."
54
+ );
55
+ error.code = "SESSION_VERIFICATION_REQUIRED";
56
+ error.isSessionEnforcement = true;
57
+ return error;
58
+ }
59
+
60
+ function isSessionEnforcementError(error) {
61
+ return Boolean(
62
+ error &&
63
+ (error.code === "SESSION_VERIFICATION_REQUIRED" ||
64
+ error.isSessionEnforcement === true)
65
+ );
66
+ }
67
+
68
+ module.exports = {
69
+ isSessionEnforcement,
70
+ createSessionEnforcementError,
71
+ isSessionEnforcementError
72
+ };