fca-nx 6.8.8 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -10
- package/func/checkUpdate.js +1 -1
- package/func/logAdapter.js +2 -0
- package/index.js +3 -0
- package/module/config.js +5 -3
- package/module/login.js +38 -13
- package/module/loginHelper.js +207 -148
- package/module/options.js +7 -1
- package/package.json +2 -2
- package/src/api/action/addfriend.js +9 -3
- package/src/api/action/changeAvatar.js +1 -0
- package/src/api/action/changeCover.js +3 -1
- package/src/api/action/enableAutoSaveAppState.js +18 -5
- package/src/api/action/refreshFb_dtsg.js +18 -76
- package/src/api/http/httpGet.js +6 -2
- package/src/api/http/httpPost.js +7 -2
- package/src/api/messaging/createNewGroup.js +1 -1
- package/src/api/messaging/deleteMessage.js +1 -1
- package/src/api/messaging/forwardMessage.js +9 -1
- package/src/api/messaging/getEmojiUrl.js +5 -1
- package/src/api/messaging/getMessage.js +4 -2
- package/src/api/messaging/getThemePictures.js +7 -0
- package/src/api/messaging/markAsRead.js +1 -0
- package/src/api/messaging/muteThread.js +1 -1
- package/src/api/messaging/pinMessage.js +10 -1
- package/src/api/messaging/scheduler.js +71 -4
- package/src/api/messaging/sendBroadcast.js +15 -0
- package/src/api/messaging/sendMessage.js +23 -1
- package/src/api/messaging/sendTypingIndicator.js +0 -15
- package/src/api/messaging/sessionGuard.js +45 -9
- package/src/api/messaging/setMessageReaction.js +2 -1
- package/src/api/messaging/threadColors.js +45 -12
- package/src/api/messaging/uploadAttachment.js +37 -3
- package/src/api/socket/OldMessage.js +7 -2
- package/src/api/socket/core/connectMqtt.js +68 -81
- package/src/api/socket/core/emitAuth.js +11 -2
- package/src/api/socket/core/getSeqID.js +52 -56
- package/src/api/socket/core/getTaskResponseData.js +3 -1
- package/src/api/socket/core/parseDelta.js +1 -1
- package/src/api/socket/detail/buildStream.js +4 -1
- package/src/api/socket/detail/constants.js +4 -1
- package/src/api/socket/e2ee/crypto.js +40 -2
- package/src/api/socket/e2ee/index.js +123 -10
- package/src/api/socket/e2ee/protocol.js +32 -1
- package/src/api/socket/e2ee/ratchet.js +44 -10
- package/src/api/socket/e2ee/store.js +13 -1
- package/src/api/socket/listenE2EE.js +25 -1
- package/src/api/socket/listenMqtt.js +94 -110
- package/src/api/socket/middleware/index.js +61 -7
- package/src/api/socket/sendMessage.js +19 -2
- package/src/api/socket/sendMessageMqtt.js +6 -0
- package/src/api/threads/getThreadHistory.js +68 -38
- package/src/api/threads/getThreadInfo.js +4 -3
- package/src/api/threads/getThreadList.js +34 -31
- package/src/api/threads/getThreadPictures.js +1 -1
- package/src/api/users/getUserInfo.js +5 -2
- package/src/api/users/getUserInfoV2.js +9 -3
- package/src/app/createFcaClient.js +2 -2
- package/src/core/sendReqMqtt.js +2 -1
- package/src/database/helpers.js +12 -0
- package/src/database/models/index.js +8 -9
- package/src/utils/broadcast.js +1 -1
- package/src/utils/clientIdentity.js +50 -3
- package/src/utils/cookies.js +4 -2
- package/src/utils/format/utils.js +10 -0
- package/src/utils/headers.js +26 -12
- package/src/utils/loginParser/autoLogin.js +12 -0
- package/src/utils/loginParser/parseAndCheckLogin.js +7 -0
- package/src/utils/loginParser/textUtils.js +6 -0
- package/src/utils/request/config.js +4 -1
- package/src/utils/request/methods.js +0 -13
- package/src/utils/request/proxy.js +13 -0
- package/src/utils/request/retry.js +0 -10
- package/src/utils/request/sanitize.js +1 -1
- package/src/utils/sendThrottle.js +14 -1
- package/src/utils/textEffects.js +92 -0
- package/src/utils/utils.js +17 -3
- package/src/utils/instanceLock.js +0 -35
- package/src/utils/ipGuard.js +0 -58
|
@@ -1,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,17 @@ 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.
|
|
77
|
+
// [Fixed by xalman] On hosts with an ephemeral filesystem (Railway, Heroku...) the
|
|
78
|
+
// device file is wiped on every deploy, which registers a brand-new E2EE device each
|
|
79
|
+
// time and leaves stale devices behind. Set FCA_NX_E2EE_DEVICE_PATH to a path on a
|
|
80
|
+
// persistent volume (e.g. /data/e2ee_device.json) to keep the same device forever.
|
|
52
81
|
if (!deviceStorePath) {
|
|
53
82
|
deviceStorePath = process.env.FCA_NX_E2EE_DEVICE_PATH
|
|
54
83
|
|| path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
|
|
55
84
|
}
|
|
56
85
|
|
|
86
|
+
// Auto-create parent directory — users don't need to create it manually
|
|
57
87
|
try {
|
|
58
88
|
fs.mkdirSync(path.dirname(deviceStorePath), { recursive: true });
|
|
59
89
|
} catch (_) {}
|
|
@@ -62,6 +92,7 @@ class E2EEBridge {
|
|
|
62
92
|
|
|
63
93
|
const FBClient = loadFBClient();
|
|
64
94
|
|
|
95
|
+
// Re-use the already-loaded session from FCA-NX's cookie jar
|
|
65
96
|
const appState = this.api.getAppState();
|
|
66
97
|
|
|
67
98
|
this.client = new FBClient({
|
|
@@ -69,6 +100,12 @@ class E2EEBridge {
|
|
|
69
100
|
platform: "facebook",
|
|
70
101
|
});
|
|
71
102
|
|
|
103
|
+
// Build the FCA-NX adapter that replaces fb-messenger-e2ee's internal
|
|
104
|
+
// fca-unofficial login. fb-messenger-e2ee calls
|
|
105
|
+
// this.gateway.login(appState)
|
|
106
|
+
// inside connect() which triggers a *second* fca-unofficial login and
|
|
107
|
+
// crashes when the network call returns undefined.
|
|
108
|
+
// By replacing gateway.login BEFORE connect() we prevent that entirely.
|
|
72
109
|
const _ctx = this.ctx;
|
|
73
110
|
const _fcanxApi = this.api;
|
|
74
111
|
const _defaultFuncs = this.defaultFuncs;
|
|
@@ -77,7 +114,11 @@ class E2EEBridge {
|
|
|
77
114
|
fb_dtsg: _ctx.fb_dtsg,
|
|
78
115
|
getCurrentUserID: () => _fcanxApi.getCurrentUserID(),
|
|
79
116
|
getAppState: () => _fcanxApi.getAppState(),
|
|
80
|
-
|
|
117
|
+
// [Fixed by xalman] httpPost always returns a string now - axios
|
|
118
|
+
// auto-parses JSON responses into objects, but the vendored engine
|
|
119
|
+
// (fetchCAT/icdc_fetch/icdc_register) expects raw text and calls
|
|
120
|
+
// .replace()/JSON.parse() on it itself. This was crashing E2EE
|
|
121
|
+
// auto-connect with "resText.replace is not a function".
|
|
81
122
|
httpPost: async function (url, form) {
|
|
82
123
|
var merged = Object.assign({}, form);
|
|
83
124
|
if (!merged.fb_dtsg && _ctx.fb_dtsg) merged.fb_dtsg = _ctx.fb_dtsg;
|
|
@@ -89,18 +130,23 @@ class E2EEBridge {
|
|
|
89
130
|
if (body == null) return body;
|
|
90
131
|
if (typeof body === "string") return body;
|
|
91
132
|
if (Buffer.isBuffer(body)) return body.toString("utf8");
|
|
92
|
-
|
|
133
|
+
// axios auto-parses JSON bodies into an object/array, but the
|
|
134
|
+
// vendored engine always expects a raw string (it strips
|
|
135
|
+
// Facebook's "for (;;);" prefix and JSON.parses it itself).
|
|
136
|
+
// Re-serialize so callers doing resText.replace(...) still work.
|
|
93
137
|
try {
|
|
94
138
|
return JSON.stringify(body);
|
|
95
139
|
} catch {
|
|
96
140
|
return String(body);
|
|
97
141
|
}
|
|
98
142
|
},
|
|
99
|
-
|
|
143
|
+
// listenMqtt — fb-e2ee.cjs calls this to route non-E2EE MQTT events.
|
|
144
|
+
// FCA-NX has its own separate MQTT listener so we provide a no-op stub
|
|
145
|
+
// to prevent a competing second listener from being started.
|
|
100
146
|
listenMqtt: function () { return; },
|
|
101
147
|
stopListenMqtt: function () {},
|
|
102
148
|
setOptions: function () {},
|
|
103
|
-
|
|
149
|
+
// Delegate messaging methods to FCA-NX's real api
|
|
104
150
|
sendMessage: function (msg, threadID, callback, replyToMessage) {
|
|
105
151
|
return _fcanxApi.sendMessage(msg, threadID, callback, replyToMessage);
|
|
106
152
|
},
|
|
@@ -134,6 +180,9 @@ class E2EEBridge {
|
|
|
134
180
|
},
|
|
135
181
|
};
|
|
136
182
|
|
|
183
|
+
// Inject the adapter as a global so that fb-e2ee.cjs's internal
|
|
184
|
+
// require("../../vendor/fca-unofficial") login() intercepts it and
|
|
185
|
+
// skips the real Facebook login, returning FCA-NX's session instead.
|
|
137
186
|
global._fcanxE2EEAdapter = _fcanxAdapter;
|
|
138
187
|
|
|
139
188
|
logger.info("E2EE", "Bootstrapping auth via vendored E2EE engine (FCA-NX session)...");
|
|
@@ -145,6 +194,7 @@ class E2EEBridge {
|
|
|
145
194
|
delete global._fcanxE2EEAdapter;
|
|
146
195
|
}
|
|
147
196
|
|
|
197
|
+
// Also patch controller.api (used for CAT/ICDC calls after connect)
|
|
148
198
|
if (this.client.controller) {
|
|
149
199
|
this.client.controller.api = _fcanxAdapter;
|
|
150
200
|
}
|
|
@@ -154,11 +204,17 @@ class E2EEBridge {
|
|
|
154
204
|
const _e2eeUserId = resolvedUserId || userId;
|
|
155
205
|
await this.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
|
|
156
206
|
|
|
207
|
+
// Auto-reconnect the Noise WebSocket whenever it drops unexpectedly.
|
|
208
|
+
// `this.connected` stays true through reconnect cycles; it's only set
|
|
209
|
+
// false by an explicit api.e2ee.disconnect() call.
|
|
210
|
+
// [Fixed by xalman] Previous version gave up after 2 failed attempts (bot stayed "connected"
|
|
211
|
+
// but deaf forever), could start several reconnects in parallel (duplicate sockets ->
|
|
212
|
+
// duplicate messages), and reacted to non-E2EE "disconnected" events too.
|
|
157
213
|
const _self = this;
|
|
158
214
|
this._reconnecting = false;
|
|
159
215
|
this.client.onEvent("disconnected", function _onE2EEDisconnected(data) {
|
|
160
|
-
if (!_self.connected) return;
|
|
161
|
-
if (data && data.isE2EE === false) return;
|
|
216
|
+
if (!_self.connected) return; // intentional disconnect — skip
|
|
217
|
+
if (data && data.isE2EE === false) return; // MQTT/gateway drop, E2EE socket is fine
|
|
162
218
|
if (_self._reconnecting) return;
|
|
163
219
|
_self._reconnecting = true;
|
|
164
220
|
logger.warn("E2EE", "Noise WebSocket disconnected — reconnecting in 5s...");
|
|
@@ -179,6 +235,7 @@ class E2EEBridge {
|
|
|
179
235
|
setTimeout(tryReconnect, 5000);
|
|
180
236
|
});
|
|
181
237
|
|
|
238
|
+
// Forward incoming E2EE messages to the registered callback.
|
|
182
239
|
this._recentIds = this._recentIds || new Set();
|
|
183
240
|
this.client.onEvent("e2ee_message", (msg) => {
|
|
184
241
|
if (!this._messageCallback) {
|
|
@@ -186,6 +243,8 @@ class E2EEBridge {
|
|
|
186
243
|
return;
|
|
187
244
|
}
|
|
188
245
|
|
|
246
|
+
// [Fixed by xalman] never deliver the same message twice (reconnect replay / overlapping
|
|
247
|
+
// sockets) — a duplicate would make the bot answer a command twice.
|
|
189
248
|
if (msg && msg.id) {
|
|
190
249
|
if (this._recentIds.has(msg.id)) return;
|
|
191
250
|
this._recentIds.add(msg.id);
|
|
@@ -196,6 +255,7 @@ class E2EEBridge {
|
|
|
196
255
|
msg.senderId ||
|
|
197
256
|
(typeof msg.senderJid === "string" ? msg.senderJid.split(".")[0] : "");
|
|
198
257
|
|
|
258
|
+
// Build mentions: vendor surfaces an array [{ id, text }] or object
|
|
199
259
|
var mentions = {};
|
|
200
260
|
if (Array.isArray(msg.mentions)) {
|
|
201
261
|
msg.mentions.forEach(function(m) {
|
|
@@ -221,11 +281,17 @@ class E2EEBridge {
|
|
|
221
281
|
args: (msg.text || "").trim().split(/\s+/).filter(Boolean),
|
|
222
282
|
};
|
|
223
283
|
|
|
284
|
+
// Populate ctx.threadTypes so that sendMessage.js can detect this
|
|
285
|
+
// as a DM and route attachments through OldMessage (not MQTT).
|
|
286
|
+
// E2EE DM messages arrive via the Noise WebSocket — not MQTT — so
|
|
287
|
+
// parseDelta never sees them and ctx.threadTypes stays empty unless
|
|
288
|
+
// we populate it here.
|
|
224
289
|
if (!event.isGroup && msg.threadId) {
|
|
225
290
|
this.ctx.threadTypes = this.ctx.threadTypes || {};
|
|
226
291
|
this.ctx.threadTypes[String(msg.threadId)] = 'dm';
|
|
227
292
|
}
|
|
228
293
|
|
|
294
|
+
// Populate messageReply so reply handlers work the same as in MQTT
|
|
229
295
|
if (isReply) {
|
|
230
296
|
event.messageReply = {
|
|
231
297
|
messageID: msg.replyTo.messageId,
|
|
@@ -242,6 +308,9 @@ class E2EEBridge {
|
|
|
242
308
|
|
|
243
309
|
event.e2eeKind = msg.kind || "text";
|
|
244
310
|
|
|
311
|
+
// [Fixed by xalman] The callback runs synchronously inside the vendor's
|
|
312
|
+
// decrypt pipeline. If the bot handler threw here, the vendor treated it as a
|
|
313
|
+
// decryption failure (retry receipt + dropped message). Isolate it.
|
|
245
314
|
try {
|
|
246
315
|
const r = this._messageCallback(null, event);
|
|
247
316
|
if (r && typeof r.catch === "function") {
|
|
@@ -252,6 +321,8 @@ class E2EEBridge {
|
|
|
252
321
|
}
|
|
253
322
|
});
|
|
254
323
|
|
|
324
|
+
// Surface connection errors so the bot log shows them.
|
|
325
|
+
// Silently ignore DuplicatedMessage errors — these are harmless replays on reconnect.
|
|
255
326
|
this.client.onEvent("error", (err) => {
|
|
256
327
|
if (err && (err.code === 1 || (err.message && err.message.includes("old counter")))) return;
|
|
257
328
|
logger.error("E2EE", "E2EE error: " + (err && err.message ? err.message : String(err)));
|
|
@@ -268,6 +339,9 @@ class E2EEBridge {
|
|
|
268
339
|
}
|
|
269
340
|
}
|
|
270
341
|
|
|
342
|
+
// [Fixed by xalman] `connected` stays true while the Noise socket reconnects, so sends made in
|
|
343
|
+
// that window used to fail (or fall back to MQTT, which cannot deliver to E2EE threads).
|
|
344
|
+
// Wait (up to timeoutMs) for the live socket instead of failing immediately.
|
|
271
345
|
async _waitReady(timeoutMs) {
|
|
272
346
|
const ctl = this.client && this.client.controller;
|
|
273
347
|
const isReady = () => !ctl || ctl.e2eeConnected !== false;
|
|
@@ -283,16 +357,32 @@ class E2EEBridge {
|
|
|
283
357
|
return this.connected;
|
|
284
358
|
}
|
|
285
359
|
|
|
360
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
361
|
+
// Send API (all go through the Noise WebSocket)
|
|
362
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Send a message on an E2EE (or non-E2EE) thread.
|
|
366
|
+
*
|
|
367
|
+
* msg can be:
|
|
368
|
+
* - string → plain text
|
|
369
|
+
* - { body, attachment} → text + one or more readable streams
|
|
370
|
+
*
|
|
371
|
+
* Attachments on E2EE threads are encrypted and sent via the Noise WebSocket.
|
|
372
|
+
* Attachments on non-E2EE threads fall back to api.sendMessage (FCA-NX's own).
|
|
373
|
+
*/
|
|
286
374
|
async sendMessage(threadId, msg, replyToMessageId) {
|
|
287
375
|
this.ensureConnected();
|
|
288
376
|
await this._waitReady();
|
|
289
|
-
await require("../../../utils/sendThrottle").waitTurn();
|
|
377
|
+
await require("../../../utils/sendThrottle").waitTurn(); // human-like pacing
|
|
290
378
|
|
|
291
379
|
const text = typeof msg === "string" ? msg : (msg && msg.body != null ? String(msg.body) : "");
|
|
292
380
|
const attachment = (msg && typeof msg === "object") ? (msg.attachment || null) : null;
|
|
293
381
|
|
|
294
382
|
if (!attachment) {
|
|
295
|
-
|
|
383
|
+
// Call the controller's E2EE senders directly: client.sendMessage() silently falls
|
|
384
|
+
// back to the regular (MQTT) sender when the socket flag is down, and that sender
|
|
385
|
+
// routes back into this bridge -> endless recursion / message never delivered.
|
|
296
386
|
const ctl = this.client.controller;
|
|
297
387
|
const tid = String(threadId);
|
|
298
388
|
if (ctl && typeof ctl.sendE2EEText === "function" && typeof ctl.sendE2EEGroupText === "function") {
|
|
@@ -305,6 +395,17 @@ class E2EEBridge {
|
|
|
305
395
|
return this.client.sendMessage({ threadId, text, replyToMessageId });
|
|
306
396
|
}
|
|
307
397
|
|
|
398
|
+
// Always use the vendor's Noise WebSocket path for attachments.
|
|
399
|
+
// The isE2EEThreadId() check was removed because:
|
|
400
|
+
// 1. It frequently returns false for valid E2EE DM thread IDs (user-id format),
|
|
401
|
+
// which caused fallback to api.sendMessage → MQTT, where Facebook strips
|
|
402
|
+
// attachment_fbids from the E2EE envelope → attachment silently dropped.
|
|
403
|
+
// 2. This method is only called when the thread is KNOWN to be an E2EE DM
|
|
404
|
+
// (sendMessage.js routes here only when isSingleUser=true AND e2ee.isConnected()).
|
|
405
|
+
// 3. client.sendImage/sendVideo/sendAudio handle the JID conversion internally
|
|
406
|
+
// (100055943906136 → 100055943906136.0@msgr) so the threadId format is fine.
|
|
407
|
+
|
|
408
|
+
// E2EE path: read stream(s) → Buffer, detect type, send via vendor
|
|
308
409
|
const path = require("path");
|
|
309
410
|
let mime;
|
|
310
411
|
try { mime = require("mime"); } catch (_) {}
|
|
@@ -361,10 +462,18 @@ class E2EEBridge {
|
|
|
361
462
|
return this.client.editMessage({ threadId, messageId, newText });
|
|
362
463
|
}
|
|
363
464
|
|
|
465
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
466
|
+
// Receive API
|
|
467
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
468
|
+
|
|
364
469
|
onMessage(callback) {
|
|
365
470
|
this._messageCallback = callback;
|
|
366
471
|
}
|
|
367
472
|
|
|
473
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
474
|
+
// Info / lifecycle
|
|
475
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
476
|
+
|
|
368
477
|
getPublicKeys() {
|
|
369
478
|
return {
|
|
370
479
|
info: "Keys managed by vendored E2EE engine (Signal Protocol / Noise handshake).",
|
|
@@ -383,6 +492,10 @@ class E2EEBridge {
|
|
|
383
492
|
|
|
384
493
|
module.exports = { E2EEBridge };
|
|
385
494
|
|
|
495
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
496
|
+
// Private helpers
|
|
497
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
498
|
+
|
|
386
499
|
function _streamToBuffer(stream) {
|
|
387
500
|
return new Promise(function (resolve, reject) {
|
|
388
501
|
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 };
|
|
@@ -38,7 +63,7 @@ function encodeFrame(type, senderID, threadID, header, payload) {
|
|
|
38
63
|
|
|
39
64
|
function decodeFrame(buf) {
|
|
40
65
|
if (Buffer.isBuffer(buf)) {
|
|
41
|
-
|
|
66
|
+
// Use the caller's buffer directly.
|
|
42
67
|
} else if (buf instanceof Uint8Array) {
|
|
43
68
|
buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
44
69
|
} else {
|
|
@@ -84,6 +109,8 @@ function decodeFrame(buf) {
|
|
|
84
109
|
return { version, type, senderID, threadID, header, payload };
|
|
85
110
|
}
|
|
86
111
|
|
|
112
|
+
// ─── Key Bundle ────────────────────────────────────────────────────────────────
|
|
113
|
+
|
|
87
114
|
function buildKeyBundle(identityKey, signedPreKey, oneTimePreKeys) {
|
|
88
115
|
return {
|
|
89
116
|
identityKey: identityKey.publicKeyRaw.toString("base64"),
|
|
@@ -103,6 +130,8 @@ function signKey(identityPrivateKey, keyToSign) {
|
|
|
103
130
|
return hmacSha256(identityPrivateKey, keyToSign.publicKeyRaw);
|
|
104
131
|
}
|
|
105
132
|
|
|
133
|
+
// ─── Facebook Graph API: key registration/fetching ───────────────────────────
|
|
134
|
+
|
|
106
135
|
async function uploadKeyBundle(defaultFuncs, ctx, keyBundle) {
|
|
107
136
|
try {
|
|
108
137
|
const res = await defaultFuncs.post(
|
|
@@ -147,6 +176,8 @@ async function fetchRecipientKeyBundle(defaultFuncs, ctx, recipientUserID) {
|
|
|
147
176
|
}
|
|
148
177
|
}
|
|
149
178
|
|
|
179
|
+
// ─── Message payload builders ─────────────────────────────────────────────────
|
|
180
|
+
|
|
150
181
|
function buildInitPayload(senderEphemeralPub, senderOneTimeKeyId, recipientOneTimeKeyId) {
|
|
151
182
|
return JSON.stringify({
|
|
152
183
|
type: "x3dh_init",
|
|
@@ -1,5 +1,11 @@
|
|
|
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
|
+
|
|
3
9
|
const { generateKeyPair, dh, hkdf, hkdfExtract, hkdfExpand, encrypt, decrypt, hmacSha256 } = require("./crypto");
|
|
4
10
|
|
|
5
11
|
const MAX_SKIP = 1000;
|
|
@@ -29,17 +35,20 @@ function deriveMessageKeys(mk) {
|
|
|
29
35
|
|
|
30
36
|
class DoubleRatchetSession {
|
|
31
37
|
constructor() {
|
|
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();
|
|
38
|
+
this.DHs = null; // Our DH ratchet key pair
|
|
39
|
+
this.DHr = null; // Their DH ratchet public key (raw 32 bytes)
|
|
40
|
+
this.RK = null; // Root key (32 bytes)
|
|
41
|
+
this.CKs = null; // Sending chain key
|
|
42
|
+
this.CKr = null; // Receiving chain key
|
|
43
|
+
this.Ns = 0; // Send message number
|
|
44
|
+
this.Nr = 0; // Receive message number
|
|
45
|
+
this.PN = 0; // Previous sending chain length
|
|
46
|
+
this.MKSKIPPED = new Map(); // Skipped message keys
|
|
41
47
|
}
|
|
42
48
|
|
|
49
|
+
/**
|
|
50
|
+
* Initialize as sender (Alice) after X3DH
|
|
51
|
+
*/
|
|
43
52
|
initAsSender(sk, recipientRatchetPublicKey) {
|
|
44
53
|
this.DHs = generateKeyPair();
|
|
45
54
|
this.DHr = Buffer.from(recipientRatchetPublicKey);
|
|
@@ -51,6 +60,9 @@ class DoubleRatchetSession {
|
|
|
51
60
|
this.Ns = 0; this.Nr = 0; this.PN = 0;
|
|
52
61
|
}
|
|
53
62
|
|
|
63
|
+
/**
|
|
64
|
+
* Initialize as receiver (Bob) after X3DH
|
|
65
|
+
*/
|
|
54
66
|
initAsReceiver(sk, ourRatchetKeyPair) {
|
|
55
67
|
this.DHs = ourRatchetKeyPair;
|
|
56
68
|
this.DHr = null;
|
|
@@ -60,6 +72,10 @@ class DoubleRatchetSession {
|
|
|
60
72
|
this.Ns = 0; this.Nr = 0; this.PN = 0;
|
|
61
73
|
}
|
|
62
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Encrypt a message
|
|
77
|
+
* Returns { header, ciphertext }
|
|
78
|
+
*/
|
|
63
79
|
encrypt(plaintext, aad) {
|
|
64
80
|
const { ck, mk } = kdfCK(this.CKs);
|
|
65
81
|
this.CKs = ck;
|
|
@@ -71,6 +87,13 @@ class DoubleRatchetSession {
|
|
|
71
87
|
return { header, ciphertext };
|
|
72
88
|
}
|
|
73
89
|
|
|
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
|
+
*/
|
|
74
97
|
decrypt(header, ciphertext, aad) {
|
|
75
98
|
const snapshot = {
|
|
76
99
|
DHs: this.DHs,
|
|
@@ -87,7 +110,8 @@ class DoubleRatchetSession {
|
|
|
87
110
|
try {
|
|
88
111
|
return this._decryptAndAdvance(header, ciphertext, aad);
|
|
89
112
|
} catch (error) {
|
|
90
|
-
|
|
113
|
+
// Authentication failure must not consume a skipped key or advance
|
|
114
|
+
// the ratchet. A later valid copy of the message can then succeed.
|
|
91
115
|
Object.assign(this, snapshot);
|
|
92
116
|
throw error;
|
|
93
117
|
}
|
|
@@ -97,6 +121,7 @@ class DoubleRatchetSession {
|
|
|
97
121
|
const { dh_pub, pn, n } = this._parseHeader(header);
|
|
98
122
|
const aadFull = aad ? Buffer.concat([aad, header]) : header;
|
|
99
123
|
|
|
124
|
+
// Check skipped keys first
|
|
100
125
|
const skipKey = `${dh_pub.toString("hex")}:${n}`;
|
|
101
126
|
if (this.MKSKIPPED.has(skipKey)) {
|
|
102
127
|
const mk = this.MKSKIPPED.get(skipKey);
|
|
@@ -105,6 +130,7 @@ class DoubleRatchetSession {
|
|
|
105
130
|
return decrypt(keys.encKey, ciphertext, aadFull);
|
|
106
131
|
}
|
|
107
132
|
|
|
133
|
+
// Check if we need to ratchet
|
|
108
134
|
const needsRatchet = !this.DHr || !dh_pub.equals(this.DHr);
|
|
109
135
|
if (needsRatchet) {
|
|
110
136
|
this._skipMessageKeys(pn);
|
|
@@ -142,11 +168,13 @@ class DoubleRatchetSession {
|
|
|
142
168
|
this.Nr = 0;
|
|
143
169
|
this.DHr = remoteDhPub;
|
|
144
170
|
|
|
171
|
+
// Receive ratchet
|
|
145
172
|
const dhOut1 = dh(this.DHs.privateKey, this.DHr);
|
|
146
173
|
const { rk: rk1, ck: ckr } = kdfRK(this.RK, dhOut1);
|
|
147
174
|
this.RK = rk1;
|
|
148
175
|
this.CKr = ckr;
|
|
149
176
|
|
|
177
|
+
// Send ratchet
|
|
150
178
|
this.DHs = generateKeyPair();
|
|
151
179
|
const dhOut2 = dh(this.DHs.privateKey, this.DHr);
|
|
152
180
|
const { rk: rk2, ck: cks } = kdfRK(this.RK, dhOut2);
|
|
@@ -173,6 +201,9 @@ class DoubleRatchetSession {
|
|
|
173
201
|
};
|
|
174
202
|
}
|
|
175
203
|
|
|
204
|
+
/**
|
|
205
|
+
* Serialize session state for persistence
|
|
206
|
+
*/
|
|
176
207
|
serialize() {
|
|
177
208
|
return JSON.stringify({
|
|
178
209
|
DHs_priv: this.DHs ? this.DHs.privateKey.toString("base64") : null,
|
|
@@ -188,6 +219,9 @@ class DoubleRatchetSession {
|
|
|
188
219
|
});
|
|
189
220
|
}
|
|
190
221
|
|
|
222
|
+
/**
|
|
223
|
+
* Restore session state from serialized string
|
|
224
|
+
*/
|
|
191
225
|
static deserialize(json) {
|
|
192
226
|
const d = JSON.parse(json);
|
|
193
227
|
const session = new DoubleRatchetSession();
|
|
@@ -1,5 +1,15 @@
|
|
|
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
|
+
|
|
3
13
|
const fs = require("fs");
|
|
4
14
|
const path = require("path");
|
|
5
15
|
const crypto = require("crypto");
|
|
@@ -24,7 +34,7 @@ class E2EEStore {
|
|
|
24
34
|
identityKey: null,
|
|
25
35
|
signedPreKey: null,
|
|
26
36
|
oneTimePreKeys: [],
|
|
27
|
-
sessions: {}
|
|
37
|
+
sessions: {} // threadID -> serialized DoubleRatchetSession
|
|
28
38
|
};
|
|
29
39
|
this._loaded = false;
|
|
30
40
|
}
|
|
@@ -139,6 +149,8 @@ class E2EEStore {
|
|
|
139
149
|
this._applyPayload(JSON.parse(decrypted));
|
|
140
150
|
this._loaded = true;
|
|
141
151
|
|
|
152
|
+
// Upgrade legacy files immediately so future writes do not keep the
|
|
153
|
+
// old colocated-key format.
|
|
142
154
|
if (isLegacy) this.save();
|
|
143
155
|
return true;
|
|
144
156
|
} catch (error) {
|