fca-nx 7.0.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "7.0.0",
3
+ "version": "7.1.0",
4
4
  "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -2,10 +2,7 @@
2
2
 
3
3
  const log = require("../../../func/logAdapter");
4
4
  const { parseAndCheckLogin } = require("../../utils/client");
5
-
6
- // api.getThemePictures(themeID, callback?)
7
- // themeID = the theme_fbid (digits), e.g. from api.getThreadInfo(tid).threadTheme.id
8
- // or from an api.createThemeAI() result.
5
+ const { getType } = require("../../utils/format");
9
6
  module.exports = function (defaultFuncs, api, ctx) {
10
7
  return function getThemePictures(id, callback) {
11
8
  let resolveFunc = function () { };
@@ -15,24 +12,24 @@ module.exports = function (defaultFuncs, api, ctx) {
15
12
  rejectFunc = reject;
16
13
  });
17
14
 
18
- if (typeof callback !== "function") {
19
- callback = function (err, data) {
20
- if (err) return rejectFunc(err);
21
- resolveFunc(data);
22
- };
15
+ if (!callback) {
16
+ if (
17
+ getType(callback) == "Function" ||
18
+ getType(callback) == "AsyncFunction"
19
+ ) {
20
+ callback = callback;
21
+ } else {
22
+ callback = function (err, data) {
23
+ if (err) {
24
+ return rejectFunc(err);
25
+ }
26
+ resolveFunc(data);
27
+ };
28
+ }
23
29
  }
24
30
 
25
- // [Hardened] Accept numbers/bigint too. Previously any non-string id was silently
26
- // replaced with "" and Facebook answered messenger_thread_theme: null.
27
- if (typeof id === "number" || typeof id === "bigint") id = String(id);
28
- id = typeof id === "string" ? id.trim() : "";
29
-
30
- if (!/^\d+$/.test(id)) {
31
- const err = {
32
- error: "getThemePictures: a numeric theme ID is required (theme_fbid), got: " + JSON.stringify(id)
33
- };
34
- callback(err);
35
- return returnPromise;
31
+ if (getType(id) != "String") {
32
+ id = "";
36
33
  }
37
34
 
38
35
  const form = {
@@ -40,30 +37,19 @@ module.exports = function (defaultFuncs, api, ctx) {
40
37
  fb_api_req_friendly_name: "MWPThreadThemeProviderQuery",
41
38
  doc_id: "9734829906576883",
42
39
  server_timestamps: true,
43
- variables: JSON.stringify({ id }),
40
+ variables: JSON.stringify({
41
+ id
42
+ }),
44
43
  av: ctx.userID
45
44
  };
46
-
47
45
  defaultFuncs
48
46
  .post("https://www.facebook.com/api/graphql/", ctx.jar, form)
49
47
  .then(parseAndCheckLogin(ctx, defaultFuncs))
50
48
  .then(function (resData) {
51
- if (resData && resData.errors) {
49
+ if (resData.errors) {
52
50
  throw resData;
53
51
  }
54
52
 
55
- // [Hardened] Request worked but Facebook has no theme with this ID for this account.
56
- // Report as failure instead of a false "success" with null theme.
57
- if (!resData || !resData.data || !resData.data.messenger_thread_theme) {
58
- const notFound = {
59
- error: "Theme not found: Facebook returned no theme for ID " + id + ". Check the ID (use the theme_fbid of a real theme).",
60
- themeID: id,
61
- raw: resData
62
- };
63
- log.error("getThemePictures", notFound.error);
64
- return callback(notFound);
65
- }
66
-
67
53
  return callback(null, resData);
68
54
  })
69
55
  .catch(function (err) {
@@ -1,18 +1,16 @@
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
-
8
3
  var utils = require("../../utils/utils");
9
4
  var logger = require("../../utils/logger");
10
- var { waitTurn } = require("../../utils/sendThrottle");
5
+ var { getTextEffectId, getTextEffectIds } = require("../../utils/textEffects");
11
6
 
12
7
  var ALLOWED = {
13
8
  attachment: true, url: true, sticker: true, emoji: true,
14
9
  emojiSize: true, body: true, mentions: true, location: true,
15
- replyToMessage: true, forwardAttachmentIds: 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
16
14
  };
17
15
 
18
16
  var EMOJI_SIZES = { small: 1, medium: 2, large: 3 };
@@ -32,15 +30,19 @@ function buildMentionData(msg, baseBody) {
32
30
  var ids = [], offsets = [], lengths = [], types = [];
33
31
  for (var i = 0; i < msg.mentions.length; i++) {
34
32
  var mention = msg.mentions[i];
33
+ // Ensure tag always has @ prefix — Facebook counts @ in both offset and length
35
34
  var tag = String(mention.tag || "");
36
35
  if (tag && !tag.startsWith("@")) tag = "@" + tag;
37
36
  var fromIndex = Number.isInteger(mention.fromIndex) ? mention.fromIndex : 0;
38
37
  var offset = baseBody.indexOf(tag, fromIndex);
39
- if (offset === -1) offset = baseBody.indexOf(tag.slice(1), fromIndex);
38
+ if (offset === -1) {
39
+ // Fallback: search for bare name without @
40
+ offset = baseBody.indexOf(tag.slice(1), fromIndex);
41
+ }
40
42
  if (offset < 0) offset = 0;
41
43
  ids.push(String(mention.id || 0));
42
44
  offsets.push(offset);
43
- lengths.push(tag.length);
45
+ lengths.push(tag.length); // includes @ — matches Facebook's expectation
44
46
  types.push("p");
45
47
  }
46
48
  return {
@@ -69,87 +71,52 @@ function extractIdsFromPayload(payload) {
69
71
  }
70
72
 
71
73
  function publishLsRequestWithAck(mqttClient, content, requestId, timeout) {
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"));
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'));
90
79
  }, timeout);
91
80
 
92
81
  function onMessage(topic, message) {
93
- if (topic !== "/ls_resp") return;
82
+ if (topic !== '/ls_resp') return;
94
83
  try {
95
84
  var data = JSON.parse(message.toString());
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
- });
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
+ }
102
91
  } catch (_) { }
103
92
  }
104
93
 
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);
128
- }
129
- if (Date.now() - start >= maxMs) {
130
- clearInterval(iv);
131
- return resolve(c || null);
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);
132
100
  }
133
- }, 200);
101
+ });
134
102
  });
