fca-nx 6.8.6 → 6.8.8
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/func/checkUpdate.js +1 -1
- package/func/logAdapter.js +0 -2
- package/index.js +0 -3
- package/module/config.js +2 -7
- package/module/login.js +10 -38
- package/module/loginHelper.js +94 -163
- package/module/options.js +1 -7
- package/package.json +2 -2
- package/src/api/action/addfriend.js +3 -9
- package/src/api/action/changeAvatar.js +0 -1
- package/src/api/action/changeCover.js +1 -3
- package/src/api/action/enableAutoSaveAppState.js +5 -18
- package/src/api/action/refreshFb_dtsg.js +2 -2
- package/src/api/http/httpGet.js +2 -6
- package/src/api/http/httpPost.js +2 -7
- package/src/api/messaging/createNewGroup.js +1 -1
- package/src/api/messaging/deleteMessage.js +1 -1
- package/src/api/messaging/forwardMessage.js +1 -9
- package/src/api/messaging/getEmojiUrl.js +1 -5
- package/src/api/messaging/getMessage.js +2 -4
- package/src/api/messaging/getThemePictures.js +0 -7
- package/src/api/messaging/markAsRead.js +0 -1
- package/src/api/messaging/muteThread.js +1 -1
- package/src/api/messaging/pinMessage.js +1 -10
- package/src/api/messaging/scheduler.js +4 -71
- package/src/api/messaging/sendBroadcast.js +0 -15
- package/src/api/messaging/sendMessage.js +1 -10
- package/src/api/messaging/sendTypingIndicator.js +2 -2
- package/src/api/messaging/sessionGuard.js +9 -45
- package/src/api/messaging/setMessageReaction.js +1 -2
- package/src/api/messaging/threadColors.js +12 -45
- package/src/api/messaging/uploadAttachment.js +3 -37
- package/src/api/socket/core/connectMqtt.js +17 -60
- package/src/api/socket/core/emitAuth.js +2 -14
- package/src/api/socket/core/getSeqID.js +23 -29
- package/src/api/socket/core/getTaskResponseData.js +1 -3
- package/src/api/socket/core/parseDelta.js +1 -1
- package/src/api/socket/detail/buildStream.js +1 -4
- package/src/api/socket/detail/constants.js +1 -4
- package/src/api/socket/e2ee/crypto.js +2 -40
- package/src/api/socket/e2ee/index.js +10 -123
- package/src/api/socket/e2ee/protocol.js +1 -32
- package/src/api/socket/e2ee/ratchet.js +10 -44
- package/src/api/socket/e2ee/store.js +1 -13
- package/src/api/socket/listenE2EE.js +1 -25
- package/src/api/socket/listenMqtt.js +13 -29
- package/src/api/socket/middleware/index.js +7 -61
- package/src/api/socket/sendMessage.js +2 -19
- package/src/api/threads/getThreadHistory.js +38 -68
- package/src/api/threads/getThreadInfo.js +3 -4
- package/src/api/threads/getThreadList.js +31 -34
- package/src/api/threads/getThreadPictures.js +1 -1
- package/src/api/users/getUserInfo.js +2 -5
- package/src/api/users/getUserInfoV2.js +3 -9
- package/src/core/sendReqMqtt.js +1 -2
- package/src/database/helpers.js +0 -12
- package/src/database/models/index.js +1 -3
- package/src/utils/broadcast.js +1 -1
- package/src/utils/clientIdentity.js +3 -50
- package/src/utils/cookies.js +2 -4
- package/src/utils/format/utils.js +0 -10
- package/src/utils/headers.js +12 -26
- package/src/utils/instanceLock.js +3 -9
- package/src/utils/ipGuard.js +1 -15
- package/src/utils/loginParser/autoLogin.js +0 -12
- package/src/utils/loginParser/parseAndCheckLogin.js +0 -7
- package/src/utils/loginParser/textUtils.js +0 -6
- package/src/utils/request/config.js +1 -4
- package/src/utils/request/methods.js +1 -4
- package/src/utils/request/proxy.js +0 -13
- package/src/utils/request/retry.js +0 -1
- package/src/utils/request/sanitize.js +1 -1
- package/src/utils/sendThrottle.js +1 -14
- package/src/utils/utils.js +3 -17
|
@@ -1,33 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
/**
|
|
4
|
-
* Facebook-specific E2EE wire protocol handling.
|
|
5
|
-
*
|
|
6
|
-
* Facebook Secret Conversations use Signal Protocol (X3DH + Double Ratchet)
|
|
7
|
-
* with their own framing on top. This module handles:
|
|
8
|
-
* - Key bundle upload/download to Facebook's graph endpoint
|
|
9
|
-
* - Message framing (encode/decode FCANX_E2EE frame format)
|
|
10
|
-
* - Signed pre-key signatures using HMAC-SHA256 (FB uses Ed25519 in practice;
|
|
11
|
-
* we sign with HMAC for our own inter-device sessions)
|
|
12
|
-
* - E2EE-capable thread detection from message metadata
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
3
|
const crypto = require("crypto");
|
|
16
4
|
const { hmacSha256, generateKeyPair, randomBytes } = require("./crypto");
|
|
17
5
|
|
|
18
|
-
// ─── Frame format ──────────────────────────────────────────────────────────────
|
|
19
|
-
// 2 bytes: magic (0x4E58 = "NX")
|
|
20
|
-
// 1 byte: version (0x01)
|
|
21
|
-
// 1 byte: type (0=init, 1=message, 2=reaction, 3=receipt, 4=typing)
|
|
22
|
-
// 4 bytes: sender ID length
|
|
23
|
-
// N bytes: sender ID (utf8)
|
|
24
|
-
// 4 bytes: thread ID length
|
|
25
|
-
// N bytes: thread ID (utf8)
|
|
26
|
-
// 4 bytes: header length [only for type 0,1,2]
|
|
27
|
-
// N bytes: header
|
|
28
|
-
// 4 bytes: payload length
|
|
29
|
-
// N bytes: payload (encrypted or raw for receipt/typing)
|
|
30
|
-
|
|
31
6
|
const MAGIC = 0x4E58;
|
|
32
7
|
const VERSION = 0x01;
|
|
33
8
|
const TYPE = { INIT: 0, MESSAGE: 1, REACTION: 2, RECEIPT: 3, TYPING: 4 };
|
|
@@ -63,7 +38,7 @@ function encodeFrame(type, senderID, threadID, header, payload) {
|
|
|
63
38
|
|
|
64
39
|
function decodeFrame(buf) {
|
|
65
40
|
if (Buffer.isBuffer(buf)) {
|
|
66
|
-
|
|
41
|
+
|
|
67
42
|
} else if (buf instanceof Uint8Array) {
|
|
68
43
|
buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
69
44
|
} else {
|
|
@@ -109,8 +84,6 @@ function decodeFrame(buf) {
|
|
|
109
84
|
return { version, type, senderID, threadID, header, payload };
|
|
110
85
|
}
|
|
111
86
|
|
|
112
|
-
// ─── Key Bundle ────────────────────────────────────────────────────────────────
|
|
113
|
-
|
|
114
87
|
function buildKeyBundle(identityKey, signedPreKey, oneTimePreKeys) {
|
|
115
88
|
return {
|
|
116
89
|
identityKey: identityKey.publicKeyRaw.toString("base64"),
|
|
@@ -130,8 +103,6 @@ function signKey(identityPrivateKey, keyToSign) {
|
|
|
130
103
|
return hmacSha256(identityPrivateKey, keyToSign.publicKeyRaw);
|
|
131
104
|
}
|
|
132
105
|
|
|
133
|
-
// ─── Facebook Graph API: key registration/fetching ───────────────────────────
|
|
134
|
-
|
|
135
106
|
async function uploadKeyBundle(defaultFuncs, ctx, keyBundle) {
|
|
136
107
|
try {
|
|
137
108
|
const res = await defaultFuncs.post(
|
|
@@ -176,8 +147,6 @@ async function fetchRecipientKeyBundle(defaultFuncs, ctx, recipientUserID) {
|
|
|
176
147
|
}
|
|
177
148
|
}
|
|
178
149
|
|
|
179
|
-
// ─── Message payload builders ─────────────────────────────────────────────────
|
|
180
|
-
|
|
181
150
|
function buildInitPayload(senderEphemeralPub, senderOneTimeKeyId, recipientOneTimeKeyId) {
|
|
182
151
|
return JSON.stringify({
|
|
183
152
|
type: "x3dh_init",
|
|
@@ -1,11 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
/**
|
|
4
|
-
* Double Ratchet Algorithm (Signal Protocol)
|
|
5
|
-
* Based on the Signal Protocol specification:
|
|
6
|
-
* https://signal.org/docs/specifications/doubleratchet/
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
3
|
const { generateKeyPair, dh, hkdf, hkdfExtract, hkdfExpand, encrypt, decrypt, hmacSha256 } = require("./crypto");
|
|
10
4
|
|
|
11
5
|
const MAX_SKIP = 1000;
|
|
@@ -35,20 +29,17 @@ function deriveMessageKeys(mk) {
|
|
|
35
29
|
|
|
36
30
|
class DoubleRatchetSession {
|
|
37
31
|
constructor() {
|
|
38
|
-
this.DHs = null;
|
|
39
|
-
this.DHr = null;
|
|
40
|
-
this.RK = null;
|
|
41
|
-
this.CKs = null;
|
|
42
|
-
this.CKr = null;
|
|
43
|
-
this.Ns = 0;
|
|
44
|
-
this.Nr = 0;
|
|
45
|
-
this.PN = 0;
|
|
46
|
-
this.MKSKIPPED = new Map();
|
|
32
|
+
this.DHs = null;
|
|
33
|
+
this.DHr = null;
|
|
34
|
+
this.RK = null;
|
|
35
|
+
this.CKs = null;
|
|
36
|
+
this.CKr = null;
|
|
37
|
+
this.Ns = 0;
|
|
38
|
+
this.Nr = 0;
|
|
39
|
+
this.PN = 0;
|
|
40
|
+
this.MKSKIPPED = new Map();
|
|
47
41
|
}
|
|
48
42
|
|
|
49
|
-
/**
|
|
50
|
-
* Initialize as sender (Alice) after X3DH
|
|
51
|
-
*/
|
|
52
43
|
initAsSender(sk, recipientRatchetPublicKey) {
|
|
53
44
|
this.DHs = generateKeyPair();
|
|
54
45
|
this.DHr = Buffer.from(recipientRatchetPublicKey);
|
|
@@ -60,9 +51,6 @@ class DoubleRatchetSession {
|
|
|
60
51
|
this.Ns = 0; this.Nr = 0; this.PN = 0;
|
|
61
52
|
}
|
|
62
53
|
|
|
63
|
-
/**
|
|
64
|
-
* Initialize as receiver (Bob) after X3DH
|
|
65
|
-
*/
|
|
66
54
|
initAsReceiver(sk, ourRatchetKeyPair) {
|
|
67
55
|
this.DHs = ourRatchetKeyPair;
|
|
68
56
|
this.DHr = null;
|
|
@@ -72,10 +60,6 @@ class DoubleRatchetSession {
|
|
|
72
60
|
this.Ns = 0; this.Nr = 0; this.PN = 0;
|
|
73
61
|
}
|
|
74
62
|
|
|
75
|
-
/**
|
|
76
|
-
* Encrypt a message
|
|
77
|
-
* Returns { header, ciphertext }
|
|
78
|
-
*/
|
|
79
63
|
encrypt(plaintext, aad) {
|
|
80
64
|
const { ck, mk } = kdfCK(this.CKs);
|
|
81
65
|
this.CKs = ck;
|
|
@@ -87,13 +71,6 @@ class DoubleRatchetSession {
|
|
|
87
71
|
return { header, ciphertext };
|
|
88
72
|
}
|
|
89
73
|
|
|
90
|
-
/**
|
|
91
|
-
* Decrypt a message
|
|
92
|
-
* @param {Buffer} header - message header
|
|
93
|
-
* @param {Buffer} ciphertext - encrypted payload
|
|
94
|
-
* @param {Buffer} [aad] - additional auth data
|
|
95
|
-
* @returns {Buffer} decrypted plaintext
|
|
96
|
-
*/
|
|
97
74
|
decrypt(header, ciphertext, aad) {
|
|
98
75
|
const snapshot = {
|
|
99
76
|
DHs: this.DHs,
|
|
@@ -110,8 +87,7 @@ class DoubleRatchetSession {
|
|
|
110
87
|
try {
|
|
111
88
|
return this._decryptAndAdvance(header, ciphertext, aad);
|
|
112
89
|
} catch (error) {
|
|
113
|
-
|
|
114
|
-
// the ratchet. A later valid copy of the message can then succeed.
|
|
90
|
+
|
|
115
91
|
Object.assign(this, snapshot);
|
|
116
92
|
throw error;
|
|
117
93
|
}
|
|
@@ -121,7 +97,6 @@ class DoubleRatchetSession {
|
|
|
121
97
|
const { dh_pub, pn, n } = this._parseHeader(header);
|
|
122
98
|
const aadFull = aad ? Buffer.concat([aad, header]) : header;
|
|
123
99
|
|
|
124
|
-
// Check skipped keys first
|
|
125
100
|
const skipKey = `${dh_pub.toString("hex")}:${n}`;
|
|
126
101
|
if (this.MKSKIPPED.has(skipKey)) {
|
|
127
102
|
const mk = this.MKSKIPPED.get(skipKey);
|
|
@@ -130,7 +105,6 @@ class DoubleRatchetSession {
|
|
|
130
105
|
return decrypt(keys.encKey, ciphertext, aadFull);
|
|
131
106
|
}
|
|
132
107
|
|
|
133
|
-
// Check if we need to ratchet
|
|
134
108
|
const needsRatchet = !this.DHr || !dh_pub.equals(this.DHr);
|
|
135
109
|
if (needsRatchet) {
|
|
136
110
|
this._skipMessageKeys(pn);
|
|
@@ -168,13 +142,11 @@ class DoubleRatchetSession {
|
|
|
168
142
|
this.Nr = 0;
|
|
169
143
|
this.DHr = remoteDhPub;
|
|
170
144
|
|
|
171
|
-
// Receive ratchet
|
|
172
145
|
const dhOut1 = dh(this.DHs.privateKey, this.DHr);
|
|
173
146
|
const { rk: rk1, ck: ckr } = kdfRK(this.RK, dhOut1);
|
|
174
147
|
this.RK = rk1;
|
|
175
148
|
this.CKr = ckr;
|
|
176
149
|
|
|
177
|
-
// Send ratchet
|
|
178
150
|
this.DHs = generateKeyPair();
|
|
179
151
|
const dhOut2 = dh(this.DHs.privateKey, this.DHr);
|
|
180
152
|
const { rk: rk2, ck: cks } = kdfRK(this.RK, dhOut2);
|
|
@@ -201,9 +173,6 @@ class DoubleRatchetSession {
|
|
|
201
173
|
};
|
|
202
174
|
}
|
|
203
175
|
|
|
204
|
-
/**
|
|
205
|
-
* Serialize session state for persistence
|
|
206
|
-
*/
|
|
207
176
|
serialize() {
|
|
208
177
|
return JSON.stringify({
|
|
209
178
|
DHs_priv: this.DHs ? this.DHs.privateKey.toString("base64") : null,
|
|
@@ -219,9 +188,6 @@ class DoubleRatchetSession {
|
|
|
219
188
|
});
|
|
220
189
|
}
|
|
221
190
|
|
|
222
|
-
/**
|
|
223
|
-
* Restore session state from serialized string
|
|
224
|
-
*/
|
|
225
191
|
static deserialize(json) {
|
|
226
192
|
const d = JSON.parse(json);
|
|
227
193
|
const session = new DoubleRatchetSession();
|
|
@@ -1,15 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
/**
|
|
4
|
-
* E2EE Device/Session Store
|
|
5
|
-
* Persists key material to a JSON file (encrypted with an external secret).
|
|
6
|
-
* Each E2EE session (thread) is stored separately.
|
|
7
|
-
*
|
|
8
|
-
* Set FCA_NX_E2EE_STORE_KEY to a high-entropy secret, or pass
|
|
9
|
-
* { encryptionKey } as the third constructor argument. The key is never saved
|
|
10
|
-
* beside the encrypted data.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
3
|
const fs = require("fs");
|
|
14
4
|
const path = require("path");
|
|
15
5
|
const crypto = require("crypto");
|
|
@@ -34,7 +24,7 @@ class E2EEStore {
|
|
|
34
24
|
identityKey: null,
|
|
35
25
|
signedPreKey: null,
|
|
36
26
|
oneTimePreKeys: [],
|
|
37
|
-
sessions: {}
|
|
27
|
+
sessions: {}
|
|
38
28
|
};
|
|
39
29
|
this._loaded = false;
|
|
40
30
|
}
|
|
@@ -149,8 +139,6 @@ class E2EEStore {
|
|
|
149
139
|
this._applyPayload(JSON.parse(decrypted));
|
|
150
140
|
this._loaded = true;
|
|
151
141
|
|
|
152
|
-
// Upgrade legacy files immediately so future writes do not keep the
|
|
153
|
-
// old colocated-key format.
|
|
154
142
|
if (isLegacy) this.save();
|
|
155
143
|
return true;
|
|
156
144
|
} catch (error) {
|
|
@@ -3,20 +3,6 @@
|
|
|
3
3
|
var logger = require("../../utils/logger");
|
|
4
4
|
var EventEmitter = require("events");
|
|
5
5
|
|
|
6
|
-
/**
|
|
7
|
-
* listenE2EE — merges E2EE messages into the same event stream as MQTT.
|
|
8
|
-
*
|
|
9
|
-
* Usage (identical to api.listen):
|
|
10
|
-
* api.listenE2EE(callback) // Node-style callback(err, event)
|
|
11
|
-
* api.listenE2EE() // returns MessageEmitter
|
|
12
|
-
*
|
|
13
|
-
* Combines:
|
|
14
|
-
* - Regular MQTT messages (from api.listenMqtt)
|
|
15
|
-
* - E2EE encrypted messages (received via FCA-NX native Noise WebSocket)
|
|
16
|
-
*
|
|
17
|
-
* All events share the same shape (type, senderID, threadID, body, etc.),
|
|
18
|
-
* with E2EE events carrying `isE2EE: true`.
|
|
19
|
-
*/
|
|
20
6
|
module.exports = function (defaultFuncs, api, ctx) {
|
|
21
7
|
return function listenE2EE(callback) {
|
|
22
8
|
class CombinedEmitter extends EventEmitter {
|
|
@@ -43,14 +29,11 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
43
29
|
emitter.emit("message", event);
|
|
44
30
|
};
|
|
45
31
|
|
|
46
|
-
// Start regular MQTT listener
|
|
47
32
|
var mqttListener = api._listenMqttRaw || api.listenMqtt;
|
|
48
33
|
if (typeof mqttListener !== "function") {
|
|
49
34
|
throw new Error("listenE2EE: MQTT listener is not available");
|
|
50
35
|
}
|
|
51
|
-
|
|
52
|
-
// normal (non-E2EE) chat, so replies must NOT be diverted to the E2EE bridge. An E2EE message
|
|
53
|
-
// flips it back to 'dm' (see e2ee/index.js). Latest activity decides where the reply goes.
|
|
36
|
+
|
|
54
37
|
var mqttCallback = function (err, event) {
|
|
55
38
|
try {
|
|
56
39
|
if (!err && event && event.type === "message" && event.isGroup === false && !event.isE2EE &&
|
|
@@ -64,12 +47,6 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
64
47
|
var mqttEmitter = mqttListener(mqttCallback);
|
|
65
48
|
api._mqttEmitter = mqttEmitter;
|
|
66
49
|
|
|
67
|
-
// [Fixed by xalman] Hook E2EE incoming messages (FCA-NX native Noise WebSocket).
|
|
68
|
-
// onMessage() only registers a callback reference - it doesn't require an
|
|
69
|
-
// active connection - so this is safe to call even while E2EE is still
|
|
70
|
-
// connecting in the background. If we skip it here just because
|
|
71
|
-
// isConnected() is momentarily false, the hook never gets attached and
|
|
72
|
-
// E2EE (inbox) messages go unheard for the lifetime of this listener.
|
|
73
50
|
var e2ee = api.e2ee || ctx.e2ee;
|
|
74
51
|
if (!e2ee) {
|
|
75
52
|
logger.warn(
|
|
@@ -87,7 +64,6 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
87
64
|
if (err) return globalCallback(err, null);
|
|
88
65
|
if (!event) return;
|
|
89
66
|
|
|
90
|
-
// Filter self-messages unless selfListen is enabled
|
|
91
67
|
if (!ctx.globalOptions.selfListen && event.senderID === ctx.userID) return;
|
|
92
68
|
|
|
93
69
|
event.isE2EE = true;
|
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* Fixed and Optimized listenMqtt.js
|
|
3
|
-
* Prevents MQTT loop hangs, fixes heartbeat ping leaks, and cleans up event listeners.
|
|
4
|
-
*/
|
|
1
|
+
|
|
5
2
|
|
|
6
3
|
"use strict";
|
|
7
4
|
|
|
@@ -20,11 +17,11 @@ const getTaskResponseData = require("./core/getTaskResponseData");
|
|
|
20
17
|
const createEmitAuth = require("./core/emitAuth");
|
|
21
18
|
const createMiddlewareSystem = require("./middleware");
|
|
22
19
|
|
|
23
|
-
const CYCLE_MS_DEFAULT = 0;
|
|
20
|
+
const CYCLE_MS_DEFAULT = 0;
|
|
24
21
|
const RECONNECT_DELAY_MS_DEFAULT = 12000;
|
|
25
22
|
const UNSUB_ALL_TIMEOUT_MS = 5000;
|
|
26
23
|
const MAX_MQTT_RECONNECT_DELAY_MS = 120000;
|
|
27
|
-
const MAX_MQTT_RECONNECT_COOLDOWN_MS = 45 * 60 * 1000;
|
|
24
|
+
const MAX_MQTT_RECONNECT_COOLDOWN_MS = 45 * 60 * 1000;
|
|
28
25
|
const MAX_MQTT_RECONNECT_ATTEMPTS = 6;
|
|
29
26
|
const HEARTBEAT_INTERVAL_MS = 60000;
|
|
30
27
|
const HEARTBEAT_TIMEOUT_MS = 20000;
|
|
@@ -83,11 +80,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
83
80
|
function postSafe(...args) {
|
|
84
81
|
return rawPost(...args).catch(err => {
|
|
85
82
|
const msg = (err && err.error) || (err && err.message) || String(err || "");
|
|
86
|
-
|
|
87
|
-
// another request is refreshing the shared cookie jar. Do not
|
|
88
|
-
// tear down the live MQTT session for that recoverable case;
|
|
89
|
-
// the shared auto-login promise handles the HTTP request and
|
|
90
|
-
// MQTT reconnects itself if the socket also needs refreshing.
|
|
83
|
+
|
|
91
84
|
if (/blocked the login|Checkpoint/i.test(msg)) {
|
|
92
85
|
emitAuth(
|
|
93
86
|
ctx,
|
|
@@ -110,9 +103,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
110
103
|
let isReconnecting = false;
|
|
111
104
|
|
|
112
105
|
function getReconnectDelay() {
|
|
113
|
-
|
|
114
|
-
// Default scheduled backoff avoids overlapping sessions that Facebook treats as multi-login.
|
|
115
|
-
// When enabled: attempts 0/1 fire at once, then 1s, 2s, 4s ... up to 60s.
|
|
106
|
+
|
|
116
107
|
const immediate = process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1";
|
|
117
108
|
if (immediate) {
|
|
118
109
|
if (reconnectAttempts <= 1) return 0;
|
|
@@ -122,7 +113,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
122
113
|
}
|
|
123
114
|
const base = conf.reconnectDelayMs || RECONNECT_DELAY_MS_DEFAULT;
|
|
124
115
|
const exp = Math.min(base * Math.pow(2, reconnectAttempts), MAX_MQTT_RECONNECT_DELAY_MS);
|
|
125
|
-
|
|
116
|
+
|
|
126
117
|
const jitter = Math.floor(Math.random() * Math.min(4000, exp * 0.4));
|
|
127
118
|
return Math.min(exp + jitter, MAX_MQTT_RECONNECT_DELAY_MS);
|
|
128
119
|
}
|
|
@@ -132,7 +123,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
132
123
|
logger("mqtt getSeqID skipped - ending", "warn");
|
|
133
124
|
return Promise.resolve();
|
|
134
125
|
}
|
|
135
|
-
|
|
126
|
+
|
|
136
127
|
if (ctx._getSeqIDInFlight) {
|
|
137
128
|
logger("mqtt getSeqID skipped - already in flight", "warn");
|
|
138
129
|
return ctx._getSeqIDInFlight;
|
|
@@ -222,7 +213,6 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
222
213
|
|
|
223
214
|
lastPongTime = Date.now();
|
|
224
215
|
|
|
225
|
-
// [Hardened6] jittered heartbeat interval so pings are not perfectly periodic
|
|
226
216
|
const hbBase = conf.heartbeatInterval || HEARTBEAT_INTERVAL_MS;
|
|
227
217
|
const hbEvery = hbBase + Math.floor(Math.random() * Math.min(8000, hbBase * 0.25));
|
|
228
218
|
let missedPongs = 0;
|
|
@@ -236,9 +226,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
236
226
|
const limit = (conf.heartbeatTimeout || HEARTBEAT_TIMEOUT_MS) * 4;
|
|
237
227
|
if (now - lastPongTime > limit) {
|
|
238
228
|
missedPongs += 1;
|
|
239
|
-
|
|
240
|
-
// few seconds is not what Messenger web does, and force-cycling
|
|
241
|
-
// on one late pong opens a second session (suspend ~1-2h).
|
|
229
|
+
|
|
242
230
|
if (missedPongs >= 3) {
|
|
243
231
|
logger("mqtt heartbeat: silent too long, closing socket once", "warn");
|
|
244
232
|
missedPongs = 0;
|
|
@@ -315,8 +303,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
315
303
|
ctx.t_mqttCalled = false;
|
|
316
304
|
ctx._ending = false;
|
|
317
305
|
ctx._cycling = false;
|
|
318
|
-
|
|
319
|
-
// reconnect forces a full re-login and looks like a new device.
|
|
306
|
+
|
|
320
307
|
if (!soft) {
|
|
321
308
|
ctx.lastSeqId = null;
|
|
322
309
|
ctx.syncToken = undefined;
|
|
@@ -376,13 +363,13 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
376
363
|
|
|
377
364
|
function delayedReconnect() {
|
|
378
365
|
if (ctx._ending) return;
|
|
379
|
-
|
|
366
|
+
|
|
380
367
|
if (ctx._reconnectTimer) {
|
|
381
368
|
logger("mqtt reconnect already scheduled - debounce", "warn");
|
|
382
369
|
return;
|
|
383
370
|
}
|
|
384
371
|
let d = getReconnectDelay();
|
|
385
|
-
|
|
372
|
+
|
|
386
373
|
if (d > 0) d += Math.floor(Math.random() * 1500);
|
|
387
374
|
logger(d === 0 ? "mqtt reconnecting immediately" : `mqtt reconnect in ${d}ms`, "info");
|
|
388
375
|
|
|
@@ -395,7 +382,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
395
382
|
}, d);
|
|
396
383
|
}
|
|
397
384
|
|
|
398
|
-
function forceCycle()
|
|
385
|
+
function forceCycle() {
|
|
399
386
|
if (ctx._cycling) {
|
|
400
387
|
logger("mqtt force cycle already in progress", "warn");
|
|
401
388
|
return;
|
|
@@ -404,7 +391,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
404
391
|
logger("mqtt force cycle skipped - ending", "warn");
|
|
405
392
|
return;
|
|
406
393
|
}
|
|
407
|
-
|
|
394
|
+
|
|
408
395
|
const now = Date.now();
|
|
409
396
|
if (ctx._lastForceCycleAt && (now - ctx._lastForceCycleAt) < MIN_FORCE_CYCLE_MS) {
|
|
410
397
|
logger("mqtt force cycle skipped - too soon since last cycle", "warn");
|
|
@@ -458,9 +445,6 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
458
445
|
|
|
459
446
|
ctx.mqttClient.removeAllListeners("packetreceive");
|
|
460
447
|
|
|
461
|
-
// Do not remove "close" / "error". connectMqtt already owns reconnect.
|
|
462
|
-
// Replacing those handlers made every drop run getSeqID (a fresh login)
|
|
463
|
-
// and sometimes opened a second socket — that is what suspends the account.
|
|
464
448
|
ctx.mqttClient.on("packetreceive", (packet) => {
|
|
465
449
|
lastPongTime = Date.now();
|
|
466
450
|
if (packet && packet.cmd === "pingresp") {
|
|
@@ -1,25 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
const logger = require("../../../../func/logger");
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
* Middleware system for filtering and processing events before they are emitted
|
|
6
|
-
*
|
|
7
|
-
* Middleware functions receive (event, next) where:
|
|
8
|
-
* - event: The event object (can be modified)
|
|
9
|
-
* - next: Function to call to continue to next middleware
|
|
10
|
-
* - next() - continue to next middleware
|
|
11
|
-
* - next(false) or next(null) - stop processing, don't emit event
|
|
12
|
-
* - next(error) - emit error instead
|
|
13
|
-
*/
|
|
14
4
|
module.exports = function createMiddlewareSystem() {
|
|
15
5
|
const middlewareStack = [];
|
|
16
6
|
|
|
17
|
-
/**
|
|
18
|
-
* Add middleware to the stack
|
|
19
|
-
* @param {Function|string} middleware - Middleware function or name for named middleware
|
|
20
|
-
* @param {Function} [fn] - Middleware function (if first param is name)
|
|
21
|
-
* @returns {Function} Unsubscribe function
|
|
22
|
-
*/
|
|
23
7
|
function use(middleware, fn) {
|
|
24
8
|
let middlewareFn, name;
|
|
25
9
|
|
|
@@ -42,7 +26,6 @@ module.exports = function createMiddlewareSystem() {
|
|
|
42
26
|
middlewareStack.push(wrapped);
|
|
43
27
|
logger(`Middleware "${name}" added`, "info");
|
|
44
28
|
|
|
45
|
-
// Return unsubscribe function
|
|
46
29
|
return function remove() {
|
|
47
30
|
const index = middlewareStack.indexOf(wrapped);
|
|
48
31
|
if (index !== -1) {
|
|
@@ -52,11 +35,6 @@ module.exports = function createMiddlewareSystem() {
|
|
|
52
35
|
};
|
|
53
36
|
}
|
|
54
37
|
|
|
55
|
-
/**
|
|
56
|
-
* Remove middleware by name or function
|
|
57
|
-
* @param {string|Function} identifier - Name or function to remove
|
|
58
|
-
* @returns {boolean} True if removed
|
|
59
|
-
*/
|
|
60
38
|
function remove(identifier) {
|
|
61
39
|
if (typeof identifier === "string") {
|
|
62
40
|
const index = middlewareStack.findIndex(m => m.name === identifier);
|
|
@@ -78,29 +56,16 @@ module.exports = function createMiddlewareSystem() {
|
|
|
78
56
|
return false;
|
|
79
57
|
}
|
|
80
58
|
|
|
81
|
-
/**
|
|
82
|
-
* Remove all middleware
|
|
83
|
-
*/
|
|
84
59
|
function clear() {
|
|
85
60
|
const count = middlewareStack.length;
|
|
86
61
|
middlewareStack.length = 0;
|
|
87
62
|
logger(`All middleware cleared (${count} removed)`, "info");
|
|
88
63
|
}
|
|
89
64
|
|
|
90
|
-
/**
|
|
91
|
-
* Get list of middleware names
|
|
92
|
-
* @returns {string[]} Array of middleware names
|
|
93
|
-
*/
|
|
94
65
|
function list() {
|
|
95
66
|
return middlewareStack.filter(m => m.enabled).map(m => m.name);
|
|
96
67
|
}
|
|
97
68
|
|
|
98
|
-
/**
|
|
99
|
-
* Enable/disable middleware by name
|
|
100
|
-
* @param {string} name - Middleware name
|
|
101
|
-
* @param {boolean} enabled - Enable or disable
|
|
102
|
-
* @returns {boolean} True if found and updated
|
|
103
|
-
*/
|
|
104
69
|
function setEnabled(name, enabled) {
|
|
105
70
|
const middleware = middlewareStack.find(m => m.name === name);
|
|
106
71
|
if (middleware) {
|
|
@@ -111,12 +76,6 @@ module.exports = function createMiddlewareSystem() {
|
|
|
111
76
|
return false;
|
|
112
77
|
}
|
|
113
78
|
|
|
114
|
-
/**
|
|
115
|
-
* Process event through middleware stack
|
|
116
|
-
* @param {*} event - Event object
|
|
117
|
-
* @param {Function} finalCallback - Callback to call after all middleware
|
|
118
|
-
* @returns {Promise} Promise that resolves when processing is complete
|
|
119
|
-
*/
|
|
120
79
|
function process(event, finalCallback) {
|
|
121
80
|
if (!middlewareStack.length) {
|
|
122
81
|
return finalCallback(null, event);
|
|
@@ -126,57 +85,47 @@ module.exports = function createMiddlewareSystem() {
|
|
|
126
85
|
const enabledMiddleware = middlewareStack.filter(m => m.enabled);
|
|
127
86
|
|
|
128
87
|
function next(err) {
|
|
129
|
-
|
|
88
|
+
|
|
130
89
|
if (err && err !== false && err !== null) {
|
|
131
90
|
return finalCallback(err, null);
|
|
132
91
|
}
|
|
133
92
|
|
|
134
|
-
// Explicitly stopped (next(false) or next(null))
|
|
135
93
|
if (err === false || err === null) {
|
|
136
|
-
return finalCallback(null, null);
|
|
94
|
+
return finalCallback(null, null);
|
|
137
95
|
}
|
|
138
96
|
|
|
139
|
-
// No more middleware, call final callback
|
|
140
97
|
if (index >= enabledMiddleware.length) {
|
|
141
98
|
return finalCallback(null, event);
|
|
142
99
|
}
|
|
143
100
|
|
|
144
|
-
// Get next middleware
|
|
145
101
|
const middleware = enabledMiddleware[index++];
|
|
146
102
|
|
|
147
103
|
try {
|
|
148
|
-
|
|
104
|
+
|
|
149
105
|
const result = middleware.fn(event, next);
|
|
150
106
|
|
|
151
|
-
// If middleware returns a promise, handle it
|
|
152
107
|
if (result && typeof result.then === "function") {
|
|
153
108
|
result
|
|
154
109
|
.then(() => next())
|
|
155
110
|
.catch(err => next(err));
|
|
156
111
|
} else if (result === false || result === null) {
|
|
157
|
-
|
|
112
|
+
|
|
158
113
|
finalCallback(null, null);
|
|
159
114
|
}
|
|
160
|
-
|
|
115
|
+
|
|
161
116
|
} catch (err) {
|
|
162
117
|
logger(`Middleware "${middleware.name}" error: ${err && err.message ? err.message : String(err)}`, "error");
|
|
163
118
|
next(err);
|
|
164
119
|
}
|
|
165
120
|
}
|
|
166
121
|
|
|
167
|
-
// Start processing
|
|
168
122
|
next();
|
|
169
123
|
}
|
|
170
124
|
|
|
171
|
-
/**
|
|
172
|
-
* Wrap a callback with middleware processing
|
|
173
|
-
* @param {Function} callback - Original callback (err, event)
|
|
174
|
-
* @returns {Function} Wrapped callback
|
|
175
|
-
*/
|
|
176
125
|
function wrapCallback(callback) {
|
|
177
126
|
return function wrappedCallback(err, event) {
|
|
178
127
|
if (err) {
|
|
179
|
-
|
|
128
|
+
|
|
180
129
|
return callback(err, null);
|
|
181
130
|
}
|
|
182
131
|
|
|
@@ -184,18 +133,15 @@ module.exports = function createMiddlewareSystem() {
|
|
|
184
133
|
return callback(null, null);
|
|
185
134
|
}
|
|
186
135
|
|
|
187
|
-
// Process event through middleware
|
|
188
136
|
process(event, (middlewareErr, processedEvent) => {
|
|
189
137
|
if (middlewareErr) {
|
|
190
138
|
return callback(middlewareErr, null);
|
|
191
139
|
}
|
|
192
140
|
|
|
193
|
-
// If processedEvent is null, middleware blocked the event
|
|
194
141
|
if (processedEvent === null) {
|
|
195
|
-
return;
|
|
142
|
+
return;
|
|
196
143
|
}
|
|
197
144
|
|
|
198
|
-
// Emit processed event
|
|
199
145
|
callback(null, processedEvent);
|
|
200
146
|
});
|
|
201
147
|
};
|
|
@@ -1,10 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
/**
|
|
4
|
-
* fca-nx sendMessage — MQTT primary, OldMessage fallback, E2EE for encrypted DMs.
|
|
5
|
-
* Hardened6: soft MQTT wait, E2EE→MQTT→HTTP cascade, ack retry, paced sends.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
3
|
var utils = require("../../utils/utils");
|
|
9
4
|
var logger = require("../../utils/logger");
|
|
10
5
|
var { waitTurn } = require("../../utils/sendThrottle");
|
|
@@ -113,7 +108,6 @@ function publishLsRequestWithAck(mqttClient, content, requestId, timeout) {
|
|
|
113
108
|
});
|
|
114
109
|
}
|
|
115
110
|
|
|
116
|
-
/** Wait briefly for MQTT to become ready (reconnect in progress). */
|
|
117
111
|
function waitForMqtt(ctx, maxMs) {
|
|
118
112
|
maxMs = maxMs || 4000;
|
|
119
113
|
return new Promise(function (resolve) {
|
|
@@ -266,7 +260,6 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
266
260
|
type: 3
|
|
267
261
|
};
|
|
268
262
|
|
|
269
|
-
// Soft retry once on timeout (common during MQTT flap)
|
|
270
263
|
var timeout = ackTimeout || 18000;
|
|
271
264
|
try {
|
|
272
265
|
return await publishLsRequestWithAck(mqttClient, content, requestId, timeout);
|
|
@@ -277,7 +270,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
277
270
|
await new Promise(function (r) { setTimeout(r, 800 + Math.floor(Math.random() * 700)); });
|
|
278
271
|
mqttClient = await waitForMqtt(ctx, 3000);
|
|
279
272
|
if (!mqttClient || !mqttClient.connected) throw firstErr;
|
|
280
|
-
|
|
273
|
+
|
|
281
274
|
requestId = Math.floor(100 + Math.random() * 900);
|
|
282
275
|
content.request_id = requestId;
|
|
283
276
|
return await publishLsRequestWithAck(mqttClient, content, requestId, Math.min(timeout + 5000, 25000));
|
|
@@ -324,12 +317,10 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
324
317
|
return promise;
|
|
325
318
|
}
|
|
326
319
|
|
|
327
|
-
// Auto-detect isSingleUser from ctx.threadTypes if not explicitly provided.
|
|
328
320
|
if (isSingleUser === undefined && ctx.threadTypes) {
|
|
329
321
|
isSingleUser = ctx.threadTypes[String(threadID)] === "dm";
|
|
330
322
|
}
|
|
331
323
|
|
|
332
|
-
// Empty payload guard (except sticker/attachment/emoji/location)
|
|
333
324
|
var hasContent =
|
|
334
325
|
(msg.body != null && String(msg.body).length > 0) ||
|
|
335
326
|
msg.attachment || msg.sticker || msg.emoji || msg.location ||
|
|
@@ -341,12 +332,8 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
341
332
|
return promise;
|
|
342
333
|
}
|
|
343
334
|
|
|
344
|
-
// Pace all outgoing traffic (anti-burst)
|
|
345
335
|
await waitTurn();
|
|
346
336
|
|
|
347
|
-
// ---- DM attachment path (skip MQTT) ----
|
|
348
|
-
// E2EE DMs: bridge only (MQTT strips attachment_fbids).
|
|
349
|
-
// Plain DMs: OldMessage (/messaging/send/ other_user_fbid).
|
|
350
337
|
if (isSingleUser && msg.attachment) {
|
|
351
338
|
var useE2EE = api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected();
|
|
352
339
|
if (useE2EE) {
|
|
@@ -376,9 +363,6 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
376
363
|
return promise;
|
|
377
364
|
}
|
|
378
365
|
|
|
379
|
-
// ---- E2EE text path with cascade fallback ----
|
|
380
|
-
// Text replies to E2EE DMs should use the bridge; if it fails, try MQTT then OldMessage
|
|
381
|
-
// instead of hard-failing (Hardened6).
|
|
382
366
|
if (isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
|
|
383
367
|
api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected()) {
|
|
384
368
|
try {
|
|
@@ -399,11 +383,10 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
399
383
|
"sendMessage",
|
|
400
384
|
"E2EE DM text failed, cascading to MQTT/HTTP: " + (e2eeTextErr.message || e2eeTextErr)
|
|
401
385
|
);
|
|
402
|
-
|
|
386
|
+
|
|
403
387
|
}
|
|
404
388
|
}
|
|
405
389
|
|
|
406
|
-
// ---- MQTT primary + OldMessage fallback ----
|
|
407
390
|
try {
|
|
408
391
|
var result = await sendViaMqtt(msg, threadID, replyToMessage, 18000);
|
|
409
392
|
if (result && !result.threadID) result.threadID = String(threadID);
|