fca-nx 6.6.8 → 6.6.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.6.8",
3
+ "version": "6.6.9",
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",
@@ -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
  }
@@ -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,7 +393,6 @@ 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
396
  ctx.mqttClient.removeAllListeners("pong");
399
397
  ctx.mqttClient.removeAllListeners("close");
400
398
  ctx.mqttClient.removeAllListeners("error");