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
|
@@ -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
|
]));
|
|
@@ -44,7 +44,24 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
44
44
|
};
|
|
45
45
|
|
|
46
46
|
// Start regular MQTT listener
|
|
47
|
-
var
|
|
47
|
+
var mqttListener = api._listenMqttRaw || api.listenMqtt;
|
|
48
|
+
if (typeof mqttListener !== "function") {
|
|
49
|
+
throw new Error("listenE2EE: MQTT listener is not available");
|
|
50
|
+
}
|
|
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);
|
|
48
65
|
api._mqttEmitter = mqttEmitter;
|
|
49
66
|
|
|
50
67
|
// [Fixed by xalman] Hook E2EE incoming messages (FCA-NX native Noise WebSocket).
|