fca-nx 6.7.8 → 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/module/login.js CHANGED
@@ -135,7 +135,7 @@ function login(loginData, options, callback) {
135
135
  forceLogin: false,
136
136
  autoMarkRead: false,
137
137
  autoReconnect: true,
138
- online: true,
138
+ online: false, // [Hardened5] always-online is a strong automation signal
139
139
  emitReady: false,
140
140
  // Single source of truth for the default identity - see src/utils/clientIdentity.js.
141
141
  // This used to be hard-coded independently here (Chrome/121), in
@@ -1174,7 +1174,8 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1174
1174
  firstListen: true,
1175
1175
  fb_dtsg,
1176
1176
  clientID: ((Math.random() * 2147483648) | 0).toString(16),
1177
- clientId: getFrom(html, '["MqttWebDeviceID",[],{"clientID":"', '"}') || "",
1177
+ // [Hardened5] never leave mqtt device id empty - empty rotates badly across reconnects
1178
+ clientId: getFrom(html, '["MqttWebDeviceID",[],{"clientID":"', '"}') || ((""+Math.random()).slice(2)+Date.now().toString(16)).slice(0, 16),
1178
1179
  wsReqNumber: 0,
1179
1180
  wsTaskNumber: 0,
1180
1181
  tasks: new Map(),
@@ -1383,7 +1384,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1383
1384
  }
1384
1385
  } catch (_) {}
1385
1386
  keepaliveLoop();
1386
- }, (15 + Math.random() * 10) * 60 * 1000);
1387
+ }, (18 + Math.random() * 14) * 60 * 1000); // [Hardened5] 18-32 min irregular keepalive
1387
1388
  if (t.unref) t.unref();
1388
1389
  })();
1389
1390
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.8",
4
- "description": "Facebook Messenger API for Node.js — anti-logout hardened (soft session recovery, keepalive, safe MQTT)",
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": {
@@ -8,8 +8,8 @@ const { getSessionIdentity } = require("../../../utils/clientIdentity");
8
8
 
9
9
  const DEFAULT_RECONNECT_DELAY_MS = 2000;
10
10
  const MAX_RECONNECT_DELAY_MS = 60000;
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)
11
+ const MAX_RECONNECT_ATTEMPTS = 8 // [Hardened5] hit long cooldown sooner instead of hammering; // cap consecutive network-failure reconnects; does not apply to confirmed auth failures (those never reconnect)
12
+ const MAX_RECONNECT_COOLDOWN_MS = 15 * 60 * 1000 /* [Hardened5] longer cooldown */; // after exhausting fast retries, wait this long before trying again (never give up permanently)
13
13
  const T_MS_WAIT_TIMEOUT_MS = 5000;
14
14
 
15
15
  // Exponential backoff with jitter, based on how many *consecutive* reconnect
@@ -39,7 +39,7 @@ function computeBackoff(ctx, baseMs) {
39
39
  return Math.min(fast + j, MAX_RECONNECT_DELAY_MS);
40
40
  }
41
41
  const exp = Math.min(baseMs * Math.pow(2, attempt), MAX_RECONNECT_DELAY_MS);
42
- const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
42
+ const jitter = Math.floor(Math.random() * Math.min(4000, exp * 0.4)); // [Hardened5]
43
43
  return Math.min(exp + jitter, MAX_RECONNECT_DELAY_MS);
44
44
  }
45
45
 
