fca-nx 7.5.5 → 7.6.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
@@ -142,6 +142,34 @@ api.sendMessage("Hello world!", threadID);
142
142
  Bubble effects (`gift`, `fire`, `love`, `textEffect`, `text_effect_ids`) are no longer sent.
143
143
  Passing those keys is ignored; the client does not currently provide a documented Meta-supported effects API.
144
144
 
145
+ ### Session repair (7.6.0)
146
+
147
+ Software bugs that looked like random logouts are fixed. Facebook checkpoints, two-factor challenges, rate limits, and account restrictions are **not** bypassed.
148
+
149
+ - Cookie values that contain `=` are preserved, and Chrome `expirationDate` seconds are no longer saved as already-expired dates.
150
+ - MQTT reconnects with backoff and cooldown. A dropped socket does **not** start a new credential login.
151
+ - Quiet sockets are not recycled every 30 seconds.
152
+ - `"autoLogin": true` is required before one credential retry, and it will not loop.
153
+ - `classifyError(err)` returns `code`, `category`, `message`, and `recovery`. See [docs/ERRORS.md](docs/ERRORS.md), [docs/LIMITATIONS.md](docs/LIMITATIONS.md), and [CHANGELOG.md](CHANGELOG.md).
154
+
155
+ ```javascript
156
+ const { login, classifyError } = require("fca-nx");
157
+
158
+ login({ appState }, (err, api) => {
159
+ if (err) {
160
+ const info = classifyError(err);
161
+ console.error(info.category, info.recovery);
162
+ return;
163
+ }
164
+ api.listenMqtt((listenErr, event) => {
165
+ if (listenErr) {
166
+ console.error(listenErr.type || listenErr.category || listenErr);
167
+ return;
168
+ }
169
+ });
170
+ });
171
+ ```
172
+
145
173
  ### Session and profile-data safety (7.4.0)
146
174
  - Explicit checkpoint, account restriction, or manual-verification responses stop automatic login and MQTT reconnect. FCA-NX does not attempt to bypass those notices.
147
175
  - Temporary network failures remain separate from account-verification signals and use the existing bounded retry behavior.
