fca-nx 6.7.7 → 6.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -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 =>
@@ -1104,7 +1181,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1104
1181
  _emitter: emitter
1105
1182
  };
1106
1183
  ctxMain.options = globalOptions;
1107
- ctxMain.guardSessionResponse = ctx.guardSessionResponse;
1184
+ ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1108
1185
  ctxMain.performAutoLogin = async () => {
1109
1186
  try {
1110
1187
  // [Fixed by xalman] First check whether the existing cookie session is actually
@@ -1124,7 +1201,6 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1124
1201
  for (let attempt = 0; attempt < 3 && !uid; attempt++) {
1125
1202
  try {
1126
1203
  const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1127
- guardSessionResponse(check);
1128
1204
  const html = check && check.data ? String(check.data) : "";
1129
1205
  stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1130
1206
  const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
@@ -1132,8 +1208,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1132
1208
  uid = uidMatch[1];
1133
1209
  break;
1134
1210
  }
1135
- } catch (checkErr) {
1136
- if (isSessionEnforcementError(checkErr)) throw checkErr;
1211
+ } catch {
1137
1212
  // network hiccup on this attempt - retry below instead of
1138
1213
  // immediately assuming the session is dead
1139
1214
  }
@@ -1143,8 +1218,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1143
1218
  logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1144
1219
  return true;
1145
1220
  }
1146
- } catch (checkErr) {
1147
- if (isSessionEnforcementError(checkErr)) throw checkErr;
1221
+ } catch {
1148
1222
  // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1149
1223
  }
1150
1224
 
@@ -1152,21 +1226,30 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1152
1226
  const p = config.credentials?.password || password;
1153
1227
  const tf = config.credentials?.twofactor || null;
1154
1228
  if (!u || !p) return false;
1229
+ // [Hardened4] Repeated credential logins are a classic trigger for "automated
1230
+ // behaviour"/"multiple sessions" restrictions. At most one per cooldown window
1231
+ // (FCA_NX_RELOGIN_COOLDOWN_MIN, default 30), and never while Facebook is showing
1232
+ // its scraping warning - re-logging in then only makes it worse.
1233
+ const cdMs = (Number(process.env.FCA_NX_RELOGIN_COOLDOWN_MIN) || 30) * 60 * 1000;
1234
+ const sinceLast = Date.now() - (global.__fcaLastCredLogin || 0);
1235
+ if (sinceLast < cdMs) {
1236
+ logger("performAutoLogin: credential login skipped (cooldown " + Math.ceil((cdMs - sinceLast) / 60000) + " min left) to avoid repeated-login restrictions", "warn");
1237
+ return false;
1238
+ }
1239
+ global.__fcaLastCredLogin = Date.now();
1155
1240
  const r = await tokens(u, p, tf);
1156
- guardSessionResponse(r);
1157
1241
  if (!(r && r.status && Array.isArray(r.cookies))) return false;
1158
1242
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
1159
1243
  setJarFromPairs(jar, pairs, ".facebook.com");
1160
- const response = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1161
- guardSessionResponse(response);
1244
+ await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1162
1245
  return true;
1163
- } catch (loginErr) {
1164
- if (isSessionEnforcementError(loginErr)) throw loginErr;
1246
+ } catch {
1165
1247
  return false;
1166
1248
  }
1167
1249
  };
1168
1250
  const api = {
1169
1251
  setOptions: require("./options").setOptions.bind(null, globalOptions),
1252
+ setSendDelay: require("../src/utils/sendThrottle").setSendDelay,
1170
1253
  getCookies: function () {
1171
1254
  return cookieHeaderFromJar(jar);
1172
1255
  },
@@ -1284,19 +1367,25 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1284
1367
  });
1285
1368
  }, 6 * 60 * 60 * 1000);
1286
1369
  // [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);
1370
+ // [Hardened4] randomised 15-25 min (a perfectly fixed interval looks scripted)
1371
+ (function keepaliveLoop() {
1372
+ const t = setTimeout(function () {
1373
+ try {
1374
+ const { get } = require("../src/utils/request");
1375
+ const { saveCookies } = require("../src/utils/client");
1376
+ if (ctxMain && ctxMain.jar && !ctxMain._ending) {
1377
+ get("https://www.facebook.com/", ctxMain.jar, null, ctxMain.globalOptions, ctxMain)
1378
+ .then(saveCookies(ctxMain.jar))
1379
+ .then(function () { logger("session keepalive ok", "debug"); })
1380
+ .catch(function (e) {
1381
+ logger("session keepalive failed: " + (e && e.message ? e.message : e), "warn");
1382
+ });
1383
+ }
1384
+ } catch (_) {}
1385
+ keepaliveLoop();
1386
+ }, (15 + Math.random() * 10) * 60 * 1000);
1387
+ if (t.unref) t.unref();
1388
+ })();
1300
1389
  }
