fca-nx 6.7.6 → 6.7.7

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
@@ -380,6 +380,12 @@ login(
380
380
 
381
381
  ```
382
382
  > Email/password authentication may require additional verification.
383
+
384
+ If Facebook returns a checkpoint, security challenge, robot verification, or
385
+ suspension notice, FCA-NX stops automatic login and reconnect attempts and
386
+ returns a `SESSION_VERIFICATION_REQUIRED` error. Complete any account review
387
+ through Facebook directly before starting a new session. This safe-stop behavior
388
+ does not guarantee that an account will avoid restrictions.
383
389
  >
384
390
  # 🧩 API Architecture
385
391
  ```text
@@ -5,11 +5,16 @@ 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
+ createSessionEnforcementError,
16
+ isSessionEnforcementError
17
+ } = require("../src/utils/sessionStatus");
13
18
  const { createRemoteClient } = require("../src/remote/remoteClient");
14
19
  const { config } = loadConfig();
15
20
  const axiosBase = require("axios");
@@ -44,6 +49,17 @@ function parseRegion(html) {
44
49
  }
45
50
  }
46
51
 
52
+ function guardSessionResponse(response) {
53
+ if (isSessionEnforcement(response)) {
54
+ logger(
55
+ chalk.italic("Facebook requires manual verification; automatic login and recovery stopped."),
56
+ "error"
57
+ );
58
+ throw createSessionEnforcementError();
59
+ }
60
+ return response;
61
+ }
62
+
47
63
  function mask(s, keep = 3) {
48
64
  if (!s) return "";
49
65
  const n = s.length;
@@ -520,6 +536,8 @@ async function hydrateJarFromDB(userID, jar) {
520
536
  }
521
537
 
522
538
  async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions, ctxRef, hadAppStateInput = false, jar) {
539
+ guardSessionResponse(currentHtml);
540
+
523
541
  // Helper to validate UID - must be a non-zero positive number string
524
542
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
525
543
 
@@ -566,19 +584,18 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
566
584
  logger("tryAutoLoginIfNeeded: Trying backup from DB...", "info");
567
585
  try {
568
586
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
569
- const resB = (await ctxRef.bypassAutomation(initial, jar)) || initial;
587
+ const resB = (await ctxRef.guardSessionResponse(initial)) || initial;
570
588
  const htmlB = resB && resB.data ? resB.data : "";
571
- if (!htmlB.includes("/checkpoint/block/?next")) {
572
- const htmlUserID = htmlUID(htmlB);
573
- if (isValidUID(htmlUserID)) {
574
- const cookiesB = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
575
- logger(`tryAutoLoginIfNeeded: DB backup session valid, USER_ID=${htmlUserID}`, "info");
576
- return { html: htmlB, cookies: cookiesB, userID: htmlUserID };
577
- } else {
578
- logger(`tryAutoLoginIfNeeded: DB backup session dead (HTML USER_ID=${htmlUserID || "empty"}), will try API login...`, "warn");
579
- }
589
+ const htmlUserID = htmlUID(htmlB);
590
+ if (isValidUID(htmlUserID)) {
591
+ const cookiesB = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
592
+ logger(`tryAutoLoginIfNeeded: DB backup session valid, USER_ID=${htmlUserID}`, "info");
593
+ return { html: htmlB, cookies: cookiesB, userID: htmlUserID };
594
+ } else {
595
+ logger(`tryAutoLoginIfNeeded: DB backup session dead (HTML USER_ID=${htmlUserID || "empty"}), will try API login...`, "warn");
580
596
  }
581
597
  } catch (dbErr) {
598
+ if (isSessionEnforcementError(dbErr)) throw dbErr;
582
599
  logger(`tryAutoLoginIfNeeded: DB backup failed - ${dbErr && dbErr.message ? dbErr.message : String(dbErr)}`, "warn");
583
600
  }
584
601
  }
@@ -601,6 +618,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
601
618
  logger(`tryAutoLoginIfNeeded: Attempting API login for ${u.slice(0, 3)}***...`, "info");
602
619
 
603
620
  const r = await tokens(u, p, tf);
621
+ guardSessionResponse(r);
604
622
  if (!r || !r.status) {
605
623
  throw new Error(r && r.message ? r.message : "API Login failed");
606
624
  }
@@ -667,7 +685,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
667
685
  logger(`tryAutoLoginIfNeeded: Refreshing ${urlToUse} (attempt ${retryCount + 1}/${maxRetries})...`, "info");
668
686
 
669
687
  const initial2 = await get(urlToUse, jar, null, globalOptions).then(saveCookies(jar));
670
- res2 = (await ctxRef.bypassAutomation(initial2, jar)) || initial2;
688
+ res2 = (await ctxRef.guardSessionResponse(initial2)) || initial2;
671
689
  html2 = res2 && res2.data ? res2.data : "";
672
690
 
673
691
  if (html2.includes("/checkpoint/block/?next")) {
@@ -691,7 +709,7 @@ async function tryAutoLoginIfNeeded(currentHtml, currentCookies, globalOptions,
691
709
  break;
692
710
  }
693
711
  } catch (err) {
694
- if (err.message && err.message.includes("Checkpoint")) {
712
+ if (isSessionEnforcementError(err) || (err.message && err.message.includes("Checkpoint"))) {
695
713
  throw err;
696
714
  }
697
715
  if (retryCount < maxRetries - 1) {
@@ -741,10 +759,12 @@ function makeLogin(j, email, password, globalOptions) {
741
759
  const tf = config.credentials?.twofactor || null;
742
760
  if (!u || !p) return;
743
761
  const r = await tokens(u, p, tf);
762
+ guardSessionResponse(r);
744
763
  if (r && r.status && Array.isArray(r.cookies)) {
745
764
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
746
765
  setJarFromPairs(j, pairs, ".facebook.com");
747
- await get("https://www.facebook.com/", j, null, globalOptions).then(saveCookies(j));
766
+ const response = await get("https://www.facebook.com/", j, null, globalOptions).then(saveCookies(j));
767
+ guardSessionResponse(response);
748
768
  } else {
749
769
  throw new Error(r && r.message ? r.message : "Login failed");
750
770
  }
@@ -843,66 +863,18 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
843
863
  return callback(e);
844
864
  }
845
865
  const ctx = { globalOptions, options: globalOptions, reconnectAttempts: 0 };
846
- ctx.bypassAutomation = async function (resp, j) {
847
- global.fca = global.fca || {};
848
- global.fca.BypassAutomationNotification = this.bypassAutomation.bind(this);
849
- const s = x => (typeof x === "string" ? x : String(x ?? ""));
850
- const u = r => r?.request?.res?.responseUrl || (r?.config?.baseURL ? new URL(r.config.url || "/", r.config.baseURL).toString() : r?.config?.url || "");
851
- const isCp = r => typeof u(r) === "string" && u(r).includes("checkpoint/601051028565049");
852
- const cookieUID = async () => {
853
- try {
854
- const cookies = typeof j?.getCookies === "function" ? await j.getCookies("https://www.facebook.com") : [];
855
- return cookies.find(c => c.key === "i_user")?.value || cookies.find(c => c.key === "c_user")?.value;
856
- } catch { return undefined; }
857
- };
858
- const htmlUID = body => s(body).match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s(body).match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
859
- const getUID = async body => (await cookieUID()) || htmlUID(body);
860
- const refreshJar = async () => get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
861
- const bypass = async body => {
862
- const b = s(body);
863
- const UID = await getUID(b);
864
- const fb_dtsg = getFrom(b, '"DTSGInitData",[],{"token":"', '",') || b.match(/name="fb_dtsg"\s+value="([^"]+)"/)?.[1];
865
- const jazoest = getFrom(b, 'name="jazoest" value="', '"') || getFrom(b, "jazoest=", '",') || b.match(/name="jazoest"\s+value="([^"]+)"/)?.[1];
866
- const lsd = getFrom(b, '["LSD",[],{"token":"', '"}') || b.match(/name="lsd"\s+value="([^"]+)"/)?.[1];
867
- 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 };
868
- await post("https://www.facebook.com/api/graphql/", j, form, null, this.options).then(saveCookies(j));
869
- logger("⚠️ Facebook automation detected — bypassing...", "warn");
870
- this.reconnectAttempts = 0;
871
- };
872
- try {
873
- if (resp) {
874
- if (isCp(resp)) {
875
- await bypass(s(resp.data));
876
- const refreshed = await refreshJar();
877
- if (isCp(refreshed)) logger("Checkpoint still present after refresh", "warn");
878
- else logger("✅ Bypass complete — session restored.", "info");
879
- return refreshed;
880
- }
881
- return resp;
882
- }
883
- const first = await get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
884
- if (isCp(first)) {
885
- await bypass(s(first.data));
886
- const refreshed = await refreshJar();
887
- if (!isCp(refreshed)) logger("✅ Bypass complete — session restored.", "info");
888
- else logger("Checkpoint still present after refresh", "warn");
889
- return refreshed;
890
- }
891
- return first;
892
- } catch (e) {
893
- logger(`Bypass automation error: ${e && e.message ? e.message : String(e)}`, "error");
894
- return resp;
895
- }
866
+ ctx.guardSessionResponse = async function (response) {
867
+ return guardSessionResponse(response);
896
868
  };
897
869
  if (appState || Cookie) {
898
870
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
899
- return (await ctx.bypassAutomation(initial, jar)) || initial;
871
+ return (await ctx.guardSessionResponse(initial, jar)) || initial;
900
872
  }
901
873
  const hydrated = await hydrateJarFromDB(null, jar);
902
874
  if (hydrated) {
903
875
  logger(chalk.italic("🔄 AppState backup found — restoring session..."), "info");
904
876
  const initial = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
905
- return (await ctx.bypassAutomation(initial, jar)) || initial;
877
+ return (await ctx.guardSessionResponse(initial, jar)) || initial;
906
878
  }
907
879
  logger(chalk.italic("😐 AppState expired — logging in with credentials..."), "warn");
908
880
  return get("https://www.facebook.com/", null, null, globalOptions)
@@ -915,45 +887,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
915
887
  .then(async function (res) {
916
888
  const ctx = {};
917
889
  ctx.options = globalOptions;
918
- ctx.bypassAutomation = async function (resp, j) {
919
- global.fca = global.fca || {};
920
- global.fca.BypassAutomationNotification = this.bypassAutomation.bind(this);
921
- const s = x => (typeof x === "string" ? x : String(x ?? ""));
922
- const u = r => r?.request?.res?.responseUrl || (r?.config?.baseURL ? new URL(r.config.url || "/", r.config.baseURL).toString() : r?.config?.url || "");
923
- const isCp = r => typeof u(r) === "string" && u(r).includes("checkpoint/601051028565049");
924
- const cookieUID = async () => {
925
- try {
926
- const cookies = typeof j?.getCookies === "function" ? await j.getCookies("https://www.facebook.com") : [];
927
- return cookies.find(c => c.key === "i_user")?.value || cookies.find(c => c.key === "c_user")?.value;
928
- } catch { return undefined; }
929
- };
930
- const htmlUID = body => s(body).match(/"USER_ID"\s*:\s*"(\d+)"/)?.[1] || s(body).match(/\["CurrentUserInitialData",\[\],\{.*?"USER_ID":"(\d+)".*?\},\d+\]/)?.[1];
931
- const getUID = async body => (await cookieUID()) || htmlUID(body);
932
- const refreshJar = async () => get("https://www.facebook.com/", j, null, this.options).then(saveCookies(j));
933
- const bypass = async body => {
934
- const b = s(body);
935
- const UID = await getUID(b);
936
- const fb_dtsg = getFrom(b, '"DTSGInitData",[],{"token":"', '",') || b.match(/name="fb_dtsg"\s+value="([^"]+)"/)?.[1];
937
- const jazoest = getFrom(b, 'name="jazoest" value="', '"') || getFrom(b, "jazoest=", '",') || b.match(/name="jazoest"\s+value="([^"]+)"/)?.[1];
938
- const lsd = getFrom(b, '["LSD",[],{"token":"', '"}') || b.match(/name="lsd"\s+value="([^"]+)"/)?.[1];
939
- 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 };
940
- await post("https://www.facebook.com/api/graphql/", j, form, null, this.options).then(saveCookies(j));
941
- logger("⚠️ Facebook automation detected — bypassing...", "warn");
942
- };
943
- try {
944
- if (res && isCp(res)) {
945
- await bypass(s(res.data));
946
- const refreshed = await refreshJar();
947
- if (!isCp(refreshed)) logger("✅ Bypass complete — session restored.", "info");
948
- return refreshed;
949
- }
950
- logger("✅ No checkpoint detected — session is clean.", "info");
951
- return res;
952
- } catch {
953
- return res;
954
- }
890
+ ctx.guardSessionResponse = async function (response) {
891
+ return guardSessionResponse(response);
955
892
  };
