fca-nx 6.6.9 → 6.7.1

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 (53) hide show
  1. package/module/login.js +17 -8
  2. package/module/loginHelper.js +68 -8
  3. package/package.json +3 -2
  4. package/src/api/messaging/uploadAttachment.js +5 -2
  5. package/src/api/socket/core/connectMqtt.js +15 -2
  6. package/src/api/socket/core/getSeqID.js +6 -1
  7. package/src/api/socket/e2ee/index.js +18 -1
  8. package/src/api/socket/listenE2EE.js +14 -4
  9. package/src/api/socket/listenMqtt.js +24 -5
  10. package/src/utils/format/utils.js +18 -12
  11. package/src/utils/loginParser/parseAndCheckLogin.js +14 -1
  12. package/src/utils/utils.js +15 -6
  13. package/e2ee/config.json +0 -0
  14. package/e2ee/crypto.js +0 -173
  15. package/e2ee/index.js +0 -1032
  16. package/e2ee/proto/ArmadilloApplication.proto +0 -281
  17. package/e2ee/proto/ArmadilloICDC.proto +0 -14
  18. package/e2ee/proto/ConsumerApplication.proto +0 -232
  19. package/e2ee/proto/MessageApplication.proto +0 -82
  20. package/e2ee/proto/MessageTransport.proto +0 -77
  21. package/e2ee/proto/WACommon.proto +0 -66
  22. package/e2ee/proto/WAMediaTransport.proto +0 -176
  23. package/e2ee/protocol.js +0 -196
  24. package/e2ee/ratchet.js +0 -219
  25. package/e2ee/store.js +0 -182
  26. package/e2ee/vendor/fb-e2ee.cjs +0 -9159
  27. package/e2ee/vendor/proto/ArmadilloApplication.proto +0 -281
  28. package/e2ee/vendor/proto/ArmadilloICDC.proto +0 -14
  29. package/e2ee/vendor/proto/ConsumerApplication.proto +0 -232
  30. package/e2ee/vendor/proto/MessageApplication.proto +0 -82
  31. package/e2ee/vendor/proto/MessageTransport.proto +0 -77
  32. package/e2ee/vendor/proto/WACommon.proto +0 -66
  33. package/e2ee/vendor/proto/WAMediaTransport.proto +0 -176
  34. package/src/api/socket/e2ee/e2ee/crypto.js +0 -173
  35. package/src/api/socket/e2ee/e2ee/index.js +0 -421
  36. package/src/api/socket/e2ee/e2ee/proto/ArmadilloApplication.proto +0 -281
  37. package/src/api/socket/e2ee/e2ee/proto/ArmadilloICDC.proto +0 -14
  38. package/src/api/socket/e2ee/e2ee/proto/ConsumerApplication.proto +0 -232
  39. package/src/api/socket/e2ee/e2ee/proto/MessageApplication.proto +0 -82
  40. package/src/api/socket/e2ee/e2ee/proto/MessageTransport.proto +0 -77
  41. package/src/api/socket/e2ee/e2ee/proto/WACommon.proto +0 -66
  42. package/src/api/socket/e2ee/e2ee/proto/WAMediaTransport.proto +0 -176
  43. package/src/api/socket/e2ee/e2ee/protocol.js +0 -196
  44. package/src/api/socket/e2ee/e2ee/ratchet.js +0 -219
  45. package/src/api/socket/e2ee/e2ee/store.js +0 -182
  46. package/src/api/socket/e2ee/e2ee/vendor/fb-e2ee.cjs +0 -9162
  47. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloApplication.proto +0 -281
  48. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloICDC.proto +0 -14
  49. package/src/api/socket/e2ee/e2ee/vendor/proto/ConsumerApplication.proto +0 -232
  50. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageApplication.proto +0 -82
  51. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageTransport.proto +0 -77
  52. package/src/api/socket/e2ee/e2ee/vendor/proto/WACommon.proto +0 -66
  53. package/src/api/socket/e2ee/e2ee/vendor/proto/WAMediaTransport.proto +0 -176
package/module/login.js CHANGED
@@ -46,10 +46,14 @@ if (!global.fca._errorHandlersInstalled) {
46
46
  }
47
47
  }
48
48
 