135
103
  }
136
104
 
137
105
  module.exports = function (defaultFuncs, api, ctx) {
138
- var uploadAttachmentFn = require("../messaging/uploadAttachment")(defaultFuncs, api, ctx);
106
+ var uploadAttachmentFn = require('../messaging/uploadAttachment')(defaultFuncs, api, ctx);
139
107
 
140
108
  async function uploadAttachments(attachments) {
141
109
  if (!Array.isArray(attachments)) attachments = [attachments];
142
110
  return uploadAttachmentFn(attachments);
143
111
  }
144
112
 
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
- }
113
+ async function sendViaMqtt(msg, threadID, replyToMessage) {
114
+ var mqttClient = ctx.mqttClient || global.mqttClient;
115
+ if (!mqttClient) throw new Error('MQTT client not available');
150
116
 
151
117
  var baseBody = msg.body != null ? String(msg.body) : "";
152
118
  var requestId = Math.floor(100 + Math.random() * 900);
119
+ var epoch = (BigInt(Date.now()) << 22n).toString();
153
120
 
154
121
  var payload0 = {
155
122
  thread_id: String(threadID),
@@ -169,23 +136,18 @@ module.exports = function (defaultFuncs, api, ctx) {
169
136
  var mentionData = buildMentionData(msg, baseBody);
170
137
  if (mentionData) payload0.mention_data = mentionData;
171
138
 
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
- }
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); }
181
146
 
