fca-nx 6.7.7 → 6.7.9

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.
@@ -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,10 +232,19 @@ 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
250
  try {
@@ -230,7 +253,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
230
253
  } catch (err) {
231
254
  logger(`mqtt heartbeat error: ${err.message}`, "warn");
232
255
  }
233
- }, conf.heartbeatInterval || HEARTBEAT_INTERVAL_MS);
256
+ }, hbEvery);
234
257
  }
235
258
 
236
259
  function stopHeartbeat() {
@@ -354,15 +377,18 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
354
377
 
355
378
  function delayedReconnect() {
356
379
  if (ctx._ending) return;
357
- const d = getReconnectDelay();
358
- logger(d === 0 ? "mqtt reconnecting immediately" : `mqtt reconnect in ${d}ms`, "info");
359
-
380
+ // [Hardened6] debounce: if a reconnect is already scheduled, keep it
360
381
  if (ctx._reconnectTimer) {
361
- clearTimeout(ctx._reconnectTimer);
362
- ctx._reconnectTimer = null;
382
+ logger("mqtt reconnect already scheduled - debounce", "warn");
383
+ return;
363
384
  }
385
+ let d = getReconnectDelay();
386
+ // Always add a little extra jitter on the scheduled path (even when d is small)
387
+ if (d > 0) d += Math.floor(Math.random() * 1500);
388
+ logger(d === 0 ? "mqtt reconnecting immediately" : `mqtt reconnect in ${d}ms`, "info");
364
389
 
365
390
  ctx._reconnectTimer = setTimeout(() => {
391
+ ctx._reconnectTimer = null;
366
392
  if (!ctx._ending) {
367
393
  isReconnecting = false;
368
394
  getSeqIDWrapper();
@@ -370,7 +396,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
370
396
  }, d);
371
397
  }
372
398
 
373
- function forceCycle() /* hardened */ {
399
+ function forceCycle() /* hardened6 */ {
374
400
  if (ctx._cycling) {
375
401
  logger("mqtt force cycle already in progress", "warn");
376
402
  return;
@@ -379,6 +405,13 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
379
405
  logger("mqtt force cycle skipped - ending", "warn");
380
406
  return;
381
407
  }
408
+ // [Hardened6] minimum 90s between forced cycles to avoid reconnect storms
409
+ const now = Date.now();
410
+ if (ctx._lastForceCycleAt && (now - ctx._lastForceCycleAt) < 90000) {
411
+ logger("mqtt force cycle skipped - too soon since last cycle", "warn");
412
+ return;
413
+ }
414
+ ctx._lastForceCycleAt = now;
382
415
 
383
416
  ctx._cycling = true;
384
417
  ctx._ending = true;
@@ -386,14 +419,21 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
386
419
 
387
420
  stopHeartbeat();
388
421
 
422
+ const finish = () => {
423
+ ctx._ending = false;
424
+ ctx._cycling = false;
425
+ if (conf.reconnectAfterStop || conf.autoReconnect !== false) {
426
+ delayedReconnect();
427
+ }
428
+ };
429
+
389
430
  unsubAll(() => {
390
- endQuietly(() => {
391
- ctx._ending = false;
392
- ctx._cycling = false;
393
- if (conf.reconnectAfterStop || conf.autoReconnect !== false) {
394
- delayedReconnect();
395
- }
396
- });
431
+ try {
432
+ endQuietly(finish);
433
+ } catch (e) {
434
+ logger(`mqtt force cycle endQuietly error: ${e && e.message ? e.message : e}`, "warn");
435
+ finish();
436
+ }
397
437
  });
398
438
  }
399
439
 
@@ -1,8 +1,14 @@
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");
11
+ var { waitTurn } = require("../../utils/sendThrottle");
6
12
 
7
13
  var ALLOWED = {
8
14
  attachment: true, url: true, sticker: true, emoji: true,
@@ -30,19 +36,15 @@ function buildMentionData(msg, baseBody) {
30
36
  var ids = [], offsets = [], lengths = [], types = [];
31
37
  for (var i = 0; i < msg.mentions.length; i++) {
32
38
  var mention = msg.mentions[i];
33
- // Ensure tag always has @ prefix — Facebook counts @ in both offset and length
34
39
  var tag = String(mention.tag || "");
35
40
  if (tag && !tag.startsWith("@")) tag = "@" + tag;
36
41
  var fromIndex = Number.isInteger(mention.fromIndex) ? mention.fromIndex : 0;
37
42
  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
- }
43
+ if (offset === -1) offset = baseBody.indexOf(tag.slice(1), fromIndex);
42
44
  if (offset < 0) offset = 0;
43
45
  ids.push(String(mention.id || 0));
44
46
  offsets.push(offset);
45
- lengths.push(tag.length); // includes @ — matches Facebook's expectation
47
+ lengths.push(tag.length);
46
48
  types.push("p");
47
49
  }
48
50
  return {
@@ -71,52 +73,87 @@ function extractIdsFromPayload(payload) {
71
73
  }
72
74
 
73
75
  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'));
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"));
79
94
  }, timeout);
80
95
 
81
96
  function onMessage(topic, message) {
82
- if (topic !== '/ls_resp') return;
97
+ if (topic !== "/ls_resp") return;
83
98
  try {
84
99
  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
- }
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
+ });
91
106
  } catch (_) { }
92
107
  }