49
- // For other unhandled rejections, log but don't crash
50
- logger(`Unhandled promise rejection (non-fatal): ${reason && reason.message ? reason.message : String(reason)}`, "error");
49
+ // [Fixed by xalman] For other unhandled rejections, log but don't crash.
50
+ // Include the stack (when available) - logging only `.message` made
51
+ // real bugs impossible to trace back to where they were thrown.
52
+ const errorDetail = reason && reason.stack ? reason.stack : (reason && reason.message ? reason.message : String(reason));
53
+ logger(`Unhandled promise rejection (non-fatal): ${errorDetail}`, "error");
51
54
  } catch (e) {
52
- // Fallback if logger fails - silent
55
+ // Logger itself failed - fall back to stderr so this isn't silently lost.
56
+ try { console.error("[fca-nx] logger failed while handling unhandledRejection:", e, reason); } catch { }
53
57
  }
54
58
  });
55
59
 
@@ -73,12 +77,17 @@ if (!global.fca._errorHandlersInstalled) {
73
77
  return; // Don't crash
74
78
  }
75
79
 
76
- // For other uncaught exceptions, log but try to continue
77
- logger(`Uncaught exception (attempting to continue): ${errorMessage}`, "error");
78
- // Note: We don't exit here to allow bot to continue running
79
- // In production, you might want to restart the process instead
80
+ // [Fixed by xalman] For other uncaught exceptions, log but try to continue.
81
+ // Include the stack trace - without it these were undebuggable in production.
82
+ logger(`Uncaught exception (attempting to continue): ${error && error.stack ? error.stack : errorMessage}`, "error");
83
+ // Note: We don't exit here to allow bot to continue running.
84
+ // This trades crash-safety for the (small) risk of continuing in a
85
+ // partially-inconsistent process state. If you run this under a process
86
+ // manager (pm2/systemd) that auto-restarts on crash, consider calling
87
+ // process.exit(1) here instead for a clean restart on truly unknown errors.
80
88
  } catch (e) {
81
- // Fallback if logger fails - silent
89
+ // Logger itself failed - fall back to stderr so this isn't silently lost.
90
+ try { console.error("[fca-nx] logger failed while handling uncaughtException:", e, error); } catch { }
82
91
  }
83
92
  });
84
93
  }
@@ -1170,6 +1170,44 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1170
1170
  ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1171
