fca-nx 6.7.0 → 6.7.1

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.
@@ -1179,11 +1179,28 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1179
1179
  // the bot (via emitAuth) and force a brand new cookie every
1180
1180
  // time instead of just continuing on the still-good session.
1181
1181
  try {
1182
- const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1183
- const html = check && check.data ? String(check.data) : "";
1184
- const stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1185
- const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
1186
- if (!stillCheckpointed && uidMatch && uidMatch[1] && uidMatch[1] !== "0") {
1182
+ // [Fixed by xalman] retry up to 3x - a transient network
1183
+ // hiccup during THIS check alone used to be treated the same
1184
+ // as a dead session and fall through to requiring credentials.
1185
+ let stillCheckpointed = true;
1186
+ let uid = null;
1187
+ for (let attempt = 0; attempt < 3 && !uid; attempt++) {
1188
+ try {
1189
+ const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1190
+ const html = check && check.data ? String(check.data) : "";
1191
+ stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1192
+ const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
1193
+ if (!stillCheckpointed && uidMatch && uidMatch[1] && uidMatch[1] !== "0") {
1194
+ uid = uidMatch[1];
1195
+ break;
1196
+ }
1197
+ } catch {
1198
+ // network hiccup on this attempt - retry below instead of
1199
+ // immediately assuming the session is dead
1200
+ }
1201
+ if (!uid && attempt < 2) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
1202
+ }
1203
+ if (uid) {
1187
1204
  logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1188
1205
  return true;
1189
1206
  }
@@ -1345,13 +1362,27 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1345
1362
  // messages even after E2EE finished connecting moments later.
1346
1363
  api.listen = api.listenE2EE;
1347
1364
  api.listenMqtt = api.listenE2EE;
1348
- api.connectE2EE()
1349
- .then(() => {
1365
+
1366
+ // [Fixed by xalman] Retry E2EE auto-connect with backoff instead of
1367
+ // giving up forever after one failed attempt - a transient network
1368
+ // blip or momentary FB rate-limit on device registration used to
1369
+ // leave the bot stuck in group-only mode until a full restart.
1370
+ const connectE2EEWithRetry = async (attempt = 0) => {
1371
+ try {
1372
+ await api.connectE2EE();
1350
1373
  logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
1351
- })
1352
- .catch((e) => {
1353
- logger(`E2EE auto-connect failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1354
- });
1374
+ } catch (e) {
1375
+ const msg = e && e.message ? e.message : String(e);
1376
+ if (attempt < 3) {
1377
+ const delayMs = 5000 * Math.pow(3, attempt); // 5s, 15s, 45s
1378
+ logger(`E2EE auto-connect failed (attempt ${attempt + 1}/4): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
1379
+ setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
1380
+ } else {
1381
+ logger(`E2EE auto-connect failed after 4 attempts (non-fatal, continuing without E2EE): ${msg}`, "warn");
1382
+ }
1383
+ }
1384
+ };
1385
+ connectE2EEWithRetry();
1355
1386
  } catch (e) {
1356
1387
  logger(`E2EE init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1357
1388
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.0",
3
+ "version": "6.7.1",
4
4
  "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -61,6 +61,9 @@ function respFinalUrl(res) {
61
61
  }
62
62
 
63
63
  function detectCheckpoint(res) {
64
+ // [Fixed by xalman] res.body -> res.data (axios response shape), same
65
+ // root cause as the parseAndCheckLogin fix in src/utils/utils.js - this
66
+ // was silently always reading undefined and never detecting checkpoints.
64
67
  const url = String(respFinalUrl(res) || "");
65
68
  const body = typeof res?.data === "string" ? res.data : "";
66
69
  const hit =
@@ -9,6 +9,7 @@ const { getSessionIdentity } = require("../../../utils/clientIdentity");
9
9
  const DEFAULT_RECONNECT_DELAY_MS = 2000;
10
10
  const MAX_RECONNECT_DELAY_MS = 60000;
11
11
  const MAX_RECONNECT_ATTEMPTS = 10; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
12
+ const MAX_RECONNECT_COOLDOWN_MS = 10 * 60 * 1000; // after exhausting fast retries, wait this long before trying again (never give up permanently)
12
13
  const T_MS_WAIT_TIMEOUT_MS = 5000;
13
14
 
14
15
  // Exponential backoff with jitter, based on how many *consecutive* reconnect
@@ -44,8 +45,20 @@ module.exports = function createListenMqtt(deps) {
44
45
  }
45
46
  ctx._reconnectAttempts = (ctx._reconnectAttempts || 0) + 1;
46
47
  if (ctx._reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
47
- logger(`mqtt reconnect attempts exceeded (${MAX_RECONNECT_ATTEMPTS}); giving up and surfacing error`, "error");
48
- globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded" }, null);
48
+ // [Fixed by xalman] Don't give up forever - a run of consecutive failures is usually a
49
+ // temporary outage (hosting network blip, FB-side hiccup), not a
50
+ // dead account. Back off to a long, FB-friendly cooldown and reset
51
+ // the counter so normal exponential backoff resumes after that.
52
+ const cooldownMs = MAX_RECONNECT_COOLDOWN_MS;
53
+ logger(`mqtt reconnect attempts exceeded (${MAX_RECONNECT_ATTEMPTS}); backing off ${Math.round(cooldownMs / 60000)}min before trying again (not giving up)`, "error");
54
+ globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded - will retry after cooldown" }, null);
55
+ ctx._reconnectAttempts = 0;
56
+ ctx._reconnectTimer = setTimeout(() => {
57
+ ctx._reconnectTimer = null;
58
+ if (!ctx._ending) {
59
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
60
+ }
61
+ }, cooldownMs);
49
62
  return;
50
63
  }
51
64
  const ms = typeof delayMs === "number" ? delayMs : computeBackoff(ctx, base);
@@ -285,7 +285,12 @@ module.exports = function createGetSeqID(deps) {
285
285
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
286
286
  }
287
287
  logger(`getSeqID: network error persisted after ${MAX_RETRIES} retries, giving up for now: ${msg}`, "error");
288
- return;
288
+ // [Fixed by xalman] throw instead of silently returning undefined -
289
+ // a bare return here made the caller think this call SUCCEEDED.
290
+ const giveUpErr = new Error(`getSeqID network error persisted after ${MAX_RETRIES} retries: ${msg}`);
291
+ giveUpErr.error = msg;
292
+ giveUpErr.isNetworkError = true;
293
+ throw giveUpErr;
289
294
  }
290
295
 
291
296
  if (isAuthError) {
@@ -103,6 +103,11 @@ class E2EEBridge {
103
103
  fb_dtsg: _ctx.fb_dtsg,
104
104
  getCurrentUserID: () => _fcanxApi.getCurrentUserID(),
105
105
  getAppState: () => _fcanxApi.getAppState(),
106
+ // [Fixed by xalman] httpPost always returns a string now - axios
107
+ // auto-parses JSON responses into objects, but the vendored engine
108
+ // (fetchCAT/icdc_fetch/icdc_register) expects raw text and calls
109
+ // .replace()/JSON.parse() on it itself. This was crashing E2EE
110
+ // auto-connect with "resText.replace is not a function".
106
111
  httpPost: async function (url, form) {
107
112
  var merged = Object.assign({}, form);
108
113
  if (!merged.fb_dtsg && _ctx.fb_dtsg) merged.fb_dtsg = _ctx.fb_dtsg;
@@ -113,7 +118,19 @@ class E2EEBridge {
113
118
  require("request")({ method: "POST", url: url, jar: _ctx.jar, form: merged, gzip: true },
114
119
  function (err, r) { if (err) return reject(err); resolve(r); });
115
120
  });
116
- return res && (res.data !== undefined ? res.data : res.body);
121
+ const body = res && (res.data !== undefined ? res.data : res.body);
122
+ if (body == null) return body;
123
+ if (typeof body === "string") return body;
124
+ if (Buffer.isBuffer(body)) return body.toString("utf8");
125
+ // axios auto-parses JSON bodies into an object/array, but the
126
+ // vendored engine always expects a raw string (it strips
127
+ // Facebook's "for (;;);" prefix and JSON.parses it itself).
128
+ // Re-serialize so callers doing resText.replace(...) still work.
129
+ try {
130
+ return JSON.stringify(body);
131
+ } catch {
132
+ return String(body);
133
+ }
117
134
  },
118
135
  // listenMqtt — fb-e2ee.cjs calls this to route non-E2EE MQTT events.
119
136
  // FCA-NX has its own separate MQTT listener so we provide a no-op stub
@@ -24,6 +24,7 @@ const CYCLE_MS_DEFAULT = 60 * 60 * 1000;
24
24
  const RECONNECT_DELAY_MS_DEFAULT = 3000;
25
25
  const UNSUB_ALL_TIMEOUT_MS = 5000;
26
26
  const MAX_MQTT_RECONNECT_DELAY_MS = 60000;
27
+ const MAX_MQTT_RECONNECT_COOLDOWN_MS = 10 * 60 * 1000; // long cooldown after exhausting fast retries - never give up permanently
27
28
  const MAX_MQTT_RECONNECT_ATTEMPTS = 10;
28
29
  const HEARTBEAT_INTERVAL_MS = 30000;
29
30
  const HEARTBEAT_TIMEOUT_MS = 10000;
@@ -154,8 +155,16 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
154
155
  const maxAttempts = conf.maxReconnectAttempts || MAX_MQTT_RECONNECT_ATTEMPTS;
155
156
 
156
157
  if (reconnectAttempts > maxAttempts) {
157
- logger("mqtt getSeqID: max reconnect attempts exceeded", "error");
158
- globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded" }, null);
158
+ const cooldownMs = MAX_MQTT_RECONNECT_COOLDOWN_MS;
159
+ logger(`mqtt getSeqID: max reconnect attempts exceeded, backing off ${Math.round(cooldownMs / 60000)}min before trying again (not giving up)`, "error");
160
+ globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded - will retry after cooldown" }, null);
161
+ reconnectAttempts = 0;
162
+ ctx._reconnectTimer = setTimeout(() => {
163
+ if (!ctx._ending) {
164
+ isReconnecting = false;
165
+ getSeqIDWrapper();
166
+ }
167
+ }, cooldownMs);
159
168
  return;
160
169
  }
161
170
 
@@ -103,7 +103,20 @@ function parseAndCheckLogin(ctx, http, retryCount = 0) {
103
103
  }
104
104
  }
105
105
 
106
- if (status === 404) return;
106
+ if (status === 404) {
107
+ const url = buildUrl(res?.config);
108
+ const method = String(res?.config?.method || "GET").toUpperCase();
109
+ const err = new Error(
110
+ `parseAndCheckLogin got status code: 404. [${method}] ${url || "(no url)"} was not found - the endpoint may have changed or been removed by Facebook.`
111
+ );
112
+ err.statusCode = 404;
113
+ err.res = res?.data;
114
+ logger(
115
+ `parseAndCheckLogin: [${method}] ${url || "(no url)"} -> 404 Not Found`,
116
+ "error"
117
+ );
118
+ throw err;
119
+ }
107
120
  if (status !== 200) {
108
121
  const err = new Error(
109
122
  "parseAndCheckLogin got status code: " +
@@ -245,7 +245,7 @@ function decodeClientPayload(payload) {
245
245
 
246
246
  function parseAndCheckLogin(ctx, defaultFuncs) {
247
247
  return function (res) {
248
- // NOTE: this used to read res.statusCode/res.body, which are the old
248
+ // [Fixed by xalman] this used to read res.statusCode/res.body, which are the old
249
249
  // `request`/`request-promise` library's property names. The actual
250
250
  // HTTP client here (src/utils/request) is axios-based, whose
251
251
  // responses use res.status/res.data instead - res.body was always