93
108
 
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);
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);
100
132
  }
101
- });
133
+ if (Date.now() - start >= maxMs) {
134
+ clearInterval(iv);
135
+ return resolve(c || null);
136
+ }
137
+ }, 200);
102
138
  });
103
139
  }
104
140
 
105
141
  module.exports = function (defaultFuncs, api, ctx) {
106
- var uploadAttachmentFn = require('../messaging/uploadAttachment')(defaultFuncs, api, ctx);
142
+ var uploadAttachmentFn = require("../messaging/uploadAttachment")(defaultFuncs, api, ctx);
107
143
 
108
144
  async function uploadAttachments(attachments) {
109
145
  if (!Array.isArray(attachments)) attachments = [attachments];
110
146
  return uploadAttachmentFn(attachments);
111
147
  }
112
148
 
113
- async function sendViaMqtt(msg, threadID, replyToMessage) {
114
- var mqttClient = ctx.mqttClient || global.mqttClient;
115
- 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
+ }
116
154
 
117
155
  var baseBody = msg.body != null ? String(msg.body) : "";
118
156
  var requestId = Math.floor(100 + Math.random() * 900);
119
- var epoch = (BigInt(Date.now()) << 22n).toString();
120
157
 
121
158
  var payload0 = {
122
159
  thread_id: String(threadID),
@@ -141,13 +178,23 @@ module.exports = function (defaultFuncs, api, ctx) {
141
178
  var effectArray = getTextEffectIds(msg);
142
179
  if (effectArray.length) payload0.text_effect_ids = effectArray;
143
180
 
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); }
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
+ }
146
190
 
