fca-nx 7.0.0 → 7.0.5
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/config.js +1 -0
- package/module/loginHelper.js +24 -46
- package/package.json +2 -2
- package/src/api/messaging/getThemePictures.js +21 -35
- package/src/api/socket/core/getSeqID.js +25 -29
- package/src/api/socket/e2ee/index.js +22 -84
- package/src/api/socket/e2ee/protocol.js +9 -32
- package/src/api/socket/e2ee/ratchet.js +1 -29
- package/src/api/socket/e2ee/store.js +42 -140
- package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +18 -140
- package/src/api/socket/listenE2EE.js +1 -14
- package/src/api/socket/sendMessage.js +77 -186
- package/src/api/users/getUserInfoV2.js +61 -61
- package/src/utils/textEffects.js +1 -8
- package/src/utils/sendThrottle.js +0 -64
package/module/config.js
CHANGED
package/module/loginHelper.js
CHANGED
|
@@ -12,6 +12,18 @@ const { getFrom } = require("../src/utils/constants");
|
|
|
12
12
|
const { loadConfig } = require("./config");
|
|
13
13
|
const { createRemoteClient } = require("../src/remote/remoteClient");
|
|
14
14
|
const { config } = loadConfig();
|
|
15
|
+
|
|
16
|
+
function e2eeEnabled() {
|
|
17
|
+
const on = (v) => v === true || v === "true";
|
|
18
|
+
try {
|
|
19
|
+
const botPath = path.join(process.cwd(), "config.json");
|
|
20
|
+
if (fs.existsSync(botPath)) {
|
|
21
|
+
const bot = JSON.parse(fs.readFileSync(botPath, "utf8"));
|
|
22
|
+
if (bot && Object.prototype.hasOwnProperty.call(bot, "e2ee")) return on(bot.e2ee);
|
|
23
|
+
}
|
|
24
|
+
} catch (_) {}
|
|
25
|
+
return on(config.e2ee);
|
|
26
|
+
}
|
|
15
27
|
const axiosBase = require("axios");
|
|
16
28
|
const regions = [
|
|
17
29
|
{ code: "PRN", name: "Pacific Northwest Region", location: "Khu vực Tây Bắc Thái Bình Dương" },
|
|
@@ -29,24 +41,6 @@ const regions = [
|
|
|
29
41
|
|
|
30
42
|
const REGION_MAP = new Map(regions.map(r => [r.code, r]));
|
|
31
43
|
|
|
32
|
-
// E2EE on/off switch. Reads "e2ee" from the bot's config.json (process.cwd()),
|
|
33
|
-
// then from the fca-nx config. Default is OFF so E2EE only starts when asked for.
|
|
34
|
-
function e2eeEnabled() {
|
|
35
|
-
const on = (v) => v === true || v === "true";
|
|
36
|
-
const off = (v) => v === false || v === "false";
|
|
37
|
-
try {
|
|
38
|
-
const botPath = path.join(process.cwd(), "config.json");
|
|
39
|
-
if (fs.existsSync(botPath)) {
|
|
40
|
-
const bot = JSON.parse(fs.readFileSync(botPath, "utf8"));
|
|
41
|
-
if (bot && Object.prototype.hasOwnProperty.call(bot, "e2ee")) {
|
|
42
|
-
return on(bot.e2ee);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
} catch (_) {}
|
|
46
|
-
if (off(config.e2ee)) return false;
|
|
47
|
-
return on(config.e2ee);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
44
|
function parseRegion(html) {
|
|
51
45
|
try {
|
|
52
46
|
const m1 = html.match(/"endpoint":"([^"]+)"/);
|
|
@@ -1359,50 +1353,34 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1359
1353
|
}, 86400000);
|
|
1360
1354
|
}
|
|
1361
1355
|
// ✅ fca-nx core features register
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1356
|
+
try {
|
|
1357
|
+
if (!e2eeEnabled()) {
|
|
1358
|
+
logger("E2EE off. Set \"e2ee\": true in config.json or fca-config.json to connect.", "info");
|
|
1359
|
+
} else {
|
|
1365
1360
|
const e2eeModule = require("../src/api/socket/e2ee");
|
|
1366
1361
|
api.e2ee = new e2eeModule.E2EEBridge(ctxMain, api, defaultFuncs);
|
|
1367
1362
|
ctxMain.e2ee = api.e2ee;
|
|
1368
1363
|
api.connectE2EE = (deviceStorePath) => api.e2ee.connect(deviceStorePath, ctxMain.userID);
|
|
1369
1364
|
api.listenE2EE = require("../src/api/socket/listenE2EE")(defaultFuncs, api, ctxMain);
|
|
1370
|
-
|
|
1371
|
-
// Auto-connect E2EE and make it the default listener so existing
|
|
1372
|
-
// bots calling api.listen() OR api.listenMqtt() directly also
|
|
1373
|
-
// receive E2EE (Secret Conversation) messages without any extra
|
|
1374
|
-
// setup or changes on the bot side.
|
|
1375
|
-
//
|
|
1376
|
-
// [Fixed by xalman] IMPORTANT: assign api.listen/api.listenMqtt to the combined
|
|
1377
|
-
// listener SYNCHRONOUSLY, before connectE2EE() resolves. Bots
|
|
1378
|
-
// commonly call api.listenMqtt(callback) immediately in the login
|
|
1379
|
-
// callback - if we waited for the async connectE2EE() promise to
|
|
1380
|
-
// swap these over, that call would already have captured the old
|
|
1381
|
-
// plain-MQTT-only function, permanently missing E2EE (inbox)
|
|
1382
|
-
// messages even after E2EE finished connecting moments later.
|
|
1383
1365
|
api.listen = api.listenE2EE;
|
|
1384
1366
|
api.listenMqtt = api.listenE2EE;
|
|
1385
|
-
|
|
1386
|
-
// [Fixed by xalman] Retry E2EE auto-connect with backoff instead of
|
|
1387
|
-
// giving up forever after one failed attempt - a transient network
|
|
1388
|
-
// blip or momentary FB rate-limit on device registration used to
|
|
1389
|
-
// leave the bot stuck in group-only mode until a full restart.
|
|
1390
1367
|
const connectE2EEWithRetry = async (attempt = 0) => {
|
|
1391
1368
|
try {
|
|
1392
1369
|
await api.connectE2EE();
|
|
1393
1370
|
logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
|
|
1394
1371
|
} catch (e) {
|
|
1395
1372
|
const msg = e && e.message ? e.message : String(e);
|
|
1396
|
-
if (attempt
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
|
|
1400
|
-
} else {
|
|
1401
|
-
logger(`E2EE auto-connect failed after 4 attempts (non-fatal, continuing without E2EE): ${msg}`, "warn");
|
|
1373
|
+
if (attempt >= 2) {
|
|
1374
|
+
logger(`E2EE auto-connect stopped after ${attempt + 1} tries: ${msg}`, "warn");
|
|
1375
|
+
return;
|
|
1402
1376
|
}
|
|
1377
|
+
const delayMs = 15000 * (attempt + 1);
|
|
1378
|
+
logger(`E2EE auto-connect failed (attempt ${attempt + 1}): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
|
|
1379
|
+
setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
|
|
1403
1380
|
}
|
|
1404
1381
|
};
|
|
1405
1382
|
connectE2EEWithRetry();
|
|
1383
|
+
}
|
|
1406
1384
|
} catch (e) {
|
|
1407
1385
|
logger(`E2EE init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
|
|
1408
1386
|
}
|
|
@@ -1438,7 +1416,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1438
1416
|
// used to silently discard it, so only group messages arriving over
|
|
1439
1417
|
// plain MQTT reached bot handlers.
|
|
1440
1418
|
api._listenMqttRaw = stableListenMqtt;
|
|
1441
|
-
if (typeof api.listenE2EE === "function") {
|
|
1419
|
+
if (e2eeEnabled() && typeof api.listenE2EE === "function") {
|
|
1442
1420
|
api.listenMqtt = api.listen = api.listenE2EE;
|
|
1443
1421
|
} else {
|
|
1444
1422
|
api.listenMqtt = api.listen = stableListenMqtt;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fca-nx",
|
|
3
|
-
"version": "7.0.
|
|
4
|
-
"description": "Facebook Messenger API for Node.js
|
|
3
|
+
"version": "7.0.5",
|
|
4
|
+
"description": "Facebook Messenger API for Node.js Fast, Secure, and Feature-Rich",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
7
7
|
"exports": {
|
|
@@ -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 (
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
-
|
|
26
|
-
|
|
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({
|
|
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
|
|
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) {
|
|
@@ -296,43 +296,39 @@ module.exports = function createGetSeqID(deps) {
|
|
|
296
296
|
if (isAuthError) {
|
|
297
297
|
if (retryCount < MAX_RETRIES) {
|
|
298
298
|
const delay = RETRY_DELAY * (retryCount + 1);
|
|
299
|
-
logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms
|
|
299
|
+
logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms, same cookie (error: ${msg})`, "warn");
|
|
300
300
|
await new Promise(resolve => setTimeout(resolve, delay));
|
|
301
|
-
|
|
302
|
-
if (retryCount === 0 && ctx.loggedIn) {
|
|
303
|
-
try {
|
|
304
|
-
logger("getSeqID: refreshing session before retry...", "info");
|
|
305
|
-
const { get } = require("../../../utils/request");
|
|
306
|
-
const { saveCookies } = require("../../../utils/client");
|
|
307
|
-
await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
|
|
308
|
-
} catch (refreshErr) {
|
|
309
|
-
logger(`getSeqID: session refresh failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
|
|
313
301
|
return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
|
|
314
302
|
}
|
|
315
303
|
|
|
316
|
-
|
|
317
|
-
const config = getConfig();
|
|
318
|
-
const loginResult = await tryAutoLogin(logger, config, ctx, defaultFuncs);
|
|
319
|
-
|
|
320
|
-
if (loginResult) {
|
|
321
|
-
logger("getSeqID: retrying with new session...", "info");
|
|
322
|
-
await new Promise(resolve => setTimeout(resolve, 3000));
|
|
323
|
-
return getSeqID(defaultFuncs, api, ctx, globalCallback, form, 0);
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
if (/blocked/i.test(msg)) {
|
|
304
|
+
if (/blocked the login|login_blocked|checkpoint/i.test(msg)) {
|
|
327
305
|
return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
|
|
328
306
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
307
|
+
|
|
308
|
+
logger(`getSeqID: auth still failing - keeping this cookie, no new login: ${msg}`, "error");
|
|
309
|
+
try {
|
|
310
|
+
if (typeof globalCallback === "function") {
|
|
311
|
+
globalCallback({ type: "session_recovering", error: msg, timestamp: Date.now() }, null);
|
|
312
|
+
}
|
|
313
|
+
} catch (_) {}
|
|
314
|
+
setTimeout(() => {
|
|
315
|
+
if (ctx._ending) return;
|
|
316
|
+
try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
|
|
317
|
+
}, 120000);
|
|
318
|
+
return;
|
|
332
319
|
}
|
|
333
320
|
|
|
334
|
-
logger(`getSeqID error: ${msg}`, "error");
|
|
335
|
-
|
|
321
|
+
logger(`getSeqID error (soft recover, no logout): ${msg}`, "error");
|
|
322
|
+
try {
|
|
323
|
+
if (typeof globalCallback === "function") {
|
|
324
|
+
globalCallback({ type: "session_recovering", error: msg, timestamp: Date.now() }, null);
|
|
325
|
+
}
|
|
326
|
+
} catch (_) {}
|
|
327
|
+
setTimeout(() => {
|
|
328
|
+
if (ctx._ending) return;
|
|
329
|
+
try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
|
|
330
|
+
}, 120000);
|
|
331
|
+
return;
|
|
336
332
|
});
|
|
337
333
|
};
|
|
338
334
|
};
|
|
@@ -73,14 +73,9 @@ class E2EEBridge {
|
|
|
73
73
|
|
|
74
74
|
userId = userId || this.ctx.userID;
|
|
75
75
|
|
|
76
|
-
// Default to .fca-nx/e2ee_device.json in the user's project directory
|
|
77
|
-
// [Fixed by xalman] On hosts with an ephemeral filesystem (Railway, Heroku...) the
|
|
78
|
-
// device file is wiped on every deploy, which registers a brand-new E2EE device each
|
|
79
|
-
// time and leaves stale devices behind. Set FCA_NX_E2EE_DEVICE_PATH to a path on a
|
|
80
|
-
// persistent volume (e.g. /data/e2ee_device.json) to keep the same device forever.
|
|
76
|
+
// Default to .fca-nx/e2ee_device.json in the user's project directory
|
|
81
77
|
if (!deviceStorePath) {
|
|
82
|
-
deviceStorePath = process.
|
|
83
|
-
|| path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
|
|
78
|
+
deviceStorePath = path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
|
|
84
79
|
}
|
|
85
80
|
|
|
86
81
|
// Auto-create parent directory — users don't need to create it manually
|
|
@@ -207,49 +202,36 @@ class E2EEBridge {
|
|
|
207
202
|
// Auto-reconnect the Noise WebSocket whenever it drops unexpectedly.
|
|
208
203
|
// `this.connected` stays true through reconnect cycles; it's only set
|
|
209
204
|
// false by an explicit api.e2ee.disconnect() call.
|
|
210
|
-
// [Fixed by xalman] Previous version gave up after 2 failed attempts (bot stayed "connected"
|
|
211
|
-
// but deaf forever), could start several reconnects in parallel (duplicate sockets ->
|
|
212
|
-
// duplicate messages), and reacted to non-E2EE "disconnected" events too.
|
|
213
205
|
const _self = this;
|
|
214
|
-
this.
|
|
215
|
-
this.client.onEvent("disconnected", function _onE2EEDisconnected(data) {
|
|
206
|
+
this.client.onEvent("disconnected", function _onE2EEDisconnected() {
|
|
216
207
|
if (!_self.connected) return; // intentional disconnect — skip
|
|
217
|
-
if (data && data.isE2EE === false) return; // MQTT/gateway drop, E2EE socket is fine
|
|
218
|
-
if (_self._reconnecting) return;
|
|
219
|
-
_self._reconnecting = true;
|
|
220
208
|
logger.warn("E2EE", "Noise WebSocket disconnected — reconnecting in 5s...");
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
if (!_self.connected) { _self._reconnecting = false; return; }
|
|
224
|
-
attempt++;
|
|
209
|
+
setTimeout(async function () {
|
|
210
|
+
if (!_self.connected) return;
|
|
225
211
|
try {
|
|
226
212
|
await _self.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
|
|
227
|
-
|
|
228
|
-
logger.success("E2EE", "E2EE WebSocket reconnected" + (attempt > 1 ? " (attempt " + attempt + ")" : "") + ".");
|
|
213
|
+
logger.success("E2EE", "E2EE WebSocket reconnected.");
|
|
229
214
|
} catch (err) {
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
215
|
+
logger.error("E2EE", "E2EE reconnect failed: " + (err && err.message ? err.message : String(err)));
|
|
216
|
+
// Retry again after another 10s if reconnect failed
|
|
217
|
+
if (_self.connected) {
|
|
218
|
+
setTimeout(async function () {
|
|
219
|
+
if (!_self.connected) return;
|
|
220
|
+
try {
|
|
221
|
+
await _self.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
|
|
222
|
+
logger.success("E2EE", "E2EE WebSocket reconnected (retry).");
|
|
223
|
+
} catch (err2) {
|
|
224
|
+
logger.error("E2EE", "E2EE reconnect retry failed: " + (err2 && err2.message ? err2.message : String(err2)));
|
|
225
|
+
}
|
|
226
|
+
}, 10000);
|
|
227
|
+
}
|
|
233
228
|
}
|
|
234
|
-
};
|
|
235
|
-
setTimeout(tryReconnect, 5000);
|
|
229
|
+
}, 5000);
|
|
236
230
|
});
|
|
237
231
|
|
|
238
232
|
// Forward incoming E2EE messages to the registered callback.
|
|
239
|
-
this._recentIds = this._recentIds || new Set();
|
|
240
233
|
this.client.onEvent("e2ee_message", (msg) => {
|
|
241
|
-
if (!this._messageCallback)
|
|
242
|
-
logger.warn("E2EE", "Incoming E2EE message dropped: no listener registered yet");
|
|
243
|
-
return;
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
// [Fixed by xalman] never deliver the same message twice (reconnect replay / overlapping
|
|
247
|
-
// sockets) — a duplicate would make the bot answer a command twice.
|
|
248
|
-
if (msg && msg.id) {
|
|
249
|
-
if (this._recentIds.has(msg.id)) return;
|
|
250
|
-
this._recentIds.add(msg.id);
|
|
251
|
-
if (this._recentIds.size > 2000) this._recentIds.delete(this._recentIds.values().next().value);
|
|
252
|
-
}
|
|
234
|
+
if (!this._messageCallback) return;
|
|
253
235
|
|
|
254
236
|
const senderID =
|
|
255
237
|
msg.senderId ||
|
|
@@ -306,19 +288,7 @@ class E2EEBridge {
|
|
|
306
288
|
};
|
|
307
289
|
}
|
|
308
290
|
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
// [Fixed by xalman] The callback runs synchronously inside the vendor's
|
|
312
|
-
// decrypt pipeline. If the bot handler threw here, the vendor treated it as a
|
|
313
|
-
// decryption failure (retry receipt + dropped message). Isolate it.
|
|
314
|
-
try {
|
|
315
|
-
const r = this._messageCallback(null, event);
|
|
316
|
-
if (r && typeof r.catch === "function") {
|
|
317
|
-
r.catch((e) => logger.error("E2EE", "Message callback rejected: " + (e && e.message ? e.message : String(e))));
|
|
318
|
-
}
|
|
319
|
-
} catch (e) {
|
|
320
|
-
logger.error("E2EE", "Message callback threw: " + (e && e.message ? e.message : String(e)));
|
|
321
|
-
}
|
|
291
|
+
this._messageCallback(null, event);
|
|
322
292
|
});
|
|
323
293
|
|
|
324
294
|
// Surface connection errors so the bot log shows them.
|
|
@@ -339,20 +309,6 @@ class E2EEBridge {
|
|
|
339
309
|
}
|
|
340
310
|
}
|
|
341
311
|
|
|
342
|
-
// [Fixed by xalman] `connected` stays true while the Noise socket reconnects, so sends made in
|
|
343
|
-
// that window used to fail (or fall back to MQTT, which cannot deliver to E2EE threads).
|
|
344
|
-
// Wait (up to timeoutMs) for the live socket instead of failing immediately.
|
|
345
|
-
async _waitReady(timeoutMs) {
|
|
346
|
-
const ctl = this.client && this.client.controller;
|
|
347
|
-
const isReady = () => !ctl || ctl.e2eeConnected !== false;
|
|
348
|
-
const deadline = Date.now() + (timeoutMs || 20000);
|
|
349
|
-
while (!isReady()) {
|
|
350
|
-
if (!this.connected) throw new Error("E2EE disconnected.");
|
|
351
|
-
if (Date.now() > deadline) throw new Error("E2EE socket is reconnecting; message not sent (timeout).");
|
|
352
|
-
await new Promise((r) => setTimeout(r, 250));
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
312
|
isConnected() {
|
|
357
313
|
return this.connected;
|
|
358
314
|
}
|
|
@@ -373,25 +329,11 @@ class E2EEBridge {
|
|
|
373
329
|
*/
|
|
374
330
|
async sendMessage(threadId, msg, replyToMessageId) {
|
|
375
331
|
this.ensureConnected();
|
|
376
|
-
await this._waitReady();
|
|
377
|
-
await require("../../../utils/sendThrottle").waitTurn(); // human-like pacing
|
|
378
332
|
|
|
379
333
|
const text = typeof msg === "string" ? msg : (msg && msg.body != null ? String(msg.body) : "");
|
|
380
334
|
const attachment = (msg && typeof msg === "object") ? (msg.attachment || null) : null;
|
|
381
335
|
|
|
382
336
|
if (!attachment) {
|
|
383
|
-
// Call the controller's E2EE senders directly: client.sendMessage() silently falls
|
|
384
|
-
// back to the regular (MQTT) sender when the socket flag is down, and that sender
|
|
385
|
-
// routes back into this bridge -> endless recursion / message never delivered.
|
|
386
|
-
const ctl = this.client.controller;
|
|
387
|
-
const tid = String(threadId);
|
|
388
|
-
if (ctl && typeof ctl.sendE2EEText === "function" && typeof ctl.sendE2EEGroupText === "function") {
|
|
389
|
-
const isGroupJid = tid.includes("@g.us") || tid.includes(".g.");
|
|
390
|
-
const messageId = isGroupJid
|
|
391
|
-
? await ctl.sendE2EEGroupText(tid, text, replyToMessageId, undefined)
|
|
392
|
-
: await ctl.sendE2EEText(tid, text, replyToMessageId, undefined);
|
|
393
|
-
return { messageId, timestampMs: Date.now() };
|
|
394
|
-
}
|
|
395
337
|
return this.client.sendMessage({ threadId, text, replyToMessageId });
|
|
396
338
|
}
|
|
397
339
|
|
|
@@ -440,25 +382,21 @@ class E2EEBridge {
|
|
|
440
382
|
|
|
441
383
|
async sendReaction(threadId, messageId, reaction, senderJid) {
|
|
442
384
|
this.ensureConnected();
|
|
443
|
-
await this._waitReady();
|
|
444
385
|
return this.client.sendReaction({ threadId, messageId, reaction, senderJid });
|
|
445
386
|
}
|
|
446
387
|
|
|
447
388
|
async sendTyping(threadId, isTyping) {
|
|
448
389
|
this.ensureConnected();
|
|
449
|
-
await this._waitReady(3000);
|
|
450
390
|
return this.client.sendTyping({ threadId, isTyping: isTyping !== false });
|
|
451
391
|
}
|
|
452
392
|
|
|
453
393
|
async unsendMessage(messageId, threadId) {
|
|
454
394
|
this.ensureConnected();
|
|
455
|
-
await this._waitReady();
|
|
456
395
|
return this.client.unsendMessage({ messageId, threadId });
|
|
457
396
|
}
|
|
458
397
|
|
|
459
398
|
async editMessage(threadId, messageId, newText) {
|
|
460
399
|
this.ensureConnected();
|
|
461
|
-
await this._waitReady();
|
|
462
400
|
return this.client.editMessage({ threadId, messageId, newText });
|
|
463
401
|
}
|
|
464
402
|
|
|
@@ -62,49 +62,26 @@ function encodeFrame(type, senderID, threadID, header, payload) {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
function decodeFrame(buf) {
|
|
65
|
-
if (Buffer.isBuffer(buf))
|
|
66
|
-
// Use the caller's buffer directly.
|
|
67
|
-
} else if (buf instanceof Uint8Array) {
|
|
68
|
-
buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
69
|
-
} else {
|
|
70
|
-
throw new TypeError("Frame must be a Buffer or Uint8Array");
|
|
71
|
-
}
|
|
65
|
+
if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
|
|
72
66
|
if (buf.length < 8) throw new Error("Frame too short");
|
|
73
67
|
let offset = 0;
|
|
74
68
|
|
|
75
|
-
function requireBytes(length, label) {
|
|
76
|
-
if (!Number.isSafeInteger(length) || length < 0 || length > buf.length - offset) {
|
|
77
|
-
throw new Error(`Invalid or truncated frame ${label}`);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function readLength(label) {
|
|
82
|
-
requireBytes(4, `${label} length`);
|
|
83
|
-
const length = buf.readUInt32BE(offset);
|
|
84
|
-
offset += 4;
|
|
85
|
-
requireBytes(length, label);
|
|
86
|
-
return length;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
69
|
const magic = buf.readUInt16BE(offset); offset += 2;
|
|
90
70
|
if (magic !== MAGIC) throw new Error("Invalid frame magic: " + magic.toString(16));
|
|
91
71
|
const version = buf.readUInt8(offset); offset += 1;
|
|
92
|
-
if (version !== VERSION) throw new Error("Unsupported frame version: " + version);
|
|
93
72
|
const type = buf.readUInt8(offset); offset += 1;
|
|
94
|
-
if (!Object.values(TYPE).includes(type)) throw new Error("Invalid frame type: " + type);
|
|
95
73
|
|
|
96
|
-
const sidLen =
|
|
97
|
-
const senderID = buf.
|
|
74
|
+
const sidLen = buf.readUInt32BE(offset); offset += 4;
|
|
75
|
+
const senderID = buf.slice(offset, offset + sidLen).toString("utf8"); offset += sidLen;
|
|
98
76
|
|
|
99
|
-
const tidLen =
|
|
100
|
-
const threadID = buf.
|
|
77
|
+
const tidLen = buf.readUInt32BE(offset); offset += 4;
|
|
78
|
+
const threadID = buf.slice(offset, offset + tidLen).toString("utf8"); offset += tidLen;
|
|
101
79
|
|
|
102
|
-
const hdrLen =
|
|
103
|
-
const header = buf.
|
|
80
|
+
const hdrLen = buf.readUInt32BE(offset); offset += 4;
|
|
81
|
+
const header = buf.slice(offset, offset + hdrLen); offset += hdrLen;
|
|
104
82
|
|
|
105
|
-
const payLen =
|
|
106
|
-
const payload = buf.
|
|
107
|
-
if (offset !== buf.length) throw new Error("Unexpected trailing bytes in frame");
|
|
83
|
+
const payLen = buf.readUInt32BE(offset); offset += 4;
|
|
84
|
+
const payload = buf.slice(offset, offset + payLen);
|
|
108
85
|
|
|
109
86
|
return { version, type, senderID, threadID, header, payload };
|
|
110
87
|
}
|
|
@@ -95,29 +95,6 @@ class DoubleRatchetSession {
|
|
|
95
95
|
* @returns {Buffer} decrypted plaintext
|
|
96
96
|
*/
|
|
97
97
|
decrypt(header, ciphertext, aad) {
|
|
98
|
-
const snapshot = {
|
|
99
|
-
DHs: this.DHs,
|
|
100
|
-
DHr: this.DHr,
|
|
101
|
-
RK: this.RK,
|
|
102
|
-
CKs: this.CKs,
|
|
103
|
-
CKr: this.CKr,
|
|
104
|
-
Ns: this.Ns,
|
|
105
|
-
Nr: this.Nr,
|
|
106
|
-
PN: this.PN,
|
|
107
|
-
MKSKIPPED: new Map(this.MKSKIPPED)
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
try {
|
|
111
|
-
return this._decryptAndAdvance(header, ciphertext, aad);
|
|
112
|
-
} catch (error) {
|
|
113
|
-
// Authentication failure must not consume a skipped key or advance
|
|
114
|
-
// the ratchet. A later valid copy of the message can then succeed.
|
|
115
|
-
Object.assign(this, snapshot);
|
|
116
|
-
throw error;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
_decryptAndAdvance(header, ciphertext, aad) {
|
|
121
98
|
const { dh_pub, pn, n } = this._parseHeader(header);
|
|
122
99
|
const aadFull = aad ? Buffer.concat([aad, header]) : header;
|
|
123
100
|
|
|
@@ -150,9 +127,6 @@ class DoubleRatchetSession {
|
|
|
150
127
|
if (this.Nr + MAX_SKIP < until) throw new Error("Too many skipped messages: " + until);
|
|
151
128
|
if (this.CKr) {
|
|
152
129
|
while (this.Nr < until) {
|
|
153
|
-
if (this.MKSKIPPED.size >= MAX_SKIP) {
|
|
154
|
-
throw new Error("Skipped message key limit exceeded");
|
|
155
|
-
}
|
|
156
130
|
const { ck, mk } = kdfCK(this.CKr);
|
|
157
131
|
this.CKr = ck;
|
|
158
132
|
const key = `${this.DHr.toString("hex")}:${this.Nr}`;
|
|
@@ -191,9 +165,7 @@ class DoubleRatchetSession {
|
|
|
191
165
|
}
|
|
192
166
|
|
|
193
167
|
_parseHeader(header) {
|
|
194
|
-
if (
|
|
195
|
-
throw new Error("Invalid ratchet header length");
|
|
196
|
-
}
|
|
168
|
+
if (header.length < 40) throw new Error("Invalid ratchet header length");
|
|
197
169
|
return {
|
|
198
170
|
dh_pub: header.slice(0, 32),
|
|
199
171
|
pn: header.readUInt32BE(32),
|