fca-nx 6.8.8 → 7.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +24 -10
  2. package/func/checkUpdate.js +1 -1
  3. package/func/logAdapter.js +2 -0
  4. package/index.js +3 -0
  5. package/module/config.js +5 -2
  6. package/module/login.js +38 -13
  7. package/module/loginHelper.js +164 -127
  8. package/module/options.js +7 -1
  9. package/package.json +2 -2
  10. package/src/api/action/addfriend.js +9 -3
  11. package/src/api/action/changeAvatar.js +1 -0
  12. package/src/api/action/changeCover.js +3 -1
  13. package/src/api/action/enableAutoSaveAppState.js +18 -5
  14. package/src/api/action/refreshFb_dtsg.js +18 -76
  15. package/src/api/http/httpGet.js +6 -2
  16. package/src/api/http/httpPost.js +7 -2
  17. package/src/api/messaging/createNewGroup.js +1 -1
  18. package/src/api/messaging/deleteMessage.js +1 -1
  19. package/src/api/messaging/forwardMessage.js +9 -1
  20. package/src/api/messaging/getEmojiUrl.js +5 -1
  21. package/src/api/messaging/getMessage.js +4 -2
  22. package/src/api/messaging/getThemePictures.js +21 -28
  23. package/src/api/messaging/markAsRead.js +1 -0
  24. package/src/api/messaging/muteThread.js +1 -1
  25. package/src/api/messaging/pinMessage.js +10 -1
  26. package/src/api/messaging/scheduler.js +71 -4
  27. package/src/api/messaging/sendBroadcast.js +15 -0
  28. package/src/api/messaging/sendMessage.js +23 -1
  29. package/src/api/messaging/sendTypingIndicator.js +0 -15
  30. package/src/api/messaging/sessionGuard.js +45 -9
  31. package/src/api/messaging/setMessageReaction.js +2 -1
  32. package/src/api/messaging/threadColors.js +45 -12
  33. package/src/api/messaging/uploadAttachment.js +37 -3
  34. package/src/api/socket/OldMessage.js +7 -2
  35. package/src/api/socket/core/connectMqtt.js +68 -81
  36. package/src/api/socket/core/emitAuth.js +11 -2
  37. package/src/api/socket/core/getSeqID.js +28 -36
  38. package/src/api/socket/core/getTaskResponseData.js +3 -1
  39. package/src/api/socket/core/parseDelta.js +1 -1
  40. package/src/api/socket/detail/buildStream.js +4 -1
  41. package/src/api/socket/detail/constants.js +4 -1
  42. package/src/api/socket/e2ee/crypto.js +40 -2
  43. package/src/api/socket/e2ee/index.js +124 -73
  44. package/src/api/socket/e2ee/protocol.js +40 -32
  45. package/src/api/socket/e2ee/ratchet.js +43 -37
  46. package/src/api/socket/e2ee/store.js +47 -133
  47. package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +18 -140
  48. package/src/api/socket/listenE2EE.js +23 -12
  49. package/src/api/socket/listenMqtt.js +94 -110
  50. package/src/api/socket/middleware/index.js +61 -7
  51. package/src/api/socket/sendMessage.js +78 -170
  52. package/src/api/socket/sendMessageMqtt.js +6 -0
  53. package/src/api/threads/getThreadHistory.js +68 -38
  54. package/src/api/threads/getThreadInfo.js +4 -3
  55. package/src/api/threads/getThreadList.js +34 -31
  56. package/src/api/threads/getThreadPictures.js +1 -1
  57. package/src/api/users/getUserInfo.js +5 -2
  58. package/src/api/users/getUserInfoV2.js +65 -59
  59. package/src/app/createFcaClient.js +2 -2
  60. package/src/core/sendReqMqtt.js +2 -1
  61. package/src/database/helpers.js +12 -0
  62. package/src/database/models/index.js +8 -9
  63. package/src/utils/broadcast.js +1 -1
  64. package/src/utils/clientIdentity.js +50 -3
  65. package/src/utils/cookies.js +4 -2
  66. package/src/utils/format/utils.js +10 -0
  67. package/src/utils/headers.js +26 -12
  68. package/src/utils/loginParser/autoLogin.js +12 -0
  69. package/src/utils/loginParser/parseAndCheckLogin.js +7 -0
  70. package/src/utils/loginParser/textUtils.js +6 -0
  71. package/src/utils/request/config.js +4 -1
  72. package/src/utils/request/methods.js +0 -13
  73. package/src/utils/request/proxy.js +13 -0
  74. package/src/utils/request/retry.js +0 -10
  75. package/src/utils/request/sanitize.js +1 -1
  76. package/src/utils/textEffects.js +85 -0
  77. package/src/utils/utils.js +17 -3
  78. package/src/utils/instanceLock.js +0 -35
  79. package/src/utils/ipGuard.js +0 -58
  80. package/src/utils/sendThrottle.js +0 -51
