fca-nx 6.6.6

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 (196) hide show
  1. package/LICENCE +21 -0
  2. package/README.md +446 -0
  3. package/e2ee/config.json +0 -0
  4. package/e2ee/crypto.js +173 -0
  5. package/e2ee/index.js +1032 -0
  6. package/e2ee/proto/ArmadilloApplication.proto +281 -0
  7. package/e2ee/proto/ArmadilloICDC.proto +14 -0
  8. package/e2ee/proto/ConsumerApplication.proto +232 -0
  9. package/e2ee/proto/MessageApplication.proto +82 -0
  10. package/e2ee/proto/MessageTransport.proto +77 -0
  11. package/e2ee/proto/WACommon.proto +66 -0
  12. package/e2ee/proto/WAMediaTransport.proto +176 -0
  13. package/e2ee/protocol.js +196 -0
  14. package/e2ee/ratchet.js +219 -0
  15. package/e2ee/store.js +182 -0
  16. package/e2ee/vendor/fb-e2ee.cjs +9159 -0
  17. package/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  18. package/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  19. package/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  20. package/e2ee/vendor/proto/MessageApplication.proto +82 -0
  21. package/e2ee/vendor/proto/MessageTransport.proto +77 -0
  22. package/e2ee/vendor/proto/WACommon.proto +66 -0
  23. package/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  24. package/func/checkUpdate.js +7 -0
  25. package/func/logAdapter.js +33 -0
  26. package/func/logger.js +134 -0
  27. package/index.js +22 -0
  28. package/module/config.js +45 -0
  29. package/module/login.js +183 -0
  30. package/module/loginHelper.js +1382 -0
  31. package/module/options.js +52 -0
  32. package/package.json +101 -0
  33. package/src/api/action/addExternalModule.js +25 -0
  34. package/src/api/action/addFriend.js +145 -0
  35. package/src/api/action/changeAvatar.js +137 -0
  36. package/src/api/action/changeBio.js +75 -0
  37. package/src/api/action/changeCover.js +277 -0
  38. package/src/api/action/enableAutoSaveAppState.js +73 -0
  39. package/src/api/action/getCurrentUserID.js +7 -0
  40. package/src/api/action/handleFriendRequest.js +57 -0
  41. package/src/api/action/logout.js +76 -0
  42. package/src/api/action/refreshFb_dtsg.js +48 -0
  43. package/src/api/action/setPostReaction.js +106 -0
  44. package/src/api/action/unfriend.js +54 -0
  45. package/src/api/http/httpGet.js +46 -0
  46. package/src/api/http/httpPost.js +52 -0
  47. package/src/api/http/postFormData.js +47 -0
  48. package/src/api/messaging/addUserToGroup.js +68 -0
  49. package/src/api/messaging/changeAdminStatus.js +126 -0
  50. package/src/api/messaging/changeArchivedStatus.js +55 -0
  51. package/src/api/messaging/changeBlockedStatus.js +48 -0
  52. package/src/api/messaging/changeGroupImage.js +91 -0
  53. package/src/api/messaging/changeNickname.js +70 -0
  54. package/src/api/messaging/changeThreadColor.js +79 -0
  55. package/src/api/messaging/changeThreadEmoji.js +111 -0
  56. package/src/api/messaging/createNewGroup.js +88 -0
  57. package/src/api/messaging/createPoll.js +46 -0
  58. package/src/api/messaging/createThemeAI.js +98 -0
  59. package/src/api/messaging/deleteMessage.js +136 -0
  60. package/src/api/messaging/deleteThread.js +56 -0
  61. package/src/api/messaging/editMessage.js +90 -0
  62. package/src/api/messaging/forwardAttachment.js +57 -0
  63. package/src/api/messaging/forwardMessage.js +134 -0
  64. package/src/api/messaging/getEmojiUrl.js +29 -0
  65. package/src/api/messaging/getFriendsList.js +82 -0
  66. package/src/api/messaging/getMessage.js +829 -0
  67. package/src/api/messaging/getThemePictures.js +62 -0
  68. package/src/api/messaging/handleMessageRequest.js +65 -0
  69. package/src/api/messaging/markAsDelivered.js +57 -0
  70. package/src/api/messaging/markAsRead.js +88 -0
  71. package/src/api/messaging/markAsReadAll.js +49 -0
  72. package/src/api/messaging/markAsSeen.js +61 -0
  73. package/src/api/messaging/muteThread.js +50 -0
  74. package/src/api/messaging/pinMessage.js +115 -0
  75. package/src/api/messaging/removeUserFromGroup.js +62 -0
  76. package/src/api/messaging/resolvePhotoUrl.js +43 -0
  77. package/src/api/messaging/scheduler.js +264 -0
  78. package/src/api/messaging/searchForThread.js +53 -0
  79. package/src/api/messaging/sendBroadcast.js +93 -0
  80. package/src/api/messaging/sendMessage.js +269 -0
  81. package/src/api/messaging/sendTypingIndicator.js +74 -0
  82. package/src/api/messaging/sessionGuard.js +208 -0
  83. package/src/api/messaging/setMessageReaction.js +95 -0
  84. package/src/api/messaging/setTitle.js +124 -0
  85. package/src/api/messaging/shareContact.js +49 -0
  86. package/src/api/messaging/threadColors.js +128 -0
  87. package/src/api/messaging/unsendMessage.js +81 -0
  88. package/src/api/messaging/uploadAttachment.js +523 -0
  89. package/src/api/socket/OldMessage.js +186 -0
  90. package/src/api/socket/core/connectMqtt.js +320 -0
  91. package/src/api/socket/core/emitAuth.js +103 -0
  92. package/src/api/socket/core/getSeqID.js +338 -0
  93. package/src/api/socket/core/getTaskResponseData.js +25 -0
  94. package/src/api/socket/core/parseDelta.js +387 -0
  95. package/src/api/socket/detail/buildStream.js +215 -0
  96. package/src/api/socket/detail/constants.js +28 -0
  97. package/src/api/socket/e2ee/crypto.js +173 -0
  98. package/src/api/socket/e2ee/e2ee/crypto.js +173 -0
  99. package/src/api/socket/e2ee/e2ee/index.js +421 -0
  100. package/src/api/socket/e2ee/e2ee/proto/ArmadilloApplication.proto +281 -0
  101. package/src/api/socket/e2ee/e2ee/proto/ArmadilloICDC.proto +14 -0
  102. package/src/api/socket/e2ee/e2ee/proto/ConsumerApplication.proto +232 -0
  103. package/src/api/socket/e2ee/e2ee/proto/MessageApplication.proto +82 -0
  104. package/src/api/socket/e2ee/e2ee/proto/MessageTransport.proto +77 -0
  105. package/src/api/socket/e2ee/e2ee/proto/WACommon.proto +66 -0
  106. package/src/api/socket/e2ee/e2ee/proto/WAMediaTransport.proto +176 -0
  107. package/src/api/socket/e2ee/e2ee/protocol.js +196 -0
  108. package/src/api/socket/e2ee/e2ee/ratchet.js +219 -0
  109. package/src/api/socket/e2ee/e2ee/store.js +182 -0
  110. package/src/api/socket/e2ee/e2ee/vendor/fb-e2ee.cjs +9162 -0
  111. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  112. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  113. package/src/api/socket/e2ee/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  114. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageApplication.proto +82 -0
  115. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageTransport.proto +77 -0
  116. package/src/api/socket/e2ee/e2ee/vendor/proto/WACommon.proto +66 -0
  117. package/src/api/socket/e2ee/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  118. package/src/api/socket/e2ee/index.js +437 -0
  119. package/src/api/socket/e2ee/proto/ArmadilloApplication.proto +281 -0
  120. package/src/api/socket/e2ee/proto/ArmadilloICDC.proto +14 -0
  121. package/src/api/socket/e2ee/proto/ConsumerApplication.proto +232 -0
  122. package/src/api/socket/e2ee/proto/MessageApplication.proto +82 -0
  123. package/src/api/socket/e2ee/proto/MessageTransport.proto +77 -0
  124. package/src/api/socket/e2ee/proto/WACommon.proto +66 -0
  125. package/src/api/socket/e2ee/proto/WAMediaTransport.proto +176 -0
  126. package/src/api/socket/e2ee/protocol.js +196 -0
  127. package/src/api/socket/e2ee/ratchet.js +219 -0
  128. package/src/api/socket/e2ee/store.js +182 -0
  129. package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +9162 -0
  130. package/src/api/socket/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  131. package/src/api/socket/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  132. package/src/api/socket/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  133. package/src/api/socket/e2ee/vendor/proto/MessageApplication.proto +82 -0
  134. package/src/api/socket/e2ee/vendor/proto/MessageTransport.proto +77 -0
  135. package/src/api/socket/e2ee/vendor/proto/WACommon.proto +66 -0
  136. package/src/api/socket/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  137. package/src/api/socket/listenE2EE.js +75 -0
  138. package/src/api/socket/listenMqtt.js +551 -0
  139. package/src/api/socket/middleware/index.js +216 -0
  140. package/src/api/socket/sendMessage.js +309 -0
  141. package/src/api/socket/sendMessageMqtt.js +69 -0
  142. package/src/api/threads/getThreadHistory.js +664 -0
  143. package/src/api/threads/getThreadInfo.js +296 -0
  144. package/src/api/threads/getThreadList.js +293 -0
  145. package/src/api/threads/getThreadPictures.js +78 -0
  146. package/src/api/users/getUserID.js +65 -0
  147. package/src/api/users/getUserInfo.js +402 -0
  148. package/src/api/users/getUserInfoV2.js +911 -0
  149. package/src/app/MessengerBot.js +209 -0
  150. package/src/app/MessengerContext.js +32 -0
  151. package/src/app/createFcaClient.js +139 -0
  152. package/src/app/threadInfoRealtimeSync.js +284 -0
  153. package/src/core/sendReqMqtt.js +96 -0
  154. package/src/database/helpers.js +53 -0
  155. package/src/database/models/index.js +88 -0
  156. package/src/database/models/thread.js +50 -0
  157. package/src/database/models/user.js +46 -0
  158. package/src/database/threadData.js +94 -0
  159. package/src/database/userData.js +98 -0
  160. package/src/remote/remoteClient.js +123 -0
  161. package/src/utils/broadcast.js +51 -0
  162. package/src/utils/client.js +10 -0
  163. package/src/utils/clientIdentity.js +118 -0
  164. package/src/utils/constants.js +23 -0
  165. package/src/utils/cookies.js +68 -0
  166. package/src/utils/format/attachment.js +357 -0
  167. package/src/utils/format/cookie.js +9 -0
  168. package/src/utils/format/date.js +50 -0
  169. package/src/utils/format/decode.js +44 -0
  170. package/src/utils/format/delta.js +194 -0
  171. package/src/utils/format/ids.js +64 -0
  172. package/src/utils/format/index.js +64 -0
  173. package/src/utils/format/message.js +88 -0
  174. package/src/utils/format/presence.js +132 -0
  175. package/src/utils/format/readTyp.js +44 -0
  176. package/src/utils/format/thread.js +42 -0
  177. package/src/utils/format/utils.js +141 -0
  178. package/src/utils/headers.js +124 -0
  179. package/src/utils/logger.js +144 -0
  180. package/src/utils/loginParser/autoLogin.js +125 -0
  181. package/src/utils/loginParser/helpers.js +43 -0
  182. package/src/utils/loginParser/index.js +10 -0
  183. package/src/utils/loginParser/parseAndCheckLogin.js +220 -0
  184. package/src/utils/loginParser/textUtils.js +28 -0
  185. package/src/utils/request/client.js +26 -0
  186. package/src/utils/request/config.js +29 -0
  187. package/src/utils/request/defaults.js +46 -0
  188. package/src/utils/request/helpers.js +46 -0
  189. package/src/utils/request/index.js +17 -0
  190. package/src/utils/request/methods.js +163 -0
  191. package/src/utils/request/proxy.js +46 -0
  192. package/src/utils/request/retry.js +77 -0
  193. package/src/utils/request/sanitize.js +49 -0
  194. package/src/utils/utils.js +686 -0
  195. package/src/utils/versionCheck.js +47 -0
  196. package/src/vendor/fca-unofficial/index.js +11 -0
