fca-nx 6.8.5 → 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.
Files changed (74) hide show
  1. package/func/checkUpdate.js +1 -1
  2. package/func/logAdapter.js +0 -2
  3. package/index.js +0 -3
  4. package/module/config.js +3 -5
  5. package/module/login.js +10 -38
  6. package/module/loginHelper.js +121 -206
  7. package/module/options.js +1 -7
  8. package/package.json +3 -3
  9. package/src/api/action/addfriend.js +3 -9
  10. package/src/api/action/changeAvatar.js +0 -1
  11. package/src/api/action/changeCover.js +1 -3
  12. package/src/api/action/enableAutoSaveAppState.js +5 -18
  13. package/src/api/action/refreshFb_dtsg.js +2 -2
  14. package/src/api/http/httpGet.js +2 -6
  15. package/src/api/http/httpPost.js +2 -7
  16. package/src/api/messaging/createNewGroup.js +1 -1
  17. package/src/api/messaging/deleteMessage.js +1 -1
  18. package/src/api/messaging/forwardMessage.js +1 -9
  19. package/src/api/messaging/getEmojiUrl.js +1 -5
  20. package/src/api/messaging/getMessage.js +2 -4
  21. package/src/api/messaging/getThemePictures.js +0 -7
  22. package/src/api/messaging/markAsRead.js +0 -1
  23. package/src/api/messaging/muteThread.js +1 -1
  24. package/src/api/messaging/pinMessage.js +1 -10
  25. package/src/api/messaging/scheduler.js +4 -71
  26. package/src/api/messaging/sendBroadcast.js +0 -15
  27. package/src/api/messaging/sendMessage.js +1 -10
  28. package/src/api/messaging/sendTypingIndicator.js +2 -2
  29. package/src/api/messaging/sessionGuard.js +9 -45
  30. package/src/api/messaging/setMessageReaction.js +1 -2
  31. package/src/api/messaging/threadColors.js +12 -45
  32. package/src/api/messaging/uploadAttachment.js +3 -37
  33. package/src/api/socket/core/connectMqtt.js +17 -60
  34. package/src/api/socket/core/emitAuth.js +2 -14
  35. package/src/api/socket/core/getSeqID.js +23 -29
  36. package/src/api/socket/core/getTaskResponseData.js +1 -3
  37. package/src/api/socket/core/parseDelta.js +1 -1
  38. package/src/api/socket/detail/buildStream.js +1 -4
  39. package/src/api/socket/detail/constants.js +1 -4
  40. package/src/api/socket/e2ee/crypto.js +2 -40
  41. package/src/api/socket/e2ee/index.js +10 -123
  42. package/src/api/socket/e2ee/protocol.js +1 -32
  43. package/src/api/socket/e2ee/ratchet.js +10 -44
  44. package/src/api/socket/e2ee/store.js +1 -13
  45. package/src/api/socket/listenE2EE.js +1 -25
  46. package/src/api/socket/listenMqtt.js +13 -29
  47. package/src/api/socket/middleware/index.js +7 -61
  48. package/src/api/socket/sendMessage.js +2 -19
  49. package/src/api/threads/getThreadHistory.js +38 -68
  50. package/src/api/threads/getThreadInfo.js +3 -4
  51. package/src/api/threads/getThreadList.js +31 -34
  52. package/src/api/threads/getThreadPictures.js +1 -1
  53. package/src/api/users/getUserInfo.js +2 -5
  54. package/src/api/users/getUserInfoV2.js +3 -9
  55. package/src/core/sendReqMqtt.js +1 -2
  56. package/src/database/helpers.js +0 -12
  57. package/src/database/models/index.js +9 -8
  58. package/src/utils/broadcast.js +1 -1
  59. package/src/utils/clientIdentity.js +3 -50
  60. package/src/utils/cookies.js +2 -4
  61. package/src/utils/format/utils.js +0 -10
  62. package/src/utils/headers.js +12 -26
  63. package/src/utils/instanceLock.js +3 -9
  64. package/src/utils/ipGuard.js +1 -15
  65. package/src/utils/loginParser/autoLogin.js +0 -12
  66. package/src/utils/loginParser/parseAndCheckLogin.js +0 -7
  67. package/src/utils/loginParser/textUtils.js +0 -6
  68. package/src/utils/request/config.js +1 -4
  69. package/src/utils/request/methods.js +1 -4
  70. package/src/utils/request/proxy.js +0 -13
  71. package/src/utils/request/retry.js +0 -1
  72. package/src/utils/request/sanitize.js +1 -1
  73. package/src/utils/sendThrottle.js +1 -14
  74. package/src/utils/utils.js +3 -17
