fca-nx 7.5.6 → 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 +28 -0
- package/docs/ERRORS.md +46 -0
- package/docs/LIMITATIONS.md +32 -0
- package/index.d.ts +19 -0
- package/index.js +4 -0
- package/module/login.js +19 -12
- package/module/loginHelper.js +100 -154
- package/package.json +5 -3
- package/src/api/messaging/sessionGuard.js +5 -1
- package/src/api/socket/OldMessage.js +24 -8
- package/src/api/socket/core/connectMqtt.js +62 -86
- package/src/api/socket/core/emitAuth.js +7 -0
- package/src/api/socket/core/getSeqID.js +13 -3
- package/src/api/socket/core/reconnectPolicy.js +40 -0
- package/src/api/socket/e2ee/index.js +4 -2
- package/src/api/socket/legacySendError.js +35 -0
- package/src/api/socket/listenE2EE.js +2 -2
- package/src/api/socket/listenMqtt.js +17 -37
- package/src/api/socket/sendMessage.js +7 -3
- package/src/database/models/index.js +22 -17
- package/src/database/threadData.js +6 -0
- package/src/database/userData.js +6 -0
- package/src/utils/appStateCookies.js +151 -0
- package/src/utils/fcaError.js +188 -0
- package/src/utils/jarSnapshot.js +20 -0
- package/src/utils/logSanitize.js +36 -0
- package/src/utils/request/methods.js +6 -4
- package/src/utils/request/retry.js +63 -29
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
var utils = require("../../utils/utils");
|
|
4
4
|
var logger = require("../../utils/logger");
|
|
5
5
|
var bluebird = require("bluebird");
|
|
6
|
+
var { snapshotJar } = require("../../utils/jarSnapshot");
|
|
7
|
+
var { legacySendFailure, shouldBounceToMqtt } = require("./legacySendError");
|
|
6
8
|
var allowedProperties = {
|
|
7
9
|
attachment: true, url: true, sticker: true, emoji: true,
|
|
8
10
|
emojiSize: true, body: true, mentions: true, location: true
|
|
@@ -16,6 +18,16 @@ var ignoredEffectKeys = {
|
|
|
16
18
|
|
|
17
19
|
module.exports = function (defaultFuncs, api, ctx) {
|
|
18
20
|
|
|
21
|
+
function requestJar() {
|
|
22
|
+
return snapshotJar(ctx.jar);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function fail(scope, err, callback) {
|
|
26
|
+
var safe = legacySendFailure(err);
|
|
27
|
+
logger.error(scope, safe && safe.message ? safe.message : "send failed");
|
|
28
|
+
callback(safe);
|
|
29
|
+
}
|
|
30
|
+
|
|
19
31
|
function uploadAttachment(attachments, callback) {
|
|
20
32
|
var uploads = [];
|
|
21
33
|
for (var i = 0; i < attachments.length; i++) {
|
|
@@ -23,7 +35,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
23
35
|
return callback({ error: "Attachment must be a readable stream." });
|
|
24
36
|
}
|
|
25
37
|
uploads.push(
|
|
26
|
-
defaultFuncs.postFormData("https://upload.facebook.com/ajax/mercury/upload.php",
|
|
38
|
+
defaultFuncs.postFormData("https://upload.facebook.com/ajax/mercury/upload.php", requestJar(), {
|
|
27
39
|
upload_1024: attachments[i],
|
|
28
40
|
voice_clip: "true"
|
|
29
41
|
})
|
|
@@ -36,11 +48,11 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
36
48
|
}
|
|
37
49
|
bluebird.all(uploads)
|
|
38
50
|
.then(resData => callback(null, resData))
|
|
39
|
-
.catch(err =>
|
|
51
|
+
.catch(err => fail("OldMessage.upload", err, callback));
|
|
40
52
|
}
|
|
41
53
|
|
|
42
54
|
function getUrl(url, callback) {
|
|
43
|
-
defaultFuncs.post("https://www.facebook.com/message_share_attachment/fromURI/",
|
|
55
|
+
defaultFuncs.post("https://www.facebook.com/message_share_attachment/fromURI/", requestJar(), {
|
|
44
56
|
image_height: 960, image_width: 960, uri: url
|
|
45
57
|
})
|
|
46
58
|
.then(utils.parseAndCheckLogin(ctx, defaultFuncs))
|
|
@@ -49,7 +61,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
49
61
|
if (!resData.payload) return callback({ error: "Invalid URL" });
|
|
50
62
|
callback(null, resData.payload.share_data.share_params);
|
|
51
63
|
})
|
|
52
|
-
.catch(err =>
|
|
64
|
+
.catch(err => fail("OldMessage.getUrl", err, callback));
|
|
53
65
|
}
|
|
54
66
|
|
|
55
67
|
function sendContent(form, threadID, isSingleUser, messageAndOTID, callback) {
|
|
@@ -74,7 +86,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
74
86
|
form["creator_info[creatorType]"] = "direct_admin";
|
|
75
87
|
}
|
|
76
88
|
|
|
77
|
-
defaultFuncs.post("https://www.facebook.com/messaging/send/",
|
|
89
|
+
defaultFuncs.post("https://www.facebook.com/messaging/send/", requestJar(), form)
|
|
78
90
|
.then(utils.parseAndCheckLogin(ctx, defaultFuncs))
|
|
79
91
|
.then(resData => {
|
|
80
92
|
if (!resData.payload) throw resData;
|
|
@@ -88,7 +100,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
88
100
|
timestamp: resData.payload.timestamp
|
|
89
101
|
});
|
|
90
102
|
})
|
|
91
|
-
.catch(err =>
|
|
103
|
+
.catch(err => fail("OldMessage.send", err, callback));
|
|
92
104
|
}
|
|
93
105
|
|
|
94
106
|
function send(form, threadID, isSingleUser, callback) {
|
|
@@ -119,9 +131,13 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
119
131
|
|
|
120
132
|
return function OldMessage(msg, threadID, callback, replyToMessage, isSingleUser) {
|
|
121
133
|
if (typeof msg === "string") msg = { body: msg };
|
|
134
|
+
var fromFallback = !!(msg && msg.__fcaSendFallback);
|
|
135
|
+
if (msg && Object.prototype.hasOwnProperty.call(msg, "__fcaSendFallback")) {
|
|
136
|
+
delete msg.__fcaSendFallback;
|
|
137
|
+
}
|
|
122
138
|
|
|
123
|
-
if (msg
|
|
124
|
-
return require(
|
|
139
|
+
if (shouldBounceToMqtt(msg && msg.body, fromFallback)) {
|
|
140
|
+
return require("./sendMessage")(defaultFuncs, api, ctx)(msg, threadID, callback, replyToMessage, isSingleUser);
|
|
125
141
|
}
|
|
126
142
|
|
|
127
143
|
var resolveFunc = () => { };
|
|
@@ -6,13 +6,12 @@
|
|
|
6
6
|
const { formatID } = require("../../../utils/format");
|
|
7
7
|
const { getSessionIdentity } = require("../../../utils/clientIdentity");
|
|
8
8
|
const { isSessionEnforcement } = require("../../../utils/sessionStatus");
|
|
9
|
+
const { planReconnect, mqttAuthFailureKind, isCurrentMqttSocket } = require("./reconnectPolicy");
|
|
9
10
|
|
|
10
11
|
const DEFAULT_RECONNECT_DELAY_MS = 8000;
|
|
11
12
|
const MAX_RECONNECT_DELAY_MS = 120000;
|
|
12
|
-
const RECONNECT_CHECKS = 3; // reconnect checks before a fresh login
|
|
13
|
-
const RECONNECT_INTERVAL_MS = 5000; // fixed gap between checks
|
|
14
13
|
const MAX_RECONNECT_ATTEMPTS = 5; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
|
|
15
|
-
const MAX_RECONNECT_COOLDOWN_MS = 20 * 60 * 1000; // after exhausting fast retries, wait this long before trying
|
|
14
|
+
const MAX_RECONNECT_COOLDOWN_MS = 20 * 60 * 1000; // after exhausting fast retries, wait this long before trying the same session again
|
|
16
15
|
const T_MS_WAIT_TIMEOUT_MS = 15000;
|
|
17
16
|
|
|
18
17
|
// Facebook's edge PUBACK/PUBREC/PUBCOMP uses non-zero reserved flag bits.
|
|
@@ -40,17 +39,6 @@ function clearSyncTimer(ctx) {
|
|
|
40
39
|
}
|
|
41
40
|
}
|
|
42
41
|
|
|
43
|
-
// Exponential backoff with jitter, based on how many *consecutive* reconnect
|
|
44
|
-
// attempts have happened for this session (reset to 0 on a successful
|
|
45
|
-
// "connect" event). This replaces the old fixed 2s-every-time behavior,
|
|
46
|
-
// which could hammer the endpoint in a tight loop during real outages.
|
|
47
|
-
function computeBackoff(ctx, baseMs) {
|
|
48
|
-
const attempt = (ctx._reconnectAttempts || 0);
|
|
49
|
-
const exp = Math.min(baseMs * Math.pow(2, attempt), MAX_RECONNECT_DELAY_MS);
|
|
50
|
-
const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
|
|
51
|
-
return Math.min(exp + jitter, MAX_RECONNECT_DELAY_MS);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
42
|
module.exports = function createListenMqtt(deps) {
|
|
55
43
|
const { WebSocket, mqtt, HttpsProxyAgent, buildStream, buildProxy,
|
|
56
44
|
topics, parseDelta, getTaskResponseData, logger, emitAuth
|
|
@@ -62,74 +50,46 @@ module.exports = function createListenMqtt(deps) {
|
|
|
62
50
|
return;
|
|
63
51
|
}
|
|
64
52
|
|
|
65
|
-
function scheduleReconnect(
|
|
53
|
+
function scheduleReconnect(reason) {
|
|
66
54
|
if (ctx._stoppedForLogin) return;
|
|
67
|
-
const base = (ctx._mqttOpt && ctx._mqttOpt.reconnectDelayMs) || DEFAULT_RECONNECT_DELAY_MS;
|
|
68
55
|
if (ctx._reconnectTimer) {
|
|
69
56
|
logger("mqtt reconnect already scheduled", "warn");
|
|
70
|
-
return; // debounce
|
|
71
|
-
}
|
|
72
|
-
if (ctx._ending) {
|
|
73
|
-
// Covers confirmed logout/checkpoint/blocked-login/invalid-session:
|
|
74
|
-
// emitAuth() sets ctx._ending = true before this is ever reached for
|
|
75
|
-
// those cases, so we never auto-reconnect after a confirmed auth failure.
|
|
76
|
-
logger("mqtt reconnect skipped - ending", "warn");
|
|
77
57
|
return;
|
|
78
58
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
// All quick reconnect checks failed. Do a brand-new login instead of
|
|
82
|
-
// another reconnect: force the credential path (skip the cookie check).
|
|
83
|
-
ctx._reconnectAttempts = 0;
|
|
84
|
-
logger(`mqtt ${RECONNECT_CHECKS} reconnect checks failed; starting a fresh login`, "error");
|
|
85
|
-
ctx._reconnectTimer = setTimeout(async () => {
|
|
86
|
-
ctx._reconnectTimer = null;
|
|
87
|
-
if (ctx._ending) return;
|
|
88
|
-
let ok = false;
|
|
89
|
-
try {
|
|
90
|
-
if (typeof ctx.performAutoLogin === "function") {
|
|
91
|
-
ctx._forceFreshLogin = true;
|
|
92
|
-
ok = await ctx.performAutoLogin();
|
|
93
|
-
}
|
|
94
|
-
} catch (loginErr) {
|
|
95
|
-
logger(`mqtt fresh login failed: ${loginErr && loginErr.message ? loginErr.message : String(loginErr)}`, "error");
|
|
96
|
-
ok = false;
|
|
97
|
-
} finally {
|
|
98
|
-
ctx._forceFreshLogin = false;
|
|
99
|
-
}
|
|
100
|
-
if (ok && !ctx._ending) {
|
|
101
|
-
ctx._stoppedForLogin = false;
|
|
102
|
-
listenMqtt(defaultFuncs, api, ctx, globalCallback);
|
|
103
|
-
} else if (!ctx._ending) {
|
|
104
|
-
ctx._stoppedForLogin = false;
|
|
105
|
-
ctx._reconnectAttempts = 0;
|
|
106
|
-
logger("mqtt fresh login unavailable for this cookie session; reconnecting with the current appstate", "warn");
|
|
107
|
-
ctx._reconnectTimer = setTimeout(() => {
|
|
108
|
-
ctx._reconnectTimer = null;
|
|
109
|
-
if (!ctx._ending) listenMqtt(defaultFuncs, api, ctx, globalCallback);
|
|
110
|
-
}, 15000);
|
|
111
|
-
} else {
|
|
112
|
-
ctx._stoppedForLogin = true;
|
|
113
|
-
ctx._ending = true;
|
|
114
|
-
clearTimeout(ctx._reconnectTimer);
|
|
115
|
-
ctx._reconnectTimer = null;
|
|
116
|
-
try {
|
|
117
|
-
if (ctx.mqttClient) ctx.mqttClient.end(true);
|
|
118
|
-
} catch (_) { }
|
|
119
|
-
logger("mqtt stopped: fresh login is not available for this cookie session (no credentials). Refresh appstate and restart the bot.", "error");
|
|
120
|
-
globalCallback({ type: "stop_listen", error: "Fresh login failed after reconnect checks" }, null);
|
|
121
|
-
}
|
|
122
|
-
}, 0);
|
|
59
|
+
if (ctx._ending || ctx._sessionEnforcement) {
|
|
60
|
+
logger("mqtt reconnect skipped - session ended or needs manual review", "warn");
|
|
123
61
|
return;
|
|
124
62
|
}
|
|
125
|
-
const
|
|
126
|
-
|
|
63
|
+
const decision = planReconnect({
|
|
64
|
+
attempts: ctx._reconnectAttempts || 0,
|
|
65
|
+
baseMs: (ctx._mqttOpt && ctx._mqttOpt.reconnectDelayMs) || DEFAULT_RECONNECT_DELAY_MS,
|
|
66
|
+
maxDelayMs: MAX_RECONNECT_DELAY_MS,
|
|
67
|
+
maxAttempts: (ctx._mqttOpt && ctx._mqttOpt.maxReconnectAttempts) || MAX_RECONNECT_ATTEMPTS,
|
|
68
|
+
cooldownMs: MAX_RECONNECT_COOLDOWN_MS,
|
|
69
|
+
reason: reason || "disconnect",
|
|
70
|
+
enforcement: false
|
|
71
|
+
});
|
|
72
|
+
ctx._reconnectAttempts = decision.action === "cooldown" ? 0 : decision.attempts;
|
|
73
|
+
logger(
|
|
74
|
+
`mqtt ${decision.action} in ${decision.delayMs}ms (${decision.reason}, next attempt counter ${decision.attempts}). Current appstate is kept; no credential login.`,
|
|
75
|
+
"warn"
|
|
76
|
+
);
|
|
77
|
+
if (decision.action === "cooldown" && typeof globalCallback === "function") {
|
|
78
|
+
try {
|
|
79
|
+
globalCallback({
|
|
80
|
+
type: "mqtt_reconnect_cooldown",
|
|
81
|
+
error: "Network retries are exhausted. Waiting before using the same session again. This is not a logout and not a new login.",
|
|
82
|
+
delayMs: decision.delayMs,
|
|
83
|
+
reason: decision.reason
|
|
84
|
+
}, null);
|
|
85
|
+
} catch (_) { }
|
|
86
|
+
}
|
|
127
87
|
ctx._reconnectTimer = setTimeout(() => {
|
|
128
88
|
ctx._reconnectTimer = null;
|
|
129
|
-
if (!ctx._ending) {
|
|
89
|
+
if (!ctx._ending && !ctx._sessionEnforcement) {
|
|
130
90
|
listenMqtt(defaultFuncs, api, ctx, globalCallback);
|
|
131
91
|
}
|
|
132
|
-
},
|
|
92
|
+
}, decision.delayMs);
|
|
133
93
|
}
|
|
134
94
|
function isEndingLikeError(msg) {
|
|
135
95
|
return /No subscription existed|client disconnecting|socket hang up|ECONNRESET/i.test(msg || "");
|
|
@@ -207,13 +167,19 @@ module.exports = function createListenMqtt(deps) {
|
|
|
207
167
|
options.wsOptions.agent = agent;
|
|
208
168
|
}
|
|
209
169
|
|
|
170
|
+
ctx._mqttGen = (ctx._mqttGen || 0) + 1;
|
|
171
|
+
const socketGen = ctx._mqttGen;
|
|
210
172
|
ctx.mqttClient = new mqtt.Client(
|
|
211
173
|
() => buildStream(options, new WebSocket(host, options.wsOptions), buildProxy()),
|
|
212
174
|
options
|
|
213
175
|
);
|
|
214
176
|
const mqttClient = ctx.mqttClient;
|
|
177
|
+
function stillThisSocket() {
|
|
178
|
+
return isCurrentMqttSocket(ctx._mqttGen, socketGen) && ctx.mqttClient === mqttClient;
|
|
179
|
+
}
|
|
215
180
|
|
|
216
181
|
mqttClient.on("error", function (err) {
|
|
182
|
+
if (!stillThisSocket()) return;
|
|
217
183
|
const msg = String(err && err.message ? err.message : err || "");
|
|
218
184
|
if ((ctx._ending || ctx._cycling) && /No subscription existed|client disconnecting/i.test(msg)) {
|
|
219
185
|
logger(`mqtt expected during shutdown: ${msg}`, "info");
|
|
@@ -236,24 +202,29 @@ module.exports = function createListenMqtt(deps) {
|
|
|
236
202
|
);
|
|
237
203
|
}
|
|
238
204
|
|
|
239
|
-
if (/Not logged in|
|
|
205
|
+
if (/Not logged in|blocked the login/i.test(msg) || mqttAuthFailureKind(msg)) {
|
|
240
206
|
try {
|
|
241
207
|
if (mqttClient && mqttClient.connected) {
|
|
242
208
|
mqttClient.end(true);
|
|
243
209
|
}
|
|
244
210
|
} catch (_) { }
|
|
245
|
-
|
|
211
|
+
const kind = mqttAuthFailureKind(msg) || (/blocked/i.test(msg) ? "login_blocked" : "not_logged_in");
|
|
212
|
+
if (kind === "login_blocked") {
|
|
246
213
|
return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
|
|
247
214
|
}
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
215
|
+
ctx._mqttAuthFailures = (ctx._mqttAuthFailures || 0) + 1;
|
|
216
|
+
if (ctx._mqttAuthFailures >= 2) {
|
|
217
|
+
return emitAuth(
|
|
218
|
+
ctx,
|
|
219
|
+
api,
|
|
220
|
+
globalCallback,
|
|
221
|
+
"not_logged_in",
|
|
222
|
+
"Messenger rejected the saved session. Refresh the appstate. Automatic credential login was not started."
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
logger(`mqtt auth-shaped error; reconnecting once with the current session and no credential login: ${msg}`, "warn");
|
|
255
226
|
if (!ctx._ending && ctx.globalOptions.autoReconnect) {
|
|
256
|
-
scheduleReconnect();
|
|
227
|
+
scheduleReconnect("auth_retry");
|
|
257
228
|
}
|
|
258
229
|
return;
|
|
259
230
|
}
|
|
@@ -277,15 +248,17 @@ module.exports = function createListenMqtt(deps) {
|
|
|
277
248
|
});
|
|
278
249
|
|
|
279
250
|
mqttClient.on("connect", function () {
|
|
251
|
+
if (!stillThisSocket()) return;
|
|
280
252
|
if (process.env.OnStatus === undefined) {
|
|
281
253
|
logger("fca-unofficial", "info");
|
|
282
254
|
process.env.OnStatus = true;
|
|
283
255
|
}
|
|
284
256
|
ctx._cycling = false;
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
257
|
+
ctx._reconnectAttempts = 0;
|
|
258
|
+
ctx._mqttAuthFailures = 0;
|
|
259
|
+
if (typeof ctx._attachMqttGuards === "function") {
|
|
260
|
+
try { ctx._attachMqttGuards(); } catch (_) { }
|
|
261
|
+
}
|
|
289
262
|
|
|
290
263
|
topics.forEach(t => mqttClient.subscribe(t));
|
|
291
264
|
|
|
@@ -331,7 +304,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
331
304
|
});
|
|
332
305
|
|
|
333
306
|
mqttClient.on("message", function (topic, message) {
|
|
334
|
-
if (ctx._ending) return;
|
|
307
|
+
if (!stillThisSocket() || ctx._ending) return;
|
|
335
308
|
try {
|
|
336
309
|
let jsonMessage = Buffer.isBuffer(message) ? Buffer.from(message).toString() : message;
|
|
337
310
|
try {
|
|
@@ -347,6 +320,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
347
320
|
globalCallback(null, { type: "friend_request_cancel", actorFbId: jsonMessage.from.toString(), timestamp: Date.now().toString() });
|
|
348
321
|
} else if (topic === "/t_ms") {
|
|
349
322
|
ctx._reconnectAttempts = 0;
|
|
323
|
+
ctx._mqttAuthFailures = 0;
|
|
350
324
|
ctx._badPuback = 0;
|
|
351
325
|
if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
|
|
352
326
|
if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
|
|
@@ -392,6 +366,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
392
366
|
});
|
|
393
367
|
|
|
394
368
|
mqttClient.on("close", function () {
|
|
369
|
+
if (!stillThisSocket()) return;
|
|
395
370
|
clearSyncTimer(ctx);
|
|
396
371
|
if (ctx._ending || ctx._cycling) {
|
|
397
372
|
logger("mqtt close expected", "info");
|
|
@@ -404,6 +379,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
404
379
|
});
|
|
405
380
|
|
|
406
381
|
mqttClient.on("disconnect", () => {
|
|
382
|
+
if (!stillThisSocket()) return;
|
|
407
383
|
if (ctx._ending || ctx._cycling) {
|
|
408
384
|
logger("mqtt disconnect expected", "info");
|
|
409
385
|
return;
|
|
@@ -41,6 +41,13 @@ module.exports = function createEmitAuth({ logger }) {
|
|
|
41
41
|
ctx.loggedIn = false;
|
|
42
42
|
|
|
43
43
|
// Clean up timeout references
|
|
44
|
+
try {
|
|
45
|
+
if (ctx._dtsgRefreshTimer) {
|
|
46
|
+
clearInterval(ctx._dtsgRefreshTimer);
|
|
47
|
+
ctx._dtsgRefreshTimer = null;
|
|
48
|
+
}
|
|
49
|
+
} catch (_) { }
|
|
50
|
+
|
|
44
51
|
try {
|
|
45
52
|
if (ctx._rTimeout) {
|
|
46
53
|
clearTimeout(ctx._rTimeout);
|
|
@@ -297,7 +297,7 @@ module.exports = function createGetSeqID(deps) {
|
|
|
297
297
|
return;
|
|
298
298
|
}
|
|
299
299
|
|
|
300
|
-
if (/Not logged in|login
|
|
300
|
+
if (/Not logged in|blocked the login/i.test(errorMsg)) {
|
|
301
301
|
throw { error: "Not logged in", originalResponse: resData };
|
|
302
302
|
}
|
|
303
303
|
}
|
|
@@ -347,7 +347,7 @@ module.exports = function createGetSeqID(deps) {
|
|
|
347
347
|
const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
|
|
348
348
|
const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
|
|
349
349
|
|
|
350
|
-
const isAuthError = /Not logged in|
|
|
350
|
+
const isAuthError = /Not logged in|blocked the login/i.test(msg);
|
|
351
351
|
const netCode = err?.code || err?.originalError?.code || "";
|
|
352
352
|
const isNetworkError = !isAuthError && (
|
|
353
353
|
/timeout|ECONNRESET|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|network error|socket hang up/i.test(msg) ||
|
|
@@ -412,8 +412,18 @@ module.exports = function createGetSeqID(deps) {
|
|
|
412
412
|
}
|
|
413
413
|
|
|
414
414
|
if (ctx._sessionEnforcement || ctx._ending) return;
|
|
415
|
-
|
|
415
|
+
if ((ctx._credentialReloginAttempts || 0) >= 1) {
|
|
416
|
+
logger("getSeqID: credential re-login already attempted for this session; not trying again", "error");
|
|
417
|
+
return emitAuth(ctx, api, globalCallback, "not_logged_in", "Saved session was rejected. Refresh the appstate instead of logging in again.");
|
|
418
|
+
}
|
|
416
419
|
const config = getConfig();
|
|
420
|
+
const autoLoginEnabled = config.autoLogin === true || config.autoLogin === "true";
|
|
421
|
+
if (!autoLoginEnabled) {
|
|
422
|
+
logger("getSeqID: session is not logged in and autoLogin is not explicitly enabled", "error");
|
|
423
|
+
return emitAuth(ctx, api, globalCallback, "not_logged_in", msg || "Not logged in");
|
|
424
|
+
}
|
|
425
|
+
ctx._credentialReloginAttempts = (ctx._credentialReloginAttempts || 0) + 1;
|
|
426
|
+
logger("getSeqID: all retries failed, attempting one credential re-login because autoLogin is explicitly enabled", "warn");
|
|
417
427
|
const loginResult = await tryAutoLogin(logger, config, ctx, defaultFuncs);
|
|
418
428
|
|
|
419
429
|
if (ctx._sessionEnforcement || ctx._ending) return;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
function planReconnect({
|
|
4
|
+
attempts = 0,
|
|
5
|
+
baseMs = 1000,
|
|
6
|
+
maxDelayMs = 300000,
|
|
7
|
+
maxAttempts = 8,
|
|
8
|
+
cooldownMs = 3600000,
|
|
9
|
+
reason = "unknown",
|
|
10
|
+
enforcement = false
|
|
11
|
+
} = {}) {
|
|
12
|
+
if (enforcement) {
|
|
13
|
+
return { action: "stop", delayMs: 0, attempts, reason };
|
|
14
|
+
}
|
|
15
|
+
const used = Number(attempts) || 0;
|
|
16
|
+
if (used >= maxAttempts) {
|
|
17
|
+
return { action: "cooldown", delayMs: cooldownMs, attempts: 0, reason };
|
|
18
|
+
}
|
|
19
|
+
const exp = Math.min(baseMs * Math.pow(2, used), maxDelayMs);
|
|
20
|
+
const jitterCap = Math.min(200, Math.floor(exp * 0.2));
|
|
21
|
+
const delayMs = Math.min(exp + Math.floor(Math.random() * (jitterCap + 1)), maxDelayMs);
|
|
22
|
+
return { action: "retry", delayMs, attempts: used + 1, reason };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function mqttAuthFailureKind(message) {
|
|
26
|
+
const text = String(message || "");
|
|
27
|
+
if (/blocked the login/i.test(text)) return "login_blocked";
|
|
28
|
+
if (/not logged in/i.test(text)) return "not_logged_in";
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isCurrentMqttSocket(activeGeneration, eventGeneration) {
|
|
33
|
+
return activeGeneration != null && activeGeneration === eventGeneration;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = {
|
|
37
|
+
planReconnect,
|
|
38
|
+
mqttAuthFailureKind,
|
|
39
|
+
isCurrentMqttSocket
|
|
40
|
+
};
|
|
@@ -122,7 +122,7 @@ class E2EEBridge {
|
|
|
122
122
|
? await _defaultFuncs.post(url, _ctx.jar, merged)
|
|
123
123
|
: await requestHttp.post(url, _ctx.jar, merged, {}, _ctx);
|
|
124
124
|
const body = res && (res.data !== undefined ? res.data : res.body);
|
|
125
|
-
if (body == null) return
|
|
125
|
+
if (body == null) return "";
|
|
126
126
|
if (typeof body === "string") return body;
|
|
127
127
|
if (Buffer.isBuffer(body)) return body.toString("utf8");
|
|
128
128
|
// axios auto-parses JSON bodies into an object/array, but the
|
|
@@ -143,7 +143,9 @@ class E2EEBridge {
|
|
|
143
143
|
setOptions: function () {},
|
|
144
144
|
// Delegate messaging methods to FCA-NX's real api
|
|
145
145
|
sendMessage: function (msg, threadID, callback, replyToMessage) {
|
|
146
|
-
|
|
146
|
+
var payload = typeof msg === "string" ? { body: msg } : Object.assign({}, msg);
|
|
147
|
+
payload.__fromE2EE = true;
|
|
148
|
+
return _fcanxApi.sendMessage(payload, threadID, callback, replyToMessage);
|
|
147
149
|
},
|
|
148
150
|
setMessageReaction: function (reaction, messageID, callback, force) {
|
|
149
151
|
if (typeof _fcanxApi.setMessageReaction === "function")
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const LINK_RE = /(https?:\/\/|www\.|t\.me\/|fb\.me\/|youtu\.be\/|facebook\.com\/|youtube\.com\/)/i;
|
|
4
|
+
|
|
5
|
+
function isLegacyAuthText(value) {
|
|
6
|
+
const text = String(value || "");
|
|
7
|
+
return text === "Not logged in" || text === "Not logged in.";
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function legacySendFailure(err) {
|
|
11
|
+
const text = err && (err.error || err.message) ? String(err.error || err.message) : "";
|
|
12
|
+
const numeric = err && (err.error === 1357001 || err.errorCode === 1357001 || (err.res && err.res.error === 1357001));
|
|
13
|
+
if (!numeric && !isLegacyAuthText(text)) return err;
|
|
14
|
+
const wrapped = new Error("Legacy Messenger send was rejected. The live session was not changed.");
|
|
15
|
+
wrapped.code = "LEGACY_SEND_REJECTED";
|
|
16
|
+
wrapped.error = "LEGACY_SEND_REJECTED";
|
|
17
|
+
wrapped.category = "unsupported_endpoint";
|
|
18
|
+
wrapped.recovery = "Retry the reply. This old send endpoint failing is not a logout and does not require a new appstate.";
|
|
19
|
+
return wrapped;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function shouldBounceToMqtt(body, fromFallback) {
|
|
23
|
+
if (fromFallback) return false;
|
|
24
|
+
return typeof body === "string" && LINK_RE.test(body);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function shouldIgnoreLegacyPostFailure(url) {
|
|
28
|
+
return /\/messaging\/send\/|mercury\/upload|message_share_attachment|reg-e2ee\.facebook\.com/i.test(String(url || ""));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
module.exports = {
|
|
32
|
+
legacySendFailure,
|
|
33
|
+
shouldBounceToMqtt,
|
|
34
|
+
shouldIgnoreLegacyPostFailure
|
|
35
|
+
};
|
|
@@ -44,8 +44,8 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
44
44
|
};
|
|
45
45
|
|
|
46
46
|
// Start regular MQTT listener
|
|
47
|
-
var mqttListener = api._listenMqttRaw
|
|
48
|
-
if (typeof mqttListener !== "function") {
|
|
47
|
+
var mqttListener = api._listenMqttRaw;
|
|
48
|
+
if (typeof mqttListener !== "function" || mqttListener === listenE2EE) {
|
|
49
49
|
throw new Error("listenE2EE: MQTT listener is not available");
|
|
50
50
|
}
|
|
51
51
|
var mqttEmitter = mqttListener(globalCallback);
|
|
@@ -19,6 +19,7 @@ const createGetSeqID = require("./core/getSeqID");
|
|
|
19
19
|
const getTaskResponseData = require("./core/getTaskResponseData");
|
|
20
20
|
const createEmitAuth = require("./core/emitAuth");
|
|
21
21
|
const createMiddlewareSystem = require("./middleware");
|
|
22
|
+
const { shouldIgnoreLegacyPostFailure } = require("./legacySendError");
|
|
22
23
|
|
|
23
24
|
const RECONNECT_DELAY_MS_DEFAULT = 3000;
|
|
24
25
|
const UNSUB_ALL_TIMEOUT_MS = 5000;
|
|
@@ -79,6 +80,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
79
80
|
|
|
80
81
|
function postSafe(...args) {
|
|
81
82
|
return rawPost(...args).catch(err => {
|
|
83
|
+
if (shouldIgnoreLegacyPostFailure(args[0])) throw err;
|
|
82
84
|
const msg = (err && err.error) || (err && err.message) || String(err || "");
|
|
83
85
|
// A single request can briefly see an expired web session while
|
|
84
86
|
// another request is refreshing the shared cookie jar. Do not
|
|
@@ -206,7 +208,12 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
206
208
|
}
|
|
207
209
|
|
|
208
210
|
const now = Date.now();
|
|
209
|
-
|
|
211
|
+
// keepalive is 60s. A 30s stall check used to recycle a quiet but
|
|
212
|
+
// healthy socket and looked like a random logout. Wait at least
|
|
213
|
+
// two keepalive periods before treating the socket as dead.
|
|
214
|
+
const keepaliveMs = (((ctx.mqttClient && ctx.mqttClient.options && ctx.mqttClient.options.keepalive) || 60) * 1000);
|
|
215
|
+
const stallMs = Math.max((conf.heartbeatTimeout || HEARTBEAT_TIMEOUT_MS) * 3, keepaliveMs * 2 + 15000);
|
|
216
|
+
if (now - lastPongTime > stallMs) {
|
|
210
217
|
logger("mqtt heartbeat: no response, forcing reconnect", "warn");
|
|
211
218
|
forceCycle();
|
|
212
219
|
return;
|
|
@@ -408,47 +415,20 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
408
415
|
}
|
|
409
416
|
|
|
410
417
|
function attachClientListeners() {
|
|
411
|
-
if (!ctx.mqttClient) return;
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
//
|
|
418
|
-
// so lastPongTime was never refreshed and the heartbeat below kept
|
|
419
|
-
// force-reconnecting the account roughly every minute (this is what
|
|
420
|
-
// looked like periodic auto logout). The library's own keepalive
|
|
421
|
-
// (keepalive: 30 in connectMqtt.js) sends PINGREQ/PINGRESP
|
|
422
|
-
// internally; we detect the PINGRESP via "packetreceive" instead.
|
|
423
|
-
// Any other incoming packet (e.g. real messages) also proves the
|
|
424
|
-
// connection is alive, so it counts too.
|
|
418
|
+
if (!ctx.mqttClient || ctx.mqttClient._fcaGuardsAttached) return;
|
|
419
|
+
ctx.mqttClient._fcaGuardsAttached = true;
|
|
420
|
+
lastPongTime = Date.now();
|
|
421
|
+
|
|
422
|
+
// Do not remove the connection's own close/error handlers. Those own
|
|
423
|
+
// reconnect policy. This listener only proves the socket is alive so
|
|
424
|
+
// the heartbeat does not recycle it.
|
|
425
425
|
ctx.mqttClient.on("packetreceive", (packet) => {
|
|
426
426
|
lastPongTime = Date.now();
|
|
427
427
|
if (packet && packet.cmd === "pingresp") {
|
|
428
428
|
logger("mqtt pong received", "debug");
|
|
429
429
|
}
|
|
430
430
|
});
|
|
431
|
-
|
|
432
|
-
ctx.mqttClient.once("close", () => {
|
|
433
|
-
logger("mqtt connection closed", "warn");
|
|
434
|
-
stopHeartbeat();
|
|
435
|
-
if (!ctx._ending && !ctx._sessionEnforcement && ctx.globalOptions.autoReconnect !== false) {
|
|
436
|
-
if (!isReconnecting) {
|
|
437
|
-
isReconnecting = true;
|
|
438
|
-
delayedReconnect();
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
});
|
|
442
|
-
|
|
443
|
-
ctx.mqttClient.once("error", (err) => {
|
|
444
|
-
logger(`mqtt error: ${err.message}`, "error");
|
|
445
|
-
if (!ctx._ending && !ctx._sessionEnforcement && ctx.globalOptions.autoReconnect !== false) {
|
|
446
|
-
if (!isReconnecting) {
|
|
447
|
-
isReconnecting = true;
|
|
448
|
-
forceCycle();
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
});
|
|
431
|
+
startHeartbeat();
|
|
452
432
|
}
|
|
453
433
|
|
|
454
434
|
return function (callback) {
|
|
@@ -510,6 +490,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
510
490
|
}
|
|
511
491
|
|
|
512
492
|
conf = mqttConf(ctx, conf);
|
|
493
|
+
ctx._attachMqttGuards = attachClientListeners;
|
|
513
494
|
|
|
514
495
|
installPostGuard();
|
|
515
496
|
|
|
@@ -527,7 +508,6 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
527
508
|
} else {
|
|
528
509
|
logger("mqtt starting listenMqtt", "info");
|
|
529
510
|
listenMqtt(defaultFuncs, api, ctx, globalCallback);
|
|
530
|
-
attachClientListeners();
|
|
531
511
|
startHeartbeat();
|
|
532
512
|
}
|
|
533
513
|
|
|
@@ -293,7 +293,9 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
293
293
|
throw new Error("OldMessage fallback is not available");
|
|
294
294
|
}
|
|
295
295
|
return new Promise(function (res2, rej2) {
|
|
296
|
-
|
|
296
|
+
var payload = msg && typeof msg === "object" ? Object.assign({}, msg) : { body: msg };
|
|
297
|
+
payload.__fcaSendFallback = true;
|
|
298
|
+
api.OldMessage(payload, threadID, function (err2, data2) {
|
|
297
299
|
if (err2) rej2(err2);
|
|
298
300
|
else res2(data2);
|
|
299
301
|
}, replyToMessage, isSingleUser);
|
|
@@ -302,6 +304,8 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
302
304
|
|
|
303
305
|
return async function sendMessage(msg, threadID, callback, replyToMessage, isSingleUser) {
|
|
304
306
|
if (typeof msg === "string") msg = { body: msg };
|
|
307
|
+
var fromE2EE = !!(msg && msg.__fromE2EE);
|
|
308
|
+
if (msg && Object.prototype.hasOwnProperty.call(msg, "__fromE2EE")) delete msg.__fromE2EE;
|
|
305
309
|
if (typeof callback !== "function") callback = null;
|
|
306
310
|
var drop = ["text_effect_ids", "textEffect", "text_effect", "text_effect_id", "textEffectId", "textEffectID", "effect", "effect_id", "effectID", "text_effect_name", "effectName", "effect_name"];
|
|
307
311
|
for (var d = 0; d < drop.length; d++) delete msg[drop[d]];
|
|
@@ -351,7 +355,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
351
355
|
// ---- DM attachment path (skip MQTT) ----
|
|
352
356
|
// E2EE DMs: bridge only (MQTT strips attachment_fbids).
|
|
353
357
|
// Plain DMs: OldMessage (/messaging/send/ other_user_fbid).
|
|
354
|
-
if (isSingleUser && msg.attachment) {
|
|
358
|
+
if (!fromE2EE && isSingleUser && msg.attachment) {
|
|
355
359
|
var useE2EE = api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected();
|
|
356
360
|
if (useE2EE) {
|
|
357
361
|
try {
|
|
@@ -383,7 +387,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
383
387
|
// ---- E2EE text path with cascade fallback ----
|
|
384
388
|
// Text replies to E2EE DMs should use the bridge; if it fails, try MQTT then OldMessage
|
|
385
389
|
// instead of hard-failing (Hardened6).
|
|
386
|
-
if (isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
|
|
390
|
+
if (!fromE2EE && isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
|
|
387
391
|
api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected()) {
|
|
388
392
|
try {
|
|
389
393
|
var e2eeText = await api.e2ee.sendMessage(
|