package/e2ee/index.js ADDED
@@ -0,0 +1,1032 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * ═══════════════════════════════════════════════════════════════════════════
5
+ * FCA-NX E2EE Bridge — full dual-engine implementation
6
+ * Dev by Mueid Mursalin Rifat
7
+ *
8
+ * Primary : Signal Protocol + Noise WebSocket (vendor/fb-e2ee.cjs)
9
+ * Fallback : Native binary Labyrinth engine (lib/index.mjs + messagix.so/dll)
10
+ *
11
+ * Connect flow:
12
+ * 1. Read config.json → e2ee.enable must be true
13
+ * 2. Try primary vendor engine (fb-e2ee.cjs) with 5s→10s auto-reconnect
14
+ * 3. If primary fails → auto-fall back to native binary engine
15
+ * 4. Both engines emit identical event shapes to listenE2EE
16
+ * ═══════════════════════════════════════════════════════════════════════════
17
+ */
18
+
19
+ var path = require("path");
20
+ var fs = require("fs");
21
+ var urlMod = require("url");
22
+ var http = require("http");
23
+ var crypto = require("crypto");
24
+ var logger = require("../../logger");
25
+
26
+ // ─────────────────────────────────────────────────────────────────────────────
27
+ // § 0 CONFIG READER
28
+ // ─────────────────────────────────────────────────────────────────────────────
29
+ function _readE2EEConfig() {
30
+ try {
31
+ var cfgPath = path.join(process.cwd(), "config.json");
32
+ if (!fs.existsSync(cfgPath)) return {};
33
+ var cfg = JSON.parse(fs.readFileSync(cfgPath, "utf8"));
34
+ return (cfg && cfg.e2ee && typeof cfg.e2ee === "object") ? cfg.e2ee : {};
35
+ } catch (_) { return {}; }
36
+ }
37
+
38
+ // ─────────────────────────────────────────────────────────────────────────────
39
+ // § 1 JID HELPERS
40
+ // ─────────────────────────────────────────────────────────────────────────────
41
+
42
+ /** Returns true for any E2EE JID (contains "@") */
43
+ function isE2EEChatJid(value) {
44
+ return typeof value === "string" && value.indexOf("@") !== -1;
45
+ }
46
+
47
+ /** Extract numeric prefix from JID: "61568577897207:69@msgr" → "61568577897207" */
48
+ function _numericId(jid) {
49
+ if (!jid) return "";
50
+ var s = String(jid);
51
+ var m = s.match(/^(\d+)/);
52
+ return m ? m[1] : s;
53
+ }
54
+
55
+ // ─────────────────────────────────────────────────────────────────────────────
56
+ // § 2 LOCAL MEDIA SERVER – caches decrypted E2EE attachments as local URLs
57
+ // ─────────────────────────────────────────────────────────────────────────────
58
+ var _mediaCache = new Map();
59
+ var _mediaServer = null;
60
+ var _mediaPort = null;
61
+
62
+ function _cleanExpired() {
63
+ var now = Date.now();
64
+ _mediaCache.forEach(function (entry, id) {
65
+ if (entry.expiry < now) _mediaCache.delete(id);
66
+ });
67
+ }
68
+
69
+ function _startMediaServer() {
70
+ if (_mediaServer && _mediaPort) return Promise.resolve(_mediaPort);
71
+ return new Promise(function (resolve, reject) {
72
+ var s = http.createServer(function (req, res) {
73
+ var id = req.url.replace(/^\/e2ee\//, "").split("?")[0];
74
+ var entry = _mediaCache.get(id);
75
+ if (!entry) { res.writeHead(404); return res.end("Not found"); }
76
+ res.writeHead(200, {
77
+ "Content-Type" : entry.mimeType || "application/octet-stream",
78
+ "Content-Length": entry.buffer.length,
79
+ "Cache-Control" : "no-cache"
80
+ });
81
+ res.end(entry.buffer);
82
+ });
83
+ s.listen(0, "127.0.0.1", function () {
84
+ _mediaPort = s.address().port;
85
+ _mediaServer = s;
86
+ resolve(_mediaPort);
87
+ });
88
+ s.on("error", reject);
89
+ });
90
+ }
91
+
92
+ async function storeMedia(buffer, mimeType) {
93
+ var port = await _startMediaServer();
94
+ _cleanExpired();
95
+ var id = crypto.randomBytes(10).toString("hex");
96
+ _mediaCache.set(id, {
97
+ buffer : buffer,
98
+ mimeType: mimeType || "application/octet-stream",
99
+ expiry : Date.now() + 10 * 60 * 1000
100
+ });
101
+ return "http://127.0.0.1:" + port + "/e2ee/" + id;
102
+ }
103
+
104
+ // ─────────────────────────────────────────────────────────────────────────────
105
+ // § 3 PRIMARY ENGINE — vendor/fb-e2ee.cjs (Signal Protocol)
106
+ // ─────────────────────────────────────────────────────────────────────────────
107
+ function _loadFBClient() {
108
+ try {
109
+ var vendorPath = path.join(__dirname, "vendor", "fb-e2ee.cjs");
110
+ return require(vendorPath).FBClient;
111
+ } catch (err) {
112
+ throw new Error(
113
+ "FCA-NX primary E2EE engine failed to load.\n" +
114
+ " Expected at: fca-nx/src/e2ee/vendor/fb-e2ee.cjs\n" +
115
+ " Cause: " + err.message
116
+ );
117
+ }
118
+ }
119
+
120
+ // ─────────────────────────────────────────────────────────────────────────────
121
+ // § 4 FALLBACK ENGINE — lib/index.mjs (native binary Labyrinth)
122
+ // ─────────────────────────────────────────────────────────────────────────────
123
+
124
+ // Polyfill File/Blob for Node < 20
125
+ (function _polyfillFileGlobal() {
126
+ try {
127
+ if (typeof globalThis.File === "undefined") {
128
+ var b = require("buffer");
129
+ if (b && typeof b.File === "function") globalThis.File = b.File;
130
+ }
131
+ if (typeof globalThis.Blob === "undefined") {
132
+ var b2 = require("buffer");
133
+ if (b2 && typeof b2.Blob === "function") globalThis.Blob = b2.Blob;
134
+ }
135
+ } catch (_) {}
136
+ })();
137
+
138
+ // ESM bundle at <fca-nx root>/lib/index.mjs
139
+ var _NATIVE_LIB_URL = urlMod.pathToFileURL(
140
+ path.join(__dirname, "..", "..", "lib", "index.mjs")
141
+ ).href;
142
+
143
+ async function _loadNativeClient() {
144
+ var mod;
145
+ try {
146
+ var dynamicImport = new Function("specifier", "return import(specifier)");
147
+ mod = await dynamicImport(_NATIVE_LIB_URL);
148
+ } catch (err) {
149
+ throw new Error(
150
+ "FCA-NX native E2EE engine (lib/index.mjs) failed to load: " +
151
+ (err && err.message ? err.message : String(err))
152
+ );
153
+ }
154
+ if (!mod || !mod.Client)
155
+ throw new Error("FCA-NX native E2EE bundle loaded but Client export not found");
156
+ return mod.Client;
157
+ }
158
+
159
+ function _cookiesFromJar(ctx) {
160
+ var out = {};
161
+ var jar = [];
162
+ try { jar = ctx.jar.getCookies("https://www.facebook.com"); } catch (_) {}
163
+ jar.forEach(function (c) { if (c && c.key) out[c.key] = c.value; });
164
+ if (!out.c_user && out.i_user) out.c_user = out.i_user;
165
+ return out;
166
+ }
167
+
168
+ function _normalizeMediaInput(input) {
169
+ if (Buffer.isBuffer(input)) return input;
170
+ if (Array.isArray(input)) return Buffer.from(input);
171
+ if (input && input.type === "Buffer" && Array.isArray(input.data)) return Buffer.from(input.data);
172
+ if (typeof input === "string") return Buffer.from(input, "base64");
173
+ throw new Error("E2EE media data must be Buffer, byte array, Buffer-JSON, or base64 string");
174
+ }
175
+
176
+ // ─── Event mappers (native fallback engine) ────────────────────────────────
177
+
178
+ function _isCallbackLike(v) { return v && typeof v.then === "function"; }
179
+
180
+ function _callUserCallback(cb, err, msg) {
181
+ if (typeof cb !== "function") return;
182
+ try {
183
+ var r = cb(err, msg);
184
+ if (_isCallbackLike(r)) r.catch(function (e) { logger.error("E2EE", e); });
185
+ } catch (e) { logger.error("E2EE", e); }
186
+ }
187
+
188
+ function _parseMentions(arr, text) {
189
+ var out = {};
190
+ if (!Array.isArray(arr) || !text) return out;
191
+ arr.forEach(function (m) {
192
+ if (!m || m.userId == null) return;
193
+ var o = Number(m.offset || 0), l = Number(m.length || 0);
194
+ out[String(m.userId)] = text.substring(o, o + l);
195
+ });
196
+ return out;
197
+ }
198
+
199
+ function _normalizeAttType(t) {
200
+ if (!t) return t;
201
+ t = String(t).toLowerCase();
202
+ if (t === "image") return "photo";
203
+ if (t === "document") return "file";
204
+ if (t === "voice" || t === "ptt") return "audio";
205
+ return t;
206
+ }
207
+
208
+ function _normalizeAtt(a) {
209
+ if (!a || typeof a !== "object") return a;
210
+ return {
211
+ type : _normalizeAttType(a.type),
212
+ ID : a.stickerId != null ? String(a.stickerId) : undefined,
213
+ url : a.url,
214
+ filename : a.fileName,
215
+ mimeType : a.mimeType,
216
+ fileSize : a.fileSize != null ? String(a.fileSize) : undefined,
217
+ width : a.width,
218
+ height : a.height,
219
+ duration : a.duration,
220
+ previewUrl : a.previewUrl,
221
+ description : a.description,
222
+ source : a.sourceText,
223
+ mediaKey : a.mediaKey,
224
+ mediaSha256 : a.mediaSha256,
225
+ mediaEncSha256: a.mediaEncSha256,
226
+ directPath : a.directPath,
227
+ latitude : a.latitude,
228
+ longitude : a.longitude,
229
+ isE2EE : true
230
+ };
231
+ }
232
+
233
+ function _mapMsg(ev) {
234
+ var text = ev && ev.text ? String(ev.text) : "";
235
+ var sid = ev && ev.senderId != null ? _numericId(String(ev.senderId)) : "";
236
+ var tid = ev && ev.chatJid ? String(ev.chatJid)
237
+ : (ev && ev.threadId != null ? String(ev.threadId) : "");
238
+ var messageReply = null;
239
+ if (ev && ev.replyTo) {
240
+ var _rtId = ev.replyTo.messageId != null ? ev.replyTo.messageId
241
+ : ev.replyTo.id != null ? ev.replyTo.id : undefined;
242
+ var _rtSender = (ev.replyTo.senderId != null &&
243
+ typeof ev.replyTo.senderId !== "object")
244
+ ? _numericId(String(ev.replyTo.senderId)) : "";
245
+ messageReply = {
246
+ messageID: _rtId != null ? String(_rtId) : undefined,
247
+ senderID: _rtSender,
248
+ body: ev.replyTo.text != null ? String(ev.replyTo.text) : "",
249
+ isE2EE: true
250
+ };
251
+ }
252
+ return {
253
+ type : messageReply ? "message_reply" : "message",
254
+ senderID : sid,
255
+ body : text,
256
+ threadID : tid,
257
+ messageID : ev.id != null ? String(ev.id) : ev.id,
258
+ messageReply: messageReply,
259
+ attachments : Array.isArray(ev.attachments) ? ev.attachments.map(_normalizeAtt) : [],
260
+ mentions : _parseMentions(ev.mentions, text),
261
+ timestamp : ev.timestampMs != null ? Number(ev.timestampMs) : Date.now(),
262
+ isGroup : /@group\.facebook\.com$/i.test(ev.chatJid || ""),
263
+ isE2EE : true,
264
+ e2ee : { chatJid: ev.chatJid, senderJid: ev.senderJid, replyTo: ev.replyTo || null, rawMentions: ev.mentions || [] },
265
+ args : text.trim() ? text.trim().split(/\s+/) : []
266
+ };
267
+ }
268
+
269
+ function _mapEdit(ev) {
270
+ var text = ev && ev.text ? String(ev.text) : "";
271
+ return {
272
+ type : "e2ee_message_edit",
273
+ senderID : ev && ev.senderId != null ? String(ev.senderId) : "",
274
+ body : text,
275
+ threadID : ev && ev.chatJid ? String(ev.chatJid) : "",
276
+ messageID: ev ? ev.messageId : undefined,
277
+ timestamp: ev && ev.timestampMs != null ? Number(ev.timestampMs) : Date.now(),
278
+ isGroup : /@group\.facebook\.com$/i.test(ev && ev.chatJid ? ev.chatJid : ""),
279
+ isE2EE : true,
280
+ e2ee : { chatJid: ev ? ev.chatJid : undefined, senderJid: ev ? ev.senderJid : undefined },
281
+ args : text.trim() ? text.trim().split(/\s+/) : []
282
+ };
283
+ }
284
+
285
+ function _mapReaction(ev) {
286
+ return {
287
+ type : "e2ee_message_reaction",
288
+ threadID : ev && ev.chatJid ? String(ev.chatJid) : "",
289
+ messageID: ev ? ev.messageId : undefined,
290
+ reaction : ev ? ev.reaction : undefined,
291
+ senderID : ev && ev.senderId != null ? String(ev.senderId) : undefined,
292
+ userID : ev && ev.senderId != null ? String(ev.senderId) : undefined,
293
+ isE2EE : true,
294
+ e2ee : { chatJid: ev ? ev.chatJid : undefined, senderJid: ev ? ev.senderJid : undefined }
295
+ };
296
+ }
297
+
298
+ function _mapReceipt(ev) {
299
+ return {
300
+ type : "e2ee_receipt",
301
+ isE2EE: true,
302
+ e2ee : {
303
+ receiptType: ev ? ev.type : undefined,
304
+ chatJid : ev ? ev.chat : undefined,
305
+ senderJid : ev ? ev.sender : undefined,
306
+ messageIds : ev ? ev.messageIds : []
307
+ }
308
+ };
309
+ }
310
+
311
+ // Global message-ID → JID maps (needed for reactions/unsend/edits to find JID)
312
+ global._e2eeMessageMap = global._e2eeMessageMap || new Map();
313
+ global._e2eeSenderJidMap = global._e2eeSenderJidMap || new Map();
314
+
315
+ function _regMsg(msgID, jid) {
316
+ if (msgID && jid) global._e2eeMessageMap.set(String(msgID), String(jid));
317
+ }
318
+
319
+ // Attach all native bridge events → globalCallback
320
+ function _attachNativeEvents(nativeClient, state, globalCallback, ctx) {
321
+ if (state.listenerAttached) return;
322
+ state.listenerAttached = true;
323
+
324
+ nativeClient.on("ready", function (p) {
325
+ state.lastReadyPayload = p;
326
+ logger.info("E2EE", "Native bridge ready.");
327
+ _callUserCallback(globalCallback, null, { type: "e2ee_ready", isE2EE: true, data: p || null });
328
+ });
329
+ nativeClient.on("fullyReady", function () {
330
+ state.nativeFullyReady = true;
331
+ logger.success("E2EE", "Native bridge fully ready — E2EE active ✅");
332
+ _callUserCallback(globalCallback, null, { type: "e2ee_fully_ready", isE2EE: true });
333
+ });
334
+ nativeClient.on("e2eeConnected", function () {
335
+ logger.info("E2EE", "Native E2EE encryption bridge connected.");
336
+ _callUserCallback(globalCallback, null, { type: "e2ee_connected", isE2EE: true });
337
+ });
338
+ nativeClient.on("deviceDataChanged", function (p) {
339
+ if (p && p.deviceData) ctx._e2eeDeviceData = p.deviceData;
340
+ _callUserCallback(globalCallback, null,
341
+ { type: "e2ee_device_data_changed", isE2EE: true, deviceData: p ? p.deviceData : undefined });
342
+ });
343
+ nativeClient.on("e2eeMessage", function (ev) {
344
+ var mapped = _mapMsg(ev);
345
+ // Register message ID → JID so reactions/unsend can find the JID later
346
+ if (mapped.messageID && mapped.threadID) {
347
+ global._e2eeMessageMap.set(String(mapped.messageID), String(mapped.threadID));
348
+ }
349
+ if (mapped.messageID && ev.senderJid) {
350
+ global._e2eeSenderJidMap.set(String(mapped.messageID), String(ev.senderJid));
351
+ }
352
+ if (ev.replyTo && ev.chatJid) {
353
+ var _rtReg = ev.replyTo.messageId || ev.replyTo.id;
354
+ if (_rtReg) global._e2eeMessageMap.set(String(_rtReg), String(ev.chatJid));
355
+ }
356
+ // Populate ctx.threadTypes for DM routing
357
+ if (!mapped.isGroup && mapped.threadID) {
358
+ ctx.threadTypes = ctx.threadTypes || {};
359
+ ctx.threadTypes[String(mapped.threadID)] = "dm";
360
+ }
361
+ _callUserCallback(globalCallback, null, mapped);
362
+ });
363
+ nativeClient.on("e2eeMessageEdit", function (ev) {
364
+ _callUserCallback(globalCallback, null, _mapEdit(ev));
365
+ });
366
+ nativeClient.on("e2eeReaction", function (ev) {
367
+ _callUserCallback(globalCallback, null, _mapReaction(ev));
368
+ });
369
+ nativeClient.on("e2eeReceipt", function (ev) {
370
+ _callUserCallback(globalCallback, null, _mapReceipt(ev));
371
+ });
372
+ nativeClient.on("error", function (err) {
373
+ var msg = err && err.message ? err.message : String(err || "");
374
+ if (/close 1006|unexpected EOF|ECONNRESET|ETIMEDOUT|read loop/i.test(msg)) {
375
+ logger.warn("E2EE", "Native transient error (reconnecting): " + msg);
376
+ return;
377
+ }
378
+ _callUserCallback(globalCallback, err || new Error("Unknown E2EE error"));
379
+ });
380
+ nativeClient.on("disconnected", function (info) {
381
+ state.nativeConnected = false;
382
+ state.nativeFullyReady = false;
383
+ var rcCfg = (_readE2EEConfig().reconnect) || {};
384
+ var nativeDelay = (typeof rcCfg.nativeDelay === "number" && rcCfg.nativeDelay > 0) ? rcCfg.nativeDelay : 5000;
385
+ var maxAtt = (typeof rcCfg.maxAttempts === "number" && rcCfg.maxAttempts > 0) ? rcCfg.maxAttempts : 3;
386
+ logger.warn("E2EE", "Native bridge disconnected — reconnecting in " + (nativeDelay / 1000) + "s…");
387
+ _callUserCallback(globalCallback, null, { type: "e2ee_disconnected", isE2EE: true, data: info || null });
388
+ var nativeAttempt = 0;
389
+ function _tryNativeReconnect() {
390
+ if (state.nativeConnecting || state.nativeConnected) return;
391
+ nativeAttempt++;
392
+ setTimeout(function () {
393
+ if (state.nativeConnecting || state.nativeConnected) return;
394
+ state.nativeConnecting = true;
395
+ nativeClient.connect()
396
+ .then(function () {
397
+ state.nativeConnected = true;
398
+ state.nativeConnecting = false;
399
+ logger.success("E2EE", "Native bridge reconnected (attempt " + nativeAttempt + ").");
400
+ })
401
+ .catch(function (e) {
402
+ state.nativeConnecting = false;
403
+ logger.error("E2EE",
404
+ "Native reconnect attempt " + nativeAttempt + " failed: " +
405
+ (e && e.message ? e.message : e));
406
+ if (nativeAttempt < maxAtt) _tryNativeReconnect();
407
+ else logger.error("E2EE", "Native bridge gave up after " + maxAtt + " attempts.");
408
+ });
409
+ }, nativeDelay);
410
+ }
411
+ _tryNativeReconnect();
412
+ });
413
+ }
414
+
415
+ // ─────────────────────────────────────────────────────────────────────────────
416
+ // § 5 E2EEBridge CLASS – unified public API
417
+ // ─────────────────────────────────────────────────────────────────────────────
418
+
419
+ class E2EEBridge {
420
+ constructor(ctx, api, defaultFuncs) {
421
+ this.ctx = ctx;
422
+ this.api = api;
423
+ this.defaultFuncs = defaultFuncs || null;
424
+
425
+ // Primary engine (fb-e2ee.cjs)
426
+ this.client = null;
427
+ this.connected = false;
428
+
429
+ // Native fallback engine (lib/index.mjs)
430
+ this._nativeClient = null;
431
+ this._nativeState = { nativeConnected: false, nativeConnecting: false, nativeFullyReady: false, listenerAttached: false };
432
+ this._useFallback = false;
433
+
434
+ this._messageCallback = null;
435
+ this._reconnectDisabled = false;
436
+ }
437
+
438
+ // ── helpers ──────────────────────────────────────────────────────────────
439
+
440
+ ensureConnected() {
441
+ if (!this.connected && !(this._useFallback && this._nativeState.nativeConnected)) {
442
+ throw new Error("E2EE not connected. Call api.connectE2EE() first.");
443
+ }
444
+ }
445
+
446
+ isConnected() {
447
+ return this.connected || (this._useFallback && !!this._nativeState.nativeConnected);
448
+ }
449
+
450
+ onMessage(callback) {
451
+ this._messageCallback = callback;
452
+ }
453
+
454
+ // ── public connect ────────────────────────────────────────────────────────
455
+
456
+ async connect(deviceStorePath, userId) {
457
+ // Idempotency — if already connected on either engine, return immediately
458
+ if (this.connected || this._nativeState.nativeConnected) {
459
+ logger.info("E2EE", "connect() called but E2EE is already connected — skipping.");
460
+ return this;
461
+ }
462
+
463
+ var e2eeCfg = _readE2EEConfig();
464
+
465
+ // Honour config.json e2ee.enable: true OR globalOptions.enableE2EE
466
+ if (e2eeCfg.enable !== true &&
467
+ !(this.ctx.globalOptions && this.ctx.globalOptions.enableE2EE === true)) {
468
+ logger.warn("E2EE", "E2EE skipped — set e2ee.enable: true in config.json to activate.");
469
+ return this;
470
+ }
471
+
472
+ userId = userId || this.ctx.userID;
473
+ if (!deviceStorePath) {
474
+ deviceStorePath = path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
475
+ }
476
+ try { fs.mkdirSync(path.dirname(deviceStorePath), { recursive: true }); } catch (_) {}
477
+
478
+ logger.info("E2EE", "Connecting E2EE — trying primary engine (Signal Protocol)…");
479
+
480
+ try {
481
+ await this._connectPrimary(deviceStorePath, userId);
482
+ logger.success("E2EE", "E2EE connected ✅ [primary — Signal Protocol / Noise WebSocket]");
483
+ this.ctx.globalOptions = this.ctx.globalOptions || {};
484
+ this.ctx.globalOptions.enableE2EE = true;
485
+ patchApiForE2EE(this.api, this.ctx);
486
+ return this;
487
+ } catch (primaryErr) {
488
+ logger.warn("E2EE",
489
+ "Primary engine failed (" +
490
+ (primaryErr && primaryErr.message ? primaryErr.message : String(primaryErr)) +
491
+ ") — switching to native binary fallback…");
492
+ }
493
+
494
+ try {
495
+ await this._connectNativeFallback(e2eeCfg);
496
+ logger.success("E2EE", "E2EE connected ✅ [fallback — native binary lib/index.mjs]");
497
+ this.ctx.globalOptions = this.ctx.globalOptions || {};
498
+ this.ctx.globalOptions.enableE2EE = true;
499
+ patchApiForE2EE(this.api, this.ctx);
500
+ return this;
501
+ } catch (fallbackErr) {
502
+ var msg = fallbackErr && fallbackErr.message ? fallbackErr.message : String(fallbackErr);
503
+ logger.error("E2EE", "Both E2EE engines failed. Last error: " + msg);
504
+ throw new Error("FCA-NX E2EE: both primary and fallback engines failed. " + msg);
505
+ }
506
+ }
507
+
508
+ // ── primary engine (fb-e2ee.cjs + Signal Protocol) ───────────────────────
509
+
510
+ async _connectPrimary(deviceStorePath, userId) {
511
+ var FBClient = _loadFBClient();
512
+ var appState = this.api.getAppState();
513
+
514
+ this.client = new FBClient({ appState, platform: "facebook" });
515
+
516
+ var _ctx = this.ctx;
517
+ var _api = this.api;
518
+ var _dFuncs = this.defaultFuncs;
519
+
520
+ var _adapter = {
521
+ fb_dtsg: _ctx.fb_dtsg,
522
+ getCurrentUserID: function () { return _api.getCurrentUserID(); },
523
+ getAppState: function () { return _api.getAppState(); },
524
+ httpPost: async function (url, form) {
525
+ var merged = Object.assign({}, form);
526
+ if (!merged.fb_dtsg && _ctx.fb_dtsg) merged.fb_dtsg = _ctx.fb_dtsg;
527
+ if (!merged.__user) merged.__user = _ctx.userID;
528
+ var res = _dFuncs
529
+ ? await _dFuncs.post(url, _ctx.jar, merged)
530
+ : await new Promise(function (resolve, reject) {
531
+ require("request")(
532
+ { method: "POST", url: url, jar: _ctx.jar, form: merged, gzip: true },
533
+ function (err, r) { if (err) return reject(err); resolve(r); }
534
+ );
535
+ });
536
+ return res && res.body;
537
+ },
538
+ listenMqtt: function () { return; },
539
+ stopListenMqtt: function () {},
540
+ setOptions: function () {},
541
+ sendMessage: function (msg, tid, cb, replyTo) { return _api.sendMessage(msg, tid, cb, replyTo); },
542
+ setMessageReaction: function (r, mid, cb, f) { if (typeof _api.setMessageReaction === "function") return _api.setMessageReaction(r, mid, cb, f); },
543
+ unsendMessage: function (mid, cb) { if (typeof _api.unsendMessage === "function") return _api.unsendMessage(mid, cb); },
544
+ sendTypingIndicator: function (t, tid, cb) { if (typeof _api.sendTypingIndicator === "function") return _api.sendTypingIndicator(t, tid, cb); },
545
+ markAsRead: function (tid, r, cb) { if (typeof _api.markAsRead === "function") return _api.markAsRead(tid, r, cb); },
546
+ muteThread: function (tid, s, cb) { if (typeof _api.muteThread === "function") return _api.muteThread(tid, s, cb); },
547
+ setTitle: function (t, tid, cb) { if (typeof _api.setTitle === "function") return _api.setTitle(t, tid, cb); },
548
+ changeGroupImage: function (img, tid, cb) { if (typeof _api.changeGroupImage === "function") return _api.changeGroupImage(img, tid, cb); },
549
+ };
550
+
551
+ global._fcanxE2EEAdapter = _adapter;
552
+ var resolvedUserId;
553
+ try {
554
+ var result = await this.client.connect();
555
+ resolvedUserId = result && result.userId;
556
+ } finally {
557
+ delete global._fcanxE2EEAdapter;
558
+ }
559
+
560
+ if (this.client.controller) {
561
+ this.client.controller.api = _adapter;
562
+ }
563
+
564
+ logger.info("E2EE", "Opening Noise WebSocket…");
565
+ var _devicePath = deviceStorePath;
566
+ var _userId = resolvedUserId || userId;
567
+ await this.client.connectE2EE(_devicePath, _userId);
568
+
569
+ // ── Auto-reconnect: configurable delay/retry/maxAttempts → fallback ────
570
+ var _self = this;
571
+ this.client.onEvent("disconnected", function _onDisconnect() {
572
+ if (_self._reconnectDisabled || !_self.connected) return;
573
+ var rcCfg = (_readE2EEConfig().reconnect) || {};
574
+ var delay1 = (typeof rcCfg.delay === "number" && rcCfg.delay > 0) ? rcCfg.delay : 5000;
575
+ var delay2 = (typeof rcCfg.retryDelay === "number" && rcCfg.retryDelay > 0) ? rcCfg.retryDelay : 10000;
576
+ var maxAtt = (typeof rcCfg.maxAttempts === "number" && rcCfg.maxAttempts > 0) ? rcCfg.maxAttempts : 3;
577
+ var attempt = 0;
578
+
579
+ function _tryReconnect() {
580
+ if (_self._reconnectDisabled || !_self.connected) return;
581
+ attempt++;
582
+ var isLast = attempt >= maxAtt;
583
+ var nextDelay = attempt === 1 ? delay1 : delay2;
584
+ logger.warn("E2EE",
585
+ "Noise WebSocket disconnected — reconnecting in " + (nextDelay / 1000) + "s… " +
586
+ "(attempt " + attempt + "/" + maxAtt + ")");
587
+ setTimeout(async function () {
588
+ if (_self._reconnectDisabled || !_self.connected) return;
589
+ try {
590
+ await _self.client.connectE2EE(_devicePath, _userId);
591
+ logger.success("E2EE", "Primary E2EE reconnected (attempt " + attempt + ").");
592
+ } catch (err) {
593
+ logger.error("E2EE",
594
+ "Primary reconnect attempt " + attempt + " failed: " +
595
+ (err && err.message ? err.message : err));
596
+ if (!isLast) {
597
+ _tryReconnect();
598
+ } else {
599
+ logger.error("E2EE", "All " + maxAtt + " reconnect attempts failed — switching to native fallback.");
600
+ _self.connected = false;
601
+ _self._connectNativeFallback(_readE2EEConfig()).catch(function (e3) {
602
+ logger.error("E2EE", "Fallback after disconnect also failed: " + (e3 && e3.message ? e3.message : e3));
603
+ });
604
+ }
605
+ }
606
+ }, nextDelay);
607
+ }
608
+ _tryReconnect();
609
+ });
610
+
611
+ // ── Forward e2ee_message events from primary ──────────────────────────
612
+ var _selfCtx = this.ctx;
613
+ var _selfCb = this;
614
+ this.client.onEvent("e2ee_message", function (msg) {
615
+ if (!_selfCb._messageCallback) return;
616
+
617
+ var senderID = msg.senderId ||
618
+ (typeof msg.senderJid === "string" ? msg.senderJid.split(".")[0] : "");
619
+ var mentions = {};
620
+ if (Array.isArray(msg.mentions)) {
621
+ msg.mentions.forEach(function (m) {
622
+ if (m && m.id) mentions[m.id] = m.text || "@" + m.id;
623
+ });
624
+ } else if (msg.mentions && typeof msg.mentions === "object") {
625
+ mentions = msg.mentions;
626
+ }
627
+ var isReply = !!(msg.replyTo && msg.replyTo.messageId);
628
+ var event = {
629
+ type : isReply ? "message_reply" : "message",
630
+ senderID : senderID,
631
+ threadID : msg.threadId,
632
+ body : msg.text || "",
633
+ isE2EE : true,
634
+ isGroup : !!msg.isGroup,
635
+ timestamp : msg.timestampMs || Date.now(),
636
+ messageID : msg.id || "",
637
+ attachments : [],
638
+ mentions : mentions,
639
+ args : (msg.text || "").trim().split(/\s+/).filter(Boolean),
640
+ };
641
+ if (!event.isGroup && msg.threadId) {
642
+ _selfCtx.threadTypes = _selfCtx.threadTypes || {};
643
+ _selfCtx.threadTypes[String(msg.threadId)] = "dm";
644
+ }
645
+ if (isReply) {
646
+ event.messageReply = {
647
+ messageID : msg.replyTo.messageId,
648
+ senderID : msg.replyTo.senderId || "",
649
+ threadID : msg.threadId,
650
+ body : msg.replyTo.text || "",
651
+ args : (msg.replyTo.text || "").trim().split(/\s+/).filter(Boolean),
652
+ isE2EE : true,
653
+ isGroup : !!msg.isGroup,
654
+ mentions : {},
655
+ attachments: []
656
+ };
657
+ }
658
+ _selfCb._messageCallback(null, event);
659
+ });
660
+
661
+ this.client.onEvent("error", function (err) {
662
+ if (err && (err.code === 1 || (err.message && err.message.includes("old counter")))) return;
663
+ logger.error("E2EE", "Primary error: " + (err && err.message ? err.message : String(err)));
664
+ });
665
+
666
+ this.connected = true;
667
+ this._useFallback = false;
668
+ }
669
+
670
+ // ── native fallback engine (lib/index.mjs + koffi) ───────────────────────
671
+
672
+ async _connectNativeFallback(e2eeCfg) {
673
+ var NativeClient = await _loadNativeClient();
674
+ var cookies = _cookiesFromJar(this.ctx);
675
+
676
+ if (!cookies.c_user || !cookies.xs) {
677
+ throw new Error("Cannot start native E2EE: c_user/xs cookies missing");
678
+ }
679
+
680
+ var saveType = e2eeCfg.saveType || (e2eeCfg.memoryOnly === false ? "path" : "memory");
681
+ var opts = {
682
+ enableE2EE: true,
683
+ e2eeMemoryOnly: saveType !== "path",
684
+ autoReconnect: e2eeCfg.autoReconnect !== false,
685
+ logLevel: e2eeCfg.logLevel || "none",
686
+ };
687
+ if (saveType === "path" && e2eeCfg.devicePath) opts.devicePath = e2eeCfg.devicePath;
688
+ if (this.ctx.globalOptions && this.ctx.globalOptions.e2eeDeviceData)
689
+ opts.deviceData = this.ctx.globalOptions.e2eeDeviceData;
690
+ if (!opts.deviceData && global._pendingE2eeDeviceData) {
691
+ opts.deviceData = global._pendingE2eeDeviceData;
692
+ delete global._pendingE2eeDeviceData;
693
+ }
694
+
695
+ this._nativeClient = new NativeClient(cookies, opts);
696
+ this._nativeState = {
697
+ nativeConnected: false, nativeConnecting: false,
698
+ nativeFullyReady: false, listenerAttached: false,
699
+ lastReadyPayload: null
700
+ };
701
+
702
+ var _self = this;
703
+ _attachNativeEvents(
704
+ this._nativeClient,
705
+ this._nativeState,
706
+ function (err, ev) { if (typeof _self._messageCallback === "function") _self._messageCallback(err, ev); },
707
+ this.ctx
708
+ );
709
+
710
+ await this._nativeClient.connect();
711
+ this._nativeState.nativeConnected = true;
712
+ this._useFallback = true;
713
+ this.connected = false; // primary not active
714
+ }
715
+
716
+ // ── ensure native client connected (lazy reconnect for send ops) ──────────
717
+
718
+ async _ensureNativeClient() {
719
+ if (this._nativeState.nativeConnected && this._nativeClient) return this._nativeClient;
720
+ if (this._nativeState.nativeConnecting) {
721
+ // wait for in-progress connect
722
+ return new Promise(function (resolve, reject) {
723
+ var t = setTimeout(function () { reject(new Error("E2EE native connect timeout")); }, 15000);
724
+ var iv = setInterval(function () {
725
+ if (this._nativeState.nativeConnected && this._nativeClient) {
726
+ clearInterval(iv); clearTimeout(t); resolve(this._nativeClient);
727
+ }
728
+ }.bind(this), 200);
729
+ }.bind(this));
730
+ }
731
+ // Not connecting — try to reconnect
732
+ await this._nativeClient.connect();
733
+ this._nativeState.nativeConnected = true;
734
+ return this._nativeClient;
735
+ }
736
+
737
+ // ── disconnect ────────────────────────────────────────────────────────────
738
+
739
+ async disconnect() {
740
+ this._reconnectDisabled = true;
741
+ if (this.client) {
742
+ try { await this.client.disconnect(); } catch (_) {}
743
+ }
744
+ if (this._nativeClient) {
745
+ try { await this._nativeClient.disconnect(); } catch (_) {}
746
+ }
747
+ this.connected = false;
748
+ this._nativeState.nativeConnected = false;
749
+ logger.info("E2EE", "E2EE disconnected.");
750
+ }
751
+
752
+ // ─────────────────────────────────────────────────────────────────────────
753
+ // § 6 SEND API — routes to whichever engine is active
754
+ // ─────────────────────────────────────────────────────────────────────────
755
+
756
+ async sendMessage(threadId, msg, replyToMessageId) {
757
+ var text = typeof msg === "string" ? msg : (msg && msg.body != null ? String(msg.body) : "");
758
+ var attachment = (msg && typeof msg === "object") ? (msg.attachment || null) : null;
759
+
760
+ // ── Native fallback path ──────────────────────────────────────────────
761
+ if (this._useFallback && this._nativeClient) {
762
+ var client = await this._ensureNativeClient();
763
+ if (!attachment) {
764
+ return client.sendE2EEMessage(threadId, text, { replyToId: replyToMessageId });
765
+ }
766
+ // Attachment via native sendMedia
767
+ var list = Array.isArray(attachment) ? attachment : [attachment];
768
+ var results = [];
769
+ for (var i = 0; i < list.length; i++) {
770
+ var stream = list[i];
771
+ var buf = await _streamToBuffer(stream);
772
+ var fileName = stream.path ? require("path").basename(String(stream.path)) : "file.bin";
773
+ var mimeType = _guessMime(fileName);
774
+ try { mimeType = require("mime").getType(fileName) || mimeType; } catch (_) {}
775
+ results.push(await this.sendMedia(threadId, _mimeToNativeType(mimeType), buf, {
776
+ mimeType: mimeType, caption: text, replyToId: replyToMessageId, filename: fileName
777
+ }));
778
+ }
779
+ return results.length === 1 ? results[0] : results;
780
+ }
781
+
782
+ // ── Primary engine path ───────────────────────────────────────────────
783
+ this.ensureConnected();
784
+
785
+ if (!attachment) {
786
+ return this.client.sendMessage({ threadId, text, replyToMessageId });
787
+ }
788
+
789
+ var pathMod = require("path");
790
+ var mimeLib;
791
+ try { mimeLib = require("mime"); } catch (_) {}
792
+
793
+ var list2 = Array.isArray(attachment) ? attachment : [attachment];
794
+ var results2 = [];
795
+ for (var j = 0; j < list2.length; j++) {
796
+ var s = list2[j];
797
+ var data = await _streamToBuffer(s);
798
+ var fn = (s.path ? pathMod.basename(String(s.path)) : "file.bin");
799
+ var mt = (mimeLib && mimeLib.getType(fn)) || _guessMime(fn);
800
+ var inp = { threadId, data, fileName: fn, mimeType: mt, caption: text || undefined, replyToMessageId };
801
+ var r;
802
+ if (mt.startsWith("image/")) r = await this.client.sendImage(inp);
803
+ else if (mt.startsWith("video/")) r = await this.client.sendVideo(inp);
804
+ else if (mt.startsWith("audio/")) r = await this.client.sendAudio(inp);
805
+ else r = await this.client.sendFile(inp);
806
+ results2.push(r);
807
+ }
808
+ return results2.length === 1 ? results2[0] : results2;
809
+ }
810
+
811
+ async sendReaction(threadId, messageId, reaction, senderJid) {
812
+ if (this._useFallback && this._nativeClient) {
813
+ var client = await this._ensureNativeClient();
814
+ return client.sendE2EEReaction(threadId, messageId, senderJid, reaction);
815
+ }
816
+ this.ensureConnected();
817
+ return this.client.sendReaction({ threadId, messageId, reaction, senderJid });
818
+ }
819
+
820
+ async sendTyping(threadId, isTyping) {
821
+ if (this._useFallback && this._nativeClient) {
822
+ var client = await this._ensureNativeClient();
823
+ return client.sendE2EETyping(threadId, isTyping !== false);
824
+ }
825
+ this.ensureConnected();
826
+ return this.client.sendTyping({ threadId, isTyping: isTyping !== false });
827
+ }
828
+
829
+ async unsendMessage(messageId, threadId) {
830
+ if (this._useFallback && this._nativeClient) {
831
+ var client = await this._ensureNativeClient();
832
+ return client.unsendE2EEMessage(threadId, messageId);
833
+ }
834
+ this.ensureConnected();
835
+ return this.client.unsendMessage({ messageId, threadId });
836
+ }
837
+
838
+ async editMessage(threadId, messageId, newText) {
839
+ if (this._useFallback && this._nativeClient) {
840
+ var client = await this._ensureNativeClient();
841
+ return client.editE2EEMessage(threadId, messageId, newText);
842
+ }
843
+ this.ensureConnected();
844
+ return this.client.editMessage({ threadId, messageId, newText });
845
+ }
846
+
847
+ /**
848
+ * sendMedia — full media send (native fallback only; primary uses sendMessage)
849
+ * @param {string} jid – E2EE thread JID
850
+ * @param {string} mediaType – "image"|"video"|"audio"|"voice"|"file"|"document"|"sticker"
851
+ * @param {Buffer|Array|string} data – media bytes
852
+ * @param {object} opts – { mimeType, caption, filename, duration, width, height, ptt, replyToId, replyToSenderJid }
853
+ */
854
+ async sendMedia(jid, mediaType, data, opts) {
855
+ if (!this._useFallback || !this._nativeClient)
856
+ throw new Error("sendMedia is only available on the native fallback engine");
857
+ var client = await this._ensureNativeClient();
858
+ var buf = _normalizeMediaInput(data);
859
+ var o = opts || {};
860
+ var ntype = String(mediaType || "").toLowerCase();
861
+ switch (ntype) {
862
+ case "image":
863
+ return client.sendE2EEImage(jid, buf, o.mimeType || "image/jpeg",
864
+ { caption: o.caption || "", width: o.width, height: o.height,
865
+ replyToId: o.replyToId, replyToSenderJid: o.replyToSenderJid });
866
+ case "video":
867
+ return client.sendE2EEVideo(jid, buf, o.mimeType || "video/mp4",
868
+ { caption: o.caption || "", duration: o.duration,
869
+ width: o.width, height: o.height,
870
+ replyToId: o.replyToId, replyToSenderJid: o.replyToSenderJid });
871
+ case "audio": case "voice": {
872
+ var mime = o.mimeType || "audio/ogg; codecs=opus";
873
+ var isVoice = ntype === "voice" || !!o.ptt;
874
+ return client.sendE2EEAudio(jid, buf, mime,
875
+ { ptt: isVoice, duration: o.duration != null ? Number(o.duration) : undefined,
876
+ replyToId: o.replyToId, replyToSenderJid: o.replyToSenderJid });
877
+ }
878
+ case "file": case "document":
879
+ return client.sendE2EEDocument(jid, buf, o.filename || "file.bin",
880
+ o.mimeType || "application/octet-stream",
881
+ { replyToId: o.replyToId, replyToSenderJid: o.replyToSenderJid });
882
+ case "sticker":
883
+ return client.sendE2EESticker(jid, buf, o.mimeType || "image/webp",
884
+ { replyToId: o.replyToId, replyToSenderJid: o.replyToSenderJid });
885
+ default:
886
+ throw new Error("Unsupported E2EE mediaType: " + ntype);
887
+ }
888
+ }
889
+
890
+ /**
891
+ * downloadMedia — decrypt and download an E2EE attachment (native fallback only)
892
+ * Returns: { data: Buffer, mimeType: string, fileSize: number }
893
+ */
894
+ async downloadMedia(opts) {
895
+ if (!this._useFallback || !this._nativeClient)
896
+ throw new Error("downloadMedia is only available on the native fallback engine");
897
+ var client = await this._ensureNativeClient();
898
+ var size = opts.fileSize != null ? Number(opts.fileSize) : undefined;
899
+ var res = await client.downloadE2EEMedia({
900
+ directPath : opts.directPath,
901
+ mediaKey : opts.mediaKey,
902
+ mediaSha256 : opts.mediaSha256,
903
+ mediaEncSha256: opts.mediaEncSha256,
904
+ mediaType : opts.mediaType,
905
+ mimeType : opts.mimeType,
906
+ fileSize : size
907
+ });
908
+ return { data: res.data, mimeType: res.mimeType, fileSize: Number(res.fileSize) };
909
+ }
910
+
911
+ /** Retrieve stored device data (native fallback only) */
912
+ async getDeviceData() {
913
+ if (!this._nativeClient) return null;
914
+ var client = await this._ensureNativeClient();
915
+ if (typeof client.getDeviceData === "function") return client.getDeviceData();
916
+ return this.ctx._e2eeDeviceData || null;
917
+ }
918
+
919
+ getPublicKeys() {
920
+ return {
921
+ info : "Keys managed by FCA-NX E2EE engine.",
922
+ engine: this._useFallback ? "native binary (lib/index.mjs)" : "vendor (fb-e2ee.cjs / Signal Protocol)",
923
+ dev : "Dev by Mueid Mursalin Rifat",
924
+ note : "Identity + device keys are stored in the device-store file. Do NOT delete it.",
925
+ };
926
+ }
927
+ }
928
+
929
+ // ─────────────────────────────────────────────────────────────────────────────
930
+ // § 7 patchApiForE2EE – adds E2EE helper methods onto the api object
931
+ // Call once after buildAPI() when E2EE is enabled.
932
+ // ─────────────────────────────────────────────────────────────────────────────
933
+ function patchApiForE2EE(api, ctx) {
934
+ // api.downloadE2EEMedia — decrypt and return raw bytes
935
+ if (typeof api.downloadE2EEMedia !== "function") {
936
+ api.downloadE2EEMedia = function (options) {
937
+ if (!api.e2ee) throw new Error("E2EE not initialised");
938
+ return api.e2ee.downloadMedia(options);
939
+ };
940
+ }
941
+
942
+ // api.resolveE2EEAttachment — decrypt and store locally, returns att with url
943
+ if (typeof api.resolveE2EEAttachment !== "function") {
944
+ api.resolveE2EEAttachment = async function (att) {
945
+ if (!att || !att.isE2EE) return att;
946
+ if (att.url && /^https?:\/\//.test(att.url)) return att;
947
+ if (!att.directPath || !att.mediaKey || !att.mediaSha256 || !att.mimeType) return att;
948
+ try {
949
+ var rawType = att.type === "photo" ? "image" : (att.type || "image");
950
+ var res = await api.downloadE2EEMedia({
951
+ directPath : att.directPath,
952
+ mediaKey : att.mediaKey,
953
+ mediaSha256 : att.mediaSha256,
954
+ mediaEncSha256: att.mediaEncSha256 || undefined,
955
+ mediaType : rawType,
956
+ mimeType : att.mimeType,
957
+ fileSize : Number(att.fileSize)
958
+ });
959
+ var localUrl = await storeMedia(res.data, res.mimeType || att.mimeType);
960
+ return Object.assign({}, att, { url: localUrl });
961
+ } catch (e) {
962
+ logger.error("E2EE", "resolveE2EEAttachment failed: " + (e && e.message ? e.message : String(e)));
963
+ return att;
964
+ }
965
+ };
966
+ }
967
+
968
+ // api.sendTypingE2EE
969
+ if (typeof api.sendTypingE2EE !== "function") {
970
+ api.sendTypingE2EE = function (chatJid, isTyping) {
971
+ if (!isE2EEChatJid(chatJid)) return Promise.resolve();
972
+ if (!api.e2ee) return Promise.resolve();
973
+ return api.e2ee.sendTyping(chatJid, isTyping !== false).catch(function () {});
974
+ };
975
+ }
976
+
977
+ // api.getE2EEDeviceData — retrieve device data (for persistence)
978
+ if (typeof api.getE2EEDeviceData !== "function") {
979
+ api.getE2EEDeviceData = function () {
980
+ if (!api.e2ee) return Promise.resolve(null);
981
+ if (typeof api.e2ee.getDeviceData === "function") return api.e2ee.getDeviceData();
982
+ return Promise.resolve(ctx._e2eeDeviceData || null);
983
+ };
984
+ }
985
+ }
986
+
987
+ // ─────────────────────────────────────────────────────────────────────────────
988
+ // Exports
989
+ // ─────────────────────────────────────────────────────────────────────────────
990
+ module.exports = {
991
+ E2EEBridge,
992
+ isE2EEChatJid,
993
+ storeMedia,
994
+ patchApiForE2EE
995
+ };
996
+
997
+ // ─────────────────────────────────────────────────────────────────────────────
998
+ // Private helpers
999
+ // ─────────────────────────────────────────────────────────────────────────────
1000
+
1001
+ function _streamToBuffer(stream) {
1002
+ return new Promise(function (resolve, reject) {
1003
+ var chunks = [];
1004
+ stream.on("data", function (c) { chunks.push(c); });
1005
+ stream.on("end", function () { resolve(Buffer.concat(chunks)); });
1006
+ stream.on("error", reject);
1007
+ });
1008
+ }
1009
+
1010
+ var _EXT_MIME = {
1011
+ jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif",
1012
+ webp: "image/webp", bmp: "image/bmp",
1013
+ mp4: "video/mp4", mov: "video/quicktime", avi: "video/x-msvideo",
1014
+ mkv: "video/x-matroska", webm: "video/webm",
1015
+ mp3: "audio/mpeg", ogg: "audio/ogg; codecs=opus", oga: "audio/ogg; codecs=opus",
1016
+ opus: "audio/ogg; codecs=opus", wav: "audio/wav", m4a: "audio/mp4",
1017
+ aac: "audio/aac", flac: "audio/flac",
1018
+ pdf: "application/pdf", txt: "text/plain", json: "application/json"
1019
+ };
1020
+
1021
+ function _guessMime(fileName) {
1022
+ var ext = (fileName || "").split(".").pop().toLowerCase();
1023
+ return _EXT_MIME[ext] || "application/octet-stream";
1024
+ }
1025
+
1026
+ function _mimeToNativeType(mime) {
1027
+ if (!mime) return "file";
1028
+ if (mime.startsWith("image/")) return "image";
1029
+ if (mime.startsWith("video/")) return "video";
1030
+ if (mime.startsWith("audio/")) return "audio";
1031
+ return "file";
1032
+ }