fca-nx 6.7.8 → 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.
- package/module/login.js +1 -1
- package/module/loginHelper.js +3 -2
- package/package.json +3 -3
- package/src/api/socket/core/connectMqtt.js +14 -6
- package/src/api/socket/core/getSeqID.js +3 -3
- package/src/api/socket/listenMqtt.js +65 -25
- package/src/api/socket/sendMessage.js +171 -80
- package/src/utils/clientIdentity.js +2 -2
- package/src/utils/request/methods.js +16 -0
- package/src/utils/request/retry.js +11 -0
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:
|
|
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
|
package/module/loginHelper.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
}, (
|
|
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.
|
|
4
|
-
"description": "Facebook Messenger API for Node.js
|
|
3
|
+
"version": "6.7.9",
|
|
4
|
+
"description": "Facebook Messenger API for Node.js \u2014 hardened sendMessage + listenMqtt (cascade fallback, soft MQTT, anti-reconnect-storm)",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
7
7
|
"exports": {
|
|
@@ -103,4 +103,4 @@
|
|
|
103
103
|
"sqlite3"
|
|
104
104
|
]
|
|
105
105
|
}
|
|
106
|
-
}
|
|
106
|
+
}
|
|
@@ -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 =
|
|
12
|
-
const MAX_RECONNECT_COOLDOWN_MS =
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
261
|
-
mqttClient.publish("/
|
|
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 =
|
|
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(
|
|
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
|
-
},
|
|
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 =
|
|
24
|
-
const RECONNECT_DELAY_MS_DEFAULT =
|
|
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 =
|
|
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 =
|
|
30
|
-
const HEARTBEAT_TIMEOUT_MS =
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
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
|
-
},
|
|
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
|
-
|
|
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
|
-
|
|
362
|
-
|
|
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() /*
|
|
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
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
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,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);
|
|
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 ||
|
|
76
|
-
return new Promise((resolve, reject)
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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 !==
|
|
97
|
+
if (topic !== "/ls_resp") return;
|
|
84
98
|
try {
|
|
85
99
|
var data = JSON.parse(message.toString());
|
|
86
|
-
if (String(data.request_id)
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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(
|
|
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
|
|
116
|
-
if (!mqttClient
|
|
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) {
|
|
146
|
-
|
|
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: {
|
|
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) {
|
|
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:
|
|
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:
|
|
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:
|
|
268
|
+
app_id: "2220391788200892",
|
|
222
269
|
payload: JSON.stringify({
|
|
223
270
|
tasks: tasks,
|
|
224
|
-
epoch_id:
|
|
225
|
-
version_id:
|
|
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
|
-
|
|
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")
|
|
310
|
+
if (typeof callback !== "function") callback = null;
|
|
238
311
|
|
|
239
312
|
var resolve, reject;
|
|
240
|
-
var promise = new Promise((res, 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 =
|
|
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)] ===
|
|
336
|
+
isSingleUser = ctx.threadTypes[String(threadID)] === "dm";
|
|
255
337
|
}
|
|
256
338
|
|
|
257
|
-
//
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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
|
|
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
|
|
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,46 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
296
383
|
return promise;
|
|
297
384
|
}
|
|
298
385
|
|
|
299
|
-
//
|
|
300
|
-
//
|
|
301
|
-
//
|
|
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
|
-
|
|
306
|
-
if (typeof getTextEffectId === "function" && getTextEffectId(msg)) {
|
|
391
|
+
if (getTextEffectId(msg)) {
|
|
307
392
|
logger.warn("sendMessage", "Text effects are not supported in E2EE DMs - sending plain text. Use a group chat for effects.");
|
|
308
393
|
}
|
|
309
394
|
try {
|
|
310
|
-
var e2eeText = await api.e2ee.sendMessage(
|
|
395
|
+
var e2eeText = await api.e2ee.sendMessage(
|
|
396
|
+
String(threadID),
|
|
397
|
+
{ body: msg.body != null ? String(msg.body) : "" },
|
|
398
|
+
replyToMessage || msg.replyToMessage
|
|
399
|
+
);
|
|
311
400
|
var e2eeWrapped = e2eeText && e2eeText.messageId
|
|
312
401
|
? { threadID: String(threadID), messageID: String(e2eeText.messageId) }
|
|
313
402
|
: e2eeText;
|
|
403
|
+
if (ctx.threadTypes) ctx.threadTypes[String(threadID)] = "dm";
|
|
314
404
|
if (callback) callback(null, e2eeWrapped);
|
|
315
405
|
else resolve(e2eeWrapped);
|
|
406
|
+
return promise;
|
|
316
407
|
} catch (e2eeTextErr) {
|
|
317
|
-
logger.
|
|
318
|
-
|
|
319
|
-
|
|
408
|
+
logger.warn(
|
|
409
|
+
"sendMessage",
|
|
410
|
+
"E2EE DM text failed, cascading to MQTT/HTTP: " + (e2eeTextErr.message || e2eeTextErr)
|
|
411
|
+
);
|
|
412
|
+
// fall through to MQTT / OldMessage
|
|
320
413
|
}
|
|
321
|
-
return promise;
|
|
322
414
|
}
|
|
323
415
|
|
|
324
|
-
|
|
416
|
+
// ---- MQTT primary + OldMessage fallback ----
|
|
325
417
|
try {
|
|
326
|
-
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);
|
|
327
420
|
if (callback) callback(null, result);
|
|
328
421
|
else resolve(result);
|
|
329
422
|
} catch (mqttErr) {
|
|
330
423
|
logger.warn("sendMessage", "MQTT failed, falling back to OldMessage: " + (mqttErr.message || mqttErr));
|
|
331
424
|
try {
|
|
332
|
-
var fbResult = await
|
|
333
|
-
api.OldMessage(msg, threadID, (err2, data2) => err2 ? rej2(err2) : res2(data2), replyToMessage, isSingleUser);
|
|
334
|
-
});
|
|
425
|
+
var fbResult = await sendViaOldMessage(msg, threadID, replyToMessage, isSingleUser);
|
|
335
426
|
if (callback) callback(null, fbResult);
|
|
336
427
|
else resolve(fbResult);
|
|
337
428
|
} catch (fbErr) {
|
|
@@ -343,4 +434,4 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
343
434
|
|
|
344
435
|
return promise;
|
|
345
436
|
};
|
|
346
|
-
};
|
|
437
|
+
};
|
|
@@ -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 = "
|
|
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") {
|