@@ -5099,30 +5099,6 @@ 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
- }
5126
5102
  init_cjs_shims();
5127
5103
  var import_libsignal_client5 = require("@signalapp/libsignal-client");
5128
5104
  var import_node_crypto8 = require("crypto");
@@ -5368,38 +5344,32 @@ function listSenderKeyDistributionIds(store, senderAddr) {
5368
5344
  const list = store.listSenderKeyDistributionIds;
5369
5345
  return typeof list === "function" ? list.call(store, senderAddr) : [];
5370
5346
  }
5371
- function establishSession(...a) { return withSignalLock(() => _establishSession_unlocked(...a)); }
5372
- async function _establishSession_unlocked(store, recipient, rawBundle) {
5347
+ async function establishSession(store, recipient, rawBundle) {
5373
5348
  const bundle = buildPreKeyBundle(rawBundle);
5374
5349
  await (0, import_libsignal_client5.processPreKeyBundle)(bundle, recipient, store, store);
5375
5350
  }
5376
- function encryptDM(...a) { return withSignalLock(() => _encryptDM_unlocked(...a)); }
5377
- async function _encryptDM_unlocked(store, recipient, selfAddress, plaintext) {
5351
+ async function encryptDM(store, recipient, selfAddress, plaintext) {
5378
5352
  const cipherMsg = await (0, import_libsignal_client5.signalEncrypt)(u83(plaintext), recipient, store, store);
5379
5353
  const type = cipherMsg.type() === import_libsignal_client5.CiphertextMessageType.Whisper ? "msg" : "pkmsg";
5380
5354
  return { type, ciphertext: cipherMsg.serialize() };
5381
5355
  }
5382
- function decryptDM(...a) { return withSignalLock(() => _decryptDM_unlocked(...a)); }
5383
- async function _decryptDM_unlocked(store, sender, ciphertext) {
5356
+ async function decryptDM(store, sender, ciphertext) {
5384
5357
  const msg = import_libsignal_client5.SignalMessage.deserialize(u83(ciphertext));
5385
5358
  return Buffer.from(await (0, import_libsignal_client5.signalDecrypt)(msg, sender, store, store));
5386
5359
  }
5387
- function decryptDMPreKey(...a) { return withSignalLock(() => _decryptDMPreKey_unlocked(...a)); }
5388
- async function _decryptDMPreKey_unlocked(store, sender, selfAddress, ciphertext) {
5360
+ async function decryptDMPreKey(store, sender, selfAddress, ciphertext) {
5389
5361
  const msg = import_libsignal_client5.PreKeySignalMessage.deserialize(u83(ciphertext));
5390
5362
  return Buffer.from(
5391
5363
  await (0, import_libsignal_client5.signalDecryptPreKey)(msg, sender, store, store, store, store, store)
5392
5364
  );
5393
5365
  }
5394
- function createSenderKeyDistributionMessage(...a) { return withSignalLock(() => _createSenderKeyDistributionMessage_unlocked(...a)); }
5395
- async function _createSenderKeyDistributionMessage_unlocked(store, groupJid, senderJid) {
5366
+ async function createSenderKeyDistributionMessage(store, groupJid, senderJid) {
5396
5367
  const distributionId = (0, import_node_crypto8.randomUUID)();
5397
5368
  const senderAddr = jidToAddress(senderJid);
5398
5369
  const skdm = await import_libsignal_client5.SenderKeyDistributionMessage.create(senderAddr, distributionId, store);
5399
5370
  return { skdm, distributionId };
5400
5371
  }
5401
- function processSKDM(...a) { return withSignalLock(() => _processSKDM_unlocked(...a)); }
5402
- async function _processSKDM_unlocked(store, senderJid, skdmBytes, groupJid) {
5372
+ async function processSKDM(store, senderJid, skdmBytes, groupJid) {
5403
5373
  const senderAddr = jidToAddress(senderJid);
5404
5374
  const buf = u83(skdmBytes);
5405
5375
  const processAndAlias = async (skdm) => {
@@ -5427,8 +5397,7 @@ async function _processSKDM_unlocked(store, senderJid, skdmBytes, groupJid) {
5427
5397
  throw primaryErr;
5428
5398
  }
5429
5399
  }
5430
- function encryptGroup(...a) { return withSignalLock(() => _encryptGroup_unlocked(...a)); }
5431
- async function _encryptGroup_unlocked(store, groupJid, senderJid, plaintext, distributionId) {
5400
+ async function encryptGroup(store, groupJid, senderJid, plaintext, distributionId) {
5432
5401
  const activeDistributionId = distributionId ?? (0, import_node_crypto8.randomUUID)();
5433
5402
  const senderAddr = jidToAddress(senderJid);
5434
5403
  const cipherMsg = await (0, import_libsignal_client5.groupEncrypt)(senderAddr, activeDistributionId, store, u83(plaintext));
@@ -5453,8 +5422,7 @@ async function _encryptGroup_unlocked(store, groupJid, senderJid, plaintext, dis
5453
5422
  }
5454
5423
  return buf;
5455
5424
  }
5456
- function decryptGroup(...a) { return withSignalLock(() => _decryptGroup_unlocked(...a)); }
5457
- async function _decryptGroup_unlocked(store, senderJid, ciphertext, groupJid) {
5425
+ async function decryptGroup(store, senderJid, ciphertext, groupJid) {
5458
5426
  const senderAddrs = addressCandidatesForJid(senderJid);
5459
5427
  const senderAddr = senderAddrs[0];
5460
5428
  let buf = u83(ciphertext);
@@ -6150,33 +6118,10 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
6150
6118
  url;
6151
6119
  heartbeatInterval = null;
6152
6120
  isConnected = false;
6153
- lastInboundAt = Date.now();
6154
- _disconnectedEmitted = false;
6155
6121
  constructor(endpoint) {
6156
6122
  super();
6157
6123
  this.url = endpoint;
6158
6124
  }
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
- }
6180
6125
  async connect(noisePrivKey, authPayload) {
6181
6126
  return new Promise((resolve, reject) => {
6182
6127
  try {
@@ -6218,7 +6163,6 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
6218
6163
  let waitingResolver = null;
6219
6164
  let waitingLen = 0;
6220
6165
  this.ws.addEventListener("message", (ev) => {
6221
- this.lastInboundAt = Date.now();
6222
6166
  const frame = Buffer.from(ev.data);
6223
6167
  streamBuffer.push(frame);
6224
6168
  streamLen += frame.length;
@@ -6265,7 +6209,7 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
6265
6209
  waitingResolver(null);
6266
6210
  waitingResolver = null;
6267
6211
  }
6268
- this._emitDisconnectedOnce();
6212
+ this.emit("disconnected");
6269
6213
  });
6270
6214
  this.ws.addEventListener("open", async () => {
6271
6215
  try {
@@ -6293,14 +6237,8 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
6293
6237
  }
6294
6238
  startHeartbeat() {
6295
6239
  this.stopHeartbeat();
6296
- this.lastInboundAt = Date.now();
6297
6240
  this.heartbeatInterval = setInterval(async () => {
6298
6241
  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
- }
6304
6242
  if (this.ws && this.ws.readyState === WebSocket.OPEN) {
6305
6243
  logger.debug("NoiseSocket", "Sending Noise heartbeat (0,0,0)...");
6306
6244
  this.ws.send(Buffer.from([0, 0, 0]));
@@ -6347,9 +6285,6 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
6347
6285
  logger.error("FacebookE2EESocket", "Read loop stopped due to error:", err);
6348
6286
  this.isConnected = false;
6349
6287
  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");
6353
6288
  }
6354
6289
  }
6355
6290
  async sendFrame(data) {
@@ -7064,15 +6999,6 @@ var E2EEHandler = class {
7064
6999
  pendingIQs = /* @__PURE__ */ new Map();
7065
7000
  retryReceipts = /* @__PURE__ */ new Map();
7066
7001
  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
- }
7076
7002
  async handleEncryptedMessage(node, selfUserId, e2eeClient) {
7077
7003
  const fromJid = node.attrs.from;
7078
7004
  const participantJid = node.attrs.participant || node.attrs.from;
@@ -7171,11 +7097,7 @@ var E2EEHandler = class {
7171
7097
  const transport = decodeMessageTransport(decrypted);
7172
7098
  logger.debug("E2EEHandler", "Decrypted transport:", JSON.stringify(transport, null, 2));
7173
7099
  chatJid = this.chatJidFromTransport(transport, chatJid);
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
- }
7100
+ this.emitTransportApplication(transport, senderJid, chatJid, node.attrs.id);
7179
7101
  if (transport?.protocol?.ancillary?.skdm) {
7180
7102
  const skdm = transport.protocol.ancillary.skdm;
7181
7103
  const gid = skdm.groupID || skdm.groupId || fromJid;
@@ -7188,19 +7110,6 @@ var E2EEHandler = class {
7188
7110
  } catch (err) {
7189
7111
  const isDuplicate = err.code === 1 || (err.message && err.message.includes("old counter"));
7190
7112
  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
- }
7204
7113
  this.sendAck(node);
7205
7114
  return;
7206
7115
  }
@@ -7431,7 +7340,7 @@ var E2EEHandler = class {
7431
7340
  }
7432
7341
  }
7433
7342
  async getMediaUploadConfig() {
7434
- const id = nextIqId("mc-");
7343
+ const id = `mc-${now()}`;
7435
7344
  const iq = encodeIQ({ id, to: "s.whatsapp.net", type: "set", xmlns: "w:m" }, [
7436
7345
  encodeNode("media_conn", {}, void 0)
7437
7346
  ]);
@@ -7481,7 +7390,7 @@ var E2EEHandler = class {
7481
7390
  };
7482
7391
  }
7483
7392
  async getServerPreKeyCount() {
7484
- const id = nextIqId("pkc-");
7393
+ const id = `pkc-${now()}`;
7485
7394
  const iq = encodeIQ({ id, to: "s.whatsapp.net", type: "get", xmlns: "encrypt" }, [
7486
7395
  encodeNode("count", {}, void 0)
7487
7396
  ]);
@@ -7497,7 +7406,7 @@ var E2EEHandler = class {
7497
7406
  });
7498
7407
  }
7499
7408
  async getGroupParticipants(groupJid) {
7500
- const id = nextIqId("gp-");
7409
+ const id = `gp-${now()}`;
7501
7410
  const iq = encodeIQ({ id, to: groupJid, type: "get", xmlns: "w:g2" }, [
7502
7411
  encodeNode("query", { request: "interactive" }, void 0)
7503
7412
  ]);
@@ -7528,7 +7437,7 @@ var E2EEHandler = class {
7528
7437
  }
7529
7438
  async getDeviceList(userJids) {
7530
7439
  if (userJids.length === 0) return [];
7531
- const id = nextIqId("dl-");
7440
+ const id = `${now()}`;
7532
7441
  const iq = encodeIQ({
7533
7442
  id,
7534
7443
  to: "s.whatsapp.net",
@@ -7574,7 +7483,7 @@ var E2EEHandler = class {
7574
7483
  return deviceJids;
7575
7484
  }
7576
7485
  async getPreKeyBundle(jid) {
7577
- const id = nextIqId("pkb-");
7486
+ const id = `pkb-${now()}`;
7578
7487
  const iq = encodeIQ({ id, to: "s.whatsapp.net", type: "get", xmlns: "encrypt" }, [
7579
7488
  encodeNode("key", {}, [
7580
7489
  encodeNode("user", { jid }, void 0)
@@ -7687,7 +7596,7 @@ var E2EEHandler = class {
7687
7596
  async sendCleanIQ(type, timestamp) {
7688
7597
  const socket = this.getSocket();
7689
7598
  if (!socket) return;
7690
- const id = nextIqId("clean-");
7599
+ const id = `clean-${now()}`;
7691
7600
  const cleanIQ = encodeIQ({ id, to: "s.whatsapp.net", type: "set", xmlns: "urn:xmpp:whatsapp:dirty" }, [
7692
7601
  encodeNode("clean", { type, timestamp }, void 0)
7693
7602
  ]);
@@ -8130,22 +8039,11 @@ var ClientController = class {
8130
8039
  auth: ""
8131
8040
  });
8132
8041
  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
- }
8143
8042
  const noiseSocket = new FacebookE2EESocket(endpoint);
8144
8043
  noiseSocket.on("connected", () => {
8145
8044
  this.eventMapper.emit({ type: "e2ee_connected", data: {} });
8146
8045
  });
8147
8046
  noiseSocket.on("disconnected", () => {
8148
- if (noiseSocket._stale) return;
8149
8047
  this.cleanup();
8150
8048
  this.eventMapper.emit({ type: "disconnected", data: { isE2EE: true } });
8151
8049
  });
@@ -8170,10 +8068,8 @@ var ClientController = class {
8170
8068
  deviceId: ds.jidDevice ?? 0,
8171
8069
  fbCatBase64: fbCat
8172
8070
  });
8173
- let messageChain = Promise.resolve(); // [Fixed by xalman] keep incoming messages in arrival order
8174
8071
  noiseSocket.on("frame", async (rawFrame) => {
8175
8072
  if (rawFrame.length === 0) return;
8176
- if (noiseSocket._stale) return;
8177
8073
  try {
8178
8074
  const node = unmarshal(rawFrame);
8179
8075
  if (["receipt", "notification", "iq", "presence", "call", "chatstate"].includes(node.tag) && node.attrs.id) {
@@ -8199,19 +8095,11 @@ var ClientController = class {
8199
8095
  break;
8200
8096
  case "message":
8201
8097
  case "appdata":
8202
- messageChain = messageChain.then(() => this.e2eeHandler.handleEncryptedMessage(node, userId, client)).catch((err) => {
8203
- logger.error("E2EE", "Message frame error:", err);
8204
- });
8098
+ await this.e2eeHandler.handleEncryptedMessage(node, userId, client);
8205
8099
  break;
8206
8100
  case "ib":
8207
8101
  this.e2eeHandler.handleIB(node);
8208
8102
  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;
8215
8103
  }
8216
8104
  } catch (err) {
8217
8105
  logger.error("E2EE", "Frame error:", err);
@@ -8388,17 +8276,7 @@ var ClientController = class {
8388
8276
  await e2eeClient.establishSession(deviceJid, bundle);
8389
8277
  }
8390
8278
  const payload = sameMessengerUser(deviceJid, selfJid) ? result.selfDevicePayload : result.devicePayload;
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
- }
8279
+ const encrypted = await e2eeClient.encryptDevicePayload(deviceJid, selfJid, payload);
8402
8280
  participantNodes.push(encodeNode("to", { jid: deviceJid }, [
8403
8281
  encodeNode("enc", { v: "3", type: encrypted.type }, encrypted.ciphertext)
8404
8282
  ]));
@@ -3,6 +3,20 @@
3
3
  var logger = require("../../utils/logger");
4
4
  var EventEmitter = require("events");
5
5
 
6
+ /**
7
+ * listenE2EE — merges E2EE messages into the same event stream as MQTT.
8
+ *
9
+ * Usage (identical to api.listen):
10
+ * api.listenE2EE(callback) // Node-style callback(err, event)
11
+ * api.listenE2EE() // returns MessageEmitter
12
+ *
13
+ * Combines:
14
+ * - Regular MQTT messages (from api.listenMqtt)
15
+ * - E2EE encrypted messages (received via FCA-NX native Noise WebSocket)
16
+ *
17
+ * All events share the same shape (type, senderID, threadID, body, etc.),
18
+ * with E2EE events carrying `isE2EE: true`.
19
+ */
6
20
  module.exports = function (defaultFuncs, api, ctx) {
7
21
  return function listenE2EE(callback) {
8
22
  class CombinedEmitter extends EventEmitter {
@@ -29,24 +43,20 @@ module.exports = function (defaultFuncs, api, ctx) {
29
43
  emitter.emit("message", event);
30
44
  };
31
45
 
46
+ // Start regular MQTT listener
32
47
  var mqttListener = api._listenMqttRaw || api.listenMqtt;
33
48
  if (typeof mqttListener !== "function") {
34
49
  throw new Error("listenE2EE: MQTT listener is not available");
35
50
  }
36
-
37
- var mqttCallback = function (err, event) {
38
- try {
39
- if (!err && event && event.type === "message" && event.isGroup === false && !event.isE2EE &&
40
- event.threadID && event.senderID !== ctx.userID) {
41
- ctx.threadTypes = ctx.threadTypes || {};
42
- ctx.threadTypes[String(event.threadID)] = "mqtt-dm";
43
- }
44
- } catch (_) { }
45
- return globalCallback(err, event);
46
- };
47
- var mqttEmitter = mqttListener(mqttCallback);
51
+ var mqttEmitter = mqttListener(globalCallback);
48
52
  api._mqttEmitter = mqttEmitter;
49
53
 
54
+ // [Fixed by xalman] Hook E2EE incoming messages (FCA-NX native Noise WebSocket).
55
+ // onMessage() only registers a callback reference - it doesn't require an
56
+ // active connection - so this is safe to call even while E2EE is still
57
+ // connecting in the background. If we skip it here just because
58
+ // isConnected() is momentarily false, the hook never gets attached and
59
+ // E2EE (inbox) messages go unheard for the lifetime of this listener.
50
60
  var e2ee = api.e2ee || ctx.e2ee;
51
61
  if (!e2ee) {
52
62
  logger.warn(
@@ -64,6 +74,7 @@ module.exports = function (defaultFuncs, api, ctx) {
64
74
  if (err) return globalCallback(err, null);
65
75
  if (!event) return;
66
76
 
77
+ // Filter self-messages unless selfListen is enabled
67
78
  if (!ctx.globalOptions.selfListen && event.senderID === ctx.userID) return;
68
79
 
69
80
  event.isE2EE = true;