fca-nx 7.0.5 → 7.2.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/module/config.js CHANGED
@@ -13,7 +13,6 @@ const defaultConfig = {
13
13
  apiServer: "",
14
14
  apiKey: "",
15
15
  credentials: { email: "", password: "", twofactor: "" },
16
- e2ee: false,
17
16
  antiGetInfo: {
18
17
  AntiGetThreadInfo: false,
19
18
  AntiGetUserInfo: false
@@ -12,18 +12,6 @@ const { getFrom } = require("../src/utils/constants");
12
12
  const { loadConfig } = require("./config");
13
13
  const { createRemoteClient } = require("../src/remote/remoteClient");
14
14
  const { config } = loadConfig();
15
-
16
- function e2eeEnabled() {
17
- const on = (v) => v === true || v === "true";
18
- try {
19
- const botPath = path.join(process.cwd(), "config.json");
20
- if (fs.existsSync(botPath)) {
21
- const bot = JSON.parse(fs.readFileSync(botPath, "utf8"));
22
- if (bot && Object.prototype.hasOwnProperty.call(bot, "e2ee")) return on(bot.e2ee);
23
- }
24
- } catch (_) {}
25
- return on(config.e2ee);
26
- }
27
15
  const axiosBase = require("axios");
28
16
  const regions = [
29
17
  { code: "PRN", name: "Pacific Northwest Region", location: "Khu vực Tây Bắc Thái Bình Dương" },
@@ -41,6 +29,24 @@ const regions = [
41
29
 
42
30
  const REGION_MAP = new Map(regions.map(r => [r.code, r]));
43
31
 
32
+ // E2EE on/off switch. Reads "e2ee" from the bot's config.json (process.cwd()),
33
+ // then from the fca-nx config. Default is OFF so E2EE only starts when asked for.
34
+ function e2eeEnabled() {
35
+ const on = (v) => v === true || v === "true";
36
+ const off = (v) => v === false || v === "false";
37
+ try {
38
+ const botPath = path.join(process.cwd(), "config.json");
39
+ if (fs.existsSync(botPath)) {
40
+ const bot = JSON.parse(fs.readFileSync(botPath, "utf8"));
41
+ if (bot && Object.prototype.hasOwnProperty.call(bot, "e2ee")) {
42
+ return on(bot.e2ee);
43
+ }
44
+ }
45
+ } catch (_) {}
46
+ if (off(config.e2ee)) return false;
47
+ return on(config.e2ee);
48
+ }
49
+
44
50
  function parseRegion(html) {
45
51
  try {
46
52
  const m1 = html.match(/"endpoint":"([^"]+)"/);
@@ -1353,34 +1359,50 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1353
1359
  }, 86400000);
1354
1360
  }
1355
1361
  // ✅ fca-nx core features register
1356
- try {
1357
- if (!e2eeEnabled()) {
1358
- logger("E2EE off. Set \"e2ee\": true in config.json or fca-config.json to connect.", "info");
1359
- } else {
1362
+ if (!e2eeEnabled()) {
1363
+ logger("E2EE off. Set \"e2ee\": true in config.json to enable it.", "info");
1364
+ } else try {
1360
1365
  const e2eeModule = require("../src/api/socket/e2ee");
1361
1366
  api.e2ee = new e2eeModule.E2EEBridge(ctxMain, api, defaultFuncs);
1362
1367
  ctxMain.e2ee = api.e2ee;
1363
1368
  api.connectE2EE = (deviceStorePath) => api.e2ee.connect(deviceStorePath, ctxMain.userID);
1364
1369
  api.listenE2EE = require("../src/api/socket/listenE2EE")(defaultFuncs, api, ctxMain);
1370
+
1371
+ // Auto-connect E2EE and make it the default listener so existing
1372
+ // bots calling api.listen() OR api.listenMqtt() directly also
1373
+ // receive E2EE (Secret Conversation) messages without any extra
1374
+ // setup or changes on the bot side.
1375
+ //
1376
+ // [Fixed by xalman] IMPORTANT: assign api.listen/api.listenMqtt to the combined
1377
+ // listener SYNCHRONOUSLY, before connectE2EE() resolves. Bots
1378
+ // commonly call api.listenMqtt(callback) immediately in the login
1379
+ // callback - if we waited for the async connectE2EE() promise to
1380
+ // swap these over, that call would already have captured the old
1381
+ // plain-MQTT-only function, permanently missing E2EE (inbox)
1382
+ // messages even after E2EE finished connecting moments later.
1365
1383
  api.listen = api.listenE2EE;
1366
1384
  api.listenMqtt = api.listenE2EE;
1385
+
1386
+ // [Fixed by xalman] Retry E2EE auto-connect with backoff instead of
1387
+ // giving up forever after one failed attempt - a transient network
1388
+ // blip or momentary FB rate-limit on device registration used to
1389
+ // leave the bot stuck in group-only mode until a full restart.
1367
1390
  const connectE2EEWithRetry = async (attempt = 0) => {
1368
1391
  try {
1369
1392
  await api.connectE2EE();
1370
1393
  logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
1371
1394
  } catch (e) {
1372
1395
  const msg = e && e.message ? e.message : String(e);
1373
- if (attempt >= 2) {
1374
- logger(`E2EE auto-connect stopped after ${attempt + 1} tries: ${msg}`, "warn");
1375
- return;
1396
+ if (attempt < 3) {
1397
+ const delayMs = 5000 * Math.pow(3, attempt); // 5s, 15s, 45s
1398
+ logger(`E2EE auto-connect failed (attempt ${attempt + 1}/4): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
1399
+ setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
1400
+ } else {
1401
+ logger(`E2EE auto-connect failed after 4 attempts (non-fatal, continuing without E2EE): ${msg}`, "warn");
1376
1402
  }
1377
- const delayMs = 15000 * (attempt + 1);
1378
- logger(`E2EE auto-connect failed (attempt ${attempt + 1}): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
1379
- setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
1380
1403
  }
1381
1404
  };
1382
1405
  connectE2EEWithRetry();
1383
- }
1384
1406
  } catch (e) {
1385
1407
  logger(`E2EE init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1386
1408
  }
@@ -1416,7 +1438,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1416
1438
  // used to silently discard it, so only group messages arriving over
1417
1439
  // plain MQTT reached bot handlers.
1418
1440
  api._listenMqttRaw = stableListenMqtt;
1419
- if (e2eeEnabled() && typeof api.listenE2EE === "function") {
1441
+ if (typeof api.listenE2EE === "function") {
1420
1442
  api.listenMqtt = api.listen = api.listenE2EE;
1421
1443
  } else {
1422
1444
  api.listenMqtt = api.listen = stableListenMqtt;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "7.0.5",
4
- "description": "Facebook Messenger API for Node.js Fast, Secure, and Feature-Rich",
3
+ "version": "7.2.0",
4
+ "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "exports": {
@@ -2,7 +2,10 @@
2
2
 
3
3
  const log = require("../../../func/logAdapter");
4
4
  const { parseAndCheckLogin } = require("../../utils/client");
5
- const { getType } = require("../../utils/format");
5
+
6
+ // api.getThemePictures(themeID, callback?)
7
+ // themeID = the theme_fbid (digits), e.g. from api.getThreadInfo(tid).threadTheme.id
8
+ // or from an api.createThemeAI() result.
6
9
  module.exports = function (defaultFuncs, api, ctx) {
7
10
  return function getThemePictures(id, callback) {
8
11
  let resolveFunc = function () { };
@@ -12,24 +15,24 @@ module.exports = function (defaultFuncs, api, ctx) {
12
15
  rejectFunc = reject;
13
16
  });
14
17
 
15
- if (!callback) {
16
- if (
17
- getType(callback) == "Function" ||
18
- getType(callback) == "AsyncFunction"
19
- ) {
20
- callback = callback;
21
- } else {
22
- callback = function (err, data) {
23
- if (err) {
24
- return rejectFunc(err);
25
- }
26
- resolveFunc(data);
27
- };
28
- }
18
+ if (typeof callback !== "function") {
19
+ callback = function (err, data) {
20
+ if (err) return rejectFunc(err);
21
+ resolveFunc(data);
22
+ };
29
23
  }
30
24
 
31
- if (getType(id) != "String") {
32
- id = "";
25
+ // [Hardened] Accept numbers/bigint too. Previously any non-string id was silently
26
+ // replaced with "" and Facebook answered messenger_thread_theme: null.
27
+ if (typeof id === "number" || typeof id === "bigint") id = String(id);
28
+ id = typeof id === "string" ? id.trim() : "";
29
+
30
+ if (!/^\d+$/.test(id)) {
31
+ const err = {
32
+ error: "getThemePictures: a numeric theme ID is required (theme_fbid), got: " + JSON.stringify(id)
33
+ };
34
+ callback(err);
35
+ return returnPromise;
33
36
  }
34
37
 
35
38
  const form = {
@@ -37,19 +40,30 @@ module.exports = function (defaultFuncs, api, ctx) {
37
40
  fb_api_req_friendly_name: "MWPThreadThemeProviderQuery",
38
41
  doc_id: "9734829906576883",
39
42
  server_timestamps: true,
40
- variables: JSON.stringify({
41
- id
42
- }),
43
+ variables: JSON.stringify({ id }),
43
44
  av: ctx.userID
44
45
  };
46
+
45
47
  defaultFuncs
46
48
  .post("https://www.facebook.com/api/graphql/", ctx.jar, form)
47
49
  .then(parseAndCheckLogin(ctx, defaultFuncs))
48
50
  .then(function (resData) {
49
- if (resData.errors) {
51
+ if (resData && resData.errors) {
50
52
  throw resData;
51
53
  }
52
54
 
55
+ // [Hardened] Request worked but Facebook has no theme with this ID for this account.
56
+ // Report as failure instead of a false "success" with null theme.
57
+ if (!resData || !resData.data || !resData.data.messenger_thread_theme) {
58
+ const notFound = {
59
+ error: "Theme not found: Facebook returned no theme for ID " + id + ". Check the ID (use the theme_fbid of a real theme).",
60
+ themeID: id,
61
+ raw: resData
62
+ };
63
+ log.error("getThemePictures", notFound.error);
64
+ return callback(notFound);
65
+ }
66
+
53
67
  return callback(null, resData);
54
68
  })
55
69
  .catch(function (err) {
@@ -296,39 +296,43 @@ module.exports = function createGetSeqID(deps) {
296
296
  if (isAuthError) {
297
297
  if (retryCount < MAX_RETRIES) {
298
298
  const delay = RETRY_DELAY * (retryCount + 1);
299
- logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms, same cookie (error: ${msg})`, "warn");
299
+ logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (error: ${msg})`, "warn");
300
300
  await new Promise(resolve => setTimeout(resolve, delay));
301
+
302
+ if (retryCount === 0 && ctx.loggedIn) {
303
+ try {
304
+ logger("getSeqID: refreshing session before retry...", "info");
305
+ const { get } = require("../../../utils/request");
306
+ const { saveCookies } = require("../../../utils/client");
307
+ await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
308
+ } catch (refreshErr) {
309
+ logger(`getSeqID: session refresh failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
310
+ }
311
+ }
312
+
301
313
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
302
314
  }
303
315
 
304
- if (/blocked the login|login_blocked|checkpoint/i.test(msg)) {
305
- return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
316
+ logger("getSeqID: all retries failed, attempting auto re-login...", "warn");
317
+ const config = getConfig();
318
+ const loginResult = await tryAutoLogin(logger, config, ctx, defaultFuncs);
319
+
320
+ if (loginResult) {
321
+ logger("getSeqID: retrying with new session...", "info");
322
+ await new Promise(resolve => setTimeout(resolve, 3000));
323
+ return getSeqID(defaultFuncs, api, ctx, globalCallback, form, 0);
306
324
  }
307
325
 
308
- logger(`getSeqID: auth still failing - keeping this cookie, no new login: ${msg}`, "error");
309
- try {
310
- if (typeof globalCallback === "function") {
311
- globalCallback({ type: "session_recovering", error: msg, timestamp: Date.now() }, null);
312
- }
313
- } catch (_) {}
314
- setTimeout(() => {
315
- if (ctx._ending) return;
316
- try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
317
- }, 120000);
318
- return;
326
+ if (/blocked/i.test(msg)) {
327
+ return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
328
+ }
329
+ if (/Not logged in/i.test(msg)) {
330
+ return emitAuth(ctx, api, globalCallback, "not_logged_in", msg);
331
+ }
319
332
  }
320
333
 
321
- logger(`getSeqID error (soft recover, no logout): ${msg}`, "error");
322
- try {
323
- if (typeof globalCallback === "function") {
324
- globalCallback({ type: "session_recovering", error: msg, timestamp: Date.now() }, null);
325
- }
326
- } catch (_) {}
327
- setTimeout(() => {
328
- if (ctx._ending) return;
329
- try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
330
- }, 120000);
331
- return;
334
+ logger(`getSeqID error: ${msg}`, "error");
335
+ return emitAuth(ctx, api, globalCallback, "auth_error", msg);
332
336
  });
333
337
  };
334
338
  };