package/docs/ERRORS.md ADDED
@@ -0,0 +1,46 @@
1
+ # Error catalogue
2
+
3
+ `classifyError(error)` and login callbacks expose these fields:
4
+
5
+ | Field | Meaning |
6
+ |---|---|
7
+ | `code` | Stable machine code |
8
+ | `category` | Group used for branching |
9
+ | `message` | What happened |
10
+ | `recovery` | What a person can legitimately do next |
11
+ | `diagnostic` | Short sanitized detail, never a cookie or password |
12
+
13
+ ## Categories
14
+
15
+ | Category | Code | What to do |
16
+ |---|---|---|
17
+ | `checkpoint` | `SESSION_VERIFICATION_REQUIRED` | Finish the checkpoint in a browser. Export a new appstate. Do not automate the challenge. |
18
+ | `account_restriction` | `SESSION_VERIFICATION_REQUIRED` | Facebook restricted the account. Resolve it with Facebook. Package changes cannot lift it. |
19
+ | `two_factor_required` | `TWO_FACTOR_REQUIRED` | Enter the code in a browser or authenticator, then export a new appstate. |
20
+ | `session_expired` | `SESSION_EXPIRED` | The saved cookies are dead. Replace `appstate.json`. Stop reconnecting the old file. |
21
+ | `authentication_failure` | varies | Check the appstate. A wrong or partial cookie set fails before MQTT starts. |
22
+ | `rate_limit` | `RATE_LIMITED` | Wait. Reduce send rate. Do not open more sessions for the same account. |
23
+ | `security_challenge` | `SESSION_VERIFICATION_REQUIRED` | Same as a checkpoint: a person has to complete it. |
24
+ | `permission` | `PERMISSION` | The account cannot perform that action. Confirm it in Messenger. |
25
+ | `invalid_request` | `INVALID_APPSTATE` or `INVALID_REQUEST` | Fix the arguments or the appstate shape. |
26
+ | `network` | `NETWORK` | Connectivity failed. This is not a logout. The same session is reused. |
27
+ | `platform_outage` | `PLATFORM_UNAVAILABLE` | Facebook returned 502/503/504. Wait and retry the same session. |
28
+ | `unsupported_endpoint` | `LEGACY_SEND_REJECTED` | The old `/messaging/send/` fallback rejected the reply. The MQTT session was not logged out. Retry the send. |
29
+ | `unknown` | `UNKNOWN` | Read `code` and `diagnostic`. Do not assume the account was banned. |
30
+
31
+ ## MQTT events
32
+
33
+ | Event | Meaning |
34
+ |---|---|
35
+ | `account_inactive` with `not_logged_in` | The saved session was rejected twice. Refresh the appstate. |
36
+ | `account_inactive` with `login_blocked` or `verification_required` | Stop. Manual review is required. |
37
+ | `mqtt_reconnect_cooldown` | Network retries were exhausted. The process waits, then reconnects the same session. |
38
+
39
+ ## Explicit non-goals
40
+
41
+ This package will not:
42
+
43
+ - solve a checkpoint, captcha, or two-factor challenge
44
+ - spoof a browser fingerprint or device identity
45
+ - keep retrying a credential login until Facebook accepts it
46
+ - claim that a code change removes an account restriction
@@ -0,0 +1,32 @@
1
+ # Known limitations
2
+
3
+ ## Platform limits
4
+
5
+ FCA-NX is an unofficial client. Facebook can expire a session, show a checkpoint, require two-factor authentication, rate-limit traffic, or restrict an account. None of those are fixed by this package. When that happens, the process stops or backs off and reports the category from `docs/ERRORS.md`.
6
+
7
+ ## Not covered by automated tests
8
+
9
+ These tests do not call Facebook:
10
+
11
+ - live login
12
+ - live MQTT delivery
13
+ - sending messages, attachments, or reactions
14
+ - E2EE device registration
15
+ - database backup against a real SQLite file (the optional `sqlite3` build)
16
+
17
+ Passed tests only prove the local logic listed in `CHANGELOG.md`.
18
+
19
+ ## Credential login
20
+
21
+ Email and password login is sent only to an `apiServer` you configure. There is no built-in default server. Prefer an appstate from a browser session you control. `"autoLogin": true` is required before a dead session may try that credential path, and it is attempted once per process session.
22
+
23
+ ## Sessions
24
+
25
+ - A usable saved session needs at least `c_user` and `xs`, and the on-disk guard also expects five cookies before it overwrites a file.
26
+ - Two accounts in one database are not restored anonymously.
27
+ - The shared Axios client still has a process-wide fallback jar. Login itself uses a jar created for that call.
28
+ - Global `unhandledRejection` and `uncaughtException` handlers are still installed so a bot process does not die on a network rejection. They redact secrets. Unknown exceptions are logged and the process continues; a supervisor that restarts on crash is safer for fatal bugs.
29
+
30
+ ## Endpoints
31
+
32
+ Existing Messenger calls are preserved. Missing or removed product features, including bubble effects and Graph cover photos, stay removed. This release does not add undocumented endpoints.
package/index.d.ts CHANGED
@@ -100,6 +100,23 @@ export function attachThreadInfoRealtimeSync(
100
100
  api: FcaApi,
101
101
  options?: ThreadInfoSyncOptions
102
102
  ): () => void;
