fca-nx 7.1.0 → 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.
@@ -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;
@@ -138,9 +166,13 @@ function normalizeUser(user) {
138
166
  firstName: meta.shortName || null,
139
167
  vanity,
140
168
  thumbSrc: extractProfilePicture(user),
141
- coverPhoto: extractPhotoUrl(
142
- user.cover_photo || user.coverPhoto || user.profile_cover_photo
143
- ),
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,
144
176
  profileUrl: user.profile_url || user.url || null,
145
177
  gender: meta.gender || null,
146
178
  type: user.__typename || "User",
@@ -249,6 +281,29 @@ module.exports = function (defaultFuncs, api, ctx) {
249
281
  logger(`getUserInfoV2 ${doc.id}: ${error.message || error}`, "warn");
250
282
  }
251
283
  }
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");
305
+ }
306
+ }
252
307
  return bestUser;
253
308
  }
254
309
 
@@ -311,7 +366,7 @@ module.exports = function (defaultFuncs, api, ctx) {
311
366
  if (!ids.length) {
312
367
  const error = new Error("Invalid user ID(s)");
313
368
  callback(error);
314
- returnPromise;
369
+ return returnPromise;
315
370
  }
316
371
  (async () => {
317
372
  try {
@@ -359,12 +414,13 @@ module.exports = function (defaultFuncs, api, ctx) {
359
414
  return callback(null, retObj);
360
415
  }
361
416
  })();
362
- return returnPromise;
417
+ return returnPromise;
363
418
  };
364
419
  };
365
420
 
366
421
  module.exports._private = {
367
422
  extractPhotoUrl,
423
+ extractCoverFromHTML,
368
424
  normalizeUser
369
425
  };
370
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 = {