956
- const processed = (await ctx.bypassAutomation(res, jar)) || res;
893
+ const processed = (await ctx.guardSessionResponse(res)) || res;
957
894
  let html = processed && processed.data ? processed.data : "";
958
895
  let cookies = await Promise.resolve(jar.getCookies("https://www.facebook.com"));
959
896
  const getUIDFromCookies = cs =>
@@ -1167,7 +1104,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1167
1104
  _emitter: emitter
1168
1105
  };
1169
1106
  ctxMain.options = globalOptions;
1170
- ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1107
+ ctxMain.guardSessionResponse = ctx.guardSessionResponse;
1171
1108
  ctxMain.performAutoLogin = async () => {
1172
1109
  try {
1173
1110
  // [Fixed by xalman] First check whether the existing cookie session is actually
@@ -1187,6 +1124,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1187
1124
  for (let attempt = 0; attempt < 3 && !uid; attempt++) {
1188
1125
  try {
1189
1126
  const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1127
+ guardSessionResponse(check);
1190
1128
  const html = check && check.data ? String(check.data) : "";
1191
1129
  stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1192
1130
  const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
@@ -1194,7 +1132,8 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1194
1132
  uid = uidMatch[1];
1195
1133
  break;
1196
1134
  }
1197
- } catch {
1135
+ } catch (checkErr) {
1136
+ if (isSessionEnforcementError(checkErr)) throw checkErr;
1198
1137
  // network hiccup on this attempt - retry below instead of
1199
1138
  // immediately assuming the session is dead
1200
1139
  }
@@ -1204,7 +1143,8 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1204
1143
  logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1205
1144
  return true;
1206
1145
  }
1207
- } catch {
1146
+ } catch (checkErr) {
1147
+ if (isSessionEnforcementError(checkErr)) throw checkErr;
1208
1148
  // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1209
1149
  }
