fca-nx 6.7.9 → 6.8.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.9",
4
- "description": "Facebook Messenger API for Node.js \u2014 hardened sendMessage + listenMqtt (cascade fallback, soft MQTT, anti-reconnect-storm)",
3
+ "version": "6.8.0",
4
+ "description": "Facebook Messenger API for Node.js — hardened sendMessage + listenMqtt (cascade fallback, soft MQTT, anti-reconnect-storm)",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "exports": {
@@ -103,4 +103,4 @@
103
103
  "sqlite3"
104
104
  ]
105
105
  }
106
- }
106
+ }
@@ -247,11 +247,17 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
247
247
  missedPongs = 0;
248
248
  }
249
249
 
250
- try {
251
- ctx.mqttClient.publish("/ping", JSON.stringify({ timestamp: Date.now() }), { qos: 0 });
252
- logger("mqtt heartbeat sent", "debug");
253
- } catch (err) {
254
- logger(`mqtt heartbeat error: ${err.message}`, "warn");
250
+ // [Hardened7] The real Messenger client never publishes a custom "/ping" message; liveness is
251
+ // handled by MQTT keepalive (PINGREQ/PINGRESP, keepalive: 30 in connectMqtt) which updates
252
+ // lastPongTime via the "pong" event. A custom topic is an easy automation fingerprint, so it is
253
+ // opt-in only (FCA_NX_MQTT_APP_PING=1).
254
+ if (process.env.FCA_NX_MQTT_APP_PING === "1") {
255
+ try {
256
+ ctx.mqttClient.publish("/ping", JSON.stringify({ timestamp: Date.now() }), { qos: 0 });
257
+ logger("mqtt heartbeat sent", "debug");
258
+ } catch (err) {
259
+ logger(`mqtt heartbeat error: ${err.message}`, "warn");
260
+ }
255
261
  }
256
262
  }, hbEvery);
257
263
  }
@@ -383,6 +389,17 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
383
389
  return;
384
390
  }
385
391
  let d = getReconnectDelay();
392
+ // [Hardened7] flap limiter: >4 reconnects within 10 min means something is wrong (killed
393
+ // sessions, checkpoint, double instance). Hammering Facebook then is what triggers
394
+ // "multiple sessions"/automation restrictions, so wait 10 min instead.
395
+ const nowTs = Date.now();
396
+ ctx._reconnectStamps = (ctx._reconnectStamps || []).filter(t => nowTs - t < 10 * 60 * 1000);
397
+ ctx._reconnectStamps.push(nowTs);
398
+ if (ctx._reconnectStamps.length > 4) {
399
+ d = Math.max(d, 10 * 60 * 1000);
400
+ logger(`mqtt reconnect flapping (${ctx._reconnectStamps.length} in 10min) - cooling down ${Math.round(d / 60000)}min`, "error");
401
+ ctx._reconnectStamps = [];
402
+ }
386
403
  // Always add a little extra jitter on the scheduled path (even when d is small)
387
404
  if (d > 0) d += Math.floor(Math.random() * 1500);
388
405
  logger(d === 0 ? "mqtt reconnecting immediately" : `mqtt reconnect in ${d}ms`, "info");
@@ -570,7 +587,14 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
570
587
  }
571
588
 
