fca-nx 6.6.9 → 6.7.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 (50) hide show
  1. package/module/login.js +17 -8
  2. package/module/loginHelper.js +31 -2
  3. package/package.json +3 -2
  4. package/src/api/messaging/uploadAttachment.js +2 -2
  5. package/src/api/socket/e2ee/index.js +1 -1
  6. package/src/api/socket/listenE2EE.js +14 -4
  7. package/src/api/socket/listenMqtt.js +13 -3
  8. package/src/utils/format/utils.js +18 -12
  9. package/src/utils/utils.js +15 -6
  10. package/e2ee/config.json +0 -0
  11. package/e2ee/crypto.js +0 -173
  12. package/e2ee/index.js +0 -1032
  13. package/e2ee/proto/ArmadilloApplication.proto +0 -281
  14. package/e2ee/proto/ArmadilloICDC.proto +0 -14
  15. package/e2ee/proto/ConsumerApplication.proto +0 -232
  16. package/e2ee/proto/MessageApplication.proto +0 -82
  17. package/e2ee/proto/MessageTransport.proto +0 -77
  18. package/e2ee/proto/WACommon.proto +0 -66
  19. package/e2ee/proto/WAMediaTransport.proto +0 -176
  20. package/e2ee/protocol.js +0 -196
  21. package/e2ee/ratchet.js +0 -219
  22. package/e2ee/store.js +0 -182
  23. package/e2ee/vendor/fb-e2ee.cjs +0 -9159
  24. package/e2ee/vendor/proto/ArmadilloApplication.proto +0 -281
  25. package/e2ee/vendor/proto/ArmadilloICDC.proto +0 -14
  26. package/e2ee/vendor/proto/ConsumerApplication.proto +0 -232
  27. package/e2ee/vendor/proto/MessageApplication.proto +0 -82
  28. package/e2ee/vendor/proto/MessageTransport.proto +0 -77
  29. package/e2ee/vendor/proto/WACommon.proto +0 -66
  30. package/e2ee/vendor/proto/WAMediaTransport.proto +0 -176
  31. package/src/api/socket/e2ee/e2ee/crypto.js +0 -173
  32. package/src/api/socket/e2ee/e2ee/index.js +0 -421
  33. package/src/api/socket/e2ee/e2ee/proto/ArmadilloApplication.proto +0 -281
  34. package/src/api/socket/e2ee/e2ee/proto/ArmadilloICDC.proto +0 -14
  35. package/src/api/socket/e2ee/e2ee/proto/ConsumerApplication.proto +0 -232
  36. package/src/api/socket/e2ee/e2ee/proto/MessageApplication.proto +0 -82
  37. package/src/api/socket/e2ee/e2ee/proto/MessageTransport.proto +0 -77
  38. package/src/api/socket/e2ee/e2ee/proto/WACommon.proto +0 -66
  39. package/src/api/socket/e2ee/e2ee/proto/WAMediaTransport.proto +0 -176
  40. package/src/api/socket/e2ee/e2ee/protocol.js +0 -196
  41. package/src/api/socket/e2ee/e2ee/ratchet.js +0 -219
  42. package/src/api/socket/e2ee/e2ee/store.js +0 -182
  43. package/src/api/socket/e2ee/e2ee/vendor/fb-e2ee.cjs +0 -9162
  44. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloApplication.proto +0 -281
  45. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloICDC.proto +0 -14
  46. package/src/api/socket/e2ee/e2ee/vendor/proto/ConsumerApplication.proto +0 -232
  47. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageApplication.proto +0 -82
  48. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageTransport.proto +0 -77
  49. package/src/api/socket/e2ee/e2ee/vendor/proto/WACommon.proto +0 -66
  50. package/src/api/socket/e2ee/e2ee/vendor/proto/WAMediaTransport.proto +0 -176
package/module/login.js CHANGED
@@ -46,10 +46,14 @@ if (!global.fca._errorHandlersInstalled) {
46
46
  }
