fca-nx 7.3.5 → 7.4.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,25 @@ 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;
1204
1141
  let uid = null;
1142
+ let transportError = null;
1205
1143
  for (let attempt = 0; attempt < 3 && !uid; attempt++) {
1206
1144
  try {
1207
1145
  const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1146
+ guardSessionResponse(check);
1208
1147
  const html = check && check.data ? String(check.data) : "";
1209
- stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1210
1148
  const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
1211
- if (!stillCheckpointed && uidMatch && uidMatch[1] && uidMatch[1] !== "0") {
1149
+ if (uidMatch && uidMatch[1] && uidMatch[1] !== "0") {
1212
1150
  uid = uidMatch[1];
1213
1151
  break;
1214
1152
  }
1215
- } catch {
1216
- // network hiccup on this attempt - retry below instead of
1217
- // immediately assuming the session is dead
1153
+ } catch (checkErr) {
1154
+ if (isSessionEnforcementError(checkErr)) throw checkErr;
1155
+ if (isTransientTransportError(checkErr)) transportError = checkErr;
1218
1156
  }
1219
1157
  if (!uid && attempt < 2) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
1220
1158
  }
@@ -1222,8 +1160,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1222
1160
  logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1223
1161
  return true;
1224
1162
  }
1225
- } catch {
1226
- // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1163
+ if (transportError) throw transportError;
1164
+ } catch (checkErr) {
1165
+ if (isSessionEnforcementError(checkErr) || isTransientTransportError(checkErr)) throw checkErr;
1166
+ // A non-enforcement response without a usable identity may use the existing credential fallback.
1227
1167
  }
1228
1168
 
1229
1169
  const u = config.credentials?.email || email;
@@ -1231,12 +1171,15 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1231
1171
  const tf = config.credentials?.twofactor || null;
1232
1172
  if (!u || !p) return false;
1233
1173
  const r = await tokens(u, p, tf);
1174
+ guardSessionResponse(r);
1234
1175
  if (!(r && r.status && Array.isArray(r.cookies))) return false;
1235
1176
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
1236
1177
  setJarFromPairs(jar, pairs, ".facebook.com");
1237
- await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1178
+ const response = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1179
+ guardSessionResponse(response);
1238
1180
  return true;
1239
- } catch {
1181
+ } catch (loginErr) {
1182
+ if (isSessionEnforcementError(loginErr) || isTransientTransportError(loginErr)) throw loginErr;
1240
1183
  return false;
1241
1184
  }
1242
1185
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "7.3.5",
3
+ "version": "7.4.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",
@@ -5,6 +5,7 @@
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;
@@ -164,6 +165,16 @@ module.exports = function createListenMqtt(deps) {
164
165
  return;
165
166
  }
166
167
 
