fca-nx 6.8.8 → 7.0.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 +24 -10
- package/func/checkUpdate.js +1 -1
- package/func/logAdapter.js +2 -0
- package/index.js +3 -0
- package/module/config.js +5 -3
- package/module/login.js +38 -13
- package/module/loginHelper.js +207 -148
- package/module/options.js +7 -1
- package/package.json +2 -2
- package/src/api/action/addfriend.js +9 -3
- package/src/api/action/changeAvatar.js +1 -0
- package/src/api/action/changeCover.js +3 -1
- package/src/api/action/enableAutoSaveAppState.js +18 -5
- package/src/api/action/refreshFb_dtsg.js +18 -76
- package/src/api/http/httpGet.js +6 -2
- package/src/api/http/httpPost.js +7 -2
- package/src/api/messaging/createNewGroup.js +1 -1
- package/src/api/messaging/deleteMessage.js +1 -1
- package/src/api/messaging/forwardMessage.js +9 -1
- package/src/api/messaging/getEmojiUrl.js +5 -1
- package/src/api/messaging/getMessage.js +4 -2
- package/src/api/messaging/getThemePictures.js +7 -0
- package/src/api/messaging/markAsRead.js +1 -0
- package/src/api/messaging/muteThread.js +1 -1
- package/src/api/messaging/pinMessage.js +10 -1
- package/src/api/messaging/scheduler.js +71 -4
- package/src/api/messaging/sendBroadcast.js +15 -0
- package/src/api/messaging/sendMessage.js +23 -1
- package/src/api/messaging/sendTypingIndicator.js +0 -15
- package/src/api/messaging/sessionGuard.js +45 -9
- package/src/api/messaging/setMessageReaction.js +2 -1
- package/src/api/messaging/threadColors.js +45 -12
- package/src/api/messaging/uploadAttachment.js +37 -3
- package/src/api/socket/OldMessage.js +7 -2
- package/src/api/socket/core/connectMqtt.js +68 -81
- package/src/api/socket/core/emitAuth.js +11 -2
- package/src/api/socket/core/getSeqID.js +52 -56
- package/src/api/socket/core/getTaskResponseData.js +3 -1
- package/src/api/socket/core/parseDelta.js +1 -1
- package/src/api/socket/detail/buildStream.js +4 -1
- package/src/api/socket/detail/constants.js +4 -1
- package/src/api/socket/e2ee/crypto.js +40 -2
- package/src/api/socket/e2ee/index.js +123 -10
- package/src/api/socket/e2ee/protocol.js +32 -1
- package/src/api/socket/e2ee/ratchet.js +44 -10
- package/src/api/socket/e2ee/store.js +13 -1
- package/src/api/socket/listenE2EE.js +25 -1
- package/src/api/socket/listenMqtt.js +94 -110
- package/src/api/socket/middleware/index.js +61 -7
- package/src/api/socket/sendMessage.js +19 -2
- package/src/api/socket/sendMessageMqtt.js +6 -0
- package/src/api/threads/getThreadHistory.js +68 -38
- package/src/api/threads/getThreadInfo.js +4 -3
- package/src/api/threads/getThreadList.js +34 -31
- package/src/api/threads/getThreadPictures.js +1 -1
- package/src/api/users/getUserInfo.js +5 -2
- package/src/api/users/getUserInfoV2.js +9 -3
- package/src/app/createFcaClient.js +2 -2
- package/src/core/sendReqMqtt.js +2 -1
- package/src/database/helpers.js +12 -0
- package/src/database/models/index.js +8 -9
- package/src/utils/broadcast.js +1 -1
- package/src/utils/clientIdentity.js +50 -3
- package/src/utils/cookies.js +4 -2
- package/src/utils/format/utils.js +10 -0
- package/src/utils/headers.js +26 -12
- package/src/utils/loginParser/autoLogin.js +12 -0
- package/src/utils/loginParser/parseAndCheckLogin.js +7 -0
- package/src/utils/loginParser/textUtils.js +6 -0
- package/src/utils/request/config.js +4 -1
- package/src/utils/request/methods.js +0 -13
- package/src/utils/request/proxy.js +13 -0
- package/src/utils/request/retry.js +0 -10
- package/src/utils/request/sanitize.js +1 -1
- package/src/utils/sendThrottle.js +14 -1
- package/src/utils/textEffects.js +92 -0
- package/src/utils/utils.js +17 -3
- package/src/utils/instanceLock.js +0 -35
- package/src/utils/ipGuard.js +0 -58
|
@@ -1,31 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* MQTT/WebSocket listener for Facebook Messenger real-time events.
|
|
4
|
+
* Connects to edge-chat.facebook.com, subscribes to topics, parses deltas and typing/presence.
|
|
5
|
+
*/
|
|
3
6
|
const { formatID } = require("../../../utils/format");
|
|
4
7
|
const { getSessionIdentity } = require("../../../utils/clientIdentity");
|
|
5
8
|
|
|
6
|
-
const DEFAULT_RECONNECT_DELAY_MS =
|
|
7
|
-
const MAX_RECONNECT_DELAY_MS =
|
|
8
|
-
const MAX_RECONNECT_ATTEMPTS =
|
|
9
|
-
const MAX_RECONNECT_COOLDOWN_MS =
|
|
10
|
-
const T_MS_WAIT_TIMEOUT_MS =
|
|
11
|
-
|
|
12
|
-
function isImmediateReconnect(ctx) {
|
|
13
|
-
|
|
14
|
-
if (process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1") return true;
|
|
15
|
-
if (ctx && ctx._mqttOpt && ctx._mqttOpt.immediateReconnect === true) return true;
|
|
16
|
-
return false;
|
|
17
|
-
}
|
|
9
|
+
const DEFAULT_RECONNECT_DELAY_MS = 2000;
|
|
10
|
+
const MAX_RECONNECT_DELAY_MS = 60000;
|
|
11
|
+
const MAX_RECONNECT_ATTEMPTS = 10; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
|
|
12
|
+
const MAX_RECONNECT_COOLDOWN_MS = 10 * 60 * 1000; // after exhausting fast retries, wait this long before trying again (never give up permanently)
|
|
13
|
+
const T_MS_WAIT_TIMEOUT_MS = 5000;
|
|
18
14
|
|
|
15
|
+
// Exponential backoff with jitter, based on how many *consecutive* reconnect
|
|
16
|
+
// attempts have happened for this session (reset to 0 on a successful
|
|
17
|
+
// "connect" event). This replaces the old fixed 2s-every-time behavior,
|
|
18
|
+
// which could hammer the endpoint in a tight loop during real outages.
|
|
19
19
|
function computeBackoff(ctx, baseMs) {
|
|
20
20
|
const attempt = (ctx._reconnectAttempts || 0);
|
|
21
|
-
if (isImmediateReconnect(ctx)) {
|
|
22
|
-
if (attempt <= 1) return 0;
|
|
23
|
-
const fast = Math.min(1000 * Math.pow(2, attempt - 2), MAX_RECONNECT_DELAY_MS);
|
|
24
|
-
const j = Math.floor(Math.random() * Math.min(500, fast * 0.2));
|
|
25
|
-
return Math.min(fast + j, MAX_RECONNECT_DELAY_MS);
|
|
26
|
-
}
|
|
27
21
|
const exp = Math.min(baseMs * Math.pow(2, attempt), MAX_RECONNECT_DELAY_MS);
|
|
28
|
-
const jitter = Math.floor(Math.random() * Math.min(
|
|
22
|
+
const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
|
|
29
23
|
return Math.min(exp + jitter, MAX_RECONNECT_DELAY_MS);
|
|
30
24
|
}
|
|
31
25
|
|
|
@@ -37,20 +31,24 @@ module.exports = function createListenMqtt(deps) {
|
|
|
37
31
|
return function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
|
|
38
32
|
|
|
39
33
|
function scheduleReconnect(delayMs) {
|
|
40
|
-
ctx._mqttConnecting = false;
|
|
41
34
|
const base = (ctx._mqttOpt && ctx._mqttOpt.reconnectDelayMs) || DEFAULT_RECONNECT_DELAY_MS;
|
|
42
35
|
if (ctx._reconnectTimer) {
|
|
43
36
|
logger("mqtt reconnect already scheduled", "warn");
|
|
44
|
-
return;
|
|
37
|
+
return; // debounce
|
|
45
38
|
}
|
|
46
39
|
if (ctx._ending) {
|
|
47
|
-
|
|
40
|
+
// Covers confirmed logout/checkpoint/blocked-login/invalid-session:
|
|
41
|
+
// emitAuth() sets ctx._ending = true before this is ever reached for
|
|
42
|
+
// those cases, so we never auto-reconnect after a confirmed auth failure.
|
|
48
43
|
logger("mqtt reconnect skipped - ending", "warn");
|
|
49
44
|
return;
|
|
50
45
|
}
|
|
51
46
|
ctx._reconnectAttempts = (ctx._reconnectAttempts || 0) + 1;
|
|
52
47
|
if (ctx._reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
|
|
53
|
-
|
|
48
|
+
// [Fixed by xalman] Don't give up forever - a run of consecutive failures is usually a
|
|
49
|
+
// temporary outage (hosting network blip, FB-side hiccup), not a
|
|
50
|
+
// dead account. Back off to a long, FB-friendly cooldown and reset
|
|
51
|
+
// the counter so normal exponential backoff resumes after that.
|
|
54
52
|
const cooldownMs = MAX_RECONNECT_COOLDOWN_MS;
|
|
55
53
|
logger(`mqtt reconnect attempts exceeded (${MAX_RECONNECT_ATTEMPTS}); backing off ${Math.round(cooldownMs / 60000)}min before trying again (not giving up)`, "error");
|
|
56
54
|
globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded - will retry after cooldown" }, null);
|
|
@@ -64,7 +62,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
64
62
|
return;
|
|
65
63
|
}
|
|
66
64
|
const ms = typeof delayMs === "number" ? delayMs : computeBackoff(ctx, base);
|
|
67
|
-
logger(`mqtt
|
|
65
|
+
logger(`mqtt will reconnect in ${ms}ms (attempt ${ctx._reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`, "warn");
|
|
68
66
|
ctx._reconnectTimer = setTimeout(() => {
|
|
69
67
|
ctx._reconnectTimer = null;
|
|
70
68
|
if (!ctx._ending) {
|
|
@@ -76,36 +74,26 @@ module.exports = function createListenMqtt(deps) {
|
|
|
76
74
|
return /No subscription existed|client disconnecting|socket hang up|ECONNRESET/i.test(msg || "");
|
|
77
75
|
}
|
|
78
76
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
ctx._mqttConnecting = true;
|
|
88
|
-
|
|
77
|
+
// Ensure only one MQTT connection exists for this session, and that any
|
|
78
|
+
// previous connection is fully closed (listeners removed, socket ended)
|
|
79
|
+
// before a new one is opened. Without this, a reconnect racing with a
|
|
80
|
+
// still-live prior connection could leave two live sockets publishing/
|
|
81
|
+
// subscribing under the same session, which looks like an invalid/
|
|
82
|
+
// duplicate session to the server.
|
|
89
83
|
if (ctx.mqttClient) {
|
|
90
84
|
try {
|
|
91
85
|
ctx.mqttClient.removeAllListeners();
|
|
92
|
-
ctx.mqttClient.end(true);
|
|
86
|
+
if (ctx.mqttClient.connected) ctx.mqttClient.end(true);
|
|
93
87
|
} catch (_) { }
|
|
94
88
|
ctx.mqttClient = undefined;
|
|
95
89
|
}
|
|
96
90
|
|
|
91
|
+
// Resolve the identity ONCE per session (cached on ctx) so MQTT and HTTP
|
|
92
|
+
// never disagree about User-Agent / Accept-Language mid-session.
|
|
97
93
|
const identity = getSessionIdentity(ctx);
|
|
98
94
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
const chatOn = ctx.globalOptions.online !== false;
|
|
104
|
-
|
|
105
|
-
if (!ctx._edgeSid) {
|
|
106
|
-
ctx._edgeSid = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
|
|
107
|
-
}
|
|
108
|
-
const sessionID = ctx._edgeSid;
|
|
95
|
+
const chatOn = ctx.globalOptions.online;
|
|
96
|
+
const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
|
|
109
97
|
const username = {
|
|
110
98
|
u: ctx.userID, s: sessionID, chat_on: chatOn, fg: false, d: ctx.clientId,
|
|
111
99
|
ct: "websocket", aid: 219994525426954, aids: null, mqtt_sid: "",
|
|
@@ -137,7 +125,10 @@ module.exports = function createListenMqtt(deps) {
|
|
|
137
125
|
Upgrade: "websocket",
|
|
138
126
|
"Sec-WebSocket-Version": "13",
|
|
139
127
|
"Accept-Encoding": "gzip, deflate, br",
|
|
140
|
-
|
|
128
|
+
// Must match the Accept-Language used for HTTP requests in this same
|
|
129
|
+
// session (src/utils/headers.js) - it previously hard-coded "vi,en;q=0.9"
|
|
130
|
+
// here while HTTP requests defaulted to "en-US,en;q=0.9,vi;q=0.8",
|
|
131
|
+
// which is a contradictory-client signal between the two channels.
|
|
141
132
|
"Accept-Language": identity.acceptLanguage,
|
|
142
133
|
"Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits"
|
|
143
134
|
},
|
|
@@ -145,10 +136,10 @@ module.exports = function createListenMqtt(deps) {
|
|
|
145
136
|
protocolVersion: 13,
|
|
146
137
|
binaryType: "arraybuffer"
|
|
147
138
|
},
|
|
148
|
-
keepalive:
|
|
139
|
+
keepalive: 30,
|
|
149
140
|
reschedulePings: true,
|
|
150
141
|
reconnectPeriod: 0,
|
|
151
|
-
connectTimeout:
|
|
142
|
+
connectTimeout: 5000
|
|
152
143
|
};
|
|
153
144
|
if (ctx.globalOptions.proxy !== undefined) {
|
|
154
145
|
const agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
|
|
@@ -162,7 +153,6 @@ module.exports = function createListenMqtt(deps) {
|
|
|
162
153
|
const mqttClient = ctx.mqttClient;
|
|
163
154
|
|
|
164
155
|
mqttClient.on("error", function (err) {
|
|
165
|
-
ctx._mqttConnecting = false;
|
|
166
156
|
const msg = String(err && err.message ? err.message : err || "");
|
|
167
157
|
if ((ctx._ending || ctx._cycling) && /No subscription existed|client disconnecting/i.test(msg)) {
|
|
168
158
|
logger(`mqtt expected during shutdown: ${msg}`, "info");
|
|
@@ -174,20 +164,24 @@ module.exports = function createListenMqtt(deps) {
|
|
|
174
164
|
return;
|
|
175
165
|
}
|
|
176
166
|
|
|
177
|
-
if (/Not logged in|blocked the login|
|
|
167
|
+
if (/Not logged in|Not logged in.|blocked the login|401|403/i.test(msg)) {
|
|
178
168
|
try {
|
|
179
169
|
if (mqttClient && mqttClient.connected) {
|
|
180
170
|
mqttClient.end(true);
|
|
181
171
|
}
|
|
182
172
|
} catch (_) { }
|
|
183
|
-
|
|
184
|
-
if (/blocked the login/i.test(msg)) {
|
|
173
|
+
if (/blocked/i.test(msg)) {
|
|
185
174
|
return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
|
|
186
175
|
}
|
|
187
176
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
177
|
+
// Auth responses can race with the shared cookie refresh triggered by
|
|
178
|
+
// another request. Treat a plain 401/403/"Not logged in" MQTT error as
|
|
179
|
+
// recoverable instead of emitting account_inactive and permanently
|
|
180
|
+
// setting ctx._ending. The close handler/scheduler will establish a
|
|
181
|
+
// fresh MQTT connection with the refreshed session.
|
|
182
|
+
logger(`mqtt transient auth error; reconnecting without logging out: ${msg}`, "warn");
|
|
183
|
+
if (!ctx._ending && ctx.globalOptions.autoReconnect) {
|
|
184
|
+
scheduleReconnect();
|
|
191
185
|
}
|
|
192
186
|
return;
|
|
193
187
|
}
|
|
@@ -199,8 +193,11 @@ module.exports = function createListenMqtt(deps) {
|
|
|
199
193
|
} catch (_) { }
|
|
200
194
|
if (ctx._ending || ctx._cycling) return;
|
|
201
195
|
|
|
202
|
-
if (ctx.globalOptions
|
|
203
|
-
|
|
196
|
+
if (ctx.globalOptions.autoReconnect && !ctx._ending) {
|
|
197
|
+
// Let scheduleReconnect() compute the exponential-backoff delay
|
|
198
|
+
// itself (instead of always passing the same fixed base delay),
|
|
199
|
+
// so repeated network failures back off instead of retrying every
|
|
200
|
+
// ~2s indefinitely.
|
|
204
201
|
scheduleReconnect();
|
|
205
202
|
} else {
|
|
206
203
|
globalCallback({ type: "stop_listen", error: msg || "Connection refused" }, null);
|
|
@@ -213,15 +210,15 @@ module.exports = function createListenMqtt(deps) {
|
|
|
213
210
|
process.env.OnStatus = true;
|
|
214
211
|
}
|
|
215
212
|
ctx._cycling = false;
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
213
|
+
// A successful connect means the session/identity/network are fine -
|
|
214
|
+
// reset the backoff counter so a later transient failure starts a
|
|
215
|
+
// fresh backoff sequence instead of inheriting a long delay from an
|
|
216
|
+
// unrelated earlier outage.
|
|
221
217
|
ctx._reconnectAttempts = 0;
|
|
222
218
|
|
|
223
219
|
topics.forEach(t => mqttClient.subscribe(t));
|
|
224
220
|
|
|
221
|
+
|
|
225
222
|
const queue = {
|
|
226
223
|
sync_api_version: 11, max_deltas_able_to_process: 100, delta_batch_size: 500,
|
|
227
224
|
encoding: "JSON", entity_fbid: ctx.userID, initial_titan_sequence_id: ctx.lastSeqId, device_params: null
|
|
@@ -229,25 +226,15 @@ module.exports = function createListenMqtt(deps) {
|
|
|
229
226
|
const topic = ctx.syncToken ? "/messenger_sync_get_diffs" : "/messenger_sync_create_queue";
|
|
230
227
|
if (ctx.syncToken) { queue.last_seq_id = ctx.lastSeqId; queue.sync_token = ctx.syncToken; }
|
|
231
228
|
mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
|
|
232
|
-
|
|
233
|
-
mqttClient.publish("/
|
|
234
|
-
if (chatOn) {
|
|
235
|
-
mqttClient.publish("/set_client_settings", JSON.stringify({ make_user_available_when_in_foreground: true }), { qos: 1 });
|
|
236
|
-
}
|
|
229
|
+
mqttClient.publish("/foreground_state", JSON.stringify({ foreground: chatOn }), { qos: 1 });
|
|
230
|
+
mqttClient.publish("/set_client_settings", JSON.stringify({ make_user_available_when_in_foreground: true }), { qos: 1 });
|
|
237
231
|
let rTimeout = setTimeout(function () {
|
|
238
232
|
rTimeout = null;
|
|
239
233
|
if (ctx._ending) {
|
|
240
234
|
logger("mqtt t_ms timeout skipped - ending", "warn");
|
|
241
235
|
return;
|
|
242
236
|
}
|
|
243
|
-
logger("mqtt t_ms timeout", "warn");
|
|
244
|
-
ctx._tmsMisses = (ctx._tmsMisses || 0) + 1;
|
|
245
|
-
if (ctx._tmsMisses < 2 && mqttClient && mqttClient.connected) {
|
|
246
|
-
try {
|
|
247
|
-
mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
|
|
248
|
-
} catch (_) { }
|
|
249
|
-
return;
|
|
250
|
-
}
|
|
237
|
+
logger("mqtt t_ms timeout, cycling", "warn");
|
|
251
238
|
try {
|
|
252
239
|
if (mqttClient && mqttClient.connected) {
|
|
253
240
|
mqttClient.end(true);
|
|
@@ -256,6 +243,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
256
243
|
scheduleReconnect();
|
|
257
244
|
}, T_MS_WAIT_TIMEOUT_MS);
|
|
258
245
|
|
|
246
|
+
// Store timeout reference for cleanup
|
|
259
247
|
ctx._rTimeout = rTimeout;
|
|
260
248
|
|
|
261
249
|
ctx.tmsWait = function () {
|
|
@@ -272,7 +260,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
272
260
|
});
|
|
273
261
|
|
|
274
262
|
mqttClient.on("message", function (topic, message) {
|
|
275
|
-
if (ctx._ending) return;
|
|
263
|
+
if (ctx._ending) return; // Ignore messages if ending
|
|
276
264
|
try {
|
|
277
265
|
let jsonMessage = Buffer.isBuffer(message) ? Buffer.from(message).toString() : message;
|
|
278
266
|
try {
|
|
@@ -326,18 +314,17 @@ module.exports = function createListenMqtt(deps) {
|
|
|
326
314
|
} catch (ex) {
|
|
327
315
|
const errMsg = ex && ex.message ? ex.message : String(ex || "Unknown error");
|
|
328
316
|
logger(`mqtt message handler error: ${errMsg}`, "error");
|
|
329
|
-
|
|
317
|
+
// Don't crash on message parsing errors, just log and continue
|
|
330
318
|
}
|
|
331
319
|
});
|
|
332
320
|
|
|
333
321
|
mqttClient.on("close", function () {
|
|
334
|
-
ctx._mqttConnecting = false;
|
|
335
322
|
if (ctx._ending || ctx._cycling) {
|
|
336
323
|
logger("mqtt close expected", "info");
|
|
337
324
|
return;
|
|
338
325
|
}
|
|
339
326
|
logger("mqtt connection closed", "warn");
|
|
340
|
-
if (ctx.globalOptions
|
|
327
|
+
if (ctx.globalOptions.autoReconnect && !ctx._ending) {
|
|
341
328
|
scheduleReconnect();
|
|
342
329
|
}
|
|
343
330
|
});
|
|
@@ -348,7 +335,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
348
335
|
return;
|
|
349
336
|
}
|
|
350
337
|
logger("mqtt disconnected", "warn");
|
|
351
|
-
if (ctx.globalOptions
|
|
338
|
+
if (ctx.globalOptions.autoReconnect && !ctx._ending) {
|
|
352
339
|
scheduleReconnect();
|
|
353
340
|
}
|
|
354
341
|
});
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Emits account_inactive to the global callback and cleans up MQTT/timers/scheduler.
|
|
4
|
+
* Used when login is invalid, blocked, or session is lost.
|
|
5
|
+
*/
|
|
3
6
|
module.exports = function createEmitAuth({ logger }) {
|
|
4
7
|
return function emitAuth(ctx, api, globalCallback, reason, detail) {
|
|
5
|
-
|
|
8
|
+
// Clean up all timers
|
|
6
9
|
try {
|
|
7
10
|
if (ctx._autoCycleTimer) {
|
|
8
11
|
clearInterval(ctx._autoCycleTimer);
|
|
@@ -21,6 +24,7 @@ module.exports = function createEmitAuth({ logger }) {
|
|
|
21
24
|
ctx._cycling = false;
|
|
22
25
|
} catch (_) { }
|
|
23
26
|
|
|
27
|
+
// Clean up MQTT client
|
|
24
28
|
try {
|
|
25
29
|
if (ctx.mqttClient) {
|
|
26
30
|
ctx.mqttClient.removeAllListeners();
|
|
@@ -33,6 +37,7 @@ module.exports = function createEmitAuth({ logger }) {
|
|
|
33
37
|
ctx.mqttClient = undefined;
|
|
34
38
|
ctx.loggedIn = false;
|
|
35
39
|
|
|
40
|
+
// Clean up timeout references
|
|
36
41
|
try {
|
|
37
42
|
if (ctx._rTimeout) {
|
|
38
43
|
clearTimeout(ctx._rTimeout);
|
|
@@ -40,12 +45,14 @@ module.exports = function createEmitAuth({ logger }) {
|
|
|
40
45
|
}
|
|
41
46
|
} catch (_) { }
|
|
42
47
|
|
|
48
|
+
// Clean up tasks Map to prevent memory leak
|
|
43
49
|
try {
|
|
44
50
|
if (ctx.tasks && ctx.tasks instanceof Map) {
|
|
45
51
|
ctx.tasks.clear();
|
|
46
52
|
}
|
|
47
53
|
} catch (_) { }
|
|
48
54
|
|
|
55
|
+
// Clean up userInfo intervals
|
|
49
56
|
try {
|
|
50
57
|
if (ctx._userInfoIntervals && Array.isArray(ctx._userInfoIntervals)) {
|
|
51
58
|
ctx._userInfoIntervals.forEach(interval => {
|
|
@@ -57,6 +64,7 @@ module.exports = function createEmitAuth({ logger }) {
|
|
|
57
64
|
}
|
|
58
65
|
} catch (_) { }
|
|
59
66
|
|
|
67
|
+
// Clean up autoSave intervals
|
|
60
68
|
try {
|
|
61
69
|
if (ctx._autoSaveInterval && Array.isArray(ctx._autoSaveInterval)) {
|
|
62
70
|
ctx._autoSaveInterval.forEach(interval => {
|
|
@@ -68,6 +76,7 @@ module.exports = function createEmitAuth({ logger }) {
|
|
|
68
76
|
}
|
|
69
77
|
} catch (_) { }
|
|
70
78
|
|
|
79
|
+
// Clean up scheduler
|
|
71
80
|
try {
|
|
72
81
|
if (ctx._scheduler && typeof ctx._scheduler.destroy === "function") {
|
|
73
82
|
ctx._scheduler.destroy();
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Fetches MQTT sync sequence ID from GraphQL and starts listenMqtt.
|
|
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.
|
|
6
|
+
*/
|
|
3
7
|
const { getType } = require("../../../utils/format");
|
|
4
8
|
const { parseAndCheckLogin } = require("../../../utils/client");
|
|
5
9
|
const path = require("path");
|
|
@@ -16,6 +20,7 @@ function getConfig() {
|
|
|
16
20
|
return {};
|
|
17
21
|
}
|
|
18
22
|
|
|
23
|
+
// Parse cookie string to array format
|
|
19
24
|
function parseCookieString(cookieStr) {
|
|
20
25
|
if (!cookieStr || typeof cookieStr !== "string") return [];
|
|
21
26
|
const cookies = [];
|
|
@@ -38,6 +43,7 @@ function parseCookieString(cookieStr) {
|
|
|
38
43
|
return cookies;
|
|
39
44
|
}
|
|
40
45
|
|
|
46
|
+
// Try to auto-login using API and refresh web session
|
|
41
47
|
async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
|
|
42
48
|
const email = config.credentials?.email || config.email;
|
|
43
49
|
const password = config.credentials?.password || config.password;
|
|
@@ -47,13 +53,6 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
|
|
|
47
53
|
return null;
|
|
48
54
|
}
|
|
49
55
|
|
|
50
|
-
let allowed = false;
|
|
51
|
-
try { allowed = require("../../../../module/loginHelper").credentialLoginAllowed(); } catch (_) {}
|
|
52
|
-
if (!allowed) {
|
|
53
|
-
logger("getSeqID: credential re-login disabled (6.8.7) - keeping current cookie, no password login", "warn");
|
|
54
|
-
return null;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
56
|
logger("getSeqID: attempting auto re-login via API...", "warn");
|
|
58
57
|
|
|
59
58
|
try {
|
|
@@ -70,7 +69,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
|
|
|
70
69
|
|
|
71
70
|
if (typeof result.cookies === "string") {
|
|
72
71
|
cookiePairs = normalizeCookieHeaderString(result.cookies);
|
|
73
|
-
}
|
|
72
|
+
}
|
|
74
73
|
else if (Array.isArray(result.cookies)) {
|
|
75
74
|
cookiePairs = result.cookies.map(c => {
|
|
76
75
|
if (typeof c === "string") return c;
|
|
@@ -78,7 +77,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
|
|
|
78
77
|
return null;
|
|
79
78
|
}).filter(Boolean);
|
|
80
79
|
}
|
|
81
|
-
|
|
80
|
+
|
|
82
81
|
if (cookiePairs.length === 0 && result.cookie) {
|
|
83
82
|
if (typeof result.cookie === "string") {
|
|
84
83
|
cookiePairs = normalizeCookieHeaderString(result.cookie);
|
|
@@ -129,12 +128,12 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
|
|
|
129
128
|
try {
|
|
130
129
|
const urlToUse = attempt === 0 ? urlsToTry[0] : urlsToTry[attempt % urlsToTry.length];
|
|
131
130
|
logger(`getSeqID: Refreshing ${urlToUse} (attempt ${attempt + 1}/3)...`, "info");
|
|
132
|
-
|
|
131
|
+
|
|
133
132
|
webResponse = await get(urlToUse, ctx.jar, null, ctx.globalOptions, ctx);
|
|
134
133
|
if (webResponse && webResponse.data) {
|
|
135
134
|
await saveWebCookies(ctx.jar)(webResponse);
|
|
136
135
|
htmlContent = typeof webResponse.data === "string" ? webResponse.data : String(webResponse.data || "");
|
|
137
|
-
|
|
136
|
+
|
|
138
137
|
const htmlUserID = htmlUID(htmlContent);
|
|
139
138
|
if (isValidUID(htmlUserID)) {
|
|
140
139
|
logger(`getSeqID: Found valid USER_ID in HTML from ${urlToUse}: ${htmlUserID}`, "info");
|
|
@@ -155,12 +154,12 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
|
|
|
155
154
|
if (webResponse && webResponse.data) {
|
|
156
155
|
const updatedCookies = await ctx.jar.getCookies("https://www.facebook.com");
|
|
157
156
|
logger(`getSeqID: refreshed session, now have ${updatedCookies.length} web cookies`, "info");
|
|
158
|
-
|
|
157
|
+
|
|
159
158
|
const htmlUserID = htmlUID(htmlContent);
|
|
160
159
|
if (!isValidUID(htmlUserID)) {
|
|
161
160
|
logger("getSeqID: WARNING - HTML does not show valid USER_ID after refresh. Session may not be fully established.", "warn");
|
|
162
161
|
}
|
|
163
|
-
|
|
162
|
+
|
|
164
163
|
if (ctx) {
|
|
165
164
|
ctx.loggedIn = true;
|
|
166
165
|
if (isValidUID(htmlUserID)) {
|
|
@@ -194,10 +193,11 @@ module.exports = function createGetSeqID(deps) {
|
|
|
194
193
|
const { listenMqtt, logger, emitAuth } = deps;
|
|
195
194
|
|
|
196
195
|
return function getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount = 0) {
|
|
197
|
-
const MAX_RETRIES =
|
|
198
|
-
const RETRY_DELAY =
|
|
196
|
+
const MAX_RETRIES = 3;
|
|
197
|
+
const RETRY_DELAY = 2000;
|
|
199
198
|
ctx.t_mqttCalled = false;
|
|
200
199
|
|
|
200
|
+
// Ensure essential tokens are injected into GraphQL Batch Payload
|
|
201
201
|
if (!form) {
|
|
202
202
|
form = {
|
|
203
203
|
av: ctx.globalOptions.pageID || ctx.userID,
|
|
@@ -225,10 +225,11 @@ module.exports = function createGetSeqID(deps) {
|
|
|
225
225
|
.post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
|
|
226
226
|
.then(parseAndCheckLogin(ctx, defaultFuncs))
|
|
227
227
|
.then(async resData => {
|
|
228
|
-
|
|
228
|
+
// Safe check for non-array responses (such as Error Objects from FB)
|
|
229
229
|
if (getType(resData) !== "Array") {
|
|
230
230
|
logger(`getSeqID: Response is not Array, received: ${getType(resData)}`, "warn");
|
|
231
231
|
|
|
232
|
+
// Handle Facebook GraphQL 1357032 or transient error responses without triggering re-login
|
|
232
233
|
if (resData && typeof resData === "object") {
|
|
233
234
|
const errCode = resData.error || resData.errorCode;
|
|
234
235
|
const errorMsg = resData.errorSummary || resData.message || "";
|
|
@@ -240,11 +241,12 @@ module.exports = function createGetSeqID(deps) {
|
|
|
240
241
|
return;
|
|
241
242
|
}
|
|
242
243
|
|
|
243
|
-
if (/Not logged in|login
|
|
244
|
+
if (/Not logged in|login|blocked|401|403|checkpoint/i.test(errorMsg)) {
|
|
244
245
|
throw { error: "Not logged in", originalResponse: resData };
|
|
245
246
|
}
|
|
246
247
|
}
|
|
247
248
|
|
|
249
|
+
// Fallback if it's an unrecognized object
|
|
248
250
|
ctx.lastSeqId = ctx.lastSeqId || "0";
|
|
249
251
|
listenMqtt(defaultFuncs, api, ctx, globalCallback);
|
|
250
252
|
return;
|
|
@@ -268,7 +270,7 @@ module.exports = function createGetSeqID(deps) {
|
|
|
268
270
|
const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
|
|
269
271
|
const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
|
|
270
272
|
|
|
271
|
-
const isAuthError = /Not logged in|no sync_sequence_id found|blocked the login
|
|
273
|
+
const isAuthError = /Not logged in|no sync_sequence_id found|blocked the login|401|403/i.test(msg);
|
|
272
274
|
const netCode = err?.code || err?.originalError?.code || "";
|
|
273
275
|
const isNetworkError = !isAuthError && (
|
|
274
276
|
/timeout|ECONNRESET|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|network error|socket hang up/i.test(msg) ||
|
|
@@ -283,7 +285,8 @@ module.exports = function createGetSeqID(deps) {
|
|
|
283
285
|
return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
|
|
284
286
|
}
|
|
285
287
|
logger(`getSeqID: network error persisted after ${MAX_RETRIES} retries, giving up for now: ${msg}`, "error");
|
|
286
|
-
|
|
288
|
+
// [Fixed by xalman] throw instead of silently returning undefined -
|
|
289
|
+
// a bare return here made the caller think this call SUCCEEDED.
|
|
287
290
|
const giveUpErr = new Error(`getSeqID network error persisted after ${MAX_RETRIES} retries: ${msg}`);
|
|
288
291
|
giveUpErr.error = msg;
|
|
289
292
|
giveUpErr.isNetworkError = true;
|
|
@@ -293,50 +296,43 @@ module.exports = function createGetSeqID(deps) {
|
|
|
293
296
|
if (isAuthError) {
|
|
294
297
|
if (retryCount < MAX_RETRIES) {
|
|
295
298
|
const delay = RETRY_DELAY * (retryCount + 1);
|
|
296
|
-
logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms
|
|
299
|
+
logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (error: ${msg})`, "warn");
|
|
297
300
|
await new Promise(resolve => setTimeout(resolve, delay));
|
|
301
|
+
|
|
302
|
+
if (retryCount === 0 && ctx.loggedIn) {
|
|
303
|
+
try {
|
|
304
|
+
logger("getSeqID: refreshing session before retry...", "info");
|
|
305
|
+
const { get } = require("../../../utils/request");
|
|
306
|
+
const { saveCookies } = require("../../../utils/client");
|
|
307
|
+
await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
|
|
308
|
+
} catch (refreshErr) {
|
|
309
|
+
logger(`getSeqID: session refresh failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
298
313
|
return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
|
|
299
314
|
}
|
|
300
315
|
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
316
|
+
logger("getSeqID: all retries failed, attempting auto re-login...", "warn");
|
|
317
|
+
const config = getConfig();
|
|
318
|
+
const loginResult = await tryAutoLogin(logger, config, ctx, defaultFuncs);
|
|
304
319
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
type: "session_recovering",
|
|
311
|
-
error: msg,
|
|
312
|
-
timestamp: Date.now()
|
|
313
|
-
}, null);
|
|
314
|
-
}
|
|
315
|
-
} catch (_) {}
|
|
320
|
+
if (loginResult) {
|
|
321
|
+
logger("getSeqID: retrying with new session...", "info");
|
|
322
|
+
await new Promise(resolve => setTimeout(resolve, 3000));
|
|
323
|
+
return getSeqID(defaultFuncs, api, ctx, globalCallback, form, 0);
|
|
324
|
+
}
|
|
316
325
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
} catch (e) {
|
|
324
|
-
logger(`getSeqID soft recovery error: ${e && e.message ? e.message : e}`, "error");
|
|
325
|
-
}
|
|
326
|
-
}, softDelay);
|
|
327
|
-
return;
|
|
326
|
+
if (/blocked/i.test(msg)) {
|
|
327
|
+
return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
|
|
328
|
+
}
|
|
329
|
+
if (/Not logged in/i.test(msg)) {
|
|
330
|
+
return emitAuth(ctx, api, globalCallback, "not_logged_in", msg);
|
|
331
|
+
}
|
|
328
332
|
}
|
|
329
333
|
|
|
330
|
-
logger(`getSeqID error
|
|
331
|
-
|
|
332
|
-
if (typeof globalCallback === "function") {
|
|
333
|
-
globalCallback({ type: "session_recovering", error: msg, timestamp: Date.now() }, null);
|
|
334
|
-
}
|
|
335
|
-
} catch (_) {}
|
|
336
|
-
setTimeout(() => {
|
|
337
|
-
if (ctx._ending) return;
|
|
338
|
-
try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
|
|
339
|
-
}, 120000);
|
|
334
|
+
logger(`getSeqID error: ${msg}`, "error");
|
|
335
|
+
return emitAuth(ctx, api, globalCallback, "auth_error", msg);
|
|
340
336
|
});
|
|
341
337
|
};
|
|
342
338
|
};
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Builds a duplex stream over WebSocket for MQTT: proxy for writes, PassThrough for reads.
|
|
4
|
+
* Handles ping/pong, liveness timeout, and clean shutdown.
|
|
5
|
+
*/
|
|
3
6
|
const { Writable, PassThrough } = require("stream");
|
|
4
7
|
const Duplexify = require("duplexify");
|
|
5
8
|
|