fca-nx 6.7.3 → 6.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -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
- if (attempt < 3) {
1377
- const delayMs = 5000 * Math.pow(3, attempt); // 5s, 15s, 45s
1378
- logger(`E2EE auto-connect failed (attempt ${attempt + 1}/4): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
1379
- setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
1380
- } else {
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.3",
3
+ "version": "6.7.5",
4
4
  "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -2,7 +2,10 @@
2
2
 
3
3
  const log = require("../../../func/logAdapter");
4
4
  const { parseAndCheckLogin } = require("../../utils/client");
5
- const { getType } = require("../../utils/format");
5
+
6
+ // api.getThemePictures(themeID, callback?)
7
+ // themeID = the theme_fbid (digits), e.g. from api.getThreadInfo(tid).threadTheme.id
8
+ // or from an api.createThemeAI() result.
6
9
  module.exports = function (defaultFuncs, api, ctx) {
7
10
  return function getThemePictures(id, callback) {
8
11
  let resolveFunc = function () { };
@@ -12,24 +15,21 @@ module.exports = function (defaultFuncs, api, ctx) {
12
15
  rejectFunc = reject;
13
16
  });
14
17
 
15
- if (!callback) {
16
- if (
17
- getType(callback) == "Function" ||
18
- getType(callback) == "AsyncFunction"
19
- ) {
20
- callback = callback;
21
- } else {
22
- callback = function (err, data) {
23
- if (err) {
24
- return rejectFunc(err);
25
- }
26
- resolveFunc(data);
27
- };
28
- }
18
+ if (typeof callback !== "function") {
19
+ callback = function (err, data) {
20
+ if (err) return rejectFunc(err);
21
+ resolveFunc(data);
22
+ };
29
23
  }
30
24
 
31
- if (getType(id) != "String") {
32
- id = "";
25
+ // [Fixed by xalman] Accept numbers too. Before, any non-string id was silently
26
+ // replaced with "" and Facebook answered messenger_thread_theme: null.
27
+ if (typeof id === "number" || typeof id === "bigint") id = String(id);
28
+ id = typeof id === "string" ? id.trim() : "";
29
+
30
+ if (!/^\d+$/.test(id)) {
31
+ callback({ error: "getThemePictures: a numeric theme ID is required (theme_fbid), got: " + JSON.stringify(id) });
32
+ return returnPromise;
33
33
  }
34
34
 
35
35
  const form = {
@@ -37,19 +37,30 @@ module.exports = function (defaultFuncs, api, ctx) {
37
37
  fb_api_req_friendly_name: "MWPThreadThemeProviderQuery",
38
38
  doc_id: "9734829906576883",
39
39
  server_timestamps: true,
40
- variables: JSON.stringify({
41
- id
42
- }),
40
+ variables: JSON.stringify({ id }),
43
41
  av: ctx.userID
44
42
  };
43
+
45
44
  defaultFuncs
46
45
  .post("https://www.facebook.com/api/graphql/", ctx.jar, form)
47
46
  .then(parseAndCheckLogin(ctx, defaultFuncs))
48
47
  .then(function (resData) {
49
- if (resData.errors) {
48
+ if (resData && resData.errors) {
50
49
  throw resData;
51
50
  }
52
51
 
52
+ // [Fixed by xalman] The request itself worked (doc_id is valid) but Facebook has
53
+ // no theme with this ID for this account. Report it as a failure instead of "success".
54
+ if (!resData || !resData.data || !resData.data.messenger_thread_theme) {
55
+ const notFound = {
56
+ error: "Theme not found: Facebook returned no theme for ID " + id + ". Check the ID (use the theme_fbid of a real theme).",
57
+ themeID: id,
58
+ raw: resData
59
+ };
60
+ log.error("getThemePictures", notFound.error);
61
+ return callback(notFound);
62
+ }
63
+
53
64
  return callback(null, resData);
54
65
  })
55
66
  .catch(function (err) {
@@ -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,25 @@ 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
+ // [Fixed by xalman] opt-in only: instant reconnects can create overlapping sessions
27
+ return process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1";
28
+ }
29
+
19
30
  function computeBackoff(ctx, baseMs) {
20
31
  const attempt = (ctx._reconnectAttempts || 0);
32
+ if (isImmediateReconnect(ctx)) {
33
+ if (attempt <= 1) return 0; // first reconnect: right now
34
+ const fast = Math.min(1000 * Math.pow(2, attempt - 2), MAX_RECONNECT_DELAY_MS);
35
+ const j = Math.floor(Math.random() * Math.min(500, fast * 0.2));
36
+ return Math.min(fast + j, MAX_RECONNECT_DELAY_MS);
37
+ }
21
38
  const exp = Math.min(baseMs * Math.pow(2, attempt), MAX_RECONNECT_DELAY_MS);
22
39
  const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
23
40
  return Math.min(exp + jitter, MAX_RECONNECT_DELAY_MS);
@@ -62,7 +79,7 @@ module.exports = function createListenMqtt(deps) {
62
79
  return;
63
80
  }
64
81
  const ms = typeof delayMs === "number" ? delayMs : computeBackoff(ctx, base);
65
- logger(`mqtt will reconnect in ${ms}ms (attempt ${ctx._reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`, "warn");
82
+ logger(`mqtt ${ms === 0 ? "reconnecting immediately" : "will reconnect in " + ms + "ms"} (attempt ${ctx._reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`, "warn");
66
83
  ctx._reconnectTimer = setTimeout(() => {
67
84
  ctx._reconnectTimer = null;
68
85
  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 = path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
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.client.onEvent("disconnected", function _onE2EEDisconnected() {
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
- setTimeout(async function () {
210
- if (!_self.connected) return;
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
- logger.success("E2EE", "E2EE WebSocket reconnected.");
227
+ _self._reconnecting = false;
228
+ logger.success("E2EE", "E2EE WebSocket reconnected" + (attempt > 1 ? " (attempt " + attempt + ")" : "") + ".");
214
229
  } catch (err) {
215
- logger.error("E2EE", "E2EE reconnect failed: " + (err && err.message ? err.message : String(err)));
216
- // Retry again after another 10s if reconnect failed
217
- if (_self.connected) {
218
- setTimeout(async function () {
219
- if (!_self.connected) return;
220
- try {
221
- await _self.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
222
- logger.success("E2EE", "E2EE WebSocket reconnected (retry).");
223
- } catch (err2) {
224
- logger.error("E2EE", "E2EE reconnect retry failed: " + (err2 && err2.message ? err2.message : String(err2)));
225
- }
226
- }, 10000);
227
- }
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
- }, 5000);
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) return;
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
- this._messageCallback(null, event);
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 (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
65
+ if (Buffer.isBuffer(buf)) {
66
+ // Use the caller's buffer directly.
67
+ } else if (buf instanceof Uint8Array) {
68
+ buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
69
+ } else {
70
+ throw new TypeError("Frame must be a Buffer or Uint8Array");
71
+ }
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 = buf.readUInt32BE(offset); offset += 4;
75
- const senderID = buf.slice(offset, offset + sidLen).toString("utf8"); offset += sidLen;
96
+ const sidLen = readLength("sender ID");
97
+ const senderID = buf.subarray(offset, offset + sidLen).toString("utf8"); offset += sidLen;
76
98
 
77
- const tidLen = buf.readUInt32BE(offset); offset += 4;
78
- const threadID = buf.slice(offset, offset + tidLen).toString("utf8"); offset += tidLen;
99
+ const tidLen = readLength("thread ID");
100
+ const threadID = buf.subarray(offset, offset + tidLen).toString("utf8"); offset += tidLen;
79
101
 
80
- const hdrLen = buf.readUInt32BE(offset); offset += 4;
81
- const header = buf.slice(offset, offset + hdrLen); offset += hdrLen;
102
+ const hdrLen = readLength("header");
103
+ const header = buf.subarray(offset, offset + hdrLen); offset += hdrLen;
82
104
 
83
- const payLen = buf.readUInt32BE(offset); offset += 4;
84
- const payload = buf.slice(offset, offset + payLen);
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 < 40) throw new Error("Invalid ratchet 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 a device secret).
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: {}, // threadID -> serialized DoubleRatchetSession
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
- _salt() {
32
- return Buffer.from(this.userID.padEnd(16, "0").slice(0, 16), "utf8");
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
- if (!this.data.deviceSecret) return data;
37
- const key = Buffer.from(this.data.deviceSecret, "base64");
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 Buffer.concat([iv, tag, enc]).toString("base64");
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(data) {
47
- if (!this.data.deviceSecret) return data;
48
- try {
49
- const key = Buffer.from(this.data.deviceSecret, "base64");
50
- if (key.length !== 32) return data;
51
- const buf = Buffer.from(data, "base64");
52
- const iv = buf.slice(0, 12);
53
- const tag = buf.slice(12, 28);
54
- const enc = buf.slice(28);
55
- const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
56
- decipher.setAuthTag(tag);
57
- return Buffer.concat([decipher.update(enc), decipher.final()]).toString("utf8");
58
- } catch (_) {
59
- return data;
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
- if (parsed.deviceSecret) this.data.deviceSecret = parsed.deviceSecret;
70
- const decrypted = this._localDecrypt(parsed.payload || "{}");
71
- const payload = JSON.parse(decrypted);
72
- this.data.identityKey = payload.identityKey || null;
73
- this.data.signedPreKey = payload.signedPreKey || null;
74
- this.data.oneTimePreKeys = payload.oneTimePreKeys || [];
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
- return false;
156
+ } catch (error) {
157
+ throw new Error(`Unable to load E2EE store: ${error.message}`);
80
158
  }
81
159
  }
82
160
 
83
161
  save() {
84
- if (!fs.existsSync(this.storePath)) {
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.writeFileSync(this._storeFile(), JSON.stringify({ deviceSecret: this.data.deviceSecret, payload: encrypted }, null, 2), "utf8");
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
- async function establishSession(store, recipient, rawBundle) {
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
- async function encryptDM(store, recipient, selfAddress, plaintext) {
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
- async function decryptDM(store, sender, ciphertext) {
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
- async function decryptDMPreKey(store, sender, selfAddress, ciphertext) {
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
- async function createSenderKeyDistributionMessage(store, groupJid, senderJid) {
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
- async function processSKDM(store, senderJid, skdmBytes, groupJid) {
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
- async function encryptGroup(store, groupJid, senderJid, plaintext, distributionId) {
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
- async function decryptGroup(store, senderJid, ciphertext, groupJid) {
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.emit("disconnected");
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 = `mc-${now()}`;
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 = `pkc-${now()}`;
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 = `gp-${now()}`;
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 = `${now()}`;
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 = `pkb-${now()}`;
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 = `clean-${now()}`;
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
- await this.e2eeHandler.handleEncryptedMessage(node, userId, client);
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
- const encrypted = await e2eeClient.encryptDevicePayload(deviceJid, selfJid, payload);
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
- var mqttEmitter = mqttListener(globalCallback);
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).
@@ -21,7 +21,7 @@ const createEmitAuth = require("./core/emitAuth");
21
21
  const createMiddlewareSystem = require("./middleware");
22
22
 
23
23
  const CYCLE_MS_DEFAULT = 60 * 60 * 1000;
24
- const RECONNECT_DELAY_MS_DEFAULT = 3000;
24
+ const RECONNECT_DELAY_MS_DEFAULT = 5000;
25
25
  const UNSUB_ALL_TIMEOUT_MS = 5000;
26
26
  const MAX_MQTT_RECONNECT_DELAY_MS = 60000;
27
27
  const MAX_MQTT_RECONNECT_COOLDOWN_MS = 10 * 60 * 1000; // long cooldown after exhausting fast retries - never give up permanently
@@ -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 === "1"; // [Fixed by xalman] off by default: instant reconnect loops look like multiple sessions
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,28 @@ 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
+ if (getTextEffectId(msg)) logger.warn("sendMessage", "Text effects are not supported in E2EE DMs - sending plain text. Use a group chat for effects.");
304
+ try {
305
+ var e2eeText = await api.e2ee.sendMessage(String(threadID), { body: msg.body != null ? String(msg.body) : "" }, replyToMessage || msg.replyToMessage);
306
+ var e2eeWrapped = e2eeText && e2eeText.messageId
307
+ ? { threadID: String(threadID), messageID: String(e2eeText.messageId) }
308
+ : e2eeText;
309
+ if (callback) callback(null, e2eeWrapped);
310
+ else resolve(e2eeWrapped);
311
+ } catch (e2eeTextErr) {
312
+ logger.error("sendMessage", "E2EE DM text send failed: " + (e2eeTextErr.message || e2eeTextErr));
313
+ if (callback) callback(e2eeTextErr);
314
+ else reject(e2eeTextErr);
315
+ }
316
+ return promise;
317
+ }
318
+
297
319
  try {
298
320
  var result = await sendViaMqtt(msg, threadID, replyToMessage);
299
321
  if (callback) callback(null, result);
@@ -315,4 +337,4 @@ module.exports = function (defaultFuncs, api, ctx) {
315
337
 
316
338
  return promise;
317
339
  };
318
- };
340
+ };
@@ -90,6 +90,30 @@ function extractPhotoUrl(photo, depth = 0) {
90
90
  return null;
91
91
  }
92
92
 
93
+
94
+ // [Fixed by xalman] Fallback: read the cover photo straight from the profile page HTML,
95
+ // used when none of the GraphQL doc_ids returned a cover (doc_ids rotate often).
96
+ function decodeJsonString(raw) {
97
+ try { return JSON.parse('"' + raw + '"'); } catch { return raw.replace(/\\\//g, "/"); }
98
+ }
99
+
100
+ function extractCoverFromHTML(html) {
101
+ if (!html || typeof html !== "string") return null;
102
+ const patterns = [
103
+ /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
104
+ /"profile_cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
105
+ /"coverPhoto"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
106
+ /"cover_photo"\s*:\s*\{[\s\S]{0,800}?"url"\s*:\s*"([^"]+)"/
107
+ ];
108
+ for (const re of patterns) {
109
+ const m = html.match(re);
110
+ if (!m) continue;
111
+ const url = decodeJsonString(m[1]).replace(/&amp;/g, "&");
112
+ if (/^https?:\/\//i.test(url) && /(fbcdn|scontent)/i.test(url)) return url;
113
+ }
114
+ return null;
115
+ }
116
+
93
117
  function pickMeta(user) {
94
118
  let friendshipStatus = null;
95
119
  let gender = null;
@@ -249,6 +273,23 @@ module.exports = function (defaultFuncs, api, ctx) {
249
273
  logger(`getUserInfoV2 ${doc.id}: ${error.message || error}`, "warn");
250
274
  }
251
275
  }
276
+ if (bestUser && !bestUser.coverPhoto) {
277
+ const pages = [`https://www.facebook.com/profile.php?id=${id}`];
278
+ if (bestUser.vanity && bestUser.vanity !== id) pages.push(`https://www.facebook.com/${bestUser.vanity}`);
279
+ for (const url of pages) {
280
+ try {
281
+ const res = await defaultFuncs.get(url, ctx.jar, null, ctx);
282
+ const html = typeof res === "string" ? res : res?.data;
283
+ const cover = extractCoverFromHTML(html);
284
+ if (cover) { bestUser.coverPhoto = cover; break; }
285
+ } catch (error) {
286
+ logger(`getUserInfoV2 cover html ${id}: ${error.message || error}`, "warn");
287
+ }
288
+ }
289
+ if (!bestUser.coverPhoto && process.env.FCA_COVER_DEBUG === "1") {
290
+ logger(`getUserInfoV2 cover ${id}: no cover found in GraphQL or profile HTML (account may have no cover photo)`, "warn");
291
+ }
292
+ }
252
293
  return bestUser;
253
294
  }
254
295
 
@@ -311,7 +352,7 @@ module.exports = function (defaultFuncs, api, ctx) {
311
352
  if (!ids.length) {
312
353
  const error = new Error("Invalid user ID(s)");
313
354
  callback(error);
314
- returnPromise;
355
+ return returnPromise;
315
356
  }
316
357
  (async () => {
317
358
  try {
@@ -365,6 +406,7 @@ module.exports = function (defaultFuncs, api, ctx) {
365
406
 
366
407
  module.exports._private = {
367
408
  extractPhotoUrl,
409
+ extractCoverFromHTML,
368
410
  normalizeUser
369
411
  };
370
412
 
@@ -65,8 +65,8 @@ function createFallbackNamespaces(api) {
65
65
  setEmoji: bindOptionalMethod(api, "changeThreadEmoji"),
66
66
  setNickname: bindOptionalMethod(api, "changeNickname"),
67
67
  createPoll: bindOptionalMethod(api, "createPoll"),
68
- createThemeAI: bindOptionalMethod(api, "createThemeAI"),
69
- getThemePictures: bindOptionalMethod(api, "getThemePictures"),
68
+ createThemeAI: bindLiveMethod(api, "createThemeAI"),
69
+ getThemePictures: bindLiveMethod(api, "getThemePictures"),
70
70
  delete: bindOptionalMethod(api, "deleteThread"),
71
71
  colors: readOptionalMember(api, "threadColors"),
72
72
  handleMessageRequest: bindOptionalMethod(api, "handleMessageRequest"),