47
47
  }
48
48
 
49
- // For other unhandled rejections, log but don't crash
50
- logger(`Unhandled promise rejection (non-fatal): ${reason && reason.message ? reason.message : String(reason)}`, "error");
49
+ // [Fixed by xalman] For other unhandled rejections, log but don't crash.
50
+ // Include the stack (when available) - logging only `.message` made
51
+ // real bugs impossible to trace back to where they were thrown.
52
+ const errorDetail = reason && reason.stack ? reason.stack : (reason && reason.message ? reason.message : String(reason));
53
+ logger(`Unhandled promise rejection (non-fatal): ${errorDetail}`, "error");
51
54
  } catch (e) {
52
- // Fallback if logger fails - silent
55
+ // Logger itself failed - fall back to stderr so this isn't silently lost.
56
+ try { console.error("[fca-nx] logger failed while handling unhandledRejection:", e, reason); } catch { }
53
57
  }
54
58
  });
55
59
 
@@ -73,12 +77,17 @@ if (!global.fca._errorHandlersInstalled) {
73
77
  return; // Don't crash
74
78
  }
75
79
 
76
- // For other uncaught exceptions, log but try to continue
77
- logger(`Uncaught exception (attempting to continue): ${errorMessage}`, "error");
78
- // Note: We don't exit here to allow bot to continue running
79
- // In production, you might want to restart the process instead
80
+ // [Fixed by xalman] For other uncaught exceptions, log but try to continue.
81
+ // Include the stack trace - without it these were undebuggable in production.
82
+ logger(`Uncaught exception (attempting to continue): ${error && error.stack ? error.stack : errorMessage}`, "error");
83
+ // Note: We don't exit here to allow bot to continue running.
84
+ // This trades crash-safety for the (small) risk of continuing in a
85
+ // partially-inconsistent process state. If you run this under a process
86
+ // manager (pm2/systemd) that auto-restarts on crash, consider calling
87
+ // process.exit(1) here instead for a clean restart on truly unknown errors.
80
88
  } catch (e) {
81
- // Fallback if logger fails - silent
89
+ // Logger itself failed - fall back to stderr so this isn't silently lost.
90
+ try { console.error("[fca-nx] logger failed while handling uncaughtException:", e, error); } catch { }
82
91
  }
83
92
  });
84
93
  }
@@ -1170,6 +1170,27 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1170
1170
  ctxMain.bypassAutomation = ctx.bypassAutomation.bind(ctxMain);