@@ -112,7 +112,12 @@ module.exports = function createListenMqtt(deps) {
112
112
  // never disagree about User-Agent / Accept-Language mid-session.
113
113
  const identity = getSessionIdentity(ctx);
114
114
 
115
- const chatOn = ctx.globalOptions.online;
115
+ // [Hardened5] stable device id for the whole process lifetime
116
+ if (!ctx.clientId || ctx.clientId === "") {
117
+ ctx.clientId = ctx.clientID || ((""+Math.random()).slice(2) + Date.now()).slice(0, 16);
118
+ }
119
+ // Prefer offline presence unless user explicitly set online:true
120
+ const chatOn = ctx.globalOptions.online === true;
116
121
  const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
117
122
  const username = {
118
123
  u: ctx.userID, s: sessionID, chat_on: chatOn, fg: false, d: ctx.clientId,
@@ -257,8 +262,11 @@ module.exports = function createListenMqtt(deps) {
257
262
  const topic = ctx.syncToken ? "/messenger_sync_get_diffs" : "/messenger_sync_create_queue";
258
263
  if (ctx.syncToken) { queue.last_seq_id = ctx.lastSeqId; queue.sync_token = ctx.syncToken; }
259
264
  mqttClient.publish(topic, JSON.stringify(queue), { qos: 1, retain: false });
260
- mqttClient.publish("/foreground_state", JSON.stringify({ foreground: chatOn }), { qos: 1 });
261
- mqttClient.publish("/set_client_settings", JSON.stringify({ make_user_available_when_in_foreground: true }), { qos: 1 });
265
+ // [Hardened5] only claim foreground/available when online:true
266
+ mqttClient.publish("/foreground_state", JSON.stringify({ foreground: !!chatOn }), { qos: 1 });
267
+ if (chatOn) {
268
+ mqttClient.publish("/set_client_settings", JSON.stringify({ make_user_available_when_in_foreground: true }), { qos: 1 });
269
+ }
262
270
  let rTimeout = setTimeout(function () {
263
271
  rTimeout = null;
264
272
  if (ctx._ending) {
@@ -194,7 +194,7 @@ module.exports = function createGetSeqID(deps) {
194
194
 
195
195
  return function getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount = 0) {
196
196
  const MAX_RETRIES = 5;
197
- const RETRY_DELAY = 3000; // [Hardened] slower + more attempts before any logout decision
197
+ const RETRY_DELAY = 5000; // [Hardened5] slower retries reduce auth race / checkpoint pressure
198
198
  ctx.t_mqttCalled = false;
199
199
 
200
200
  // Ensure essential tokens are injected into GraphQL Batch Payload
@@ -349,7 +349,7 @@ module.exports = function createGetSeqID(deps) {
349
349
  }
350
350
  } catch (_) {}
351
351
  // Re-attempt getSeqID after long cooldown without marking account inactive
352
- const softDelay = Math.min(5 * 60 * 1000, 60000 * (retryCount + 1));
352
+ const softDelay = Math.min(15 * 60 * 1000, 90000 * (retryCount + 1)); // [Hardened5] longer soft cooldown
353
353
  setTimeout(() => {
354
354
  if (ctx._ending) return;
355
355
  logger("getSeqID: soft recovery timer fired - retrying getSeqID", "warn");
@@ -372,7 +372,7 @@ module.exports = function createGetSeqID(deps) {
372
372
  setTimeout(() => {
373
373
  if (ctx._ending) return;
374
374
  try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
375
- }, 60000);
375
+ }, 120000); // [Hardened5] 2min soft recover for non-auth errors
376
376
  });
377
377
  };
378
378
  };
@@ -20,14 +20,14 @@ const getTaskResponseData = require("./core/getTaskResponseData");
20
20
  const createEmitAuth = require("./core/emitAuth");
21
21
  const createMiddlewareSystem = require("./middleware");
22
22
 
23
- const CYCLE_MS_DEFAULT = 2 * 60 * 60 * 1000; // [Hardened] 2h cycle - less session churn / multi-login risk
24
- const RECONNECT_DELAY_MS_DEFAULT = 5000;
23
+ const CYCLE_MS_DEFAULT = 6 * 60 * 60 * 1000; // [Hardened5] 6h cycle - minimize session churn
24
+ const RECONNECT_DELAY_MS_DEFAULT = 8000; // [Hardened5]
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
+ const MAX_MQTT_RECONNECT_COOLDOWN_MS = 15 * 60 * 1000 /* [Hardened5] longer cooldown */; // long cooldown after exhausting fast retries - never give up permanently
28
28
  const MAX_MQTT_RECONNECT_ATTEMPTS = 10;
29
- const HEARTBEAT_INTERVAL_MS = 30000;
30
- const HEARTBEAT_TIMEOUT_MS = 10000;
29
+ const HEARTBEAT_INTERVAL_MS = 45000 // [Hardened5];
30
+ const HEARTBEAT_TIMEOUT_MS = 15000 // [Hardened5];
31
31
 
32
32
  const parseDelta = createParseDelta({ parseAndCheckLogin });
33
33
  const emitAuth = createEmitAuth({ logger });
@@ -121,7 +121,8 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
121
121
  }
122
122
  const base = conf.reconnectDelayMs || RECONNECT_DELAY_MS_DEFAULT;
123
123
  const exp = Math.min(base * Math.pow(2, reconnectAttempts), MAX_MQTT_RECONNECT_DELAY_MS);
124
- const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
124
+ // [Hardened5] wider jitter (20-40%) so reconnect timing looks less scripted
125
+ const jitter = Math.floor(Math.random() * Math.min(4000, exp * 0.4));
125
126
  return Math.min(exp + jitter, MAX_MQTT_RECONNECT_DELAY_MS);
126
127
  }
127
128
 
@@ -130,6 +131,11 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
130
131
  logger("mqtt getSeqID skipped - ending", "warn");
131
132
  return Promise.resolve();
132
133
  }
134
+ // [Hardened6] single-flight: avoid parallel getSeqID (looks like multi-session)
135
+ if (ctx._getSeqIDInFlight) {
136
+ logger("mqtt getSeqID skipped - already in flight", "warn");
137
+ return ctx._getSeqIDInFlight;
138
+ }
133
139
 
134
140
  const form = {
135
141
  av: ctx.globalOptions.pageID || ctx.userID,
@@ -150,7 +156,11 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
150
156
  };
151
157
 
152
158
  logger("mqtt getSeqID call", "info");