182
147
  if (msg.location && msg.location.latitude != null && msg.location.longitude != null) {
183
148
  payload0.send_type = 1;
184
149
  payload0.location_data = {
185
- coordinates: {
186
- latitude: msg.location.latitude,
187
- longitude: msg.location.longitude
188
- },
150
+ coordinates: { latitude: msg.location.latitude, longitude: msg.location.longitude },
189
151
  is_current_location: Boolean(msg.location.current),
190
152
  is_live_location: Boolean(msg.location.live)
191
153
  };
@@ -217,15 +179,14 @@ module.exports = function (defaultFuncs, api, ctx) {
217
179
  if (msg.forwardAttachmentIds && msg.forwardAttachmentIds.length) {
218
180
  payload0.attachment_fbids = payload0.attachment_fbids.concat(msg.forwardAttachmentIds.map(String));
219
181
  }
182
+
220
183
  if (toUpload.length) {
221
184
  var uploaded = await uploadAttachments(toUpload);
222
185
  for (var u of uploaded) {
223
186
  if (!u) continue;
224
187
  var fbid = u.image_id || u.video_id || u.audio_id || u.file_id || u.sticker_id || u.gif_id;
225
188
  if (!fbid) {
226
- var firstKey = Object.keys(u).find(function (k) {
227
- return u[k] && /^\d+$/.test(String(u[k]));
228
- });
189
+ var firstKey = Object.keys(u).find(function(k) { return u[k] && /^\d+$/.test(String(u[k])); });
229
190
  if (firstKey) fbid = u[firstKey];
230
191
  }
231
192
  if (fbid) payload0.attachment_fbids.push(String(fbid));
@@ -236,14 +197,14 @@ module.exports = function (defaultFuncs, api, ctx) {
236
197
 
237
198
  var tasks = [
238
199
  {
239
- label: "46",
200
+ label: '46',
240
201
  payload: JSON.stringify(payload0),
241
202
  queue_name: String(threadID),
242
203
  task_id: 400,
243
204
  failure_count: null
244
205
  },
245
206
  {
246
- label: "21",
207
+ label: '21',
247
208
  payload: JSON.stringify({
248
209
  thread_id: String(threadID),
249
210
  last_read_watermark_ts: Date.now(),
@@ -256,102 +217,57 @@ module.exports = function (defaultFuncs, api, ctx) {
256
217
  ];
257
218
 
258
219
  var content = {
259
- app_id: "2220391788200892",
220
+ app_id: '2220391788200892',
260
221
  payload: JSON.stringify({
261
222
  tasks: tasks,
262
- epoch_id: (BigInt(Date.now()) << 22n).toString(),
263
- version_id: "24804310205905615"
223
+ epoch_id: epoch,
224
+ version_id: '24804310205905615',
225
+ data_trace_id: '#' + Buffer.from(String(Math.random())).toString('base64').replace(/=+$/, '')
264
226
  }),
265
227
  request_id: requestId,
266
228
  type: 3
267
229
  };
268
230
 
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
- });
231
+ return publishLsRequestWithAck(mqttClient, content, requestId, 15000);
297
232
  }
298
233
 
299
234
  return async function sendMessage(msg, threadID, callback, replyToMessage, isSingleUser) {
300
235
  if (typeof msg === "string") msg = { body: msg };
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]];
236
+ if (typeof callback !== "function") { callback = null; }
304
237
 
305
238
  var resolve, reject;
306
- var promise = new Promise(function (res, rej) {
307
- resolve = res;
308
- reject = rej;
309
- });
239
+ var promise = new Promise((res, rej) => { resolve = res; reject = rej; });
310
240
 
311
241
  for (var key in msg) {
312
242
  if (!ALLOWED[key]) {
313
- var err = new Error("Message key '" + key + "' is not allowed.");
243
+ var err = { error: "sendMessage: Unknown property '" + key + "'" };
314
244
  if (callback) callback(err);
315
245
  else reject(err);
316
246
  return promise;
317
247
  }
318
248
  }
319
249
 
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
-
327
250
  // Auto-detect isSingleUser from ctx.threadTypes if not explicitly provided.
251
+ // parseDelta in listenMqtt.js populates ctx.threadTypes[senderID] = 'dm' | 'group'
328
252
  if (isSingleUser === undefined && ctx.threadTypes) {
329
- isSingleUser = ctx.threadTypes[String(threadID)] === "dm";
253
+ isSingleUser = ctx.threadTypes[String(threadID)] === 'dm';
330
254
  }
331
255
 
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).
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.)
350
266
  if (isSingleUser && msg.attachment) {
351
267
  var useE2EE = api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected();
352
268
  if (useE2EE) {
353
269
  try {
354
- var e2eeResult = await api.e2ee.sendMessage(String(threadID), msg, replyToMessage || msg.replyToMessage);
270
+ var e2eeResult = await api.e2ee.sendMessage(String(threadID), msg, replyToMessage);
355
271
  var wrapped = e2eeResult && e2eeResult.messageId
356
272
  ? { threadID: String(threadID), messageID: String(e2eeResult.messageId) }
357
273
  : e2eeResult;
@@ -364,11 +280,13 @@ module.exports = function (defaultFuncs, api, ctx) {
364
280
  }
365
281
  } else {
366
282
  try {
367
- var omResult = await sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser);
283
+ var omResult = await new Promise((res2, rej2) => {
284
+ api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, true);
285
+ });
368
286
  if (callback) callback(null, omResult);
369
287
  else resolve(omResult);
370
288
  } catch (omErr) {
371
- logger.error("sendMessage", "DM attachment OldMessage failed: " + (omErr.message || omErr));
289
+ logger.error("sendMessage", "DM attachment via OldMessage failed: " + (omErr.error || omErr.message || omErr));
372
290
  if (callback) callback(omErr);
373
291
  else reject(omErr);
374
292
  }
@@ -376,43 +294,16 @@ module.exports = function (defaultFuncs, api, ctx) {
376
294
  return promise;
377
295
  }
378
296
 
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 ----
407
297
  try {
408
- var result = await sendViaMqtt(msg, threadID, replyToMessage, 18000);
409
- if (result && !result.threadID) result.threadID = String(threadID);
298
+ var result = await sendViaMqtt(msg, threadID, replyToMessage);
410
299
  if (callback) callback(null, result);
411
300
  else resolve(result);
412
301
  } catch (mqttErr) {
413
302
  logger.warn("sendMessage", "MQTT failed, falling back to OldMessage: " + (mqttErr.message || mqttErr));
414
303
  try {
415
- var fbResult = await sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser);
304
+ var fbResult = await new Promise((res2, rej2) => {
305
+ api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, isSingleUser);
306
+ });
416
307
  if (callback) callback(null, fbResult);
417
308
  else resolve(fbResult);
418
309
  } catch (fbErr) {
@@ -424,4 +315,4 @@ module.exports = function (defaultFuncs, api, ctx) {
424
315
 
425
316
  return promise;
426
317
  };
427
- };
318
+ };
@@ -79,8 +79,6 @@ function extractPhotoUrl(photo, depth = 0) {
79
79
  "uri",
80
80
  "url",
81
81
  "image",
82
- "full_image",
83
- "viewer_image",
84
82
  "photo",
85
83
  "media",
86
84
  "cover_photo",
@@ -92,32 +90,6 @@ function extractPhotoUrl(photo, depth = 0) {
92
90
  return null;
93
91
  }
94
92
 
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
-
121
93
  function pickMeta(user) {
122
94
  let friendshipStatus = null;
123
95
  let gender = null;
@@ -166,13 +138,9 @@ function normalizeUser(user) {
166
138
  firstName: meta.shortName || null,
167
139
  vanity,
168
140
  thumbSrc: extractProfilePicture(user),
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,
141
+ coverPhoto: extractPhotoUrl(
142
+ user.cover_photo || user.coverPhoto || user.profile_cover_photo
143
+ ),
176
144
  profileUrl: user.profile_url || user.url || null,
177
145
  gender: meta.gender || null,
178
146
  type: user.__typename || "User",
@@ -281,29 +249,6 @@ module.exports = function (defaultFuncs, api, ctx) {
281
249
  logger(`getUserInfoV2 ${doc.id}: ${error.message || error}`, "warn");
282
250
  }
283
251
  }
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
- }
307
252
  return bestUser;
308
253
  }
309
254
 
@@ -366,7 +311,7 @@ module.exports = function (defaultFuncs, api, ctx) {
366
311
  if (!ids.length) {
367
312
  const error = new Error("Invalid user ID(s)");
368
313
  callback(error);
369
- return returnPromise;
314
+ returnPromise;
370
315
  }
371
316
  (async () => {
372
317
  try {
@@ -414,13 +359,12 @@ module.exports = function (defaultFuncs, api, ctx) {
414
359
  return callback(null, retObj);
415
360
  }
416
361
  })();
417
- return returnPromise;
362
+ return returnPromise;
418
363
  };
419
364
  };
420
365
 
421
366
  module.exports._private = {
422
367
  extractPhotoUrl,
423
- extractCoverFromHTML,
424
368
  normalizeUser
425
369
  };
426
370
 
@@ -71,16 +71,9 @@ 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
- const ids = rawIDs
74
+ return 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;
84
77
  }
85
78
 
86
79
  module.exports = {
@@ -1,64 +0,0 @@
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 };