1210
1150
 
@@ -1213,12 +1153,15 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1213
1153
  const tf = config.credentials?.twofactor || null;
1214
1154
  if (!u || !p) return false;
1215
1155
  const r = await tokens(u, p, tf);
1156
+ guardSessionResponse(r);
1216
1157
  if (!(r && r.status && Array.isArray(r.cookies))) return false;
1217
1158
  const pairs = r.cookies.map(c => `${c.key || c.name}=${c.value}`);
1218
1159
  setJarFromPairs(jar, pairs, ".facebook.com");
1219
- await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1160
+ const response = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1161
+ guardSessionResponse(response);
1220
1162
  return true;
1221
- } catch {
1163
+ } catch (loginErr) {
1164
+ if (isSessionEnforcementError(loginErr)) throw loginErr;
1222
1165
  return false;
1223
1166
  }
1224
1167
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.6",
3
+ "version": "6.7.7",
4
4
  "description": "Facebook Messenger API for Node.js \u2014 anti-logout hardened (soft session recovery, keepalive, safe MQTT)",
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 = 2000;
10
11
  const MAX_RECONNECT_DELAY_MS = 60000;
@@ -184,6 +185,16 @@ module.exports = function createListenMqtt(deps) {
184
185
  return;
185
186
  }
186
187
 