1301
1390
  // ✅ fca-nx core features register
1302
1391
  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.8",
4
+ "description": "Facebook Messenger API for Node.js — anti-logout hardened (soft session recovery, keepalive, safe MQTT)",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "exports": {
@@ -103,4 +103,4 @@
103
103
  "sqlite3"
104
104
  ]
105
105
  }
106
- }
106
+ }
@@ -5,7 +5,6 @@
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;
@@ -185,16 +184,6 @@ module.exports = function createListenMqtt(deps) {
185
184
  return;
186
185
  }
187
186
 
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
187
  if (/Not logged in|Not logged in.|blocked the login|401|403/i.test(msg)) {
199
188
  try {
200
189
  if (mqttClient && mqttClient.connected) {
@@ -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
 
@@ -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
 
@@ -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;
@@ -3,6 +3,7 @@
3
3
  var utils = require("../../utils/utils");
4
4
  var logger = require("../../utils/logger");
5
5
  var { getTextEffectId, getTextEffectIds } = require("../../utils/textEffects");
6
+ var { waitTurn } = require("../../utils/sendThrottle");
6
7
 
7
8
  var ALLOWED = {
8
9
  attachment: true, url: true, sticker: true, emoji: true,
@@ -279,6 +280,7 @@ module.exports = function (defaultFuncs, api, ctx) {
279
280
  else reject(e2eeErr);
280
281
  }
281
282
  } else {
283
+ await waitTurn();
282
284
  try {
283
285
  var omResult = await new Promise((res2, rej2) => {
284
286
  api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, true);
@@ -319,6 +321,7 @@ module.exports = function (defaultFuncs, api, ctx) {
319
321
  return promise;
320
322
  }
321
323
 
324
+ await waitTurn();
322
325
  try {
323
326
  var result = await sendViaMqtt(msg, threadID, replyToMessage);
324
327
  if (callback) callback(null, result);
@@ -79,6 +79,8 @@ function extractPhotoUrl(photo, depth = 0) {
79
79
  "uri",
80
80
  "url",
81
81
  "image",
82
+ "full_image",
83
+ "viewer_image",
82
84
  "photo",
83
85
  "media",
84
86
  "cover_photo",
@@ -164,9 +166,13 @@ function normalizeUser(user) {
164
166
  firstName: meta.shortName || null,
165
167
  vanity,
166
168
  thumbSrc: extractProfilePicture(user),
167
- coverPhoto: extractPhotoUrl(
168
- user.cover_photo || user.coverPhoto || user.profile_cover_photo
169
- ),
169
+ coverPhoto:
170
+ extractPhotoUrl(user.cover_photo) ||
171
+ extractPhotoUrl(user.coverPhoto) ||
172
+ extractPhotoUrl(user.profile_cover_photo) ||
173
+ extractPhotoUrl(user.cover_photo_renderer) ||
174
+ extractCoverPhoto(user) ||
175
+ null,
170
176
  profileUrl: user.profile_url || user.url || null,
171
177
  gender: meta.gender || null,
172
178
  type: user.__typename || "User",
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /**
3
+ * Single-instance lock per account. Two processes logged into the same account at the same time
4
+ * (overlapping Railway deploys, a forgotten second start) produce Facebook's
5
+ * "You can't create multiple sessions" restriction. The lock file lives in FCA_NX_STATE_DIR and is
6
+ * refreshed every 30s; a lock not refreshed for 120s (crashed process) is considered stale.
7
+ * FCA_NX_INSTANCE_LOCK=off disables it.
8
+ */
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const STALE_MS = 120000;
12
+ let timer = null;
13
+
14
+ function acquire(userID) {
15
+ if (/^(off|0|false)$/i.test(String(process.env.FCA_NX_INSTANCE_LOCK || ""))) return { ok: true };
16
+ const dir = process.env.FCA_NX_STATE_DIR || path.join(process.cwd(), ".fca-nx");
17
+ const file = path.join(dir, "instance_" + String(userID || "default") + ".lock");
18
+ try {
19
+ fs.mkdirSync(dir, { recursive: true });
20
+ try {
21
+ const cur = JSON.parse(fs.readFileSync(file, "utf8"));
22
+ if (cur && cur.pid !== process.pid && Date.now() - cur.at < STALE_MS) {
23
+ let alive = true;
24
+ try { process.kill(cur.pid, 0); } catch (e) { alive = e.code === "EPERM"; }
25
+ // pid namespaces differ between containers, so trust a fresh heartbeat over kill(0)
26
+ if (alive || Date.now() - cur.at < 45000) return { ok: false, pid: cur.pid };
27
+ }
28
+ } catch (_) {}
29
+ const beat = () => { try { fs.writeFileSync(file, JSON.stringify({ pid: process.pid, at: Date.now() })); } catch (_) {} };
30
+ beat();
31
+ if (timer) clearInterval(timer);
32
+ timer = setInterval(beat, 30000);
33
+ if (timer.unref) timer.unref();
34
+ const release = () => { try { const c = JSON.parse(fs.readFileSync(file, "utf8")); if (c.pid === process.pid) fs.unlinkSync(file); } catch (_) {} };
35
+ process.once("exit", release);
36
+ for (const sig of ["SIGINT", "SIGTERM"]) process.once(sig, () => { release(); process.exit(0); });
37
+ } catch (_) { /* never block login because of the lock itself */ }
38
+ return { ok: true };
39
+ }
40
+
41
+ module.exports = { acquire };
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Login-location consistency guard.
5
+ *
6
+ * Facebook flags accounts that are logged in from many different IPs/locations. Before a
7
+ * cookie login we look up the public IP this process uses (through the same proxy/agent the
8
+ * bot uses for Facebook), compare it with the IP of the previous login (stored on disk) and:
9
+ * - warn loudly when it changed (default), or
10
+ * - refuse to log in when FCA_NX_IP_GUARD=block (use with a static proxy / fixed-IP host).
11
+ *
12
+ * FCA_NX_IP_GUARD=off disables it. FCA_NX_STATE_DIR (default ./.fca-nx) holds the state file;
13
+ * on Railway point it at a Volume so it survives deploys.
14
+ */
15
+
16
+ const fs = require("fs");
17
+ const path = require("path");
18
+ const logger = require("../../func/logger");
19
+
20
+ const ENDPOINTS = [
21
+ "https://api.ipify.org?format=json",
22
+ "https://ipinfo.io/json"
23
+ ];
24
+
25
+ function stateFile() {
26
+ const dir = process.env.FCA_NX_STATE_DIR || path.join(process.cwd(), ".fca-nx");
27
+ return { dir, file: path.join(dir, "last_login_ip.json") };
28
+ }
29
+
30
+ async function lookupIP(client) {
31
+ for (const url of ENDPOINTS) {
32
+ try {
33
+ const res = await client.get(url, { timeout: 5000, headers: { Accept: "application/json" } });
34
+ const ip = res && res.data && (res.data.ip || res.data.query);
35
+ if (typeof ip === "string" && ip) return { ip, country: res.data.country || null, region: res.data.region || null };
36
+ } catch (_) { /* try next */ }
37
+ }
38
+ return null;
39
+ }
40
+
41
+ /** @returns {Promise<{ok:boolean, changed:boolean, ip:string|null, previous:string|null}>} */
42
+ async function checkLoginIP(client, userID) {
43
+ const mode = String(process.env.FCA_NX_IP_GUARD || "warn").toLowerCase();
44
+ if (mode === "off" || mode === "0" || mode === "false") return { ok: true, changed: false, ip: null, previous: null };
45
+ const now = await lookupIP(client);
46
+ if (!now) {
47
+ logger("ipGuard: could not determine public IP (continuing)", "warn");
48
+ return { ok: true, changed: false, ip: null, previous: null };
49
+ }
50
+ const { dir, file } = stateFile();
51
+ let all = {};
52
+ try { all = JSON.parse(fs.readFileSync(file, "utf8")) || {}; } catch (_) {}
53
+ const key = String(userID || "default");
54
+ const prev = all[key] && all[key].ip ? all[key] : null;
55
+ const changed = !!prev && prev.ip !== now.ip;
56
+ if (changed) {
57
+ const msg = `ipGuard: login IP changed ${prev.ip} -> ${now.ip}. Logging into the same account from different IPs/locations is a top cause of "automated behaviour", checkpoints and suspensions. Use ONE host with a fixed IP (or a static proxy via the 'proxy' option).`;
58
+ if (mode === "block") {
59
+ logger(msg + " Login refused (FCA_NX_IP_GUARD=block). Set FCA_NX_IP_GUARD=warn to override.", "error");
60
+ return { ok: false, changed: true, ip: now.ip, previous: prev.ip };
61
+ }
62
+ logger(msg, "warn");
63
+ }
64
+ try {
65
+ fs.mkdirSync(dir, { recursive: true });
66
+ all[key] = { ip: now.ip, country: now.country, region: now.region, at: new Date().toISOString() };
67
+ fs.writeFileSync(file, JSON.stringify(all, null, 2));
68
+ } catch (_) {}
69
+ return { ok: true, changed, ip: now.ip, previous: prev ? prev.ip : null };
70
+ }
71
+
72
+ module.exports = { checkLoginIP, lookupIP };
@@ -1,11 +1,6 @@
1
1
  "use strict";
2
2
 
3
3
  const logger = require("../../../func/logger");
4
- const {
5
- isSessionEnforcement,
6
- createSessionEnforcementError,
7
- isSessionEnforcementError
8
- } = require("../sessionStatus");
9
4
 
10
5
  /**
11
6
  * Tạo hàm maybeAutoLogin: khi session hết hạn thì thử đăng nhập lại và retry request.
@@ -19,23 +14,6 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
19
14
  const { buildUrl, headerOf, formatCookie } = helpers;
20
15
 
21
16
  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
-
39
17
  const retryAfterLogin = async function () {
40
18
  if (!resConfig) {
41
19
  const e = new Error(
@@ -64,10 +42,6 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
64
42
  }
65
43
  return await parseAndCheckLogin(ctx, http)(newData);
66
44
  } catch (retryErr) {
67
- if (isSessionEnforcementError(retryErr)) {
68
- ctx._sessionEnforcement = true;
69
- throw retryErr;
70
- }
71
45
  if (
72
46
  retryErr?.code === "ERR_INVALID_CHAR" ||
73
47
  (retryErr?.message && retryErr.message.includes("Invalid character in header"))
@@ -105,10 +79,6 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
105
79
  try {
106
80
  ok = await ctx._autoLoginPromise;
107
81
  } catch (autoLoginErr) {
108
- if (isSessionEnforcementError(autoLoginErr)) {
109
- ctx._sessionEnforcement = true;
110
- throw autoLoginErr;
111
- }
112
82
  const e = new Error("Not logged in. Auto login failed.");
113
83
  e.error = "Not logged in.";
114
84
  e.res = resData;
@@ -152,14 +122,6 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
152
122
  throw e;
153
123
  }
154
124
  } 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
- }
163
125
  if (autoLoginErr.error === "Not logged in.") {
164
126
  throw autoLoginErr;
165
127
  }
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Outgoing-message pacing.
5
+ *
6
+ * Every outgoing message (MQTT, OldMessage and E2EE) is serialised through one queue and is
7
+ * released no sooner than `delay` ms after the previous one. This avoids sending bursts that
8
+ * look like a script and that Facebook's rate limiting reacts to.
9
+ *
10
+ * FCA_NX_SEND_DELAY_MS base gap between sends, default 1000 (set 0 to disable)
11
+ * FCA_NX_SEND_JITTER_MS extra random 0..N ms added to each gap, default 400
12
+ * or at runtime: api.setSendDelay(ms, jitterMs)
13
+ */
14
+
15
+ const state = { last: 0, chain: Promise.resolve(), delay: null, jitter: null, stamps: [] };
16
+ // Hard ceiling per rolling minute (FCA_NX_SEND_MAX_PER_MIN, default 20, 0 = off).
17
+ function maxPerMin() {
18
+ const n = Number(process.env.FCA_NX_SEND_MAX_PER_MIN);
19
+ return Number.isFinite(n) && n >= 0 ? n : 20;
20
+ }
21
+
22
+ function readNum(v, d) {
23
+ const n = Number(v);
24
+ return Number.isFinite(n) && n >= 0 ? n : d;
25
+ }
26
+
27
+ function getDelay() {
28
+ return state.delay != null ? state.delay : readNum(process.env.FCA_NX_SEND_DELAY_MS, 1000);
29
+ }
30
+ function getJitter() {
31
+ return state.jitter != null ? state.jitter : readNum(process.env.FCA_NX_SEND_JITTER_MS, 400);
32
+ }
33
+
34
+ function setSendDelay(ms, jitterMs) {
35
+ if (ms != null) state.delay = readNum(ms, 1000);
36
+ if (jitterMs != null) state.jitter = readNum(jitterMs, 400);
37
+ return { delay: getDelay(), jitter: getJitter() };
38
+ }
39
+
40
+ /** Resolves when it is this caller's turn to send. */
41
+ function waitTurn() {
42
+ const delay = getDelay();
43
+ if (delay <= 0) return Promise.resolve();
44
+ const turn = state.chain.then(async () => {
45
+ const gap = delay + Math.floor(Math.random() * (getJitter() + 1));
46
+ const wait = state.last + gap - Date.now();
47
+ if (wait > 0) await new Promise(r => setTimeout(r, wait));
48
+ const cap = maxPerMin();
49
+ if (cap > 0) {
50
+ for (;;) {
51
+ const now = Date.now();
52
+ state.stamps = state.stamps.filter(t => now - t < 60000);
53
+ if (state.stamps.length < cap) break;
54
+ await new Promise(r => setTimeout(r, state.stamps[0] + 60000 - now + 50));
55
+ }
56
+ state.stamps.push(Date.now());
57
+ }
58
+ state.last = Date.now();
59
+ });
60
+ state.chain = turn.catch(() => {});
61
+ return turn;
62
+ }
63
+
64
+ module.exports = { waitTurn, setSendDelay };
@@ -1,72 +0,0 @@
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
- };