@@ -1,16 +1,18 @@
1
1
  "use strict";
2
2
 
3
+ /**
4
+ * fca-nx sendMessage — MQTT primary, OldMessage fallback, E2EE for encrypted DMs.
5
+ * Hardened6: soft MQTT wait, E2EE→MQTT→HTTP cascade, ack retry, paced sends.
6
+ */
7
+
3
8
  var utils = require("../../utils/utils");
4
9
  var logger = require("../../utils/logger");
5
- var { getTextEffectId, getTextEffectIds } = require("../../utils/textEffects");
10
+ var { waitTurn } = require("../../utils/sendThrottle");
6
11
 
7
12
  var ALLOWED = {
8
13
  attachment: true, url: true, sticker: true, emoji: true,
9
14
  emojiSize: true, body: true, mentions: true, location: true,
10
- replyToMessage: true, forwardAttachmentIds: true, text_effect_ids: true,
11
- textEffect: true, text_effect: true, text_effect_id: true,
12
- textEffectId: true, textEffectID: true, effect: true, effect_id: true,
13
- effectID: true, text_effect_name: true, effectName: true, effect_name: true
15
+ replyToMessage: true, forwardAttachmentIds: true
14
16
  };
15
17
 
16
18
  var EMOJI_SIZES = { small: 1, medium: 2, large: 3 };