147
191
  if (msg.location && msg.location.latitude != null && msg.location.longitude != null) {
148
192
  payload0.send_type = 1;
149
193
  payload0.location_data = {
150
- coordinates: { latitude: msg.location.latitude, longitude: msg.location.longitude },
194
+ coordinates: {
195
+ latitude: msg.location.latitude,
196
+ longitude: msg.location.longitude
197
+ },
151
198
  is_current_location: Boolean(msg.location.current),
152
199
  is_live_location: Boolean(msg.location.live)
153
200
  };
@@ -179,14 +226,15 @@ module.exports = function (defaultFuncs, api, ctx) {
179
226
  if (msg.forwardAttachmentIds && msg.forwardAttachmentIds.length) {
180
227
  payload0.attachment_fbids = payload0.attachment_fbids.concat(msg.forwardAttachmentIds.map(String));
181
228
  }
182
-
183
229
  if (toUpload.length) {
184
230
  var uploaded = await uploadAttachments(toUpload);
185
231
  for (var u of uploaded) {
186
232
  if (!u) continue;
187
233
  var fbid = u.image_id || u.video_id || u.audio_id || u.file_id || u.sticker_id || u.gif_id;
188
234
  if (!fbid) {
189
- 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
+ });
190
238
  if (firstKey) fbid = u[firstKey];
191
239
  }
192
240
  if (fbid) payload0.attachment_fbids.push(String(fbid));
@@ -197,14 +245,14 @@ module.exports = function (defaultFuncs, api, ctx) {
197
245
 
198
246
  var tasks = [
199
247
  {
200
- label: '46',
248
+ label: "46",
201
249
  payload: JSON.stringify(payload0),
202
250
  queue_name: String(threadID),
203
251
  task_id: 400,
204
252
  failure_count: null
205
253
  },
206
254
  {
207
- label: '21',
255
+ label: "21",
208
256
  payload: JSON.stringify({
209
257
  thread_id: String(threadID),
210
258
  last_read_watermark_ts: Date.now(),
@@ -217,57 +265,100 @@ module.exports = function (defaultFuncs, api, ctx) {
217
265
  ];
218
266
 
219
267
  var content = {
220
- app_id: '2220391788200892',
268
+ app_id: "2220391788200892",
221
269
  payload: JSON.stringify({
222
270
  tasks: tasks,
223
- epoch_id: epoch,
224
- version_id: '24804310205905615',
225
- data_trace_id: '#' + Buffer.from(String(Math.random())).toString('base64').replace(/=+$/, '')
271
+ epoch_id: (BigInt(Date.now()) << 22n).toString(),
272
+ version_id: "24804310205905615"
226
273
  }),
227
274
  request_id: requestId,
228
275
  type: 3
229
276
  };
230
277
 
231
- 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
+ });
232
306
  }
233
307
 
234
308
  return async function sendMessage(msg, threadID, callback, replyToMessage, isSingleUser) {
235
309
  if (typeof msg === "string") msg = { body: msg };
236
- if (typeof callback !== "function") { callback = null; }
310
+ if (typeof callback !== "function") callback = null;
237
311
 
238
312
  var resolve, reject;
239
- 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
+ });
240
317
 
241
318
  for (var key in msg) {
242
319
  if (!ALLOWED[key]) {
243
- var err = { error: "sendMessage: Unknown property '" + key + "'" };
320
+ var err = new Error("Message key '" + key + "' is not allowed.");
244
321
  if (callback) callback(err);
245
322
  else reject(err);
246
323
  return promise;
247
324
  }
248
325
  }
249
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
+
250
334
  // Auto-detect isSingleUser from ctx.threadTypes if not explicitly provided.
251
- // parseDelta in listenMqtt.js populates ctx.threadTypes[senderID] = 'dm' | 'group'
252
335
  if (isSingleUser === undefined && ctx.threadTypes) {
253
- isSingleUser = ctx.threadTypes[String(threadID)] === 'dm';
336
+ isSingleUser = ctx.threadTypes[String(threadID)] === "dm";
254
337
  }
255
338
 
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.)
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).
266
357
  if (isSingleUser && msg.attachment) {
267
358
  var useE2EE = api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected();
268
359
  if (useE2EE) {
269
360
  try {
270
- var e2eeResult = await api.e2ee.sendMessage(String(threadID), msg, replyToMessage);
361
+ var e2eeResult = await api.e2ee.sendMessage(String(threadID), msg, replyToMessage || msg.replyToMessage);
271
362
  var wrapped = e2eeResult && e2eeResult.messageId
272
363
  ? { threadID: String(threadID), messageID: String(e2eeResult.messageId) }
273
364
  : e2eeResult;
@@ -280,13 +371,11 @@ module.exports = function (defaultFuncs, api, ctx) {
280
371
  }
281
372
  } else {
282
373
  try {
283
- var omResult = await new Promise((res2, rej2) => {
284
- api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, true);
285
- });
374
+ var omResult = await sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser);
286
375
  if (callback) callback(null, omResult);
287
376
  else resolve(omResult);
288
377
  } catch (omErr) {
289
- logger.error("sendMessage", "DM attachment via OldMessage failed: " + (omErr.error || omErr.message || omErr));
378
+ logger.error("sendMessage", "DM attachment OldMessage failed: " + (omErr.message || omErr));
290
379
  if (callback) callback(omErr);
291
380
  else reject(omErr);
292
381
  }
@@ -294,41 +383,46 @@ module.exports = function (defaultFuncs, api, ctx) {
294
383
  return promise;
295
384
  }
296
385
 
297
- // [Fixed by xalman] Text replies to a DM whose latest activity was E2EE must go through the
298
- // E2EE bridge. MQTT cannot deliver into an end-to-end encrypted chat: it waited 15s for an
299
- // ack that never came, so every command that calls api.sendMessage() directly looked dead
300
- // 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).
301
389
  if (isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
302
390
  api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected()) {
303
- // [Hardened] Text effects unsupported on E2EE path — warn once then send plain text
304
- if (typeof getTextEffectId === "function" && getTextEffectId(msg)) {
391
+ if (getTextEffectId(msg)) {
305
392
  logger.warn("sendMessage", "Text effects are not supported in E2EE DMs - sending plain text. Use a group chat for effects.");
306
393
  }
307
394
  try {
308
- var e2eeText = await api.e2ee.sendMessage(String(threadID), { body: msg.body != null ? String(msg.body) : "" }, replyToMessage || msg.replyToMessage);
395
+ var e2eeText = await api.e2ee.sendMessage(
396
+ String(threadID),
397
+ { body: msg.body != null ? String(msg.body) : "" },
398
+ replyToMessage || msg.replyToMessage
399
+ );
309
400
  var e2eeWrapped = e2eeText && e2eeText.messageId
310
401
  ? { threadID: String(threadID), messageID: String(e2eeText.messageId) }
311
402
  : e2eeText;
403
+ if (ctx.threadTypes) ctx.threadTypes[String(threadID)] = "dm";
312
404
  if (callback) callback(null, e2eeWrapped);
313
405
  else resolve(e2eeWrapped);
406
+ return promise;
314
407
  } catch (e2eeTextErr) {
315
- logger.error("sendMessage", "E2EE DM text send failed: " + (e2eeTextErr.message || e2eeTextErr));
316
- if (callback) callback(e2eeTextErr);
317
- else reject(e2eeTextErr);
408
+ logger.warn(
409
+ "sendMessage",
410
+ "E2EE DM text failed, cascading to MQTT/HTTP: " + (e2eeTextErr.message || e2eeTextErr)
411
+ );
412
+ // fall through to MQTT / OldMessage
318
413
  }
319
- return promise;
320
414
  }
321
415
 
416
+ // ---- MQTT primary + OldMessage fallback ----
322
417
  try {
323
- var result = await sendViaMqtt(msg, threadID, replyToMessage);
418
+ var result = await sendViaMqtt(msg, threadID, replyToMessage, 18000);
419
+ if (result && !result.threadID) result.threadID = String(threadID);
324
420
  if (callback) callback(null, result);
325
421
  else resolve(result);
326
422
  } catch (mqttErr) {
327
423
  logger.warn("sendMessage", "MQTT failed, falling back to OldMessage: " + (mqttErr.message || mqttErr));
328
424
  try {
329
- var fbResult = await new Promise((res2, rej2) => {
330
- api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, isSingleUser);
331
- });
425
+ var fbResult = await sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser);
332
426
  if (callback) callback(null, fbResult);
333
427
  else resolve(fbResult);
334
428
  } catch (fbErr) {
@@ -340,4 +434,4 @@ module.exports = function (defaultFuncs, api, ctx) {
340
434
 
341
435
  return promise;
342
436
  };
343
- };
437
+ };
@@ -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",
@@ -164,9 +166,13 @@ function normalizeUser(user) {
164
166
  firstName: meta.shortName || null,
165
167
  vanity,
166
168
  thumbSrc: extractProfilePicture(user),
167
- coverPhoto: extractPhotoUrl(
168
- user.cover_photo || user.coverPhoto || user.profile_cover_photo
169
- ),
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,
170
176
  profileUrl: user.profile_url || user.url || null,
171
177
  gender: meta.gender || null,
172
178
  type: user.__typename || "User",
@@ -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"',