fca-nx 7.5.5 → 7.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +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 +90 -90
- 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,24 +6,37 @@
|
|
|
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
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
17
|
+
// Facebook's edge PUBACK/PUBREC/PUBCOMP uses non-zero reserved flag bits.
|
|
18
|
+
// mqtt-packet 9 treats that as a fatal protocol error and closes the socket
|
|
19
|
+
// within a second of connect, before /t_ms ever arrives.
|
|
20
|
+
function relaxFacebookAckFlags() {
|
|
21
|
+
const ids = ["mqtt-packet/constants", "mqtt/node_modules/mqtt-packet/constants"];
|
|
22
|
+
for (const id of ids) {
|
|
23
|
+
try {
|
|
24
|
+
const constants = require(id);
|
|
25
|
+
if (!constants || !constants.requiredHeaderFlags) continue;
|
|
26
|
+
constants.requiredHeaderFlags[4] = null;
|
|
27
|
+
constants.requiredHeaderFlags[5] = null;
|
|
28
|
+
constants.requiredHeaderFlags[7] = null;
|
|
29
|
+
return;
|
|
30
|
+
} catch (_) { }
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
relaxFacebookAckFlags();
|
|
34
|
+
|
|
35
|
+
function clearSyncTimer(ctx) {
|
|
36
|
+
if (ctx._rTimeout) {
|
|
37
|
+
clearTimeout(ctx._rTimeout);
|
|
38
|
+
ctx._rTimeout = null;
|
|
39
|
+
}
|
|
27
40
|
}
|
|
28
41
|
|
|
29
42
|
module.exports = function createListenMqtt(deps) {
|
|
@@ -37,66 +50,46 @@ module.exports = function createListenMqtt(deps) {
|
|
|
37
50
|
return;
|
|
38
51
|
}
|
|
39
52
|
|
|
40
|
-
function scheduleReconnect(
|
|
53
|
+
function scheduleReconnect(reason) {
|
|
41
54
|
if (ctx._stoppedForLogin) return;
|
|
42
|
-
const base = (ctx._mqttOpt && ctx._mqttOpt.reconnectDelayMs) || DEFAULT_RECONNECT_DELAY_MS;
|
|
43
55
|
if (ctx._reconnectTimer) {
|
|
44
56
|
logger("mqtt reconnect already scheduled", "warn");
|
|
45
|
-
return; // debounce
|
|
46
|
-
}
|
|
47
|
-
if (ctx._ending) {
|
|
48
|
-
// Covers confirmed logout/checkpoint/blocked-login/invalid-session:
|
|
49
|
-
// emitAuth() sets ctx._ending = true before this is ever reached for
|
|
50
|
-
// those cases, so we never auto-reconnect after a confirmed auth failure.
|
|
51
|
-
logger("mqtt reconnect skipped - ending", "warn");
|
|
52
57
|
return;
|
|
53
58
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
// All quick reconnect checks failed. Do a brand-new login instead of
|
|
57
|
-
// another reconnect: force the credential path (skip the cookie check).
|
|
58
|
-
ctx._reconnectAttempts = 0;
|
|
59
|
-
logger(`mqtt ${RECONNECT_CHECKS} reconnect checks failed; starting a fresh login`, "error");
|
|
60
|
-
ctx._reconnectTimer = setTimeout(async () => {
|
|
61
|
-
ctx._reconnectTimer = null;
|
|
62
|
-
if (ctx._ending) return;
|
|
63
|
-
let ok = false;
|
|
64
|
-
try {
|
|
65
|
-
if (typeof ctx.performAutoLogin === "function") {
|
|
66
|
-
ctx._forceFreshLogin = true;
|
|
67
|
-
ok = await ctx.performAutoLogin();
|
|
68
|
-
}
|
|
69
|
-
} catch (loginErr) {
|
|
70
|
-
logger(`mqtt fresh login failed: ${loginErr && loginErr.message ? loginErr.message : String(loginErr)}`, "error");
|
|
71
|
-
ok = false;
|
|
72
|
-
} finally {
|
|
73
|
-
ctx._forceFreshLogin = false;
|
|
74
|
-
}
|
|
75
|
-
if (ok && !ctx._ending) {
|
|
76
|
-
ctx._stoppedForLogin = false;
|
|
77
|
-
listenMqtt(defaultFuncs, api, ctx, globalCallback);
|
|
78
|
-
} else {
|
|
79
|
-
ctx._stoppedForLogin = true;
|
|
80
|
-
ctx._ending = true;
|
|
81
|
-
clearTimeout(ctx._reconnectTimer);
|
|
82
|
-
ctx._reconnectTimer = null;
|
|
83
|
-
try {
|
|
84
|
-
if (ctx.mqttClient) ctx.mqttClient.end(true);
|
|
85
|
-
} catch (_) { }
|
|
86
|
-
logger("mqtt stopped: fresh login is not available for this cookie session (no credentials). Refresh appstate and restart the bot.", "error");
|
|
87
|
-
globalCallback({ type: "stop_listen", error: "Fresh login failed after reconnect checks" }, null);
|
|
88
|
-
}
|
|
89
|
-
}, 0);
|
|
59
|
+
if (ctx._ending || ctx._sessionEnforcement) {
|
|
60
|
+
logger("mqtt reconnect skipped - session ended or needs manual review", "warn");
|
|
90
61
|
return;
|
|
91
62
|
}
|
|
92
|
-
const
|
|
93
|
-
|
|
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
|
+
}
|
|
94
87
|
ctx._reconnectTimer = setTimeout(() => {
|
|
95
88
|
ctx._reconnectTimer = null;
|
|
96
|
-
if (!ctx._ending) {
|
|
89
|
+
if (!ctx._ending && !ctx._sessionEnforcement) {
|
|
97
90
|
listenMqtt(defaultFuncs, api, ctx, globalCallback);
|
|
98
91
|
}
|
|
99
|
-
},
|
|
92
|
+
}, decision.delayMs);
|
|
100
93
|
}
|
|
101
94
|
function isEndingLikeError(msg) {
|
|
102
95
|
return /No subscription existed|client disconnecting|socket hang up|ECONNRESET/i.test(msg || "");
|
|
@@ -157,12 +150,12 @@ module.exports = function createListenMqtt(deps) {
|
|
|
157
150
|
// session (src/utils/headers.js) - it previously hard-coded "vi,en;q=0.9"
|
|
158
151
|
// here while HTTP requests defaulted to "en-US,en;q=0.9,vi;q=0.8",
|
|
159
152
|
// which is a contradictory-client signal between the two channels.
|
|
160
|
-
"Accept-Language": identity.acceptLanguage
|
|
161
|
-
"Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits"
|
|
153
|
+
"Accept-Language": identity.acceptLanguage
|
|
162
154
|
},
|
|
163
155
|
origin: "https://www.facebook.com",
|
|
164
156
|
protocolVersion: 13,
|
|
165
|
-
binaryType: "arraybuffer"
|
|
157
|
+
binaryType: "arraybuffer",
|
|
158
|
+
perMessageDeflate: false
|
|
166
159
|
},
|
|
167
160
|
keepalive: 60,
|
|
168
161
|
reschedulePings: true,
|
|
@@ -174,13 +167,19 @@ module.exports = function createListenMqtt(deps) {
|
|
|
174
167
|
options.wsOptions.agent = agent;
|
|
175
168
|
}
|
|
176
169
|
|
|
170
|
+
ctx._mqttGen = (ctx._mqttGen || 0) + 1;
|
|
171
|
+
const socketGen = ctx._mqttGen;
|
|
177
172
|
ctx.mqttClient = new mqtt.Client(
|
|
178
173
|
() => buildStream(options, new WebSocket(host, options.wsOptions), buildProxy()),
|
|
179
174
|
options
|
|
180
175
|
);
|
|
181
176
|
const mqttClient = ctx.mqttClient;
|
|
177
|
+
function stillThisSocket() {
|
|
178
|
+
return isCurrentMqttSocket(ctx._mqttGen, socketGen) && ctx.mqttClient === mqttClient;
|
|
179
|
+
}
|
|
182
180
|
|
|
183
181
|
mqttClient.on("error", function (err) {
|
|
182
|
+
if (!stillThisSocket()) return;
|
|
184
183
|
const msg = String(err && err.message ? err.message : err || "");
|
|
185
184
|
if ((ctx._ending || ctx._cycling) && /No subscription existed|client disconnecting/i.test(msg)) {
|
|
186
185
|
logger(`mqtt expected during shutdown: ${msg}`, "info");
|
|
@@ -188,18 +187,8 @@ module.exports = function createListenMqtt(deps) {
|
|
|
188
187
|
}
|
|
189
188
|
|
|
190
189
|
if (/Invalid header flag bits|must be 0x0 for puback/i.test(msg)) {
|
|
191
|
-
// A malformed puback means the byte stream is out of step. Each one is
|
|
192
|
-
// harmless alone, but a run of them means this connection is dead and
|
|
193
|
-
// the t_ms reply will never come. After 3 in a row, drop and reconnect.
|
|
194
190
|
ctx._badPuback = (ctx._badPuback || 0) + 1;
|
|
195
|
-
logger(`mqtt puback ignored (${ctx._badPuback}
|
|
196
|
-
if (ctx._badPuback >= 3) {
|
|
197
|
-
ctx._badPuback = 0;
|
|
198
|
-
try {
|
|
199
|
-
if (mqttClient) mqttClient.end(true);
|
|
200
|
-
} catch (_) { }
|
|
201
|
-
scheduleReconnect();
|
|
202
|
-
}
|
|
191
|
+
logger(`mqtt puback ignored (${ctx._badPuback}): ${msg}`, "warn");
|
|
203
192
|
return;
|
|
204
193
|
}
|
|
205
194
|
|
|
@@ -213,24 +202,29 @@ module.exports = function createListenMqtt(deps) {
|
|
|
213
202
|
);
|
|
214
203
|
}
|
|
215
204
|
|
|
216
|
-
if (/Not logged in|
|
|
205
|
+
if (/Not logged in|blocked the login/i.test(msg) || mqttAuthFailureKind(msg)) {
|
|
217
206
|
try {
|
|
218
207
|
if (mqttClient && mqttClient.connected) {
|
|
219
208
|
mqttClient.end(true);
|
|
220
209
|
}
|
|
221
210
|
} catch (_) { }
|
|
222
|
-
|
|
211
|
+
const kind = mqttAuthFailureKind(msg) || (/blocked/i.test(msg) ? "login_blocked" : "not_logged_in");
|
|
212
|
+
if (kind === "login_blocked") {
|
|
223
213
|
return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
|
|
224
214
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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");
|
|
232
226
|
if (!ctx._ending && ctx.globalOptions.autoReconnect) {
|
|
233
|
-
scheduleReconnect();
|
|
227
|
+
scheduleReconnect("auth_retry");
|
|
234
228
|
}
|
|
235
229
|
return;
|
|
236
230
|
}
|
|
@@ -254,15 +248,17 @@ module.exports = function createListenMqtt(deps) {
|
|
|
254
248
|
});
|
|
255
249
|
|
|
256
250
|
mqttClient.on("connect", function () {
|
|
251
|
+
if (!stillThisSocket()) return;
|
|
257
252
|
if (process.env.OnStatus === undefined) {
|
|
258
253
|
logger("fca-unofficial", "info");
|
|
259
254
|
process.env.OnStatus = true;
|
|
260
255
|
}
|
|
261
256
|
ctx._cycling = false;
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
257
|
+
ctx._reconnectAttempts = 0;
|
|
258
|
+
ctx._mqttAuthFailures = 0;
|
|
259
|
+
if (typeof ctx._attachMqttGuards === "function") {
|
|
260
|
+
try { ctx._attachMqttGuards(); } catch (_) { }
|
|
261
|
+
}
|
|
266
262
|
|
|
267
263
|
topics.forEach(t => mqttClient.subscribe(t));
|
|
268
264
|
|
|
@@ -308,7 +304,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
308
304
|
});
|
|
309
305
|
|
|
310
306
|
mqttClient.on("message", function (topic, message) {
|
|
311
|
-
if (ctx._ending) return;
|
|
307
|
+
if (!stillThisSocket() || ctx._ending) return;
|
|
312
308
|
try {
|
|
313
309
|
let jsonMessage = Buffer.isBuffer(message) ? Buffer.from(message).toString() : message;
|
|
314
310
|
try {
|
|
@@ -324,6 +320,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
324
320
|
globalCallback(null, { type: "friend_request_cancel", actorFbId: jsonMessage.from.toString(), timestamp: Date.now().toString() });
|
|
325
321
|
} else if (topic === "/t_ms") {
|
|
326
322
|
ctx._reconnectAttempts = 0;
|
|
323
|
+
ctx._mqttAuthFailures = 0;
|
|
327
324
|
ctx._badPuback = 0;
|
|
328
325
|
if (ctx.tmsWait && typeof ctx.tmsWait == "function") ctx.tmsWait();
|
|
329
326
|
if (jsonMessage.firstDeltaSeqId && jsonMessage.syncToken) {
|
|
@@ -369,6 +366,8 @@ module.exports = function createListenMqtt(deps) {
|
|
|
369
366
|
});
|
|
370
367
|
|
|
371
368
|
mqttClient.on("close", function () {
|
|
369
|
+
if (!stillThisSocket()) return;
|
|
370
|
+
clearSyncTimer(ctx);
|
|
372
371
|
if (ctx._ending || ctx._cycling) {
|
|
373
372
|
logger("mqtt close expected", "info");
|
|
374
373
|
return;
|
|
@@ -380,6 +379,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
380
379
|
});
|
|
381
380
|
|
|
382
381
|
mqttClient.on("disconnect", () => {
|
|
382
|
+
if (!stillThisSocket()) return;
|
|
383
383
|
if (ctx._ending || ctx._cycling) {
|
|
384
384
|
logger("mqtt disconnect expected", "info");
|
|
385
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
|
|