188
+ if (isSessionEnforcement(err)) {
189
+ return emitAuth(
190
+ ctx,
191
+ api,
192
+ globalCallback,
193
+ "verification_required",
194
+ "Facebook requires manual account verification; automatic reconnect stopped."
195
+ );
196
+ }
197
+
187
198
  if (/Not logged in|Not logged in.|blocked the login|401|403/i.test(msg)) {
188
199
  try {
189
200
  if (mqttClient && mqttClient.connected) {
@@ -8,6 +8,11 @@ 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
+ createSessionEnforcementError,
14
+ isSessionEnforcementError
15
+ } = require("../../../utils/sessionStatus");
11
16
 
12
17
  function getConfig() {
13
18
  try {
@@ -62,6 +67,9 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
62
67
  twofactor,
63
68
  config.apiServer || null
64
69
  );
70
+ if (isSessionEnforcement(result)) {
71
+ throw createSessionEnforcementError();
72
+ }
65
73
 
66
74
  if (result && result.status) {
67
75
  const normalizeCookieHeaderString = loginHelper.normalizeCookieHeaderString;
@@ -130,6 +138,9 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
130
138
  logger(`getSeqID: Refreshing ${urlToUse} (attempt ${attempt + 1}/3)...`, "info");
131
139
 
132
140
  webResponse = await get(urlToUse, ctx.jar, null, ctx.globalOptions, ctx);
141
+ if (isSessionEnforcement(webResponse)) {
142
+ throw createSessionEnforcementError();
143
+ }
133
144
  if (webResponse && webResponse.data) {
134
145
  await saveWebCookies(ctx.jar)(webResponse);
135
146
  htmlContent = typeof webResponse.data === "string" ? webResponse.data : String(webResponse.data || "");
@@ -183,6 +194,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
183
194
 
184
195
  logger(`getSeqID: auto re-login failed - ${result && result.message ? result.message : "unknown error"}`, "error");
185
196
  } catch (loginErr) {
197
+ if (isSessionEnforcementError(loginErr)) throw loginErr;
186
198
  logger(`getSeqID: auto re-login error - ${loginErr && loginErr.message ? loginErr.message : String(loginErr)}`, "error");
187
199
  }
188
200
 
@@ -225,6 +237,16 @@ module.exports = function createGetSeqID(deps) {
225
237
  .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
226
238
  .then(parseAndCheckLogin(ctx, defaultFuncs))
227
239
  .then(async resData => {
240
+ if (isSessionEnforcement(resData)) {
241
+ return emitAuth(
242
+ ctx,
243
+ api,
244
+ globalCallback,
245
+ "verification_required",
246
+ "Facebook requires manual account verification; automatic recovery stopped."
247
+ );
248
+ }
249
+
228
250
  // Safe check for non-array responses (such as Error Objects from FB)
229
251
  if (getType(resData) !== "Array") {
230
252
  logger(`getSeqID: Response is not Array, received: ${getType(resData)}`, "warn");
@@ -267,6 +289,21 @@ module.exports = function createGetSeqID(deps) {
267
289
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
268
290
  })
269
291
  .catch(async err => {
292
+ if (
293
+ isSessionEnforcementError(err) ||
294
+ isSessionEnforcement(err) ||
295
+ isSessionEnforcement(err && err.originalResponse) ||
296
+ isSessionEnforcement(err && err.response)
297
+ ) {
298
+ return emitAuth(
299
+ ctx,
300
+ api,
301
+ globalCallback,
302
+ "verification_required",
303
+ "Facebook requires manual account verification; automatic recovery stopped."
304
+ );
305
+ }
306
+
270
307
  const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
271
308
  const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
272
309
 
@@ -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,23 @@ 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
+ if (ctx._sessionEnforcement) {
23
+ throw createSessionEnforcementError();
24
+ }
25
+
26
+ const responseUrl = resConfig ? buildUrl(resConfig) : "";
27
+ if (isSessionEnforcement(resData) || isSessionEnforcement(responseUrl)) {
28
+ ctx._sessionEnforcement = true;
29
+ const error = createSessionEnforcementError();
30
+ if (typeof emit === "function") {
31
+ emit("verificationRequired", {
32
+ code: error.code,
33
+ message: error.message
34
+ });
35
+ }
36
+ throw error;
37
+ }
38
+
17
39
  const retryAfterLogin = async function () {
18
40
  if (!resConfig) {
19
41
  const e = new Error(
@@ -42,6 +64,10 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
42
64
  }
43
65
  return await parseAndCheckLogin(ctx, http)(newData);
44
66
  } catch (retryErr) {
67
+ if (isSessionEnforcementError(retryErr)) {
68
+ ctx._sessionEnforcement = true;
69
+ throw retryErr;
70
+ }
45
71
  if (
46
72
  retryErr?.code === "ERR_INVALID_CHAR" ||
47
73
  (retryErr?.message && retryErr.message.includes("Invalid character in header"))
@@ -79,6 +105,10 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
79
105
  try {
80
106
  ok = await ctx._autoLoginPromise;
81
107
  } catch (autoLoginErr) {
108
+ if (isSessionEnforcementError(autoLoginErr)) {
109
+ ctx._sessionEnforcement = true;
110
+ throw autoLoginErr;
111
+ }
82
112
  const e = new Error("Not logged in. Auto login failed.");
83
113
  e.error = "Not logged in.";
84
114
  e.res = resData;
@@ -122,6 +152,14 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
122
152
  throw e;
123
153
  }
124
154
  } catch (autoLoginErr) {
155
+ if (isSessionEnforcementError(autoLoginErr)) {
156
+ ctx._sessionEnforcement = true;
157
+ emit("verificationRequired", {
158
+ code: autoLoginErr.code,
159
+ message: autoLoginErr.message
160
+ });
161
+ throw autoLoginErr;
162
+ }
125
163
  if (autoLoginErr.error === "Not logged in.") {
126
164
  throw autoLoginErr;
127
165
  }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+
3
+ const RESPONSE_FIELDS = [
4
+ "url",
5
+ "responseUrl",
6
+ "location",
7
+ "redirect",
8
+ "config",
9
+ "message",
10
+ "error",
11
+ "errorSummary",
12
+ "errorDescription",
13
+ "reason",
14
+ "data",
15
+ "body",
16
+ "text",
17
+ "response",
18
+ "originalResponse",
19
+ "request",
20
+ "res"
21
+ ];
22
+
23
+ const ENFORCEMENT_MARKER =
24
+ /(?:\/checkpoint(?:\/|[?#])|XCheckpointFBScrapingWarningController|checkpoint_(?:282|956)\b|blocked the login|manual account verification|(?:account|profile)\b[\s\S]{0,50}\b(?:suspended|disabled)\b|\b(?:suspended|disabled)\s+(?:your|this|the)\s+(?:account|profile)\b|robot verification|security check required|confirm (?:that )?you(?:'re| are) (?:a human|not a robot))/i;
25
+
26
+ function collectResponseText(value, seen = new Set(), depth = 0) {
27
+ if (value === null || value === undefined || depth > 4) return "";
28
+ if (typeof value === "string") return value;
29
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
30
+ if (Buffer.isBuffer(value)) return value.toString("utf8");
31
+ if (typeof value !== "object" || seen.has(value)) return "";
32
+
33
+ seen.add(value);
34
+ if (Array.isArray(value)) {
35
+ return value
36
+ .slice(0, 20)
37
+ .map(item => collectResponseText(item, seen, depth + 1))
38
+ .join("\n");
39
+ }
40
+
41
+ return RESPONSE_FIELDS
42
+ .filter(key => Object.prototype.hasOwnProperty.call(value, key))
43
+ .map(key => collectResponseText(value[key], seen, depth + 1))
44
+ .join("\n");
45
+ }
46
+
47
+ function isSessionEnforcement(value) {
48
+ return ENFORCEMENT_MARKER.test(collectResponseText(value));
49
+ }
50
+
51
+ function createSessionEnforcementError() {
52
+ const error = new Error(
53
+ "Facebook requires manual account verification; automatic login and recovery stopped."
54
+ );
55
+ error.code = "SESSION_VERIFICATION_REQUIRED";
56
+ error.isSessionEnforcement = true;
57
+ return error;
58
+ }
59
+
60
+ function isSessionEnforcementError(error) {
61
+ return Boolean(
62
+ error &&
63
+ (error.code === "SESSION_VERIFICATION_REQUIRED" ||
64
+ error.isSessionEnforcement === true)
65
+ );
66
+ }
67
+
68
+ module.exports = {
69
+ isSessionEnforcement,
70
+ createSessionEnforcementError,
71
+ isSessionEnforcementError
72
+ };