fca-nx 6.7.2 → 6.7.4
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/README.md +34 -0
- package/module/loginHelper.js +16 -9
- package/package.json +1 -1
- package/src/api/action/addfriend.js +110 -31
- package/src/api/messaging/sendTypingIndicator.js +15 -0
- package/src/api/socket/OldMessage.js +7 -1
- package/src/api/socket/core/connectMqtt.js +33 -5
- package/src/api/socket/e2ee/index.js +83 -22
- package/src/api/socket/e2ee/protocol.js +32 -9
- package/src/api/socket/e2ee/ratchet.js +29 -1
- package/src/api/socket/e2ee/store.js +140 -42
- package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +140 -18
- package/src/api/socket/listenE2EE.js +18 -1
- package/src/api/socket/listenMqtt.js +18 -3
- package/src/api/socket/sendMessage.js +31 -1
- package/src/api/socket/sendMessageMqtt.js +6 -0
- package/src/api/users/getUserInfoV2.js +143 -27
- package/src/utils/loginParser/autoLogin.js +89 -63
- package/src/utils/textEffects.js +85 -0
package/README.md
CHANGED
|
@@ -132,12 +132,46 @@ api.restoreFromBackup();
|
|
|
132
132
|
api.stopAutoSave();
|
|
133
133
|
|
|
134
134
|
```
|
|
135
|
+
|
|
136
|
+
### Local E2EE helper-store encryption
|
|
137
|
+
|
|
138
|
+
The optional local E2EE helper store requires an external secret. Set
|
|
139
|
+
`FCA_NX_E2EE_STORE_KEY` to a high-entropy value of at least 32 characters, or
|
|
140
|
+
pass `{ encryptionKey }` to `E2EEStore`. The secret is not written to the store
|
|
141
|
+
file. Keep it in your deployment's secret manager; without it, loading or
|
|
142
|
+
saving the helper store fails closed. Legacy helper-store files are re-encrypted
|
|
143
|
+
on load when this key is configured.
|
|
144
|
+
|
|
135
145
|
# 💬 Messaging
|
|
136
146
|
### Send Message
|
|
137
147
|
```javascript
|
|
138
148
|
api.sendMessage("Hello world!", threadID);
|
|
139
149
|
|
|
140
150
|
```
|
|
151
|
+
### Message Effects
|
|
152
|
+
```javascript
|
|
153
|
+
api.sendMessage(
|
|
154
|
+
{
|
|
155
|
+
body: "I love you! ❤️",
|
|
156
|
+
textEffect: "love"
|
|
157
|
+
},
|
|
158
|
+
threadID
|
|
159
|
+
);
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Built-in effect names are `heart`, `hearts`, `love`, `gift`, `present`, `fire`,
|
|
163
|
+
`flame`, `confetti`, `confecti`, `party`, `sparkles`, `sparkle`, `star`, and
|
|
164
|
+
`magic`. You can also pass a custom numeric effect ID:
|
|
165
|
+
|
|
166
|
+
```javascript
|
|
167
|
+
api.sendMessage({ body: "Party time!", effect: "confetti" }, threadID);
|
|
168
|
+
api.sendMessage({ body: "Custom effect", textEffect: 27 }, threadID);
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
The aliases `textEffect`, `text_effect`, `effect`, `effectName`, and their
|
|
172
|
+
snake/camel-case ID variants are accepted. Effects are applied through both
|
|
173
|
+
the MQTT sender and the legacy fallback sender.
|
|
174
|
+
|
|
141
175
|
### Send Attachment
|
|
142
176
|
```javascript
|
|
143
177
|
const fs = require("fs");
|
package/module/loginHelper.js
CHANGED
|
@@ -1373,13 +1373,11 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1373
1373
|
logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
|
|
1374
1374
|
} catch (e) {
|
|
1375
1375
|
const msg = e && e.message ? e.message : String(e);
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
logger(`E2EE auto-connect failed after 4 attempts (non-fatal, continuing without E2EE): ${msg}`, "warn");
|
|
1382
|
-
}
|
|
1376
|
+
// [Fixed by xalman] never give up: after 4 attempts the bot used to stay without E2EE
|
|
1377
|
+
// (inbox dead) until a manual restart. Keep retrying, backing off up to 5 minutes.
|
|
1378
|
+
const delayMs = Math.min(5000 * Math.pow(3, attempt), 300000); // 5s, 15s, 45s, 135s, 300s...
|
|
1379
|
+
logger(`E2EE auto-connect failed (attempt ${attempt + 1}): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
|
|
1380
|
+
setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
|
|
1383
1381
|
}
|
|
1384
1382
|
};
|
|
1385
1383
|
connectE2EEWithRetry();
|
|
@@ -1412,8 +1410,17 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1412
1410
|
|
|
1413
1411
|
// listenMqtt override with fca-nx version (better MQTT stability)
|
|
1414
1412
|
try {
|
|
1415
|
-
|
|
1416
|
-
|
|
1413
|
+
const stableListenMqtt = require("../src/api/socket/listenMqtt")(defaultFuncs, api, ctxMain);
|
|
1414
|
+
// Keep the raw MQTT listener behind the combined listener. The
|
|
1415
|
+
// E2EE bridge is installed above, but replacing api.listenMqtt here
|
|
1416
|
+
// used to silently discard it, so only group messages arriving over
|
|
1417
|
+
// plain MQTT reached bot handlers.
|
|
1418
|
+
api._listenMqttRaw = stableListenMqtt;
|
|
1419
|
+
if (typeof api.listenE2EE === "function") {
|
|
1420
|
+
api.listenMqtt = api.listen = api.listenE2EE;
|
|
1421
|
+
} else {
|
|
1422
|
+
api.listenMqtt = api.listen = stableListenMqtt;
|
|
1423
|
+
}
|
|
1417
1424
|
} catch (e) {
|
|
1418
1425
|
logger(`listenMqtt fca-nx override failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
|
|
1419
1426
|
}
|
package/package.json
CHANGED
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
|
|
7
7
|
const log = require("../../../func/logAdapter");
|
|
8
8
|
const { parseAndCheckLogin } = require("../../utils/client");
|
|
9
|
-
const { formatID } = require("../../utils/format");
|
|
9
|
+
const { formatID, getSignatureID } = require("../../utils/format");
|
|
10
|
+
|
|
11
|
+
const FRIEND_REQUEST_DOC_ID = "FriendingCometFriendRequestSendMutation";
|
|
10
12
|
|
|
11
13
|
module.exports = function (defaultFuncs, api, ctx) {
|
|
12
14
|
return function addFriend(userID, callback) {
|
|
@@ -50,51 +52,128 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
50
52
|
return returnPromise;
|
|
51
53
|
}
|
|
52
54
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
55
|
+
const sendRequest = async function () {
|
|
56
|
+
// Facebook retired the old /ajax/friends/requests/send/ action. The
|
|
57
|
+
// profile button now uses this Relay mutation instead.
|
|
58
|
+
if (!ctx.fb_dtsg && typeof api?.refreshFb_dtsg === "function") {
|
|
59
|
+
try {
|
|
60
|
+
await api.refreshFb_dtsg();
|
|
61
|
+
} catch (_) {
|
|
62
|
+
// The request below will return the actionable Facebook error.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const actorID = String(ctx.i_userID || ctx.userID);
|
|
67
|
+
const form = {
|
|
68
|
+
av: actorID,
|
|
69
|
+
__aaid: "0",
|
|
70
|
+
__user: actorID,
|
|
71
|
+
__a: "1",
|
|
72
|
+
__req: getSignatureID(),
|
|
73
|
+
__hs: "20353.HYP:comet_pkg.2.1...0",
|
|
74
|
+
dpr: "1",
|
|
75
|
+
__ccg: "EXCELLENT",
|
|
76
|
+
__rev: "1027405870",
|
|
77
|
+
__s: getSignatureID(),
|
|
78
|
+
__hsi: "7552782279085106329",
|
|
79
|
+
__comet_req: "15",
|
|
80
|
+
fb_dtsg: ctx.fb_dtsg,
|
|
81
|
+
jazoest: ctx.ttstamp || ctx.jazoest,
|
|
82
|
+
lsd: ctx.fb_dtsg,
|
|
83
|
+
__spin_r: "1027405870",
|
|
84
|
+
__spin_b: "trunk",
|
|
85
|
+
__spin_t: String(Date.now()),
|
|
86
|
+
__crn: "comet.fbweb.CometFriendingRoute",
|
|
87
|
+
fb_api_caller_class: "RelayModern",
|
|
88
|
+
fb_api_req_friendly_name: "FriendingCometFriendRequestSendMutation",
|
|
89
|
+
server_timestamps: true,
|
|
90
|
+
doc_id: "24614631718227645",
|
|
91
|
+
variables: JSON.stringify({
|
|
92
|
+
input: {
|
|
93
|
+
click_correlation_id: String(Date.now()),
|
|
94
|
+
click_proof_validation_result: JSON.stringify({ validated: true }),
|
|
95
|
+
friend_requestee_ids: [String(targetID)],
|
|
96
|
+
friending_channel: "FRIENDS_HOME_MAIN",
|
|
97
|
+
warn_ack_for_ids: [],
|
|
98
|
+
actor_id: actorID,
|
|
99
|
+
client_mutation_id: String(Math.floor(Math.random() * 100000))
|
|
100
|
+
},
|
|
101
|
+
scale: 1
|
|
102
|
+
})
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
return defaultFuncs
|
|
106
|
+
.post(
|
|
107
|
+
"https://www.facebook.com/api/graphql/",
|
|
108
|
+
ctx.jar,
|
|
109
|
+
form
|
|
110
|
+
)
|
|
111
|
+
.then(parseAndCheckLogin(ctx, defaultFuncs));
|
|
63
112
|
};
|
|
64
113
|
|
|
65
|
-
|
|
66
|
-
.post(
|
|
67
|
-
"https://www.facebook.com/ajax/friends/requests/send/",
|
|
68
|
-
ctx.jar,
|
|
69
|
-
form
|
|
70
|
-
)
|
|
71
|
-
.then(parseAndCheckLogin(ctx, defaultFuncs))
|
|
114
|
+
sendRequest()
|
|
72
115
|
.then(function (resData) {
|
|
73
116
|
if (!resData) {
|
|
74
117
|
throw new Error("Empty response from Facebook");
|
|
75
118
|
}
|
|
76
119
|
|
|
77
|
-
|
|
78
|
-
|
|
120
|
+
const payload = resData.payload || resData.data || resData;
|
|
121
|
+
const errorValue =
|
|
122
|
+
resData.error ||
|
|
123
|
+
resData.errors ||
|
|
124
|
+
resData.errorDescription ||
|
|
125
|
+
payload?.error ||
|
|
126
|
+
payload?.err ||
|
|
127
|
+
payload?.errorDescription ||
|
|
128
|
+
payload?.message;
|
|
129
|
+
if (errorValue) {
|
|
130
|
+
const error = new Error(
|
|
131
|
+
typeof errorValue === "string"
|
|
132
|
+
? errorValue
|
|
133
|
+
: errorValue.message || JSON.stringify(errorValue)
|
|
134
|
+
);
|
|
135
|
+
error.error = errorValue;
|
|
136
|
+
error.res = resData;
|
|
137
|
+
throw error;
|
|
79
138
|
}
|
|
80
139
|
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
throw payload;
|
|
140
|
+
const findRequestID = value => {
|
|
141
|
+
if (!value || typeof value !== "object") return null;
|
|
142
|
+
for (const key of ["friend_request_id", "friendRequestId", "request_id"]) {
|
|
143
|
+
if (value[key]) return String(value[key]);
|
|
86
144
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
145
|
+
for (const child of Object.values(value)) {
|
|
146
|
+
const nested = findRequestID(child);
|
|
147
|
+
if (nested) return nested;
|
|
90
148
|
}
|
|
149
|
+
return null;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const response = Array.isArray(resData) ? resData[0] : resData;
|
|
153
|
+
const data = response?.data?.friend_request_send ||
|
|
154
|
+
response?.friend_request_send;
|
|
155
|
+
const requestee = Array.isArray(data?.friend_requestees)
|
|
156
|
+
? data.friend_requestees[0]
|
|
157
|
+
: null;
|
|
158
|
+
const requestID = findRequestID(payload);
|
|
159
|
+
if (!requestee && !requestID) {
|
|
160
|
+
throw new Error("No friend request data received");
|
|
91
161
|
}
|
|
92
162
|
|
|
93
163
|
const result = {
|
|
94
|
-
success:
|
|
95
|
-
|
|
96
|
-
|
|
164
|
+
success: requestee
|
|
165
|
+
? requestee.friendship_status === "OUTGOING_REQUEST"
|
|
166
|
+
: true,
|
|
167
|
+
userID: requestee?.id || String(targetID)
|
|
97
168
|
};
|
|
169
|
+
if (requestee) {
|
|
170
|
+
result.friendshipStatus = requestee.friendship_status || null;
|
|
171
|
+
result.actionTitle = requestee.profile_action?.title?.text || null;
|
|
172
|
+
}
|
|
173
|
+
if (requestID) {
|
|
174
|
+
result.requestID = requestID;
|
|
175
|
+
result.response = response;
|
|
176
|
+
}
|
|
98
177
|
|
|
99
178
|
return handleCallback(null, result);
|
|
100
179
|
})
|
|
@@ -8,6 +8,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
8
8
|
resolveFunc = resolve;
|
|
9
9
|
rejectFunc = reject;
|
|
10
10
|
});
|
|
11
|
+
returnPromise.catch(function () { }); // [Fixed by xalman] unawaited callers caused unhandledRejection
|
|
11
12
|
if (getType(options) == "Function" || getType(options) == "AsyncFunction") {
|
|
12
13
|
callback = options;
|
|
13
14
|
options = {};
|
|
@@ -22,6 +23,20 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
22
23
|
if (!threadID) {
|
|
23
24
|
return callback(new Error("threadID is required"));
|
|
24
25
|
}
|
|
26
|
+
// [Fixed by xalman] E2EE DM: show typing through the E2EE bridge instead of (useless) MQTT.
|
|
27
|
+
if (typeof threadID === "string" || typeof threadID === "number") {
|
|
28
|
+
var _tid = String(threadID);
|
|
29
|
+
if (ctx.threadTypes && ctx.threadTypes[_tid] === "dm" && ctx.e2ee &&
|
|
30
|
+
typeof ctx.e2ee.isConnected === "function" && ctx.e2ee.isConnected()) {
|
|
31
|
+
ctx.e2ee.sendTyping(_tid, !!isTyping).catch(function () { });
|
|
32
|
+
if (isTyping && options.autoStop !== false) {
|
|
33
|
+
var _t = setTimeout(function () { ctx.e2ee.sendTyping(_tid, false).catch(function () { }); }, options.duration || 10000);
|
|
34
|
+
if (_t.unref) _t.unref();
|
|
35
|
+
}
|
|
36
|
+
callback(null, true);
|
|
37
|
+
return returnPromise;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
25
40
|
if (!ctx.mqttClient) {
|
|
26
41
|
const err = new Error("Not connected to MQTT");
|
|
27
42
|
callback(err);
|
|
@@ -3,10 +3,14 @@
|
|
|
3
3
|
var utils = require("../../utils/utils");
|
|
4
4
|
var logger = require("../../utils/logger");
|
|
5
5
|
var bluebird = require("bluebird");
|
|
6
|
+
var { getTextEffectId } = require("../../utils/textEffects");
|
|
6
7
|
|
|
7
8
|
var allowedProperties = {
|
|
8
9
|
attachment: true, url: true, sticker: true, emoji: true,
|
|
9
|
-
emojiSize: true, body: true, mentions: true, location: true,
|
|
10
|
+
emojiSize: true, body: true, mentions: true, location: true, text_effect_ids: true,
|
|
11
|
+
textEffect: true, text_effect: true, text_effect_id: true, textEffectId: true,
|
|
12
|
+
textEffectID: true, effect: true, effect_id: true, effectID: true,
|
|
13
|
+
text_effect_name: true, effectName: true, effect_name: true,
|
|
10
14
|
};
|
|
11
15
|
|
|
12
16
|
module.exports = function (defaultFuncs, api, ctx) {
|
|
@@ -134,6 +138,8 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
134
138
|
|
|
135
139
|
var form = {};
|
|
136
140
|
if (msg.body) form.body = msg.body;
|
|
141
|
+
var textEffectId = getTextEffectId(msg);
|
|
142
|
+
if (textEffectId) form.text_effect_id = textEffectId;
|
|
137
143
|
|
|
138
144
|
if (msg.mentions && Array.isArray(msg.mentions)) {
|
|
139
145
|
form.body = msg.body || "";
|
|
@@ -16,8 +16,26 @@ const T_MS_WAIT_TIMEOUT_MS = 5000;
|
|
|
16
16
|
// attempts have happened for this session (reset to 0 on a successful
|
|
17
17
|
// "connect" event). This replaces the old fixed 2s-every-time behavior,
|
|
18
18
|
// which could hammer the endpoint in a tight loop during real outages.
|
|
19
|
+
//
|
|
20
|
+
// [Fixed by xalman] IMMEDIATE RECONNECT: the first reconnect after a disconnect now happens at
|
|
21
|
+
// once (0ms) instead of waiting for a scheduled 4-6s delay. Only if that attempt also fails does
|
|
22
|
+
// the backoff start (1s, 2s, 4s ... capped at 60s) so a real outage still can't hammer Facebook.
|
|
23
|
+
// Set env FCA_NX_MQTT_IMMEDIATE_RECONNECT=0 (or mqtt option immediateReconnect:false) to get the
|
|
24
|
+
// old scheduled behaviour back.
|
|
25
|
+
function isImmediateReconnect(ctx) {
|
|
26
|
+
if (process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "0") return false;
|
|
27
|
+
if (ctx && ctx._mqttOpt && ctx._mqttOpt.immediateReconnect === false) return false;
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
|
|
19
31
|
function computeBackoff(ctx, baseMs) {
|
|
20
32
|
const attempt = (ctx._reconnectAttempts || 0);
|
|
33
|
+
if (isImmediateReconnect(ctx)) {
|
|
34
|
+
if (attempt <= 1) return 0; // first reconnect: right now
|
|
35
|
+
const fast = Math.min(1000 * Math.pow(2, attempt - 2), MAX_RECONNECT_DELAY_MS);
|
|
36
|
+
const j = Math.floor(Math.random() * Math.min(500, fast * 0.2));
|
|
37
|
+
return Math.min(fast + j, MAX_RECONNECT_DELAY_MS);
|
|
38
|
+
}
|
|
21
39
|
const exp = Math.min(baseMs * Math.pow(2, attempt), MAX_RECONNECT_DELAY_MS);
|
|
22
40
|
const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
|
|
23
41
|
return Math.min(exp + jitter, MAX_RECONNECT_DELAY_MS);
|
|
@@ -62,7 +80,7 @@ module.exports = function createListenMqtt(deps) {
|
|
|
62
80
|
return;
|
|
63
81
|
}
|
|
64
82
|
const ms = typeof delayMs === "number" ? delayMs : computeBackoff(ctx, base);
|
|
65
|
-
logger(`mqtt will reconnect in
|
|
83
|
+
logger(`mqtt ${ms === 0 ? "reconnecting immediately" : "will reconnect in " + ms + "ms"} (attempt ${ctx._reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`, "warn");
|
|
66
84
|
ctx._reconnectTimer = setTimeout(() => {
|
|
67
85
|
ctx._reconnectTimer = null;
|
|
68
86
|
if (!ctx._ending) {
|
|
@@ -170,10 +188,20 @@ module.exports = function createListenMqtt(deps) {
|
|
|
170
188
|
mqttClient.end(true);
|
|
171
189
|
}
|
|
172
190
|
} catch (_) { }
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
191
|
+
if (/blocked/i.test(msg)) {
|
|
192
|
+
return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Auth responses can race with the shared cookie refresh triggered by
|
|
196
|
+
// another request. Treat a plain 401/403/"Not logged in" MQTT error as
|
|
197
|
+
// recoverable instead of emitting account_inactive and permanently
|
|
198
|
+
// setting ctx._ending. The close handler/scheduler will establish a
|
|
199
|
+
// fresh MQTT connection with the refreshed session.
|
|
200
|
+
logger(`mqtt transient auth error; reconnecting without logging out: ${msg}`, "warn");
|
|
201
|
+
if (!ctx._ending && ctx.globalOptions.autoReconnect) {
|
|
202
|
+
scheduleReconnect();
|
|
203
|
+
}
|
|
204
|
+
return;
|
|
177
205
|
}
|
|
178
206
|
logger(`mqtt error: ${msg}`, "error");
|
|
179
207
|
try {
|
|
@@ -73,9 +73,14 @@ 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
|
|
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.
|
|
77
81
|
if (!deviceStorePath) {
|
|
78
|
-
deviceStorePath =
|
|
82
|
+
deviceStorePath = process.env.FCA_NX_E2EE_DEVICE_PATH
|
|
83
|
+
|| path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
|
|
79
84
|
}
|
|
80
85
|
|
|
81
86
|
// Auto-create parent directory — users don't need to create it manually
|
|
@@ -202,36 +207,49 @@ class E2EEBridge {
|
|
|
202
207
|
// Auto-reconnect the Noise WebSocket whenever it drops unexpectedly.
|
|
203
208
|
// `this.connected` stays true through reconnect cycles; it's only set
|
|
204
209
|
// 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.
|
|
205
213
|
const _self = this;
|
|
206
|
-
this.
|
|
214
|
+
this._reconnecting = false;
|
|
215
|
+
this.client.onEvent("disconnected", function _onE2EEDisconnected(data) {
|
|
207
216
|
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;
|
|
208
220
|
logger.warn("E2EE", "Noise WebSocket disconnected — reconnecting in 5s...");
|
|
209
|
-
|
|
210
|
-
|
|
221
|
+
let attempt = 0;
|
|
222
|
+
const tryReconnect = async function () {
|
|
223
|
+
if (!_self.connected) { _self._reconnecting = false; return; }
|
|
224
|
+
attempt++;
|
|
211
225
|
try {
|
|
212
226
|
await _self.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
|
|
213
|
-
|
|
227
|
+
_self._reconnecting = false;
|
|
228
|
+
logger.success("E2EE", "E2EE WebSocket reconnected" + (attempt > 1 ? " (attempt " + attempt + ")" : "") + ".");
|
|
214
229
|
} catch (err) {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
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
|
-
}
|
|
230
|
+
const delay = Math.min(5000 * Math.pow(2, attempt - 1), 60000);
|
|
231
|
+
logger.error("E2EE", "E2EE reconnect failed (attempt " + attempt + "): " + (err && err.message ? err.message : String(err)) + " — retrying in " + Math.round(delay / 1000) + "s");
|
|
232
|
+
setTimeout(tryReconnect, delay);
|
|
228
233
|
}
|
|
229
|
-
}
|
|
234
|
+
};
|
|
235
|
+
setTimeout(tryReconnect, 5000);
|
|
230
236
|
});
|
|
231
237
|
|
|
232
238
|
// Forward incoming E2EE messages to the registered callback.
|
|
239
|
+
this._recentIds = this._recentIds || new Set();
|
|
233
240
|
this.client.onEvent("e2ee_message", (msg) => {
|
|
234
|
-
if (!this._messageCallback)
|
|
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
|
+
}
|
|
235
253
|
|
|
236
254
|
const senderID =
|
|
237
255
|
msg.senderId ||
|
|
@@ -288,7 +306,19 @@ class E2EEBridge {
|
|
|
288
306
|
};
|
|
289
307
|
}
|
|
290
308
|
|
|
291
|
-
|
|
309
|
+
event.e2eeKind = msg.kind || "text";
|
|
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
|
+
}
|
|
292
322
|
});
|
|
293
323
|
|
|
294
324
|
// Surface connection errors so the bot log shows them.
|
|
@@ -309,6 +339,20 @@ class E2EEBridge {
|
|
|
309
339
|
}
|
|
310
340
|
}
|
|
311
341
|
|
|
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
|
+
|
|
312
356
|
isConnected() {
|
|
313
357
|
return this.connected;
|
|
314
358
|
}
|
|
@@ -329,11 +373,24 @@ class E2EEBridge {
|
|
|
329
373
|
*/
|
|
330
374
|
async sendMessage(threadId, msg, replyToMessageId) {
|
|
331
375
|
this.ensureConnected();
|
|
376
|
+
await this._waitReady();
|
|
332
377
|
|
|
333
378
|
const text = typeof msg === "string" ? msg : (msg && msg.body != null ? String(msg.body) : "");
|
|
334
379
|
const attachment = (msg && typeof msg === "object") ? (msg.attachment || null) : null;
|
|
335
380
|
|
|
336
381
|
if (!attachment) {
|
|
382
|
+
// Call the controller's E2EE senders directly: client.sendMessage() silently falls
|
|
383
|
+
// back to the regular (MQTT) sender when the socket flag is down, and that sender
|
|
384
|
+
// routes back into this bridge -> endless recursion / message never delivered.
|
|
385
|
+
const ctl = this.client.controller;
|
|
386
|
+
const tid = String(threadId);
|
|
387
|
+
if (ctl && typeof ctl.sendE2EEText === "function" && typeof ctl.sendE2EEGroupText === "function") {
|
|
388
|
+
const isGroupJid = tid.includes("@g.us") || tid.includes(".g.");
|
|
389
|
+
const messageId = isGroupJid
|
|
390
|
+
? await ctl.sendE2EEGroupText(tid, text, replyToMessageId, undefined)
|
|
391
|
+
: await ctl.sendE2EEText(tid, text, replyToMessageId, undefined);
|
|
392
|
+
return { messageId, timestampMs: Date.now() };
|
|
393
|
+
}
|
|
337
394
|
return this.client.sendMessage({ threadId, text, replyToMessageId });
|
|
338
395
|
}
|
|
339
396
|
|
|
@@ -382,21 +439,25 @@ class E2EEBridge {
|
|
|
382
439
|
|
|
383
440
|
async sendReaction(threadId, messageId, reaction, senderJid) {
|
|
384
441
|
this.ensureConnected();
|
|
442
|
+
await this._waitReady();
|
|
385
443
|
return this.client.sendReaction({ threadId, messageId, reaction, senderJid });
|
|
386
444
|
}
|
|
387
445
|
|
|
388
446
|
async sendTyping(threadId, isTyping) {
|
|
389
447
|
this.ensureConnected();
|
|
448
|
+
await this._waitReady(3000);
|
|
390
449
|
return this.client.sendTyping({ threadId, isTyping: isTyping !== false });
|
|
391
450
|
}
|
|
392
451
|
|
|
393
452
|
async unsendMessage(messageId, threadId) {
|
|
394
453
|
this.ensureConnected();
|
|
454
|
+
await this._waitReady();
|
|
395
455
|
return this.client.unsendMessage({ messageId, threadId });
|
|
396
456
|
}
|
|
397
457
|
|
|
398
458
|
async editMessage(threadId, messageId, newText) {
|
|
399
459
|
this.ensureConnected();
|
|
460
|
+
await this._waitReady();
|
|
400
461
|
return this.client.editMessage({ threadId, messageId, newText });
|
|
401
462
|
}
|
|
402
463
|
|
|
@@ -62,26 +62,49 @@ function encodeFrame(type, senderID, threadID, header, payload) {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
function decodeFrame(buf) {
|
|
65
|
-
if (
|
|
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
|
+
}
|
|
66
72
|
if (buf.length < 8) throw new Error("Frame too short");
|
|
67
73
|
let offset = 0;
|
|
68
74
|
|
|
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
|
+
|
|
69
89
|
const magic = buf.readUInt16BE(offset); offset += 2;
|
|
70
90
|
if (magic !== MAGIC) throw new Error("Invalid frame magic: " + magic.toString(16));
|
|
71
91
|
const version = buf.readUInt8(offset); offset += 1;
|
|
92
|
+
if (version !== VERSION) throw new Error("Unsupported frame version: " + version);
|
|
72
93
|
const type = buf.readUInt8(offset); offset += 1;
|
|
94
|
+
if (!Object.values(TYPE).includes(type)) throw new Error("Invalid frame type: " + type);
|
|
73
95
|
|
|
74
|
-
const sidLen =
|
|
75
|
-
const senderID = buf.
|
|
96
|
+
const sidLen = readLength("sender ID");
|
|
97
|
+
const senderID = buf.subarray(offset, offset + sidLen).toString("utf8"); offset += sidLen;
|
|
76
98
|
|
|
77
|
-
const tidLen =
|
|
78
|
-
const threadID = buf.
|
|
99
|
+
const tidLen = readLength("thread ID");
|
|
100
|
+
const threadID = buf.subarray(offset, offset + tidLen).toString("utf8"); offset += tidLen;
|
|
79
101
|
|
|
80
|
-
const hdrLen =
|
|
81
|
-
const header = buf.
|
|
102
|
+
const hdrLen = readLength("header");
|
|
103
|
+
const header = buf.subarray(offset, offset + hdrLen); offset += hdrLen;
|
|
82
104
|
|
|
83
|
-
const payLen =
|
|
84
|
-
const payload = buf.
|
|
105
|
+
const payLen = readLength("payload");
|
|
106
|
+
const payload = buf.subarray(offset, offset + payLen); offset += payLen;
|
|
107
|
+
if (offset !== buf.length) throw new Error("Unexpected trailing bytes in frame");
|
|
85
108
|
|
|
86
109
|
return { version, type, senderID, threadID, header, payload };
|
|
87
110
|
}
|