fca-nx 6.8.8 → 7.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -10
- package/func/checkUpdate.js +1 -1
- package/func/logAdapter.js +2 -0
- package/index.js +3 -0
- package/module/config.js +5 -2
- package/module/login.js +38 -13
- package/module/loginHelper.js +164 -127
- package/module/options.js +7 -1
- package/package.json +2 -2
- package/src/api/action/addfriend.js +9 -3
- package/src/api/action/changeAvatar.js +1 -0
- package/src/api/action/changeCover.js +3 -1
- package/src/api/action/enableAutoSaveAppState.js +18 -5
- package/src/api/action/refreshFb_dtsg.js +18 -76
- package/src/api/http/httpGet.js +6 -2
- package/src/api/http/httpPost.js +7 -2
- package/src/api/messaging/createNewGroup.js +1 -1
- package/src/api/messaging/deleteMessage.js +1 -1
- package/src/api/messaging/forwardMessage.js +9 -1
- package/src/api/messaging/getEmojiUrl.js +5 -1
- package/src/api/messaging/getMessage.js +4 -2
- package/src/api/messaging/getThemePictures.js +21 -28
- package/src/api/messaging/markAsRead.js +1 -0
- package/src/api/messaging/muteThread.js +1 -1
- package/src/api/messaging/pinMessage.js +10 -1
- package/src/api/messaging/scheduler.js +71 -4
- package/src/api/messaging/sendBroadcast.js +15 -0
- package/src/api/messaging/sendMessage.js +23 -1
- package/src/api/messaging/sendTypingIndicator.js +0 -15
- package/src/api/messaging/sessionGuard.js +45 -9
- package/src/api/messaging/setMessageReaction.js +2 -1
- package/src/api/messaging/threadColors.js +45 -12
- package/src/api/messaging/uploadAttachment.js +37 -3
- package/src/api/socket/OldMessage.js +7 -2
- package/src/api/socket/core/connectMqtt.js +68 -81
- package/src/api/socket/core/emitAuth.js +11 -2
- package/src/api/socket/core/getSeqID.js +28 -36
- package/src/api/socket/core/getTaskResponseData.js +3 -1
- package/src/api/socket/core/parseDelta.js +1 -1
- package/src/api/socket/detail/buildStream.js +4 -1
- package/src/api/socket/detail/constants.js +4 -1
- package/src/api/socket/e2ee/crypto.js +40 -2
- package/src/api/socket/e2ee/index.js +124 -73
- package/src/api/socket/e2ee/protocol.js +40 -32
- package/src/api/socket/e2ee/ratchet.js +43 -37
- package/src/api/socket/e2ee/store.js +47 -133
- package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +18 -140
- package/src/api/socket/listenE2EE.js +23 -12
- package/src/api/socket/listenMqtt.js +94 -110
- package/src/api/socket/middleware/index.js +61 -7
- package/src/api/socket/sendMessage.js +78 -170
- package/src/api/socket/sendMessageMqtt.js +6 -0
- package/src/api/threads/getThreadHistory.js +68 -38
- package/src/api/threads/getThreadInfo.js +4 -3
- package/src/api/threads/getThreadList.js +34 -31
- package/src/api/threads/getThreadPictures.js +1 -1
- package/src/api/users/getUserInfo.js +5 -2
- package/src/api/users/getUserInfoV2.js +65 -59
- package/src/app/createFcaClient.js +2 -2
- package/src/core/sendReqMqtt.js +2 -1
- package/src/database/helpers.js +12 -0
- package/src/database/models/index.js +8 -9
- package/src/utils/broadcast.js +1 -1
- package/src/utils/clientIdentity.js +50 -3
- package/src/utils/cookies.js +4 -2
- package/src/utils/format/utils.js +10 -0
- package/src/utils/headers.js +26 -12
- package/src/utils/loginParser/autoLogin.js +12 -0
- package/src/utils/loginParser/parseAndCheckLogin.js +7 -0
- package/src/utils/loginParser/textUtils.js +6 -0
- package/src/utils/request/config.js +4 -1
- package/src/utils/request/methods.js +0 -13
- package/src/utils/request/proxy.js +13 -0
- package/src/utils/request/retry.js +0 -10
- package/src/utils/request/sanitize.js +1 -1
- package/src/utils/textEffects.js +85 -0
- package/src/utils/utils.js +17 -3
- package/src/utils/instanceLock.js +0 -35
- package/src/utils/ipGuard.js +0 -58
- package/src/utils/sendThrottle.js +0 -51
|
@@ -1,7 +1,17 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* FCA-NX E2EE Crypto — All primitives using Node.js built-in crypto only.
|
|
5
|
+
* Implements: X25519 DH, HKDF-SHA256, AES-256-GCM, HMAC-SHA256
|
|
6
|
+
* Node.js >= 15 required (crypto.hkdfSync, crypto.generateKeyPairSync x25519).
|
|
7
|
+
*/
|
|
8
|
+
|
|
3
9
|
const crypto = require("crypto");
|
|
4
10
|
|
|
11
|
+
// ─────────────────────────────────────────────────────────
|
|
12
|
+
// X25519 Key Management
|
|
13
|
+
// ─────────────────────────────────────────────────────────
|
|
14
|
+
|
|
5
15
|
function generateKeyPair() {
|
|
6
16
|
const { privateKey, publicKey } = crypto.generateKeyPairSync("x25519", {
|
|
7
17
|
privateKeyEncoding: { type: "pkcs8", format: "der" },
|
|
@@ -15,13 +25,13 @@ function generateKeyPair() {
|
|
|
15
25
|
}
|
|
16
26
|
|
|
17
27
|
function exportRawPublicKey(spkiDer) {
|
|
18
|
-
|
|
28
|
+
// X25519 SPKI DER: 12 bytes header + 32 bytes key
|
|
19
29
|
return Buffer.from(spkiDer).slice(-32);
|
|
20
30
|
}
|
|
21
31
|
|
|
22
32
|
function importPublicKey(raw32bytes) {
|
|
23
33
|
if (raw32bytes.length !== 32) throw new Error("X25519 public key must be 32 bytes");
|
|
24
|
-
|
|
34
|
+
// Build minimal SPKI wrapper for X25519
|
|
25
35
|
const header = Buffer.from("302a300506032b656e032100", "hex");
|
|
26
36
|
return Buffer.concat([header, raw32bytes]);
|
|
27
37
|
}
|
|
@@ -33,6 +43,10 @@ function dh(privateKeyPkcs8Der, peerPublicRaw32) {
|
|
|
33
43
|
return crypto.diffieHellman({ privateKey: privKey, publicKey: pubKey });
|
|
34
44
|
}
|
|
35
45
|
|
|
46
|
+
// ─────────────────────────────────────────────────────────
|
|
47
|
+
// HKDF-SHA256
|
|
48
|
+
// ─────────────────────────────────────────────────────────
|
|
49
|
+
|
|
36
50
|
function hkdf(ikm, length, salt, info) {
|
|
37
51
|
if (!salt) salt = Buffer.alloc(32, 0);
|
|
38
52
|
if (!info) info = Buffer.alloc(0);
|
|
@@ -60,6 +74,10 @@ function hkdfExpand(prk, info, length) {
|
|
|
60
74
|
return Buffer.concat(results).slice(0, length);
|
|
61
75
|
}
|
|
62
76
|
|
|
77
|
+
// ─────────────────────────────────────────────────────────
|
|
78
|
+
// AES-256-GCM
|
|
79
|
+
// ─────────────────────────────────────────────────────────
|
|
80
|
+
|
|
63
81
|
function encrypt(key32, plaintext, aad) {
|
|
64
82
|
if (key32.length !== 32) throw new Error("AES-GCM key must be 32 bytes");
|
|
65
83
|
const iv = crypto.randomBytes(12);
|
|
@@ -82,6 +100,10 @@ function decrypt(key32, ciphertext, aad) {
|
|
|
82
100
|
return Buffer.concat([decipher.update(data), decipher.final()]);
|
|
83
101
|
}
|
|
84
102
|
|
|
103
|
+
// ─────────────────────────────────────────────────────────
|
|
104
|
+
// HMAC-SHA256
|
|
105
|
+
// ─────────────────────────────────────────────────────────
|
|
106
|
+
|
|
85
107
|
function hmacSha256(key, data) {
|
|
86
108
|
return crypto.createHmac("sha256", key).update(data).digest();
|
|
87
109
|
}
|
|
@@ -91,6 +113,19 @@ function constantTimeEqual(a, b) {
|
|
|
91
113
|
return crypto.timingSafeEqual(a, b);
|
|
92
114
|
}
|
|
93
115
|
|
|
116
|
+
// ─────────────────────────────────────────────────────────
|
|
117
|
+
// X3DH Key Agreement (Extended Triple Diffie-Hellman)
|
|
118
|
+
// ─────────────────────────────────────────────────────────
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Sender side of X3DH.
|
|
122
|
+
* @param {object} senderIdKey - { privateKey, publicKey, publicKeyRaw } of sender identity key
|
|
123
|
+
* @param {object} ephemeralKey - { privateKey, publicKey, publicKeyRaw } of ephemeral key
|
|
124
|
+
* @param {Buffer} recipientIdPub - recipient's identity public key (raw 32 bytes)
|
|
125
|
+
* @param {Buffer} recipientSpkPub - recipient's signed pre-key (raw 32 bytes)
|
|
126
|
+
* @param {Buffer} [recipientOpkPub] - recipient's one-time pre-key (raw 32 bytes), optional
|
|
127
|
+
* @returns {Buffer} 32-byte shared master secret
|
|
128
|
+
*/
|
|
94
129
|
function x3dhSend(senderIdKey, ephemeralKey, recipientIdPub, recipientSpkPub, recipientOpkPub) {
|
|
95
130
|
const dh1 = dh(senderIdKey.privateKey, recipientSpkPub);
|
|
96
131
|
const dh2 = dh(ephemeralKey.privateKey, recipientIdPub);
|
|
@@ -104,6 +139,9 @@ function x3dhSend(senderIdKey, ephemeralKey, recipientIdPub, recipientSpkPub, re
|
|
|
104
139
|
return hkdf(Buffer.concat([F, ikm]), 32, salt, Buffer.from("WhisperText", "utf8"));
|
|
105
140
|
}
|
|
106
141
|
|
|
142
|
+
/**
|
|
143
|
+
* Receiver side of X3DH.
|
|
144
|
+
*/
|
|
107
145
|
function x3dhReceive(recipientIdKey, recipientSpkKey, recipientOpkKey, senderIdPub, senderEphemeralPub) {
|
|
108
146
|
const dh1 = dh(recipientSpkKey.privateKey, senderIdPub);
|
|
109
147
|
const dh2 = dh(recipientIdKey.privateKey, senderEphemeralPub);
|
|
@@ -1,12 +1,29 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* FCA-NX E2EE Bridge — Signal Protocol + Noise WebSocket
|
|
5
|
+
*
|
|
6
|
+
* Uses FCA-NX's own native E2EE engine bundled at ./vendor/fb-e2ee.cjs.
|
|
7
|
+
* No external npm package needed — all E2EE code is owned by FCA-NX.
|
|
8
|
+
*
|
|
9
|
+
* Direct deps (fca/package.json): @signalapp/libsignal-client, protobufjs,
|
|
10
|
+
* @noble/curves, @noble/hashes
|
|
11
|
+
*
|
|
12
|
+
* Full protocol stack:
|
|
13
|
+
* • @signalapp/libsignal-client — Signal Protocol (Double Ratchet)
|
|
14
|
+
* • Noise_XX_25519_AESGCM_SHA256 WebSocket handshake
|
|
15
|
+
* • WA-binary + Protobuf message encoding
|
|
16
|
+
* • ICDC device registration with Facebook
|
|
17
|
+
*/
|
|
18
|
+
|
|
3
19
|
const path = require("path");
|
|
4
20
|
const logger = require("../../../utils/logger");
|
|
5
21
|
const requestHttp = require("../../../utils/request");
|
|
6
22
|
|
|
7
23
|
function loadFBClient() {
|
|
8
24
|
try {
|
|
9
|
-
|
|
25
|
+
// [Fixed by xalman] see comment above loadFBClient - Node < 22 has no
|
|
26
|
+
// global WebSocket, but fb-e2ee.cjs unconditionally does `new WebSocket(...)`.
|
|
10
27
|
if (typeof global.WebSocket === "undefined") {
|
|
11
28
|
global.WebSocket = require("ws");
|
|
12
29
|
}
|
|
@@ -31,8 +48,15 @@ class E2EEBridge {
|
|
|
31
48
|
this._messageCallback = null;
|
|
32
49
|
}
|
|
33
50
|
|
|
34
|
-
|
|
51
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
52
|
+
// Setup
|
|
53
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
35
54
|
|
|
55
|
+
async connect(deviceStorePath, userId) {
|
|
56
|
+
// Guard against concurrent/duplicate connect() calls (e.g. bot code
|
|
57
|
+
// calling api.connectE2EE() explicitly while auto-connect is also
|
|
58
|
+
// running) — without this, two parallel connects race and corrupt
|
|
59
|
+
// `this.client`, causing undefined responses downstream.
|
|
36
60
|
if (this._connectPromise) return this._connectPromise;
|
|
37
61
|
if (this.connected) return Promise.resolve({ userId: this.ctx.userID });
|
|
38
62
|
|
|
@@ -49,11 +73,12 @@ class E2EEBridge {
|
|
|
49
73
|
|
|
50
74
|
userId = userId || this.ctx.userID;
|
|
51
75
|
|
|
76
|
+
// Default to .fca-nx/e2ee_device.json in the user's project directory
|
|
52
77
|
if (!deviceStorePath) {
|
|
53
|
-
deviceStorePath = process.
|
|
54
|
-
|| path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
|
|
78
|
+
deviceStorePath = path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
|
|
55
79
|
}
|
|
56
80
|
|
|
81
|
+
// Auto-create parent directory — users don't need to create it manually
|
|
57
82
|
try {
|
|
58
83
|
fs.mkdirSync(path.dirname(deviceStorePath), { recursive: true });
|
|
59
84
|
} catch (_) {}
|
|
@@ -62,6 +87,7 @@ class E2EEBridge {
|
|
|
62
87
|
|
|
63
88
|
const FBClient = loadFBClient();
|
|
64
89
|
|
|
90
|
+
// Re-use the already-loaded session from FCA-NX's cookie jar
|
|
65
91
|
const appState = this.api.getAppState();
|
|
66
92
|
|
|
67
93
|
this.client = new FBClient({
|
|
@@ -69,6 +95,12 @@ class E2EEBridge {
|
|
|
69
95
|
platform: "facebook",
|
|
70
96
|
});
|
|
71
97
|
|
|
98
|
+
// Build the FCA-NX adapter that replaces fb-messenger-e2ee's internal
|
|
99
|
+
// fca-unofficial login. fb-messenger-e2ee calls
|
|
100
|
+
// this.gateway.login(appState)
|
|
101
|
+
// inside connect() which triggers a *second* fca-unofficial login and
|
|
102
|
+
// crashes when the network call returns undefined.
|
|
103
|
+
// By replacing gateway.login BEFORE connect() we prevent that entirely.
|
|
72
104
|
const _ctx = this.ctx;
|
|
73
105
|
const _fcanxApi = this.api;
|
|
74
106
|
const _defaultFuncs = this.defaultFuncs;
|
|
@@ -77,7 +109,11 @@ class E2EEBridge {
|
|
|
77
109
|
fb_dtsg: _ctx.fb_dtsg,
|
|
78
110
|
getCurrentUserID: () => _fcanxApi.getCurrentUserID(),
|
|
79
111
|
getAppState: () => _fcanxApi.getAppState(),
|
|
80
|
-
|
|
112
|
+
// [Fixed by xalman] httpPost always returns a string now - axios
|
|
113
|
+
// auto-parses JSON responses into objects, but the vendored engine
|
|
114
|
+
// (fetchCAT/icdc_fetch/icdc_register) expects raw text and calls
|
|
115
|
+
// .replace()/JSON.parse() on it itself. This was crashing E2EE
|
|
116
|
+
// auto-connect with "resText.replace is not a function".
|
|
81
117
|
httpPost: async function (url, form) {
|
|
82
118
|
var merged = Object.assign({}, form);
|
|
83
119
|
if (!merged.fb_dtsg && _ctx.fb_dtsg) merged.fb_dtsg = _ctx.fb_dtsg;
|
|
@@ -89,18 +125,23 @@ class E2EEBridge {
|
|
|
89
125
|
if (body == null) return body;
|
|
90
126
|
if (typeof body === "string") return body;
|
|
91
127
|
if (Buffer.isBuffer(body)) return body.toString("utf8");
|
|
92
|
-
|
|
128
|
+
// axios auto-parses JSON bodies into an object/array, but the
|
|
129
|
+
// vendored engine always expects a raw string (it strips
|
|
130
|
+
// Facebook's "for (;;);" prefix and JSON.parses it itself).
|
|
131
|
+
// Re-serialize so callers doing resText.replace(...) still work.
|
|
93
132
|
try {
|
|
94
133
|
return JSON.stringify(body);
|
|
95
134
|
} catch {
|
|
96
135
|
return String(body);
|
|
97
136
|
}
|
|
98
137
|
},
|
|
99
|
-
|
|
138
|
+
// listenMqtt — fb-e2ee.cjs calls this to route non-E2EE MQTT events.
|
|
139
|
+
// FCA-NX has its own separate MQTT listener so we provide a no-op stub
|
|
140
|
+
// to prevent a competing second listener from being started.
|
|
100
141
|
listenMqtt: function () { return; },
|
|
101
142
|
stopListenMqtt: function () {},
|
|
102
143
|
setOptions: function () {},
|
|
103
|
-
|
|
144
|
+
// Delegate messaging methods to FCA-NX's real api
|
|
104
145
|
sendMessage: function (msg, threadID, callback, replyToMessage) {
|
|
105
146
|
return _fcanxApi.sendMessage(msg, threadID, callback, replyToMessage);
|
|
106
147
|
},
|
|
@@ -134,6 +175,9 @@ class E2EEBridge {
|
|
|
134
175
|
},
|
|
135
176
|
};
|
|
136
177
|
|
|
178
|
+
// Inject the adapter as a global so that fb-e2ee.cjs's internal
|
|
179
|
+
// require("../../vendor/fca-unofficial") login() intercepts it and
|
|
180
|
+
// skips the real Facebook login, returning FCA-NX's session instead.
|
|
137
181
|
global._fcanxE2EEAdapter = _fcanxAdapter;
|
|
138
182
|
|
|
139
183
|
logger.info("E2EE", "Bootstrapping auth via vendored E2EE engine (FCA-NX session)...");
|
|
@@ -145,6 +189,7 @@ class E2EEBridge {
|
|
|
145
189
|
delete global._fcanxE2EEAdapter;
|
|
146
190
|
}
|
|
147
191
|
|
|
192
|
+
// Also patch controller.api (used for CAT/ICDC calls after connect)
|
|
148
193
|
if (this.client.controller) {
|
|
149
194
|
this.client.controller.api = _fcanxAdapter;
|
|
150
195
|
}
|
|
@@ -154,48 +199,45 @@ class E2EEBridge {
|
|
|
154
199
|
const _e2eeUserId = resolvedUserId || userId;
|
|
155
200
|
await this.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
|
|
156
201
|
|
|
202
|
+
// Auto-reconnect the Noise WebSocket whenever it drops unexpectedly.
|
|
203
|
+
// `this.connected` stays true through reconnect cycles; it's only set
|
|
204
|
+
// false by an explicit api.e2ee.disconnect() call.
|
|
157
205
|
const _self = this;
|
|
158
|
-
this.
|
|
159
|
-
|
|
160
|
-
if (!_self.connected) return;
|
|
161
|
-
if (data && data.isE2EE === false) return;
|
|
162
|
-
if (_self._reconnecting) return;
|
|
163
|
-
_self._reconnecting = true;
|
|
206
|
+
this.client.onEvent("disconnected", function _onE2EEDisconnected() {
|
|
207
|
+
if (!_self.connected) return; // intentional disconnect — skip
|
|
164
208
|
logger.warn("E2EE", "Noise WebSocket disconnected — reconnecting in 5s...");
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
if (!_self.connected) { _self._reconnecting = false; return; }
|
|
168
|
-
attempt++;
|
|
209
|
+
setTimeout(async function () {
|
|
210
|
+
if (!_self.connected) return;
|
|
169
211
|
try {
|
|
170
212
|
await _self.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
|
|
171
|
-
|
|
172
|
-
logger.success("E2EE", "E2EE WebSocket reconnected" + (attempt > 1 ? " (attempt " + attempt + ")" : "") + ".");
|
|
213
|
+
logger.success("E2EE", "E2EE WebSocket reconnected.");
|
|
173
214
|
} catch (err) {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
215
|
+
logger.error("E2EE", "E2EE reconnect failed: " + (err && err.message ? err.message : String(err)));
|
|
216
|
+
// Retry again after another 10s if reconnect failed
|
|
217
|
+
if (_self.connected) {
|
|
218
|
+
setTimeout(async function () {
|
|
219
|
+
if (!_self.connected) return;
|
|
220
|
+
try {
|
|
221
|
+
await _self.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
|
|
222
|
+
logger.success("E2EE", "E2EE WebSocket reconnected (retry).");
|
|
223
|
+
} catch (err2) {
|
|
224
|
+
logger.error("E2EE", "E2EE reconnect retry failed: " + (err2 && err2.message ? err2.message : String(err2)));
|
|
225
|
+
}
|
|
226
|
+
}, 10000);
|
|
227
|
+
}
|
|
177
228
|
}
|
|
178
|
-
};
|
|
179
|
-
setTimeout(tryReconnect, 5000);
|
|
229
|
+
}, 5000);
|
|
180
230
|
});
|
|
181
231
|
|
|
182
|
-
|
|
232
|
+
// Forward incoming E2EE messages to the registered callback.
|
|
183
233
|
this.client.onEvent("e2ee_message", (msg) => {
|
|
184
|
-
if (!this._messageCallback)
|
|
185
|
-
logger.warn("E2EE", "Incoming E2EE message dropped: no listener registered yet");
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
if (msg && msg.id) {
|
|
190
|
-
if (this._recentIds.has(msg.id)) return;
|
|
191
|
-
this._recentIds.add(msg.id);
|
|
192
|
-
if (this._recentIds.size > 2000) this._recentIds.delete(this._recentIds.values().next().value);
|
|
193
|
-
}
|
|
234
|
+
if (!this._messageCallback) return;
|
|
194
235
|
|
|
195
236
|
const senderID =
|
|
196
237
|
msg.senderId ||
|
|
197
238
|
(typeof msg.senderJid === "string" ? msg.senderJid.split(".")[0] : "");
|
|
198
239
|
|
|
240
|
+
// Build mentions: vendor surfaces an array [{ id, text }] or object
|
|
199
241
|
var mentions = {};
|
|
200
242
|
if (Array.isArray(msg.mentions)) {
|
|
201
243
|
msg.mentions.forEach(function(m) {
|
|
@@ -221,11 +263,17 @@ class E2EEBridge {
|
|
|
221
263
|
args: (msg.text || "").trim().split(/\s+/).filter(Boolean),
|
|
222
264
|
};
|
|
223
265
|
|
|
266
|
+
// Populate ctx.threadTypes so that sendMessage.js can detect this
|
|
267
|
+
// as a DM and route attachments through OldMessage (not MQTT).
|
|
268
|
+
// E2EE DM messages arrive via the Noise WebSocket — not MQTT — so
|
|
269
|
+
// parseDelta never sees them and ctx.threadTypes stays empty unless
|
|
270
|
+
// we populate it here.
|
|
224
271
|
if (!event.isGroup && msg.threadId) {
|
|
225
272
|
this.ctx.threadTypes = this.ctx.threadTypes || {};
|
|
226
273
|
this.ctx.threadTypes[String(msg.threadId)] = 'dm';
|
|
227
274
|
}
|
|
228
275
|
|
|
276
|
+
// Populate messageReply so reply handlers work the same as in MQTT
|
|
229
277
|
if (isReply) {
|
|
230
278
|
event.messageReply = {
|
|
231
279
|
messageID: msg.replyTo.messageId,
|
|
@@ -240,18 +288,11 @@ class E2EEBridge {
|
|
|
240
288
|
};
|
|
241
289
|
}
|
|
242
290
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
try {
|
|
246
|
-
const r = this._messageCallback(null, event);
|
|
247
|
-
if (r && typeof r.catch === "function") {
|
|
248
|
-
r.catch((e) => logger.error("E2EE", "Message callback rejected: " + (e && e.message ? e.message : String(e))));
|
|
249
|
-
}
|
|
250
|
-
} catch (e) {
|
|
251
|
-
logger.error("E2EE", "Message callback threw: " + (e && e.message ? e.message : String(e)));
|
|
252
|
-
}
|
|
291
|
+
this._messageCallback(null, event);
|
|
253
292
|
});
|
|
254
293
|
|
|
294
|
+
// Surface connection errors so the bot log shows them.
|
|
295
|
+
// Silently ignore DuplicatedMessage errors — these are harmless replays on reconnect.
|
|
255
296
|
this.client.onEvent("error", (err) => {
|
|
256
297
|
if (err && (err.code === 1 || (err.message && err.message.includes("old counter")))) return;
|
|
257
298
|
logger.error("E2EE", "E2EE error: " + (err && err.message ? err.message : String(err)));
|
|
@@ -268,43 +309,45 @@ class E2EEBridge {
|
|
|
268
309
|
}
|
|
269
310
|
}
|
|
270
311
|
|
|
271
|
-
async _waitReady(timeoutMs) {
|
|
272
|
-
const ctl = this.client && this.client.controller;
|
|
273
|
-
const isReady = () => !ctl || ctl.e2eeConnected !== false;
|
|
274
|
-
const deadline = Date.now() + (timeoutMs || 20000);
|
|
275
|
-
while (!isReady()) {
|
|
276
|
-
if (!this.connected) throw new Error("E2EE disconnected.");
|
|
277
|
-
if (Date.now() > deadline) throw new Error("E2EE socket is reconnecting; message not sent (timeout).");
|
|
278
|
-
await new Promise((r) => setTimeout(r, 250));
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
312
|
isConnected() {
|
|
283
313
|
return this.connected;
|
|
284
314
|
}
|
|
285
315
|
|
|
316
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
317
|
+
// Send API (all go through the Noise WebSocket)
|
|
318
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Send a message on an E2EE (or non-E2EE) thread.
|
|
322
|
+
*
|
|
323
|
+
* msg can be:
|
|
324
|
+
* - string → plain text
|
|
325
|
+
* - { body, attachment} → text + one or more readable streams
|
|
326
|
+
*
|
|
327
|
+
* Attachments on E2EE threads are encrypted and sent via the Noise WebSocket.
|
|
328
|
+
* Attachments on non-E2EE threads fall back to api.sendMessage (FCA-NX's own).
|
|
329
|
+
*/
|
|
286
330
|
async sendMessage(threadId, msg, replyToMessageId) {
|
|
287
331
|
this.ensureConnected();
|
|
288
|
-
await this._waitReady();
|
|
289
|
-
await require("../../../utils/sendThrottle").waitTurn();
|
|
290
332
|
|
|
291
333
|
const text = typeof msg === "string" ? msg : (msg && msg.body != null ? String(msg.body) : "");
|
|
292
334
|
const attachment = (msg && typeof msg === "object") ? (msg.attachment || null) : null;
|
|
293
335
|
|
|
294
336
|
if (!attachment) {
|
|
295
|
-
|
|
296
|
-
const ctl = this.client.controller;
|
|
297
|
-
const tid = String(threadId);
|
|
298
|
-
if (ctl && typeof ctl.sendE2EEText === "function" && typeof ctl.sendE2EEGroupText === "function") {
|
|
299
|
-
const isGroupJid = tid.includes("@g.us") || tid.includes(".g.");
|
|
300
|
-
const messageId = isGroupJid
|
|
301
|
-
? await ctl.sendE2EEGroupText(tid, text, replyToMessageId, undefined)
|
|
302
|
-
: await ctl.sendE2EEText(tid, text, replyToMessageId, undefined);
|
|
303
|
-
return { messageId, timestampMs: Date.now() };
|
|
304
|
-
}
|
|
305
337
|
return this.client.sendMessage({ threadId, text, replyToMessageId });
|
|
306
338
|
}
|
|
307
339
|
|
|
340
|
+
// Always use the vendor's Noise WebSocket path for attachments.
|
|
341
|
+
// The isE2EEThreadId() check was removed because:
|
|
342
|
+
// 1. It frequently returns false for valid E2EE DM thread IDs (user-id format),
|
|
343
|
+
// which caused fallback to api.sendMessage → MQTT, where Facebook strips
|
|
344
|
+
// attachment_fbids from the E2EE envelope → attachment silently dropped.
|
|
345
|
+
// 2. This method is only called when the thread is KNOWN to be an E2EE DM
|
|
346
|
+
// (sendMessage.js routes here only when isSingleUser=true AND e2ee.isConnected()).
|
|
347
|
+
// 3. client.sendImage/sendVideo/sendAudio handle the JID conversion internally
|
|
348
|
+
// (100055943906136 → 100055943906136.0@msgr) so the threadId format is fine.
|
|
349
|
+
|
|
350
|
+
// E2EE path: read stream(s) → Buffer, detect type, send via vendor
|
|
308
351
|
const path = require("path");
|
|
309
352
|
let mime;
|
|
310
353
|
try { mime = require("mime"); } catch (_) {}
|
|
@@ -339,32 +382,36 @@ class E2EEBridge {
|
|
|
339
382
|
|
|
340
383
|
async sendReaction(threadId, messageId, reaction, senderJid) {
|
|
341
384
|
this.ensureConnected();
|
|
342
|
-
await this._waitReady();
|
|
343
385
|
return this.client.sendReaction({ threadId, messageId, reaction, senderJid });
|
|
344
386
|
}
|
|
345
387
|
|
|
346
388
|
async sendTyping(threadId, isTyping) {
|
|
347
389
|
this.ensureConnected();
|
|
348
|
-
await this._waitReady(3000);
|
|
349
390
|
return this.client.sendTyping({ threadId, isTyping: isTyping !== false });
|
|
350
391
|
}
|
|
351
392
|
|
|
352
393
|
async unsendMessage(messageId, threadId) {
|
|
353
394
|
this.ensureConnected();
|
|
354
|
-
await this._waitReady();
|
|
355
395
|
return this.client.unsendMessage({ messageId, threadId });
|
|
356
396
|
}
|
|
357
397
|
|
|
358
398
|
async editMessage(threadId, messageId, newText) {
|
|
359
399
|
this.ensureConnected();
|
|
360
|
-
await this._waitReady();
|
|
361
400
|
return this.client.editMessage({ threadId, messageId, newText });
|
|
362
401
|
}
|
|
363
402
|
|
|
403
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
404
|
+
// Receive API
|
|
405
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
406
|
+
|
|
364
407
|
onMessage(callback) {
|
|
365
408
|
this._messageCallback = callback;
|
|
366
409
|
}
|
|
367
410
|
|
|
411
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
412
|
+
// Info / lifecycle
|
|
413
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
414
|
+
|
|
368
415
|
getPublicKeys() {
|
|
369
416
|
return {
|
|
370
417
|
info: "Keys managed by vendored E2EE engine (Signal Protocol / Noise handshake).",
|
|
@@ -383,6 +430,10 @@ class E2EEBridge {
|
|
|
383
430
|
|
|
384
431
|
module.exports = { E2EEBridge };
|
|
385
432
|
|
|
433
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
434
|
+
// Private helpers
|
|
435
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
436
|
+
|
|
386
437
|
function _streamToBuffer(stream) {
|
|
387
438
|
return new Promise(function (resolve, reject) {
|
|
388
439
|
var chunks = [];
|
|
@@ -1,8 +1,33 @@
|
|
|
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
|
+
|
|
3
15
|
const crypto = require("crypto");
|
|
4
16
|
const { hmacSha256, generateKeyPair, randomBytes } = require("./crypto");
|
|
5
17
|
|
|
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
|
+
|
|
6
31
|
const MAGIC = 0x4E58;
|
|
7
32
|
const VERSION = 0x01;
|
|
8
33
|
const TYPE = { INIT: 0, MESSAGE: 1, REACTION: 2, RECEIPT: 3, TYPING: 4 };
|
|
@@ -37,53 +62,32 @@ function encodeFrame(type, senderID, threadID, header, payload) {
|
|
|
37
62
|
}
|
|
38
63
|
|
|
39
64
|
function decodeFrame(buf) {
|
|
40
|
-
if (Buffer.isBuffer(buf))
|
|
41
|
-
|
|
42
|
-
} else if (buf instanceof Uint8Array) {
|
|
43
|
-
buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
44
|
-
} else {
|
|
45
|
-
throw new TypeError("Frame must be a Buffer or Uint8Array");
|
|
46
|
-
}
|
|
65
|
+
if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
|
|
47
66
|
if (buf.length < 8) throw new Error("Frame too short");
|
|
48
67
|
let offset = 0;
|
|
49
68
|
|
|
50
|
-
function requireBytes(length, label) {
|
|
51
|
-
if (!Number.isSafeInteger(length) || length < 0 || length > buf.length - offset) {
|
|
52
|
-
throw new Error(`Invalid or truncated frame ${label}`);
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function readLength(label) {
|
|
57
|
-
requireBytes(4, `${label} length`);
|
|
58
|
-
const length = buf.readUInt32BE(offset);
|
|
59
|
-
offset += 4;
|
|
60
|
-
requireBytes(length, label);
|
|
61
|
-
return length;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
69
|
const magic = buf.readUInt16BE(offset); offset += 2;
|
|
65
70
|
if (magic !== MAGIC) throw new Error("Invalid frame magic: " + magic.toString(16));
|
|
66
71
|
const version = buf.readUInt8(offset); offset += 1;
|
|
67
|
-
if (version !== VERSION) throw new Error("Unsupported frame version: " + version);
|
|
68
72
|
const type = buf.readUInt8(offset); offset += 1;
|
|
69
|
-
if (!Object.values(TYPE).includes(type)) throw new Error("Invalid frame type: " + type);
|
|
70
73
|
|
|
71
|
-
const sidLen =
|
|
72
|
-
const senderID = buf.
|
|
74
|
+
const sidLen = buf.readUInt32BE(offset); offset += 4;
|
|
75
|
+
const senderID = buf.slice(offset, offset + sidLen).toString("utf8"); offset += sidLen;
|
|
73
76
|
|
|
74
|
-
const tidLen =
|
|
75
|
-
const threadID = buf.
|
|
77
|
+
const tidLen = buf.readUInt32BE(offset); offset += 4;
|
|
78
|
+
const threadID = buf.slice(offset, offset + tidLen).toString("utf8"); offset += tidLen;
|
|
76
79
|
|
|
77
|
-
const hdrLen =
|
|
78
|
-
const header = buf.
|
|
80
|
+
const hdrLen = buf.readUInt32BE(offset); offset += 4;
|
|
81
|
+
const header = buf.slice(offset, offset + hdrLen); offset += hdrLen;
|
|
79
82
|
|
|
80
|
-
const payLen =
|
|
81
|
-
const payload = buf.
|
|
82
|
-
if (offset !== buf.length) throw new Error("Unexpected trailing bytes in frame");
|
|
83
|
+
const payLen = buf.readUInt32BE(offset); offset += 4;
|
|
84
|
+
const payload = buf.slice(offset, offset + payLen);
|
|
83
85
|
|
|
84
86
|
return { version, type, senderID, threadID, header, payload };
|
|
85
87
|
}
|
|
86
88
|
|
|
89
|
+
// ─── Key Bundle ────────────────────────────────────────────────────────────────
|
|
90
|
+
|
|
87
91
|
function buildKeyBundle(identityKey, signedPreKey, oneTimePreKeys) {
|
|
88
92
|
return {
|
|
89
93
|
identityKey: identityKey.publicKeyRaw.toString("base64"),
|
|
@@ -103,6 +107,8 @@ function signKey(identityPrivateKey, keyToSign) {
|
|
|
103
107
|
return hmacSha256(identityPrivateKey, keyToSign.publicKeyRaw);
|
|
104
108
|
}
|
|
105
109
|
|
|
110
|
+
// ─── Facebook Graph API: key registration/fetching ───────────────────────────
|
|
111
|
+
|
|
106
112
|
async function uploadKeyBundle(defaultFuncs, ctx, keyBundle) {
|
|
107
113
|
try {
|
|
108
114
|
const res = await defaultFuncs.post(
|
|
@@ -147,6 +153,8 @@ async function fetchRecipientKeyBundle(defaultFuncs, ctx, recipientUserID) {
|
|
|
147
153
|
}
|
|
148
154
|
}
|
|
149
155
|
|
|
156
|
+
// ─── Message payload builders ─────────────────────────────────────────────────
|
|
157
|
+
|
|
150
158
|
function buildInitPayload(senderEphemeralPub, senderOneTimeKeyId, recipientOneTimeKeyId) {
|
|
151
159
|
return JSON.stringify({
|
|
152
160
|
type: "x3dh_init",
|