103
+ export interface ClassifiedErrorFields {
104
+ code: string;
105
+ category: string;
106
+ message: string;
107
+ recovery: string;
108
+ diagnostic?: string;
109
+ }
110
+
111
+ export class FcaError extends Error {
112
+ code: string;
113
+ category: string;
114
+ recovery: string;
115
+ diagnostic: string;
116
+ }
117
+
118
+ export function classifyError(input: unknown): FcaError;
119
+
103
120
  export function applyThreadInfoRealtimeEvent(
104
121
  api: FcaApi,
105
122
  event: any,
@@ -115,6 +132,8 @@ declare const exportedLogin: typeof login & {
115
132
  MessengerContext: typeof MessengerContext;
116
133
  attachThreadInfoRealtimeSync: typeof attachThreadInfoRealtimeSync;
117
134
  applyThreadInfoRealtimeEvent: typeof applyThreadInfoRealtimeEvent;
135
+ classifyError: typeof classifyError;
136
+ FcaError: typeof FcaError;
118
137
  };
119
138
 
120
139
  export = exportedLogin;
package/index.js CHANGED
@@ -20,3 +20,7 @@ module.exports.createMessengerBot = createMessengerBot;
20
20
  module.exports.MessengerContext = MessengerContext;
21
21
  module.exports.attachThreadInfoRealtimeSync = attachThreadInfoRealtimeSync;
22
22
  module.exports.applyThreadInfoRealtimeEvent = applyThreadInfoRealtimeEvent;
23
+ const { classifyError, FcaError } = require("./src/utils/fcaError");
24
+
25
+ module.exports.classifyError = classifyError;
26
+ module.exports.FcaError = FcaError;
package/module/login.js CHANGED
@@ -4,6 +4,8 @@ const { loadConfig } = require("./config");
4
4
  const { checkAndUpdateVersion } = require("../func/checkUpdate");
5
5
  const loginHelper = require("./loginHelper");
6
6
  const logger = require("../func/logger");
7
+ const { sanitizeForLog } = require("../src/utils/logSanitize");
8
+ const { isSessionEnforcementError } = require("../src/utils/sessionStatus");
7
9
  const { DEFAULT_IDENTITY } = require("../src/utils/clientIdentity");
8
10
 
9
11
  const { config } = loadConfig();
@@ -31,7 +33,7 @@ if (!global.fca._errorHandlersInstalled) {
31
33
  errorCode === "ETIMEDOUT" ||
32
34
  errorMessage.includes("Connect Timeout") ||
33
35
  errorMessage.includes("fetch failed")) {
34
- logger(`Network timeout error caught (non-fatal): ${errorMessage}`, "warn");
36
+ logger(`Network timeout error caught (non-fatal): ${sanitizeForLog(errorMessage)}`, "warn");
35
37
  return; // Don't crash, just log
36
38
  }
37
39
 
@@ -41,19 +43,21 @@ if (!global.fca._errorHandlersInstalled) {
41
43
  errorCode === "ECONNRESET" ||
42
44
  errorMessage.includes("ECONNREFUSED") ||
43
45
  errorMessage.includes("ENOTFOUND")) {
44
- logger(`Network connection error caught (non-fatal): ${errorMessage}`, "warn");
46
+ logger(`Network connection error caught (non-fatal): ${sanitizeForLog(errorMessage)}`, "warn");
45
47
  return; // Don't crash, just log
46
48
  }
47
49
  }
48
50
 
49
- // [Fixed by xalman] For other unhandled rejections, log but don't crash.
50
- // Include the stack (when available) - logging only `.message` made
51
- // real bugs impossible to trace back to where they were thrown.
52
- const errorDetail = reason && reason.stack ? reason.stack : (reason && reason.message ? reason.message : String(reason));
51
+ if (isSessionEnforcementError(reason)) {
52
+ logger(`Session needs manual review. Automatic recovery stopped. ${sanitizeForLog(reason && reason.message)}`, "error");
53
+ return;
54
+ }
55
+
56
+ const errorDetail = sanitizeForLog(reason);
53
57
  logger(`Unhandled promise rejection (non-fatal): ${errorDetail}`, "error");