168
+ if (isSessionEnforcement(err)) {
169
+ return emitAuth(
170
+ ctx,
171
+ api,
172
+ globalCallback,
173
+ "verification_required",
174
+ "Facebook requires manual account review; automatic reconnect stopped."
175
+ );
176
+ }
177
+
167
178
  if (/Not logged in|Not logged in.|blocked the login|401|403/i.test(msg)) {
168
179
  try {
169
180
  if (mqttClient && mqttClient.connected) {
@@ -8,7 +8,7 @@ module.exports = function createEmitAuth({ logger }) {
8
8
  // Clean up all timers
9
9
  try {
10
10
  if (ctx._autoCycleTimer) {
11
- clearInterval(ctx._autoCycleTimer);
11
+ clearTimeout(ctx._autoCycleTimer);
12
12
  ctx._autoCycleTimer = null;
13
13
  }
14
14
  } catch (_) { }
@@ -22,6 +22,9 @@ module.exports = function createEmitAuth({ logger }) {
22
22
  try {
23
23
  ctx._ending = true;
24
24
  ctx._cycling = false;
25
+ if (reason === "verification_required" || reason === "login_blocked") {
26
+ ctx._sessionEnforcement = true;
27
+ }
25
28
  } catch (_) { }
26
29
 
27
30
  // Clean up MQTT client
@@ -8,6 +8,12 @@ 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
+ isTransientTransportError,
14
+ createSessionEnforcementError,
15
+ isSessionEnforcementError
16
+ } = require("../../../utils/sessionStatus");
11
17
 
12
18
  function getConfig() {
13
19
  try {
@@ -62,6 +68,12 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
62
68
  twofactor,
63
69
  config.apiServer || null
64
70
  );
71
+ if (isSessionEnforcement(result)) throw createSessionEnforcementError();
72
+ if (isTransientTransportError(result)) {
73
+ const error = new Error("The login service is temporarily unavailable.");
74
+ error.code = result.code || "ERR_NETWORK";
75
+ throw error;
76
+ }
65
77
 
66
78
  if (result && result.status) {
67
79
  const normalizeCookieHeaderString = loginHelper.normalizeCookieHeaderString;
@@ -103,8 +115,8 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
103
115
  } else if (typeof ctx.jar.setCookie === "function") {
104
116
  await ctx.jar.setCookie(cookieStr, "https://www.facebook.com");
105
117
  }
106
- } catch (err) {
107
- logger(`getSeqID: Failed to set cookie ${kv.substring(0, 50)}: ${err && err.message ? err.message : String(err)}`, "warn");
118
+ } catch {
119
+ logger("getSeqID: Failed to apply a session cookie to the cookie jar", "warn");
108
120
  }
109
121
  }
110
122
  logger(`getSeqID: applied ${cookiePairs.length} API cookies to jar`, "info");
@@ -117,6 +129,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
117
129
 
118
130
  let webResponse = null;
119
131
  let htmlContent = "";
132
+ let lastTransportError = null;
120
133
  const htmlUID = body => {
121
134
  const s = typeof body === "string" ? body : String(body ?? "");
122
135
  return s.match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s.match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
@@ -130,6 +143,8 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
130
143
  logger(`getSeqID: Refreshing ${urlToUse} (attempt ${attempt + 1}/3)...`, "info");
131
144
 
132
145
  webResponse = await get(urlToUse, ctx.jar, null, ctx.globalOptions, ctx);
146
+ if (isSessionEnforcement(webResponse)) throw createSessionEnforcementError();
147
+ lastTransportError = null;
133
148
  if (webResponse && webResponse.data) {
134
149
  await saveWebCookies(ctx.jar)(webResponse);
135
150
  htmlContent = typeof webResponse.data === "string" ? webResponse.data : String(webResponse.data || "");
@@ -144,6 +159,8 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
144
159
  }
145
160
  }
146
161
  } catch (refreshErr) {
162
+ if (isSessionEnforcementError(refreshErr)) throw refreshErr;
163
+ if (isTransientTransportError(refreshErr)) lastTransportError = refreshErr;
147
164
  logger(`getSeqID: Error refreshing session (attempt ${attempt + 1}/3): ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
148
165
  if (attempt < 2) {
149
166
  await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));
@@ -151,6 +168,8 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
151
168
  }
152
169
  }
153
170
 
171
+ if (lastTransportError && !isValidUID(htmlUID(htmlContent))) throw lastTransportError;
172
+
154
173
  if (webResponse && webResponse.data) {
155
174
  const updatedCookies = await ctx.jar.getCookies("https://www.facebook.com");
156
175
  logger(`getSeqID: refreshed session, now have ${updatedCookies.length} web cookies`, "info");
@@ -174,6 +193,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
174
193
  logger("getSeqID: Failed to refresh web session after API login", "error");
175
194
  }
176
195
  } catch (refreshErr) {
196
+ if (isSessionEnforcementError(refreshErr) || isTransientTransportError(refreshErr)) throw refreshErr;
177
197
  logger(`getSeqID: web session refresh failed - ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
178
198
  }
179
199
 
@@ -183,6 +203,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
183
203
 
184
204
  logger(`getSeqID: auto re-login failed - ${result && result.message ? result.message : "unknown error"}`, "error");
185
205
  } catch (loginErr) {
206
+ if (isSessionEnforcementError(loginErr) || isTransientTransportError(loginErr)) throw loginErr;
186
207
  logger(`getSeqID: auto re-login error - ${loginErr && loginErr.message ? loginErr.message : String(loginErr)}`, "error");
187
208
  }
188
209
 
@@ -195,6 +216,15 @@ module.exports = function createGetSeqID(deps) {
195
216
  return function getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount = 0) {
196
217
  const MAX_RETRIES = 3;
197
218
  const RETRY_DELAY = 2000;
219
+ if (ctx._sessionEnforcement) {
220
+ return emitAuth(
221
+ ctx,
222
+ api,
223
+ globalCallback,
224
+ "verification_required",
225
+ "Facebook requires manual account review; automatic login and reconnect stopped."
226
+ );
227
+ }
198
228
  ctx.t_mqttCalled = false;
199
229
 
200
230
  // Ensure essential tokens are injected into GraphQL Batch Payload
@@ -225,6 +255,16 @@ module.exports = function createGetSeqID(deps) {
225
255
  .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
226
256
  .then(parseAndCheckLogin(ctx, defaultFuncs))
227
257
  .then(async resData => {
258
+ if (isSessionEnforcement(resData)) {
259
+ return emitAuth(
260
+ ctx,
261
+ api,
262
+ globalCallback,
263
+ "verification_required",
264
+ "Facebook requires manual account review; automatic login and reconnect stopped."
265
+ );
266
+ }
267
+
228
268
  // Safe check for non-array responses (such as Error Objects from FB)
229
269
  if (getType(resData) !== "Array") {
230
270
  logger(`getSeqID: Response is not Array, received: ${getType(resData)}`, "warn");
@@ -237,7 +277,8 @@ module.exports = function createGetSeqID(deps) {
237
277
  if (errCode === 1357032 || /Something Went Wrong/i.test(errorMsg)) {
238
278
  logger("getSeqID: FB returned error 1357032. Using fallback seqID and continuing to MQTT.", "warn");
239
279
  ctx.lastSeqId = ctx.lastSeqId || "0";
240
- listenMqtt(defaultFuncs, api, ctx, globalCallback);
280
+ ctx._sessionEnforcement = false; // 7.4.1: a successful login clears a stale stop flag
281
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
241
282
  return;
242
283
  }
243
284
 
@@ -248,7 +289,8 @@ module.exports = function createGetSeqID(deps) {
248
289
 
249
290
  // Fallback if it's an unrecognized object
250
291
  ctx.lastSeqId = ctx.lastSeqId || "0";
251
- listenMqtt(defaultFuncs, api, ctx, globalCallback);
292
+ ctx._sessionEnforcement = false; // 7.4.1: a successful login clears a stale stop flag
293
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
252
294
  return;
253
295
  }
254
296
 
@@ -264,9 +306,25 @@ module.exports = function createGetSeqID(deps) {
264
306
  ctx.lastSeqId = ctx.lastSeqId || "0";
265
307
  logger("getSeqID: sync_sequence_id not found, fallback lastSeqId=" + ctx.lastSeqId, "warn");
266
308
  }
309
+ ctx._sessionEnforcement = false; // 7.4.1: a successful login clears a stale stop flag
267
310
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
268
311
  })
269
312
  .catch(async err => {
313
+ if (
314
+ isSessionEnforcementError(err) ||
315
+ isSessionEnforcement(err) ||
316
+ isSessionEnforcement(err && err.originalResponse) ||
317
+ isSessionEnforcement(err && err.response)
318
+ ) {
319
+ return emitAuth(
320
+ ctx,
321
+ api,
322
+ globalCallback,
323
+ "verification_required",
324
+ "Facebook requires manual account review; automatic login and reconnect stopped."
325
+ );
326
+ }
327
+
270
328
  const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
271
329
  const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
272
330
 
@@ -304,8 +362,27 @@ module.exports = function createGetSeqID(deps) {
304
362
  logger("getSeqID: refreshing session before retry...", "info");
305
363
  const { get } = require("../../../utils/request");
306
364
  const { saveCookies } = require("../../../utils/client");
307
- await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
365
+ const refreshed = await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx);
366
+ if (isSessionEnforcement(refreshed)) {
367
+ return emitAuth(
368
+ ctx,
369
+ api,
370
+ globalCallback,
371
+ "verification_required",
372
+ "Facebook requires manual account review; automatic login and reconnect stopped."
373
+ );
374
+ }
375
+ await saveCookies(ctx.jar)(refreshed);
308
376
  } catch (refreshErr) {
377
+ if (isSessionEnforcementError(refreshErr) || isSessionEnforcement(refreshErr)) {
378
+ return emitAuth(
379
+ ctx,
380
+ api,
381
+ globalCallback,
382
+ "verification_required",
383
+ "Facebook requires manual account review; automatic login and reconnect stopped."
384
+ );
385
+ }
309
386
  logger(`getSeqID: session refresh failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
310
387
  }
311
388
  }
@@ -20,12 +20,6 @@ const getTaskResponseData = require("./core/getTaskResponseData");
20
20
  const createEmitAuth = require("./core/emitAuth");
21
21
  const createMiddlewareSystem = require("./middleware");
22
22
 
23
- // 7.3.5: no hourly hard cycle (7.2.5 published /browser_close every hour and
24
- // the session came back logged out) and no immortal socket (7.3.0 never
25
- // cycled, and a custom /ping every 30s on that socket got accounts suspended).
26
- // Soft-recycle the MQTT socket on a long jittered timer. Real keepalive is
27
- // MQTT PINGREQ (connectMqtt keepalive). Set mqtt cycleMs to 0 to disable.
28
- const CYCLE_MS_DEFAULT = 6 * 60 * 60 * 1000;
29
23
  const RECONNECT_DELAY_MS_DEFAULT = 3000;
30
24
  const UNSUB_ALL_TIMEOUT_MS = 5000;
31
25
  const MAX_MQTT_RECONNECT_DELAY_MS = 60000;
@@ -51,7 +45,6 @@ const listenMqtt = createListenMqtt({
51
45
  const getSeqIDFactory = createGetSeqID({ parseAndCheckLogin, listenMqtt, logger, emitAuth });
52
46
 
53
47
  const MQTT_DEFAULTS = {
54
- cycleMs: CYCLE_MS_DEFAULT,
55
48
  reconnectDelayMs: RECONNECT_DELAY_MS_DEFAULT,
56
49
  autoReconnect: true,
57
50
  reconnectAfterStop: false,
@@ -219,11 +212,8 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
219
212
  return;
220
213
  }
221
214
 
222
- // 7.3.5: do not publish a custom "/ping" payload. MQTT keepalive
223
- // (PINGREQ every 60s in connectMqtt.js) is the real browser
224
- // signal. A JSON /ping every 30s on a socket that never closed
225
- // is what 7.3.0 left running, and that pattern suspended accounts.
226
- // Liveness is tracked from "packetreceive" above.
215
+ // MQTT keepalive is handled by the client. This timer only checks
216
+ // whether packets have arrived; it does not publish a custom ping.
227
217
  }, conf.heartbeatInterval || HEARTBEAT_INTERVAL_MS);
228
218
  }
229
219
 
@@ -305,9 +295,8 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
305
295
  ctx.tasks.clear();
306
296
  }
307
297
 
308
- // Only a real stopListening tears down appstate autosave, the
309
- // user-info refresh timers and the scheduler. A soft cycle must
310
- // leave those running or the saved session goes stale (logout).
298
+ // Only a full stop tears down appstate autosave, user-info refresh
299
+ // timers, and the scheduler.
311
300
  if (full) {
312
301
  if (ctx._userInfoIntervals && Array.isArray(ctx._userInfoIntervals)) {
313
302
  ctx._userInfoIntervals.forEach(interval => {
@@ -337,9 +326,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
337
326
 
338
327
  try {
339
328
  if (ctx.mqttClient) {
340
- // /browser_close tells Facebook the user left. Sending it on a
341
- // routine recycle is what 7.2.5 did every hour, and the account
342
- // came back logged out. Only a real stop publishes it.
329
+ // Send the close event only for an explicit full stop.
343
330
  if (full && isConnected()) {
344
331
  try {
345
332
  ctx.mqttClient.publish("/browser_close", "{}", { qos: 0 });
@@ -355,7 +342,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
355
342
  }
356
343
 
357
344
  function delayedReconnect() {
358
- if (ctx._ending) return;
345
+ if (ctx._ending || ctx._sessionEnforcement) return;
359
346
  const d = getReconnectDelay();
360
347
  logger(`mqtt reconnect in ${d}ms`, "info");
361
348
 
@@ -365,31 +352,18 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
365
352
  }
366
353
 
367
354
  ctx._reconnectTimer = setTimeout(() => {
368
- if (!ctx._ending) {
355
+ if (!ctx._ending && !ctx._sessionEnforcement) {
369
356
  isReconnecting = false;
370
357
  getSeqIDWrapper();
371
358
  }
372
359
  }, d);
373
360
  }
374
361
 
375
- function scheduleSoftCycle() {
376
- if (ctx._autoCycleTimer) {
377
- clearTimeout(ctx._autoCycleTimer);
378
- ctx._autoCycleTimer = null;
379
- }
380
- const base = conf.cycleMs;
381
- if (!base || base <= 0) return;
382
- // ±20% so the reconnect is not a fixed cron-like interval.
383
- const jitter = Math.floor((Math.random() - 0.5) * base * 0.4);
384
- const wait = Math.max(30 * 60 * 1000, base + jitter);
385
- ctx._autoCycleTimer = setTimeout(() => {
386
- ctx._autoCycleTimer = null;
387
- if (!ctx._ending && !ctx._cycling) forceCycle();
388
- }, wait);
389
- logger(`mqtt soft-cycle in ${Math.round(wait / 60000)}min`, "info");
390
- }
391
-
392
362
  function forceCycle() {
363
+ if (ctx._sessionEnforcement) {
364
+ logger("mqtt cycle skipped - manual account review is required", "warn");
365
+ return;
366
+ }
393
367
  if (ctx._cycling) {
394
368
  logger("mqtt force cycle already in progress", "warn");
395
369
  return;
@@ -411,7 +385,6 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
411
385
  ctx._cycling = false;
412
386
  if (conf.reconnectAfterStop || conf.autoReconnect !== false) {
413
387
  delayedReconnect();
414
- scheduleSoftCycle();
415
388
  }
416
389
  }, false);
417
390
  });
@@ -459,7 +432,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
459
432
  ctx.mqttClient.once("close", () => {
460
433
  logger("mqtt connection closed", "warn");
461
434
  stopHeartbeat();
462
- if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
435
+ if (!ctx._ending && !ctx._sessionEnforcement && ctx.globalOptions.autoReconnect !== false) {
463
436
  if (!isReconnecting) {
464
437
  isReconnecting = true;
465
438
  delayedReconnect();
@@ -469,7 +442,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
469
442
 
470
443
  ctx.mqttClient.once("error", (err) => {
471
444
  logger(`mqtt error: ${err.message}`, "error");
472
- if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
445
+ if (!ctx._ending && !ctx._sessionEnforcement && ctx.globalOptions.autoReconnect !== false) {
473
446
  if (!isReconnecting) {
474
447
  isReconnecting = true;
475
448
  forceCycle();
@@ -491,7 +464,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
491
464
  if (ctx._autoCycleTimer) {
492
465
  clearTimeout(ctx._autoCycleTimer);
493
466
  ctx._autoCycleTimer = null;
494
- logger("mqtt auto-cycle cleared", "info");
467
+ logger("mqtt legacy cycle timer cleared", "info");
495
468
  }
496
469
 
497
470
  if (ctx._reconnectTimer) {
@@ -549,8 +522,6 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
549
522
  ctx._autoCycleTimer = null;
550
523
  }
551
524
 
552
- scheduleSoftCycle();
553
-
554
525
  if (!ctx.firstListen || !ctx.lastSeqId) {
555
526
  getSeqIDWrapper();
556
527
  } else {
@@ -3,35 +3,25 @@ const { parseAndCheckLogin } = require("../../utils/client.js");
3
3
  const logger = require("../../../func/logger");
4
4
 
5
5
  const DOC_IDS = [
6
- {
7
- id: "2399631849267992",
8
- name: "CometUserProfileCoverPhotoQuery",
9
- hasCover: true
10
- },
11
6
  {
12
7
  id: "5009315269112105",
13
- name: "CometProfilePhotoGridQuery",
14
- hasCover: true
8
+ name: "CometProfilePhotoGridQuery"
15
9
  },
16
10
  {
17
11
  id: "24418640587785718",
18
- name: "CometHovercardQueryRendererQuery",
19
- hasCover: false
12
+ name: "CometHovercardQueryRendererQuery"
20
13
  },
21
14
  {
22
15
  id: "6003371686559437",
23
- name: "CometProfileInfoRendererQuery",
24
- hasCover: true
16
+ name: "CometProfileInfoRendererQuery"
25
17
  },
26
18
  {
27
19
  id: "6184020922587885",
28
- name: "CometProfilePageQuery",
29
- hasCover: true
20
+ name: "CometProfilePageQuery"
30
21
  },
31
22
  {
32
23
  id: "5069749766627730",
33
- name: "CometActorProfilePictureQuery",
34
- hasCover: false
24
+ name: "CometActorProfilePictureQuery"
35
25
  }
36
26
  ];
37
27
  const CALLER_CLASS = "RelayModern";
@@ -82,9 +72,7 @@ function extractPhotoUrl(photo, depth = 0) {
82
72
  "full_image",
83
73
  "viewer_image",
84
74
  "photo",
85
- "media",
86
- "cover_photo",
87
- "coverPhoto"
75
+ "media"
88
76
  ]) {
89
77
  const value = extractPhotoUrl(photo[key], depth + 1);
90
78
  if (value) return value;
@@ -93,31 +81,6 @@ function extractPhotoUrl(photo, depth = 0) {
93
81
  }
94
82
 
95
83
 
96
- // [Hardened] Fallback: read the cover photo straight from the profile page HTML,
97
- // used when none of the GraphQL doc_ids returned a cover (doc_ids rotate often).
98
- function decodeJsonString(raw) {
99
- try { return JSON.parse('"' + raw + '"'); } catch { return String(raw).replace(/\\\//g, "/"); }
100
- }
101
-
102
- function extractCoverFromHTML(html) {
103
- if (!html || typeof html !== "string") return null;
104
- const patterns = [
105
- /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
106
- /"profile_cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
107
- /"coverPhoto"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
108
- /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"url"\s*:\s*"([^"]+)"/,
109
- /property="og:image"\s+content="(https:\/\/[^"]+fbcdn[^"]+)"/i,
110
- /content="(https:\/\/[^"]+fbcdn[^"]+)"\s+property="og:image"/i
111
- ];
112
- for (const re of patterns) {
113
- const m = html.match(re);
114
- if (!m) continue;
115
- const url = decodeJsonString(m[1]).replace(/&amp;/g, "&");
116
- if (/^https?:\/\//i.test(url) && /(fbcdn|scontent)/i.test(url)) return url;
117
- }
118
- return null;
119
- }
120
-
121
84
  function pickMeta(user) {
122
85
  let friendshipStatus = null;
123
86
  let gender = null;
@@ -142,20 +105,6 @@ function pickMeta(user) {
142
105
  return { friendshipStatus, gender, shortName };
143
106
  }
144
107
 
145
- function extractCoverPhoto(user) {
146
- const cover = user?.cover_photo;
147
- if (!cover) return null;
148
- if (typeof cover === "string") return cover;
149
- return cover.source?.uri ||
150
- cover.source ||
151
- cover.uri ||
152
- cover.photo?.image?.uri ||
153
- cover.photo?.image?.url ||
154
- cover.image?.uri ||
155
- cover.image?.url ||
156
- cover.photo?.url ||
157
- null;
158
- }
159
108
  function normalizeUser(user) {
160
109
  if (!user) return null;
161
110
  const meta = pickMeta(user);
@@ -166,13 +115,8 @@ function normalizeUser(user) {
166
115
  firstName: meta.shortName || null,
167
116
  vanity,
168
117
  thumbSrc: extractProfilePicture(user),
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,
118
+ coverPhoto: null,
119
+ coverPhotoStatus: "unavailable",
176
120
  profileUrl: user.profile_url || user.url || null,
177
121
  gender: meta.gender || null,
178
122
  type: user.__typename || "User",
@@ -196,7 +140,8 @@ function createDefaultUser(id) {
196
140
  vanity: String(id),
197
141
  thumbSrc: `https://graph.facebook.com/${id}/picture?width=720&height=720`,
198
142
  profilePicUrl: `https://graph.facebook.com/${id}/picture?width=720&height=720`,
199
- coverPhoto: null, // FIX: default e null
143
+ coverPhoto: null,
144
+ coverPhotoStatus: "unavailable",
200
145
  profileUrl: `https://www.facebook.com/profile.php?id=${id}`,
201
146
  gender: "no specific gender",
202
147
  type: "User",
@@ -223,7 +168,8 @@ function formatUser(user, id) {
223
168
  lastName: nameParts.length > 1? nameParts.slice(1).join(" ") : null,
224
169
  vanity: user.vanity || String(id),
225
170
  profilePicUrl: user.thumbSrc || `https://graph.facebook.com/${id}/picture?width=720&height=720`,
226
- coverPhoto: user.coverPhoto || null, // FIX: cover photo pass
171
+ coverPhoto: null,
172
+ coverPhotoStatus: "unavailable",
227
173
  profileUrl: user.profileUrl || `https://www.facebook.com/profile.php?id=${id}`,
228
174
  gender: user.gender || "no specific gender",
229
175
  type: user.type || "User",
@@ -270,40 +216,16 @@ module.exports = function (defaultFuncs, api, ctx) {
270
216
  if (!bestUser) {
271
217
  bestUser = normalized;
272
218
  } else {
273
- for (const field of ["thumbSrc", "profileUrl", "vanity", "coverPhoto", "firstName", "gender"]) {
219
+ for (const field of ["thumbSrc", "profileUrl", "vanity", "firstName", "gender"]) {
274
220
  if (!bestUser[field] && normalized[field]) bestUser[field] = normalized[field];
275
221
  }
276
222
  if (normalized.isVerified) bestUser.isVerified = true;
277
223
  if (normalized.isFriend) bestUser.isFriend = true;
278
224
  }
279
- if (doc.hasCover && bestUser.coverPhoto) break;
280
225
  } catch (error) {
281
226
  logger(`getUserInfoV2 ${doc.id}: ${error.message || error}`, "warn");
282
227
  }
283
228
  }
284
- // [Hardened] GraphQL often omits cover; scrape profile HTML as last resort
285
- if (bestUser && !bestUser.coverPhoto) {
286
- const pages = [`https://www.facebook.com/profile.php?id=${id}`];
287
- if (bestUser.vanity && bestUser.vanity !== id) {
288
- pages.push(`https://www.facebook.com/${bestUser.vanity}`);
289
- }
290
- for (const url of pages) {
291
- try {
292
- const res = await defaultFuncs.get(url, ctx.jar, null, ctx);
293
- const html = typeof res === "string" ? res : (res && res.data);
294
- const cover = extractCoverFromHTML(html);
295
- if (cover) {
296
- bestUser.coverPhoto = cover;
297
- break;
298
- }
299
- } catch (error) {
300
- logger(`getUserInfoV2 cover html ${id}: ${error.message || error}`, "warn");
301
- }
302
- }
303
- if (!bestUser.coverPhoto && process.env.FCA_COVER_DEBUG === "1") {
304
- logger(`getUserInfoV2 cover ${id}: no cover found in GraphQL or profile HTML`, "warn");
305
- }
306
- }
307
229
  return bestUser;
308
230
  }
309
231
 
@@ -329,7 +251,8 @@ module.exports = function (defaultFuncs, api, ctx) {
329
251
  lastName: nameParts.length > 1? nameParts.slice(1).join(" ") : null,
330
252
  vanity: profile.vanity || null,
331
253
  thumbSrc: null,
332
- coverPhoto: extractPhotoUrl(profile.cover_photo),
254
+ coverPhoto: null,
255
+ coverPhotoStatus: "unavailable",
333
256
  profileUrl: profile.uri || `https://www.facebook.com/profile.php?id=${id}`,
334
257
  gender: profile.gender === 1? "male" : profile.gender === 2? "female" : "no specific gender",
335
258
  type: profile.type || "User",
@@ -420,7 +343,6 @@ module.exports = function (defaultFuncs, api, ctx) {
420
343
 
421
344
  module.exports._private = {
422
345
  extractPhotoUrl,
423
- extractCoverFromHTML,
424
346
  normalizeUser
425
347
  };
426
348
 
@@ -1,6 +1,11 @@
1
1
  "use strict";
2
2
 
3
3
  const logger = require("../../../func/logger");
4
+ const {
5
+ isSessionEnforcement,
6
+ createSessionEnforcementError,
7
+ isSessionEnforcementError
8
+ } = require("../sessionStatus");
4
9
 
5
10
  /**
6
11
  * Tạo hàm maybeAutoLogin: khi session hết hạn thì thử đăng nhập lại và retry request.
@@ -14,6 +19,22 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
14
19
  const { buildUrl, headerOf, formatCookie } = helpers;
15
20
 
16
21
  return async function maybeAutoLogin(resData, resConfig) {
22
+ const stopForEnforcement = () => {
23
+ const alreadyStopped = ctx._sessionEnforcement;
24
+ ctx._sessionEnforcement = true;
25
+ const error = createSessionEnforcementError();
26
+ if (!alreadyStopped) {
27
+ try {
28
+ emit("verificationRequired", { code: error.code, message: error.message });
29
+ } catch { }
30
+ }
31
+ return error;
32
+ };
33
+
34
+ if (ctx._sessionEnforcement || isSessionEnforcement(resData) || isSessionEnforcement(resConfig)) {
35
+ throw stopForEnforcement();
36
+ }
37
+
17
38
  const retryAfterLogin = async function () {
18
39
  if (!resConfig) {
19
40
  const e = new Error(
@@ -42,6 +63,9 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
42
63
  }
43
64
  return await parseAndCheckLogin(ctx, http)(newData);
44
65
  } catch (retryErr) {
66
+ if (isSessionEnforcementError(retryErr) || isSessionEnforcement(retryErr)) {
67
+ throw stopForEnforcement();
68
+ }
45
69
  if (
46
70
  retryErr?.code === "ERR_INVALID_CHAR" ||
47
71
  (retryErr?.message && retryErr.message.includes("Invalid character in header"))
@@ -79,6 +103,9 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
79
103
  try {
80
104
  ok = await ctx._autoLoginPromise;
81
105
  } catch (autoLoginErr) {
106
+ if (isSessionEnforcementError(autoLoginErr) || isSessionEnforcement(autoLoginErr)) {
107
+ throw stopForEnforcement();
108
+ }
82
109
  const e = new Error("Not logged in. Auto login failed.");
83
110
  e.error = "Not logged in.";
84
111
  e.res = resData;
@@ -122,6 +149,9 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
122
149
  throw e;
123
150
  }
124
151
  } catch (autoLoginErr) {
152
+ if (isSessionEnforcementError(autoLoginErr) || isSessionEnforcement(autoLoginErr)) {
153
+ throw stopForEnforcement();
154
+ }
125
155
  if (autoLoginErr.error === "Not logged in.") {
126
156
  throw autoLoginErr;
127
157
  }
@@ -4,15 +4,14 @@
4
4
  * Outgoing-message pacing.
5
5
  *
6
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.
7
+ * released no sooner than a fixed `delay` after the previous one. The rolling cap limits bursts;
8
+ * send timing is not randomized to imitate a person.
9
9
  *
10
10
  * FCA_NX_SEND_DELAY_MS base gap between sends, default 2800 (set 0 to disable)
11
- * FCA_NX_SEND_JITTER_MS extra random 0..N ms added to each gap, default 1400
12
- * or at runtime: api.setSendDelay(ms, jitterMs)
11
+ * or at runtime: setSendDelay(ms)
13
12
  */
14
13
 
15
- const state = { last: 0, chain: Promise.resolve(), delay: null, jitter: null, stamps: [] };
14
+ const state = { last: 0, chain: Promise.resolve(), delay: null, stamps: [] };
16
15
  // Hard ceiling per rolling minute (FCA_NX_SEND_MAX_PER_MIN, default 8, 0 = off).
17
16
  function maxPerMin() {
18
17
  const n = Number(process.env.FCA_NX_SEND_MAX_PER_MIN);
@@ -27,14 +26,9 @@ function readNum(v, d) {
27
26
  function getDelay() {
28
27
  return state.delay != null ? state.delay : readNum(process.env.FCA_NX_SEND_DELAY_MS, 2800);
29
28
  }
30
- function getJitter() {
31
- return state.jitter != null ? state.jitter : readNum(process.env.FCA_NX_SEND_JITTER_MS, 1400);
32
- }
33
-
34
- function setSendDelay(ms, jitterMs) {
29
+ function setSendDelay(ms) {
35
30
  if (ms != null) state.delay = readNum(ms, 1000);
36
- if (jitterMs != null) state.jitter = readNum(jitterMs, 400);
37
- return { delay: getDelay(), jitter: getJitter() };
31
+ return { delay: getDelay(), jitter: 0 };
38
32
  }
39
33
 
40
34
  /** Resolves when it is this caller's turn to send. */
@@ -42,8 +36,7 @@ function waitTurn() {
42
36
  const delay = getDelay();
43
37
  if (delay <= 0) return Promise.resolve();
44
38
  const turn = state.chain.then(async () => {
45
- const gap = delay + Math.floor(Math.random() * (getJitter() + 1));
46
- const wait = state.last + gap - Date.now();
39
+ const wait = state.last + delay - Date.now();
47
40
  if (wait > 0) await new Promise(r => setTimeout(r, wait));
48
41
  const cap = maxPerMin();
49
42
  if (cap > 0) {
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+
3
+ // 7.4.1: detection narrowed. Only real checkpoint signals count:
4
+ // - an explicit SESSION_VERIFICATION_REQUIRED code or requiresManualAction flag
5
+ // - a URL that points to facebook.com/checkpoint/
6
+ // - a checkpoint page marker inside an HTML page
7
+ // Generic words such as "checkpoint", "restricted" or "disabled" in ordinary
8
+ // text (chat messages, help pages, scripts) no longer match.
9
+ const SESSION_ENFORCEMENT_REQUIRED = "SESSION_VERIFICATION_REQUIRED";
10
+
11
+ const CHECKPOINT_PAGE_MARKER =
12
+ /XCheckpointFBScrapingWarningController|\/checkpoint\/block\/|\/checkpoint\/\d{6,}/;
13
+ const CHECKPOINT_URL = /(?:facebook\.com)?\/checkpoint\/(?:\d|block|[?#]|$)/i;
14
+ const TRANSPORT_MARKER =
15
+ /(?:timed?\s*out|timeout|network error|socket hang up|connection reset|ECONNRESET|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|ERR_NETWORK|UND_ERR_CONNECT_TIMEOUT)/i;
16
+
17
+ const URL_FIELDS = ["url", "redirect", "redirectUrl", "responseUrl", "location", "href"];
18
+ const CODE_FIELDS = ["code", "error", "name"];
19
+
20
+ function isCheckpointUrl(value) {
21
+ return typeof value === "string" && CHECKPOINT_URL.test(value);
22
+ }
23
+
24
+ function hasSignalFields(value, depth) {
25
+ if (!value || typeof value !== "object" || depth > 4) return false;
26
+ if (value.requiresManualAction === true) return true;
27
+ for (const key of CODE_FIELDS) {
28
+ if (value[key] === SESSION_ENFORCEMENT_REQUIRED) return true;
29
+ }
30
+ for (const key of URL_FIELDS) {
31
+ if (isCheckpointUrl(value[key])) return true;
32
+ }
33
+ // Nested response wrappers (axios-style and error objects) only.
34
+ for (const key of ["originalResponse", "response", "res", "request", "config"]) {
35
+ if (hasSignalFields(value[key], depth + 1)) return true;
36
+ }
37
+ return false;
38
+ }
39
+
40
+ function isSessionEnforcement(value) {
41
+ if (typeof value === "string") {
42
+ return CHECKPOINT_PAGE_MARKER.test(value) || isCheckpointUrl(value);
43
+ }
44
+ if (!value || typeof value !== "object") return false;
45
+ if (hasSignalFields(value, 0)) return true;
46
+ // A fetched HTML page is passed as `data` (or `body`). Scan only for the
47
+ // checkpoint page markers, never for general words.
48
+ const page = typeof value.data === "string" ? value.data : typeof value.body === "string" ? value.body : "";
49
+ return page ? CHECKPOINT_PAGE_MARKER.test(page) : false;
50
+ }
51
+
52
+ function isTransientTransportError(value) {
53
+ if (isSessionEnforcement(value)) return false;
54
+ const text = typeof value === "string" ? value : value && (value.message || value.error || value.code) ? String(value.message || value.error || value.code) : "";
55
+ return TRANSPORT_MARKER.test(text);
56
+ }
57
+
58
+ function createSessionEnforcementError() {
59
+ const error = new Error(
60
+ "Facebook requires manual account review; automatic login and reconnect stopped. Resolve the notice with Facebook before restarting."
61
+ );
62
+ error.name = "SessionVerificationRequiredError";
63
+ error.code = SESSION_ENFORCEMENT_REQUIRED;
64
+ error.requiresManualAction = true;
65
+ return error;
66
+ }
67
+
68
+ function isSessionEnforcementError(value) {
69
+ return Boolean(
70
+ value &&
71
+ typeof value === "object" &&
72
+ (value.code === SESSION_ENFORCEMENT_REQUIRED || value.requiresManualAction === true || isSessionEnforcement(value))
73
+ );
74
+ }
75
+
76
+ module.exports = {
77
+ SESSION_ENFORCEMENT_REQUIRED,
78
+ isSessionEnforcement,
79
+ isTransientTransportError,
80
+ createSessionEnforcementError,
81
+ isSessionEnforcementError
82
+ };