fca-nx 6.6.8 → 6.7.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.
Files changed (51) hide show
  1. package/module/login.js +17 -8
  2. package/module/loginHelper.js +31 -2
  3. package/package.json +3 -2
  4. package/src/api/messaging/uploadAttachment.js +2 -2
  5. package/src/api/socket/core/getSeqID.js +53 -58
  6. package/src/api/socket/e2ee/index.js +1 -1
  7. package/src/api/socket/listenE2EE.js +14 -4
  8. package/src/api/socket/listenMqtt.js +20 -12
  9. package/src/utils/format/utils.js +18 -12
  10. package/src/utils/utils.js +15 -6
  11. package/e2ee/config.json +0 -0
  12. package/e2ee/crypto.js +0 -173
  13. package/e2ee/index.js +0 -1032
  14. package/e2ee/proto/ArmadilloApplication.proto +0 -281
  15. package/e2ee/proto/ArmadilloICDC.proto +0 -14
  16. package/e2ee/proto/ConsumerApplication.proto +0 -232
  17. package/e2ee/proto/MessageApplication.proto +0 -82
  18. package/e2ee/proto/MessageTransport.proto +0 -77
  19. package/e2ee/proto/WACommon.proto +0 -66
  20. package/e2ee/proto/WAMediaTransport.proto +0 -176
  21. package/e2ee/protocol.js +0 -196
  22. package/e2ee/ratchet.js +0 -219
  23. package/e2ee/store.js +0 -182
  24. package/e2ee/vendor/fb-e2ee.cjs +0 -9159
  25. package/e2ee/vendor/proto/ArmadilloApplication.proto +0 -281
  26. package/e2ee/vendor/proto/ArmadilloICDC.proto +0 -14
  27. package/e2ee/vendor/proto/ConsumerApplication.proto +0 -232
  28. package/e2ee/vendor/proto/MessageApplication.proto +0 -82
  29. package/e2ee/vendor/proto/MessageTransport.proto +0 -77
  30. package/e2ee/vendor/proto/WACommon.proto +0 -66
  31. package/e2ee/vendor/proto/WAMediaTransport.proto +0 -176
  32. package/src/api/socket/e2ee/e2ee/crypto.js +0 -173
  33. package/src/api/socket/e2ee/e2ee/index.js +0 -421
  34. package/src/api/socket/e2ee/e2ee/proto/ArmadilloApplication.proto +0 -281
  35. package/src/api/socket/e2ee/e2ee/proto/ArmadilloICDC.proto +0 -14
  36. package/src/api/socket/e2ee/e2ee/proto/ConsumerApplication.proto +0 -232
  37. package/src/api/socket/e2ee/e2ee/proto/MessageApplication.proto +0 -82
  38. package/src/api/socket/e2ee/e2ee/proto/MessageTransport.proto +0 -77
  39. package/src/api/socket/e2ee/e2ee/proto/WACommon.proto +0 -66
  40. package/src/api/socket/e2ee/e2ee/proto/WAMediaTransport.proto +0 -176
  41. package/src/api/socket/e2ee/e2ee/protocol.js +0 -196
  42. package/src/api/socket/e2ee/e2ee/ratchet.js +0 -219
  43. package/src/api/socket/e2ee/e2ee/store.js +0 -182
  44. package/src/api/socket/e2ee/e2ee/vendor/fb-e2ee.cjs +0 -9162
  45. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloApplication.proto +0 -281
  46. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloICDC.proto +0 -14
  47. package/src/api/socket/e2ee/e2ee/vendor/proto/ConsumerApplication.proto +0 -232
  48. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageApplication.proto +0 -82
  49. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageTransport.proto +0 -77
  50. package/src/api/socket/e2ee/e2ee/vendor/proto/WACommon.proto +0 -66
  51. package/src/api/socket/e2ee/e2ee/vendor/proto/WAMediaTransport.proto +0 -176
package/module/login.js CHANGED
@@ -46,10 +46,14 @@ if (!global.fca._errorHandlersInstalled) {
46
46
  }
47
47
  }
48
48
 