54
58
  } catch (e) {
55
59
  // Logger itself failed - fall back to stderr so this isn't silently lost.
56
- try { console.error("[fca-nx] logger failed while handling unhandledRejection:", e, reason); } catch { }
60
+ try { console.error("[fca-nx] logger failed while handling unhandledRejection:", e && e.message ? e.message : e); } catch { }
57
61
  }
58
62
  });
59
63
 
@@ -73,13 +77,16 @@ if (!global.fca._errorHandlersInstalled) {
73
77
  errorCode === "ETIMEDOUT" ||
74
78
  errorMessage.includes("Connect Timeout") ||
75
79
  errorMessage.includes("fetch failed")) {
76
- logger(`Uncaught network timeout error (non-fatal): ${errorMessage}`, "warn");
80
+ logger(`Uncaught network timeout error (non-fatal): ${sanitizeForLog(errorMessage)}`, "warn");
77
81
  return; // Don't crash
78
82
  }
79
83
 
80
- // [Fixed by xalman] For other uncaught exceptions, log but try to continue.
81
- // Include the stack trace - without it these were undebuggable in production.
82
- logger(`Uncaught exception (attempting to continue): ${error && error.stack ? error.stack : errorMessage}`, "error");
84
+ if (isSessionEnforcementError(error)) {
85
+ logger(`Uncaught session review error. Automatic recovery stopped. ${sanitizeForLog(error && error.message)}`, "error");
86
+ return;
87
+ }
88
+
89
+ logger(`Uncaught exception (attempting to continue): ${sanitizeForLog(error)}`, "error");
83
90
  // Note: We don't exit here to allow bot to continue running.
84
91
  // This trades crash-safety for the (small) risk of continuing in a
85
92
  // partially-inconsistent process state. If you run this under a process
@@ -87,7 +94,7 @@ if (!global.fca._errorHandlersInstalled) {
87
94
  // process.exit(1) here instead for a clean restart on truly unknown errors.
88
95
  } catch (e) {
89
96
  // Logger itself failed - fall back to stderr so this isn't silently lost.
90
- try { console.error("[fca-nx] logger failed while handling uncaughtException:", e, error); } catch { }
97
+ try { console.error("[fca-nx] logger failed while handling uncaughtException:", e && e.message ? e.message : e); } catch { }
91
98
  }
92
99
  });
93
100
  }
@@ -16,6 +16,8 @@ const {
16
16
  createSessionEnforcementError,
17
17
  isSessionEnforcementError
18
18
  } = require("../src/utils/sessionStatus");
19
+ const { parseAppStateInput, buildSetCookie } = require("../src/utils/appStateCookies");
20
+ const { annotateError } = require("../src/utils/fcaError");
19
21
  const { createRemoteClient } = require("../src/remote/remoteClient");
20
22
  const { config } = loadConfig();
21
23
  const axiosBase = require("axios");