@@ -1,9 +1,5 @@
1
1
  "use strict";
2
- /**
3
- * Fetches MQTT sync sequence ID from GraphQL and starts listenMqtt.
4
- * Handles retries and auto re-login via fca-config.json when session expires.
5
- * Fixed by Xalman: Added fb_dtsg/jazoest payload & 1357032 Object error fallback.
6
- */
2
+
7
3
  const { getType } = require("../../../utils/format");
8
4
  const { parseAndCheckLogin } = require("../../../utils/client");
9
5
  const path = require("path");
@@ -20,7 +16,6 @@ function getConfig() {
20
16
  return {};
21
17
  }
22
18
 
23
- // Parse cookie string to array format
24
19
  function parseCookieString(cookieStr) {
25
20
  if (!cookieStr || typeof cookieStr !== "string") return [];
26
21
  const cookies = [];
@@ -43,7 +38,6 @@ function parseCookieString(cookieStr) {
43
38
  return cookies;
44
39
  }
45
40
 
46
- // Try to auto-login using API and refresh web session
47
41
  async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
48
42
  const email = config.credentials?.email || config.email;
49
43
  const password = config.credentials?.password || config.password;
@@ -53,6 +47,13 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
53
47
  return null;
54
48
  }
55
49
 
50
+ let allowed = false;
51
+ try { allowed = require("../../../../module/loginHelper").credentialLoginAllowed(); } catch (_) {}
52
+ if (!allowed) {
53
+ logger("getSeqID: credential re-login disabled (6.8.7) - keeping current cookie, no password login", "warn");
54
+ return null;
55
+ }
56
+
56
57
  logger("getSeqID: attempting auto re-login via API...", "warn");
57
58
 
58
59
  try {
@@ -69,7 +70,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
69
70
 
70
71
  if (typeof result.cookies === "string") {
71
72
  cookiePairs = normalizeCookieHeaderString(result.cookies);
72
- }
73
+ }
73
74
  else if (Array.isArray(result.cookies)) {
74
75
  cookiePairs = result.cookies.map(c => {
75
76
  if (typeof c === "string") return c;
@@ -77,7 +78,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
77
78
  return null;
78
79
  }).filter(Boolean);
79
80
  }
