fca-nx 6.7.7 → 6.7.9

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,12 +380,6 @@ 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.
389
383
  >
390
384
  # 🧩 API Architecture
391
385
  ```text
package/module/login.js CHANGED
@@ -135,7 +135,7 @@ function login(loginData, options, callback) {
135
135
  forceLogin: false,
136
136
  autoMarkRead: false,
137
137
  autoReconnect: true,
138
- online: true,
138
+ online: false, // [Hardened5] always-online is a strong automation signal
139
139
  emitReady: false,
140
140
  // Single source of truth for the default identity - see src/utils/clientIdentity.js.
141
141
  // This used to be hard-coded independently here (Chrome/121), in
@@ -5,16 +5,11 @@ 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, makeDefaults } = require("../src/utils/request");
8
+ const { get, post, 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");
18
13
  const { createRemoteClient } = require("../src/remote/remoteClient");
19
14
  const { config } = loadConfig();
20
15
  const axiosBase = require("axios");
@@ -49,17 +44,6 @@ function parseRegion(html) {
49
44
  }
50
45
  }
51
46
 
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
-
63
47
  function mask(s, keep = 3) {
64
48
  if (!s) return "";
65
49
  const n = s.length;
@@ -536,8 +520,6 @@ async function hydrateJarFromDB(userID, jar) {
536
520
  }
537
521
 
538
522
  async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions, ctxRef, hadAppStateInput = false, jar) {
539
- guardSessionResponse(currentHtml);
540
-
541
523
  // Helper to validate UID - must be a non-zero positive number string
542
524
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
543
525
 
@@ -584,18 +566,19 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
584
566
  logger("tryAutoLoginIfNeeded: Trying backup from DB...", "info");
585
567
  try {
586
568
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
587
- const resB = (await ctxRef.guardSessionResponse(initial)) || initial;
569
+ const resB = (await ctxRef.bypassAutomation(initial, jar)) || initial;
588
570
  const htmlB = resB && resB.data ? resB.data : "";
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");
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
+ }
596
580
  }
597
581
  } catch (dbErr) {
598
- if (isSessionEnforcementError(dbErr)) throw dbErr;
599
582
  logger(`tryAutoLoginIfNeeded: DB backup failed - ${dbErr && dbErr.message ? dbErr.message : String(dbErr)}`, "warn");
600
583
  }
601
584
  }
@@ -618,7 +601,6 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
618
601
  logger(`tryAutoLoginIfNeeded: Attempting API login for ${u.slice(0, 3)}***...`, "info");
619
602
 
620
603
  const r = await tokens(u, p, tf);
621
- guardSessionResponse(r);
622
604
  if (!r || !r.status) {
623
605
  throw new Error(r && r.message ? r.message : "API Login failed");
624
606
  }
@@ -685,7 +667,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
685
667
  logger(`tryAutoLoginIfNeeded: Refreshing ${urlToUse} (attempt ${retryCount + 1}/${maxRetries})...`, "info");
686
668
 
687
669
  const initial2 = await get(urlToUse, jar, null, globalOptions).then(saveCookies(jar));
688
- res2 = (await ctxRef.guardSessionResponse(initial2)) || initial2;
670
+ res2 = (await ctxRef.bypassAutomation(initial2, jar)) || initial2;
689
671
  html2 = res2 && res2.data ? res2.data : "";
690
672
 
691
673
  if (html2.includes("/checkpoint/block/?next")) {
@@ -709,7 +691,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
709
691
  break;
710
692
  }
711
693
  } catch (err) {
712
- if (isSessionEnforcementError(err) || (err.message && err.message.includes("Checkpoint"))) {
694
+ if (err.message && err.message.includes("Checkpoint")) {
713
695
  throw err;
714
696
  }
715
697
  if (retryCount < maxRetries - 1) {
@@ -759,12 +741,10 @@ function makeLogin(j, email, password, globalOptions) {
759
741
  const tf = config.credentials?.twofactor || null;
760
742
  if (!u || !p) return;
761
743
  const r = await tokens(u, p, tf);
762
- guardSessionResponse(r);
763
744
  if (r && r.status && Array.isArray(r.cookies)) {
764
745
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
765
746
  setJarFromPairs(j, pairs, ".facebook.com");
766
- const response = await get("https://www.facebook.com/", j, null, globalOptions).then(saveCookies(j));
767
- guardSessionResponse(response);
747
+ await get("https://www.facebook.com/", j, null, globalOptions).then(saveCookies(j));
768
748
  } else {
769
749
  throw new Error(r && r.message ? r.message : "Login failed");
770
750
  }
@@ -805,6 +785,20 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
805
785
  let userIDFromAppState = extractUIDFromAppState(appState);
806
786
  (async () => {
807
787
  try {
788
+ // [Hardened4] one live process per account (overlapping deploys / double start = "multiple sessions")
789
+ try {
790
+ const lk = require("../src/utils/instanceLock").acquire(userIDFromAppState);
791
+ if (!lk.ok) {
792
+ return callback(new Error("Another bot process is already running this account (pid " + lk.pid + "). Refusing to start a second session. Set FCA_NX_INSTANCE_LOCK=off to disable."));
793
+ }
794
+ } catch (_) {}
795
+ // Same-IP/location guard (warn by default, FCA_NX_IP_GUARD=block to refuse).
796
+ try {
797
+ const ipRes = await require("../src/utils/ipGuard").checkLoginIP(require("../src/utils/request").client, userIDFromAppState);
798
+ if (!ipRes.ok) {
799
+ return callback(new Error("Login refused: public IP changed (" + ipRes.previous + " -> " + ipRes.ip + ") and FCA_NX_IP_GUARD=block"));
800
+ }
801
+ } catch (_) { /* never let the guard break login */ }
808
802
  if (appState) {
809
803
  // Check and convert cookie to appState format
810
804
  if (Array.isArray(appState) && appState.some(c => c.name)) {
@@ -863,18 +857,66 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
863
857
  return callback(e);
864
858
  }
865
859
  const ctx = { globalOptions, options: globalOptions, reconnectAttempts: 0 };
866
- ctx.guardSessionResponse = async function (response) {
867
- return guardSessionResponse(response);
860
+ ctx.bypassAutomation = async function (resp, j) {
861
+ global.fca = global.fca || {};
862
+ global.fca.BypassAutomationNotification = this.bypassAutomation.bind(this);
863
+ const s = x => (typeof x === "string" ? x : String(x ?? ""));
864
+ const u = r => r?.request?.res?.responseUrl || (r?.config?.baseURL ? new URL(r.config.url || "/", r.config.baseURL).toString() : r?.config?.url || "");
865
+ const isCp = r => typeof u(r) === "string" && u(r).includes("checkpoint/601051028565049");
866
+ const cookieUID = async () => {
867
+ try {
868
+ const cookies = typeof j?.getCookies === "function" ? await j.getCookies("https://www.facebook.com") : [];
869
+ return cookies.find(c => c.key === "i_user")?.value || cookies.find(c => c.key === "c_user")?.value;
870
+ } catch { return undefined; }
871
+ };
872
+ const htmlUID = body => s(body).match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s(body).match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
873
+ const getUID = async body => (await cookieUID()) || htmlUID(body);
874
+ const refreshJar = async () => get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
875
+ const bypass = async body => {
876
+ const b = s(body);
877
+ const UID = await getUID(b);
878
+ const fb_dtsg = getFrom(b, '"DTSGInitData",[],{"token":"', '",') || b.match(/name="fb_dtsg"\s+value="([^"]+)"/)?.[1];
879
+ const jazoest = getFrom(b, 'name="jazoest" value="', '"') || getFrom(b, "jazoest=", '",') || b.match(/name="jazoest"\s+value="([^"]+)"/)?.[1];
880
+ const lsd = getFrom(b, '["LSD",[],{"token":"', '"}') || b.match(/name="lsd"\s+value="([^"]+)"/)?.[1];
881
+ 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 };
882
+ await post("https://www.facebook.com/api/graphql/", j, form, null, this.options).then(saveCookies(j));
883
+ logger("⚠️ Facebook automation detected — bypassing...", "warn");
884
+ this.reconnectAttempts = 0;
885
+ };
886
+ try {
887
+ if (resp) {
888
+ if (isCp(resp)) {
889
+ await bypass(s(resp.data));
890
+ const refreshed = await refreshJar();
891
+ if (isCp(refreshed)) logger("Checkpoint still present after refresh", "warn");
892
+ else logger("✅ Bypass complete — session restored.", "info");
893
+ return refreshed;
894
+ }
895
+ return resp;
896
+ }
897
+ const first = await get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
898
+ if (isCp(first)) {
899
+ await bypass(s(first.data));
900
+ const refreshed = await refreshJar();
901
+ if (!isCp(refreshed)) logger("✅ Bypass complete — session restored.", "info");
902
+ else logger("Checkpoint still present after refresh", "warn");
903
+ return refreshed;
904
+ }
905
+ return first;
906
+ } catch (e) {
907
+ logger(`Bypass automation error: ${e && e.message ? e.message : String(e)}`, "error");
908
+ return resp;
909
+ }
868
910
  };
869
911
  if (appState || Cookie) {
870
912
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
871
- return (await ctx.guardSessionResponse(initial, jar)) || initial;
913
+ return (await ctx.bypassAutomation(initial, jar)) || initial;
872
914
  }
873
915
  const hydrated = await hydrateJarFromDB(null, jar);
874
916
  if (hydrated) {
875
917
  logger(chalk.italic("🔄 AppState backup found — restoring session..."), "info");
876
918
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
877
- return (await ctx.guardSessionResponse(initial, jar)) || initial;
919
+ return (await ctx.bypassAutomation(initial, jar)) || initial;
878
920
  }
879
921
  logger(chalk.italic("😐 AppState expired — logging in with credentials..."), "warn");
880
922
  return get("https://www.facebook.com/", null, null, globalOptions)
@@ -887,10 +929,45 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
887
929
  .then(async function (res) {
888
930
  const ctx = {};
889
931
  ctx.options = globalOptions;
890
- ctx.guardSessionResponse = async function (response) {
891
- return guardSessionResponse(response);
932
+ ctx.bypassAutomation = async function (resp, j) {
933
+ global.fca = global.fca || {};
934
+ global.fca.BypassAutomationNotification = this.bypassAutomation.bind(this);
935
+ const s = x => (typeof x === "string" ? x : String(x ?? ""));
936
+ const u = r => r?.request?.res?.responseUrl || (r?.config?.baseURL ? new URL(r.config.url || "/", r.config.baseURL).toString() : r?.config?.url || "");
937
+ const isCp = r => typeof u(r) === "string" && u(r).includes("checkpoint/601051028565049");
938
+ const cookieUID = async () => {
939
+ try {
940
+ const cookies = typeof j?.getCookies === "function" ? await j.getCookies("https://www.facebook.com") : [];
941
+ return cookies.find(c => c.key === "i_user")?.value || cookies.find(c => c.key === "c_user")?.value;
942
+ } catch { return undefined; }
943
+ };
944
+ const htmlUID = body => s(body).match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s(body).match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
945
+ const getUID = async body => (await cookieUID()) || htmlUID(body);
946
+ const refreshJar = async () => get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
947
+ const bypass = async body => {
948
+ const b = s(body);
949
+ const UID = await getUID(b);
950
+ const fb_dtsg = getFrom(b, '"DTSGInitData",[],{"token":"', '",') || b.match(/name="fb_dtsg"\s+value="([^"]+)"/)?.[1];
951
+ const jazoest = getFrom(b, 'name="jazoest" value="', '"') || getFrom(b, "jazoest=", '",') || b.match(/name="jazoest"\s+value="([^"]+)"/)?.[1];
952
+ const lsd = getFrom(b, '["LSD",[],{"token":"', '"}') || b.match(/name="lsd"\s+value="([^"]+)"/)?.[1];
953
+ 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 };
954
+ await post("https://www.facebook.com/api/graphql/", j, form, null, this.options).then(saveCookies(j));
955
+ logger("⚠️ Facebook automation detected — bypassing...", "warn");
956
+ };
957
+ try {
958
+ if (res && isCp(res)) {
959
+ await bypass(s(res.data));
960
+ const refreshed = await refreshJar();
961
+ if (!isCp(refreshed)) logger("✅ Bypass complete — session restored.", "info");
962
+ return refreshed;
963
+ }
964
+ logger("✅ No checkpoint detected — session is clean.", "info");
965
+ return res;
966
+ } catch {
967
+ return res;
968
+ }
892
969
  };
893
- const processed = (await ctx.guardSessionResponse(res)) || res;
970
+ const processed = (await ctx.bypassAutomation(res, jar)) || res;
894
971
  let html = processed && processed.data ? processed.data : "";
895
972
  let cookies = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
896
973
  const getUIDFromCookies = cs =>
@@ -1097,14 +1174,15 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1097
1174
  firstListen: true,
1098
1175
  fb_dtsg,
1099
1176
  clientID: ((Math.random() * 2147483648) | 0).toString(16),
1100
- clientId: getFrom(html, '["MqttWebDeviceID",[],{"clientID":"', '"}') || "",
1177
+ // [Hardened5] never leave mqtt device id empty - empty rotates badly across reconnects
1178
+ clientId: getFrom(html, '["MqttWebDeviceID",[],{"clientID":"', '"}') || ((""+Math.random()).slice(2)+Date.now().toString(16)).slice(0, 16),
1101
1179
  wsReqNumber: 0,
1102
1180
  wsTaskNumber: 0,
1103
1181
  tasks: new Map(),
1104
1182
  _emitter: emitter
1105
1183
  };
1106
1184
  ctxMain.options = globalOptions;
1107
- ctxMain.guardSessionResponse = ctx.guardSessionResponse;
1185
+ ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1108
1186
  ctxMain.performAutoLogin = async () => {
1109
1187
  try {
1110
1188
  // [Fixed by xalman] First check whether the existing cookie session is actually
@@ -1124,7 +1202,6 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1124
1202
  for (let attempt = 0; attempt < 3 && !uid; attempt++) {
1125
1203
  try {
1126
1204
  const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1127
- guardSessionResponse(check);
1128
1205
  const html = check && check.data ? String(check.data) : "";
1129
1206
  stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1130
1207
  const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
@@ -1132,8 +1209,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1132
1209
  uid = uidMatch[1];
1133
1210
  break;
1134
1211
  }
1135
- } catch (checkErr) {
1136
- if (isSessionEnforcementError(checkErr)) throw checkErr;
1212
+ } catch {
1137
1213
  // network hiccup on this attempt - retry below instead of
1138
1214
  // immediately assuming the session is dead
1139
1215
  }
@@ -1143,8 +1219,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1143
1219
  logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1144
1220
  return true;
1145
1221
  }
1146
- } catch (checkErr) {
1147
- if (isSessionEnforcementError(checkErr)) throw checkErr;
1222
+ } catch {
1148
1223
  // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1149
1224
  }
1150
1225
 
@@ -1152,21 +1227,30 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1152
1227
  const p = config.credentials?.password || password;
1153
1228
  const tf = config.credentials?.twofactor || null;
1154
1229
  if (!u || !p) return false;
1230
+ // [Hardened4] Repeated credential logins are a classic trigger for "automated
1231
+ // behaviour"/"multiple sessions" restrictions. At most one per cooldown window
1232
+ // (FCA_NX_RELOGIN_COOLDOWN_MIN, default 30), and never while Facebook is showing
1233
+ // its scraping warning - re-logging in then only makes it worse.
1234
+ const cdMs = (Number(process.env.FCA_NX_RELOGIN_COOLDOWN_MIN) || 30) * 60 * 1000;
1235
+ const sinceLast = Date.now() - (global.__fcaLastCredLogin || 0);
1236
+ if (sinceLast < cdMs) {
1237
+ logger("performAutoLogin: credential login skipped (cooldown " + Math.ceil((cdMs - sinceLast) / 60000) + " min left) to avoid repeated-login restrictions", "warn");
1238
+ return false;
1239
+ }
1240
+ global.__fcaLastCredLogin = Date.now();
1155
1241
  const r = await tokens(u, p, tf);
1156
- guardSessionResponse(r);
1157
1242
  if (!(r && r.status && Array.isArray(r.cookies))) return false;
1158
1243
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
1159
1244
  setJarFromPairs(jar, pairs, ".facebook.com");
1160
- const response = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1161
- guardSessionResponse(response);
1245
+ await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1162
1246
  return true;
1163
- } catch (loginErr) {
1164
- if (isSessionEnforcementError(loginErr)) throw loginErr;
1247
+ } catch {
1165
1248
  return false;
1166
1249
  }
1167
1250
  };
1168
1251
  const api = {
1169
1252
  setOptions: require("./options").setOptions.bind(null, globalOptions),
1253
+ setSendDelay: require("../src/utils/sendThrottle").setSendDelay,
1170
1254
  getCookies: function () {
1171
1255
  return cookieHeaderFromJar(jar);
1172
1256
  },
@@ -1284,19 +1368,25 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1284
1368
  });
1285
1369
  }, 6 * 60 * 60 * 1000);
1286
1370
  // [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);
1371
+ // [Hardened4] randomised 15-25 min (a perfectly fixed interval looks scripted)
1372
+ (function keepaliveLoop() {
1373
+ const t = setTimeout(function () {
1374
+ try {
1375
+ const { get } = require("../src/utils/request");
1376
+ const { saveCookies } = require("../src/utils/client");
1377
+ if (ctxMain && ctxMain.jar && !ctxMain._ending) {
1378
+ get("https://www.facebook.com/", ctxMain.jar, null, ctxMain.globalOptions, ctxMain)
1379
+ .then(saveCookies(ctxMain.jar))
1380
+ .then(function () { logger("session keepalive ok", "debug"); })
1381
+ .catch(function (e) {
1382
+ logger("session keepalive failed: " + (e && e.message ? e.message : e), "warn");
1383
+ });
1384
+ }
1385
+ } catch (_) {}
1386
+ keepaliveLoop();
1387
+ }, (18 + Math.random() * 14) * 60 * 1000); // [Hardened5] 18-32 min irregular keepalive
1388
+ if (t.unref) t.unref();
1389
+ })();
1300
1390
  }
1301
1391
  // ✅ fca-nx core features register
1302
1392
  try {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.7",
4
- "description": "Facebook Messenger API for Node.js \u2014 anti-logout hardened (soft session recovery, keepalive, safe MQTT)",
3
+ "version": "6.7.9",
4
+ "description": "Facebook Messenger API for Node.js \u2014 hardened sendMessage + listenMqtt (cascade fallback, soft MQTT, anti-reconnect-storm)",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "exports": {
@@ -5,12 +5,11 @@
5
5
  */
6
6
  const { formatID } = require("../../../utils/format");
7
7
  const { getSessionIdentity } = require("../../../utils/clientIdentity");
8
- const { isSessionEnforcement } = require("../../../utils/sessionStatus");
9
8
 
10
9
  const DEFAULT_RECONNECT_DELAY_MS = 2000;
11
10
  const MAX_RECONNECT_DELAY_MS = 60000;
12
- const MAX_RECONNECT_ATTEMPTS = 10; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
13
- const MAX_RECONNECT_COOLDOWN_MS = 10 * 60 * 1000; // after exhausting fast retries, wait this long before trying again (never give up permanently)
11
+ const MAX_RECONNECT_ATTEMPTS = 8 // [Hardened5] hit long cooldown sooner instead of hammering; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
12
+ const MAX_RECONNECT_COOLDOWN_MS = 15 * 60 * 1000 /* [Hardened5] longer cooldown */; // after exhausting fast retries, wait this long before trying again (never give up permanently)
14
13
  const T_MS_WAIT_TIMEOUT_MS = 5000;
15
14
 
16
15
  // Exponential backoff with jitter, based on how many *consecutive* reconnect
@@ -40,7 +39,7 @@ function computeBackoff(ctx, baseMs) {
40
39
  return Math.min(fast + j, MAX_RECONNECT_DELAY_MS);
41
40
  }
42
41
  const exp = Math.min(baseMs * Math.pow(2, attempt), MAX_RECONNECT_DELAY_MS);
43
- const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
42
+ const jitter = Math.floor(Math.random() * Math.min(4000, exp * 0.4)); // [Hardened5]
44
43
  return Math.min(exp + jitter, MAX_RECONNECT_DELAY_MS);
45
44
  }
46
45
 
@@ -113,7 +112,12 @@ module.exports = function createListenMqtt(deps) {
113
112
  // never disagree about User-Agent / Accept-Language mid-session.
114
113
  const identity = getSessionIdentity(ctx);
115
114
 
116
- const chatOn = ctx.globalOptions.online;
115
+ // [Hardened5] stable device id for the whole process lifetime
116
+ if (!ctx.clientId || ctx.clientId === "") {
117
+ ctx.clientId = ctx.clientID || ((""+Math.random()).slice(2) + Date.now()).slice(0, 16);
118
+ }
119
+ // Prefer offline presence unless user explicitly set online:true
120
+ const chatOn = ctx.globalOptions.online === true;
117
121
  const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
118
122
  const username = {
119
123
  u: ctx.userID, s: sessionID, chat_on: chatOn, fg: false, d: ctx.clientId,
@@ -185,16 +189,6 @@ module.exports = function createListenMqtt(deps) {
185
189
  return;
186
190
  }
187
191
 
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
-
198
192
  if (/Not logged in|Not logged in.|blocked the login|401|403/i.test(msg)) {
199
193
  try {
200
194
  if (mqttClient && mqttClient.connected) {
@@ -268,8 +262,11 @@ module.exports = function createListenMqtt(deps) {
268
262
  const topic = ctx.syncToken ? "/messenger_sync_get_diffs" : "/messenger_sync_create_queue";
269
263
  if (ctx.syncToken) { queue.last_seq_id = ctx.lastSeqId; queue.sync_token = ctx.syncToken; }
270
264
  mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
271
- mqttClient.publish("/foreground_state", JSON.stringify({ foreground: chatOn }), { qos: 1 });
272
- mqttClient.publish("/set_client_settings", JSON.stringify({ make_user_available_when_in_foreground: true }), { qos: 1 });
265
+ // [Hardened5] only claim foreground/available when online:true
266
+ mqttClient.publish("/foreground_state", JSON.stringify({ foreground: !!chatOn }), { qos: 1 });
267
+ if (chatOn) {
268
+ mqttClient.publish("/set_client_settings", JSON.stringify({ make_user_available_when_in_foreground: true }), { qos: 1 });
269
+ }
273
270
  let rTimeout = setTimeout(function () {
274
271
  rTimeout = null;
275
272
  if (ctx._ending) {
@@ -8,11 +8,6 @@ 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");
16
11
 
17
12
  function getConfig() {
18
13
  try {
@@ -67,9 +62,6 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
67
62
  twofactor,
68
63
  config.apiServer || null
69
64
  );
70
- if (isSessionEnforcement(result)) {
71
- throw createSessionEnforcementError();
72
- }
73
65
 
74
66
  if (result && result.status) {
75
67
  const normalizeCookieHeaderString = loginHelper.normalizeCookieHeaderString;
@@ -138,9 +130,6 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
138
130
  logger(`getSeqID: Refreshing ${urlToUse} (attempt ${attempt + 1}/3)...`, "info");
139
131
 
140
132
  webResponse = await get(urlToUse, ctx.jar, null, ctx.globalOptions, ctx);
141
- if (isSessionEnforcement(webResponse)) {
142
- throw createSessionEnforcementError();
143
- }
144
133
  if (webResponse && webResponse.data) {
145
134
  await saveWebCookies(ctx.jar)(webResponse);
146
135
  htmlContent = typeof webResponse.data === "string" ? webResponse.data : String(webResponse.data || "");
@@ -194,7 +183,6 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
194
183
 
195
184
  logger(`getSeqID: auto re-login failed - ${result && result.message ? result.message : "unknown error"}`, "error");
196
185
  } catch (loginErr) {
197
- if (isSessionEnforcementError(loginErr)) throw loginErr;
198
186
  logger(`getSeqID: auto re-login error - ${loginErr && loginErr.message ? loginErr.message : String(loginErr)}`, "error");
199
187
  }
200
188
 
@@ -206,7 +194,7 @@ module.exports = function createGetSeqID(deps) {
206
194
 
207
195
  return function getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount = 0) {
208
196
  const MAX_RETRIES = 5;
209
- const RETRY_DELAY = 3000; // [Hardened] slower + more attempts before any logout decision
197
+ const RETRY_DELAY = 5000; // [Hardened5] slower retries reduce auth race / checkpoint pressure
210
198
  ctx.t_mqttCalled = false;
211
199
 
212
200
  // Ensure essential tokens are injected into GraphQL Batch Payload
@@ -237,16 +225,6 @@ module.exports = function createGetSeqID(deps) {
237
225
  .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
238
226
  .then(parseAndCheckLogin(ctx, defaultFuncs))
239
227
  .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
-
250
228
  // Safe check for non-array responses (such as Error Objects from FB)
251
229
  if (getType(resData) !== "Array") {
252
230
  logger(`getSeqID: Response is not Array, received: ${getType(resData)}`, "warn");
@@ -289,21 +267,6 @@ module.exports = function createGetSeqID(deps) {
289
267
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
290
268
  })
291
269
  .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
-
307
270
  const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
308
271
  const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
309
272
 
@@ -386,7 +349,7 @@ module.exports = function createGetSeqID(deps) {
386
349
  }
387
350
  } catch (_) {}
388
351
  // Re-attempt getSeqID after long cooldown without marking account inactive
389
- const softDelay = Math.min(5 * 60 * 1000, 60000 * (retryCount + 1));
352
+ const softDelay = Math.min(15 * 60 * 1000, 90000 * (retryCount + 1)); // [Hardened5] longer soft cooldown
390
353
  setTimeout(() => {
391
354
  if (ctx._ending) return;
392
355
  logger("getSeqID: soft recovery timer fired - retrying getSeqID", "warn");
@@ -409,7 +372,7 @@ module.exports = function createGetSeqID(deps) {
409
372
  setTimeout(() => {
410
373
  if (ctx._ending) return;
411
374
  try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
412
- }, 60000);
375
+ }, 120000); // [Hardened5] 2min soft recover for non-auth errors
413
376
  });
414
377
  };
415
378
  };
@@ -374,6 +374,7 @@ class E2EEBridge {
374
374
  async sendMessage(threadId, msg, replyToMessageId) {
375
375
  this.ensureConnected();
376
376
  await this._waitReady();
377
+ await require("../../../utils/sendThrottle").waitTurn(); // human-like pacing
377
378
 
378
379
  const text = typeof msg === "string" ? msg : (msg && msg.body != null ? String(msg.body) : "");
379
380
  const attachment = (msg && typeof msg === "object") ? (msg.attachment || null) : null;