153
- return getSeqIDFactory(defaultFuncs, api, ctx, globalCallback, form)
159
+ const _seqP = Promise.resolve().then(function () {
160
+ return getSeqIDFactory(defaultFuncs, api, ctx, globalCallback, form);
161
+ }).finally(function () { ctx._getSeqIDInFlight = null; });
162
+ ctx._getSeqIDInFlight = _seqP;
163
+ return _seqP
154
164
  .then(() => {
155
165
  logger("mqtt getSeqID done", "info");
156
166
  ctx._cycling = false;
@@ -211,6 +221,10 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
211
221
 
212
222
  lastPongTime = Date.now();
213
223
 
224
+ // [Hardened6] jittered heartbeat interval so pings are not perfectly periodic
225
+ const hbBase = conf.heartbeatInterval || HEARTBEAT_INTERVAL_MS;
226
+ const hbEvery = hbBase + Math.floor(Math.random() * Math.min(8000, hbBase * 0.25));
227
+ let missedPongs = 0;
214
228
  heartbeatTimer = setInterval(() => {
215
229
  if (!isConnected()) {
216
230
  stopHeartbeat();
@@ -218,19 +232,34 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
218
232
  }
219
233
 
220
234
  const now = Date.now();
221
- if (now - lastPongTime > (conf.heartbeatTimeout || HEARTBEAT_TIMEOUT_MS) * 5) { // [Hardened] more tolerant before force cycle
222
- logger("mqtt heartbeat: no response, forcing reconnect", "warn");
223
- forceCycle();
224
- return;
235
+ const limit = (conf.heartbeatTimeout || HEARTBEAT_TIMEOUT_MS) * 5;
236
+ if (now - lastPongTime > limit) {
237
+ missedPongs += 1;
238
+ // Require 2 consecutive misses before forceCycle (avoid one delayed pong killing session)
239
+ if (missedPongs >= 2) {
240
+ logger("mqtt heartbeat: no response x2, forcing reconnect", "warn");
241
+ missedPongs = 0;
242
+ forceCycle();
243
+ return;
244
+ }
245
+ logger("mqtt heartbeat: pong late, waiting one more cycle", "warn");
246
+ } else {
247
+ missedPongs = 0;
225
248
  }
226
249
 
227
- try {
228
- ctx.mqttClient.publish("/ping", JSON.stringify({ timestamp: Date.now() }), { qos: 0 });
229
- logger("mqtt heartbeat sent", "debug");
230
- } catch (err) {
231
- 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
+ }
232
261
  }
233
- }, conf.heartbeatInterval || HEARTBEAT_INTERVAL_MS);
262
+ }, hbEvery);
234
263
  }
235
264
 
236
265
  function stopHeartbeat() {
@@ -354,15 +383,29 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
354
383
 
355
384
  function delayedReconnect() {
356
385
  if (ctx._ending) return;
357
- const d = getReconnectDelay();
358
- logger(d === 0 ? "mqtt reconnecting immediately" : `mqtt reconnect in ${d}ms`, "info");
359
-
386
+ // [Hardened6] debounce: if a reconnect is already scheduled, keep it
360
387
  if (ctx._reconnectTimer) {
361
- clearTimeout(ctx._reconnectTimer);
362
- ctx._reconnectTimer = null;
388
+ logger("mqtt reconnect already scheduled - debounce", "warn");
389
+ return;
363
390
  }
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
+ }
403
+ // Always add a little extra jitter on the scheduled path (even when d is small)
404
+ if (d > 0) d += Math.floor(Math.random() * 1500);
405
+ logger(d === 0 ? "mqtt reconnecting immediately" : `mqtt reconnect in ${d}ms`, "info");
364
406
 
365
407
  ctx._reconnectTimer = setTimeout(() => {
408
+ ctx._reconnectTimer = null;
366
409
  if (!ctx._ending) {
367
410
  isReconnecting = false;
368
411
  getSeqIDWrapper();
@@ -370,7 +413,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
370
413
  }, d);
371
414
  }
372
415
 
373
- function forceCycle() /* hardened */ {
416
+ function forceCycle() /* hardened6 */ {
374
417
  if (ctx._cycling) {
375
418
  logger("mqtt force cycle already in progress", "warn");
376
419
  return;
@@ -379,6 +422,13 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
379
422
  logger("mqtt force cycle skipped - ending", "warn");
380
423
  return;
381
424
  }
425
+ // [Hardened6] minimum 90s between forced cycles to avoid reconnect storms
426
+ const now = Date.now();
427
+ if (ctx._lastForceCycleAt && (now - ctx._lastForceCycleAt) < 90000) {
428
+ logger("mqtt force cycle skipped - too soon since last cycle", "warn");
429
+ return;
430
+ }
431
+ ctx._lastForceCycleAt = now;
382
432
 
383
433
  ctx._cycling = true;
384
434
  ctx._ending = true;
@@ -386,14 +436,21 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
386
436
 
387
437
  stopHeartbeat();
388
438
 
439
+ const finish = () => {
440
+ ctx._ending = false;
441
+ ctx._cycling = false;
442
+ if (conf.reconnectAfterStop || conf.autoReconnect !== false) {
443
+ delayedReconnect();
444
+ }
445
+ };
446
+
389
447
  unsubAll(() => {
390
- endQuietly(() => {
391
- ctx._ending = false;
392
- ctx._cycling = false;
393
- if (conf.reconnectAfterStop || conf.autoReconnect !== false) {
394
- delayedReconnect();
395
- }
396
- });
448
+ try {
449
+ endQuietly(finish);
450
+ } catch (e) {
451
+ logger(`mqtt force cycle endQuietly error: ${e && e.message ? e.message : e}`, "warn");
452
+ finish();
453
+ }
397
454
  });
398
455
  }
399
456
 
@@ -530,7 +587,14 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
530
587
  }
531
588
 
532
589
  if (conf.cycleMs && conf.cycleMs > 0) {
533
- 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
+ })();
534
598
  logger(`mqtt auto-cycle enabled ${conf.cycleMs}ms`, "info");
