fca-nx 7.3.5 → 7.5.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.
package/README.md CHANGED
@@ -140,18 +140,20 @@ api.sendMessage("Hello world!", threadID);
140
140
  ```
141
141
  ### Message effects removed (7.2.5)
142
142
  Bubble effects (`gift`, `fire`, `love`, `textEffect`, `text_effect_ids`) are no longer sent.
143
- Passing those keys is ignored. Sending them was a non-browser payload and a common checkpoint/suspend trigger.
143
+ Passing those keys is ignored; the client does not currently provide a documented Meta-supported effects API.
144
144
 
145
- ### Session safety (7.3.5)
146
- - 7.2.5 reconnected MQTT every hour and published `/browser_close` first. Facebook treated that as the user leaving, so the saved appstate came back logged out. That publish now happens only on a real `stopListening`, and a recycle no longer clears autosave.
147
- - 7.3.0 never recycled the socket and published a custom `/ping` every 30 seconds. That is not a browser packet (keepalive is MQTT PINGREQ). Leaving it on a socket that never closed was suspending accounts. The custom ping is gone.
148
- - The socket is soft-recycled about every 6 hours, with jitter, so it is neither an hourly logout nor an immortal connection. Set `cycleMs: 0` in the mqtt options to turn that off.
149
- - `getUserInfo` uses the cached GraphQL path again unless `antiGetInfo.AntiGetUserInfo` is `true`. The 7.3.0 default could send every lookup to `/chat/user_info/`, which is a spam signal.
145
+ ### Session and profile-data safety (7.4.0)
146
+ - Explicit checkpoint, account restriction, or manual-verification responses stop automatic login and MQTT reconnect. FCA-NX does not attempt to bypass those notices.
147
+ - Temporary network failures remain separate from account-verification signals and use the existing bounded retry behavior.
148
+ - Removed the randomized periodic MQTT recycle. Reconnects now follow connection errors or an explicit user action; this does not guarantee that Facebook will keep a session active.
149
+ - Outgoing messages keep a fixed spacing and a rolling-minute cap; randomized human-like send timing is not used.
150
+ - `getUserInfoV2` returns `coverPhoto: null` and `coverPhotoStatus: "unavailable"` because this cookie-based client has no authorized Graph API cover-photo source. It no longer extracts covers from private GraphQL payloads or scraped profile HTML.
151
+ - The official Graph API documents a User Cover Photo object with a `source` URL, but access depends on Meta's permissions and an authorized Graph API token: https://developers.facebook.com/docs/graph-api/reference/user-cover-photo/
152
+ - This release does not promise that an account will avoid restrictions or suspension. Stop automation and resolve any notice directly with Facebook.
150
153
 
151
154
  ### Session safety (7.2.5)
152
155
  - Default `online` is `false` (MQTT `chat_on` stays off unless you opt in).
153
156
  - `mark_thread_read` is sent only when `autoMarkRead: true`.
154
- - Outgoing sends are slower by default (about 2.8s + jitter, max 8/min).
155
157
  - MQTT reconnect backs off harder (8s → 120s, then a 20 minute cooldown) instead of hammering the socket.
156
158
 
157
159
  ### Send Attachment
@@ -5,11 +5,17 @@ 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, post, makeDefaults } = require("../src/utils/request");
8
+ const { get, 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
+ isTransientTransportError,
16
+ createSessionEnforcementError,
17
+ isSessionEnforcementError
18
+ } = require("../src/utils/sessionStatus");
13
19
  const { createRemoteClient } = require("../src/remote/remoteClient");
14
20
  const { config } = loadConfig();
15
21
  const axiosBase = require("axios");
@@ -62,6 +68,13 @@ function parseRegion(html) {
62
68
  }
63
69
  }
64
70
 
71
+ function guardSessionResponse(response) {
72
+ if (isSessionEnforcement(response)) {
73
+ throw createSessionEnforcementError();
74
+ }
75
+ return response;
76
+ }
77
+
65
78
  function mask(s, keep = 3) {
66
79
  if (!s) return "";
67
80
  const n = s.length;
@@ -538,6 +551,8 @@ async function hydrateJarFromDB(userID, jar) {
538
551
  }
539
552
 
540
553
  async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions, ctxRef, hadAppStateInput = false, jar) {
554
+ guardSessionResponse(currentHtml);
555
+
541
556
  // Helper to validate UID - must be a non-zero positive number string
542
557
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
543
558
 
@@ -584,19 +599,18 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
584
599
  logger("tryAutoLoginIfNeeded: Trying backup from DB...", "info");
585
600
  try {
586
601
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
587
- const resB = (await ctxRef.bypassAutomation(initial, jar)) || initial;
602
+ const resB = (await ctxRef.guardSessionResponse(initial)) || initial;
588
603
  const htmlB = resB && resB.data ? resB.data : "";
589
- if (!htmlB.includes("/checkpoint/block/?next")) {
590
- const htmlUserID = htmlUID(htmlB);
591
- if (isValidUID(htmlUserID)) {
592
- const cookiesB = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
593
- logger(`tryAutoLoginIfNeeded: DB backup session valid, USER_ID=${htmlUserID}`, "info");
594
- return { html: htmlB, cookies: cookiesB, userID: htmlUserID };
595
- } else {
596
- logger(`tryAutoLoginIfNeeded: DB backup session dead (HTML USER_ID=${htmlUserID || "empty"}), will try API login...`, "warn");
597
- }
604
+ const htmlUserID = htmlUID(htmlB);
605
+ if (isValidUID(htmlUserID)) {
606
+ const cookiesB = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
607
+ logger(`tryAutoLoginIfNeeded: DB backup session valid, USER_ID=${htmlUserID}`, "info");
608
+ return { html: htmlB, cookies: cookiesB, userID: htmlUserID };
609
+ } else {
610
+ logger(`tryAutoLoginIfNeeded: DB backup session dead (HTML USER_ID=${htmlUserID || "empty"}), will try API login...`, "warn");
598
611
  }
599
612
  } catch (dbErr) {
613
+ if (isSessionEnforcementError(dbErr) || isTransientTransportError(dbErr)) throw dbErr;
600
614
  logger(`tryAutoLoginIfNeeded: DB backup failed - ${dbErr && dbErr.message ? dbErr.message : String(dbErr)}`, "warn");
601
615
  }
602
616
  }
@@ -619,7 +633,13 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
619
633
  logger(`tryAutoLoginIfNeeded: Attempting API login for ${u.slice(0, 3)}***...`, "info");
620
634
 
621
635
  const r = await tokens(u, p, tf);
636
+ guardSessionResponse(r);
622
637
  if (!r || !r.status) {
638
+ if (isTransientTransportError(r)) {
639
+ const error = new Error("The login service is temporarily unavailable.");
640
+ error.code = r.code || "ERR_NETWORK";
641
+ throw error;
642
+ }
623
643
  throw new Error(r && r.message ? r.message : "API Login failed");
624
644
  }
625
645
 
@@ -685,7 +705,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
685
705
  logger(`tryAutoLoginIfNeeded: Refreshing ${urlToUse} (attempt ${retryCount + 1}/${maxRetries})...`, "info");
686
706
 
687
707
  const initial2 = await get(urlToUse, jar, null, globalOptions).then(saveCookies(jar));
688
- res2 = (await ctxRef.bypassAutomation(initial2, jar)) || initial2;
708
+ res2 = (await ctxRef.guardSessionResponse(initial2)) || initial2;
689
709
  html2 = res2 && res2.data ? res2.data : "";
690
710
 
691
711
  if (html2.includes("/checkpoint/block/?next")) {
@@ -709,6 +729,8 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
709
729
  break;
710
730
  }
711
731
  } catch (err) {
732
+ if (isSessionEnforcementError(err)) throw err;
733
+ if (isTransientTransportError(err)) throw err;
712
734
  if (err.message && err.message.includes("Checkpoint")) {
713
735
  throw err;
714
736
  }
@@ -759,10 +781,12 @@ function makeLogin(j, email, password, globalOptions) {
759
781
  const tf = config.credentials?.twofactor || null;
760
782
  if (!u || !p) return;
761
783
  const r = await tokens(u, p, tf);
784
+ guardSessionResponse(r);
762
785
  if (r && r.status && Array.isArray(r.cookies)) {
763
786
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
764
787
  setJarFromPairs(j, pairs, ".facebook.com");
765
- await get("https://www.facebook.com/", j, null, globalOptions).then(saveCookies(j));
788
+ const response = await get("https://www.facebook.com/", j, null, globalOptions).then(saveCookies(j));
789
+ guardSessionResponse(response);
766
790
  } else {
767
791
  throw new Error(r && r.message ? r.message : "Login failed");
768
792
  }
@@ -861,70 +885,26 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
861
885
  return callback(e);
862
886
  }
863
887
  const ctx = { globalOptions, options: globalOptions, reconnectAttempts: 0 };
864
- ctx.bypassAutomation = async function (resp, j) {
865
- global.fca = global.fca || {};
866
- global.fca.BypassAutomationNotification = this.bypassAutomation.bind(this);
867
- const s = x => (typeof x === "string" ? x : String(x ?? ""));
868
- const u = r => r?.request?.res?.responseUrl || (r?.config?.baseURL ? new URL(r.config.url || "/", r.config.baseURL).toString() : r?.config?.url || "");
869
- const isCp = r => typeof u(r) === "string" && u(r).includes("checkpoint/601051028565049");
870
- const cookieUID = async () => {
871
- try {
872
- const cookies = typeof j?.getCookies === "function" ? await j.getCookies("https://www.facebook.com") : [];
873
- return cookies.find(c => c.key === "i_user")?.value || cookies.find(c => c.key === "c_user")?.value;
874
- } catch { return undefined; }
875
- };
876
- const htmlUID = body => s(body).match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s(body).match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
877
- const getUID = async body => (await cookieUID()) || htmlUID(body);
878
- const refreshJar = async () => get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
879
- const bypass = async body => {
880
- const b = s(body);
881
- const UID = await getUID(b);
882
- const fb_dtsg = getFrom(b, '"DTSGInitData",[],{"token":"', '",') || b.match(/name="fb_dtsg"\s+value="([^"]+)"/)?.[1];
883
- const jazoest = getFrom(b, 'name="jazoest" value="', '"') || getFrom(b, "jazoest=", '",') || b.match(/name="jazoest"\s+value="([^"]+)"/)?.[1];
884
- const lsd = getFrom(b, '["LSD",[],{"token":"', '"}') || b.match(/name="lsd"\s+value="([^"]+)"/)?.[1];
885
- 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 };
886
- await post("https://www.facebook.com/api/graphql/", j, form, null, this.options).then(saveCookies(j));
887
- logger("⚠️ Facebook automation detected — bypassing...", "warn");
888
- this.reconnectAttempts = 0;
889
- };
890
- try {
891
- if (resp) {
892
- if (isCp(resp)) {
893
- await bypass(s(resp.data));
894
- const refreshed = await refreshJar();
895
- if (isCp(refreshed)) logger("Checkpoint still present after refresh", "warn");
896
- else logger("✅ Bypass complete — session restored.", "info");
897
- return refreshed;
898
- }
899
- return resp;
900
- }
901
- const first = await get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
902
- if (isCp(first)) {
903
- await bypass(s(first.data));
904
- const refreshed = await refreshJar();
905
- if (!isCp(refreshed)) logger("✅ Bypass complete — session restored.", "info");
906
- else logger("Checkpoint still present after refresh", "warn");
907
- return refreshed;
908
- }
909
- return first;
910
- } catch (e) {
911
- logger(`Bypass automation error: ${e && e.message ? e.message : String(e)}`, "error");
912
- return resp;
913
- }
888
+ ctx.guardSessionResponse = async function (response) {
889
+ return guardSessionResponse(response);
914
890
  };
915
891
  if (appState || Cookie) {
916
892
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
917
- return (await ctx.bypassAutomation(initial, jar)) || initial;
893
+ return (await ctx.guardSessionResponse(initial)) || initial;
918
894
  }
919
895
  const hydrated = await hydrateJarFromDB(null, jar);
920
896
  if (hydrated) {
921
897
  logger(chalk.italic("🔄 AppState backup found — restoring session..."), "info");
922
898
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
923
- return (await ctx.bypassAutomation(initial, jar)) || initial;
899
+ return (await ctx.guardSessionResponse(initial)) || initial;
924
900
  }
925
901
  logger(chalk.italic("😐 AppState expired — logging in with credentials..."), "warn");
926
902
  return get("https://www.facebook.com/", null, null, globalOptions)
927
903
  .then(saveCookies(jar))
904
+ .then(function (response) {
905
+ guardSessionResponse(response);
906
+ return response;
907
+ })
928
908
  .then(makeLogin(jar, email, password, globalOptions))
929
909
  .then(function () {
930
910
  return get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
@@ -933,45 +913,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
933
913
  .then(async function (res) {
934
914
  const ctx = {};
935
915
  ctx.options = globalOptions;
936
- ctx.bypassAutomation = async function (resp, j) {
937
- global.fca = global.fca || {};
938
- global.fca.BypassAutomationNotification = this.bypassAutomation.bind(this);
939
- const s = x => (typeof x === "string" ? x : String(x ?? ""));
940
- const u = r => r?.request?.res?.responseUrl || (r?.config?.baseURL ? new URL(r.config.url || "/", r.config.baseURL).toString() : r?.config?.url || "");
941
- const isCp = r => typeof u(r) === "string" && u(r).includes("checkpoint/601051028565049");
942
- const cookieUID = async () => {
943
- try {
944
- const cookies = typeof j?.getCookies === "function" ? await j.getCookies("https://www.facebook.com") : [];
945
- return cookies.find(c => c.key === "i_user")?.value || cookies.find(c => c.key === "c_user")?.value;
946
- } catch { return undefined; }
947
- };
948
- const htmlUID = body => s(body).match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s(body).match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
949
- const getUID = async body => (await cookieUID()) || htmlUID(body);
950
- const refreshJar = async () => get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
951
- const bypass = async body => {
952
- const b = s(body);
953
- const UID = await getUID(b);
954
- const fb_dtsg = getFrom(b, '"DTSGInitData",[],{"token":"', '",') || b.match(/name="fb_dtsg"\s+value="([^"]+)"/)?.[1];
955
- const jazoest = getFrom(b, 'name="jazoest" value="', '"') || getFrom(b, "jazoest=", '",') || b.match(/name="jazoest"\s+value="([^"]+)"/)?.[1];
956
- const lsd = getFrom(b, '["LSD",[],{"token":"', '"}') || b.match(/name="lsd"\s+value="([^"]+)"/)?.[1];
957
- 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 };
958
- await post("https://www.facebook.com/api/graphql/", j, form, null, this.options).then(saveCookies(j));
959
- logger("⚠️ Facebook automation detected — bypassing...", "warn");
960
- };
961
- try {
962
- if (res && isCp(res)) {
963
- await bypass(s(res.data));
964
- const refreshed = await refreshJar();
965
- if (!isCp(refreshed)) logger("✅ Bypass complete — session restored.", "info");
966
- return refreshed;
967
- }
968
- logger("✅ No checkpoint detected — session is clean.", "info");
969
- return res;
970
- } catch {
971
- return res;
972
- }
916
+ ctx.guardSessionResponse = async function (response) {
917
+ return guardSessionResponse(response);
973
918
  };
974
- const processed = (await ctx.bypassAutomation(res, jar)) || res;
919
+ const processed = (await ctx.guardSessionResponse(res)) || res;
975
920
  let html = processed && processed.data ? processed.data : "";
976
921
  let cookies = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
977
922
  const getUIDFromCookies = cs =>
@@ -1011,6 +956,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1011
956
  // Try one more refresh
1012
957
  try {
1013
958
  const refreshRes = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
959
+ guardSessionResponse(refreshRes);
1014
960
  const refreshedHtml = refreshRes && refreshRes.data ? refreshRes.data : "";
1015
961
  const refreshedHtmlUID = getUIDFromHTML(refreshedHtml);
1016
962
  if (isValidUID(refreshedHtmlUID)) {
@@ -1021,6 +967,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1021
967
  throw new Error("Login failed - HTML does not show valid USER_ID after auto-login and refresh");
1022
968
  }
1023
969
  } catch (refreshErr) {
970
+ if (isSessionEnforcementError(refreshErr)) throw refreshErr;
1024
971
  throw new Error(`Login failed - Could not establish valid session. HTML USER_ID check failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`);
1025
972
  }
1026
973
  } else {
@@ -1049,6 +996,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1049
996
  // Try refreshing with m.facebook.com/home.php (mobile home page)
1050
997
  logger("Trying to activate session via m.facebook.com/home.php...", "info");
1051
998
  const activateRes = await get("https://m.facebook.com/home.php", jar, null, globalOptions).then(saveCookies(jar));
999
+ guardSessionResponse(activateRes);
1052
1000
  const activateHtml = activateRes && activateRes.data ? activateRes.data : "";
1053
1001
  const activateUID = getUIDFromHTML(activateHtml);
1054
1002
 
@@ -1062,6 +1010,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1062
1010
  await new Promise(resolve => setTimeout(resolve, 1500));
1063
1011
  logger("Trying to activate session via www.facebook.com/home.php...", "info");
1064
1012
  const activateRes2 = await get("https://www.facebook.com/home.php", jar, null, globalOptions).then(saveCookies(jar));
1013
+ guardSessionResponse(activateRes2);
1065
1014
  const activateHtml2 = activateRes2 && activateRes2.data ? activateRes2.data : "";
1066
1015
  const activateUID2 = getUIDFromHTML(activateHtml2);
1067
1016
 
@@ -1185,36 +1134,26 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1185
1134
  _emitter: emitter
1186
1135
  };
1187
1136
  ctxMain.options = globalOptions;
1188
- ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1137
+ ctxMain.guardSessionResponse = ctx.guardSessionResponse;
1189
1138
  ctxMain.performAutoLogin = async () => {
1190
1139
  try {
1191
- // [Fixed by xalman] First check whether the existing cookie session is actually
1192
- // still usable. A checkpoint/redirect seen on one request
1193
- // doesn't always mean the whole session is dead (transient FB
1194
- // blips, rate limiting, etc). Cookie/appstate-only logins have
1195
- // no email+password to re-login with, so without this check a
1196
- // single false-positive checkpoint would permanently tear down
1197
- // the bot (via emitAuth) and force a brand new cookie every
1198
- // time instead of just continuing on the still-good session.
1199
1140
  try {
1200
- // [Fixed by xalman] retry up to 3x - a transient network
1201
- // hiccup during THIS check alone used to be treated the same
1202
- // as a dead session and fall through to requiring credentials.
1203
- let stillCheckpointed = true;
1141
+ if (ctxMain._forceFreshLogin) throw { __skipCookieCheck: true };
1204
1142
  let uid = null;
1143
+ let transportError = null;
1205
1144
  for (let attempt = 0; attempt < 3 && !uid; attempt++) {
1206
1145
  try {
1207
1146
  const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1147
+ guardSessionResponse(check);
1208
1148
  const html = check && check.data ? String(check.data) : "";
1209
- stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1210
1149
  const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
1211
- if (!stillCheckpointed && uidMatch && uidMatch[1] && uidMatch[1] !== "0") {
1150
+ if (uidMatch && uidMatch[1] && uidMatch[1] !== "0") {
1212
1151
  uid = uidMatch[1];
1213
1152
  break;
1214
1153
  }
1215
- } catch {
1216
- // network hiccup on this attempt - retry below instead of
1217
- // immediately assuming the session is dead
1154
+ } catch (checkErr) {
1155
+ if (isSessionEnforcementError(checkErr)) throw checkErr;
1156
+ if (isTransientTransportError(checkErr)) transportError = checkErr;
1218
1157
  }
1219
1158
  if (!uid && attempt < 2) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
1220
1159
  }
@@ -1222,8 +1161,12 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1222
1161
  logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1223
1162
  return true;
1224
1163
  }
1225
- } catch {
1226
- // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1164
+ if (transportError) throw transportError;
1165
+ } catch (checkErr) {
1166
+ if (checkErr && checkErr.__skipCookieCheck) {
1167
+ // fresh login requested: go straight to the credential login below
1168
+ } else if (isSessionEnforcementError(checkErr) || isTransientTransportError(checkErr)) throw checkErr;
1169
+ // A non-enforcement response without a usable identity may use the existing credential fallback.
1227
1170
  }
1228
1171
 
1229
1172
  const u = config.credentials?.email || email;
@@ -1231,12 +1174,15 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1231
1174
  const tf = config.credentials?.twofactor || null;
1232
1175
  if (!u || !p) return false;
1233
1176
  const r = await tokens(u, p, tf);
1177
+ guardSessionResponse(r);
1234
1178
  if (!(r && r.status && Array.isArray(r.cookies))) return false;
1235
1179
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
1236
1180
  setJarFromPairs(jar, pairs, ".facebook.com");
1237
- await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1181
+ const response = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1182
+ guardSessionResponse(response);
1238
1183
  return true;
1239
- } catch {
1184
+ } catch (loginErr) {
1185
+ if (isSessionEnforcementError(loginErr) || isTransientTransportError(loginErr)) throw loginErr;
1240
1186
  return false;
1241
1187
  }
1242
1188
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "7.3.5",
3
+ "version": "7.5.0",
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",
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Accept one incoming friend request, by the requester's user ID.
3
+ *
4
+ * api.acceptFriendRequest(userID, callback?) -> Promise<{ userID, accepted: true }>
5
+ *
6
+ * Uses the same Relay/GraphQL pattern as addFriend. The confirm mutation's
7
+ * doc_id can change when Facebook redeploys; set FCA_NX_FRIEND_CONFIRM_DOC_ID to
8
+ * override the built-in default.
9
+ */
10
+
11
+ "use strict";
12
+
13
+ const log = require("../../../func/logAdapter");
14
+ const { parseAndCheckLogin } = require("../../utils/client");
15
+ const { formatID, getSignatureID } = require("../../utils/format");
16
+
17
+ const CONFIRM_FRIENDLY_NAME = "FriendingCometFriendRequestConfirmMutation";
18
+ // doc_id of the confirm mutation, taken from the bot's acp.js (add) command.
19
+ // FCA_NX_FRIEND_CONFIRM_DOC_ID overrides it if Facebook changes it.
20
+ const DEFAULT_CONFIRM_DOC_ID = "3147613905362928";
21
+
22
+ module.exports = function (defaultFuncs, api, ctx) {
23
+ return function acceptFriendRequest(userID, callback) {
24
+ let resolveFunc;
25
+ let rejectFunc;
26
+ const returnPromise = new Promise(function (resolve, reject) {
27
+ resolveFunc = resolve;
28
+ rejectFunc = reject;
29
+ });
30
+
31
+ const handleCallback = (err, data) => {
32
+ if (typeof callback === "function") callback(err, data);
33
+ if (err) rejectFunc(err);
34
+ else resolveFunc(data);
35
+ };
36
+
37
+ let requesterID;
38
+ try {
39
+ requesterID = formatID(userID);
40
+ } catch (err) {
41
+ handleCallback(err);
42
+ return returnPromise;
43
+ }
44
+ if (!requesterID) {
45
+ handleCallback(new Error("Invalid user ID"));
46
+ return returnPromise;
47
+ }
48
+
49
+ const docID = process.env.FCA_NX_FRIEND_CONFIRM_DOC_ID || DEFAULT_CONFIRM_DOC_ID;
50
+ const run = async function () {
51
+ if (!ctx.fb_dtsg && typeof api?.refreshFb_dtsg === "function") {
52
+ try {
53
+ await api.refreshFb_dtsg();
54
+ } catch (_) {
55
+ // The request below returns the actionable Facebook error.
56
+ }
57
+ }
58
+
59
+ const actorID = String(ctx.i_userID || ctx.userID);
60
+ const form = {
61
+ av: actorID,
62
+ __aaid: "0",
63
+ __user: actorID,
64
+ __a: "1",
65
+ __req: getSignatureID(),
66
+ __comet_req: "15",
67
+ fb_dtsg: ctx.fb_dtsg,
68
+ jazoest: ctx.ttstamp || ctx.jazoest,
69
+ lsd: ctx.fb_dtsg,
70
+ __spin_t: String(Date.now()),
71
+ __crn: "comet.fbweb.CometFriendingRoute",
72
+ fb_api_caller_class: "RelayModern",
73
+ fb_api_req_friendly_name: CONFIRM_FRIENDLY_NAME,
74
+ server_timestamps: true,
75
+ doc_id: docID,
76
+ variables: JSON.stringify({
77
+ input: {
78
+ click_correlation_id: String(Date.now()),
79
+ click_proof_validation_result: JSON.stringify({ validated: true }),
80
+ friend_requester_id: String(requesterID),
81
+ friending_channel: "FRIENDS_HOME_MAIN",
82
+ actor_id: actorID,
83
+ client_mutation_id: String(Math.floor(Math.random() * 100000))
84
+ },
85
+ scale: 1
86
+ })
87
+ };
88
+
89
+ return defaultFuncs
90
+ .post("https://www.facebook.com/api/graphql/", ctx.jar, form)
91
+ .then(parseAndCheckLogin(ctx, defaultFuncs));
92
+ };
93
+
94
+ run()
95
+ .then(function (resData) {
96
+ if (!resData) throw new Error("Empty response from Facebook");
97
+
98
+ const payload = resData.payload || resData.data || resData;
99
+ const errorValue =
100
+ resData.error ||
101
+ resData.errors ||
102
+ resData.errorDescription ||
103
+ payload?.error ||
104
+ payload?.err ||
105
+ payload?.errorDescription;
106
+ if (errorValue) {
107
+ const error = new Error(
108
+ typeof errorValue === "string"
109
+ ? errorValue
110
+ : errorValue.message || JSON.stringify(errorValue)
111
+ );
112
+ error.error = errorValue;
113
+ error.res = resData;
114
+ throw error;
115
+ }
116
+
117
+ return handleCallback(null, { userID: String(requesterID), accepted: true });
118
+ })
119
+ .catch(function (err) {
120
+ log.error("acceptFriendRequest", err && err.message ? err.message : err);
121
+ handleCallback(err);
122
+ });
123
+
124
+ return returnPromise;
125
+ };
126
+ };
@@ -5,12 +5,15 @@
5
5
  */
6
6
  const { formatID } = require("../../../utils/format");
7
7
  const { getSessionIdentity } = require("../../../utils/clientIdentity");
8
+ const { isSessionEnforcement } = require("../../../utils/sessionStatus");
8
9
 
9
10
  const DEFAULT_RECONNECT_DELAY_MS = 8000;
10
11
  const MAX_RECONNECT_DELAY_MS = 120000;
12
+ const RECONNECT_CHECKS = 3; // reconnect checks before a fresh login
13
+ const RECONNECT_INTERVAL_MS = 5000; // fixed gap between checks
11
14
  const MAX_RECONNECT_ATTEMPTS = 5; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
12
15
  const MAX_RECONNECT_COOLDOWN_MS = 20 * 60 * 1000; // after exhausting fast retries, wait this long before trying again (never give up permanently)
13
- const T_MS_WAIT_TIMEOUT_MS = 5000;
16
+ const T_MS_WAIT_TIMEOUT_MS = 15000;
14
17
 
15
18
  // Exponential backoff with jitter, based on how many *consecutive* reconnect
16
19
  // attempts have happened for this session (reset to 0 on a successful
@@ -29,6 +32,10 @@ module.exports = function createListenMqtt(deps) {
29
32
  } = deps;
30
33
 
31
34
  return function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
35
+ if (ctx._ending || ctx._sessionEnforcement) {
36
+ logger("mqtt connect skipped - session is stopped or requires manual review", "warn");
37
+ return;
38
+ }
32
39
 
33
40
  function scheduleReconnect(delayMs) {
34
41
  const base = (ctx._mqttOpt && ctx._mqttOpt.reconnectDelayMs) || DEFAULT_RECONNECT_DELAY_MS;
@@ -44,25 +51,36 @@ module.exports = function createListenMqtt(deps) {
44
51
  return;
45
52
  }
46
53
  ctx._reconnectAttempts = (ctx._reconnectAttempts || 0) + 1;
47
- if (ctx._reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
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);
54
+ if (ctx._reconnectAttempts > RECONNECT_CHECKS) {
55
+ // All quick reconnect checks failed. Do a brand-new login instead of
56
+ // another reconnect: force the credential path (skip the cookie check).
55
57
  ctx._reconnectAttempts = 0;
56
- ctx._reconnectTimer = setTimeout(() => {
58
+ logger(`mqtt ${RECONNECT_CHECKS} reconnect checks failed; starting a fresh login`, "error");
59
+ ctx._reconnectTimer = setTimeout(async () => {
57
60
  ctx._reconnectTimer = null;
58
- if (!ctx._ending) {
61
+ if (ctx._ending) return;
62
+ let ok = false;
63
+ try {
64
+ if (typeof ctx.performAutoLogin === "function") {
65
+ ctx._forceFreshLogin = true;
66
+ ok = await ctx.performAutoLogin();
67
+ }
68
+ } catch (loginErr) {
69
+ logger(`mqtt fresh login failed: ${loginErr && loginErr.message ? loginErr.message : String(loginErr)}`, "error");
70
+ ok = false;
71
+ } finally {
72
+ ctx._forceFreshLogin = false;
73
+ }
74
+ if (ok && !ctx._ending) {
59
75
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
76
+ } else {
77
+ globalCallback({ type: "stop_listen", error: "Fresh login failed after reconnect checks" }, null);
60
78
  }
61
- }, cooldownMs);
79
+ }, 0);
62
80
  return;
63
81
  }
64
- const ms = typeof delayMs === "number" ? delayMs : computeBackoff(ctx, base);
65
- logger(`mqtt will reconnect in ${ms}ms (attempt ${ctx._reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`, "warn");
82
+ const ms = RECONNECT_INTERVAL_MS;
83
+ logger(`mqtt reconnect check ${ctx._reconnectAttempts}/${RECONNECT_CHECKS} in ${ms}ms`, "warn");
66
84
  ctx._reconnectTimer = setTimeout(() => {
67
85
  ctx._reconnectTimer = null;
68
86
  if (!ctx._ending) {
@@ -160,10 +178,31 @@ module.exports = function createListenMqtt(deps) {
160
178
  }
161
179
 
162
180
  if (/Invalid header flag bits|must be 0x0 for puback/i.test(msg)) {
163
- logger(`mqtt puback ignored: ${msg}`, "warn");
181
+ // A malformed puback means the byte stream is out of step. Each one is
182
+ // harmless alone, but a run of them means this connection is dead and
183
+ // the t_ms reply will never come. After 3 in a row, drop and reconnect.
184
+ ctx._badPuback = (ctx._badPuback || 0) + 1;
185
+ logger(`mqtt puback ignored (${ctx._badPuback}/3): ${msg}`, "warn");
186
+ if (ctx._badPuback >= 3) {
187
+ ctx._badPuback = 0;
188
+ try {
189
+ if (mqttClient) mqttClient.end(true);
190
+ } catch (_) { }
191
+ scheduleReconnect();
192
+ }
164
193
  return;
165
194
  }
166
195
 
196
+ if (isSessionEnforcement(err)) {
197
+ return emitAuth(
198
+ ctx,
199
+ api,
200
+ globalCallback,
201
+ "verification_required",
202
+ "Facebook requires manual account review; automatic reconnect stopped."
203
+ );
204
+ }
205
+
167
206
  if (/Not logged in|Not logged in.|blocked the login|401|403/i.test(msg)) {
168
207
  try {
169
208
  if (mqttClient && mqttClient.connected) {
@@ -214,7 +253,6 @@ module.exports = function createListenMqtt(deps) {
214
253
  // reset the backoff counter so a later transient failure starts a
215
254
  // fresh backoff sequence instead of inheriting a long delay from an
216
255
  // unrelated earlier outage.
217
- ctx._reconnectAttempts = 0;
218
256
 
219
257
  topics.forEach(t => mqttClient.subscribe(t));
220
258
 
@@ -275,6 +313,8 @@ module.exports = function createListenMqtt(deps) {
275
313
  } else if (jsonMessage.type === "jewel_requests_remove_old") {
276
314
  globalCallback(null, { type: "friend_request_cancel", actorFbId: jsonMessage.from.toString(), timestamp: Date.now().toString() });
277
315
  } else if (topic === "/t_ms") {
316
+ ctx._reconnectAttempts = 0;
317
+ ctx._badPuback = 0;
278
318
  if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
279
319
  if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
280
320
  ctx.lastSeqId = jsonMessage.firstDeltaSeqId;