fca-nx 6.7.6 → 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.
@@ -785,6 +785,20 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
785
785
  let userIDFromAppState = extractUIDFromAppState(appState);
786
786
  (async () => {
787
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 */ }
788
802
  if (appState) {
789
803
  // Check and convert cookie to appState format
790
804
  if (Array.isArray(appState) && appState.some(c => c.name)) {
@@ -1212,6 +1226,17 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1212
1226
  const p = config.credentials?.password || password;
1213
1227
  const tf = config.credentials?.twofactor || null;
1214
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();
1215
1240
  const r = await tokens(u, p, tf);
1216
1241
  if (!(r && r.status && Array.isArray(r.cookies))) return false;
1217
1242
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
@@ -1224,6 +1249,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1224
1249
  };
1225
1250
  const api = {
1226
1251
  setOptions: require("./options").setOptions.bind(null, globalOptions),
1252
+ setSendDelay: require("../src/utils/sendThrottle").setSendDelay,
1227
1253
  getCookies: function () {
1228
1254
  return cookieHeaderFromJar(jar);
1229
1255
  },
@@ -1341,19 +1367,25 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1341
1367
  });
1342
1368
  }, 6 * 60 * 60 * 1000);
1343
1369
  // [Hardened] light session keepalive every 20 min - hits facebook.com so cookies stay warm
1344
- setInterval(function () {
1345
- try {
1346
- const { get } = require("../src/utils/request");
1347
- const { saveCookies } = require("../src/utils/client");
1348
- if (!ctxMain || !ctxMain.jar || ctxMain._ending) return;
1349
- get("https://www.facebook.com/", ctxMain.jar, null, ctxMain.globalOptions, ctxMain)
1350
- .then(saveCookies(ctxMain.jar))
1351
- .then(function () { logger("session keepalive ok", "debug"); })
1352
- .catch(function (e) {
1353
- logger("session keepalive failed: " + (e && e.message ? e.message : e), "warn");
1354
- });
1355
- } catch (_) {}
1356
- }, 20 * 60 * 1000);
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
+ })();
1357
1389
  }
1358
1390
  // ✅ fca-nx core features register
1359
1391
  try {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.6",
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
+ }
@@ -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 };
@@ -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 };