fca-nx 7.4.0 → 7.5.5

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.
@@ -1138,6 +1138,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1138
1138
  ctxMain.performAutoLogin = async () => {
1139
1139
  try {
1140
1140
  try {
1141
+ if (ctxMain._forceFreshLogin) throw { __skipCookieCheck: true };
1141
1142
  let uid = null;
1142
1143
  let transportError = null;
1143
1144
  for (let attempt = 0; attempt < 3 && !uid; attempt++) {
@@ -1162,7 +1163,9 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1162
1163
  }
1163
1164
  if (transportError) throw transportError;
1164
1165
  } catch (checkErr) {
1165
- if (isSessionEnforcementError(checkErr) || isTransientTransportError(checkErr)) throw 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;
1166
1169
  // A non-enforcement response without a usable identity may use the existing credential fallback.
1167
1170
  }
1168
1171
 
package/package.json CHANGED
@@ -1,7 +1,27 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "7.4.0",
3
+ "version": "7.5.5",
4
4
  "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
+ "keywords": [
6
+ "facebook",
7
+ "chat",
8
+ "api",
9
+ "messenger",
10
+ "bot",
11
+ "unofficial",
12
+ "fca",
13
+ "fca-nx",
14
+ "xalman",
15
+ "messenger-bot",
16
+ "chatbot",
17
+ "facebook-api",
18
+ "messenger-chat",
19
+ "mqtt",
20
+ "e2ee",
21
+ "goatbot",
22
+ "unofficial-api",
23
+ "facebook-chat"
24
+ ],
5
25
  "main": "index.js",
6
26
  "types": "index.d.ts",
7
27
  "exports": {
@@ -27,20 +47,6 @@
27
47
  "type": "git",
28
48
  "url": "git+https://github.com/xalmandevv/fca-nx.git"
29
49
  },
30
- "keywords": [
31
- "facebook",
32
- "chat",
33
- "api",
34
- "messenger",
35
- "bot",
36
- "unofficial",
37
- "fca",
38
- "fca-nx",
39
- "xalman",
40
- "messenger-bot",
41
- "chatbot",
42
- "facebook-api"
43
- ],
44
50
  "author": {
45
51
  "name": "XALMAN",
46
52
  "url": "https://github.com/xalmandevv"
@@ -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
+ };
@@ -9,9 +9,11 @@ const { isSessionEnforcement } = require("../../../utils/sessionStatus");
9
9
 
10
10
  const DEFAULT_RECONNECT_DELAY_MS = 8000;
11
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
12
14
  const MAX_RECONNECT_ATTEMPTS = 5; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
13
15
  const MAX_RECONNECT_COOLDOWN_MS = 20 * 60 * 1000; // after exhausting fast retries, wait this long before trying again (never give up permanently)
14
- const T_MS_WAIT_TIMEOUT_MS = 5000;
16
+ const T_MS_WAIT_TIMEOUT_MS = 15000;
15
17
 
16
18
  // Exponential backoff with jitter, based on how many *consecutive* reconnect
17
19
  // attempts have happened for this session (reset to 0 on a successful
@@ -30,8 +32,13 @@ module.exports = function createListenMqtt(deps) {
30
32
  } = deps;
31
33
 
32
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
+ }
33
39
 
34
40
  function scheduleReconnect(delayMs) {
41
+ if (ctx._stoppedForLogin) return;
35
42
  const base = (ctx._mqttOpt && ctx._mqttOpt.reconnectDelayMs) || DEFAULT_RECONNECT_DELAY_MS;
36
43
  if (ctx._reconnectTimer) {
37
44
  logger("mqtt reconnect already scheduled", "warn");
@@ -45,25 +52,45 @@ module.exports = function createListenMqtt(deps) {
45
52
  return;
46
53
  }
47
54
  ctx._reconnectAttempts = (ctx._reconnectAttempts || 0) + 1;
48
- if (ctx._reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
49
- // [Fixed by xalman] Don't give up forever - a run of consecutive failures is usually a
50
- // temporary outage (hosting network blip, FB-side hiccup), not a
51
- // dead account. Back off to a long, FB-friendly cooldown and reset
52
- // the counter so normal exponential backoff resumes after that.
53
- const cooldownMs = MAX_RECONNECT_COOLDOWN_MS;
54
- logger(`mqtt reconnect attempts exceeded (${MAX_RECONNECT_ATTEMPTS}); backing off ${Math.round(cooldownMs / 60000)}min before trying again (not giving up)`, "error");
55
- globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded - will retry after cooldown" }, null);
55
+ if (ctx._reconnectAttempts > RECONNECT_CHECKS) {
56
+ // All quick reconnect checks failed. Do a brand-new login instead of
57
+ // another reconnect: force the credential path (skip the cookie check).
56
58
  ctx._reconnectAttempts = 0;
57
- ctx._reconnectTimer = setTimeout(() => {
59
+ logger(`mqtt ${RECONNECT_CHECKS} reconnect checks failed; starting a fresh login`, "error");
60
+ ctx._reconnectTimer = setTimeout(async () => {
58
61
  ctx._reconnectTimer = null;
59
- if (!ctx._ending) {
62
+ if (ctx._ending) return;
63
+ let ok = false;
64
+ try {
65
+ if (typeof ctx.performAutoLogin === "function") {
66
+ ctx._forceFreshLogin = true;
67
+ ok = await ctx.performAutoLogin();
68
+ }
69
+ } catch (loginErr) {
70
+ logger(`mqtt fresh login failed: ${loginErr && loginErr.message ? loginErr.message : String(loginErr)}`, "error");
71
+ ok = false;
72
+ } finally {
73
+ ctx._forceFreshLogin = false;
74
+ }
75
+ if (ok && !ctx._ending) {
76
+ ctx._stoppedForLogin = false;
60
77
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
78
+ } else {
79
+ ctx._stoppedForLogin = true;
80
+ ctx._ending = true;
81
+ clearTimeout(ctx._reconnectTimer);
82
+ ctx._reconnectTimer = null;
83
+ try {
84
+ if (ctx.mqttClient) ctx.mqttClient.end(true);
85
+ } catch (_) { }
86
+ logger("mqtt stopped: fresh login is not available for this cookie session (no credentials). Refresh appstate and restart the bot.", "error");
87
+ globalCallback({ type: "stop_listen", error: "Fresh login failed after reconnect checks" }, null);
61
88
  }
62
- }, cooldownMs);
89
+ }, 0);
63
90
  return;
64
91
  }
65
- const ms = typeof delayMs === "number" ? delayMs : computeBackoff(ctx, base);
66
- logger(`mqtt will reconnect in ${ms}ms (attempt ${ctx._reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`, "warn");
92
+ const ms = RECONNECT_INTERVAL_MS;
93
+ logger(`mqtt reconnect check ${ctx._reconnectAttempts}/${RECONNECT_CHECKS} in ${ms}ms`, "warn");
67
94
  ctx._reconnectTimer = setTimeout(() => {
68
95
  ctx._reconnectTimer = null;
69
96
  if (!ctx._ending) {
@@ -161,7 +188,18 @@ module.exports = function createListenMqtt(deps) {
161
188
  }
162
189
 
163
190
  if (/Invalid header flag bits|must be 0x0 for puback/i.test(msg)) {
164
- logger(`mqtt puback ignored: ${msg}`, "warn");
191
+ // A malformed puback means the byte stream is out of step. Each one is
192
+ // harmless alone, but a run of them means this connection is dead and
193
+ // the t_ms reply will never come. After 3 in a row, drop and reconnect.
194
+ ctx._badPuback = (ctx._badPuback || 0) + 1;
195
+ logger(`mqtt puback ignored (${ctx._badPuback}/3): ${msg}`, "warn");
196
+ if (ctx._badPuback >= 3) {
197
+ ctx._badPuback = 0;
198
+ try {
199
+ if (mqttClient) mqttClient.end(true);
200
+ } catch (_) { }
201
+ scheduleReconnect();
202
+ }
165
203
  return;
166
204
  }
167
205
 
@@ -225,7 +263,6 @@ module.exports = function createListenMqtt(deps) {
225
263
  // reset the backoff counter so a later transient failure starts a
226
264
  // fresh backoff sequence instead of inheriting a long delay from an
227
265
  // unrelated earlier outage.
228
- ctx._reconnectAttempts = 0;
229
266
 
230
267
  topics.forEach(t => mqttClient.subscribe(t));
231
268
 
@@ -286,6 +323,8 @@ module.exports = function createListenMqtt(deps) {
286
323
  } else if (jsonMessage.type === "jewel_requests_remove_old") {
287
324
  globalCallback(null, { type: "friend_request_cancel", actorFbId: jsonMessage.from.toString(), timestamp: Date.now().toString() });
288
325
  } else if (topic === "/t_ms") {
326
+ ctx._reconnectAttempts = 0;
327
+ ctx._badPuback = 0;
289
328
  if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
290
329
  if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
291
330
  ctx.lastSeqId = jsonMessage.firstDeltaSeqId;
@@ -217,6 +217,7 @@ module.exports = function createGetSeqID(deps) {
217
217
  const MAX_RETRIES = 3;
218
218
  const RETRY_DELAY = 2000;
219
219
  if (ctx._sessionEnforcement) {
220
+ if (ctx._ending) return;
220
221
  return emitAuth(
221
222
  ctx,
222
223
  api,
@@ -225,6 +226,7 @@ module.exports = function createGetSeqID(deps) {
225
226
  "Facebook requires manual account review; automatic login and reconnect stopped."
226
227
  );
227
228
  }
229
+ if (ctx._ending) return;
228
230
  ctx.t_mqttCalled = false;
229
231
 
230
232
  // Ensure essential tokens are injected into GraphQL Batch Payload
@@ -256,6 +258,7 @@ module.exports = function createGetSeqID(deps) {
256
258
  .then(parseAndCheckLogin(ctx, defaultFuncs))
257
259
  .then(async resData => {
258
260
  if (isSessionEnforcement(resData)) {
261
+ if (ctx._ending) return;
259
262
  return emitAuth(
260
263
  ctx,
261
264
  api,
@@ -264,6 +267,17 @@ module.exports = function createGetSeqID(deps) {
264
267
  "Facebook requires manual account review; automatic login and reconnect stopped."
265
268
  );
266
269
  }
270
+ if (ctx._sessionEnforcement) {
271
+ if (ctx._ending) return;
272
+ return emitAuth(
273
+ ctx,
274
+ api,
275
+ globalCallback,
276
+ "verification_required",
277
+ "Facebook requires manual account review; automatic login and reconnect stopped."
278
+ );
279
+ }
280
+ if (ctx._ending) return;
267
281
 
268
282
  // Safe check for non-array responses (such as Error Objects from FB)
269
283
  if (getType(resData) !== "Array") {
@@ -277,8 +291,9 @@ module.exports = function createGetSeqID(deps) {
277
291
  if (errCode === 1357032 || /Something Went Wrong/i.test(errorMsg)) {
278
292
  logger("getSeqID: FB returned error 1357032. Using fallback seqID and continuing to MQTT.", "warn");
279
293
  ctx.lastSeqId = ctx.lastSeqId || "0";
280
- ctx._sessionEnforcement = false; // 7.4.1: a successful login clears a stale stop flag
281
- listenMqtt(defaultFuncs, api, ctx, globalCallback);
294
+ if (!ctx._ending && !ctx._sessionEnforcement) {
295
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
296
+ }
282
297
  return;
283
298
  }
284
299
 
@@ -289,8 +304,9 @@ module.exports = function createGetSeqID(deps) {
289
304
 
290
305
  // Fallback if it's an unrecognized object
291
306
  ctx.lastSeqId = ctx.lastSeqId || "0";
292
- ctx._sessionEnforcement = false; // 7.4.1: a successful login clears a stale stop flag
293
- listenMqtt(defaultFuncs, api, ctx, globalCallback);
307
+ if (!ctx._ending && !ctx._sessionEnforcement) {
308
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
309
+ }
294
310
  return;
295
311
  }
296
312
 
@@ -306,8 +322,9 @@ module.exports = function createGetSeqID(deps) {
306
322
  ctx.lastSeqId = ctx.lastSeqId || "0";
307
323
  logger("getSeqID: sync_sequence_id not found, fallback lastSeqId=" + ctx.lastSeqId, "warn");
308
324
  }
309
- ctx._sessionEnforcement = false; // 7.4.1: a successful login clears a stale stop flag
310
- listenMqtt(defaultFuncs, api, ctx, globalCallback);
325
+ if (!ctx._ending && !ctx._sessionEnforcement) {
326
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
327
+ }
311
328
  })
312
329
  .catch(async err => {
313
330
  if (
@@ -316,6 +333,7 @@ module.exports = function createGetSeqID(deps) {
316
333
  isSessionEnforcement(err && err.originalResponse) ||
317
334
  isSessionEnforcement(err && err.response)
318
335
  ) {
336
+ if (ctx._ending) return;
319
337
  return emitAuth(
320
338
  ctx,
321
339
  api,
@@ -324,6 +342,7 @@ module.exports = function createGetSeqID(deps) {
324
342
  "Facebook requires manual account review; automatic login and reconnect stopped."
325
343
  );
326
344
  }
345
+ if (ctx._sessionEnforcement || ctx._ending) return;
327
346
 
328
347
  const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
329
348
  const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
@@ -340,6 +359,7 @@ module.exports = function createGetSeqID(deps) {
340
359
  const delay = RETRY_DELAY * (retryCount + 1);
341
360
  logger(`getSeqID: network error, retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (${msg})`, "warn");
342
361
  await new Promise(resolve => setTimeout(resolve, delay));
362
+ if (ctx._sessionEnforcement || ctx._ending) return;
343
363
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
344
364
  }
345
365
  logger(`getSeqID: network error persisted after ${MAX_RETRIES} retries, giving up for now: ${msg}`, "error");
@@ -356,6 +376,7 @@ module.exports = function createGetSeqID(deps) {
356
376
  const delay = RETRY_DELAY * (retryCount + 1);
357
377
  logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (error: ${msg})`, "warn");
358
378
  await new Promise(resolve => setTimeout(resolve, delay));
379
+ if (ctx._sessionEnforcement || ctx._ending) return;
359
380
 
360
381
  if (retryCount === 0 && ctx.loggedIn) {
361
382
  try {
@@ -390,10 +411,12 @@ module.exports = function createGetSeqID(deps) {
390
411
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
391
412
  }
392
413
 
414
+ if (ctx._sessionEnforcement || ctx._ending) return;
393
415
  logger("getSeqID: all retries failed, attempting auto re-login...", "warn");
394
416
  const config = getConfig();
395
417
  const loginResult = await tryAutoLogin(logger, config, ctx, defaultFuncs);
396
418
 
419
+ if (ctx._sessionEnforcement || ctx._ending) return;
397
420
  if (loginResult) {
398
421
  logger("getSeqID: retrying with new session...", "info");
399
422
  await new Promise(resolve => setTimeout(resolve, 3000));
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+
3
+ const axios = require("axios");
4
+
5
+ // api.getCoverPhoto(profile, callback?)
6
+ // profile = username, profile URL, or numeric UID
7
+ // Resolves/calls back with { id, name, coverPhoto } where coverPhoto is a URL or null.
8
+ //
9
+ // Lookup goes through a third-party profile API (no session cookies are sent).
10
+ // Override the endpoint with FCA_NX_COVER_LOOKUP_URL (must end with "?profile=" style query base).
11
+ const DEFAULT_LOOKUP_BASE = "https://xalman-apis.vercel.app/api/fbstalk?profile=";
12
+ const LOOKUP_TIMEOUT_MS = 20000;
13
+
14
+ function parseProfileInput(raw) {
15
+ const input = String(raw === undefined || raw === null ? "" : raw).trim();
16
+ if (!input) return null;
17
+
18
+ const idMatch = input.match(/[?&]id=(\d{5,})/);
19
+ if (idMatch) return idMatch[1];
20
+
21
+ if (/^\d{5,}$/.test(input)) return input;
22
+
23
+ const urlMatch = input.match(/facebook\.com\/(?:people\/[^/]+\/)?([^/?#&]+)/i);
24
+ if (urlMatch) {
25
+ const slug = urlMatch[1];
26
+ if (/^\d{5,}$/.test(slug)) return slug;
27
+ if (!["profile.php", "people", "pages"].includes(slug.toLowerCase())) return slug;
28
+ return null;
29
+ }
30
+
31
+ if (/^[A-Za-z0-9.]{3,}$/.test(input)) return input;
32
+
33
+ return null;
34
+ }
35
+
36
+ module.exports = function () {
37
+ return function getCoverPhoto(profile, callback) {
38
+ let resolveFunc = function () {};
39
+ let rejectFunc = function () {};
40
+ const returnPromise = new Promise(function (resolve, reject) {
41
+ resolveFunc = resolve;
42
+ rejectFunc = reject;
43
+ });
44
+
45
+ if (typeof callback !== "function") {
46
+ callback = function (err, data) {
47
+ if (err) return rejectFunc(err);
48
+ resolveFunc(data);
49
+ };
50
+ }
51
+
52
+ const target = parseProfileInput(profile);
53
+ if (!target) {
54
+ callback({ error: "getCoverPhoto: a username, profile URL or numeric UID is required" });
55
+ return returnPromise;
56
+ }
57
+
58
+ const base = process.env.FCA_NX_COVER_LOOKUP_URL || DEFAULT_LOOKUP_BASE;
59
+
60
+ axios
61
+ .get(base + encodeURIComponent(target), {
62
+ timeout: LOOKUP_TIMEOUT_MS,
63
+ validateStatus: () => true
64
+ })
65
+ .then(function (res) {
66
+ const data = res.data || {};
67
+ if (res.status !== 200 || data.status !== true || !data.data) {
68
+ return callback({
69
+ error: "getCoverPhoto: lookup failed: " + (data.message || "HTTP " + res.status)
70
+ });
71
+ }
72
+ return callback(null, {
73
+ id: data.data.entity_id || target,
74
+ name: data.data.name || null,
75
+ coverPhoto: data.data.cover_photo || null
76
+ });
77
+ })
78
+ .catch(function (err) {
79
+ callback({ error: "getCoverPhoto: " + (err && err.message ? err.message : String(err)) });
80
+ });
81
+
82
+ return returnPromise;
83
+ };
84
+ };
85
+
86
+ module.exports.parseProfileInput = parseProfileInput;
@@ -78,6 +78,7 @@ function createFallbackNamespaces(api) {
78
78
  getID: bindOptionalMethod(api, "getUserID"),
79
79
  getInfo: bindOptionalMethod(api, "getUserInfo"),
80
80
  getInfoV2: bindOptionalMethod(api, "getUserInfoV2"),
81
+ getCoverPhoto: bindOptionalMethod(api, "getCoverPhoto"),
81
82
  getFriends: bindOptionalMethod(api, "getFriendsList")
82
83
  }),
83
84
  account: compactNamespace({
@@ -89,6 +90,7 @@ function createFallbackNamespaces(api) {
89
90
  enableAutoSaveAppState: bindOptionalMethod(api, "enableAutoSaveAppState"),
90
91
  getCurrentUserID: bindOptionalMethod(api, "getCurrentUserID"),
91
92
  handleFriendRequest: bindOptionalMethod(api, "handleFriendRequest"),
93
+ acceptFriendRequest: bindOptionalMethod(api, "acceptFriendRequest"),
92
94
  logout: bindOptionalMethod(api, "logout"),
93
95
  refreshDtsg: bindOptionalMethod(api, "refreshFb_dtsg"),
94
96
  changeBlockedStatus: bindOptionalMethod(api, "changeBlockedStatus"),
@@ -1,11 +1,7 @@
1
1
  "use strict";
2
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.
3
+ // Only explicit enforcement signals count. Ordinary page/chat text is not
4
+ // searched for general words such as "checkpoint" or "restricted".
9
5
  const SESSION_ENFORCEMENT_REQUIRED = "SESSION_VERIFICATION_REQUIRED";
10
6
 
11
7
  const CHECKPOINT_PAGE_MARKER =
@@ -14,39 +10,73 @@ const CHECKPOINT_URL = /(?:facebook\.com)?\/checkpoint\/(?:\d|block|[?#]|$)/i;
14
10
  const TRANSPORT_MARKER =
15
11
  /(?: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
12
 
17
- const URL_FIELDS = ["url", "redirect", "redirectUrl", "responseUrl", "location", "href"];
13
+ const URL_FIELDS = ["url", "redirect", "redirectUrl", "responseUrl", "responseURL", "location", "href"];
14
+ const ACCOUNT_STATUS_FIELD_MARKER =
15
+ /^\s*(?:your|this)\s+account\s+(?:is|has been|was)\s+(?:temporarily\s+)?(?:restricted|suspended|disabled|locked)\.?\s*$/i;
16
+ const CHECKPOINT_STATUS_FIELD_MARKER =
17
+ /^\s*checkpoint(?:\s+(?:verification|challenge))?\s+(?:is\s+)?(?:required|needed)\.?\s*$/i;
18
18
  const CODE_FIELDS = ["code", "error", "name"];
19
+ const SUMMARY_FIELDS = [
20
+ "errorSummary",
21
+ "error_summary",
22
+ "errorDescription",
23
+ "error_description",
24
+ "errorMessage",
25
+ "error_message",
26
+ "error",
27
+ "reason"
28
+ ];
29
+ const NESTED_FIELDS = [
30
+ "body",
31
+ "config",
32
+ "data",
33
+ "error",
34
+ "errors",
35
+ "originalResponse",
36
+ "payload",
37
+ "request",
38
+ "res",
39
+ "response"
40
+ ];
19
41
 
20
42
  function isCheckpointUrl(value) {
21
43
  return typeof value === "string" && CHECKPOINT_URL.test(value);
22
44
  }
23
45
 
24
- function hasSignalFields(value, depth) {
25
- if (!value || typeof value !== "object" || depth > 4) return false;
46
+ function hasSignalFields(value, depth, seen) {
47
+ if (typeof value === "string") {
48
+ return CHECKPOINT_PAGE_MARKER.test(value) || isCheckpointUrl(value);
49
+ }
50
+ if (!value || typeof value !== "object" || depth > 5 || seen.has(value)) return false;
51
+ seen.add(value);
52
+ if (Array.isArray(value)) {
53
+ return value.slice(0, 20).some(entry => hasSignalFields(entry, depth + 1, seen));
54
+ }
26
55
  if (value.requiresManualAction === true) return true;
27
56
  for (const key of CODE_FIELDS) {
28
57
  if (value[key] === SESSION_ENFORCEMENT_REQUIRED) return true;
29
58
  }
59
+ for (const key of SUMMARY_FIELDS) {
60
+ if (
61
+ typeof value[key] === "string" &&
62
+ (CHECKPOINT_PAGE_MARKER.test(value[key]) || ACCOUNT_STATUS_FIELD_MARKER.test(value[key]) || CHECKPOINT_STATUS_FIELD_MARKER.test(value[key]))
63
+ ) {
64
+ return true;
65
+ }
66
+ }
67
+ if (typeof value.message === "string" && CHECKPOINT_PAGE_MARKER.test(value.message)) return true;
30
68
  for (const key of URL_FIELDS) {
31
69
  if (isCheckpointUrl(value[key])) return true;
32
70
  }
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;
71
+ // Follow known response/error wrappers, not arbitrary application data.
72
+ for (const key of NESTED_FIELDS) {
73
+ if (hasSignalFields(value[key], depth + 1, seen)) return true;
36
74
  }
37
75
  return false;
38
76
  }
39
77
 
40
78
  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;
79
+ return hasSignalFields(value, 0, new Set());
50
80
  }
51
81
 
52
82
  function isTransientTransportError(value) {