1171
1171
  ctxMain.performAutoLogin = async () => {
1172
1172
  try {
1173
+ // [Fixed by xalman] First check whether the existing cookie session is actually
1174
+ // still usable. A checkpoint/redirect seen on one request
1175
+ // doesn't always mean the whole session is dead (transient FB
1176
+ // blips, rate limiting, etc). Cookie/appstate-only logins have
1177
+ // no email+password to re-login with, so without this check a
1178
+ // single false-positive checkpoint would permanently tear down
1179
+ // the bot (via emitAuth) and force a brand new cookie every
1180
+ // time instead of just continuing on the still-good session.
1181
+ try {
1182
+ const check = await get("https://www.facebook.com/", jar, null, globalOptions).then(saveCookies(jar));
1183
+ const html = check && check.data ? String(check.data) : "";
1184
+ const stillCheckpointed = html.includes("/checkpoint/block/?next") || html.includes("XCheckpointFBScrapingWarningController");
1185
+ const uidMatch = html.match(/"USER_ID"\s*:\s*"(\d+)"/);
1186
+ if (!stillCheckpointed && uidMatch && uidMatch[1] && uidMatch[1] !== "0") {
1187
+ logger("performAutoLogin: existing cookie session is still valid, continuing without re-login", "info");
1188
+ return true;
1189
+ }
1190
+ } catch {
1191
+ // Self-check failed (network hiccup, etc) - fall through to credential-based login below.
1192
+ }
1193
+
1173
1194
  const u = config.credentials?.email || email;
1174
1195
  const p = config.credentials?.password || password;
1175
1196
  const tf = config.credentials?.twofactor || null;
@@ -1314,10 +1335,18 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1314
1335
  // bots calling api.listen() OR api.listenMqtt() directly also
1315
1336
  // receive E2EE (Secret Conversation) messages without any extra
1316
1337
  // setup or changes on the bot side.
1338
+ //
1339
+ // [Fixed by xalman] IMPORTANT: assign api.listen/api.listenMqtt to the combined
1340
+ // listener SYNCHRONOUSLY, before connectE2EE() resolves. Bots
1341
+ // commonly call api.listenMqtt(callback) immediately in the login
1342
+ // callback - if we waited for the async connectE2EE() promise to
1343
+ // swap these over, that call would already have captured the old
1344
+ // plain-MQTT-only function, permanently missing E2EE (inbox)
1345
+ // messages even after E2EE finished connecting moments later.
1346
+ api.listen = api.listenE2EE;
1347
+ api.listenMqtt = api.listenE2EE;
1317
1348
  api.connectE2EE()
1318
1349
  .then(() => {
1319
- api.listen = api.listenE2EE;
1320
- api.listenMqtt = api.listenE2EE;
1321
1350
  logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
1322
1351
  })
1323
1352
  .catch((e) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.6.9",
3
+ "version": "6.7.0",
4
4
  "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -17,7 +17,6 @@
17
17
  "module/",
18
18
  "func/",
19
19
  "src/",
20
- "e2ee/",
21
20
  "DOCS.md",
22
21
  "README.md",
23
22
  "src/app/"
@@ -85,9 +84,11 @@
85
84
  "mime": "^3.0.0",
86
85
  "mqtt": "^5.10.1",
87
86
  "protobufjs": "^8.4.0",
87
+ "request": "^2.88.2",
88
88
  "sequelize": "^6.37.8",
89
89
  "sqlite3": "^5.1.7",
90
90
  "totp-generator": "^1.0.0",
91
+ "tough-cookie": "^4.1.4",
91
92
  "ws": "^8.18.0"
92
93
  },
93
94
  "devDependencies": {
@@ -62,7 +62,7 @@ function respFinalUrl(res) {
62
62
 
63
63
  function detectCheckpoint(res) {
64
64
  const url = String(respFinalUrl(res) || "");
65
- const body = typeof res?.body === "string" ? res.body : "";
65
+ const body = typeof res?.data === "string" ? res.data : "";
66
66
  const hit =
67
67
  /\/checkpoint\//i.test(url) ||
68
68
  /(?:href|action)\s*=\s*["']https?:\/\/[^"']*\/checkpoint\//i.test(body) ||
@@ -78,7 +78,7 @@ function checkpointError(res) {
78
78
  e.code = "CHECKPOINT";
79
79
  e.checkpoint = true;
80
80
  e.url = d.url || "https://www.facebook.com/checkpoint/";
81
- e.status = res?.statusCode || res?.status;
81
+ e.status = res?.status || res?.statusCode;
82
82
  return e;
83
83
  }
84
84
 
@@ -113,7 +113,7 @@ class E2EEBridge {
113
113
  require("request")({ method: "POST", url: url, jar: _ctx.jar, form: merged, gzip: true },
114
114
  function (err, r) { if (err) return reject(err); resolve(r); });
115
115
  });
116
- return res && res.body;
116
+ return res && (res.data !== undefined ? res.data : res.body);
117
117
  },
118
118
  // listenMqtt — fb-e2ee.cjs calls this to route non-E2EE MQTT events.
119
119
  // FCA-NX has its own separate MQTT listener so we provide a no-op stub
@@ -47,15 +47,25 @@ module.exports = function (defaultFuncs, api, ctx) {
47
47
  var mqttEmitter = (api._listenMqttRaw || api.listenMqtt)(globalCallback);
48
48
  api._mqttEmitter = mqttEmitter;
49
49
 
50
- // Hook E2EE incoming messages (FCA-NX native Noise WebSocket)
50
+ // [Fixed by xalman] Hook E2EE incoming messages (FCA-NX native Noise WebSocket).
51
+ // onMessage() only registers a callback reference - it doesn't require an
52
+ // active connection - so this is safe to call even while E2EE is still
53
+ // connecting in the background. If we skip it here just because
54
+ // isConnected() is momentarily false, the hook never gets attached and
55
+ // E2EE (inbox) messages go unheard for the lifetime of this listener.
51
56
  var e2ee = api.e2ee || ctx.e2ee;
52
- if (!e2ee || !e2ee.isConnected()) {
57
+ if (!e2ee) {
53
58
  logger.warn(
54
59
  "listenE2EE",
55
- "E2EE not connected. E2EE messages will not be received. " +
56
- "Call api.connectE2EE() before listenE2EE() to enable encrypted message reception."
60
+ "E2EE bridge not available. E2EE messages will not be received."
57
61
  );
58
62
  } else {
63
+ if (!e2ee.isConnected()) {
64
+ logger.info(
65
+ "listenE2EE",
66
+ "E2EE still connecting - message hook registered, will receive events once the handshake completes."
67
+ );
68
+ }
59
69
  e2ee.onMessage(function (err, event) {
60
70
  if (err) return globalCallback(err, null);
61
71
  if (!event) return;
@@ -393,13 +393,23 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
393
393
  function attachClientListeners() {
394
394
  if (!ctx.mqttClient) return;
395
395
 
396
- ctx.mqttClient.removeAllListeners("pong");
396
+ ctx.mqttClient.removeAllListeners("packetreceive");
397
397
  ctx.mqttClient.removeAllListeners("close");
398
398
  ctx.mqttClient.removeAllListeners("error");
399
399
 
400
- ctx.mqttClient.on("pong", () => {
400
+ // [Fixed by xalman] mqtt.js does NOT emit a "pong" event - that was never firing,
401
+ // so lastPongTime was never refreshed and the heartbeat below kept
402
+ // force-reconnecting the account roughly every minute (this is what
403
+ // looked like periodic auto logout). The library's own keepalive
404
+ // (keepalive: 30 in connectMqtt.js) sends PINGREQ/PINGRESP
405
+ // internally; we detect the PINGRESP via "packetreceive" instead.
406
+ // Any other incoming packet (e.g. real messages) also proves the
407
+ // connection is alive, so it counts too.
408
+ ctx.mqttClient.on("packetreceive", (packet) => {
401
409
  lastPongTime = Date.now();
402
- logger("mqtt pong received", "debug");
410
+ if (packet && packet.cmd === "pingresp") {
411
+ logger("mqtt pong received", "debug");
412
+ }
403
413
  });
404
414
 
405
415
  ctx.mqttClient.once("close", () => {
@@ -4,8 +4,11 @@ function getType(obj) {
4
4
  return Object.prototype.toString.call(obj).slice(8, -1);
5
5
  }
6
6
 
7
+ // [Fixed by xalman] formatID now coerces id to String before .replace() -
8
+ // previously crashed with "id.replace is not a function" whenever a numeric
9
+ // userID was passed (e.g. addFriend), since Number has no .replace method.
7
10
  function formatID(id) {
8
- if (id != undefined && id != null) return id.replace(/(fb)?id[:.]/, "");
11
+ if (id != undefined && id != null) return String(id).replace(/(fb)?id[:.]/, "");
9
12
  else return id;
10
13
  }
11
14
 
@@ -35,6 +38,10 @@ function arrToForm(form) {
35
38
  );
36
39
  }
37
40
 
41
+ // [Fixed by xalman] Stt was previously incremented ("Stt++") on every
42
+ // recursive call, which silently coerced any non-numeric default value
43
+ // (string/null/object - the normal case) to NaN one level deep. It's a
44
+ // static fallback value, so it's now passed through unchanged.
38
45
  function getData_Path(Obj, Arr, Stt) {
39
46
  if (Arr.length === 0 && Obj != undefined) {
40
47
  return Obj;
@@ -46,27 +53,26 @@ function getData_Path(Obj, Arr, Stt) {
46
53
  return Stt;
47
54
  }
48
55
  const tail = Arr.slice(1);
49
- return getData_Path(Obj[head], tail, Stt++);
56
+ return getData_Path(Obj[head], tail, Stt);
50
57
  }
51
58
 
59
+ // [Fixed by xalman] Rewritten - the old version reassigned a local variable
60
+ // instead of the actual object property, so updating an EXISTING truthy
61
+ // value silently did nothing. Also stopped mutating the caller's path array.
52
62
  function setData_Path(obj, path, value) {
53
63
  if (!path.length) {
54
64
  return obj;
55
65
  }
56
66
  const currentKey = path[0];
57
- let currentObj = obj[currentKey];
58
-
59
- if (!currentObj) {
67
+ const remaining = path.slice(1);
68
+ if (!remaining.length) {
60
69
  obj[currentKey] = value;
61
- currentObj = obj[currentKey];
62
- }
63
- path.shift();
64
- if (!path.length) {
65
- currentObj = value;
66
70
  } else {
67
- currentObj = setData_Path(currentObj, path, value);
71
+ if (!obj[currentKey] || typeof obj[currentKey] !== "object") {
72
+ obj[currentKey] = {};
73
+ }
74
+ setData_Path(obj[currentKey], remaining, value);
68
75
  }
69
-
70
76
  return obj;
71
77
  }
72
78
 
@@ -245,15 +245,24 @@ function decodeClientPayload(payload) {
245
245
 
246
246
  function parseAndCheckLogin(ctx, defaultFuncs) {
247
247
  return function (res) {
248
- if (res.statusCode >= 500 && res.statusCode < 600) {
249
- throw { error: "Facebook internal server error: " + res.statusCode, res };
248
+ // NOTE: this used to read res.statusCode/res.body, which are the old
249
+ // `request`/`request-promise` library's property names. The actual
250
+ // HTTP client here (src/utils/request) is axios-based, whose
251
+ // responses use res.status/res.data instead - res.body was always
252
+ // undefined, so this threw "Empty response body" on every single
253
+ // call. That silently broke OldMessage.js (used for DM attachments,
254
+ // and as the fallback whenever an MQTT send fails).
255
+ var status = res && res.status !== undefined ? res.status : (res && res.statusCode);
256
+ if (status >= 500 && status < 600) {
257
+ throw { error: "Facebook internal server error: " + status, res };
250
258
  }
251
- if (res.statusCode === 404 || res.statusCode === 410) {
252
- throw { error: "Endpoint not found: " + res.statusCode, res };
259
+ if (status === 404 || status === 410) {
260
+ throw { error: "Endpoint not found: " + status, res };
253
261
  }
254
- if (!res.body) throw { error: "Empty response body", res };
262
+ var rawBody = res && res.data !== undefined ? res.data : (res && res.body);
263
+ if (rawBody === undefined || rawBody === null || rawBody === "") throw { error: "Empty response body", res };
255
264
 
256
- var body = res.body;
265
+ var body = rawBody;
257
266
  if (typeof body !== "string") body = JSON.stringify(body);
258
267
 
259
268
  var stripped = body;
package/e2ee/config.json DELETED
File without changes
package/e2ee/crypto.js DELETED
@@ -1,173 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * FCA-NX E2EE Crypto — All primitives using Node.js built-in crypto only.
5
- * Implements: X25519 DH, HKDF-SHA256, AES-256-GCM, HMAC-SHA256
6
- * Node.js >= 15 required (crypto.hkdfSync, crypto.generateKeyPairSync x25519).
7
- */
8
-
9
- const crypto = require("crypto");
10
-
11
- // ─────────────────────────────────────────────────────────
12
- // X25519 Key Management
13
- // ─────────────────────────────────────────────────────────
14
-
15
- function generateKeyPair() {
16
- const { privateKey, publicKey } = crypto.generateKeyPairSync("x25519", {
17
- privateKeyEncoding: { type: "pkcs8", format: "der" },
18
- publicKeyEncoding: { type: "spki", format: "der" }
19
- });
20
- return {
21
- privateKey,
22
- publicKey,
23
- publicKeyRaw: exportRawPublicKey(publicKey)
24
- };
25
- }
26
-
27
- function exportRawPublicKey(spkiDer) {
28
- // X25519 SPKI DER: 12 bytes header + 32 bytes key
29
- return Buffer.from(spkiDer).slice(-32);
30
- }
31
-
32
- function importPublicKey(raw32bytes) {
33
- if (raw32bytes.length !== 32) throw new Error("X25519 public key must be 32 bytes");
34
- // Build minimal SPKI wrapper for X25519
35
- const header = Buffer.from("302a300506032b656e032100", "hex");
36
- return Buffer.concat([header, raw32bytes]);
37
- }
38
-
39
- function dh(privateKeyPkcs8Der, peerPublicRaw32) {
40
- const privKey = crypto.createPrivateKey({ key: Buffer.from(privateKeyPkcs8Der), format: "der", type: "pkcs8" });
41
- const pubKeyDer = importPublicKey(Buffer.from(peerPublicRaw32));
42
- const pubKey = crypto.createPublicKey({ key: pubKeyDer, format: "der", type: "spki" });
43
- return crypto.diffieHellman({ privateKey: privKey, publicKey: pubKey });
44
- }
45
-
46
- // ─────────────────────────────────────────────────────────
47
- // HKDF-SHA256
48
- // ─────────────────────────────────────────────────────────
49
-
50
- function hkdf(ikm, length, salt, info) {
51
- if (!salt) salt = Buffer.alloc(32, 0);
52
- if (!info) info = Buffer.alloc(0);
53
- if (typeof info === "string") info = Buffer.from(info, "utf8");
54
- return Buffer.from(crypto.hkdfSync("sha256", ikm, salt, info, length));
55
- }
56
-
57
- function hkdfExtract(salt, ikm) {
58
- return crypto.createHmac("sha256", salt).update(ikm).digest();
59
- }
60
-
61
- function hkdfExpand(prk, info, length) {
62
- const results = [];
63
- let t = Buffer.alloc(0);
64
- let i = 0;
65
- while (results.reduce((s, b) => s + b.length, 0) < length) {
66
- i++;
67
- const hmac = crypto.createHmac("sha256", prk);
68
- hmac.update(t);
69
- if (info) hmac.update(info);
70
- hmac.update(Buffer.from([i]));
71
- t = hmac.digest();
72
- results.push(t);
73
- }
74
- return Buffer.concat(results).slice(0, length);
75
- }
76
-
77
- // ─────────────────────────────────────────────────────────
78
- // AES-256-GCM
79
- // ─────────────────────────────────────────────────────────
80
-
81
- function encrypt(key32, plaintext, aad) {
82
- if (key32.length !== 32) throw new Error("AES-GCM key must be 32 bytes");
83
- const iv = crypto.randomBytes(12);
84
- const cipher = crypto.createCipheriv("aes-256-gcm", key32, iv);
85
- if (aad) cipher.setAAD(aad);
86
- const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
87
- const authTag = cipher.getAuthTag();
88
- return Buffer.concat([iv, authTag, encrypted]);
89
- }
90
-
91
- function decrypt(key32, ciphertext, aad) {
92
- if (key32.length !== 32) throw new Error("AES-GCM key must be 32 bytes");
93
- if (ciphertext.length < 28) throw new Error("Ciphertext too short");
94
- const iv = ciphertext.slice(0, 12);
95
- const authTag = ciphertext.slice(12, 28);
96
- const data = ciphertext.slice(28);
97
- const decipher = crypto.createDecipheriv("aes-256-gcm", key32, iv);
98
- decipher.setAuthTag(authTag);
99
- if (aad) decipher.setAAD(aad);
100
- return Buffer.concat([decipher.update(data), decipher.final()]);
101
- }
102
-
103
- // ─────────────────────────────────────────────────────────
104
- // HMAC-SHA256
105
- // ─────────────────────────────────────────────────────────
106
-
107
- function hmacSha256(key, data) {
108
- return crypto.createHmac("sha256", key).update(data).digest();
109
- }
110
-
111
- function constantTimeEqual(a, b) {
112
- if (a.length !== b.length) return false;
113
- return crypto.timingSafeEqual(a, b);
114
- }
115
-
116
- // ─────────────────────────────────────────────────────────
117
- // X3DH Key Agreement (Extended Triple Diffie-Hellman)
118
- // ─────────────────────────────────────────────────────────
119
-
120
- /**
121
- * Sender side of X3DH.
122
- * @param {object} senderIdKey - { privateKey, publicKey, publicKeyRaw } of sender identity key
123
- * @param {object} ephemeralKey - { privateKey, publicKey, publicKeyRaw } of ephemeral key
124
- * @param {Buffer} recipientIdPub - recipient's identity public key (raw 32 bytes)
125
- * @param {Buffer} recipientSpkPub - recipient's signed pre-key (raw 32 bytes)
126
- * @param {Buffer} [recipientOpkPub] - recipient's one-time pre-key (raw 32 bytes), optional
127
- * @returns {Buffer} 32-byte shared master secret
128
- */
129
- function x3dhSend(senderIdKey, ephemeralKey, recipientIdPub, recipientSpkPub, recipientOpkPub) {
130
- const dh1 = dh(senderIdKey.privateKey, recipientSpkPub);
131
- const dh2 = dh(ephemeralKey.privateKey, recipientIdPub);
132
- const dh3 = dh(ephemeralKey.privateKey, recipientSpkPub);
133
- const parts = recipientOpkPub
134
- ? [dh1, dh2, dh3, dh(ephemeralKey.privateKey, recipientOpkPub)]
135
- : [dh1, dh2, dh3];
136
- const ikm = Buffer.concat(parts);
137
- const F = Buffer.alloc(32, 0xFF);
138
- const salt = Buffer.alloc(32, 0);
139
- return hkdf(Buffer.concat([F, ikm]), 32, salt, Buffer.from("WhisperText", "utf8"));
140
- }
141
-
142
- /**
143
- * Receiver side of X3DH.
144
- */
145
- function x3dhReceive(recipientIdKey, recipientSpkKey, recipientOpkKey, senderIdPub, senderEphemeralPub) {
146
- const dh1 = dh(recipientSpkKey.privateKey, senderIdPub);
147
- const dh2 = dh(recipientIdKey.privateKey, senderEphemeralPub);
148
- const dh3 = dh(recipientSpkKey.privateKey, senderEphemeralPub);
149
- const parts = recipientOpkKey
150
- ? [dh1, dh2, dh3, dh(recipientOpkKey.privateKey, senderEphemeralPub)]
151
- : [dh1, dh2, dh3];
152
- const ikm = Buffer.concat(parts);
153
- const F = Buffer.alloc(32, 0xFF);
154
- const salt = Buffer.alloc(32, 0);
155
- return hkdf(Buffer.concat([F, ikm]), 32, salt, Buffer.from("WhisperText", "utf8"));
156
- }
157
-
158
- module.exports = {
159
- generateKeyPair,
160
- exportRawPublicKey,
161
- importPublicKey,
162
- dh,
163
- hkdf,
164
- hkdfExtract,
165
- hkdfExpand,
166
- encrypt,
167
- decrypt,
168
- hmacSha256,
169
- constantTimeEqual,
170
- x3dhSend,
171
- x3dhReceive,
172
- randomBytes: crypto.randomBytes.bind(crypto)
173
- };