fca-nx 6.8.6 → 7.0.0

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.
@@ -6,40 +6,20 @@
6
6
  const { formatID } = require("../../../utils/format");
7
7
  const { getSessionIdentity } = require("../../../utils/clientIdentity");
8
8
 
9
- const DEFAULT_RECONNECT_DELAY_MS = 15000;
10
- const MAX_RECONNECT_DELAY_MS = 120000;
11
- const MAX_RECONNECT_ATTEMPTS = 6
12
- const MAX_RECONNECT_COOLDOWN_MS = 45 * 60 * 1000;
13
- const T_MS_WAIT_TIMEOUT_MS = 20000;
9
+ const DEFAULT_RECONNECT_DELAY_MS = 2000;
10
+ const MAX_RECONNECT_DELAY_MS = 60000;
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)
13
+ const T_MS_WAIT_TIMEOUT_MS = 5000;
14
14
 
15
15
  // Exponential backoff with jitter, based on how many *consecutive* reconnect
16
16
  // attempts have happened for this session (reset to 0 on a successful
17
17
  // "connect" event). This replaces the old fixed 2s-every-time behavior,
18
18
  // which could hammer the endpoint in a tight loop during real outages.
19
- //
20
- // [Fixed by xalman] IMMEDIATE RECONNECT: the first reconnect after a disconnect now happens at
21
- // once (0ms) instead of waiting for a scheduled 4-6s delay. Only if that attempt also fails does
22
- // the backoff start (1s, 2s, 4s ... capped at 60s) so a real outage still can't hammer Facebook.
23
- // Default is scheduled reconnect (safer). Set FCA_NX_MQTT_IMMEDIATE_RECONNECT=1
24
- // (or mqtt option immediateReconnect:true) only if you need the old instant behaviour.
25
- function isImmediateReconnect(ctx) {
26
- // [Hardened] opt-in only: instant reconnects can create overlapping sessions / checkpoint risk
27
- // Enable with FCA_NX_MQTT_IMMEDIATE_RECONNECT=1 or mqtt option immediateReconnect:true
28
- if (process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1") return true;
29
- if (ctx && ctx._mqttOpt && ctx._mqttOpt.immediateReconnect === true) return true;
30
- return false;
31
- }
32
-
33
19
  function computeBackoff(ctx, baseMs) {
34
20
  const attempt = (ctx._reconnectAttempts || 0);
35
- if (isImmediateReconnect(ctx)) {
36
- if (attempt <= 1) return 0; // first reconnect: right now
37
- const fast = Math.min(1000 * Math.pow(2, attempt - 2), MAX_RECONNECT_DELAY_MS);
38
- const j = Math.floor(Math.random() * Math.min(500, fast * 0.2));
39
- return Math.min(fast + j, MAX_RECONNECT_DELAY_MS);
40
- }
41
21
  const exp = Math.min(baseMs * Math.pow(2, attempt), MAX_RECONNECT_DELAY_MS);
42
- const jitter = Math.floor(Math.random() * Math.min(4000, exp * 0.4)); // [Hardened5]
22
+ const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
43
23
  return Math.min(exp + jitter, MAX_RECONNECT_DELAY_MS);
44
24
  }
45
25
 
@@ -51,7 +31,6 @@ module.exports = function createListenMqtt(deps) {
51
31
  return function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
52
32
 
53
33
  function scheduleReconnect(delayMs) {
54
- ctx._mqttConnecting = false;
55
34
  const base = (ctx._mqttOpt && ctx._mqttOpt.reconnectDelayMs) || DEFAULT_RECONNECT_DELAY_MS;
56
35
  if (ctx._reconnectTimer) {
57
36
  logger("mqtt reconnect already scheduled", "warn");
@@ -83,7 +62,7 @@ module.exports = function createListenMqtt(deps) {
83
62
  return;
84
63
  }
85
64
  const ms = typeof delayMs === "number" ? delayMs : computeBackoff(ctx, base);
86
- logger(`mqtt ${ms === 0 ? "reconnecting immediately" : "will reconnect in " + ms + "ms"} (attempt ${ctx._reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`, "warn");
65
+ logger(`mqtt will reconnect in ${ms}ms (attempt ${ctx._reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`, "warn");
87
66
  ctx._reconnectTimer = setTimeout(() => {
88
67
  ctx._reconnectTimer = null;
89
68
  if (!ctx._ending) {
@@ -95,16 +74,6 @@ module.exports = function createListenMqtt(deps) {
95
74
  return /No subscription existed|client disconnecting|socket hang up|ECONNRESET/i.test(msg || "");
96
75
  }
97
76
 
98
- if (ctx.mqttClient && ctx.mqttClient.connected && !ctx._ending) {
99
- logger("mqtt connect skipped - already connected", "warn");
100
- return;
101
- }
102
- if (ctx._mqttConnecting) {
103
- logger("mqtt connect skipped - already connecting", "warn");
104
- return;
105
- }
106
- ctx._mqttConnecting = true;
107
-
108
77
  // Ensure only one MQTT connection exists for this session, and that any
109
78
  // previous connection is fully closed (listeners removed, socket ended)
110
79
  // before a new one is opened. Without this, a reconnect racing with a
@@ -114,7 +83,7 @@ module.exports = function createListenMqtt(deps) {
114
83
  if (ctx.mqttClient) {
115
84
  try {
116
85
  ctx.mqttClient.removeAllListeners();
117
- ctx.mqttClient.end(true);
86
+ if (ctx.mqttClient.connected) ctx.mqttClient.end(true);
118
87
  } catch (_) { }
119
88
  ctx.mqttClient = undefined;
120
89
  }
@@ -123,19 +92,8 @@ module.exports = function createListenMqtt(deps) {
123
92
  // never disagree about User-Agent / Accept-Language mid-session.
124
93
  const identity = getSessionIdentity(ctx);
125
94
 
126
- // [Hardened5] stable device id for the whole process lifetime
127
- if (!ctx.clientId || ctx.clientId === "") {
128
- ctx.clientId = ctx.clientID || ((""+Math.random()).slice(2) + Date.now()).slice(0, 16);
129
- }
130
- // Online while this session is actually connected. Offline only if the
131
- // caller set online:false. A running Messenger tab is online.
132
- const chatOn = ctx.globalOptions.online !== false;
133
- // Same browser tab for the life of the process. A new sid on every
134
- // reconnect looks like a new login and is a common suspend trigger.
135
- if (!ctx._edgeSid) {
136
- ctx._edgeSid = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
137
- }
138
- const sessionID = ctx._edgeSid;
95
+ const chatOn = ctx.globalOptions.online;
96
+ const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
139
97
  const username = {
140
98
  u: ctx.userID, s: sessionID, chat_on: chatOn, fg: false, d: ctx.clientId,
141
99
  ct: "websocket", aid: 219994525426954, aids: null, mqtt_sid: "",
@@ -178,10 +136,10 @@ module.exports = function createListenMqtt(deps) {
178
136
  protocolVersion: 13,
179
137
  binaryType: "arraybuffer"
180
138
  },
181
- keepalive: 60,
139
+ keepalive: 30,
182
140
  reschedulePings: true,
183
141
  reconnectPeriod: 0,
184
- connectTimeout: 20000
142
+ connectTimeout: 5000
185
143
  };
186
144
  if (ctx.globalOptions.proxy !== undefined) {
187
145
  const agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
@@ -195,7 +153,6 @@ module.exports = function createListenMqtt(deps) {
195
153
  const mqttClient = ctx.mqttClient;
196
154
 
197
155
  mqttClient.on("error", function (err) {
198
- ctx._mqttConnecting = false;
199
156
  const msg = String(err && err.message ? err.message : err || "");
200
157
  if ((ctx._ending || ctx._cycling) && /No subscription existed|client disconnecting/i.test(msg)) {
201
158
  logger(`mqtt expected during shutdown: ${msg}`, "info");
@@ -213,16 +170,18 @@ module.exports = function createListenMqtt(deps) {
213
170
  mqttClient.end(true);
214
171
  }
215
172
  } catch (_) { }
216
- // [Hardened] Only permanent-logout on explicit "blocked the login"
217
- if (/blocked the login/i.test(msg)) {
173
+ if (/blocked/i.test(msg)) {
218
174
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
219
175
  }
220
176
 
221
- // Plain 401/403/"Not logged in" is often a cookie race. Do not hit
222
- // facebook.com (that is a fresh login). Wait, then open one socket.
223
- logger(`mqtt transient auth error; one delayed reconnect (no homepage login): ${msg}`, "warn");
224
- if (!ctx._ending && ctx.globalOptions && ctx.globalOptions.autoReconnect !== false) {
225
- scheduleReconnect(30000);
177
+ // Auth responses can race with the shared cookie refresh triggered by
178
+ // another request. Treat a plain 401/403/"Not logged in" MQTT error as
179
+ // recoverable instead of emitting account_inactive and permanently
180
+ // setting ctx._ending. The close handler/scheduler will establish a
181
+ // fresh MQTT connection with the refreshed session.
182
+ logger(`mqtt transient auth error; reconnecting without logging out: ${msg}`, "warn");
183
+ if (!ctx._ending && ctx.globalOptions.autoReconnect) {
184
+ scheduleReconnect();
226
185
  }
227
186
  return;
228
187
  }
@@ -234,7 +193,7 @@ module.exports = function createListenMqtt(deps) {
234
193
  } catch (_) { }
235
194
  if (ctx._ending || ctx._cycling) return;
236
195
 
237
- if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
196
+ if (ctx.globalOptions.autoReconnect && !ctx._ending) {
238
197
  // Let scheduleReconnect() compute the exponential-backoff delay
239
198
  // itself (instead of always passing the same fixed base delay),
240
199
  // so repeated network failures back off instead of retrying every
@@ -251,10 +210,6 @@ module.exports = function createListenMqtt(deps) {
251
210
  process.env.OnStatus = true;
252
211
  }
253
212
  ctx._cycling = false;
254
- ctx.loggedIn = true;
255
- ctx._sessionRecovering = false;
256
- ctx._mqttConnecting = false;
257
- ctx._tmsMisses = 0;
258
213
  // A successful connect means the session/identity/network are fine -
259
214
  // reset the backoff counter so a later transient failure starts a
260
215
  // fresh backoff sequence instead of inheriting a long delay from an
@@ -271,25 +226,15 @@ module.exports = function createListenMqtt(deps) {
271
226
  const topic = ctx.syncToken ? "/messenger_sync_get_diffs" : "/messenger_sync_create_queue";
272
227
  if (ctx.syncToken) { queue.last_seq_id = ctx.lastSeqId; queue.sync_token = ctx.syncToken; }
273
228
  mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
274
- // [Hardened5] only claim foreground/available when online:true
275
- mqttClient.publish("/foreground_state", JSON.stringify({ foreground: !!chatOn }), { qos: 1 });
276
- if (chatOn) {
277
- mqttClient.publish("/set_client_settings", JSON.stringify({ make_user_available_when_in_foreground: true }), { qos: 1 });
278
- }
229
+ mqttClient.publish("/foreground_state", JSON.stringify({ foreground: chatOn }), { qos: 1 });
230
+ mqttClient.publish("/set_client_settings", JSON.stringify({ make_user_available_when_in_foreground: true }), { qos: 1 });
279
231
  let rTimeout = setTimeout(function () {
280
232
  rTimeout = null;
281
233
  if (ctx._ending) {
282
234
  logger("mqtt t_ms timeout skipped - ending", "warn");
283
235
  return;
284
236
  }
285
- logger("mqtt t_ms timeout", "warn");
286
- ctx._tmsMisses = (ctx._tmsMisses || 0) + 1;
287
- if (ctx._tmsMisses < 2 && mqttClient && mqttClient.connected) {
288
- try {
289
- mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
290
- } catch (_) { }
291
- return;
292
- }
237
+ logger("mqtt t_ms timeout, cycling", "warn");
293
238
  try {
294
239
  if (mqttClient && mqttClient.connected) {
295
240
  mqttClient.end(true);
@@ -374,13 +319,12 @@ module.exports = function createListenMqtt(deps) {
374
319
  });
375
320
 
376
321
  mqttClient.on("close", function () {
377
- ctx._mqttConnecting = false;
378
322
  if (ctx._ending || ctx._cycling) {
379
323
  logger("mqtt close expected", "info");
380
324
  return;
381
325
  }
382
326
  logger("mqtt connection closed", "warn");
383
- if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
327
+ if (ctx.globalOptions.autoReconnect && !ctx._ending) {
384
328
  scheduleReconnect();
385
329
  }
386
330
  });
@@ -391,7 +335,7 @@ module.exports = function createListenMqtt(deps) {
391
335
  return;
392
336
  }
393
337
  logger("mqtt disconnected", "warn");
394
- if (ctx.globalOptions && ctx.globalOptions.autoReconnect !== false && !ctx._ending) {
338
+ if (ctx.globalOptions.autoReconnect && !ctx._ending) {
395
339
  scheduleReconnect();
396
340
  }
397
341
  });
@@ -36,9 +36,6 @@ module.exports = function createEmitAuth({ logger }) {
36
36
 
37
37
  ctx.mqttClient = undefined;
38
38
  ctx.loggedIn = false;
39
- // [Hardened] cookies / jar intentionally preserved so auto-relogin or
40
- // soft recovery can reuse the session without full credential login.
41
- // Only MQTT + timers are torn down.
42
39
 
43
40
  // Clean up timeout references
44
41
  try {
@@ -193,8 +193,8 @@ module.exports = function createGetSeqID(deps) {
193
193
  const { listenMqtt, logger, emitAuth } = deps;
194
194
 
195
195
  return function getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount = 0) {
196
- const MAX_RETRIES = 5;
197
- const RETRY_DELAY = 5000; // [Hardened5] slower retries reduce auth race / checkpoint pressure
196
+ const MAX_RETRIES = 3;
197
+ const RETRY_DELAY = 2000;
198
198
  ctx.t_mqttCalled = false;
199
199
 
200
200
  // Ensure essential tokens are injected into GraphQL Batch Payload
@@ -296,53 +296,43 @@ module.exports = function createGetSeqID(deps) {
296
296
  if (isAuthError) {
297
297
  if (retryCount < MAX_RETRIES) {
298
298
  const delay = RETRY_DELAY * (retryCount + 1);
299
- logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms, same cookie (error: ${msg})`, "warn");
299
+ logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (error: ${msg})`, "warn");
300
300
  await new Promise(resolve => setTimeout(resolve, delay));
301
+
302
+ if (retryCount === 0 && ctx.loggedIn) {
303
+ try {
304
+ logger("getSeqID: refreshing session before retry...", "info");
305
+ const { get } = require("../../../utils/request");
306
+ const { saveCookies } = require("../../../utils/client");
307
+ await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
308
+ } catch (refreshErr) {
309
+ logger(`getSeqID: session refresh failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
310
+ }
311
+ }
312
+
301
313
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
302
314
  }
303
315
 
304
- // A new email/password login here kills the cookie the bot is
305
- // already using and Facebook treats it as a second device.
306
- if (/blocked the login|login_blocked|checkpoint_282|checkpoint_956/i.test(msg)) {
307
- return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
316
+ logger("getSeqID: all retries failed, attempting auto re-login...", "warn");
317
+ const config = getConfig();
318
+ const loginResult = await tryAutoLogin(logger, config, ctx, defaultFuncs);
319
+
320
+ if (loginResult) {
321
+ logger("getSeqID: retrying with new session...", "info");
322
+ await new Promise(resolve => setTimeout(resolve, 3000));
323
+ return getSeqID(defaultFuncs, api, ctx, globalCallback, form, 0);
308
324
  }
309
325
 
310
- logger(`getSeqID: auth still failing - keeping this cookie, no new login: ${msg}`, "error");
311
- // Soft recovery: do NOT set ctx._ending. Notify listener, then retry later.
312
- try {
313
- if (typeof globalCallback === "function") {
314
- globalCallback({
315
- type: "session_recovering",
316
- error: msg,
317
- timestamp: Date.now()
318
- }, null);
319
- }
320
- } catch (_) {}
321
- // Re-attempt getSeqID after long cooldown without marking account inactive
322
- const softDelay = Math.min(15 * 60 * 1000, 90000 * (retryCount + 1)); // [Hardened5] longer soft cooldown
323
- setTimeout(() => {
324
- if (ctx._ending) return;
325
- logger("getSeqID: soft recovery timer fired - retrying getSeqID", "warn");
326
- try {
327
- getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0);
328
- } catch (e) {
329
- logger(`getSeqID soft recovery error: ${e && e.message ? e.message : e}`, "error");
330
- }
331
- }, softDelay);
332
- return;
326
+ if (/blocked/i.test(msg)) {
327
+ return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
328
+ }
329
+ if (/Not logged in/i.test(msg)) {
330
+ return emitAuth(ctx, api, globalCallback, "not_logged_in", msg);
331
+ }
333
332
  }
334
333
 
335
- // Non-auth, non-network: still soft-recover instead of permanent logout
336
- logger(`getSeqID error (soft recover, no logout): ${msg}`, "error");
337
- try {
338
- if (typeof globalCallback === "function") {
339
- globalCallback({ type: "session_recovering", error: msg, timestamp: Date.now() }, null);
340
- }
341
- } catch (_) {}
342
- setTimeout(() => {
343
- if (ctx._ending) return;
344
- try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
345
- }, 120000); // [Hardened5] 2min soft recover for non-auth errors
334
+ logger(`getSeqID error: ${msg}`, "error");
335
+ return emitAuth(ctx, api, globalCallback, "auth_error", msg);
346
336
  });
347
337
  };
348
338
  };