fca-nx 6.7.3 → 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 +10 -0
- package/module/loginHelper.js +5 -7
- package/package.json +1 -1
- package/src/api/messaging/sendTypingIndicator.js +15 -0
- package/src/api/socket/core/connectMqtt.js +19 -1
- 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 +14 -1
- package/src/api/socket/listenMqtt.js +11 -1
- package/src/api/socket/sendMessage.js +21 -0
package/README.md
CHANGED
|
@@ -132,6 +132,16 @@ 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
|
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();
|
package/package.json
CHANGED
|
@@ -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);
|
|
@@ -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) {
|
|
@@ -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
|
}
|
|
@@ -95,6 +95,29 @@ 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) {
|
|
98
121
|
const { dh_pub, pn, n } = this._parseHeader(header);
|
|
99
122
|
const aadFull = aad ? Buffer.concat([aad, header]) : header;
|
|
100
123
|
|
|
@@ -127,6 +150,9 @@ class DoubleRatchetSession {
|
|
|
127
150
|
if (this.Nr + MAX_SKIP < until) throw new Error("Too many skipped messages: " + until);
|
|
128
151
|
if (this.CKr) {
|
|
129
152
|
while (this.Nr < until) {
|
|
153
|
+
if (this.MKSKIPPED.size >= MAX_SKIP) {
|
|
154
|
+
throw new Error("Skipped message key limit exceeded");
|
|
155
|
+
}
|
|
130
156
|
const { ck, mk } = kdfCK(this.CKr);
|
|
131
157
|
this.CKr = ck;
|
|
132
158
|
const key = `${this.DHr.toString("hex")}:${this.Nr}`;
|
|
@@ -165,7 +191,9 @@ class DoubleRatchetSession {
|
|
|
165
191
|
}
|
|
166
192
|
|
|
167
193
|
_parseHeader(header) {
|
|
168
|
-
if (header.length
|
|
194
|
+
if (!Buffer.isBuffer(header) || header.length !== 40) {
|
|
195
|
+
throw new Error("Invalid ratchet header length");
|
|
196
|
+
}
|
|
169
197
|
return {
|
|
170
198
|
dh_pub: header.slice(0, 32),
|
|
171
199
|
pn: header.readUInt32BE(32),
|
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* E2EE Device/Session Store
|
|
5
|
-
* Persists key material to a JSON file (encrypted with
|
|
5
|
+
* Persists key material to a JSON file (encrypted with an external secret).
|
|
6
6
|
* Each E2EE session (thread) is stored separately.
|
|
7
|
+
*
|
|
8
|
+
* Set FCA_NX_E2EE_STORE_KEY to a high-entropy secret, or pass
|
|
9
|
+
* { encryptionKey } as the third constructor argument. The key is never saved
|
|
10
|
+
* beside the encrypted data.
|
|
7
11
|
*/
|
|
8
12
|
|
|
9
13
|
const fs = require("fs");
|
|
@@ -11,15 +15,26 @@ const path = require("path");
|
|
|
11
15
|
const crypto = require("crypto");
|
|
12
16
|
|
|
13
17
|
class E2EEStore {
|
|
14
|
-
constructor(storePath, userID) {
|
|
18
|
+
constructor(storePath, userID, options = {}) {
|
|
19
|
+
if (typeof storePath !== "string" || !storePath.trim()) {
|
|
20
|
+
throw new TypeError("E2EE store path must be a non-empty string.");
|
|
21
|
+
}
|
|
22
|
+
if ((typeof userID !== "string" && typeof userID !== "number") ||
|
|
23
|
+
!/^[A-Za-z0-9._-]{1,128}$/.test(String(userID))) {
|
|
24
|
+
throw new TypeError("E2EE user ID contains unsupported path characters.");
|
|
25
|
+
}
|
|
26
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) options = {};
|
|
27
|
+
|
|
15
28
|
this.storePath = storePath;
|
|
16
|
-
this.userID = userID;
|
|
29
|
+
this.userID = String(userID);
|
|
30
|
+
this.encryptionKey = Object.prototype.hasOwnProperty.call(options, "encryptionKey")
|
|
31
|
+
? options.encryptionKey
|
|
32
|
+
: (process.env.FCA_NX_E2EE_STORE_KEY || "");
|
|
17
33
|
this.data = {
|
|
18
34
|
identityKey: null,
|
|
19
35
|
signedPreKey: null,
|
|
20
36
|
oneTimePreKeys: [],
|
|
21
|
-
sessions: {}
|
|
22
|
-
deviceSecret: null // 32-byte random secret for local encryption
|
|
37
|
+
sessions: {} // threadID -> serialized DoubleRatchetSession
|
|
23
38
|
};
|
|
24
39
|
this._loaded = false;
|
|
25
40
|
}
|
|
@@ -28,36 +43,96 @@ class E2EEStore {
|
|
|
28
43
|
return path.join(this.storePath, `fcanx_e2ee_${this.userID}.json`);
|
|
29
44
|
}
|
|
30
45
|
|
|
31
|
-
|
|
32
|
-
|
|
46
|
+
_requireEncryptionKey() {
|
|
47
|
+
if (typeof this.encryptionKey !== "string" || this.encryptionKey.length < 32) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
"E2EE store encryption key is missing or too short. Set FCA_NX_E2EE_STORE_KEY to a secret of at least 32 characters."
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
_deriveStorageKey(salt) {
|
|
55
|
+
this._requireEncryptionKey();
|
|
56
|
+
return crypto.scryptSync(this.encryptionKey, salt, 32, {
|
|
57
|
+
N: 16384,
|
|
58
|
+
r: 8,
|
|
59
|
+
p: 1,
|
|
60
|
+
maxmem: 32 * 1024 * 1024
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
_associatedData() {
|
|
65
|
+
return Buffer.from(`fca-nx-e2ee-store:v2:${this.userID}`, "utf8");
|
|
33
66
|
}
|
|
34
67
|
|
|
35
68
|
_localEncrypt(data) {
|
|
36
|
-
|
|
37
|
-
const key =
|
|
38
|
-
if (key.length !== 32) return data;
|
|
69
|
+
const salt = crypto.randomBytes(16);
|
|
70
|
+
const key = this._deriveStorageKey(salt);
|
|
39
71
|
const iv = crypto.randomBytes(12);
|
|
40
72
|
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
|
|
73
|
+
cipher.setAAD(this._associatedData());
|
|
41
74
|
const enc = Buffer.concat([cipher.update(Buffer.from(data, "utf8")), cipher.final()]);
|
|
42
75
|
const tag = cipher.getAuthTag();
|
|
43
|
-
return
|
|
76
|
+
return {
|
|
77
|
+
version: 2,
|
|
78
|
+
salt: salt.toString("base64"),
|
|
79
|
+
iv: iv.toString("base64"),
|
|
80
|
+
tag: tag.toString("base64"),
|
|
81
|
+
payload: enc.toString("base64")
|
|
82
|
+
};
|
|
44
83
|
}
|
|
45
84
|
|
|
46
|
-
_localDecrypt(
|
|
47
|
-
if (!
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
85
|
+
_localDecrypt(envelope) {
|
|
86
|
+
if (!envelope || envelope.version !== 2) {
|
|
87
|
+
throw new Error("Unsupported E2EE store format.");
|
|
88
|
+
}
|
|
89
|
+
const salt = decodeBase64(envelope.salt, "salt");
|
|
90
|
+
const iv = decodeBase64(envelope.iv, "IV");
|
|
91
|
+
const tag = decodeBase64(envelope.tag, "authentication tag");
|
|
92
|
+
const encrypted = decodeBase64(envelope.payload, "payload");
|
|
93
|
+
if (salt.length !== 16 || iv.length !== 12 || tag.length !== 16) {
|
|
94
|
+
throw new Error("Invalid E2EE store encryption metadata.");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const key = this._deriveStorageKey(salt);
|
|
98
|
+
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
|
|
99
|
+
decipher.setAAD(this._associatedData());
|
|
100
|
+
decipher.setAuthTag(tag);
|
|
101
|
+
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
_decryptLegacy(parsed) {
|
|
105
|
+
this._requireEncryptionKey();
|
|
106
|
+
const legacyKey = decodeBase64(parsed.deviceSecret, "legacy device secret");
|
|
107
|
+
const packed = decodeBase64(parsed.payload, "legacy payload");
|
|
108
|
+
if (legacyKey.length !== 32 || packed.length < 28) {
|
|
109
|
+
throw new Error("Invalid legacy E2EE store.");
|
|
60
110
|
}
|
|
111
|
+
|
|
112
|
+
const decipher = crypto.createDecipheriv("aes-256-gcm", legacyKey, packed.subarray(0, 12));
|
|
113
|
+
decipher.setAuthTag(packed.subarray(12, 28));
|
|
114
|
+
return Buffer.concat([
|
|
115
|
+
decipher.update(packed.subarray(28)),
|
|
116
|
+
decipher.final()
|
|
117
|
+
]).toString("utf8");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
_applyPayload(payload) {
|
|
121
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
122
|
+
throw new Error("Invalid E2EE store payload.");
|
|
123
|
+
}
|
|
124
|
+
if (payload.oneTimePreKeys !== undefined && !Array.isArray(payload.oneTimePreKeys)) {
|
|
125
|
+
throw new Error("Invalid E2EE one-time pre-key list.");
|
|
126
|
+
}
|
|
127
|
+
if (payload.sessions !== undefined &&
|
|
128
|
+
(!payload.sessions || typeof payload.sessions !== "object" || Array.isArray(payload.sessions))) {
|
|
129
|
+
throw new Error("Invalid E2EE session map.");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
this.data.identityKey = payload.identityKey || null;
|
|
133
|
+
this.data.signedPreKey = payload.signedPreKey || null;
|
|
134
|
+
this.data.oneTimePreKeys = payload.oneTimePreKeys || [];
|
|
135
|
+
this.data.sessions = payload.sessions || {};
|
|
61
136
|
}
|
|
62
137
|
|
|
63
138
|
load() {
|
|
@@ -66,35 +141,50 @@ class E2EEStore {
|
|
|
66
141
|
try {
|
|
67
142
|
const raw = fs.readFileSync(file, "utf8");
|
|
68
143
|
const parsed = JSON.parse(raw);
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
this.
|
|
75
|
-
this.data.sessions = payload.sessions || {};
|
|
144
|
+
const isLegacy = parsed && parsed.version === undefined &&
|
|
145
|
+
typeof parsed.deviceSecret === "string";
|
|
146
|
+
const decrypted = isLegacy
|
|
147
|
+
? this._decryptLegacy(parsed)
|
|
148
|
+
: this._localDecrypt(parsed);
|
|
149
|
+
this._applyPayload(JSON.parse(decrypted));
|
|
76
150
|
this._loaded = true;
|
|
151
|
+
|
|
152
|
+
// Upgrade legacy files immediately so future writes do not keep the
|
|
153
|
+
// old colocated-key format.
|
|
154
|
+
if (isLegacy) this.save();
|
|
77
155
|
return true;
|
|
78
|
-
} catch (
|
|
79
|
-
|
|
156
|
+
} catch (error) {
|
|
157
|
+
throw new Error(`Unable to load E2EE store: ${error.message}`);
|
|
80
158
|
}
|
|
81
159
|
}
|
|
82
160
|
|
|
83
161
|
save() {
|
|
84
|
-
|
|
85
|
-
fs.mkdirSync(this.storePath, { recursive: true });
|
|
86
|
-
}
|
|
87
|
-
if (!this.data.deviceSecret) {
|
|
88
|
-
this.data.deviceSecret = crypto.randomBytes(32).toString("base64");
|
|
89
|
-
}
|
|
162
|
+
this._requireEncryptionKey();
|
|
90
163
|
const payload = JSON.stringify({
|
|
91
164
|
identityKey: this.data.identityKey,
|
|
92
165
|
signedPreKey: this.data.signedPreKey,
|
|
93
166
|
oneTimePreKeys: this.data.oneTimePreKeys,
|
|
94
167
|
sessions: this.data.sessions
|
|
95
168
|
});
|
|
96
|
-
const encrypted = this._localEncrypt(payload);
|
|
97
|
-
fs.
|
|
169
|
+
const encrypted = JSON.stringify(this._localEncrypt(payload));
|
|
170
|
+
fs.mkdirSync(this.storePath, { recursive: true, mode: 0o700 });
|
|
171
|
+
|
|
172
|
+
const file = this._storeFile();
|
|
173
|
+
const tempFile = `${file}.${process.pid}.${crypto.randomBytes(8).toString("hex")}.tmp`;
|
|
174
|
+
let fd;
|
|
175
|
+
try {
|
|
176
|
+
fd = fs.openSync(tempFile, "wx", 0o600);
|
|
177
|
+
fs.writeFileSync(fd, encrypted, "utf8");
|
|
178
|
+
fs.fsyncSync(fd);
|
|
179
|
+
fs.closeSync(fd);
|
|
180
|
+
fd = undefined;
|
|
181
|
+
fs.renameSync(tempFile, file);
|
|
182
|
+
} finally {
|
|
183
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
184
|
+
try {
|
|
185
|
+
if (fs.existsSync(tempFile)) fs.unlinkSync(tempFile);
|
|
186
|
+
} catch (_) {}
|
|
187
|
+
}
|
|
98
188
|
}
|
|
99
189
|
|
|
100
190
|
hasIdentityKey() { return !!this.data.identityKey; }
|
|
@@ -179,4 +269,12 @@ class E2EEStore {
|
|
|
179
269
|
deleteSession(threadID) { delete this.data.sessions[threadID]; }
|
|
180
270
|
}
|
|
181
271
|
|
|
272
|
+
function decodeBase64(value, label) {
|
|
273
|
+
if (typeof value !== "string" ||
|
|
274
|
+
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
|
|
275
|
+
throw new Error(`Invalid E2EE store ${label}.`);
|
|
276
|
+
}
|
|
277
|
+
return Buffer.from(value, "base64");
|
|
278
|
+
}
|
|
279
|
+
|
|
182
280
|
module.exports = { E2EEStore };
|
|
@@ -5099,6 +5099,30 @@ function decryptMedia(opts) {
|
|
|
5099
5099
|
}
|
|
5100
5100
|
|
|
5101
5101
|
// src/e2ee/signal/signal-manager.ts
|
|
5102
|
+
// ── [Fixed by xalman] Global Signal session lock ───────────────────────────
|
|
5103
|
+
// libsignal's load-session -> encrypt/decrypt -> save-session cycle is NOT atomic
|
|
5104
|
+
// in Node. Incoming frames and outgoing sends ran concurrently, so two operations
|
|
5105
|
+
// on the same session could read the same record and the later save overwrote the
|
|
5106
|
+
// earlier one (lost ratchet state -> "old counter" errors -> dropped messages).
|
|
5107
|
+
// Every operation that touches the Signal stores now runs through this queue.
|
|
5108
|
+
var _iqSeq = 0;
|
|
5109
|
+
function nextIqId(prefix) {
|
|
5110
|
+
// [Fixed by xalman] ids built from Date.now() alone collide when two requests start in the
|
|
5111
|
+
// same millisecond (pendingIQs entry overwritten -> that IQ never resolves -> send fails).
|
|
5112
|
+
_iqSeq = (_iqSeq + 1) % 1e9;
|
|
5113
|
+
return `${prefix}${Date.now()}-${_iqSeq.toString(36)}`;
|
|
5114
|
+
}
|
|
5115
|
+
var _signalLockTail = Promise.resolve();
|
|
5116
|
+
function withSignalLock(fn) {
|
|
5117
|
+
const run = _signalLockTail.then(fn);
|
|
5118
|
+
_signalLockTail = new Promise((resolve) => {
|
|
5119
|
+
const t = setTimeout(resolve, 3e4); // safety: never block the queue forever
|
|
5120
|
+
if (t.unref) t.unref();
|
|
5121
|
+
const done = () => { clearTimeout(t); resolve(); };
|
|
5122
|
+
run.then(done, done);
|
|
5123
|
+
});
|
|
5124
|
+
return run;
|
|
5125
|
+
}
|
|
5102
5126
|
init_cjs_shims();
|
|
5103
5127
|
var import_libsignal_client5 = require("@signalapp/libsignal-client");
|
|
5104
5128
|
var import_node_crypto8 = require("crypto");
|
|
@@ -5344,32 +5368,38 @@ function listSenderKeyDistributionIds(store, senderAddr) {
|
|
|
5344
5368
|
const list = store.listSenderKeyDistributionIds;
|
|
5345
5369
|
return typeof list === "function" ? list.call(store, senderAddr) : [];
|
|
5346
5370
|
}
|
|
5347
|
-
|
|
5371
|
+
function establishSession(...a) { return withSignalLock(() => _establishSession_unlocked(...a)); }
|
|
5372
|
+
async function _establishSession_unlocked(store, recipient, rawBundle) {
|
|
5348
5373
|
const bundle = buildPreKeyBundle(rawBundle);
|
|
5349
5374
|
await (0, import_libsignal_client5.processPreKeyBundle)(bundle, recipient, store, store);
|
|
5350
5375
|
}
|
|
5351
|
-
|
|
5376
|
+
function encryptDM(...a) { return withSignalLock(() => _encryptDM_unlocked(...a)); }
|
|
5377
|
+
async function _encryptDM_unlocked(store, recipient, selfAddress, plaintext) {
|
|
5352
5378
|
const cipherMsg = await (0, import_libsignal_client5.signalEncrypt)(u83(plaintext), recipient, store, store);
|
|
5353
5379
|
const type = cipherMsg.type() === import_libsignal_client5.CiphertextMessageType.Whisper ? "msg" : "pkmsg";
|
|
5354
5380
|
return { type, ciphertext: cipherMsg.serialize() };
|
|
5355
5381
|
}
|
|
5356
|
-
|
|
5382
|
+
function decryptDM(...a) { return withSignalLock(() => _decryptDM_unlocked(...a)); }
|
|
5383
|
+
async function _decryptDM_unlocked(store, sender, ciphertext) {
|
|
5357
5384
|
const msg = import_libsignal_client5.SignalMessage.deserialize(u83(ciphertext));
|
|
5358
5385
|
return Buffer.from(await (0, import_libsignal_client5.signalDecrypt)(msg, sender, store, store));
|
|
5359
5386
|
}
|
|
5360
|
-
|
|
5387
|
+
function decryptDMPreKey(...a) { return withSignalLock(() => _decryptDMPreKey_unlocked(...a)); }
|
|
5388
|
+
async function _decryptDMPreKey_unlocked(store, sender, selfAddress, ciphertext) {
|
|
5361
5389
|
const msg = import_libsignal_client5.PreKeySignalMessage.deserialize(u83(ciphertext));
|
|
5362
5390
|
return Buffer.from(
|
|
5363
5391
|
await (0, import_libsignal_client5.signalDecryptPreKey)(msg, sender, store, store, store, store, store)
|
|
5364
5392
|
);
|
|
5365
5393
|
}
|
|
5366
|
-
|
|
5394
|
+
function createSenderKeyDistributionMessage(...a) { return withSignalLock(() => _createSenderKeyDistributionMessage_unlocked(...a)); }
|
|
5395
|
+
async function _createSenderKeyDistributionMessage_unlocked(store, groupJid, senderJid) {
|
|
5367
5396
|
const distributionId = (0, import_node_crypto8.randomUUID)();
|
|
5368
5397
|
const senderAddr = jidToAddress(senderJid);
|
|
5369
5398
|
const skdm = await import_libsignal_client5.SenderKeyDistributionMessage.create(senderAddr, distributionId, store);
|
|
5370
5399
|
return { skdm, distributionId };
|
|
5371
5400
|
}
|
|
5372
|
-
|
|
5401
|
+
function processSKDM(...a) { return withSignalLock(() => _processSKDM_unlocked(...a)); }
|
|
5402
|
+
async function _processSKDM_unlocked(store, senderJid, skdmBytes, groupJid) {
|
|
5373
5403
|
const senderAddr = jidToAddress(senderJid);
|
|
5374
5404
|
const buf = u83(skdmBytes);
|
|
5375
5405
|
const processAndAlias = async (skdm) => {
|
|
@@ -5397,7 +5427,8 @@ async function processSKDM(store, senderJid, skdmBytes, groupJid) {
|
|
|
5397
5427
|
throw primaryErr;
|
|
5398
5428
|
}
|
|
5399
5429
|
}
|
|
5400
|
-
|
|
5430
|
+
function encryptGroup(...a) { return withSignalLock(() => _encryptGroup_unlocked(...a)); }
|
|
5431
|
+
async function _encryptGroup_unlocked(store, groupJid, senderJid, plaintext, distributionId) {
|
|
5401
5432
|
const activeDistributionId = distributionId ?? (0, import_node_crypto8.randomUUID)();
|
|
5402
5433
|
const senderAddr = jidToAddress(senderJid);
|
|
5403
5434
|
const cipherMsg = await (0, import_libsignal_client5.groupEncrypt)(senderAddr, activeDistributionId, store, u83(plaintext));
|
|
@@ -5422,7 +5453,8 @@ async function encryptGroup(store, groupJid, senderJid, plaintext, distributionI
|
|
|
5422
5453
|
}
|
|
5423
5454
|
return buf;
|
|
5424
5455
|
}
|
|
5425
|
-
|
|
5456
|
+
function decryptGroup(...a) { return withSignalLock(() => _decryptGroup_unlocked(...a)); }
|
|
5457
|
+
async function _decryptGroup_unlocked(store, senderJid, ciphertext, groupJid) {
|
|
5426
5458
|
const senderAddrs = addressCandidatesForJid(senderJid);
|
|
5427
5459
|
const senderAddr = senderAddrs[0];
|
|
5428
5460
|
let buf = u83(ciphertext);
|
|
@@ -6118,10 +6150,33 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6118
6150
|
url;
|
|
6119
6151
|
heartbeatInterval = null;
|
|
6120
6152
|
isConnected = false;
|
|
6153
|
+
lastInboundAt = Date.now();
|
|
6154
|
+
_disconnectedEmitted = false;
|
|
6121
6155
|
constructor(endpoint) {
|
|
6122
6156
|
super();
|
|
6123
6157
|
this.url = endpoint;
|
|
6124
6158
|
}
|
|
6159
|
+
// [Fixed by xalman] emit "disconnected" exactly once per socket (close event, watchdog and
|
|
6160
|
+
// read-loop failure could all fire it -> several parallel reconnects -> duplicate sockets).
|
|
6161
|
+
_emitDisconnectedOnce() {
|
|
6162
|
+
if (this._disconnectedEmitted) return;
|
|
6163
|
+
this._disconnectedEmitted = true;
|
|
6164
|
+
this.emit("disconnected");
|
|
6165
|
+
}
|
|
6166
|
+
// [Fixed by xalman] A half-open TCP connection (NAT/proxy dropped it) never fires "close", so
|
|
6167
|
+
// the bot looked connected but was deaf. Force the socket down so the reconnect logic runs.
|
|
6168
|
+
forceDisconnect(reason) {
|
|
6169
|
+
logger.warn("FacebookE2EESocket", `Forcing E2EE socket down: ${reason}`);
|
|
6170
|
+
this.isConnected = false;
|
|
6171
|
+
this.stopHeartbeat();
|
|
6172
|
+
try {
|
|
6173
|
+
if (this.ws && typeof this.ws.terminate === "function") this.ws.terminate();
|
|
6174
|
+
else this.ws?.close();
|
|
6175
|
+
} catch (_) {
|
|
6176
|
+
}
|
|
6177
|
+
const t = setTimeout(() => this._emitDisconnectedOnce(), 3e3);
|
|
6178
|
+
if (t.unref) t.unref();
|
|
6179
|
+
}
|
|
6125
6180
|
async connect(noisePrivKey, authPayload) {
|
|
6126
6181
|
return new Promise((resolve, reject) => {
|
|
6127
6182
|
try {
|
|
@@ -6163,6 +6218,7 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6163
6218
|
let waitingResolver = null;
|
|
6164
6219
|
let waitingLen = 0;
|
|
6165
6220
|
this.ws.addEventListener("message", (ev) => {
|
|
6221
|
+
this.lastInboundAt = Date.now();
|
|
6166
6222
|
const frame = Buffer.from(ev.data);
|
|
6167
6223
|
streamBuffer.push(frame);
|
|
6168
6224
|
streamLen += frame.length;
|
|
@@ -6209,7 +6265,7 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6209
6265
|
waitingResolver(null);
|
|
6210
6266
|
waitingResolver = null;
|
|
6211
6267
|
}
|
|
6212
|
-
this.
|
|
6268
|
+
this._emitDisconnectedOnce();
|
|
6213
6269
|
});
|
|
6214
6270
|
this.ws.addEventListener("open", async () => {
|
|
6215
6271
|
try {
|
|
@@ -6237,8 +6293,14 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6237
6293
|
}
|
|
6238
6294
|
startHeartbeat() {
|
|
6239
6295
|
this.stopHeartbeat();
|
|
6296
|
+
this.lastInboundAt = Date.now();
|
|
6240
6297
|
this.heartbeatInterval = setInterval(async () => {
|
|
6241
6298
|
try {
|
|
6299
|
+
const idleLimit = Number(process.env.FCA_NX_E2EE_IDLE_TIMEOUT_MS ?? "120000");
|
|
6300
|
+
if (idleLimit > 0 && this.isConnected && Date.now() - this.lastInboundAt > idleLimit) {
|
|
6301
|
+
this.forceDisconnect(`no data received for ${Math.round((Date.now() - this.lastInboundAt) / 1e3)}s`);
|
|
6302
|
+
return;
|
|
6303
|
+
}
|
|
6242
6304
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
6243
6305
|
logger.debug("NoiseSocket", "Sending Noise heartbeat (0,0,0)...");
|
|
6244
6306
|
this.ws.send(Buffer.from([0, 0, 0]));
|
|
@@ -6285,6 +6347,9 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6285
6347
|
logger.error("FacebookE2EESocket", "Read loop stopped due to error:", err);
|
|
6286
6348
|
this.isConnected = false;
|
|
6287
6349
|
this.emit("error", err);
|
|
6350
|
+
// [Fixed by xalman] the read loop is dead: without this the websocket stayed open but
|
|
6351
|
+
// nothing was ever read again (silent deaf bot). Drop the socket so it reconnects.
|
|
6352
|
+
this.forceDisconnect("read loop died");
|
|
6288
6353
|
}
|
|
6289
6354
|
}
|
|
6290
6355
|
async sendFrame(data) {
|
|
@@ -6999,6 +7064,15 @@ var E2EEHandler = class {
|
|
|
6999
7064
|
pendingIQs = /* @__PURE__ */ new Map();
|
|
7000
7065
|
retryReceipts = /* @__PURE__ */ new Map();
|
|
7001
7066
|
maxRetryReceiptsPerMessage = 2;
|
|
7067
|
+
seenMessageIds = /* @__PURE__ */ new Set();
|
|
7068
|
+
markSeen(id) {
|
|
7069
|
+
if (!id) return;
|
|
7070
|
+
this.seenMessageIds.add(id);
|
|
7071
|
+
if (this.seenMessageIds.size > 5e3) {
|
|
7072
|
+
const oldest = this.seenMessageIds.values().next().value;
|
|
7073
|
+
this.seenMessageIds.delete(oldest);
|
|
7074
|
+
}
|
|
7075
|
+
}
|
|
7002
7076
|
async handleEncryptedMessage(node, selfUserId, e2eeClient) {
|
|
7003
7077
|
const fromJid = node.attrs.from;
|
|
7004
7078
|
const participantJid = node.attrs.participant || node.attrs.from;
|
|
@@ -7097,7 +7171,11 @@ var E2EEHandler = class {
|
|
|
7097
7171
|
const transport = decodeMessageTransport(decrypted);
|
|
7098
7172
|
logger.debug("E2EEHandler", "Decrypted transport:", JSON.stringify(transport, null, 2));
|
|
7099
7173
|
chatJid = this.chatJidFromTransport(transport, chatJid);
|
|
7100
|
-
this.emitTransportApplication(transport, senderJid, chatJid, node.attrs.id);
|
|
7174
|
+
const emittedApp = this.emitTransportApplication(transport, senderJid, chatJid, node.attrs.id);
|
|
7175
|
+
this.markSeen(node.attrs.id);
|
|
7176
|
+
if (!emittedApp && !transport?.protocol?.ancillary?.skdm) {
|
|
7177
|
+
logger.warn("E2EEHandler", `Decrypted message ${node.attrs.id} from ${senderJid} but it produced no event (unsupported/empty payload)`);
|
|
7178
|
+
}
|
|
7101
7179
|
if (transport?.protocol?.ancillary?.skdm) {
|
|
7102
7180
|
const skdm = transport.protocol.ancillary.skdm;
|
|
7103
7181
|
const gid = skdm.groupID || skdm.groupId || fromJid;
|
|
@@ -7110,6 +7188,19 @@ var E2EEHandler = class {
|
|
|
7110
7188
|
} catch (err) {
|
|
7111
7189
|
const isDuplicate = err.code === 1 || (err.message && err.message.includes("old counter"));
|
|
7112
7190
|
if (isDuplicate) {
|
|
7191
|
+
// [Fixed by xalman] Do not silently drop. A real replay (id already delivered) is
|
|
7192
|
+
// ignored, but a fresh message we have NEVER delivered means our session state is
|
|
7193
|
+
// out of sync -> log it and ask the sender to re-send with fresh keys (retry receipt).
|
|
7194
|
+
const msgId = node.attrs.id;
|
|
7195
|
+
if (this.seenMessageIds.has(msgId)) {
|
|
7196
|
+
logger.debug("E2EEHandler", `Ignoring replayed message ${msgId} from ${senderJid}`);
|
|
7197
|
+
} else {
|
|
7198
|
+
const ageSec = node.attrs.t ? Math.floor(now() / 1e3) - Number(node.attrs.t) : 0;
|
|
7199
|
+
logger.warn("E2EEHandler", `Old-counter error on UNSEEN message ${msgId} from ${senderJid} (age ${ageSec}s): ${err.message}`);
|
|
7200
|
+
if (!node.attrs.t || (ageSec >= -60 && ageSec <= 120)) {
|
|
7201
|
+
await this.maybeSendRetryReceipt(node, senderJid, chatJid, err);
|
|
7202
|
+
}
|
|
7203
|
+
}
|
|
7113
7204
|
this.sendAck(node);
|
|
7114
7205
|
return;
|
|
7115
7206
|
}
|
|
@@ -7340,7 +7431,7 @@ var E2EEHandler = class {
|
|
|
7340
7431
|
}
|
|
7341
7432
|
}
|
|
7342
7433
|
async getMediaUploadConfig() {
|
|
7343
|
-
const id =
|
|
7434
|
+
const id = nextIqId("mc-");
|
|
7344
7435
|
const iq = encodeIQ({ id, to: "s.whatsapp.net", type: "set", xmlns: "w:m" }, [
|
|
7345
7436
|
encodeNode("media_conn", {}, void 0)
|
|
7346
7437
|
]);
|
|
@@ -7390,7 +7481,7 @@ var E2EEHandler = class {
|
|
|
7390
7481
|
};
|
|
7391
7482
|
}
|
|
7392
7483
|
async getServerPreKeyCount() {
|
|
7393
|
-
const id =
|
|
7484
|
+
const id = nextIqId("pkc-");
|
|
7394
7485
|
const iq = encodeIQ({ id, to: "s.whatsapp.net", type: "get", xmlns: "encrypt" }, [
|
|
7395
7486
|
encodeNode("count", {}, void 0)
|
|
7396
7487
|
]);
|
|
@@ -7406,7 +7497,7 @@ var E2EEHandler = class {
|
|
|
7406
7497
|
});
|
|
7407
7498
|
}
|
|
7408
7499
|
async getGroupParticipants(groupJid) {
|
|
7409
|
-
const id =
|
|
7500
|
+
const id = nextIqId("gp-");
|
|
7410
7501
|
const iq = encodeIQ({ id, to: groupJid, type: "get", xmlns: "w:g2" }, [
|
|
7411
7502
|
encodeNode("query", { request: "interactive" }, void 0)
|
|
7412
7503
|
]);
|
|
@@ -7437,7 +7528,7 @@ var E2EEHandler = class {
|
|
|
7437
7528
|
}
|
|
7438
7529
|
async getDeviceList(userJids) {
|
|
7439
7530
|
if (userJids.length === 0) return [];
|
|
7440
|
-
const id =
|
|
7531
|
+
const id = nextIqId("dl-");
|
|
7441
7532
|
const iq = encodeIQ({
|
|
7442
7533
|
id,
|
|
7443
7534
|
to: "s.whatsapp.net",
|
|
@@ -7483,7 +7574,7 @@ var E2EEHandler = class {
|
|
|
7483
7574
|
return deviceJids;
|
|
7484
7575
|
}
|
|
7485
7576
|
async getPreKeyBundle(jid) {
|
|
7486
|
-
const id =
|
|
7577
|
+
const id = nextIqId("pkb-");
|
|
7487
7578
|
const iq = encodeIQ({ id, to: "s.whatsapp.net", type: "get", xmlns: "encrypt" }, [
|
|
7488
7579
|
encodeNode("key", {}, [
|
|
7489
7580
|
encodeNode("user", { jid }, void 0)
|
|
@@ -7596,7 +7687,7 @@ var E2EEHandler = class {
|
|
|
7596
7687
|
async sendCleanIQ(type, timestamp) {
|
|
7597
7688
|
const socket = this.getSocket();
|
|
7598
7689
|
if (!socket) return;
|
|
7599
|
-
const id =
|
|
7690
|
+
const id = nextIqId("clean-");
|
|
7600
7691
|
const cleanIQ = encodeIQ({ id, to: "s.whatsapp.net", type: "set", xmlns: "urn:xmpp:whatsapp:dirty" }, [
|
|
7601
7692
|
encodeNode("clean", { type, timestamp }, void 0)
|
|
7602
7693
|
]);
|
|
@@ -8039,11 +8130,22 @@ var ClientController = class {
|
|
|
8039
8130
|
auth: ""
|
|
8040
8131
|
});
|
|
8041
8132
|
const endpoint = "wss://web-chat-e2ee.facebook.com/ws/chat?cid=client-" + now();
|
|
8133
|
+
// [Fixed by xalman] retire the previous socket so its late close/frames cannot flip the
|
|
8134
|
+
// state of the new connection (e2eeConnected=false, heartbeat stopped, duplicate messages).
|
|
8135
|
+
const previousSocket = this.e2eeSocket;
|
|
8136
|
+
if (previousSocket) {
|
|
8137
|
+
previousSocket._stale = true;
|
|
8138
|
+
try {
|
|
8139
|
+
previousSocket.close();
|
|
8140
|
+
} catch (_) {
|
|
8141
|
+
}
|
|
8142
|
+
}
|
|
8042
8143
|
const noiseSocket = new FacebookE2EESocket(endpoint);
|
|
8043
8144
|
noiseSocket.on("connected", () => {
|
|
8044
8145
|
this.eventMapper.emit({ type: "e2ee_connected", data: {} });
|
|
8045
8146
|
});
|
|
8046
8147
|
noiseSocket.on("disconnected", () => {
|
|
8148
|
+
if (noiseSocket._stale) return;
|
|
8047
8149
|
this.cleanup();
|
|
8048
8150
|
this.eventMapper.emit({ type: "disconnected", data: { isE2EE: true } });
|
|
8049
8151
|
});
|
|
@@ -8068,8 +8170,10 @@ var ClientController = class {
|
|
|
8068
8170
|
deviceId: ds.jidDevice ?? 0,
|
|
8069
8171
|
fbCatBase64: fbCat
|
|
8070
8172
|
});
|
|
8173
|
+
let messageChain = Promise.resolve(); // [Fixed by xalman] keep incoming messages in arrival order
|
|
8071
8174
|
noiseSocket.on("frame", async (rawFrame) => {
|
|
8072
8175
|
if (rawFrame.length === 0) return;
|
|
8176
|
+
if (noiseSocket._stale) return;
|
|
8073
8177
|
try {
|
|
8074
8178
|
const node = unmarshal(rawFrame);
|
|
8075
8179
|
if (["receipt", "notification", "iq", "presence", "call", "chatstate"].includes(node.tag) && node.attrs.id) {
|
|
@@ -8095,11 +8199,19 @@ var ClientController = class {
|
|
|
8095
8199
|
break;
|
|
8096
8200
|
case "message":
|
|
8097
8201
|
case "appdata":
|
|
8098
|
-
|
|
8202
|
+
messageChain = messageChain.then(() => this.e2eeHandler.handleEncryptedMessage(node, userId, client)).catch((err) => {
|
|
8203
|
+
logger.error("E2EE", "Message frame error:", err);
|
|
8204
|
+
});
|
|
8099
8205
|
break;
|
|
8100
8206
|
case "ib":
|
|
8101
8207
|
this.e2eeHandler.handleIB(node);
|
|
8102
8208
|
break;
|
|
8209
|
+
case "ack":
|
|
8210
|
+
// [Fixed by xalman] server-side rejections of our sends were silently ignored.
|
|
8211
|
+
if (node.attrs.error) {
|
|
8212
|
+
logger.warn("E2EE", `Server rejected ${node.attrs.class || "stanza"} id=${node.attrs.id} error=${node.attrs.error}`);
|
|
8213
|
+
}
|
|
8214
|
+
break;
|
|
8103
8215
|
}
|
|
8104
8216
|
} catch (err) {
|
|
8105
8217
|
logger.error("E2EE", "Frame error:", err);
|
|
@@ -8276,7 +8388,17 @@ var ClientController = class {
|
|
|
8276
8388
|
await e2eeClient.establishSession(deviceJid, bundle);
|
|
8277
8389
|
}
|
|
8278
8390
|
const payload = sameMessengerUser(deviceJid, selfJid) ? result.selfDevicePayload : result.devicePayload;
|
|
8279
|
-
|
|
8391
|
+
let encrypted;
|
|
8392
|
+
try {
|
|
8393
|
+
encrypted = await e2eeClient.encryptDevicePayload(deviceJid, selfJid, payload);
|
|
8394
|
+
} catch (firstErr) {
|
|
8395
|
+
// [Fixed by xalman] a stale/broken session used to silently drop that device from the
|
|
8396
|
+
// fanout. Rebuild the session from a fresh prekey bundle and try once more.
|
|
8397
|
+
logger.warn("ClientController", `Encrypt to ${deviceJid} failed (${firstErr && firstErr.message}); rebuilding session and retrying`);
|
|
8398
|
+
const freshBundle = await this.e2eeHandler.getPreKeyBundle(deviceJid);
|
|
8399
|
+
await e2eeClient.establishSession(deviceJid, freshBundle);
|
|
8400
|
+
encrypted = await e2eeClient.encryptDevicePayload(deviceJid, selfJid, payload);
|
|
8401
|
+
}
|
|
8280
8402
|
participantNodes.push(encodeNode("to", { jid: deviceJid }, [
|
|
8281
8403
|
encodeNode("enc", { v: "3", type: encrypted.type }, encrypted.ciphertext)
|
|
8282
8404
|
]));
|
|
@@ -48,7 +48,20 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
48
48
|
if (typeof mqttListener !== "function") {
|
|
49
49
|
throw new Error("listenE2EE: MQTT listener is not available");
|
|
50
50
|
}
|
|
51
|
-
|
|
51
|
+
// [Fixed by xalman] A DM message arriving over plain MQTT means the user is currently in the
|
|
52
|
+
// normal (non-E2EE) chat, so replies must NOT be diverted to the E2EE bridge. An E2EE message
|
|
53
|
+
// flips it back to 'dm' (see e2ee/index.js). Latest activity decides where the reply goes.
|
|
54
|
+
var mqttCallback = function (err, event) {
|
|
55
|
+
try {
|
|
56
|
+
if (!err && event && event.type === "message" && event.isGroup === false && !event.isE2EE &&
|
|
57
|
+
event.threadID && event.senderID !== ctx.userID) {
|
|
58
|
+
ctx.threadTypes = ctx.threadTypes || {};
|
|
59
|
+
ctx.threadTypes[String(event.threadID)] = "mqtt-dm";
|
|
60
|
+
}
|
|
61
|
+
} catch (_) { }
|
|
62
|
+
return globalCallback(err, event);
|
|
63
|
+
};
|
|
64
|
+
var mqttEmitter = mqttListener(mqttCallback);
|
|
52
65
|
api._mqttEmitter = mqttEmitter;
|
|
53
66
|
|
|
54
67
|
// [Fixed by xalman] Hook E2EE incoming messages (FCA-NX native Noise WebSocket).
|
|
@@ -109,6 +109,16 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
109
109
|
let isReconnecting = false;
|
|
110
110
|
|
|
111
111
|
function getReconnectDelay() {
|
|
112
|
+
// [Fixed by xalman] immediate first reconnect (see connectMqtt.js computeBackoff). Called with
|
|
113
|
+
// reconnectAttempts === 0 for a fresh cycle/disconnect and === 1 for the first retry after a
|
|
114
|
+
// failed getSeqID; both go out at once, later ones back off 1s, 2s, 4s ... up to 60s.
|
|
115
|
+
const immediate = process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT !== "0" && conf.immediateReconnect !== false;
|
|
116
|
+
if (immediate) {
|
|
117
|
+
if (reconnectAttempts <= 1) return 0;
|
|
118
|
+
const fast = Math.min(1000 * Math.pow(2, reconnectAttempts - 2), MAX_MQTT_RECONNECT_DELAY_MS);
|
|
119
|
+
const j = Math.floor(Math.random() * Math.min(500, fast * 0.2));
|
|
120
|
+
return Math.min(fast + j, MAX_MQTT_RECONNECT_DELAY_MS);
|
|
121
|
+
}
|
|
112
122
|
const base = conf.reconnectDelayMs || RECONNECT_DELAY_MS_DEFAULT;
|
|
113
123
|
const exp = Math.min(base * Math.pow(2, reconnectAttempts), MAX_MQTT_RECONNECT_DELAY_MS);
|
|
114
124
|
const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
|
|
@@ -345,7 +355,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
345
355
|
function delayedReconnect() {
|
|
346
356
|
if (ctx._ending) return;
|
|
347
357
|
const d = getReconnectDelay();
|
|
348
|
-
logger(`mqtt reconnect in ${d}ms`, "info");
|
|
358
|
+
logger(d === 0 ? "mqtt reconnecting immediately" : `mqtt reconnect in ${d}ms`, "info");
|
|
349
359
|
|
|
350
360
|
if (ctx._reconnectTimer) {
|
|
351
361
|
clearTimeout(ctx._reconnectTimer);
|
|
@@ -294,6 +294,27 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
294
294
|
return promise;
|
|
295
295
|
}
|
|
296
296
|
|
|
297
|
+
// [Fixed by xalman] Text replies to a DM whose latest activity was E2EE must go through the
|
|
298
|
+
// E2EE bridge. MQTT cannot deliver into an end-to-end encrypted chat: it waited 15s for an
|
|
299
|
+
// ack that never came, so every command that calls api.sendMessage() directly looked dead
|
|
300
|
+
// in inbox. (Group chats and normal MQTT DMs are unchanged.)
|
|
301
|
+
if (isSingleUser && !msg.attachment && !msg.sticker && !msg.location && !msg.emoji &&
|
|
302
|
+
api.e2ee && typeof api.e2ee.isConnected === "function" && api.e2ee.isConnected()) {
|
|
303
|
+
try {
|
|
304
|
+
var e2eeText = await api.e2ee.sendMessage(String(threadID), { body: msg.body != null ? String(msg.body) : "" }, replyToMessage || msg.replyToMessage);
|
|
305
|
+
var e2eeWrapped = e2eeText && e2eeText.messageId
|
|
306
|
+
? { threadID: String(threadID), messageID: String(e2eeText.messageId) }
|
|
307
|
+
: e2eeText;
|
|
308
|
+
if (callback) callback(null, e2eeWrapped);
|
|
309
|
+
else resolve(e2eeWrapped);
|
|
310
|
+
} catch (e2eeTextErr) {
|
|
311
|
+
logger.error("sendMessage", "E2EE DM text send failed: " + (e2eeTextErr.message || e2eeTextErr));
|
|
312
|
+
if (callback) callback(e2eeTextErr);
|
|
313
|
+
else reject(e2eeTextErr);
|
|
314
|
+
}
|
|
315
|
+
return promise;
|
|
316
|
+
}
|
|
317
|
+
|
|
297
318
|
try {
|
|
298
319
|
var result = await sendViaMqtt(msg, threadID, replyToMessage);
|
|
299
320
|
if (callback) callback(null, result);
|