535
599
  } else {
536
600
  logger("mqtt auto-cycle disabled", "info");
@@ -1,5 +1,10 @@
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
10
  var { getTextEffectId, getTextEffectIds } = require("../../utils/textEffects");
@@ -31,19 +36,15 @@ function buildMentionData(msg, baseBody) {
31
36
  var ids = [], offsets = [], lengths = [], types = [];
32
37
  for (var i = 0; i < msg.mentions.length; i++) {
33
38
  var mention = msg.mentions[i];
34
- // Ensure tag always has @ prefix — Facebook counts @ in both offset and length
35
39
  var tag = String(mention.tag || "");
36
40
  if (tag && !tag.startsWith("@")) tag = "@" + tag;
37
41
  var fromIndex = Number.isInteger(mention.fromIndex) ? mention.fromIndex : 0;
38
42
  var offset = baseBody.indexOf(tag, fromIndex);
39
- if (offset === -1) {
40
- // Fallback: search for bare name without @
41
- offset = baseBody.indexOf(tag.slice(1), fromIndex);
42
- }
43
+ if (offset === -1) offset = baseBody.indexOf(tag.slice(1), fromIndex);
43
44
  if (offset < 0) offset = 0;
44
45
  ids.push(String(mention.id || 0));
45
46
  offsets.push(offset);
46
- lengths.push(tag.length); // includes @ — matches Facebook's expectation
47
+ lengths.push(tag.length);
47
48
  types.push("p");
48
49
  }
49
50
  return {
@@ -72,52 +73,87 @@ function extractIdsFromPayload(payload) {
72
73
  }
73
74
 
74
75
  function publishLsRequestWithAck(mqttClient, content, requestId, timeout) {
75
- timeout = timeout || 15000;
76
- return new Promise((resolve, reject) => {
77
- var timer = setTimeout(() => {
78
- mqttClient.removeListener('message', onMessage);
79
- reject(new Error('MQTT sendMessage timed out after ' + timeout + 'ms'));
76
+ timeout = timeout || 18000;
77
+ return new Promise(function (resolve, reject) {
78
+ if (!mqttClient || typeof mqttClient.publish !== "function") {
79
+ return reject(new Error("MQTT client not available"));
80
+ }
81
+
82
+ var settled = false;
83
+ function done(err, val) {
84
+ if (settled) return;
85
+ settled = true;
86
+ try { clearTimeout(timer); } catch (_) { }
87
+ try { mqttClient.removeListener("message", onMessage); } catch (_) { }
88
+ if (err) reject(err);
89
+ else resolve(val);
90
+ }
91
+
92
+ var timer = setTimeout(function () {
93
+ done(new Error("MQTT sendMessage timed out after " + timeout + "ms"));
80
94
  }, timeout);
81
95
 
82
96
  function onMessage(topic, message) {
83
- if (topic !== '/ls_resp') return;
97
+ if (topic !== "/ls_resp") return;
84
98
  try {
85
99
  var data = JSON.parse(message.toString());
86
- if (String(data.request_id) === String(requestId)) {
87
- clearTimeout(timer);
88
- mqttClient.removeListener('message', onMessage);
89
- var extracted = extractIdsFromPayload(data.payload ? JSON.parse(data.payload) : {});
90
- resolve({ threadID: extracted.threadID, messageID: extracted.messageID });
91
- }
100
+ if (String(data.request_id) !== String(requestId)) return;
101
+ var extracted = extractIdsFromPayload(data.payload ? JSON.parse(data.payload) : {});
102
+ done(null, {
103
+ threadID: extracted.threadID,
104
+ messageID: extracted.messageID
105
+ });
92
106
  } catch (_) { }
93
107
  }
94
108
 
95
- mqttClient.on('message', onMessage);
96
- mqttClient.publish('/ls_req', JSON.stringify(content), { qos: 1 }, err => {
97
- if (err) {
98
- clearTimeout(timer);
99
- mqttClient.removeListener('message', onMessage);
100
- reject(err);
109
+ mqttClient.on("message", onMessage);
110
+ try {
111
+ mqttClient.publish("/ls_req", JSON.stringify(content), { qos: 1 }, function (err) {
112
+ if (err) done(err);
113
+ });
114
+ } catch (pubErr) {
115
+ done(pubErr);
116
+ }
117
+ });
118
+ }
119
+
120
+ /** Wait briefly for MQTT to become ready (reconnect in progress). */
121
+ function waitForMqtt(ctx, maxMs) {
122
+ maxMs = maxMs || 4000;
123
+ return new Promise(function (resolve) {
124
+ var client = ctx.mqttClient || global.mqttClient;
125
+ if (client && client.connected) return resolve(client);
126
+ var start = Date.now();
127
+ var iv = setInterval(function () {
128
+ var c = ctx.mqttClient || global.mqttClient;
129
+ if (c && c.connected) {
130
+ clearInterval(iv);
131
+ return resolve(c);
101
132
  }
102
- });
133
+ if (Date.now() - start >= maxMs) {
134
+ clearInterval(iv);
135
+ return resolve(c || null);
136
+ }
137
+ }, 200);
103
138
  });
104
139
  }
105
140
 
106
141
  module.exports = function (defaultFuncs, api, ctx) {
107
- var uploadAttachmentFn = require('../messaging/uploadAttachment')(defaultFuncs, api, ctx);
142
+ var uploadAttachmentFn = require("../messaging/uploadAttachment")(defaultFuncs, api, ctx);
108
143
 
109
144
  async function uploadAttachments(attachments) {
110
145
  if (!Array.isArray(attachments)) attachments = [attachments];
111
146
  return uploadAttachmentFn(attachments);
112
147
  }
113
148
 
114
- async function sendViaMqtt(msg, threadID, replyToMessage) {
115
- var mqttClient = ctx.mqttClient || global.mqttClient;
116
- if (!mqttClient) throw new Error('MQTT client not available');
149
+ async function sendViaMqtt(msg, threadID, replyToMessage, ackTimeout) {
150
+ var mqttClient = await waitForMqtt(ctx, 4000);
151
+ if (!mqttClient || !mqttClient.connected) {
152
+ throw new Error("MQTT client not available");
153
+ }
117
154
 
118
155
  var baseBody = msg.body != null ? String(msg.body) : "";
119
156
  var requestId = Math.floor(100 + Math.random() * 900);
120
- var epoch = (BigInt(Date.now()) << 22n).toString();
121
157
 
122
158
  var payload0 = {
123
159
  thread_id: String(threadID),
@@ -142,13 +178,23 @@ module.exports = function (defaultFuncs, api, ctx) {
142
178
  var effectArray = getTextEffectIds(msg);
143
179
  if (effectArray.length) payload0.text_effect_ids = effectArray;
144
180
 
145
- if (msg.sticker) { payload0.send_type = 2; payload0.sticker_id = msg.sticker; }
146
- if (msg.emoji) { payload0.send_type = 1; payload0.text = msg.emoji; payload0.hot_emoji_size = toEmojiSize(msg.emojiSize); }
181
+ if (msg.sticker) {
182
+ payload0.send_type = 2;
183
+ payload0.sticker_id = msg.sticker;
184
+ }
185
+ if (msg.emoji) {
186
+ payload0.send_type = 1;
187
+ payload0.text = msg.emoji;
188
+ payload0.hot_emoji_size = toEmojiSize(msg.emojiSize);
189
+ }
147
190
 
148
191
  if (msg.location && msg.location.latitude != null && msg.location.longitude != null) {
149
192
  payload0.send_type = 1;
150
193
  payload0.location_data = {
151
- coordinates: { latitude: msg.location.latitude, longitude: msg.location.longitude },
194
+ coordinates: {
195
+ latitude: msg.location.latitude,
196
+ longitude: msg.location.longitude
197
+ },
152
198
  is_current_location: Boolean(msg.location.current),
153
199
  is_live_location: Boolean(msg.location.live)
154
200
  };
@@ -180,14 +226,15 @@ module.exports = function (defaultFuncs, api, ctx) {
180
226
  if (msg.forwardAttachmentIds && msg.forwardAttachmentIds.length) {
181
227
  payload0.attachment_fbids = payload0.attachment_fbids.concat(msg.forwardAttachmentIds.map(String));
182
228
  }
183
-
184
229
  if (toUpload.length) {
185
230
  var uploaded = await uploadAttachments(toUpload);
186
231
  for (var u of uploaded) {
187
232
  if (!u) continue;
188
233
  var fbid = u.image_id || u.video_id || u.audio_id || u.file_id || u.sticker_id || u.gif_id;
189
234
  if (!fbid) {
190
- var firstKey = Object.keys(u).find(function(k) { return u[k] && /^\d+$/.test(String(u[k])); });
235
+ var firstKey = Object.keys(u).find(function (k) {
236
+ return u[k] && /^\d+$/.test(String(u[k]));
237
+ });
191
238
  if (firstKey) fbid = u[firstKey];
192
239
  }
193
240
  if (fbid) payload0.attachment_fbids.push(String(fbid));
@@ -198,14 +245,14 @@ module.exports = function (defaultFuncs, api, ctx) {
198
245
 
199
246
  var tasks = [
200
247
  {
201
- label: '46',
248
+ label: "46",
202
249
  payload: JSON.stringify(payload0),
203
250
  queue_name: String(threadID),
204
251
  task_id: 400,
205
252
  failure_count: null
206
253
  },
207
254
  {
208
- label: '21',
255
+ label: "21",
209
256
  payload: JSON.stringify({
210
257
  thread_id: String(threadID),
211
258
  last_read_watermark_ts: Date.now(),
@@ -218,57 +265,100 @@ module.exports = function (defaultFuncs, api, ctx) {
218
265
  ];
219
266
 
220
267
  var content = {
221
- app_id: '2220391788200892',
268
+ app_id: "2220391788200892",
222
269
  payload: JSON.stringify({
223
270
  tasks: tasks,
224
- epoch_id: epoch,
225
- version_id: '24804310205905615',
226
- data_trace_id: '#' + Buffer.from(String(Math.random())).toString('base64').replace(/=+$/, '')
271
+ epoch_id: (BigInt(Date.now()) << 22n).toString(),
272
+ version_id: "24804310205905615"
227
273
  }),
228
274
  request_id: requestId,
229
275
  type: 3
230
276
  };
231
277
 
232
- return publishLsRequestWithAck(mqttClient, content, requestId, 15000);
278
+ // Soft retry once on timeout (common during MQTT flap)
279
+ var timeout = ackTimeout || 18000;
280
+ try {
281
+ return await publishLsRequestWithAck(mqttClient, content, requestId, timeout);
282
+ } catch (firstErr) {
283
+ var msgErr = firstErr && firstErr.message ? firstErr.message : String(firstErr);
284
+ if (!/timed out/i.test(msgErr)) throw firstErr;
285
+ logger.warn("sendMessage", "MQTT ack timeout - one soft retry");
286
+ await new Promise(function (r) { setTimeout(r, 800 + Math.floor(Math.random() * 700)); });
287
+ mqttClient = await waitForMqtt(ctx, 3000);
288
+ if (!mqttClient || !mqttClient.connected) throw firstErr;
289
+ // new request id for retry
290
+ requestId = Math.floor(100 + Math.random() * 900);
291
+ content.request_id = requestId;
292
+ return await publishLsRequestWithAck(mqttClient, content, requestId, Math.min(timeout + 5000, 25000));
293
+ }
294
+ }
295
+
296
+ async function sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser) {
297
+ if (typeof api.OldMessage !== "function") {
298
+ throw new Error("OldMessage fallback is not available");
299
+ }
300
+ return new Promise(function (res2, rej2) {
301
+ api.OldMessage(msg, threadID, function (err2, data2) {
302
+ if (err2) rej2(err2);
303
+ else res2(data2);
304
+ }, replyToMessage, isSingleUser);
305
+ });
233
306
  }
234
307
 
235
308
  return async function sendMessage(msg, threadID, callback, replyToMessage, isSingleUser) {
236
309
  if (typeof msg === "string") msg = { body: msg };
237
- if (typeof callback !== "function") { callback = null; }
310
+ if (typeof callback !== "function") callback = null;
238
311
 
239
312
  var resolve, reject;
240
- var promise = new Promise((res, rej) => { resolve = res; reject = rej; });
313
+ var promise = new Promise(function (res, rej) {
314
+ resolve = res;
315
+ reject = rej;
316
+ });
241
317
 
242
318
  for (var key in msg) {
243
319
  if (!ALLOWED[key]) {
244
- var err = { error: "sendMessage: Unknown property '" + key + "'" };
320
+ var err = new Error("Message key '" + key + "' is not allowed.");
245
321
  if (callback) callback(err);
246
322
  else reject(err);
247
323
  return promise;
248
324
  }
249
325
  }
250
326
 
327
+ if (!threadID && threadID !== 0) {
328
+ var tidErr = new Error("threadID is required");
329
+ if (callback) callback(tidErr);
330
+ else reject(tidErr);
331
+ return promise;
332
+ }
333
+
251
334
  // Auto-detect isSingleUser from ctx.threadTypes if not explicitly provided.
252
- // parseDelta in listenMqtt.js populates ctx.threadTypes[senderID] = 'dm' | 'group'
253
335
  if (isSingleUser === undefined && ctx.threadTypes) {
254
- isSingleUser = ctx.threadTypes[String(threadID)] === 'dm';
336
+ isSingleUser = ctx.threadTypes[String(threadID)] === "dm";
255
337
  }
256
338
 
257
- // DM attachment sends — skip MQTT entirely.
258
- // For E2EE DMs: route through the E2EE bridge (Noise WebSocket, Signal Protocol).
259
- // Facebook strips attachment_fbids from MQTT messages in E2EE threads
260
- // (can't re-encrypt CDN attachments on the fly), so MQTT silently drops them.
261
- // The vendor's client.sendImage/sendVideo/sendAudio encrypts the file data
262
- // and sends via the Noise WebSocket — the only path that actually delivers
263
- // attachments in E2EE threads.
264
- // For non-E2EE DMs: use OldMessage.
265
- // /messaging/send/ with other_user_fbid routing works for plain DMs.
266
- // (For E2EE DMs it returns 404 because the endpoint is deprecated for those.)
339
+ // Empty payload guard (except sticker/attachment/emoji/location)
340
+ var hasContent =
341
+ (msg.body != null && String(msg.body).length > 0) ||
342
+ msg.attachment || msg.sticker || msg.emoji || msg.location ||
343
+ (msg.forwardAttachmentIds && msg.forwardAttachmentIds.length);
344
+ if (!hasContent) {
345
+ var emptyErr = new Error("Message must have body, attachment, sticker, emoji or location");
346
+ if (callback) callback(emptyErr);
347
+ else reject(emptyErr);
348
+ return promise;
349
+ }
350
+
351
+ // Pace all outgoing traffic (anti-burst)
352
+ await waitTurn();
353
+
354
+ // ---- DM attachment path (skip MQTT) ----
355
+ // E2EE DMs: bridge only (MQTT strips attachment_fbids).
356
+ // Plain DMs: OldMessage (/messaging/send/ other_user_fbid).
267
357
  if (isSingleUser && msg.attachment) {
268
358
  var useE2EE = api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected();
269
359
  if (useE2EE) {
270
360
  try {
271
- var e2eeResult = await api.e2ee.sendMessage(String(threadID), msg, replyToMessage);
361
+ var e2eeResult = await api.e2ee.sendMessage(String(threadID), msg, replyToMessage || msg.replyToMessage);
272
362
  var wrapped = e2eeResult && e2eeResult.messageId
273
363
  ? { threadID: String(threadID), messageID: String(e2eeResult.messageId) }
274
364
  : e2eeResult;
@@ -280,15 +370,12 @@ module.exports = function (defaultFuncs, api, ctx) {
280
370
  else reject(e2eeErr);
281
371
  }
282
372
  } else {
283
- await waitTurn();
284
373
  try {
285
- var omResult = await new Promise((res2, rej2) => {
286
- api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, true);
287
- });
374
+ var omResult = await sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser);
288
375
  if (callback) callback(null, omResult);
289
376
  else resolve(omResult);
290
377
  } catch (omErr) {
291
- logger.error("sendMessage", "DM attachment via OldMessage failed: " + (omErr.error || omErr.message || omErr));
378
+ logger.error("sendMessage", "DM attachment OldMessage failed: " + (omErr.message || omErr));
292
379
  if (callback) callback(omErr);
293
380
  else reject(omErr);
294
381
  }
@@ -296,42 +383,61 @@ module.exports = function (defaultFuncs, api, ctx) {
296
383
  return promise;
297
384
  }
298
385
 
299
- // [Fixed by xalman] Text replies to a DM whose latest activity was E2EE must go through the
300
- // E2EE bridge. MQTT cannot deliver into an end-to-end encrypted chat: it waited 15s for an
301
- // ack that never came, so every command that calls api.sendMessage() directly looked dead
302
- // in inbox. (Group chats and normal MQTT DMs are unchanged.)
386
+ // ---- E2EE text path with cascade fallback ----
387
+ // Text replies to E2EE DMs should use the bridge; if it fails, try MQTT then OldMessage
388
+ // instead of hard-failing (Hardened6).
303
389
  if (isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
304
390
  api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected()) {
305
- // [Hardened] Text effects unsupported on E2EE path — warn once then send plain text
306
- if (typeof getTextEffectId === "function" && getTextEffectId(msg)) {
307
- logger.warn("sendMessage", "Text effects are not supported in E2EE DMs - sending plain text. Use a group chat for effects.");
391
+ if (getTextEffectId(msg)) {
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
+ }
308
408
  }
309
409
  try {
310
- var e2eeText = await api.e2ee.sendMessage(String(threadID), { body: msg.body != null ? String(msg.body) : "" }, replyToMessage || msg.replyToMessage);
410
+ var e2eeText = await api.e2ee.sendMessage(
411
+ String(threadID),
412
+ { body: msg.body != null ? String(msg.body) : "" },
413
+ replyToMessage || msg.replyToMessage
414
+ );
311
415
  var e2eeWrapped = e2eeText && e2eeText.messageId
312
416
  ? { threadID: String(threadID), messageID: String(e2eeText.messageId) }
313
417
  : e2eeText;
418
+ if (ctx.threadTypes) ctx.threadTypes[String(threadID)] = "dm";
314
419
  if (callback) callback(null, e2eeWrapped);
315
420
  else resolve(e2eeWrapped);
421
+ return promise;
316
422
  } catch (e2eeTextErr) {
317
- logger.error("sendMessage", "E2EE DM text send failed: " + (e2eeTextErr.message || e2eeTextErr));
318
- if (callback) callback(e2eeTextErr);
319
- else reject(e2eeTextErr);
423
+ logger.warn(
424
+ "sendMessage",
425
+ "E2EE DM text failed, cascading to MQTT/HTTP: " + (e2eeTextErr.message || e2eeTextErr)
426
+ );
427
+ // fall through to MQTT / OldMessage
320
428
  }
321
- return promise;
322
429
  }
323
430
 
324
- await waitTurn();
431
+ // ---- MQTT primary + OldMessage fallback ----
325
432
  try {
326
- var result = await sendViaMqtt(msg, threadID, replyToMessage);
433
+ var result = await sendViaMqtt(msg, threadID, replyToMessage, 18000);
434
+ if (result && !result.threadID) result.threadID = String(threadID);
327
435
  if (callback) callback(null, result);
328
436
  else resolve(result);
329
437
  } catch (mqttErr) {
330
438
  logger.warn("sendMessage", "MQTT failed, falling back to OldMessage: " + (mqttErr.message || mqttErr));
331
439
  try {
332
- var fbResult = await new Promise((res2, rej2) => {
333
- api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, isSingleUser);
334
- });
440
+ var fbResult = await sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser);
335
441
  if (callback) callback(null, fbResult);
336
442
  else resolve(fbResult);
337
443
  } catch (fbErr) {
@@ -343,4 +449,4 @@ module.exports = function (defaultFuncs, api, ctx) {
343
449
 
344
450
  return promise;
345
451
  };
346
- };
452
+ };
@@ -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"),
@@ -20,12 +20,12 @@
20
20
  */
21
21
 
22
22
  // One version pin used everywhere. Bump this in one place when needed.
23
- const CHROME_VERSION = "139.0.0.0";
23
+ const CHROME_VERSION = "131.0.6778.205"; // [Hardened5] realistic build, not x.0.0.0 (bot-looking)
24
24
  const CHROME_MAJOR = CHROME_VERSION.split(".")[0];
25
25
 
26
26
  const DEFAULT_IDENTITY = Object.freeze({
27
27
  userAgent: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${CHROME_VERSION} Safari/537.36`,
28
- acceptLanguage: "en-US,en;q=0.9",
28
+ acceptLanguage: "en-US,en;q=0.9,bn;q=0.8", // mild secondary locale is common in BD/SA users
29
29
  secChUa: `"Chromium";v="${CHROME_MAJOR}", "Not;A=Brand";v="24", "Google Chrome";v="${CHROME_MAJOR}"`,
30
30
  secChUaMobile: "?0",
31
31
  secChUaPlatform: '"Windows"',
@@ -14,6 +14,22 @@ const {
14
14
  isPairArrayList,
15
15
  } = require("./helpers");
16
16
 
17
+
18
+ // [Hardened5] mild global spacing between FB Graph/API posts to avoid bursty bot patterns.
19
+ // Does NOT block forever - only adds a small delay when calls are very close together.
20
+ let __lastFbPostAt = 0;
21
+ const __MIN_FB_POST_GAP_MS = 180; // ~5-6 req/s max sustained, still fast enough for bots
22
+ async function __paceFbPost(url) {
23
+ try {
24
+ const u = String(url || "");
25
+ if (!/facebook\.com|messenger\.com/i.test(u)) return;
26
+ const now = Date.now();
27
+ const wait = __MIN_FB_POST_GAP_MS - (now - __lastFbPostAt);
28
+ if (wait > 0) await new Promise(r => setTimeout(r, wait + Math.floor(Math.random() * 80)));
29
+ __lastFbPostAt = Date.now();
30
+ } catch (_) {}
31
+ }
32
+
17
33
  function cleanGet(url, ctx) {
18
34
  return requestWithRetry(() => client.get(url, cfg()), 3, 1000, ctx);
19
35
  }
@@ -2,8 +2,19 @@
2
2
 
3
3
  const { delay } = require("./client");
4
4
 
5
+ // [Hardened5] light spacing for FB hosts to reduce burst fingerprints
6
+ let __lastFbAt = 0;
7
+ async function __pace() {
8
+ const now = Date.now();
9
+ const gap = 150 + Math.floor(Math.random() * 100);
10
+ const wait = gap - (now - __lastFbAt);
11
+ if (wait > 0) await delay(wait);
12
+ __lastFbAt = Date.now();
13
+ }
14
+
5
15
  async function requestWithRetry(fn, retries = 3, baseDelay = 1000, ctx) {
6
16
  let lastError;
17
+ try { await __pace(); } catch (_) {}
7
18
  const emit = (event, payload) => {
8
19
  try {
9
20
  if (ctx && ctx._emitter && typeof ctx._emitter.emit === "function") {
@@ -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
- };