1171
  ctxMain.performAutoLogin = async () => {
1172
1172
  try {
1173
+ // [Fixed by xalman] First check whether the existing cookie session is actually
1174
+ // still usable. A checkpoint/redirect seen on one request
1175
+ // doesn't always mean the whole session is dead (transient FB
1176
+ // blips, rate limiting, etc). Cookie/appstate-only logins have
1177
+ // no email+password to re-login with, so without this check a
1178
+ // single false-positive checkpoint would permanently tear down
1179
+ // the bot (via emitAuth) and force a brand new cookie every
1180
+ // time instead of just continuing on the still-good session.
1181
+ try {
1182
+ // [Fixed by xalman] retry up to 3x - a transient network
1183
+ // hiccup during THIS check alone used to be treated the same
1184
+ // as a dead session and fall through to requiring credentials.
1185
+ let stillCheckpointed = true;
1186
+ let uid = null;
1187
+ for (let attempt = 0; attempt < 3 && !uid; attempt++) {
1188
+ try {
1189
+ const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1190
+ const html = check && check.data ? String(check.data) : "";
1191
+ stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1192
+ const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
1193
+ if (!stillCheckpointed && uidMatch && uidMatch[1] && uidMatch[1] !== "0") {
1194
+ uid = uidMatch[1];
1195
+ break;
1196
+ }
1197
+ } catch {
1198
+ // network hiccup on this attempt - retry below instead of
1199
+ // immediately assuming the session is dead
1200
+ }
1201
+ if (!uid && attempt < 2) await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
1202
+ }
1203
+ if (uid) {
1204
+ logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1205
+ return true;
1206
+ }
1207
+ } catch {
1208
+ // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1209
+ }
1210
+
1173
1211
  const u = config.credentials?.email || email;
1174
1212
  const p = config.credentials?.password || password;
1175
1213
  const tf = config.credentials?.twofactor || null;
@@ -1314,15 +1352,37 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1314
1352
  // bots calling api.listen() OR api.listenMqtt() directly also
1315
1353
  // receive E2EE (Secret Conversation) messages without any extra
1316
1354
  // setup or changes on the bot side.
1317
- api.connectE2EE()
1318
- .then(() => {
1319
- api.listen = api.listenE2EE;
1320
- api.listenMqtt = api.listenE2EE;
1355
+ //
1356
+ // [Fixed by xalman] IMPORTANT: assign api.listen/api.listenMqtt to the combined
1357
+ // listener SYNCHRONOUSLY, before connectE2EE() resolves. Bots
1358
+ // commonly call api.listenMqtt(callback) immediately in the login
1359
+ // callback - if we waited for the async connectE2EE() promise to
1360
+ // swap these over, that call would already have captured the old
1361
+ // plain-MQTT-only function, permanently missing E2EE (inbox)
1362
+ // messages even after E2EE finished connecting moments later.
1363
+ api.listen = api.listenE2EE;
1364
+ api.listenMqtt = api.listenE2EE;
1365
+
1366
+ // [Fixed by xalman] Retry E2EE auto-connect with backoff instead of
1367
+ // giving up forever after one failed attempt - a transient network
1368
+ // blip or momentary FB rate-limit on device registration used to
1369
+ // leave the bot stuck in group-only mode until a full restart.
1370
+ const connectE2EEWithRetry = async (attempt = 0) => {
1371
+ try {
1372
+ await api.connectE2EE();
1321
1373
  logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
1322
- })
1323
- .catch((e) => {
1324
- logger(`E2EE auto-connect failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1325
- });
1374
+ } catch (e) {
1375
+ const msg = e && e.message ? e.message : String(e);
1376
+ if (attempt < 3) {
1377
+ const delayMs = 5000 * Math.pow(3, attempt); // 5s, 15s, 45s
1378
+ logger(`E2EE auto-connect failed (attempt ${attempt + 1}/4): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
1379
+ setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
1380
+ } else {
1381
+ logger(`E2EE auto-connect failed after 4 attempts (non-fatal, continuing without E2EE): ${msg}`, "warn");
1382
+ }
1383
+ }
1384
+ };
1385
+ connectE2EEWithRetry();
1326
1386
  } catch (e) {
1327
1387
  logger(`E2EE init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1328
1388
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.6.9",
3
+ "version": "6.7.1",
4
4
  "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -17,7 +17,6 @@
17
17
  "module/",
18
18
  "func/",
19
19
  "src/",
20
- "e2ee/",
21
20
  "DOCS.md",
22
21
  "README.md",
23
22
  "src/app/"
@@ -85,9 +84,11 @@
85
84
  "mime": "^3.0.0",
86
85
  "mqtt": "^5.10.1",
87
86
  "protobufjs": "^8.4.0",
87
+ "request": "^2.88.2",
88
88
  "sequelize": "^6.37.8",
89
89
  "sqlite3": "^5.1.7",
90
90
  "totp-generator": "^1.0.0",
91
+ "tough-cookie": "^4.1.4",
91
92
  "ws": "^8.18.0"
92
93
  },
93
94
  "devDependencies": {
@@ -61,8 +61,11 @@ function respFinalUrl(res) {
61
61
  }
62
62
 
63
63
  function detectCheckpoint(res) {
64
+ // [Fixed by xalman] res.body -> res.data (axios response shape), same
65
+ // root cause as the parseAndCheckLogin fix in src/utils/utils.js - this
66
+ // was silently always reading undefined and never detecting checkpoints.
64
67
  const url = String(respFinalUrl(res) || "");
65
- const body = typeof res?.body === "string" ? res.body : "";
68
+ const body = typeof res?.data === "string" ? res.data : "";
66
69
  const hit =
67
70
  /\/checkpoint\//i.test(url) ||
68
71
  /(?:href|action)\s*=\s*["']https?:\/\/[^"']*\/checkpoint\//i.test(body) ||
@@ -78,7 +81,7 @@ function checkpointError(res) {
78
81
  e.code = "CHECKPOINT";
79
82
  e.checkpoint = true;
80
83
  e.url = d.url || "https://www.facebook.com/checkpoint/";
81
- e.status = res?.statusCode || res?.status;
84
+ e.status = res?.status || res?.statusCode;
82
85
  return e;
83
86
  }
84
87
 
@@ -9,6 +9,7 @@ const { getSessionIdentity } = require("../../../utils/clientIdentity");
9
9
  const DEFAULT_RECONNECT_DELAY_MS = 2000;
10
10
  const MAX_RECONNECT_DELAY_MS = 60000;
11
11
  const MAX_RECONNECT_ATTEMPTS = 10; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
12
+ const MAX_RECONNECT_COOLDOWN_MS = 10 * 60 * 1000; // after exhausting fast retries, wait this long before trying again (never give up permanently)
12
13
  const T_MS_WAIT_TIMEOUT_MS = 5000;
13
14
 
14
15
  // Exponential backoff with jitter, based on how many *consecutive* reconnect
@@ -44,8 +45,20 @@ module.exports = function createListenMqtt(deps) {
44
45
  }
45
46
  ctx._reconnectAttempts = (ctx._reconnectAttempts || 0) + 1;
46
47
  if (ctx._reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
47
- logger(`mqtt reconnect attempts exceeded (${MAX_RECONNECT_ATTEMPTS}); giving up and surfacing error`, "error");
48
- globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded" }, null);
48
+ // [Fixed by xalman] Don't give up forever - a run of consecutive failures is usually a
49
+ // temporary outage (hosting network blip, FB-side hiccup), not a
50
+ // dead account. Back off to a long, FB-friendly cooldown and reset
51
+ // the counter so normal exponential backoff resumes after that.
52
+ const cooldownMs = MAX_RECONNECT_COOLDOWN_MS;
53
+ logger(`mqtt reconnect attempts exceeded (${MAX_RECONNECT_ATTEMPTS}); backing off ${Math.round(cooldownMs / 60000)}min before trying again (not giving up)`, "error");
54
+ globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded - will retry after cooldown" }, null);
55
+ ctx._reconnectAttempts = 0;
56
+ ctx._reconnectTimer = setTimeout(() => {
57
+ ctx._reconnectTimer = null;
58
+ if (!ctx._ending) {
59
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
60
+ }
61
+ }, cooldownMs);
49
62
  return;
50
63
  }
51
64
  const ms = typeof delayMs === "number" ? delayMs : computeBackoff(ctx, base);
@@ -285,7 +285,12 @@ module.exports = function createGetSeqID(deps) {
285
285
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
286
286
  }
287
287
  logger(`getSeqID: network error persisted after ${MAX_RETRIES} retries, giving up for now: ${msg}`, "error");
288
- return;
288
+ // [Fixed by xalman] throw instead of silently returning undefined -
289
+ // a bare return here made the caller think this call SUCCEEDED.
290
+ const giveUpErr = new Error(`getSeqID network error persisted after ${MAX_RETRIES} retries: ${msg}`);
291
+ giveUpErr.error = msg;
292
+ giveUpErr.isNetworkError = true;
293
+ throw giveUpErr;
289
294
  }
290
295
 
291
296
  if (isAuthError) {
@@ -103,6 +103,11 @@ class E2EEBridge {
103
103
  fb_dtsg: _ctx.fb_dtsg,
104
104
  getCurrentUserID: () => _fcanxApi.getCurrentUserID(),
105
105
  getAppState: () => _fcanxApi.getAppState(),
106
+ // [Fixed by xalman] httpPost always returns a string now - axios
107
+ // auto-parses JSON responses into objects, but the vendored engine
108
+ // (fetchCAT/icdc_fetch/icdc_register) expects raw text and calls
109
+ // .replace()/JSON.parse() on it itself. This was crashing E2EE
110
+ // auto-connect with "resText.replace is not a function".
106
111
  httpPost: async function (url, form) {
107
112
  var merged = Object.assign({}, form);
108
113
  if (!merged.fb_dtsg && _ctx.fb_dtsg) merged.fb_dtsg = _ctx.fb_dtsg;
@@ -113,7 +118,19 @@ class E2EEBridge {
113
118
  require("request")({ method: "POST", url: url, jar: _ctx.jar, form: merged, gzip: true },
114
119
  function (err, r) { if (err) return reject(err); resolve(r); });
115
120
  });
116
- return res && res.body;
121
+ const body = res && (res.data !== undefined ? res.data : res.body);
122
+ if (body == null) return body;
123
+ if (typeof body === "string") return body;
124
+ if (Buffer.isBuffer(body)) return body.toString("utf8");
125
+ // axios auto-parses JSON bodies into an object/array, but the
126
+ // vendored engine always expects a raw string (it strips
127
+ // Facebook's "for (;;);" prefix and JSON.parses it itself).
128
+ // Re-serialize so callers doing resText.replace(...) still work.
129
+ try {
130
+ return JSON.stringify(body);
131
+ } catch {
132
+ return String(body);
133
+ }
117
134
  },
118
135
  // listenMqtt — fb-e2ee.cjs calls this to route non-E2EE MQTT events.
119
136
  // FCA-NX has its own separate MQTT listener so we provide a no-op stub
@@ -47,15 +47,25 @@ module.exports = function (defaultFuncs, api, ctx) {
47
47
  var mqttEmitter = (api._listenMqttRaw || api.listenMqtt)(globalCallback);
48
48
  api._mqttEmitter = mqttEmitter;
49
49
 
50
- // Hook E2EE incoming messages (FCA-NX native Noise WebSocket)
50
+ // [Fixed by xalman] Hook E2EE incoming messages (FCA-NX native Noise WebSocket).
51
+ // onMessage() only registers a callback reference - it doesn't require an
52
+ // active connection - so this is safe to call even while E2EE is still
53
+ // connecting in the background. If we skip it here just because
54
+ // isConnected() is momentarily false, the hook never gets attached and
55
+ // E2EE (inbox) messages go unheard for the lifetime of this listener.
51
56
  var e2ee = api.e2ee || ctx.e2ee;
52
- if (!e2ee || !e2ee.isConnected()) {
57
+ if (!e2ee) {
53
58
  logger.warn(
54
59
  "listenE2EE",
55
- "E2EE not connected. E2EE messages will not be received. " +
56
- "Call api.connectE2EE() before listenE2EE() to enable encrypted message reception."
60
+ "E2EE bridge not available. E2EE messages will not be received."
57
61
  );
58
62
  } else {
63
+ if (!e2ee.isConnected()) {
64
+ logger.info(
65
+ "listenE2EE",
66
+ "E2EE still connecting - message hook registered, will receive events once the handshake completes."
67
+ );
68
+ }
59
69
  e2ee.onMessage(function (err, event) {
60
70
  if (err) return globalCallback(err, null);
61
71
  if (!event) return;
@@ -24,6 +24,7 @@ const CYCLE_MS_DEFAULT = 60 * 60 * 1000;
24
24
  const RECONNECT_DELAY_MS_DEFAULT = 3000;
25
25
  const UNSUB_ALL_TIMEOUT_MS = 5000;
26
26
  const MAX_MQTT_RECONNECT_DELAY_MS = 60000;
27
+ const MAX_MQTT_RECONNECT_COOLDOWN_MS = 10 * 60 * 1000; // long cooldown after exhausting fast retries - never give up permanently
27
28
  const MAX_MQTT_RECONNECT_ATTEMPTS = 10;
28
29
  const HEARTBEAT_INTERVAL_MS = 30000;
29
30
  const HEARTBEAT_TIMEOUT_MS = 10000;
@@ -154,8 +155,16 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
154
155
  const maxAttempts = conf.maxReconnectAttempts || MAX_MQTT_RECONNECT_ATTEMPTS;
155
156
 
156
157
  if (reconnectAttempts > maxAttempts) {
157
- logger("mqtt getSeqID: max reconnect attempts exceeded", "error");
158
- globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded" }, null);
158
+ const cooldownMs = MAX_MQTT_RECONNECT_COOLDOWN_MS;
159
+ logger(`mqtt getSeqID: max reconnect attempts exceeded, backing off ${Math.round(cooldownMs / 60000)}min before trying again (not giving up)`, "error");
160
+ globalCallback({ type: "stop_listen", error: "Max reconnect attempts exceeded - will retry after cooldown" }, null);
161
+ reconnectAttempts = 0;
162
+ ctx._reconnectTimer = setTimeout(() => {
163
+ if (!ctx._ending) {
164
+ isReconnecting = false;
165
+ getSeqIDWrapper();
166
+ }
167
+ }, cooldownMs);
159
168
  return;
160
169
  }
161
170
 
@@ -393,13 +402,23 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
393
402
  function attachClientListeners() {
394
403
  if (!ctx.mqttClient) return;
395
404
 
396
- ctx.mqttClient.removeAllListeners("pong");
405
+ ctx.mqttClient.removeAllListeners("packetreceive");
397
406
  ctx.mqttClient.removeAllListeners("close");
398
407
  ctx.mqttClient.removeAllListeners("error");
399
408
 
400
- ctx.mqttClient.on("pong", () => {
409
+ // [Fixed by xalman] mqtt.js does NOT emit a "pong" event - that was never firing,
410
+ // so lastPongTime was never refreshed and the heartbeat below kept
411
+ // force-reconnecting the account roughly every minute (this is what
412
+ // looked like periodic auto logout). The library's own keepalive
413
+ // (keepalive: 30 in connectMqtt.js) sends PINGREQ/PINGRESP
414
+ // internally; we detect the PINGRESP via "packetreceive" instead.
415
+ // Any other incoming packet (e.g. real messages) also proves the
416
+ // connection is alive, so it counts too.
417
+ ctx.mqttClient.on("packetreceive", (packet) => {
401
418
  lastPongTime = Date.now();
402
- logger("mqtt pong received", "debug");
419
+ if (packet && packet.cmd === "pingresp") {
420
+ logger("mqtt pong received", "debug");
421
+ }
403
422
  });
404
423
 
405
424
  ctx.mqttClient.once("close", () => {
@@ -4,8 +4,11 @@ function getType(obj) {
4
4
  return Object.prototype.toString.call(obj).slice(8, -1);
5
5
  }
6
6
 
7
+ // [Fixed by xalman] formatID now coerces id to String before .replace() -
8
+ // previously crashed with "id.replace is not a function" whenever a numeric
9
+ // userID was passed (e.g. addFriend), since Number has no .replace method.
7
10
  function formatID(id) {
8
- if (id != undefined && id != null) return id.replace(/(fb)?id[:.]/, "");
11
+ if (id != undefined && id != null) return String(id).replace(/(fb)?id[:.]/, "");
9
12
  else return id;
10
13
  }
11
14
 
@@ -35,6 +38,10 @@ function arrToForm(form) {
35
38
  );
36
39
  }
37
40
 
41
+ // [Fixed by xalman] Stt was previously incremented ("Stt++") on every
42
+ // recursive call, which silently coerced any non-numeric default value
43
+ // (string/null/object - the normal case) to NaN one level deep. It's a
44
+ // static fallback value, so it's now passed through unchanged.
38
45
  function getData_Path(Obj, Arr, Stt) {
39
46
  if (Arr.length === 0 && Obj != undefined) {
40
47
  return Obj;
@@ -46,27 +53,26 @@ function getData_Path(Obj, Arr, Stt) {
46
53
  return Stt;
47
54
  }
48
55
  const tail = Arr.slice(1);
49
- return getData_Path(Obj[head], tail, Stt++);
56
+ return getData_Path(Obj[head], tail, Stt);
50
57
  }
51
58
 
59
+ // [Fixed by xalman] Rewritten - the old version reassigned a local variable
60
+ // instead of the actual object property, so updating an EXISTING truthy
61
+ // value silently did nothing. Also stopped mutating the caller's path array.
52
62
  function setData_Path(obj, path, value) {
53
63
  if (!path.length) {
54
64
  return obj;
55
65
  }
56
66
  const currentKey = path[0];
57
- let currentObj = obj[currentKey];
58
-
59
- if (!currentObj) {
67
+ const remaining = path.slice(1);
68
+ if (!remaining.length) {
60
69
  obj[currentKey] = value;
61
- currentObj = obj[currentKey];
62
- }
63
- path.shift();
64
- if (!path.length) {
65
- currentObj = value;
66
70
  } else {
67
- currentObj = setData_Path(currentObj, path, value);
71
+ if (!obj[currentKey] || typeof obj[currentKey] !== "object") {
72
+ obj[currentKey] = {};
73
+ }
74
+ setData_Path(obj[currentKey], remaining, value);
68
75
  }
69
-
70
76
  return obj;
71
77
  }
72
78
 
@@ -103,7 +103,20 @@ function parseAndCheckLogin(ctx, http, retryCount = 0) {
103
103
  }
104
104
  }
105
105
 
106
- if (status === 404) return;
106
+ if (status === 404) {
107
+ const url = buildUrl(res?.config);
108
+ const method = String(res?.config?.method || "GET").toUpperCase();
109
+ const err = new Error(
110
+ `parseAndCheckLogin got status code: 404. [${method}] ${url || "(no url)"} was not found - the endpoint may have changed or been removed by Facebook.`
111
+ );
112
+ err.statusCode = 404;
113
+ err.res = res?.data;
114
+ logger(
115
+ `parseAndCheckLogin: [${method}] ${url || "(no url)"} -> 404 Not Found`,
116
+ "error"
117
+ );
118
+ throw err;
119
+ }
107
120
  if (status !== 200) {
108
121
  const err = new Error(
109
122
  "parseAndCheckLogin got status code: " +
@@ -245,15 +245,24 @@ function decodeClientPayload(payload) {
245
245
 
246
246
  function parseAndCheckLogin(ctx, defaultFuncs) {
247
247
  return function (res) {
248
- if (res.statusCode >= 500 && res.statusCode < 600) {
249
- throw { error: "Facebook internal server error: " + res.statusCode, res };
248
+ // [Fixed by xalman] this used to read res.statusCode/res.body, which are the old
249
+ // `request`/`request-promise` library's property names. The actual
250
+ // HTTP client here (src/utils/request) is axios-based, whose
251
+ // responses use res.status/res.data instead - res.body was always
252
+ // undefined, so this threw "Empty response body" on every single
253
+ // call. That silently broke OldMessage.js (used for DM attachments,
254
+ // and as the fallback whenever an MQTT send fails).
255
+ var status = res && res.status !== undefined ? res.status : (res && res.statusCode);
256
+ if (status >= 500 && status < 600) {
257
+ throw { error: "Facebook internal server error: " + status, res };
250
258
  }
251
- if (res.statusCode === 404 || res.statusCode === 410) {
252
- throw { error: "Endpoint not found: " + res.statusCode, res };
259
+ if (status === 404 || status === 410) {
260
+ throw { error: "Endpoint not found: " + status, res };
253
261
  }
254
- if (!res.body) throw { error: "Empty response body", res };
262
+ var rawBody = res && res.data !== undefined ? res.data : (res && res.body);
263
+ if (rawBody === undefined || rawBody === null || rawBody === "") throw { error: "Empty response body", res };
255
264
 
256
- var body = res.body;
265
+ var body = rawBody;
257
266
  if (typeof body !== "string") body = JSON.stringify(body);
258
267
 
259
268
  var stripped = body;
package/e2ee/config.json DELETED
File without changes
package/e2ee/crypto.js DELETED
@@ -1,173 +0,0 @@
1
- "use strict";
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
- const crypto = require("crypto");
10
-
11
- // ─────────────────────────────────────────────────────────
12
- // X25519 Key Management
13
- // ─────────────────────────────────────────────────────────
14
-
15
- function generateKeyPair() {
16
- const { privateKey, publicKey } = crypto.generateKeyPairSync("x25519", {
17
- privateKeyEncoding: { type: "pkcs8", format: "der" },
18
- publicKeyEncoding: { type: "spki", format: "der" }
19
- });
20
- return {
21
- privateKey,
22
- publicKey,
23
- publicKeyRaw: exportRawPublicKey(publicKey)
24
- };
25
- }
26
-
27
- function exportRawPublicKey(spkiDer) {
28
- // X25519 SPKI DER: 12 bytes header + 32 bytes key
29
- return Buffer.from(spkiDer).slice(-32);
30
- }
31
-
32
- function importPublicKey(raw32bytes) {
33
- if (raw32bytes.length !== 32) throw new Error("X25519 public key must be 32 bytes");
34
- // Build minimal SPKI wrapper for X25519
35
- const header = Buffer.from("302a300506032b656e032100", "hex");
36
- return Buffer.concat([header, raw32bytes]);
37
- }
38
-
39
- function dh(privateKeyPkcs8Der, peerPublicRaw32) {
40
- const privKey = crypto.createPrivateKey({ key: Buffer.from(privateKeyPkcs8Der), format: "der", type: "pkcs8" });
41
- const pubKeyDer = importPublicKey(Buffer.from(peerPublicRaw32));
42
- const pubKey = crypto.createPublicKey({ key: pubKeyDer, format: "der", type: "spki" });
43
- return crypto.diffieHellman({ privateKey: privKey, publicKey: pubKey });
44
- }
45
-
46
- // ─────────────────────────────────────────────────────────
47
- // HKDF-SHA256
48
- // ─────────────────────────────────────────────────────────
49
-
50
- function hkdf(ikm, length, salt, info) {
51
- if (!salt) salt = Buffer.alloc(32, 0);
52
- if (!info) info = Buffer.alloc(0);
53
- if (typeof info === "string") info = Buffer.from(info, "utf8");
54
- return Buffer.from(crypto.hkdfSync("sha256", ikm, salt, info, length));
55
- }
56
-
57
- function hkdfExtract(salt, ikm) {
58
- return crypto.createHmac("sha256", salt).update(ikm).digest();
59
- }
60
-
61
- function hkdfExpand(prk, info, length) {
62
- const results = [];
63
- let t = Buffer.alloc(0);
64
- let i = 0;
65
- while (results.reduce((s, b) => s + b.length, 0) < length) {
66
- i++;
67
- const hmac = crypto.createHmac("sha256", prk);
68
- hmac.update(t);
69
- if (info) hmac.update(info);
70
- hmac.update(Buffer.from([i]));
71
- t = hmac.digest();
72
- results.push(t);
73
- }
74
- return Buffer.concat(results).slice(0, length);
75
- }
76
-
77
- // ─────────────────────────────────────────────────────────
78
- // AES-256-GCM
79
- // ─────────────────────────────────────────────────────────
80
-
81
- function encrypt(key32, plaintext, aad) {
82
- if (key32.length !== 32) throw new Error("AES-GCM key must be 32 bytes");
83
- const iv = crypto.randomBytes(12);
84
- const cipher = crypto.createCipheriv("aes-256-gcm", key32, iv);
85
- if (aad) cipher.setAAD(aad);
86
- const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
87
- const authTag = cipher.getAuthTag();
88
- return Buffer.concat([iv, authTag, encrypted]);
89
- }
90
-
91
- function decrypt(key32, ciphertext, aad) {
92
- if (key32.length !== 32) throw new Error("AES-GCM key must be 32 bytes");
93
- if (ciphertext.length < 28) throw new Error("Ciphertext too short");
94
- const iv = ciphertext.slice(0, 12);
95
- const authTag = ciphertext.slice(12, 28);
96
- const data = ciphertext.slice(28);
97
- const decipher = crypto.createDecipheriv("aes-256-gcm", key32, iv);
98
- decipher.setAuthTag(authTag);
99
- if (aad) decipher.setAAD(aad);
100
- return Buffer.concat([decipher.update(data), decipher.final()]);
101
- }
102
-
103
- // ─────────────────────────────────────────────────────────
104
- // HMAC-SHA256
105
- // ─────────────────────────────────────────────────────────
106
-
107
- function hmacSha256(key, data) {
108
- return crypto.createHmac("sha256", key).update(data).digest();
109
- }
110
-
111
- function constantTimeEqual(a, b) {
112
- if (a.length !== b.length) return false;
113
- return crypto.timingSafeEqual(a, b);
114
- }
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
- */
129
- function x3dhSend(senderIdKey, ephemeralKey, recipientIdPub, recipientSpkPub, recipientOpkPub) {
130
- const dh1 = dh(senderIdKey.privateKey, recipientSpkPub);
131
- const dh2 = dh(ephemeralKey.privateKey, recipientIdPub);
132
- const dh3 = dh(ephemeralKey.privateKey, recipientSpkPub);
133
- const parts = recipientOpkPub
134
- ? [dh1, dh2, dh3, dh(ephemeralKey.privateKey, recipientOpkPub)]
135
- : [dh1, dh2, dh3];
136
- const ikm = Buffer.concat(parts);
137
- const F = Buffer.alloc(32, 0xFF);
138
- const salt = Buffer.alloc(32, 0);
139
- return hkdf(Buffer.concat([F, ikm]), 32, salt, Buffer.from("WhisperText", "utf8"));
140
- }
141
-
142
- /**
143
- * Receiver side of X3DH.
144
- */
145
- function x3dhReceive(recipientIdKey, recipientSpkKey, recipientOpkKey, senderIdPub, senderEphemeralPub) {
146
- const dh1 = dh(recipientSpkKey.privateKey, senderIdPub);
147
- const dh2 = dh(recipientIdKey.privateKey, senderEphemeralPub);
148
- const dh3 = dh(recipientSpkKey.privateKey, senderEphemeralPub);
149
- const parts = recipientOpkKey
150
- ? [dh1, dh2, dh3, dh(recipientOpkKey.privateKey, senderEphemeralPub)]
151
- : [dh1, dh2, dh3];
152
- const ikm = Buffer.concat(parts);
153
- const F = Buffer.alloc(32, 0xFF);
154
- const salt = Buffer.alloc(32, 0);
155
- return hkdf(Buffer.concat([F, ikm]), 32, salt, Buffer.from("WhisperText", "utf8"));
156
- }
157
-
158
- module.exports = {
159
- generateKeyPair,
160
- exportRawPublicKey,
161
- importPublicKey,
162
- dh,
163
- hkdf,
164
- hkdfExtract,
165
- hkdfExpand,
166
- encrypt,
167
- decrypt,
168
- hmacSha256,
169
- constantTimeEqual,
170
- x3dhSend,
171
- x3dhReceive,
172
- randomBytes: crypto.randomBytes.bind(crypto)
173
- };