fca-riyad 37.0.0

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 (242) hide show
  1. package/CHANGELOG.md +325 -0
  2. package/DOCS.md +2712 -0
  3. package/README.md +410 -0
  4. package/func/checkUpdate.js +7 -0
  5. package/func/logAdapter.js +33 -0
  6. package/func/logger.js +48 -0
  7. package/index.d.ts +751 -0
  8. package/index.js +22 -0
  9. package/module/config.js +40 -0
  10. package/module/login.js +133 -0
  11. package/module/loginHelper.js +1359 -0
  12. package/module/options.js +44 -0
  13. package/package.json +95 -0
  14. package/src/api/action/addExternalModule.js +25 -0
  15. package/src/api/action/changeAvatar.js +137 -0
  16. package/src/api/action/changeBio.js +75 -0
  17. package/src/api/action/enableAutoSaveAppState.js +73 -0
  18. package/src/api/action/getCurrentUserID.js +7 -0
  19. package/src/api/action/handleFriendRequest.js +57 -0
  20. package/src/api/action/logout.js +76 -0
  21. package/src/api/action/refreshFb_dtsg.js +48 -0
  22. package/src/api/action/setPostReaction.js +106 -0
  23. package/src/api/action/unfriend.js +54 -0
  24. package/src/api/http/httpGet.js +46 -0
  25. package/src/api/http/httpPost.js +52 -0
  26. package/src/api/http/postFormData.js +47 -0
  27. package/src/api/messaging/addUserToGroup.js +68 -0
  28. package/src/api/messaging/changeAdminStatus.js +126 -0
  29. package/src/api/messaging/changeArchivedStatus.js +55 -0
  30. package/src/api/messaging/changeBlockedStatus.js +48 -0
  31. package/src/api/messaging/changeGroupImage.js +91 -0
  32. package/src/api/messaging/changeNickname.js +70 -0
  33. package/src/api/messaging/changeThreadColor.js +79 -0
  34. package/src/api/messaging/changeThreadEmoji.js +111 -0
  35. package/src/api/messaging/createNewGroup.js +88 -0
  36. package/src/api/messaging/createPoll.js +46 -0
  37. package/src/api/messaging/createThemeAI.js +98 -0
  38. package/src/api/messaging/deleteMessage.js +136 -0
  39. package/src/api/messaging/deleteThread.js +56 -0
  40. package/src/api/messaging/editMessage.js +90 -0
  41. package/src/api/messaging/forwardAttachment.js +57 -0
  42. package/src/api/messaging/forwardMessage.js +134 -0
  43. package/src/api/messaging/getEmojiUrl.js +29 -0
  44. package/src/api/messaging/getFriendsList.js +82 -0
  45. package/src/api/messaging/getMessage.js +829 -0
  46. package/src/api/messaging/getThemePictures.js +62 -0
  47. package/src/api/messaging/handleMessageRequest.js +65 -0
  48. package/src/api/messaging/markAsDelivered.js +57 -0
  49. package/src/api/messaging/markAsRead.js +88 -0
  50. package/src/api/messaging/markAsReadAll.js +49 -0
  51. package/src/api/messaging/markAsSeen.js +61 -0
  52. package/src/api/messaging/muteThread.js +50 -0
  53. package/src/api/messaging/pinMessage.js +115 -0
  54. package/src/api/messaging/removeUserFromGroup.js +62 -0
  55. package/src/api/messaging/resolvePhotoUrl.js +43 -0
  56. package/src/api/messaging/scheduler.js +264 -0
  57. package/src/api/messaging/searchForThread.js +53 -0
  58. package/src/api/messaging/sendBroadcast.js +93 -0
  59. package/src/api/messaging/sendMessage.js +269 -0
  60. package/src/api/messaging/sendTypingIndicator.js +74 -0
  61. package/src/api/messaging/sessionGuard.js +130 -0
  62. package/src/api/messaging/setMessageReaction.js +95 -0
  63. package/src/api/messaging/setTitle.js +124 -0
  64. package/src/api/messaging/shareContact.js +49 -0
  65. package/src/api/messaging/threadColors.js +128 -0
  66. package/src/api/messaging/unsendMessage.js +81 -0
  67. package/src/api/messaging/uploadAttachment.js +492 -0
  68. package/src/api/socket/OldMessage.js +186 -0
  69. package/src/api/socket/core/connectMqtt.js +269 -0
  70. package/src/api/socket/core/emitAuth.js +103 -0
  71. package/src/api/socket/core/getSeqID.js +321 -0
  72. package/src/api/socket/core/getTaskResponseData.js +25 -0
  73. package/src/api/socket/core/parseDelta.js +387 -0
  74. package/src/api/socket/detail/buildStream.js +215 -0
  75. package/src/api/socket/detail/constants.js +28 -0
  76. package/src/api/socket/e2ee/crypto.js +173 -0
  77. package/src/api/socket/e2ee/e2ee/crypto.js +173 -0
  78. package/src/api/socket/e2ee/e2ee/index.js +421 -0
  79. package/src/api/socket/e2ee/e2ee/proto/ArmadilloApplication.proto +281 -0
  80. package/src/api/socket/e2ee/e2ee/proto/ArmadilloICDC.proto +14 -0
  81. package/src/api/socket/e2ee/e2ee/proto/ConsumerApplication.proto +232 -0
  82. package/src/api/socket/e2ee/e2ee/proto/MessageApplication.proto +82 -0
  83. package/src/api/socket/e2ee/e2ee/proto/MessageTransport.proto +77 -0
  84. package/src/api/socket/e2ee/e2ee/proto/WACommon.proto +66 -0
  85. package/src/api/socket/e2ee/e2ee/proto/WAMediaTransport.proto +176 -0
  86. package/src/api/socket/e2ee/e2ee/proto/proto-writer.ts +76 -0
  87. package/src/api/socket/e2ee/e2ee/protocol.js +196 -0
  88. package/src/api/socket/e2ee/e2ee/ratchet.js +219 -0
  89. package/src/api/socket/e2ee/e2ee/store.js +182 -0
  90. package/src/api/socket/e2ee/e2ee/vendor/fb-e2ee.cjs +9162 -0
  91. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  92. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  93. package/src/api/socket/e2ee/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  94. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageApplication.proto +82 -0
  95. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageTransport.proto +77 -0
  96. package/src/api/socket/e2ee/e2ee/vendor/proto/WACommon.proto +66 -0
  97. package/src/api/socket/e2ee/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  98. package/src/api/socket/e2ee/e2ee/vendor/proto/proto-writer.ts +76 -0
  99. package/src/api/socket/e2ee/index.js +437 -0
  100. package/src/api/socket/e2ee/proto/ArmadilloApplication.proto +281 -0
  101. package/src/api/socket/e2ee/proto/ArmadilloICDC.proto +14 -0
  102. package/src/api/socket/e2ee/proto/ConsumerApplication.proto +232 -0
  103. package/src/api/socket/e2ee/proto/MessageApplication.proto +82 -0
  104. package/src/api/socket/e2ee/proto/MessageTransport.proto +77 -0
  105. package/src/api/socket/e2ee/proto/WACommon.proto +66 -0
  106. package/src/api/socket/e2ee/proto/WAMediaTransport.proto +176 -0
  107. package/src/api/socket/e2ee/proto/proto-writer.ts +76 -0
  108. package/src/api/socket/e2ee/protocol.js +196 -0
  109. package/src/api/socket/e2ee/ratchet.js +219 -0
  110. package/src/api/socket/e2ee/store.js +182 -0
  111. package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +9162 -0
  112. package/src/api/socket/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  113. package/src/api/socket/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  114. package/src/api/socket/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  115. package/src/api/socket/e2ee/vendor/proto/MessageApplication.proto +82 -0
  116. package/src/api/socket/e2ee/vendor/proto/MessageTransport.proto +77 -0
  117. package/src/api/socket/e2ee/vendor/proto/WACommon.proto +66 -0
  118. package/src/api/socket/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  119. package/src/api/socket/e2ee/vendor/proto/proto-writer.ts +76 -0
  120. package/src/api/socket/listenE2EE.js +75 -0
  121. package/src/api/socket/listenMqtt.js +388 -0
  122. package/src/api/socket/middleware/index.js +216 -0
  123. package/src/api/socket/sendMessage.js +309 -0
  124. package/src/api/socket/sendMessageMqtt.js +69 -0
  125. package/src/api/threads/getThreadHistory.js +664 -0
  126. package/src/api/threads/getThreadInfo.js +296 -0
  127. package/src/api/threads/getThreadList.js +293 -0
  128. package/src/api/threads/getThreadPictures.js +78 -0
  129. package/src/api/users/getUserID.js +65 -0
  130. package/src/api/users/getUserInfo.js +402 -0
  131. package/src/api/users/getUserInfoV2.js +134 -0
  132. package/src/app/MessengerBot.js +209 -0
  133. package/src/app/MessengerContext.js +32 -0
  134. package/src/app/createFcaClient.js +136 -0
  135. package/src/app/threadInfoRealtimeSync.js +284 -0
  136. package/src/core/sendReqMqtt.js +96 -0
  137. package/src/database/helpers.js +53 -0
  138. package/src/database/models/index.js +88 -0
  139. package/src/database/models/thread.js +50 -0
  140. package/src/database/models/user.js +46 -0
  141. package/src/database/threadData.js +94 -0
  142. package/src/database/userData.js +98 -0
  143. package/src/remote/remoteClient.js +123 -0
  144. package/src/utils/broadcast.js +51 -0
  145. package/src/utils/client.js +10 -0
  146. package/src/utils/constants.js +23 -0
  147. package/src/utils/cookies.js +68 -0
  148. package/src/utils/format/attachment.js +357 -0
  149. package/src/utils/format/cookie.js +9 -0
  150. package/src/utils/format/date.js +50 -0
  151. package/src/utils/format/decode.js +44 -0
  152. package/src/utils/format/delta.js +194 -0
  153. package/src/utils/format/ids.js +64 -0
  154. package/src/utils/format/index.js +64 -0
  155. package/src/utils/format/message.js +88 -0
  156. package/src/utils/format/presence.js +132 -0
  157. package/src/utils/format/readTyp.js +44 -0
  158. package/src/utils/format/thread.js +42 -0
  159. package/src/utils/format/utils.js +141 -0
  160. package/src/utils/headers.js +115 -0
  161. package/src/utils/loginParser/autoLogin.js +125 -0
  162. package/src/utils/loginParser/helpers.js +43 -0
  163. package/src/utils/loginParser/index.js +10 -0
  164. package/src/utils/loginParser/parseAndCheckLogin.js +220 -0
  165. package/src/utils/loginParser/textUtils.js +28 -0
  166. package/src/utils/nexca-logger.js +144 -0
  167. package/src/utils/nexca-utils.js +686 -0
  168. package/src/utils/request/client.js +26 -0
  169. package/src/utils/request/config.js +23 -0
  170. package/src/utils/request/defaults.js +46 -0
  171. package/src/utils/request/helpers.js +46 -0
  172. package/src/utils/request/index.js +17 -0
  173. package/src/utils/request/methods.js +163 -0
  174. package/src/utils/request/proxy.js +21 -0
  175. package/src/utils/request/retry.js +77 -0
  176. package/src/utils/request/sanitize.js +49 -0
  177. package/src/utils/versionCheck.js +47 -0
  178. package/src/vendor/fca-unofficial/.github/workflows/nodejs.yml +26 -0
  179. package/src/vendor/fca-unofficial/.github/workflows/npmpublish.yml +30 -0
  180. package/src/vendor/fca-unofficial/.travis.yml +6 -0
  181. package/src/vendor/fca-unofficial/DOCS.md +1731 -0
  182. package/src/vendor/fca-unofficial/LICENSE-MIT +21 -0
  183. package/src/vendor/fca-unofficial/README.md +225 -0
  184. package/src/vendor/fca-unofficial/index.js +619 -0
  185. package/src/vendor/fca-unofficial/package.json +76 -0
  186. package/src/vendor/fca-unofficial/src/addExternalModule.js +19 -0
  187. package/src/vendor/fca-unofficial/src/addUserToGroup.js +113 -0
  188. package/src/vendor/fca-unofficial/src/changeAdminStatus.js +79 -0
  189. package/src/vendor/fca-unofficial/src/changeArchivedStatus.js +55 -0
  190. package/src/vendor/fca-unofficial/src/changeBio.js +77 -0
  191. package/src/vendor/fca-unofficial/src/changeBlockedStatus.js +47 -0
  192. package/src/vendor/fca-unofficial/src/changeGroupImage.js +129 -0
  193. package/src/vendor/fca-unofficial/src/changeNickname.js +59 -0
  194. package/src/vendor/fca-unofficial/src/changeThreadColor.js +71 -0
  195. package/src/vendor/fca-unofficial/src/changeThreadEmoji.js +55 -0
  196. package/src/vendor/fca-unofficial/src/createNewGroup.js +86 -0
  197. package/src/vendor/fca-unofficial/src/createPoll.js +71 -0
  198. package/src/vendor/fca-unofficial/src/deleteMessage.js +56 -0
  199. package/src/vendor/fca-unofficial/src/deleteThread.js +56 -0
  200. package/src/vendor/fca-unofficial/src/forwardAttachment.js +60 -0
  201. package/src/vendor/fca-unofficial/src/getCurrentUserID.js +7 -0
  202. package/src/vendor/fca-unofficial/src/getEmojiUrl.js +29 -0
  203. package/src/vendor/fca-unofficial/src/getFriendsList.js +84 -0
  204. package/src/vendor/fca-unofficial/src/getThreadHistory.js +645 -0
  205. package/src/vendor/fca-unofficial/src/getThreadHistoryDeprecated.js +93 -0
  206. package/src/vendor/fca-unofficial/src/getThreadInfo.js +201 -0
  207. package/src/vendor/fca-unofficial/src/getThreadInfoDeprecated.js +80 -0
  208. package/src/vendor/fca-unofficial/src/getThreadList.js +238 -0
  209. package/src/vendor/fca-unofficial/src/getThreadListDeprecated.js +75 -0
  210. package/src/vendor/fca-unofficial/src/getThreadPictures.js +79 -0
  211. package/src/vendor/fca-unofficial/src/getUserID.js +66 -0
  212. package/src/vendor/fca-unofficial/src/getUserInfo.js +72 -0
  213. package/src/vendor/fca-unofficial/src/handleFriendRequest.js +61 -0
  214. package/src/vendor/fca-unofficial/src/handleMessageRequest.js +65 -0
  215. package/src/vendor/fca-unofficial/src/httpGet.js +52 -0
  216. package/src/vendor/fca-unofficial/src/httpPost.js +52 -0
  217. package/src/vendor/fca-unofficial/src/listenMqtt.js +788 -0
  218. package/src/vendor/fca-unofficial/src/logout.js +75 -0
  219. package/src/vendor/fca-unofficial/src/markAsDelivered.js +58 -0
  220. package/src/vendor/fca-unofficial/src/markAsRead.js +80 -0
  221. package/src/vendor/fca-unofficial/src/markAsReadAll.js +50 -0
  222. package/src/vendor/fca-unofficial/src/markAsSeen.js +59 -0
  223. package/src/vendor/fca-unofficial/src/muteThread.js +52 -0
  224. package/src/vendor/fca-unofficial/src/removeUserFromGroup.js +79 -0
  225. package/src/vendor/fca-unofficial/src/resolvePhotoUrl.js +45 -0
  226. package/src/vendor/fca-unofficial/src/searchForThread.js +53 -0
  227. package/src/vendor/fca-unofficial/src/sendMessage.js +459 -0
  228. package/src/vendor/fca-unofficial/src/sendTypingIndicator.js +103 -0
  229. package/src/vendor/fca-unofficial/src/setMessageReaction.js +117 -0
  230. package/src/vendor/fca-unofficial/src/setPostReaction.js +76 -0
  231. package/src/vendor/fca-unofficial/src/setTitle.js +86 -0
  232. package/src/vendor/fca-unofficial/src/threadColors.js +57 -0
  233. package/src/vendor/fca-unofficial/src/unfriend.js +52 -0
  234. package/src/vendor/fca-unofficial/src/unsendMessage.js +49 -0
  235. package/src/vendor/fca-unofficial/test/data/shareAttach.js +146 -0
  236. package/src/vendor/fca-unofficial/test/data/something.mov +0 -0
  237. package/src/vendor/fca-unofficial/test/data/test.png +0 -0
  238. package/src/vendor/fca-unofficial/test/data/test.txt +7 -0
  239. package/src/vendor/fca-unofficial/test/example-config.json +18 -0
  240. package/src/vendor/fca-unofficial/test/test-page.js +140 -0
  241. package/src/vendor/fca-unofficial/test/test.js +385 -0
  242. package/src/vendor/fca-unofficial/utils.js +1358 -0
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Double Ratchet Algorithm (Signal Protocol)
5
+ * Based on the Signal Protocol specification:
6
+ * https://signal.org/docs/specifications/doubleratchet/
7
+ */
8
+
9
+ const { generateKeyPair, dh, hkdf, hkdfExtract, hkdfExpand, encrypt, decrypt, hmacSha256 } = require("./crypto");
10
+
11
+ const MAX_SKIP = 1000;
12
+ const INFO_RATCHET = Buffer.from("WhisperRatchet", "utf8");
13
+ const INFO_MSG = Buffer.from("WhisperMessageKeys", "utf8");
14
+
15
+ function kdfCK(ck) {
16
+ const ck2 = hmacSha256(ck, Buffer.from([0x02]));
17
+ const mk = hmacSha256(ck, Buffer.from([0x01]));
18
+ return { ck: ck2, mk };
19
+ }
20
+
21
+ function kdfRK(rk, dh_out) {
22
+ const salt = rk;
23
+ const out = hkdf(dh_out, 64, salt, INFO_RATCHET);
24
+ return { rk: out.slice(0, 32), ck: out.slice(32, 64) };
25
+ }
26
+
27
+ function deriveMessageKeys(mk) {
28
+ const out = hkdf(mk, 80, Buffer.alloc(32, 0), INFO_MSG);
29
+ return {
30
+ encKey: out.slice(0, 32),
31
+ authKey: out.slice(32, 64),
32
+ iv: out.slice(64, 80)
33
+ };
34
+ }
35
+
36
+ class DoubleRatchetSession {
37
+ constructor() {
38
+ this.DHs = null; // Our DH ratchet key pair
39
+ this.DHr = null; // Their DH ratchet public key (raw 32 bytes)
40
+ this.RK = null; // Root key (32 bytes)
41
+ this.CKs = null; // Sending chain key
42
+ this.CKr = null; // Receiving chain key
43
+ this.Ns = 0; // Send message number
44
+ this.Nr = 0; // Receive message number
45
+ this.PN = 0; // Previous sending chain length
46
+ this.MKSKIPPED = new Map(); // Skipped message keys
47
+ }
48
+
49
+ /**
50
+ * Initialize as sender (Alice) after X3DH
51
+ */
52
+ initAsSender(sk, recipientRatchetPublicKey) {
53
+ this.DHs = generateKeyPair();
54
+ this.DHr = Buffer.from(recipientRatchetPublicKey);
55
+ const dhOut = dh(this.DHs.privateKey, this.DHr);
56
+ const { rk, ck } = kdfRK(sk, dhOut);
57
+ this.RK = rk;
58
+ this.CKs = ck;
59
+ this.CKr = null;
60
+ this.Ns = 0; this.Nr = 0; this.PN = 0;
61
+ }
62
+
63
+ /**
64
+ * Initialize as receiver (Bob) after X3DH
65
+ */
66
+ initAsReceiver(sk, ourRatchetKeyPair) {
67
+ this.DHs = ourRatchetKeyPair;
68
+ this.DHr = null;
69
+ this.RK = sk;
70
+ this.CKs = null;
71
+ this.CKr = null;
72
+ this.Ns = 0; this.Nr = 0; this.PN = 0;
73
+ }
74
+
75
+ /**
76
+ * Encrypt a message
77
+ * Returns { header, ciphertext }
78
+ */
79
+ encrypt(plaintext, aad) {
80
+ const { ck, mk } = kdfCK(this.CKs);
81
+ this.CKs = ck;
82
+ const header = this._buildHeader(this.DHs.publicKeyRaw, this.PN, this.Ns);
83
+ this.Ns++;
84
+ const keys = deriveMessageKeys(mk);
85
+ const aadFull = aad ? Buffer.concat([aad, header]) : header;
86
+ const ciphertext = encrypt(keys.encKey, Buffer.isBuffer(plaintext) ? plaintext : Buffer.from(plaintext, "utf8"), aadFull);
87
+ return { header, ciphertext };
88
+ }
89
+
90
+ /**
91
+ * Decrypt a message
92
+ * @param {Buffer} header - message header
93
+ * @param {Buffer} ciphertext - encrypted payload
94
+ * @param {Buffer} [aad] - additional auth data
95
+ * @returns {Buffer} decrypted plaintext
96
+ */
97
+ decrypt(header, ciphertext, aad) {
98
+ const { dh_pub, pn, n } = this._parseHeader(header);
99
+ const aadFull = aad ? Buffer.concat([aad, header]) : header;
100
+
101
+ // Check skipped keys first
102
+ const skipKey = `${dh_pub.toString("hex")}:${n}`;
103
+ if (this.MKSKIPPED.has(skipKey)) {
104
+ const mk = this.MKSKIPPED.get(skipKey);
105
+ this.MKSKIPPED.delete(skipKey);
106
+ const keys = deriveMessageKeys(mk);
107
+ return decrypt(keys.encKey, ciphertext, aadFull);
108
+ }
109
+
110
+ // Check if we need to ratchet
111
+ const needsRatchet = !this.DHr || !dh_pub.equals(this.DHr);
112
+ if (needsRatchet) {
113
+ this._skipMessageKeys(pn);
114
+ this._dhRatchetStep(dh_pub);
115
+ }
116
+
117
+ this._skipMessageKeys(n);
118
+ const { ck, mk } = kdfCK(this.CKr);
119
+ this.CKr = ck;
120
+ this.Nr++;
121
+
122
+ const keys = deriveMessageKeys(mk);
123
+ return decrypt(keys.encKey, ciphertext, aadFull);
124
+ }
125
+
126
+ _skipMessageKeys(until) {
127
+ if (this.Nr + MAX_SKIP < until) throw new Error("Too many skipped messages: " + until);
128
+ if (this.CKr) {
129
+ while (this.Nr < until) {
130
+ const { ck, mk } = kdfCK(this.CKr);
131
+ this.CKr = ck;
132
+ const key = `${this.DHr.toString("hex")}:${this.Nr}`;
133
+ this.MKSKIPPED.set(key, mk);
134
+ this.Nr++;
135
+ }
136
+ }
137
+ }
138
+
139
+ _dhRatchetStep(remoteDhPub) {
140
+ this.PN = this.Ns;
141
+ this.Ns = 0;
142
+ this.Nr = 0;
143
+ this.DHr = remoteDhPub;
144
+
145
+ // Receive ratchet
146
+ const dhOut1 = dh(this.DHs.privateKey, this.DHr);
147
+ const { rk: rk1, ck: ckr } = kdfRK(this.RK, dhOut1);
148
+ this.RK = rk1;
149
+ this.CKr = ckr;
150
+
151
+ // Send ratchet
152
+ this.DHs = generateKeyPair();
153
+ const dhOut2 = dh(this.DHs.privateKey, this.DHr);
154
+ const { rk: rk2, ck: cks } = kdfRK(this.RK, dhOut2);
155
+ this.RK = rk2;
156
+ this.CKs = cks;
157
+ }
158
+
159
+ _buildHeader(dhPub, pn, n) {
160
+ const buf = Buffer.allocUnsafe(32 + 4 + 4);
161
+ Buffer.from(dhPub).copy(buf, 0);
162
+ buf.writeUInt32BE(pn, 32);
163
+ buf.writeUInt32BE(n, 36);
164
+ return buf;
165
+ }
166
+
167
+ _parseHeader(header) {
168
+ if (header.length < 40) throw new Error("Invalid ratchet header length");
169
+ return {
170
+ dh_pub: header.slice(0, 32),
171
+ pn: header.readUInt32BE(32),
172
+ n: header.readUInt32BE(36)
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Serialize session state for persistence
178
+ */
179
+ serialize() {
180
+ return JSON.stringify({
181
+ DHs_priv: this.DHs ? this.DHs.privateKey.toString("base64") : null,
182
+ DHs_pub: this.DHs ? this.DHs.publicKeyRaw.toString("base64") : null,
183
+ DHr: this.DHr ? this.DHr.toString("base64") : null,
184
+ RK: this.RK ? this.RK.toString("base64") : null,
185
+ CKs: this.CKs ? this.CKs.toString("base64") : null,
186
+ CKr: this.CKr ? this.CKr.toString("base64") : null,
187
+ Ns: this.Ns,
188
+ Nr: this.Nr,
189
+ PN: this.PN,
190
+ MKSKIPPED: Array.from(this.MKSKIPPED.entries()).map(([k, v]) => [k, v.toString("base64")])
191
+ });
192
+ }
193
+
194
+ /**
195
+ * Restore session state from serialized string
196
+ */
197
+ static deserialize(json) {
198
+ const d = JSON.parse(json);
199
+ const session = new DoubleRatchetSession();
200
+ if (d.DHs_priv) {
201
+ session.DHs = {
202
+ privateKey: Buffer.from(d.DHs_priv, "base64"),
203
+ publicKey: null,
204
+ publicKeyRaw: Buffer.from(d.DHs_pub, "base64")
205
+ };
206
+ }
207
+ session.DHr = d.DHr ? Buffer.from(d.DHr, "base64") : null;
208
+ session.RK = d.RK ? Buffer.from(d.RK, "base64") : null;
209
+ session.CKs = d.CKs ? Buffer.from(d.CKs, "base64") : null;
210
+ session.CKr = d.CKr ? Buffer.from(d.CKr, "base64") : null;
211
+ session.Ns = d.Ns || 0;
212
+ session.Nr = d.Nr || 0;
213
+ session.PN = d.PN || 0;
214
+ session.MKSKIPPED = new Map((d.MKSKIPPED || []).map(([k, v]) => [k, Buffer.from(v, "base64")]));
215
+ return session;
216
+ }
217
+ }
218
+
219
+ module.exports = { DoubleRatchetSession, kdfCK, kdfRK, deriveMessageKeys };
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * E2EE Device/Session Store
5
+ * Persists key material to a JSON file (encrypted with a device secret).
6
+ * Each E2EE session (thread) is stored separately.
7
+ */
8
+
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const crypto = require("crypto");
12
+
13
+ class E2EEStore {
14
+ constructor(storePath, userID) {
15
+ this.storePath = storePath;
16
+ this.userID = userID;
17
+ this.data = {
18
+ identityKey: null,
19
+ signedPreKey: null,
20
+ oneTimePreKeys: [],
21
+ sessions: {}, // threadID -> serialized DoubleRatchetSession
22
+ deviceSecret: null // 32-byte random secret for local encryption
23
+ };
24
+ this._loaded = false;
25
+ }
26
+
27
+ _storeFile() {
28
+ return path.join(this.storePath, `nexca_e2ee_${this.userID}.json`);
29
+ }
30
+
31
+ _salt() {
32
+ return Buffer.from(this.userID.padEnd(16, "0").slice(0, 16), "utf8");
33
+ }
34
+
35
+ _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;
39
+ const iv = crypto.randomBytes(12);
40
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
41
+ const enc = Buffer.concat([cipher.update(Buffer.from(data, "utf8")), cipher.final()]);
42
+ const tag = cipher.getAuthTag();
43
+ return Buffer.concat([iv, tag, enc]).toString("base64");
44
+ }
45
+
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;
60
+ }
61
+ }
62
+
63
+ load() {
64
+ const file = this._storeFile();
65
+ if (!fs.existsSync(file)) return false;
66
+ try {
67
+ const raw = fs.readFileSync(file, "utf8");
68
+ 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 || {};
76
+ this._loaded = true;
77
+ return true;
78
+ } catch (_) {
79
+ return false;
80
+ }
81
+ }
82
+
83
+ 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
+ }
90
+ const payload = JSON.stringify({
91
+ identityKey: this.data.identityKey,
92
+ signedPreKey: this.data.signedPreKey,
93
+ oneTimePreKeys: this.data.oneTimePreKeys,
94
+ sessions: this.data.sessions
95
+ });
96
+ const encrypted = this._localEncrypt(payload);
97
+ fs.writeFileSync(this._storeFile(), JSON.stringify({ deviceSecret: this.data.deviceSecret, payload: encrypted }, null, 2), "utf8");
98
+ }
99
+
100
+ hasIdentityKey() { return !!this.data.identityKey; }
101
+
102
+ getIdentityKey() {
103
+ const ik = this.data.identityKey;
104
+ if (!ik) return null;
105
+ return {
106
+ privateKey: Buffer.from(ik.privateKey, "base64"),
107
+ publicKey: Buffer.from(ik.publicKey, "base64"),
108
+ publicKeyRaw: Buffer.from(ik.publicKeyRaw, "base64")
109
+ };
110
+ }
111
+
112
+ setIdentityKey(keyPair) {
113
+ this.data.identityKey = {
114
+ privateKey: keyPair.privateKey.toString("base64"),
115
+ publicKey: keyPair.publicKey.toString("base64"),
116
+ publicKeyRaw: keyPair.publicKeyRaw.toString("base64")
117
+ };
118
+ }
119
+
120
+ getSignedPreKey() {
121
+ const spk = this.data.signedPreKey;
122
+ if (!spk) return null;
123
+ return {
124
+ privateKey: Buffer.from(spk.privateKey, "base64"),
125
+ publicKey: Buffer.from(spk.publicKey, "base64"),
126
+ publicKeyRaw: Buffer.from(spk.publicKeyRaw, "base64"),
127
+ signature: Buffer.from(spk.signature, "base64"),
128
+ keyId: spk.keyId
129
+ };
130
+ }
131
+
132
+ setSignedPreKey(keyPair) {
133
+ this.data.signedPreKey = {
134
+ privateKey: keyPair.privateKey.toString("base64"),
135
+ publicKey: keyPair.publicKey.toString("base64"),
136
+ publicKeyRaw: keyPair.publicKeyRaw.toString("base64"),
137
+ signature: keyPair.signature ? keyPair.signature.toString("base64") : "",
138
+ keyId: keyPair.keyId || 1
139
+ };
140
+ }
141
+
142
+ getOneTimePreKeys() {
143
+ return (this.data.oneTimePreKeys || []).map(k => ({
144
+ privateKey: Buffer.from(k.privateKey, "base64"),
145
+ publicKey: Buffer.from(k.publicKey, "base64"),
146
+ publicKeyRaw: Buffer.from(k.publicKeyRaw, "base64"),
147
+ keyId: k.keyId
148
+ }));
149
+ }
150
+
151
+ addOneTimePreKey(keyPair) {
152
+ this.data.oneTimePreKeys = this.data.oneTimePreKeys || [];
153
+ this.data.oneTimePreKeys.push({
154
+ privateKey: keyPair.privateKey.toString("base64"),
155
+ publicKey: keyPair.publicKey.toString("base64"),
156
+ publicKeyRaw: keyPair.publicKeyRaw.toString("base64"),
157
+ keyId: keyPair.keyId
158
+ });
159
+ }
160
+
161
+ consumeOneTimePreKey(keyId) {
162
+ const idx = (this.data.oneTimePreKeys || []).findIndex(k => k.keyId === keyId);
163
+ if (idx < 0) return null;
164
+ const k = this.data.oneTimePreKeys.splice(idx, 1)[0];
165
+ return {
166
+ privateKey: Buffer.from(k.privateKey, "base64"),
167
+ publicKey: Buffer.from(k.publicKey, "base64"),
168
+ publicKeyRaw: Buffer.from(k.publicKeyRaw, "base64"),
169
+ keyId: k.keyId
170
+ };
171
+ }
172
+
173
+ hasSession(threadID) { return !!this.data.sessions[threadID]; }
174
+
175
+ getSession(threadID) { return this.data.sessions[threadID] || null; }
176
+
177
+ setSession(threadID, serializedSession) { this.data.sessions[threadID] = serializedSession; }
178
+
179
+ deleteSession(threadID) { delete this.data.sessions[threadID]; }
180
+ }
181
+
182
+ module.exports = { E2EEStore };