49
- // For other unhandled rejections, log but don't crash
50
- logger(`Unhandled promise rejection (non-fatal): ${reason && reason.message ? reason.message : String(reason)}`, "error");
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));
53
+ logger(`Unhandled promise rejection (non-fatal): ${errorDetail}`, "error");
51
54
  } catch (e) {
52
- // Fallback if logger fails - silent
55
+ // 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 { }
53
57
  }
54
58
  });
55
59
 
@@ -73,12 +77,17 @@ if (!global.fca._errorHandlersInstalled) {
73
77
  return; // Don't crash
74
78
  }
75
79
 
76
- // For other uncaught exceptions, log but try to continue
77
- logger(`Uncaught exception (attempting to continue): ${errorMessage}`, "error");
78
- // Note: We don't exit here to allow bot to continue running
79
- // In production, you might want to restart the process instead
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");
83
+ // Note: We don't exit here to allow bot to continue running.
84
+ // This trades crash-safety for the (small) risk of continuing in a
85
+ // partially-inconsistent process state. If you run this under a process
86
+ // manager (pm2/systemd) that auto-restarts on crash, consider calling
87
+ // process.exit(1) here instead for a clean restart on truly unknown errors.
80
88
  } catch (e) {
81
- // Fallback if logger fails - silent
89
+ // 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 { }
82
91
  }
83
92
  });
84
93
  }
@@ -1170,6 +1170,27 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1170
1170
  ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1171