572
589
  if (conf.cycleMs && conf.cycleMs > 0) {
573
- ctx._autoCycleTimer = setInterval(forceCycle, conf.cycleMs);
590
+ // [Hardened7] jittered (+-15%) so the cycle is not an exact clock
591
+ (function scheduleCycle() {
592
+ const j = conf.cycleMs * (0.85 + Math.random() * 0.3);
593
+ ctx._autoCycleTimer = setTimeout(function () {
594
+ if (!ctx._ending) forceCycle();
595
+ if (ctx._autoCycleTimer) scheduleCycle();
596
+ }, j);
597
+ })();
574
598
  logger(`mqtt auto-cycle enabled ${conf.cycleMs}ms`, "info");
575
599
  } else {
576
600
  logger("mqtt auto-cycle disabled", "info");
@@ -389,7 +389,22 @@ module.exports = function (defaultFuncs, api, ctx) {
389
389
  if (isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
390
390
  api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected()) {
391
391
  if (getTextEffectId(msg)) {
392
- logger.warn("sendMessage", "Text effects are not supported in E2EE DMs - sending plain text. Use a group chat for effects.");
392
+ // [Hardened8] Effects can't ride the E2EE bridge. Try MQTT once so the effect is kept;
393
+ // if that errors/times out, fall back to plain E2EE text so the reply is never lost.
394
+ // FCA_NX_E2EE_EFFECT_VIA_MQTT=0 disables the MQTT attempt (always plain E2EE text).
395
+ if (process.env.FCA_NX_E2EE_EFFECT_VIA_MQTT !== "0") {
396
+ try {
397
+ var fxResult = await sendViaMqtt(msg, threadID, replyToMessage, 8000);
398
+ if (fxResult && !fxResult.threadID) fxResult.threadID = String(threadID);
399
+ if (callback) callback(null, fxResult);
400
+ else resolve(fxResult);
401
+ return promise;
402
+ } catch (fxErr) {
403
+ logger.warn("sendMessage", "Effect via MQTT failed in E2EE DM, sending plain E2EE text: " + (fxErr.message || fxErr));
404
+ }
405
+ } else {
406
+ logger.warn("sendMessage", "Text effects are not supported in E2EE DMs - sending plain text. Use a group chat for effects.");
407
+ }
393
408
  }
394
409
  try {
395
410
  var e2eeText = await api.e2ee.sendMessage(
@@ -48,8 +48,7 @@ function createFallbackNamespaces(api) {
48
48
  getEmojiUrl: bindOptionalMethod(api, "getEmojiUrl"),
49
49
  resolvePhotoUrl: bindOptionalMethod(api, "resolvePhotoUrl"),
50
50
  uploadAttachment: bindOptionalMethod(api, "uploadAttachment"),
51
- forwardAttachment: bindOptionalMethod(api, "forwardAttachment"),
52
- bump: bindLiveMethod(api, "bump")
51
+ forwardAttachment: bindOptionalMethod(api, "forwardAttachment")
53
52
  }),
54
53
  threads: compactNamespace({
55
54
  createGroup: bindOptionalMethod(api, "createNewGroup"),
@@ -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 = {
@@ -1,134 +0,0 @@
1
- "use strict";
2
-
3
- // api.bump(threadID, options?, callback?)
4
- // Bumps a thread by sending a short message (default "👆") then optionally unsending it.
5
- //
6
- // options:
7
- // text: message to send (default "👆")
8
- // unsend: unsend after sending (default true)
9
- // delay: ms to wait before unsend (default 1500, clamped 500..10000)
10
- //
11
- // Returns: { threadID, messageID, unsent, unsendError? }
12
- //
13
- // Safety (hardened):
14
- // - per-thread cooldown 45s
15
- // - global cap 8 bumps / 60s
16
- // - rejects invalid threadID early
17
- // - never throws on unsend failure (message already bumped the thread)
18
-
19
- const COOLDOWN_MS = 45 * 1000;
20
- const WINDOW_MS = 60 * 1000;
21
- const MAX_PER_WINDOW = 8;
22
- const MIN_DELAY = 500;
23
- const MAX_DELAY = 10000;
24
-
25
- module.exports = function (defaultFuncs, api, ctx) {
26
- const lastBump = new Map();
27
- let recent = [];
28
-
29
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
30
-
31
- const send = (body, threadID) =>
32
- new Promise((resolve, reject) => {
33
- if (typeof api.sendMessage !== "function") {
34
- return reject(new Error("bump: api.sendMessage is not available"));
35
- }
36
- api.sendMessage({ body }, threadID, (err, info) => (err ? reject(err) : resolve(info)));
37
- });
38
-
39
- const unsend = (messageID, threadID) =>
40
- new Promise((resolve, reject) => {
41
- if (typeof api.unsendMessage !== "function") {
42
- return reject(new Error("bump: api.unsendMessage is not available"));
43
- }
44
- // support both (messageID, callback) and (messageID, threadID, callback) styles
45
- try {
46
- const ret = api.unsendMessage(messageID, threadID, (err) => (err ? reject(err) : resolve()));
47
- if (ret && typeof ret.then === "function") {
48
- ret.then(resolve, reject);
49
- }
50
- } catch (e) {
51
- // fallback single-arg form
52
- try {
53
- const ret2 = api.unsendMessage(messageID, (err) => (err ? reject(err) : resolve()));
54
- if (ret2 && typeof ret2.then === "function") {
55
- ret2.then(resolve, reject);
56
- }
57
- } catch (e2) {
58
- reject(e2 || e);
59
- }
60
- }
61
- });
62
-
63
- return function bump(threadID, options, callback) {
64
- if (typeof options === "function") {
65
- callback = options;
66
- options = {};
67
- }
68
- options = options || {};
69
-
70
- const promise = (async () => {
71
- if (threadID == null || threadID === "") {
72
- throw new Error("bump: threadID is required");
73
- }
74
- const tid = String(threadID).trim();
75
- if (!tid) throw new Error("bump: threadID is required");
76
-
77
- const now = Date.now();
78
-
79
- const last = lastBump.get(tid) || 0;
80
- if (now - last < COOLDOWN_MS) {
81
- throw new Error(
82
- `bump: cooldown active for this thread, wait ${Math.ceil((COOLDOWN_MS - (now - last)) / 1000)}s`
83
- );
84
- }
85
-
86
- recent = recent.filter((t) => now - t < WINDOW_MS);
87
- if (recent.length >= MAX_PER_WINDOW) {
88
- throw new Error("bump: global rate limit reached (max 8 / minute), try again shortly");
89
- }
90
-
91
- const text = options.text != null ? String(options.text) : "👆";
92
- const doUnsend = options.unsend !== false;
93
- let delay = Number.isFinite(options.delay) ? Number(options.delay) : 1500;
94
- if (delay < MIN_DELAY) delay = MIN_DELAY;
95
- if (delay > MAX_DELAY) delay = MAX_DELAY;
96
-
97
- const info = await send(text, tid);
98
- lastBump.set(tid, Date.now());
99
- recent.push(Date.now());
100
-
101
- // prune map if it grows too large (memory safety)
102
- if (lastBump.size > 5000) {
103
- const cutoff = Date.now() - COOLDOWN_MS * 2;
104
- for (const [k, v] of lastBump) {
105
- if (v < cutoff) lastBump.delete(k);
106
- }
107
- }
108
-
109
- const result = {
110
- threadID: tid,
111
- messageID: info && info.messageID ? String(info.messageID) : null,
112
- unsent: false
113
- };
114
-
115
- if (doUnsend && result.messageID) {
116
- await sleep(delay);
117
- try {
118
- await unsend(result.messageID, tid);
119
- result.unsent = true;
120
- } catch (e) {
121
- // Message was still sent (thread is bumped); unsend can fail e.g. in E2EE DMs.
122
- result.unsendError = e && e.message ? e.message : String(e);
123
- }
124
- }
125
-
126
- return result;
127
- })();
128
-
129
- if (typeof callback === "function") {
130
- promise.then((r) => callback(null, r), (e) => callback(e));
131
- }
132
- return promise;
133
- };
134
- };