80
-
81
+
81
82
  if (cookiePairs.length === 0 && result.cookie) {
82
83
  if (typeof result.cookie === "string") {
83
84
  cookiePairs = normalizeCookieHeaderString(result.cookie);
@@ -128,12 +129,12 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
128
129
  try {
129
130
  const urlToUse = attempt === 0 ? urlsToTry[0] : urlsToTry[attempt % urlsToTry.length];
130
131
  logger(`getSeqID: Refreshing ${urlToUse} (attempt ${attempt + 1}/3)...`, "info");
131
-
132
+
132
133
  webResponse = await get(urlToUse, ctx.jar, null, ctx.globalOptions, ctx);
133
134
  if (webResponse && webResponse.data) {
134
135
  await saveWebCookies(ctx.jar)(webResponse);
135
136
  htmlContent = typeof webResponse.data === "string" ? webResponse.data : String(webResponse.data || "");
136
-
137
+
137
138
  const htmlUserID = htmlUID(htmlContent);
138
139
  if (isValidUID(htmlUserID)) {
139
140
  logger(`getSeqID: Found valid USER_ID in HTML from ${urlToUse}: ${htmlUserID}`, "info");
@@ -154,12 +155,12 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
154
155
  if (webResponse && webResponse.data) {
155
156
  const updatedCookies = await ctx.jar.getCookies("https://www.facebook.com");
156
157
  logger(`getSeqID: refreshed session, now have ${updatedCookies.length} web cookies`, "info");
157
-
158
+
158
159
  const htmlUserID = htmlUID(htmlContent);
159
160
  if (!isValidUID(htmlUserID)) {
160
161
  logger("getSeqID: WARNING - HTML does not show valid USER_ID after refresh. Session may not be fully established.", "warn");
161
162
  }
162
-
163
+
163
164
  if (ctx) {
164
165
  ctx.loggedIn = true;
165
166
  if (isValidUID(htmlUserID)) {
@@ -194,10 +195,9 @@ module.exports = function createGetSeqID(deps) {
194
195
 
195
196
  return function getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount = 0) {
196
197
  const MAX_RETRIES = 5;
197
- const RETRY_DELAY = 5000; // [Hardened5] slower retries reduce auth race / checkpoint pressure
198
+ const RETRY_DELAY = 5000;
198
199
  ctx.t_mqttCalled = false;
199
200
 
200
- // Ensure essential tokens are injected into GraphQL Batch Payload
201
201
  if (!form) {
202
202
  form = {
203
203
  av: ctx.globalOptions.pageID || ctx.userID,
@@ -225,11 +225,10 @@ module.exports = function createGetSeqID(deps) {
225
225
  .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
226
226
  .then(parseAndCheckLogin(ctx, defaultFuncs))
227
227
  .then(async resData => {
228
- // Safe check for non-array responses (such as Error Objects from FB)
228
+
229
229
  if (getType(resData) !== "Array") {
230
230
  logger(`getSeqID: Response is not Array, received: ${getType(resData)}`, "warn");
231
231
 
232
- // Handle Facebook GraphQL 1357032 or transient error responses without triggering re-login
233
232
  if (resData && typeof resData === "object") {
234
233
  const errCode = resData.error || resData.errorCode;
235
234
  const errorMsg = resData.errorSummary || resData.message || "";
@@ -241,12 +240,11 @@ module.exports = function createGetSeqID(deps) {
241
240
  return;
242
241
  }
243
242
 
244
- if (/Not logged in|login|blocked|401|403|checkpoint/i.test(errorMsg)) {
243
+ if (/Not logged in|login required|blocked the login|checkpoint|\b(?:401|403)\b/i.test(errorMsg)) {
245
244
  throw { error: "Not logged in", originalResponse: resData };
246
245
  }
247
246
  }
248
247
 
249
- // Fallback if it's an unrecognized object
250
248
  ctx.lastSeqId = ctx.lastSeqId || "0";
251
249
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
252
250
  return;
@@ -270,7 +268,7 @@ module.exports = function createGetSeqID(deps) {
270
268
  const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
271
269
  const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
272
270
 
273
- const isAuthError = /Not logged in|no sync_sequence_id found|blocked the login|401|403/i.test(msg);
271
+ const isAuthError = /Not logged in|no sync_sequence_id found|blocked the login|\b(?:401|403)\b/i.test(msg);
274
272
  const netCode = err?.code || err?.originalError?.code || "";
275
273
  const isNetworkError = !isAuthError && (
276
274
  /timeout|ECONNRESET|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|network error|socket hang up/i.test(msg) ||
@@ -285,8 +283,7 @@ module.exports = function createGetSeqID(deps) {
285
283
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
286
284
  }
287
285
  logger(`getSeqID: network error persisted after ${MAX_RETRIES} retries, giving up for now: ${msg}`, "error");
288
- // [Fixed by xalman] throw instead of silently returning undefined -
289
- // a bare return here made the caller think this call SUCCEEDED.
286
+
290
287
  const giveUpErr = new Error(`getSeqID network error persisted after ${MAX_RETRIES} retries: ${msg}`);
291
288
  giveUpErr.error = msg;
292
289
  giveUpErr.isNetworkError = true;
@@ -301,14 +298,12 @@ module.exports = function createGetSeqID(deps) {
301
298
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
302
299
  }
303
300
 
304
- // A new email/password login here kills the cookie the bot is
305
- // already using and Facebook treats it as a second device.
306
301
  if (/blocked the login|login_blocked|checkpoint_282|checkpoint_956/i.test(msg)) {
307
302
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
308
303
  }
309
304
 
310
305
  logger(`getSeqID: auth still failing - keeping this cookie, no new login: ${msg}`, "error");
311
- // Soft recovery: do NOT set ctx._ending. Notify listener, then retry later.
306
+
312
307
  try {
313
308
  if (typeof globalCallback === "function") {
314
309
  globalCallback({
@@ -318,8 +313,8 @@ module.exports = function createGetSeqID(deps) {
318
313
  }, null);
319
314
  }
320
315
  } catch (_) {}
321
- // Re-attempt getSeqID after long cooldown without marking account inactive
322
- const softDelay = Math.min(15 * 60 * 1000, 90000 * (retryCount + 1)); // [Hardened5] longer soft cooldown
316
+
317
+ const softDelay = Math.min(15 * 60 * 1000, 90000 * (retryCount + 1));
323
318
  setTimeout(() => {
324
319
  if (ctx._ending) return;
325
320
  logger("getSeqID: soft recovery timer fired - retrying getSeqID", "warn");
@@ -332,7 +327,6 @@ module.exports = function createGetSeqID(deps) {
332
327
  return;
333
328
  }
334
329
 
335
- // Non-auth, non-network: still soft-recover instead of permanent logout
336
330
  logger(`getSeqID error (soft recover, no logout): ${msg}`, "error");
337
331
  try {
338
332
  if (typeof globalCallback === "function") {
@@ -342,7 +336,7 @@ module.exports = function createGetSeqID(deps) {
342
336
  setTimeout(() => {
343
337
  if (ctx._ending) return;
344
338
  try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
345
- }, 120000); // [Hardened5] 2min soft recover for non-auth errors
339
+ }, 120000);
346
340
  });
347
341
  };
348
342
  };
@@ -1,7 +1,5 @@
1
1
  "use strict";
2
- /**
3
- * Maps /ls_resp task types to a normalized response shape for send_message_mqtt, set_message_reaction, edit_message.
4
- */
2
+
5
3
  module.exports = function getTaskResponseData(taskType, payload) {
6
4
  try {
7
5
  switch (taskType) {
@@ -93,7 +93,7 @@ module.exports = function createParseDelta(deps) {
93
93
  const mercury = JSON.parse(att.mercuryJSON);
94
94
  Object.assign(att, mercury);
95
95
  } catch (ex) {
96
- // Ignore parsing errors
96
+
97
97
  }
98
98
  return att;
99
99
  }).map(att => {
@@ -1,8 +1,5 @@
1
1
  "use strict";
2
- /**
3
- * Builds a duplex stream over WebSocket for MQTT: proxy for writes, PassThrough for reads.
4
- * Handles ping/pong, liveness timeout, and clean shutdown.
5
- */
2
+
6
3
  const { Writable, PassThrough } = require("stream");
7
4
  const Duplexify = require("duplexify");
8
5
 
@@ -1,8 +1,5 @@
1
1
  "use strict";
2
- /**
3
- * MQTT topic list for Facebook Messenger real-time connection.
4
- * Subscriptions are created in connectMqtt on "connect".
5
- */
2
+
6
3
  module.exports = {
7
4
  topics: [
8
5
  "/ls_req",
@@ -1,17 +1,7 @@
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
-
9
3
  const crypto = require("crypto");
10
4
 
11
- // ─────────────────────────────────────────────────────────
12
- // X25519 Key Management
13
- // ─────────────────────────────────────────────────────────
14
-
15
5
  function generateKeyPair() {
16
6
  const { privateKey, publicKey } = crypto.generateKeyPairSync("x25519", {
17
7
  privateKeyEncoding: { type: "pkcs8", format: "der" },
@@ -25,13 +15,13 @@ function generateKeyPair() {
25
15
  }
26
16
 
27
17
  function exportRawPublicKey(spkiDer) {
28
- // X25519 SPKI DER: 12 bytes header + 32 bytes key
18
+
29
19
  return Buffer.from(spkiDer).slice(-32);
30
20
  }
31
21
 
32
22
  function importPublicKey(raw32bytes) {
33
23
  if (raw32bytes.length !== 32) throw new Error("X25519 public key must be 32 bytes");
34
- // Build minimal SPKI wrapper for X25519
24
+
35
25
  const header = Buffer.from("302a300506032b656e032100", "hex");
36
26
  return Buffer.concat([header, raw32bytes]);
37
27
  }
@@ -43,10 +33,6 @@ function dh(privateKeyPkcs8Der, peerPublicRaw32) {
43
33
  return crypto.diffieHellman({ privateKey: privKey, publicKey: pubKey });
44
34
  }
45
35
 
46
- // ─────────────────────────────────────────────────────────
47
- // HKDF-SHA256
48
- // ─────────────────────────────────────────────────────────
49
-
50
36
  function hkdf(ikm, length, salt, info) {
51
37
  if (!salt) salt = Buffer.alloc(32, 0);
52
38
  if (!info) info = Buffer.alloc(0);
@@ -74,10 +60,6 @@ function hkdfExpand(prk, info, length) {
74
60
  return Buffer.concat(results).slice(0, length);
75
61
  }
76
62
 
77
- // ─────────────────────────────────────────────────────────
78
- // AES-256-GCM
79
- // ─────────────────────────────────────────────────────────
80
-
81
63
  function encrypt(key32, plaintext, aad) {
82
64
  if (key32.length !== 32) throw new Error("AES-GCM key must be 32 bytes");
83
65
  const iv = crypto.randomBytes(12);
@@ -100,10 +82,6 @@ function decrypt(key32, ciphertext, aad) {
100
82
  return Buffer.concat([decipher.update(data), decipher.final()]);
101
83
  }
102
84
 
103
- // ─────────────────────────────────────────────────────────
104
- // HMAC-SHA256
105
- // ─────────────────────────────────────────────────────────
106
-
107
85
  function hmacSha256(key, data) {
108
86
  return crypto.createHmac("sha256", key).update(data).digest();
109
87
  }
@@ -113,19 +91,6 @@ function constantTimeEqual(a, b) {
113
91
  return crypto.timingSafeEqual(a, b);
114
92
  }
115
93
 
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
- */
129
94
  function x3dhSend(senderIdKey, ephemeralKey, recipientIdPub, recipientSpkPub, recipientOpkPub) {
130
95
  const dh1 = dh(senderIdKey.privateKey, recipientSpkPub);
131
96
  const dh2 = dh(ephemeralKey.privateKey, recipientIdPub);
@@ -139,9 +104,6 @@ function x3dhSend(senderIdKey, ephemeralKey, recipientIdPub, recipientSpkPub, re
139
104
  return hkdf(Buffer.concat([F, ikm]), 32, salt, Buffer.from("WhisperText", "utf8"));
140
105
  }
141
106
 
142
- /**
143
- * Receiver side of X3DH.
144
- */
145
107
  function x3dhReceive(recipientIdKey, recipientSpkKey, recipientOpkKey, senderIdPub, senderEphemeralPub) {
146
108
  const dh1 = dh(recipientSpkKey.privateKey, senderIdPub);
147
109
  const dh2 = dh(recipientIdKey.privateKey, senderEphemeralPub);
@@ -1,29 +1,12 @@
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
-
19
3
  const path = require("path");
20
4
  const logger = require("../../../utils/logger");
21
5
  const requestHttp = require("../../../utils/request");
22
6
 
23
7
  function loadFBClient() {
24
8
  try {
25
- // [Fixed by xalman] see comment above loadFBClient - Node < 22 has no
26
- // global WebSocket, but fb-e2ee.cjs unconditionally does `new WebSocket(...)`.
9
+
27
10
  if (typeof global.WebSocket === "undefined") {
28
11
  global.WebSocket = require("ws");
29
12
  }
@@ -48,15 +31,8 @@ class E2EEBridge {
48
31
  this._messageCallback = null;
49
32
  }
50
33
 
51
- // ─────────────────────────────────────────────────────────────────────────
52
- // Setup
53
- // ─────────────────────────────────────────────────────────────────────────
54
-
55
34
  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.
35
+
60
36
  if (this._connectPromise) return this._connectPromise;
61
37
  if (this.connected) return Promise.resolve({ userId: this.ctx.userID });
62
38
 
@@ -73,17 +49,11 @@ class E2EEBridge {
73
49
 
74
50
  userId = userId || this.ctx.userID;
75
51
 
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.
81
52
  if (!deviceStorePath) {
82
53
  deviceStorePath = process.env.FCA_NX_E2EE_DEVICE_PATH
83
54
  || path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
84
55
  }
85
56
 
86
- // Auto-create parent directory — users don't need to create it manually
87
57
  try {
88
58
  fs.mkdirSync(path.dirname(deviceStorePath), { recursive: true });
89
59
  } catch (_) {}
@@ -92,7 +62,6 @@ class E2EEBridge {
92
62
 
93
63
  const FBClient = loadFBClient();
94
64
 
95
- // Re-use the already-loaded session from FCA-NX's cookie jar
96
65
  const appState = this.api.getAppState();
97
66
 
98
67
  this.client = new FBClient({
@@ -100,12 +69,6 @@ class E2EEBridge {
100
69
  platform: "facebook",
101
70
  });
102
71
 
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.
109
72
  const _ctx = this.ctx;
110
73
  const _fcanxApi = this.api;
111
74
  const _defaultFuncs = this.defaultFuncs;
@@ -114,11 +77,7 @@ class E2EEBridge {
114
77
  fb_dtsg: _ctx.fb_dtsg,
115
78
  getCurrentUserID: () => _fcanxApi.getCurrentUserID(),
116
79
  getAppState: () => _fcanxApi.getAppState(),
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".
80
+
122
81
  httpPost: async function (url, form) {
123
82
  var merged = Object.assign({}, form);
124
83
  if (!merged.fb_dtsg && _ctx.fb_dtsg) merged.fb_dtsg = _ctx.fb_dtsg;
@@ -130,23 +89,18 @@ class E2EEBridge {
130
89
  if (body == null) return body;
131
90
  if (typeof body === "string") return body;
132
91
  if (Buffer.isBuffer(body)) return body.toString("utf8");
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.
92
+
137
93
  try {
138
94
  return JSON.stringify(body);
139
95
  } catch {
140
96
  return String(body);
141
97
  }
142
98
  },
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.
99
+
146
100
  listenMqtt: function () { return; },
147
101
  stopListenMqtt: function () {},
148
102
  setOptions: function () {},
149
- // Delegate messaging methods to FCA-NX's real api
103
+
150
104
  sendMessage: function (msg, threadID, callback, replyToMessage) {
151
105
  return _fcanxApi.sendMessage(msg, threadID, callback, replyToMessage);
152
106
  },
@@ -180,9 +134,6 @@ class E2EEBridge {
180
134
  },
181
135
  };
182
136
 
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.
186
137
  global._fcanxE2EEAdapter = _fcanxAdapter;
187
138
 
188
139
  logger.info("E2EE", "Bootstrapping auth via vendored E2EE engine (FCA-NX session)...");
@@ -194,7 +145,6 @@ class E2EEBridge {
194
145
  delete global._fcanxE2EEAdapter;
195
146
  }
196
147
 
197
- // Also patch controller.api (used for CAT/ICDC calls after connect)
198
148
  if (this.client.controller) {
199
149
  this.client.controller.api = _fcanxAdapter;
200
150
  }
@@ -204,17 +154,11 @@ class E2EEBridge {
204
154
  const _e2eeUserId = resolvedUserId || userId;
205
155
  await this.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
206
156
 
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.
213
157
  const _self = this;
214
158
  this._reconnecting = false;
215
159
  this.client.onEvent("disconnected", function _onE2EEDisconnected(data) {
216
- if (!_self.connected) return; // intentional disconnect — skip
217
- if (data && data.isE2EE === false) return; // MQTT/gateway drop, E2EE socket is fine
160
+ if (!_self.connected) return;
161
+ if (data && data.isE2EE === false) return;
218
162
  if (_self._reconnecting) return;
219
163
  _self._reconnecting = true;
220
164
  logger.warn("E2EE", "Noise WebSocket disconnected — reconnecting in 5s...");
@@ -235,7 +179,6 @@ class E2EEBridge {
235
179
  setTimeout(tryReconnect, 5000);
236
180
  });
237
181
 
238
- // Forward incoming E2EE messages to the registered callback.
239
182
  this._recentIds = this._recentIds || new Set();
240
183
  this.client.onEvent("e2ee_message", (msg) => {
241
184
  if (!this._messageCallback) {
@@ -243,8 +186,6 @@ class E2EEBridge {
243
186
  return;
244
187
  }
245
188
 
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.
248
189
  if (msg && msg.id) {
249
190
  if (this._recentIds.has(msg.id)) return;
250
191
  this._recentIds.add(msg.id);
@@ -255,7 +196,6 @@ class E2EEBridge {
255
196
  msg.senderId ||
256
197
  (typeof msg.senderJid === "string" ? msg.senderJid.split(".")[0] : "");
257
198
 
258
- // Build mentions: vendor surfaces an array [{ id, text }] or object
259
199
  var mentions = {};
260
200
  if (Array.isArray(msg.mentions)) {
261
201
  msg.mentions.forEach(function(m) {
@@ -281,17 +221,11 @@ class E2EEBridge {
281
221
  args: (msg.text || "").trim().split(/\s+/).filter(Boolean),
282
222
  };
283
223
 
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.
289
224
  if (!event.isGroup && msg.threadId) {
290
225
  this.ctx.threadTypes = this.ctx.threadTypes || {};
291
226
  this.ctx.threadTypes[String(msg.threadId)] = 'dm';
292
227
  }
293
228
 
294
- // Populate messageReply so reply handlers work the same as in MQTT
295
229
  if (isReply) {
296
230
  event.messageReply = {
297
231
  messageID: msg.replyTo.messageId,
@@ -308,9 +242,6 @@ class E2EEBridge {
308
242
 
309
243
  event.e2eeKind = msg.kind || "text";
310
244
 
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.
314
245
  try {
315
246
  const r = this._messageCallback(null, event);
316
247
  if (r && typeof r.catch === "function") {
@@ -321,8 +252,6 @@ class E2EEBridge {
321
252
  }
322
253
  });
323
254
 
324
- // Surface connection errors so the bot log shows them.
325
- // Silently ignore DuplicatedMessage errors — these are harmless replays on reconnect.
326
255
  this.client.onEvent("error", (err) => {
327
256
  if (err && (err.code === 1 || (err.message && err.message.includes("old counter")))) return;
328
257
  logger.error("E2EE", "E2EE error: " + (err && err.message ? err.message : String(err)));
@@ -339,9 +268,6 @@ class E2EEBridge {
339
268
  }
340
269
  }
341
270
 
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.
345
271
  async _waitReady(timeoutMs) {
346
272
  const ctl = this.client && this.client.controller;
347
273
  const isReady = () => !ctl || ctl.e2eeConnected !== false;
@@ -357,32 +283,16 @@ class E2EEBridge {
357
283
  return this.connected;
358
284
  }
359
285
 
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
- */
374
286
  async sendMessage(threadId, msg, replyToMessageId) {
375
287
  this.ensureConnected();
376
288
  await this._waitReady();
377
- await require("../../../utils/sendThrottle").waitTurn(); // human-like pacing
289
+ await require("../../../utils/sendThrottle").waitTurn();
378
290
 
379
291
  const text = typeof msg === "string" ? msg : (msg && msg.body != null ? String(msg.body) : "");
380
292
  const attachment = (msg && typeof msg === "object") ? (msg.attachment || null) : null;
381
293
 
382
294
  if (!attachment) {
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.
295
+
386
296
  const ctl = this.client.controller;
387
297
  const tid = String(threadId);
388
298
  if (ctl && typeof ctl.sendE2EEText === "function" && typeof ctl.sendE2EEGroupText === "function") {
@@ -395,17 +305,6 @@ class E2EEBridge {
395
305
  return this.client.sendMessage({ threadId, text, replyToMessageId });
396
306
  }
397
307
 
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
409
308
  const path = require("path");
410
309
  let mime;
411
310
  try { mime = require("mime"); } catch (_) {}
@@ -462,18 +361,10 @@ class E2EEBridge {
462
361
  return this.client.editMessage({ threadId, messageId, newText });
463
362
  }
464
363
 
465
- // ─────────────────────────────────────────────────────────────────────────
466
- // Receive API
467
- // ─────────────────────────────────────────────────────────────────────────
468
-
469
364
  onMessage(callback) {
470
365
  this._messageCallback = callback;
471
366
  }
472
367
 
473
- // ─────────────────────────────────────────────────────────────────────────
474
- // Info / lifecycle
475
- // ─────────────────────────────────────────────────────────────────────────
476
-
477
368
  getPublicKeys() {
478
369
  return {
479
370
  info: "Keys managed by vendored E2EE engine (Signal Protocol / Noise handshake).",
@@ -492,10 +383,6 @@ class E2EEBridge {
492
383
 
493
384
  module.exports = { E2EEBridge };
494
385
 
495
- // ─────────────────────────────────────────────────────────────────────────────
496
- // Private helpers
497
- // ─────────────────────────────────────────────────────────────────────────────
498
-
499
386
  function _streamToBuffer(stream) {
500
387
  return new Promise(function (resolve, reject) {
501
388
  var chunks = [];