@@ -30,19 +32,15 @@ function buildMentionData(msg, baseBody) {
30
32
  var ids = [], offsets = [], lengths = [], types = [];
31
33
  for (var i = 0; i < msg.mentions.length; i++) {
32
34
  var mention = msg.mentions[i];
33
- // Ensure tag always has @ prefix — Facebook counts @ in both offset and length
34
35
  var tag = String(mention.tag || "");
35
36
  if (tag && !tag.startsWith("@")) tag = "@" + tag;
36
37
  var fromIndex = Number.isInteger(mention.fromIndex) ? mention.fromIndex : 0;
37
38
  var offset = baseBody.indexOf(tag, fromIndex);
38
- if (offset === -1) {
39
- // Fallback: search for bare name without @
40
- offset = baseBody.indexOf(tag.slice(1), fromIndex);
41
- }
39
+ if (offset === -1) offset = baseBody.indexOf(tag.slice(1), fromIndex);
42
40
  if (offset < 0) offset = 0;
43
41
  ids.push(String(mention.id || 0));
44
42
  offsets.push(offset);
45
- lengths.push(tag.length); // includes @ — matches Facebook's expectation
43
+ lengths.push(tag.length);
46
44
  types.push("p");
47
45
  }
48
46
  return {
@@ -71,52 +69,87 @@ function extractIdsFromPayload(payload) {
71
69
  }
72
70
 
73
71
  function publishLsRequestWithAck(mqttClient, content, requestId, timeout) {
74
- timeout = timeout || 15000;
75
- return new Promise((resolve, reject) => {
76
- var timer = setTimeout(() => {
77
- mqttClient.removeListener('message', onMessage);
78
- reject(new Error('MQTT sendMessage timed out after ' + timeout + 'ms'));
72
+ timeout = timeout || 18000;
73
+ return new Promise(function (resolve, reject) {
74
+ if (!mqttClient || typeof mqttClient.publish !== "function") {
75
+ return reject(new Error("MQTT client not available"));
76
+ }
77
+
78
+ var settled = false;
79
+ function done(err, val) {
80
+ if (settled) return;
81
+ settled = true;
82
+ try { clearTimeout(timer); } catch (_) { }
83
+ try { mqttClient.removeListener("message", onMessage); } catch (_) { }
84
+ if (err) reject(err);
85
+ else resolve(val);
86
+ }
87
+
88
+ var timer = setTimeout(function () {
89
+ done(new Error("MQTT sendMessage timed out after " + timeout + "ms"));
79
90
  }, timeout);
80
91
 
81
92
  function onMessage(topic, message) {
82
- if (topic !== '/ls_resp') return;
93
+ if (topic !== "/ls_resp") return;
83
94
  try {
84
95
  var data = JSON.parse(message.toString());
85
- if (String(data.request_id) === String(requestId)) {
86
- clearTimeout(timer);
87
- mqttClient.removeListener('message', onMessage);
88
- var extracted = extractIdsFromPayload(data.payload ? JSON.parse(data.payload) : {});
89
- resolve({ threadID: extracted.threadID, messageID: extracted.messageID });
90
- }
96
+ if (String(data.request_id) !== String(requestId)) return;
97
+ var extracted = extractIdsFromPayload(data.payload ? JSON.parse(data.payload) : {});
98
+ done(null, {
99
+ threadID: extracted.threadID,
100
+ messageID: extracted.messageID
101
+ });
91
102
  } catch (_) { }
92
103
  }
93
104
 
94
- mqttClient.on('message', onMessage);
95
- mqttClient.publish('/ls_req', JSON.stringify(content), { qos: 1 }, err => {
96
- if (err) {
97
- clearTimeout(timer);
98
- mqttClient.removeListener('message', onMessage);
99
- reject(err);
105
+ mqttClient.on("message", onMessage);
106
+ try {
107
+ mqttClient.publish("/ls_req", JSON.stringify(content), { qos: 1 }, function (err) {
108
+ if (err) done(err);
109
+ });
110
+ } catch (pubErr) {
111
+ done(pubErr);
112
+ }
113
+ });
114
+ }
115
+
116
+ /** Wait briefly for MQTT to become ready (reconnect in progress). */
117
+ function waitForMqtt(ctx, maxMs) {
118
+ maxMs = maxMs || 4000;
119
+ return new Promise(function (resolve) {
120
+ var client = ctx.mqttClient || global.mqttClient;
121
+ if (client && client.connected) return resolve(client);
122
+ var start = Date.now();
123
+ var iv = setInterval(function () {
124
+ var c = ctx.mqttClient || global.mqttClient;
125
+ if (c && c.connected) {
126
+ clearInterval(iv);
127
+ return resolve(c);
100
128
  }
101
- });
129
+ if (Date.now() - start >= maxMs) {
130
+ clearInterval(iv);
131
+ return resolve(c || null);
132
+ }
133
+ }, 200);
102
134
  });
103
135
  }
104
136
 
105
137
  module.exports = function (defaultFuncs, api, ctx) {
106
- var uploadAttachmentFn = require('../messaging/uploadAttachment')(defaultFuncs, api, ctx);
138
+ var uploadAttachmentFn = require("../messaging/uploadAttachment")(defaultFuncs, api, ctx);
107
139
 
108
140
  async function uploadAttachments(attachments) {
109
141
  if (!Array.isArray(attachments)) attachments = [attachments];
110
142
  return uploadAttachmentFn(attachments);
111
143
  }
112
144
 
113
- async function sendViaMqtt(msg, threadID, replyToMessage) {
114
- var mqttClient = ctx.mqttClient || global.mqttClient;
115
- if (!mqttClient) throw new Error('MQTT client not available');
145
+ async function sendViaMqtt(msg, threadID, replyToMessage, ackTimeout) {
146
+ var mqttClient = await waitForMqtt(ctx, 4000);
147
+ if (!mqttClient || !mqttClient.connected) {
148
+ throw new Error("MQTT client not available");
149
+ }
116
150
 
117
151
  var baseBody = msg.body != null ? String(msg.body) : "";
118
152
  var requestId = Math.floor(100 + Math.random() * 900);
119
- var epoch = (BigInt(Date.now()) << 22n).toString();
120
153
 
121
154
  var payload0 = {
122
155
  thread_id: String(threadID),
@@ -136,18 +169,23 @@ module.exports = function (defaultFuncs, api, ctx) {
136
169
  var mentionData = buildMentionData(msg, baseBody);
137
170
  if (mentionData) payload0.mention_data = mentionData;
138
171
 
139
- var textEffectId = getTextEffectId(msg);
140
- if (textEffectId) payload0.text_effect_id = textEffectId;
141
- var effectArray = getTextEffectIds(msg);
142
- if (effectArray.length) payload0.text_effect_ids = effectArray;
143
-
144
- if (msg.sticker) { payload0.send_type = 2; payload0.sticker_id = msg.sticker; }
145
- if (msg.emoji) { payload0.send_type = 1; payload0.text = msg.emoji; payload0.hot_emoji_size = toEmojiSize(msg.emojiSize); }
172
+ if (msg.sticker) {
173
+ payload0.send_type = 2;
174
+ payload0.sticker_id = msg.sticker;
175
+ }
176
+ if (msg.emoji) {
177
+ payload0.send_type = 1;
178
+ payload0.text = msg.emoji;
179
+ payload0.hot_emoji_size = toEmojiSize(msg.emojiSize);
180
+ }
146
181
 
147
182
  if (msg.location && msg.location.latitude != null && msg.location.longitude != null) {
148
183
  payload0.send_type = 1;
149
184
  payload0.location_data = {
150
- coordinates: { latitude: msg.location.latitude, longitude: msg.location.longitude },
185
+ coordinates: {
186
+ latitude: msg.location.latitude,
187
+ longitude: msg.location.longitude
188
+ },
151
189
  is_current_location: Boolean(msg.location.current),
152
190
  is_live_location: Boolean(msg.location.live)
153
191
  };
@@ -179,14 +217,15 @@ module.exports = function (defaultFuncs, api, ctx) {
179
217
  if (msg.forwardAttachmentIds && msg.forwardAttachmentIds.length) {
180
218
  payload0.attachment_fbids = payload0.attachment_fbids.concat(msg.forwardAttachmentIds.map(String));
181
219
  }
182
-
183
220
  if (toUpload.length) {
184
221
  var uploaded = await uploadAttachments(toUpload);
185
222
  for (var u of uploaded) {
186
223
  if (!u) continue;
187
224
  var fbid = u.image_id || u.video_id || u.audio_id || u.file_id || u.sticker_id || u.gif_id;
188
225
  if (!fbid) {
189
- var firstKey = Object.keys(u).find(function(k) { return u[k] && /^\d+$/.test(String(u[k])); });
226
+ var firstKey = Object.keys(u).find(function (k) {
227
+ return u[k] && /^\d+$/.test(String(u[k]));
228
+ });
190
229
  if (firstKey) fbid = u[firstKey];
191
230
  }
192
231
  if (fbid) payload0.attachment_fbids.push(String(fbid));
@@ -197,14 +236,14 @@ module.exports = function (defaultFuncs, api, ctx) {
197
236
 
198
237
  var tasks = [
199
238
  {
200
- label: '46',
239
+ label: "46",
201
240
  payload: JSON.stringify(payload0),
202
241
  queue_name: String(threadID),
203
242
  task_id: 400,
204
243
  failure_count: null
205
244
  },
206
245
  {
207
- label: '21',
246
+ label: "21",
208
247
  payload: JSON.stringify({
209
248
  thread_id: String(threadID),
210
249
  last_read_watermark_ts: Date.now(),
@@ -217,57 +256,102 @@ module.exports = function (defaultFuncs, api, ctx) {
217
256
  ];
218
257
 
219
258
  var content = {
220
- app_id: '2220391788200892',
259
+ app_id: "2220391788200892",
221
260
  payload: JSON.stringify({
222
261
  tasks: tasks,
223
- epoch_id: epoch,
224
- version_id: '24804310205905615',
225
- data_trace_id: '#' + Buffer.from(String(Math.random())).toString('base64').replace(/=+$/, '')
262
+ epoch_id: (BigInt(Date.now()) << 22n).toString(),
263
+ version_id: "24804310205905615"
226
264
  }),
227
265
  request_id: requestId,
228
266
  type: 3
229
267
  };
230
268
 
231
- return publishLsRequestWithAck(mqttClient, content, requestId, 15000);
269
+ // Soft retry once on timeout (common during MQTT flap)
270
+ var timeout = ackTimeout || 18000;
271
+ try {
272
+ return await publishLsRequestWithAck(mqttClient, content, requestId, timeout);
273
+ } catch (firstErr) {
274
+ var msgErr = firstErr && firstErr.message ? firstErr.message : String(firstErr);
275
+ if (!/timed out/i.test(msgErr)) throw firstErr;
276
+ logger.warn("sendMessage", "MQTT ack timeout - one soft retry");
277
+ await new Promise(function (r) { setTimeout(r, 800 + Math.floor(Math.random() * 700)); });
278
+ mqttClient = await waitForMqtt(ctx, 3000);
279
+ if (!mqttClient || !mqttClient.connected) throw firstErr;
280
+ // new request id for retry
281
+ requestId = Math.floor(100 + Math.random() * 900);
282
+ content.request_id = requestId;
283
+ return await publishLsRequestWithAck(mqttClient, content, requestId, Math.min(timeout + 5000, 25000));
284
+ }
285
+ }
286
+
287
+ async function sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser) {
288
+ if (typeof api.OldMessage !== "function") {
289
+ throw new Error("OldMessage fallback is not available");
290
+ }
291
+ return new Promise(function (res2, rej2) {
292
+ api.OldMessage(msg, threadID, function (err2, data2) {
293
+ if (err2) rej2(err2);
294
+ else res2(data2);
295
+ }, replyToMessage, isSingleUser);
296
+ });
232
297
  }
233
298
 
234
299
  return async function sendMessage(msg, threadID, callback, replyToMessage, isSingleUser) {
235
300
  if (typeof msg === "string") msg = { body: msg };
236
- if (typeof callback !== "function") { callback = null; }
301
+ if (typeof callback !== "function") callback = null;
302
+ var drop = ["text_effect_ids", "textEffect", "text_effect", "text_effect_id", "textEffectId", "textEffectID", "effect", "effect_id", "effectID", "text_effect_name", "effectName", "effect_name"];
303
+ for (var d = 0; d < drop.length; d++) delete msg[drop[d]];
237
304
 
238
305
  var resolve, reject;
239
- var promise = new Promise((res, rej) => { resolve = res; reject = rej; });
306
+ var promise = new Promise(function (res, rej) {
307
+ resolve = res;
308
+ reject = rej;
309
+ });
240
310
 
241
311
  for (var key in msg) {
242
312
  if (!ALLOWED[key]) {
243
- var err = { error: "sendMessage: Unknown property '" + key + "'" };
313
+ var err = new Error("Message key '" + key + "' is not allowed.");
244
314
  if (callback) callback(err);
245
315
  else reject(err);
246
316
  return promise;
247
317
  }
248
318
  }
249
319
 
320
+ if (!threadID && threadID !== 0) {
321
+ var tidErr = new Error("threadID is required");
322
+ if (callback) callback(tidErr);
323
+ else reject(tidErr);
324
+ return promise;
325
+ }
326
+
250
327
  // Auto-detect isSingleUser from ctx.threadTypes if not explicitly provided.
251
- // parseDelta in listenMqtt.js populates ctx.threadTypes[senderID] = 'dm' | 'group'
252
328
  if (isSingleUser === undefined && ctx.threadTypes) {
253
- isSingleUser = ctx.threadTypes[String(threadID)] === 'dm';
329
+ isSingleUser = ctx.threadTypes[String(threadID)] === "dm";
254
330
  }
255
331
 
256
- // DM attachment sends — skip MQTT entirely.
257
- // For E2EE DMs: route through the E2EE bridge (Noise WebSocket, Signal Protocol).
258
- // Facebook strips attachment_fbids from MQTT messages in E2EE threads
259
- // (can't re-encrypt CDN attachments on the fly), so MQTT silently drops them.
260
- // The vendor's client.sendImage/sendVideo/sendAudio encrypts the file data
261
- // and sends via the Noise WebSocket — the only path that actually delivers
262
- // attachments in E2EE threads.
263
- // For non-E2EE DMs: use OldMessage.
264
- // /messaging/send/ with other_user_fbid routing works for plain DMs.
265
- // (For E2EE DMs it returns 404 because the endpoint is deprecated for those.)
332
+ // Empty payload guard (except sticker/attachment/emoji/location)
333
+ var hasContent =
334
+ (msg.body != null && String(msg.body).length > 0) ||
335
+ msg.attachment || msg.sticker || msg.emoji || msg.location ||
336
+ (msg.forwardAttachmentIds && msg.forwardAttachmentIds.length);
337
+ if (!hasContent) {
338
+ var emptyErr = new Error("Message must have body, attachment, sticker, emoji or location");
339
+ if (callback) callback(emptyErr);
340
+ else reject(emptyErr);
341
+ return promise;
342
+ }
343
+
344
+ // Pace all outgoing traffic (anti-burst)
345
+ await waitTurn();
346
+
347
+ // ---- DM attachment path (skip MQTT) ----
348
+ // E2EE DMs: bridge only (MQTT strips attachment_fbids).
349
+ // Plain DMs: OldMessage (/messaging/send/ other_user_fbid).
266
350
  if (isSingleUser && msg.attachment) {
267
351
  var useE2EE = api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected();
268
352
  if (useE2EE) {
269
353
  try {
270
- var e2eeResult = await api.e2ee.sendMessage(String(threadID), msg, replyToMessage);
354
+ var e2eeResult = await api.e2ee.sendMessage(String(threadID), msg, replyToMessage || msg.replyToMessage);
271
355
  var wrapped = e2eeResult && e2eeResult.messageId
272
356
  ? { threadID: String(threadID), messageID: String(e2eeResult.messageId) }
273
357
  : e2eeResult;
@@ -280,13 +364,11 @@ module.exports = function (defaultFuncs, api, ctx) {
280
364
  }
281
365
  } else {
282
366
  try {
283
- var omResult = await new Promise((res2, rej2) => {
284
- api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, true);
285
- });
367
+ var omResult = await sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser);
286
368
  if (callback) callback(null, omResult);
287
369
  else resolve(omResult);
288
370
  } catch (omErr) {
289
- logger.error("sendMessage", "DM attachment via OldMessage failed: " + (omErr.error || omErr.message || omErr));
371
+ logger.error("sendMessage", "DM attachment OldMessage failed: " + (omErr.message || omErr));
290
372
  if (callback) callback(omErr);
291
373
  else reject(omErr);
292
374
  }
@@ -294,16 +376,43 @@ module.exports = function (defaultFuncs, api, ctx) {
294
376
  return promise;
295
377
  }
296
378
 
379
+ // ---- E2EE text path with cascade fallback ----
380
+ // Text replies to E2EE DMs should use the bridge; if it fails, try MQTT then OldMessage
381
+ // instead of hard-failing (Hardened6).
382
+ if (isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
383
+ api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected()) {
384
+ try {
385
+ var e2eeText = await api.e2ee.sendMessage(
386
+ String(threadID),
387
+ { body: msg.body != null ? String(msg.body) : "" },
388
+ replyToMessage || msg.replyToMessage
389
+ );
390
+ var e2eeWrapped = e2eeText && e2eeText.messageId
391
+ ? { threadID: String(threadID), messageID: String(e2eeText.messageId) }
392
+ : e2eeText;
393
+ if (ctx.threadTypes) ctx.threadTypes[String(threadID)] = "dm";
394
+ if (callback) callback(null, e2eeWrapped);
395
+ else resolve(e2eeWrapped);
396
+ return promise;
397
+ } catch (e2eeTextErr) {
398
+ logger.warn(
399
+ "sendMessage",
400
+ "E2EE DM text failed, cascading to MQTT/HTTP: " + (e2eeTextErr.message || e2eeTextErr)
401
+ );
402
+ // fall through to MQTT / OldMessage
403
+ }
404
+ }
405
+
406
+ // ---- MQTT primary + OldMessage fallback ----
297
407
  try {
298
- var result = await sendViaMqtt(msg, threadID, replyToMessage);
408
+ var result = await sendViaMqtt(msg, threadID, replyToMessage, 18000);
409
+ if (result && !result.threadID) result.threadID = String(threadID);
299
410
  if (callback) callback(null, result);
300
411
  else resolve(result);
301
412
  } catch (mqttErr) {
302
413
  logger.warn("sendMessage", "MQTT failed, falling back to OldMessage: " + (mqttErr.message || mqttErr));
303
414
  try {
304
- var fbResult = await new Promise((res2, rej2) => {
305
- api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, isSingleUser);
306
- });
415
+ var fbResult = await sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser);
307
416
  if (callback) callback(null, fbResult);
308
417
  else resolve(fbResult);
309
418
  } catch (fbErr) {
@@ -315,4 +424,4 @@ module.exports = function (defaultFuncs, api, ctx) {
315
424
 
316
425
  return promise;
317
426
  };
318
- };
427
+ };
@@ -79,6 +79,8 @@ function extractPhotoUrl(photo, depth = 0) {
79
79
  "uri",
80
80
  "url",
81
81
  "image",
82
+ "full_image",
83
+ "viewer_image",
82
84
  "photo",
83
85
  "media",
84
86
  "cover_photo",
@@ -90,6 +92,32 @@ function extractPhotoUrl(photo, depth = 0) {
90
92
  return null;
91
93
  }
92
94
 
95
+
96
+ // [Hardened] Fallback: read the cover photo straight from the profile page HTML,
97
+ // used when none of the GraphQL doc_ids returned a cover (doc_ids rotate often).
98
+ function decodeJsonString(raw) {
99
+ try { return JSON.parse('"' + raw + '"'); } catch { return String(raw).replace(/\\\//g, "/"); }
100
+ }
101
+
102
+ function extractCoverFromHTML(html) {
103
+ if (!html || typeof html !== "string") return null;
104
+ const patterns = [
105
+ /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
106
+ /"profile_cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
107
+ /"coverPhoto"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
108
+ /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"url"\s*:\s*"([^"]+)"/,
109
+ /property="og:image"\s+content="(https:\/\/[^"]+fbcdn[^"]+)"/i,
110
+ /content="(https:\/\/[^"]+fbcdn[^"]+)"\s+property="og:image"/i
111
+ ];
112
+ for (const re of patterns) {
113
+ const m = html.match(re);
114
+ if (!m) continue;
115
+ const url = decodeJsonString(m[1]).replace(/&amp;/g, "&");
116
+ if (/^https?:\/\//i.test(url) && /(fbcdn|scontent)/i.test(url)) return url;
117
+ }
118
+ return null;
119
+ }
120
+
93
121
  function pickMeta(user) {
94
122
  let friendshipStatus = null;
95
123
  let gender = null;
@@ -114,38 +142,6 @@ function pickMeta(user) {
114
142
  return { friendshipStatus, gender, shortName };
115
143
  }
116
144
 
117
-
118
- function findCoverUri(node, depth = 0) {
119
- if (!node || depth > 12) return null;
120
- if (typeof node === "string" || typeof node !== "object") return null;
121
- for (const key of ["cover_photo", "coverPhoto", "profile_cover_photo", "timeline_cover_photo", "cover"]) {
122
- if (node[key] != null) {
123
- const direct = extractPhotoUrl(node[key]);
124
- if (direct) return direct;
125
- }
126
- }
127
- const list = Array.isArray(node) ? node : Object.keys(node).filter(k => k !== "extensions" && k !== "errors").map(k => node[k]);
128
- for (const child of list) {
129
- const found = findCoverUri(child, depth + 1);
130
- if (found) return found;
131
- }
132
- return null;
133
- }
134
-
135
- function coverFromHtml(html) {
136
- const text = String(html || "");
137
- const patterns = [
138
- /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
139
- /"profile_cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
140
- /"timeline_cover_photo"\s*:\s*\{[\s\S]{0,400}?"uri"\s*:\s*"([^"]+)"/
141
- ];
142
- for (const re of patterns) {
143
- const match = text.match(re);
144
- if (match && match[1]) return match[1].replace(/\\\//g, "/").replace(/\\u0026/g, "&");
145
- }
146
- return null;
147
- }
148
-
149
145
  function extractCoverPhoto(user) {
150
146
  const cover = user?.cover_photo;
151
147
  if (!cover) return null;
@@ -170,9 +166,13 @@ function normalizeUser(user) {
170
166
  firstName: meta.shortName || null,
171
167
  vanity,
172
168
  thumbSrc: extractProfilePicture(user),
173
- coverPhoto: extractPhotoUrl(
174
- user.cover_photo || user.coverPhoto || user.profile_cover_photo
175
- ),
169
+ coverPhoto:
170
+ extractPhotoUrl(user.cover_photo) ||
171
+ extractPhotoUrl(user.coverPhoto) ||
172
+ extractPhotoUrl(user.profile_cover_photo) ||
173
+ extractPhotoUrl(user.cover_photo_renderer) ||
174
+ extractCoverPhoto(user) ||
175
+ null,
176
176
  profileUrl: user.profile_url || user.url || null,
177
177
  gender: meta.gender || null,
178
178
  type: user.__typename || "User",
@@ -266,8 +266,6 @@ module.exports = function (defaultFuncs, api, ctx) {
266
266
  const parsed = toJSONMaybe(response) || response;
267
267
  const root = Array.isArray(parsed) ? parsed[0] : parsed;
268
268
  const normalized = normalizeUser(findUser(root));
269
- const cover = findCoverUri(parsed) || findCoverUri(root);
270
- if (normalized && cover && !normalized.coverPhoto) normalized.coverPhoto = cover;
271
269
  if (!normalized?.id) continue;
272
270
  if (!bestUser) {
273
271
  bestUser = normalized;
@@ -283,25 +281,30 @@ module.exports = function (defaultFuncs, api, ctx) {
283
281
  logger(`getUserInfoV2 ${doc.id}: ${error.message || error}`, "warn");
284
282
  }
285
283
  }
286
- return bestUser;
287
- }
288
-
289
- async function fetchCoverFromProfile(userID) {
290
- const urls = [
291
- `https://www.facebook.com/profile.php?id=${userID}`,
292
- `https://mbasic.facebook.com/profile.php?id=${userID}`
293
- ];
294
- for (const url of urls) {
295
- try {
296
- const response = await defaultFuncs.get(url, ctx.jar);
297
- const html = typeof response === "string" ? response : (response && (response.body || response.data)) || "";
298
- const cover = coverFromHtml(html);
299
- if (cover) return cover;
300
- } catch (error) {
301
- logger(`getUserInfoV2 cover page: ${error.message || error}`, "warn");
284
+ // [Hardened] GraphQL often omits cover; scrape profile HTML as last resort
285
+ if (bestUser && !bestUser.coverPhoto) {
286
+ const pages = [`https://www.facebook.com/profile.php?id=${id}`];
287
+ if (bestUser.vanity && bestUser.vanity !== id) {
288
+ pages.push(`https://www.facebook.com/${bestUser.vanity}`);
289
+ }
290
+ for (const url of pages) {
291
+ try {
292
+ const res = await defaultFuncs.get(url, ctx.jar, null, ctx);
293
+ const html = typeof res === "string" ? res : (res && res.data);
294
+ const cover = extractCoverFromHTML(html);
295
+ if (cover) {
296
+ bestUser.coverPhoto = cover;
297
+ break;
298
+ }
299
+ } catch (error) {
300
+ logger(`getUserInfoV2 cover html ${id}: ${error.message || error}`, "warn");
301
+ }
302
+ }
303
+ if (!bestUser.coverPhoto && process.env.FCA_COVER_DEBUG === "1") {
304
+ logger(`getUserInfoV2 cover ${id}: no cover found in GraphQL or profile HTML`, "warn");
302
305
  }
303
306
  }
304
- return null;
307
+ return bestUser;
305
308
  }
306
309
 
307
310
  async function fetchLegacy(userIDs) {
@@ -326,7 +329,7 @@ module.exports = function (defaultFuncs, api, ctx) {
326
329
  lastName: nameParts.length > 1? nameParts.slice(1).join(" ") : null,
327
330
  vanity: profile.vanity || null,
328
331
  thumbSrc: null,
329
- coverPhoto: extractPhotoUrl(profile.cover_photo || profile.coverPhoto || profile.cover || profile.profile_cover_photo),
332
+ coverPhoto: extractPhotoUrl(profile.cover_photo),
330
333
  profileUrl: profile.uri || `https://www.facebook.com/profile.php?id=${id}`,
331
334
  gender: profile.gender === 1? "male" : profile.gender === 2? "female" : "no specific gender",
332
335
  type: profile.type || "User",
@@ -373,11 +376,7 @@ module.exports = function (defaultFuncs, api, ctx) {
373
376
  for (let i = 0; i < ids.length; i++) {
374
377
  const id = ids[i];
375
378
  if (results[i].status === "fulfilled" && results[i].value?.id) {
376
- const user = results[i].value;
377
- if (!user.coverPhoto) {
378
- user.coverPhoto = await fetchCoverFromProfile(id);
379
- }
380
- retObj[id] = formatUser(user, id);
379
+ retObj[id] = formatUser(results[i].value, id);
381
380
  } else {
382
381
  needFallback.push(id);
383
382
  }
@@ -415,12 +414,13 @@ module.exports = function (defaultFuncs, api, ctx) {
415
414
  return callback(null, retObj);
416
415
  }
417
416
  })();
418
- return returnPromise;
417
+ return returnPromise;
419
418
  };
420
419
  };
421
420
 
422
421
  module.exports._private = {
423
422
  extractPhotoUrl,
423
+ extractCoverFromHTML,
424
424
  normalizeUser
425
425
  };
426
426
 
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Outgoing-message pacing.
5
+ *
6
+ * Every outgoing message (MQTT, OldMessage and E2EE) is serialised through one queue and is
7
+ * released no sooner than `delay` ms after the previous one. This avoids sending bursts that
8
+ * look like a script and that Facebook's rate limiting reacts to.
9
+ *
10
+ * FCA_NX_SEND_DELAY_MS base gap between sends, default 1500 (set 0 to disable)
11
+ * FCA_NX_SEND_JITTER_MS extra random 0..N ms added to each gap, default 600
12
+ * or at runtime: api.setSendDelay(ms, jitterMs)
13
+ */
14
+
15
+ const state = { last: 0, chain: Promise.resolve(), delay: null, jitter: null, stamps: [] };
16
+ // Hard ceiling per rolling minute (FCA_NX_SEND_MAX_PER_MIN, default 12, 0 = off).
17
+ function maxPerMin() {
18
+ const n = Number(process.env.FCA_NX_SEND_MAX_PER_MIN);
19
+ return Number.isFinite(n) && n >= 0 ? n : 12;
20
+ }
21
+
22
+ function readNum(v, d) {
23
+ const n = Number(v);
24
+ return Number.isFinite(n) && n >= 0 ? n : d;
25
+ }
26
+
27
+ function getDelay() {
28
+ return state.delay != null ? state.delay : readNum(process.env.FCA_NX_SEND_DELAY_MS, 1500);
29
+ }
30
+ function getJitter() {
31
+ return state.jitter != null ? state.jitter : readNum(process.env.FCA_NX_SEND_JITTER_MS, 600);
32
+ }
33
+
34
+ function setSendDelay(ms, jitterMs) {
35
+ if (ms != null) state.delay = readNum(ms, 1000);
36
+ if (jitterMs != null) state.jitter = readNum(jitterMs, 400);
37
+ return { delay: getDelay(), jitter: getJitter() };
38
+ }
39
+
40
+ /** Resolves when it is this caller's turn to send. */
41
+ function waitTurn() {
42
+ const delay = getDelay();
43
+ if (delay <= 0) return Promise.resolve();
44
+ const turn = state.chain.then(async () => {
45
+ const gap = delay + Math.floor(Math.random() * (getJitter() + 1));
46
+ const wait = state.last + gap - Date.now();
47
+ if (wait > 0) await new Promise(r => setTimeout(r, wait));
48
+ const cap = maxPerMin();
49
+ if (cap > 0) {
50
+ for (;;) {
51
+ const now = Date.now();
52
+ state.stamps = state.stamps.filter(t => now - t < 60000);
53
+ if (state.stamps.length < cap) break;
54
+ await new Promise(r => setTimeout(r, state.stamps[0] + 60000 - now + 50));
55
+ }
56
+ state.stamps.push(Date.now());
57
+ }
58
+ state.last = Date.now();
59
+ });
60
+ state.chain = turn.catch(() => {});
61
+ return turn;
62
+ }
63
+
64
+ module.exports = { waitTurn, setSendDelay };
@@ -71,9 +71,16 @@ function getTextEffectIds(message) {
71
71
  const rawIDs = Array.isArray(message.text_effect_ids)
72
72
  ? message.text_effect_ids
73
73
  : [message.text_effect_ids];
74
- return rawIDs
74
+ const ids = rawIDs
75
75
  .map(toTextEffectId)
76
76
  .filter(Boolean);
77
+ // [Hardened7] `effect: "fire"` / `textEffect` / `effectName` only produced the single id; the
78
+ // array form (text_effect_ids) stayed empty, and Messenger reads the array. Always send both.
79
+ if (!ids.length) {
80
+ const single = getTextEffectId(message);
81
+ if (single) ids.push(single);
82
+ }
83
+ return ids;
77
84
  }
78
85
 
79
86
  module.exports = {