@@ -385,11 +387,17 @@ async function upsertBackup(Model, userID, type, data) {
385
387
 
386
388
  async function backupAppStateSQL(j, userID) {
387
389
  try {
390
+ if (models && typeof models.ensureReady === "function") {
391
+ await models.ensureReady();
392
+ }
388
393
  const Model = getBackupModel();
389
394
  if (!Model) return;
390
395
  if (!models || !models.sequelize) return;
391
- await Model.sync();
392
- await ensureUniqueIndex(models.sequelize);
396
+ if (!backupAppStateSQL._synced) {
397
+ await Model.sync();
398
+ await ensureUniqueIndex(models.sequelize);
399
+ backupAppStateSQL._synced = true;
400
+ }
393
401
  const appJson = getAppState(j);
394
402
  const ck = cookieHeaderFromJar(j);
395
403
  await upsertBackup(Model, userID, "appstate", JSON.stringify(appJson));
@@ -424,90 +432,65 @@ async function getLatestBackupAny(type) {
424
432
 
425
433
 
426
434
 
427
- async function setJarCookies(j, appstate) {
428
- const tasks = [];
429
- for (const c of appstate) {
430
- const cookieName = c.name || c.key;
431
- const cookieValue = c.value;
432
- if (!cookieName || cookieValue === undefined) continue;
433
-
434
- const cookieDomain = c.domain || ".facebook.com";
435
- const cookiePath = c.path || "/";
436
- const dom = cookieDomain.replace(/^\./, "");
437
-
438
- // Handle expirationDate (can be in seconds or milliseconds)
439
- let expiresStr = "";
440
- if (c.expirationDate !== undefined) {
441
- let expiresDate;
442
- if (typeof c.expirationDate === "number") {
443
- // If expirationDate is less than a year from now in seconds, treat as seconds
444
- // Otherwise treat as milliseconds
445
- const now = Date.now();
446
- const oneYearInMs = 365 * 24 * 60 * 60 * 1000;
447
- if (c.expirationDate < (now + oneYearInMs) / 1000) {
448
- expiresDate = new Date(c.expirationDate * 1000);
449
- } else {
450
- expiresDate = new Date(c.expirationDate);
451
- }
452
- } else {
453
- expiresDate = new Date(c.expirationDate);
454
- }
455
- expiresStr = `; expires=${expiresDate.toUTCString()}`;
456
- } else if (c.expires) {
457
- const expiresDate = typeof c.expires === "number" ? new Date(c.expires) : new Date(c.expires);
458
- expiresStr = `; expires=${expiresDate.toUTCString()}`;
459
- }
460
-
461
- // Helper function to build cookie string
462
- const buildCookieString = (domainOverride = null) => {
463
- const domain = domainOverride || cookieDomain;
464
- let cookieParts = [`${cookieName}=${cookieValue}${expiresStr}`];
465
- cookieParts.push(`Domain=${domain}`);
466
- cookieParts.push(`Path=${cookiePath}`);
467
-
468
- // Add Secure flag if secure is true
469
- if (c.secure === true) {
470
- cookieParts.push("Secure");
471
- }
472
-
473
- // Add HttpOnly flag if httpOnly is true
474
- if (c.httpOnly === true) {
475
- cookieParts.push("HttpOnly");
476
- }
477
-
478
- // Add SameSite attribute if provided
479
- if (c.sameSite) {
480
- const sameSiteValue = String(c.sameSite).toLowerCase();
481
- if (["strict", "lax", "none"].includes(sameSiteValue)) {
482
- cookieParts.push(`SameSite=${sameSiteValue.charAt(0).toUpperCase() + sameSiteValue.slice(1)}`);
483
- }
484
- }
485
-
486
- return cookieParts.join("; ");
487
- };
488
- const cookieConfigs = [];
489
- if (cookieDomain === ".facebook.com" || cookieDomain === "facebook.com") {
490
- cookieConfigs.push({ url: `http://${dom}${cookiePath}`, cookieStr: buildCookieString() });
491
- cookieConfigs.push({ url: `https://${dom}${cookiePath}`, cookieStr: buildCookieString() });
492
- cookieConfigs.push({ url: `http://www.${dom}${cookiePath}`, cookieStr: buildCookieString() });
493
- cookieConfigs.push({ url: `https://www.${dom}${cookiePath}`, cookieStr: buildCookieString() });
494
- } else {
495
- cookieConfigs.push({ url: `http://${dom}${cookiePath}`, cookieStr: buildCookieString() });
496
- cookieConfigs.push({ url: `https://${dom}${cookiePath}`, cookieStr: buildCookieString() });
497
- cookieConfigs.push({ url: `http://www.${dom}${cookiePath}`, cookieStr: buildCookieString() });
498
- cookieConfigs.push({ url: `https://www.${dom}${cookiePath}`, cookieStr: buildCookieString() });
435
+ async function listBackupUserIDs() {
436
+ try {
437
+ const Model = getBackupModel();
438
+ if (!Model || typeof Model.findAll !== "function") return [];
439
+ const rows = await Model.findAll({ attributes: ["userID"] });
440
+ const ids = new Set();
441
+ for (const row of rows || []) {
442
+ const id = row && (row.userID || (row.get && row.get("userID")));
443
+ if (id) ids.add(String(id));
499
444
  }
445
+ return Array.from(ids);
446
+ } catch {
447
+ return [];
448
+ }
449
+ }
500
450
 
501
- for (const config of cookieConfigs) {
502
- tasks.push(j.setCookie(config.cookieStr, config.url).catch((err) => {
503
- if (err && err.message && err.message.includes("Cookie not in this host's domain")) {
504
- return;
505
- }
506
- return;
507
- }));
451
+ async function setJarCookies(j, appstate) {
452
+ const tasks = [];
453
+ const setState = Object.create(null);
454
+ let expiredCount = 0;
455
+ for (const record of appstate) {
456
+ const built = buildSetCookie(record);
457
+ if (!built) continue;
458
+ if (built.expired) expiredCount += 1;
459
+ const cookieName = built.key;
460
+ const dom = String((record && record.domain) || ".facebook.com").replace(/^\./, "");
461
+ const urls = [
462
+ `https://${dom}/`,
463
+ `https://www.${dom}/`,
464
+ `http://${dom}/`,
465
+ `http://www.${dom}/`
466
+ ];
467
+ for (const url of urls) {
468
+ tasks.push(Promise.resolve()
469
+ .then(() => j.setCookie(built.cookie, url))
470
+ .then(() => {
471
+ setState[cookieName] = "ok";
472
+ })
473
+ .catch(() => {
474
+ if (setState[cookieName] !== "ok") setState[cookieName] = "fail";
475
+ }));
508
476
  }
509
477
  }
510
478
  await Promise.all(tasks);
479
+ if (expiredCount) {
480
+ logger(`Session load: ${expiredCount} cookies are already expired. They were not extended. Export a fresh appstate if login fails.`, "warn");
481
+ }
482
+ const required = ["c_user", "xs"];
483
+ const missing = required.filter((name) => {
484
+ const wanted = appstate.some((cookie) => cookie && (cookie.key === name || cookie.name === name));
485
+ return wanted && setState[name] === "fail";
486
+ });
487
+ if (missing.length) {
488
+ const error = new Error(`Required session cookies could not be loaded (${missing.join(", ")}). Export a fresh appstate. Cookie values were not logged.`);
489
+ error.code = "INVALID_APPSTATE";
490
+ error.category = "session_expired";
491
+ error.recovery = "Replace the appstate with a new browser export. Do not paste cookies into logs or tickets.";
492
+ throw error;
493
+ }
511
494
  }
512
495
 
513
496
  // tokens function - alias to tokensViaAPI for backward compatibility
@@ -517,14 +500,20 @@ async function tokens(username, password, twofactor = null) {
517
500
 
518
501
  async function hydrateJarFromDB(userID, jar) {
519
502
  try {
503
+ let resolvedID = userID ? String(userID) : "";
504
+ if (!resolvedID) {
505
+ const ids = await listBackupUserIDs();
506
+ if (ids.length > 1) {
507
+ logger("Refusing anonymous session restore because more than one account is stored. Pass that account's appstate explicitly.", "error");
508
+ return false;
509
+ }
510
+ if (ids.length === 1) resolvedID = ids[0];
511
+ }
520
512
  let ck = null;
521
513
  let app = null;
522
- if (userID) {
523
- ck = await getLatestBackup(userID, "cookie");
524
- app = await getLatestBackup(userID, "appstate");
525
- } else {
526
- ck = await getLatestBackupAny("cookie");
527
- app = await getLatestBackupAny("appstate");
514
+ if (resolvedID) {
515
+ ck = await getLatestBackup(resolvedID, "cookie");
516
+ app = await getLatestBackup(resolvedID, "appstate");
528
517
  }
529
518
  if (ck) {
530
519
  const pairs = normalizeCookieHeaderString(ck);
@@ -828,51 +817,15 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
828
817
  (async () => {
829
818
  try {
830
819
  if (appState) {
831
- // Check and convert cookie to appState format
832
- if (Array.isArray(appState) && appState.some(c => c.name)) {
833
- // Convert name to key if needed
834
- appState = appState.map(c => {
835
- if (c.name && !c.key) {
836
- c.key = c.name;
837
- delete c.name;
838
- }
839
- return c;
840
- });
841
- } else if (typeof appState === "string") {
842
- // Try to parse as JSON first
843
- let parsed = appState;
844
- try {
845
- parsed = JSON.parse(appState);
846
- } catch { }
847
-
848
- if (Array.isArray(parsed)) {
849
- // Already parsed as array, use it
850
- appState = parsed;
851
- } else {
852
- // Parse string cookie format (key=value; key2=value2)
853
- const arrayAppState = [];
854
- appState.split(';').forEach(c => {
855
- const [key, value] = c.split('=');
856
- if (key && value) {
857
- arrayAppState.push({
858
- key: key.trim(),
859
- value: value.trim(),
860
- domain: ".facebook.com",
861
- path: "/",
862
- expires: new Date().getTime() + 1000 * 60 * 60 * 24 * 365
863
- });
864
- }
865
- });
866
- appState = arrayAppState;
867
- }
820
+ try {
821
+ appState = parseAppStateInput(appState);
822
+ } catch (parseErr) {
823
+ throw parseErr;
868
824
  }
869
-
870
- // Set cookies into jar with individual domain/path
871
- if (Array.isArray(appState)) {
872
- await setJarCookies(jar, appState);
873
- } else {
825
+ if (!Array.isArray(appState)) {
874
826
  throw new Error("Invalid appState format");
875
827
  }
828
+ await setJarCookies(jar, appState);
876
829
  }
877
830
  if (Cookie) {
878
831
  let cookiePairs = [];
@@ -882,7 +835,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
882
835
  if (cookiePairs.length) setJarFromPairs(jar, cookiePairs, domain);
883
836
  }
884
837
  } catch (e) {
885
- return callback(e);
838
+ return callback(annotateError(e));
886
839
  }
887
840
  const ctx = { globalOptions, options: globalOptions, reconnectAttempts: 0 };
888
841
  ctx.guardSessionResponse = async function (response) {
@@ -1089,27 +1042,11 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1089
1042
  const tokenMatch = html.match(/DTSGInitialData.*?token":"(.*?)"/);
1090
1043
  if (tokenMatch) fb_dtsg = tokenMatch[1];
1091
1044
  try {
1092
- if (userID) await backupAppStateSQL(jar, userID);
1045
+ if (userID) {
1046
+ const backup = backupAppStateSQL(jar, userID);
1047
+ if (backup && typeof backup.catch === "function") backup.catch(() => {});
1048
+ }
1093
1049
  } catch { }
1094
- Promise.resolve()
1095
- .then(function () {
1096
- if (models && models.sequelize && typeof models.sequelize.authenticate === "function") {
1097
- return models.sequelize.authenticate();
1098
- }
1099
- })
1100
- .then(function () {
1101
- if (models && typeof models.syncAll === "function") {
1102
- return models.syncAll();
1103
- }
1104
- })
1105
- .catch(function (error) {
1106
- // Silently handle database errors - they're not critical for login
1107
- const errorMsg = error && error.message ? error.message : String(error);
1108
- if (!errorMsg.includes("No Sequelize instance passed")) {
1109
- // Only log non-Sequelize instance errors
1110
- logger(`Database connection failed: ${errorMsg}`, "warn");
1111
- }
1112
- });
1113
1050
  logger(chalk.italic("⚡ fca-nx | github.com/xalmandevv ⚡"), "info");
1114
1051
  const emitter = new EventEmitter();
1115
1052
  const ctxMain = {
@@ -1296,13 +1233,22 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1296
1233
  api.listen = api.listenMqtt;
1297
1234
  }
1298
1235
  if (api.refreshFb_dtsg) {
1299
- setInterval(function () {
1236
+ if (ctxMain._dtsgRefreshTimer) clearInterval(ctxMain._dtsgRefreshTimer);
1237
+ ctxMain._dtsgRefreshTimer = setInterval(function () {
1238
+ if (ctxMain._ending || ctxMain._sessionEnforcement) return;
1300
1239
  api.refreshFb_dtsg().then(function () {
1301
1240
  logger("Successfully refreshed fb_dtsg");
1302
- }).catch(function () {
1241
+ }).catch(function (refreshErr) {
1242
+ if (isSessionEnforcementError(refreshErr)) {
1243
+ clearInterval(ctxMain._dtsgRefreshTimer);
1244
+ ctxMain._dtsgRefreshTimer = null;
1245
+ logger("Stopped fb_dtsg refresh because Facebook requires manual review", "error");
1246
+ return;
1247
+ }
1303
1248
  logger("An error occurred while refreshing fb_dtsg", "error");
1304
1249
  });
1305
1250
  }, 86400000);
1251
+ if (ctxMain._dtsgRefreshTimer.unref) ctxMain._dtsgRefreshTimer.unref();
1306
1252
  }
1307
1253
  // ✅ fca-nx core features register
1308
1254
  if (!e2eeEnabled()) {
@@ -1401,10 +1347,10 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1401
1347
  callback(null, api);
1402
1348
  })
1403
1349
  .catch(function (e) {
1404
- callback(e);
1350
+ callback(annotateError(e));
1405
1351
  });
1406
1352
  } catch (e) {
1407
- callback(e);
1353
+ callback(annotateError(e));
1408
1354
  }
1409
1355
  }
1410
1356
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "7.5.5",
3
+ "version": "7.6.0",
4
4
  "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
5
  "keywords": [
6
6
  "facebook",
@@ -37,7 +37,9 @@
37
37
  "module/",
38
38
  "func/",
39
39
  "src/",
40
- "README.md"
40
+ "README.md",
41
+ "CHANGELOG.md",
42
+ "docs/"
41
43
  ],
42
44
  "scripts": {
43
45
  "test": "mocha",
@@ -83,12 +85,12 @@
83
85
  "chalk": "^4.1.2",
84
86
  "cheerio": "1.0.0-rc.12",
85
87
  "duplexify": "^4.1.3",
88
+ "form-data": "^4.0.4",
86
89
  "gradient-string": "^2.0.2",
87
90
  "https-proxy-agent": "^4.0.0",
88
91
  "mime": "^3.0.0",
89
92
  "mqtt": "^5.10.1",
90
93
  "protobufjs": "^8.4.0",
91
- "form-data": "^4.0.4",
92
94
  "sequelize": "^6.37.8",
93
95
  "sqlite3": "^6.0.1",
94
96
  "totp-generator": "^1.0.0",
@@ -84,8 +84,10 @@ module.exports = function (defaultFuncs, api, ctx) {
84
84
  // readers either see the old complete file or the new complete file.
85
85
  var dir = path.dirname(filePath);
86
86
  var tmpPath = path.join(dir, "." + path.basename(filePath) + "." + process.pid + "." + Date.now() + ".tmp");
87
- fs.writeFileSync(tmpPath, data, "utf8");
87
+ fs.writeFileSync(tmpPath, data, { encoding: "utf8", mode: 0o600 });
88
+ try { fs.chmodSync(tmpPath, 0o600); } catch (_) { }
88
89
  fs.renameSync(tmpPath, filePath);
90
+ try { fs.chmodSync(filePath, 0o600); } catch (_) { }
89
91
  }
90
92
 
91
93
  function saveToDiskSync(filePath) {
@@ -206,3 +208,5 @@ module.exports = function (defaultFuncs, api, ctx) {
206
208
  };
207
209
  };
208
210
  };
211
+
212
+ module.exports.isValidAppState = isValidAppState;