1171
  ctxMain.performAutoLogin = async () => {
1172
1172
  try {
1173
+ // [Fixed by xalman] First check whether the existing cookie session is actually
1174
+ // still usable. A checkpoint/redirect seen on one request
1175
+ // doesn't always mean the whole session is dead (transient FB
1176
+ // blips, rate limiting, etc). Cookie/appstate-only logins have
1177
+ // no email+password to re-login with, so without this check a
1178
+ // single false-positive checkpoint would permanently tear down
1179
+ // the bot (via emitAuth) and force a brand new cookie every
1180
+ // time instead of just continuing on the still-good session.
1181
+ try {
1182
+ const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1183
+ const html = check && check.data ? String(check.data) : "";
1184
+ const stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1185
+ const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
1186
+ if (!stillCheckpointed && uidMatch && uidMatch[1] && uidMatch[1] !== "0") {
1187
+ logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1188
+ return true;
1189
+ }
1190
+ } catch {
1191
+ // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1192
+ }
1193
+
1173
1194
  const u = config.credentials?.email || email;
1174
1195
  const p = config.credentials?.password || password;
1175
1196
  const tf = config.credentials?.twofactor || null;
@@ -1314,10 +1335,18 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1314
1335
  // bots calling api.listen() OR api.listenMqtt() directly also
1315
1336
  // receive E2EE (Secret Conversation) messages without any extra
1316
1337
  // setup or changes on the bot side.
1338
+ //
1339
+ // [Fixed by xalman] IMPORTANT: assign api.listen/api.listenMqtt to the combined
1340
+ // listener SYNCHRONOUSLY, before connectE2EE() resolves. Bots
1341
+ // commonly call api.listenMqtt(callback) immediately in the login
1342
+ // callback - if we waited for the async connectE2EE() promise to
1343
+ // swap these over, that call would already have captured the old
1344
+ // plain-MQTT-only function, permanently missing E2EE (inbox)
1345
+ // messages even after E2EE finished connecting moments later.
1346
+ api.listen = api.listenE2EE;
1347
+ api.listenMqtt = api.listenE2EE;
1317
1348
  api.connectE2EE()
1318
1349
  .then(() => {
1319
- api.listen = api.listenE2EE;
1320
- api.listenMqtt = api.listenE2EE;
1321
1350
  logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
1322
1351
  })
1323
1352
  .catch((e) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.6.8",
3
+ "version": "6.7.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",
@@ -17,7 +17,6 @@
17
17
  "module/",
18
18
  "func/",
19
19
  "src/",
20
- "e2ee/",
21
20
  "DOCS.md",
22
21
  "README.md",
23
22
  "src/app/"
@@ -85,9 +84,11 @@
85
84
  "mime": "^3.0.0",
86
85
  "mqtt": "^5.10.1",
87
86
  "protobufjs": "^8.4.0",
87
+ "request": "^2.88.2",
88
88
  "sequelize": "^6.37.8",
89
89
  "sqlite3": "^5.1.7",
90
90
  "totp-generator": "^1.0.0",
91
+ "tough-cookie": "^4.1.4",
91
92
  "ws": "^8.18.0"
92
93
  },
93
94
  "devDependencies": {
@@ -62,7 +62,7 @@ function respFinalUrl(res) {
62
62
 
63
63
  function detectCheckpoint(res) {
64
64
  const url = String(respFinalUrl(res) || "");
65
- const body = typeof res?.body === "string" ? res.body : "";
65
+ const body = typeof res?.data === "string" ? res.data : "";
66
66
  const hit =
67
67
  /\/checkpoint\//i.test(url) ||
68
68
  /(?:href|action)\s*=\s*["']https?:\/\/[^"']*\/checkpoint\//i.test(body) ||
@@ -78,7 +78,7 @@ function checkpointError(res) {
78
78
  e.code = "CHECKPOINT";
79
79
  e.checkpoint = true;
80
80
  e.url = d.url || "https://www.facebook.com/checkpoint/";
81
- e.status = res?.statusCode || res?.status;
81
+ e.status = res?.status || res?.statusCode;
82
82
  return e;
83
83
  }
84
84
 
@@ -2,9 +2,10 @@
2
2
  /**
3
3
  * Fetches MQTT sync sequence ID from GraphQL and starts listenMqtt.
4
4
  * Handles retries and auto re-login via fca-config.json when session expires.
5
+ * Fixed by Xalman: Added fb_dtsg/jazoest payload & 1357032 Object error fallback.
5
6
  */
6
7
  const { getType } = require("../../../utils/format");
7
- const { parseAndCheckLogin, saveCookies } = require("../../../utils/client");
8
+ const { parseAndCheckLogin } = require("../../../utils/client");
8
9
  const path = require("path");
9
10
  const loginHelper = require("../../../../module/loginHelper");
10
11
 
@@ -69,21 +70,14 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
69
70
  if (typeof result.cookies === "string") {
70
71
  cookiePairs = normalizeCookieHeaderString(result.cookies);
71
72
  }
72
- // If cookies is an array, convert to pairs
73
73
  else if (Array.isArray(result.cookies)) {
74
74
  cookiePairs = result.cookies.map(c => {
75
- if (typeof c === "string") {
76
- // Already in "key=value" format
77
- return c;
78
- } else if (c && typeof c === "object") {
79
- // Object format {key, value} or {name, value}
80
- return `${c.key || c.name}=${c.value}`;
81
- }
75
+ if (typeof c === "string") return c;
76
+ if (c && typeof c === "object") return `${c.key || c.name}=${c.value}`;
82
77
  return null;
83
78
  }).filter(Boolean);
84
79
  }
85
80
 
86
- // Also check for cookie field (alternative field name)
87
81
  if (cookiePairs.length === 0 && result.cookie) {
88
82
  if (typeof result.cookie === "string") {
89
83
  cookiePairs = normalizeCookieHeaderString(result.cookie);
@@ -99,7 +93,6 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
99
93
  if (cookiePairs.length > 0 || result.uid) {
100
94
  logger(`getSeqID: auto re-login successful! UID: ${result.uid}, Cookies: ${cookiePairs.length}`, "info");
101
95
 
102
- // Apply cookies to ctx.jar using setJarFromPairs approach
103
96
  if (ctx.jar && cookiePairs.length > 0) {
104
97
  const expires = new Date(Date.now() + 31536e6).toUTCString();
105
98
  for (const kv of cookiePairs) {
@@ -117,23 +110,11 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
117
110
  logger(`getSeqID: applied ${cookiePairs.length} API cookies to jar`, "info");
118
111
  }
119
112
 
120
- // Now refresh web session to get proper web cookies
121
113
  logger("getSeqID: refreshing web session after API login...", "info");
122
114
  try {
123
115
  const { get } = require("../../../utils/request");
124
116
  const { saveCookies: saveWebCookies } = require("../../../utils/client");
125
117
 
126
- // NOTE: cookies are applied to ctx.jar only (above), not to any
127
- // process-wide/global jar. Each login/session now owns its own
128
- // CookieJar (see module/loginHelper.js); writing this account's
129
- // cookies into a shared global jar would leak them into any other
130
- // account/session running in the same process and corrupt both
131
- // sessions' identity - exactly the kind of bug that produces
132
- // random/abnormal logouts when running more than one account.
133
-
134
- // Fetch Facebook to refresh and get web session cookies
135
- // Do this multiple times to ensure session is fully established
136
- // Try both m.facebook.com and www.facebook.com
137
118
  let webResponse = null;
138
119
  let htmlContent = "";
139
120
  const htmlUID = body => {
@@ -143,10 +124,8 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
143
124
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
144
125
  const urlsToTry = ["https://m.facebook.com/", "https://www.facebook.com/"];
145
126
 
146
- // Try refreshing up to 3 times to get valid session
147
127
  for (let attempt = 0; attempt < 3; attempt++) {
148
128
  try {
149
- // Try m.facebook.com first (mobile version often works better for API login)
150
129
  const urlToUse = attempt === 0 ? urlsToTry[0] : urlsToTry[attempt % urlsToTry.length];
151
130
  logger(`getSeqID: Refreshing ${urlToUse} (attempt ${attempt + 1}/3)...`, "info");
152
131
 
@@ -155,7 +134,6 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
155
134
  await saveWebCookies(ctx.jar)(webResponse);
156
135
  htmlContent = typeof webResponse.data === "string" ? webResponse.data : String(webResponse.data || "");
157
136
 
158
- // Check if HTML contains valid USER_ID
159
137
  const htmlUserID = htmlUID(htmlContent);
160
138
  if (isValidUID(htmlUserID)) {
161
139
  logger(`getSeqID: Found valid USER_ID in HTML from ${urlToUse}: ${htmlUserID}`, "info");
@@ -174,20 +152,16 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
174
152
  }
175
153
 
176
154
  if (webResponse && webResponse.data) {
177
- // Get updated cookies from jar
178
155
  const updatedCookies = await ctx.jar.getCookies("https://www.facebook.com");
179
156
  logger(`getSeqID: refreshed session, now have ${updatedCookies.length} web cookies`, "info");
180
157
 
181
- // Check HTML for USER_ID
182
158
  const htmlUserID = htmlUID(htmlContent);
183
159
  if (!isValidUID(htmlUserID)) {
184
160
  logger("getSeqID: WARNING - HTML does not show valid USER_ID after refresh. Session may not be fully established.", "warn");
185
161
  }
186
162
 
187
- // Update ctx state
188
163
  if (ctx) {
189
164
  ctx.loggedIn = true;
190
- // Use USER_ID from HTML if available, otherwise from API response
191
165
  if (isValidUID(htmlUserID)) {
192
166
  ctx.userID = htmlUserID;
193
167
  logger(`getSeqID: Updated ctx.userID from HTML: ${htmlUserID}`, "info");
@@ -203,7 +177,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
203
177
  logger(`getSeqID: web session refresh failed - ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
204
178
  }
205
179
 
206
- return { ...result, cookies };
180
+ return { ...result, cookies: parseCookieString(result.cookies || result.cookie) };
207
181
  }
208
182
  }
209
183
 
@@ -223,25 +197,61 @@ module.exports = function createGetSeqID(deps) {
223
197
  const RETRY_DELAY = 2000;
224
198
  ctx.t_mqttCalled = false;
225
199
 
200
+ // Ensure essential tokens are injected into GraphQL Batch Payload
201
+ if (!form) {
202
+ form = {
203
+ av: ctx.globalOptions.pageID || ctx.userID,
204
+ fb_dtsg: ctx.fb_dtsg,
205
+ jazoest: ctx.jazoest,
206
+ queries: JSON.stringify({
207
+ o0: {
208
+ doc_id: "3336396659757871",
209
+ query_params: {
210
+ limit: 1,
211
+ before: null,
212
+ tags: ["INBOX", "PENDING", "OTHER"],
213
+ includeDeliveryReceipts: false,
214
+ includeSeqID: true
215
+ }
216
+ }
217
+ })
218
+ };
219
+ } else {
220
+ if (!form.fb_dtsg && ctx.fb_dtsg) form.fb_dtsg = ctx.fb_dtsg;
221
+ if (!form.jazoest && ctx.jazoest) form.jazoest = ctx.jazoest;
222
+ }
223
+
226
224
  return defaultFuncs
227
225
  .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
228
226
  .then(parseAndCheckLogin(ctx, defaultFuncs))
229
227
  .then(async resData => {
230
- // Better error handling: check what we actually got
228
+ // Safe check for non-array responses (such as Error Objects from FB)
231
229
  if (getType(resData) !== "Array") {
232
- // Log what we actually received for debugging
233
- logger(`getSeqID: Unexpected response type: ${getType(resData)}, value: ${JSON.stringify(resData).substring(0, 200)}`, "warn");
234
-
235
- // If parseAndCheckLogin returned an error object, check if it's an auth error
230
+ logger(`getSeqID: Response is not Array, received: ${getType(resData)}`, "warn");
231
+
232
+ // Handle Facebook GraphQL 1357032 or transient error responses without triggering re-login
236
233
  if (resData && typeof resData === "object") {
237
- const errorMsg = resData.error || resData.message || "";
234
+ const errCode = resData.error || resData.errorCode;
235
+ const errorMsg = resData.errorSummary || resData.message || "";
236
+
237
+ if (errCode === 1357032 || /Something Went Wrong/i.test(errorMsg)) {
238
+ logger("getSeqID: FB returned error 1357032. Using fallback seqID and continuing to MQTT.", "warn");
239
+ ctx.lastSeqId = ctx.lastSeqId || "0";
240
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
241
+ return;
242
+ }
243
+
238
244
  if (/Not logged in|login|blocked|401|403|checkpoint/i.test(errorMsg)) {
239
245
  throw { error: "Not logged in", originalResponse: resData };
240
246
  }
241
247
  }
242
-
243
- throw { error: "Not logged in", originalResponse: resData };
248
+
249
+ // Fallback if it's an unrecognized object
250
+ ctx.lastSeqId = ctx.lastSeqId || "0";
251
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
252
+ return;
244
253
  }
254
+
245
255
  if (!Array.isArray(resData) || !resData.length) return;
246
256
  const lastRes = resData[resData.length - 1];
247
257
  if (lastRes && lastRes.successful_results === 0) return;
@@ -251,7 +261,7 @@ module.exports = function createGetSeqID(deps) {
251
261
  ctx.lastSeqId = syncSeqId;
252
262
  logger("mqtt getSeqID ok -> listenMqtt()", "info");
253
263
  } else {
254
- ctx.lastSeqId = ctx.lastSeqId || 0;
264
+ ctx.lastSeqId = ctx.lastSeqId || "0";
255
265
  logger("getSeqID: sync_sequence_id not found, fallback lastSeqId=" + ctx.lastSeqId, "warn");
256
266
  }
257
267
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
@@ -260,11 +270,6 @@ module.exports = function createGetSeqID(deps) {
260
270
  const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
261
271
  const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
262
272
 
263
- // Check if this is a CONFIRMED auth-related error (session actually
264
- // rejected) versus a transient network problem. Only confirmed auth
265
- // errors should ever lead to emitAuth() / auto-login; a timeout or
266
- // connection reset is not evidence the session is invalid and must
267
- // not be treated as a logout.
268
273
  const isAuthError = /Not logged in|no sync_sequence_id found|blocked the login|401|403/i.test(msg);
269
274
  const netCode = err?.code || err?.originalError?.code || "";
270
275
  const isNetworkError = !isAuthError && (
@@ -279,23 +284,16 @@ module.exports = function createGetSeqID(deps) {
279
284
  await new Promise(resolve => setTimeout(resolve, delay));
280
285
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
281
286
  }
282
- // Exhausted retries on a network error - this is NOT a confirmed
283
- // auth failure, so we do not call emitAuth()/tear down the
284
- // session. Surface it and let the caller's own reconnect/backoff
285
- // logic (see connectMqtt.js) decide whether to keep trying.
286
- logger(`getSeqID: network error persisted after ${MAX_RETRIES} retries, giving up for now (session left intact): ${msg}`, "error");
287
+ logger(`getSeqID: network error persisted after ${MAX_RETRIES} retries, giving up for now: ${msg}`, "error");
287
288
  return;
288
289
  }
289
290
 
290
- // For confirmed auth errors, try retry + auto-login
291
291
  if (isAuthError) {
292
- // Retry logic with increasing delay
293
292
  if (retryCount < MAX_RETRIES) {
294
- const delay = RETRY_DELAY * (retryCount + 1); // Increasing delay: 2s, 4s, 6s
293
+ const delay = RETRY_DELAY * (retryCount + 1);
295
294
  logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (error: ${msg})`, "warn");
296
295
  await new Promise(resolve => setTimeout(resolve, delay));
297
296
 
298
- // Before retrying, try to refresh the session if this is the first retry
299
297
  if (retryCount === 0 && ctx.loggedIn) {
300
298
  try {
301
299
  logger("getSeqID: refreshing session before retry...", "info");
@@ -310,19 +308,16 @@ module.exports = function createGetSeqID(deps) {
310
308
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
311
309
  }
312
310
 
313
- // All retries failed, try auto-login
314
311
  logger("getSeqID: all retries failed, attempting auto re-login...", "warn");
315
312
  const config = getConfig();
316
313
  const loginResult = await tryAutoLogin(logger, config, ctx, defaultFuncs);
317
314
 
318
315
  if (loginResult) {
319
- // Wait longer after auto-login to ensure session is ready
320
316
  logger("getSeqID: retrying with new session...", "info");
321
- await new Promise(resolve => setTimeout(resolve, 3000)); // Increased delay to 3s
317
+ await new Promise(resolve => setTimeout(resolve, 3000));
322
318
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, 0);
323
319
  }
324
320
 
325
- // Determine the auth error type
326
321
  if (/blocked/i.test(msg)) {
327
322
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
328
323
  }
@@ -113,7 +113,7 @@ class E2EEBridge {
113
113
  require("request")({ method: "POST", url: url, jar: _ctx.jar, form: merged, gzip: true },
114
114
  function (err, r) { if (err) return reject(err); resolve(r); });
115
115
  });
116
- return res && res.body;
116
+ return res && (res.data !== undefined ? res.data : res.body);
117
117
  },
118
118
  // listenMqtt — fb-e2ee.cjs calls this to route non-E2EE MQTT events.
119
119
  // FCA-NX has its own separate MQTT listener so we provide a no-op stub
@@ -47,15 +47,25 @@ module.exports = function (defaultFuncs, api, ctx) {
47
47
  var mqttEmitter = (api._listenMqttRaw || api.listenMqtt)(globalCallback);
48
48
  api._mqttEmitter = mqttEmitter;
49
49
 
50
- // Hook E2EE incoming messages (FCA-NX native Noise WebSocket)
50
+ // [Fixed by xalman] Hook E2EE incoming messages (FCA-NX native Noise WebSocket).
51
+ // onMessage() only registers a callback reference - it doesn't require an
52
+ // active connection - so this is safe to call even while E2EE is still
53
+ // connecting in the background. If we skip it here just because
54
+ // isConnected() is momentarily false, the hook never gets attached and
55
+ // E2EE (inbox) messages go unheard for the lifetime of this listener.
51
56
  var e2ee = api.e2ee || ctx.e2ee;
52
- if (!e2ee || !e2ee.isConnected()) {
57
+ if (!e2ee) {
53
58
  logger.warn(
54
59
  "listenE2EE",
55
- "E2EE not connected. E2EE messages will not be received. " +
56
- "Call api.connectE2EE() before listenE2EE() to enable encrypted message reception."
60
+ "E2EE bridge not available. E2EE messages will not be received."
57
61
  );
58
62
  } else {
63
+ if (!e2ee.isConnected()) {
64
+ logger.info(
65
+ "listenE2EE",
66
+ "E2EE still connecting - message hook registered, will receive events once the handshake completes."
67
+ );
68
+ }
59
69
  e2ee.onMessage(function (err, event) {
60
70
  if (err) return globalCallback(err, null);
61
71
  if (!event) return;
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Modified by Xalman
3
- * Fixed Auto-Logout, MQTT Heartbeat Leak, and Loop Reconnection Bugs.
2
+ * Fixed and Optimized listenMqtt.js
3
+ * Prevents MQTT loop hangs, fixes heartbeat ping leaks, and cleans up event listeners.
4
4
  */
5
5
 
6
6
  "use strict";
@@ -24,7 +24,7 @@ const CYCLE_MS_DEFAULT = 60 * 60 * 1000;
24
24
  const RECONNECT_DELAY_MS_DEFAULT = 3000;
25
25
  const UNSUB_ALL_TIMEOUT_MS = 5000;
26
26
  const MAX_MQTT_RECONNECT_DELAY_MS = 60000;
27
- const MAX_MQTT_RECONNECT_ATTEMPTS = 15;
27
+ const MAX_MQTT_RECONNECT_ATTEMPTS = 10;
28
28
  const HEARTBEAT_INTERVAL_MS = 30000;
29
29
  const HEARTBEAT_TIMEOUT_MS = 10000;
30
30
 
@@ -81,8 +81,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
81
81
  function postSafe(...args) {
82
82
  return rawPost(...args).catch(err => {
83
83
  const msg = (err && err.error) || (err && err.message) || String(err || "");
84
- // Handle Auto-Logout and Checkpoint Auth triggers
85
- if (/Not logged in|blocked the login|Checkpoint|Login approved/i.test(msg)) {
84
+ if (/Not logged in|blocked the login|Checkpoint/i.test(msg)) {
86
85
  emitAuth(
87
86
  ctx,
88
87
  api,
@@ -116,12 +115,13 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
116
115
  return Promise.resolve();
117
116
  }
118
117
 
119
- // Updated Doc ID to modern Facebook GraphQL Thread Query Endpoint to avoid logouts
120
118
  const form = {
121
119
  av: ctx.globalOptions.pageID || ctx.userID,
120
+ fb_dtsg: ctx.fb_dtsg,
121
+ jazoest: ctx.jazoest,
122
122
  queries: JSON.stringify({
123
123
  o0: {
124
- doc_id: "6007624976008514",
124
+ doc_id: "3336396659757871",
125
125
  query_params: {
126
126
  limit: 1,
127
127
  before: null,
@@ -201,7 +201,6 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
201
201
  }
202
202
 
203
203
  try {
204
- // Send standard MQTT ping timestamp packet to keep Facebook connection alive
205
204
  ctx.mqttClient.publish("/ping", JSON.stringify({ timestamp: Date.now() }), { qos: 0 });
206
205
  logger("mqtt heartbeat sent", "debug");
207
206
  } catch (err) {
@@ -394,14 +393,23 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
394
393
  function attachClientListeners() {
395
394
  if (!ctx.mqttClient) return;
396
395
 
397
- // Clean up prior event listeners to prevent memory leak & double-triggering
398
- ctx.mqttClient.removeAllListeners("pong");
396
+ ctx.mqttClient.removeAllListeners("packetreceive");
399
397
  ctx.mqttClient.removeAllListeners("close");
400
398
  ctx.mqttClient.removeAllListeners("error");
401
399
 
402
- ctx.mqttClient.on("pong", () => {
400
+ // [Fixed by xalman] mqtt.js does NOT emit a "pong" event - that was never firing,
401
+ // so lastPongTime was never refreshed and the heartbeat below kept
402
+ // force-reconnecting the account roughly every minute (this is what
403
+ // looked like periodic auto logout). The library's own keepalive
404
+ // (keepalive: 30 in connectMqtt.js) sends PINGREQ/PINGRESP
405
+ // internally; we detect the PINGRESP via "packetreceive" instead.
406
+ // Any other incoming packet (e.g. real messages) also proves the
407
+ // connection is alive, so it counts too.
408
+ ctx.mqttClient.on("packetreceive", (packet) => {
403
409
  lastPongTime = Date.now();
404
- logger("mqtt pong received", "debug");
410
+ if (packet && packet.cmd === "pingresp") {
411
+ logger("mqtt pong received", "debug");
412
+ }
405
413
  });
406
414
 
407
415
  ctx.mqttClient.once("close", () => {
@@ -4,8 +4,11 @@ function getType(obj) {
4
4
  return Object.prototype.toString.call(obj).slice(8, -1);
5
5
  }
6
6
 
7
+ // [Fixed by xalman] formatID now coerces id to String before .replace() -
8
+ // previously crashed with "id.replace is not a function" whenever a numeric
9
+ // userID was passed (e.g. addFriend), since Number has no .replace method.
7
10
  function formatID(id) {
8
- if (id != undefined && id != null) return id.replace(/(fb)?id[:.]/, "");
11
+ if (id != undefined && id != null) return String(id).replace(/(fb)?id[:.]/, "");
9
12
  else return id;
10
13
  }
11
14
 
@@ -35,6 +38,10 @@ function arrToForm(form) {
35
38
  );
36
39
  }
37
40
 
41
+ // [Fixed by xalman] Stt was previously incremented ("Stt++") on every
42
+ // recursive call, which silently coerced any non-numeric default value
43
+ // (string/null/object - the normal case) to NaN one level deep. It's a
44
+ // static fallback value, so it's now passed through unchanged.
38
45
  function getData_Path(Obj, Arr, Stt) {
39
46
  if (Arr.length === 0 && Obj != undefined) {
40
47
  return Obj;
@@ -46,27 +53,26 @@ function getData_Path(Obj, Arr, Stt) {
46
53
  return Stt;
47
54
  }
48
55
  const tail = Arr.slice(1);
49
- return getData_Path(Obj[head], tail, Stt++);
56
+ return getData_Path(Obj[head], tail, Stt);
50
57
  }
51
58
 
59
+ // [Fixed by xalman] Rewritten - the old version reassigned a local variable
60
+ // instead of the actual object property, so updating an EXISTING truthy
61
+ // value silently did nothing. Also stopped mutating the caller's path array.
52
62
  function setData_Path(obj, path, value) {
53
63
  if (!path.length) {
54
64
  return obj;
55
65
  }
56
66
  const currentKey = path[0];
57
- let currentObj = obj[currentKey];
58
-
59
- if (!currentObj) {
67
+ const remaining = path.slice(1);
68
+ if (!remaining.length) {
60
69
  obj[currentKey] = value;
61
- currentObj = obj[currentKey];
62
- }
63
- path.shift();
64
- if (!path.length) {
65
- currentObj = value;
66
70
  } else {
67
- currentObj = setData_Path(currentObj, path, value);
71
+ if (!obj[currentKey] || typeof obj[currentKey] !== "object") {
72
+ obj[currentKey] = {};
73
+ }
74
+ setData_Path(obj[currentKey], remaining, value);
68
75
  }
69
-
70
76
  return obj;
71
77
  }
72
78
 
@@ -245,15 +245,24 @@ function decodeClientPayload(payload) {
245
245
 
246
246
  function parseAndCheckLogin(ctx, defaultFuncs) {
247
247
  return function (res) {
248
- if (res.statusCode >= 500 && res.statusCode < 600) {
249
- throw { error: "Facebook internal server error: " + res.statusCode, res };
248
+ // NOTE: this used to read res.statusCode/res.body, which are the old
249
+ // `request`/`request-promise` library's property names. The actual
250
+ // HTTP client here (src/utils/request) is axios-based, whose
251
+ // responses use res.status/res.data instead - res.body was always
252
+ // undefined, so this threw "Empty response body" on every single
253
+ // call. That silently broke OldMessage.js (used for DM attachments,
254
+ // and as the fallback whenever an MQTT send fails).
255
+ var status = res && res.status !== undefined ? res.status : (res && res.statusCode);
256
+ if (status >= 500 && status < 600) {
257
+ throw { error: "Facebook internal server error: " + status, res };
250
258
  }
251
- if (res.statusCode === 404 || res.statusCode === 410) {
252
- throw { error: "Endpoint not found: " + res.statusCode, res };
259
+ if (status === 404 || status === 410) {
260
+ throw { error: "Endpoint not found: " + status, res };
253
261
  }
254
- if (!res.body) throw { error: "Empty response body", res };
262
+ var rawBody = res && res.data !== undefined ? res.data : (res && res.body);
263
+ if (rawBody === undefined || rawBody === null || rawBody === "") throw { error: "Empty response body", res };
255
264
 
256
- var body = res.body;
265
+ var body = rawBody;
257
266
  if (typeof body !== "string") body = JSON.stringify(body);
258
267
 
259
268
  var stripped = body;
package/e2ee/config.json DELETED
File without changes