fca-nx 7.1.0 → 7.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "7.1.0",
3
+ "version": "7.2.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",
@@ -2,7 +2,10 @@
2
2
 
3
3
  const log = require("../../../func/logAdapter");
4
4
  const { parseAndCheckLogin } = require("../../utils/client");
5
- const { getType } = require("../../utils/format");
5
+
6
+ // api.getThemePictures(themeID, callback?)
7
+ // themeID = the theme_fbid (digits), e.g. from api.getThreadInfo(tid).threadTheme.id
8
+ // or from an api.createThemeAI() result.
6
9
  module.exports = function (defaultFuncs, api, ctx) {
7
10
  return function getThemePictures(id, callback) {
8
11
  let resolveFunc = function () { };
@@ -12,24 +15,24 @@ module.exports = function (defaultFuncs, api, ctx) {
12
15
  rejectFunc = reject;
13
16
  });
14
17
 
15
- if (!callback) {
16
- if (
17
- getType(callback) == "Function" ||
18
- getType(callback) == "AsyncFunction"
19
- ) {
20
- callback = callback;
21
- } else {
22
- callback = function (err, data) {
23
- if (err) {
24
- return rejectFunc(err);
25
- }
26
- resolveFunc(data);
27
- };
28
- }
18
+ if (typeof callback !== "function") {
19
+ callback = function (err, data) {
20
+ if (err) return rejectFunc(err);
21
+ resolveFunc(data);
22
+ };
29
23
  }
30
24
 
31
- if (getType(id) != "String") {
32
- id = "";
25
+ // [Hardened] Accept numbers/bigint too. Previously any non-string id was silently
26
+ // replaced with "" and Facebook answered messenger_thread_theme: null.
27
+ if (typeof id === "number" || typeof id === "bigint") id = String(id);
28
+ id = typeof id === "string" ? id.trim() : "";
29
+
30
+ if (!/^\d+$/.test(id)) {
31
+ const err = {
32
+ error: "getThemePictures: a numeric theme ID is required (theme_fbid), got: " + JSON.stringify(id)
33
+ };
34
+ callback(err);
35
+ return returnPromise;
33
36
  }
34
37
 
35
38
  const form = {
@@ -37,19 +40,30 @@ module.exports = function (defaultFuncs, api, ctx) {
37
40
  fb_api_req_friendly_name: "MWPThreadThemeProviderQuery",
38
41
  doc_id: "9734829906576883",
39
42
  server_timestamps: true,
40
- variables: JSON.stringify({
41
- id
42
- }),
43
+ variables: JSON.stringify({ id }),
43
44
  av: ctx.userID
44
45
  };
46
+
45
47
  defaultFuncs
46
48
  .post("https://www.facebook.com/api/graphql/", ctx.jar, form)
47
49
  .then(parseAndCheckLogin(ctx, defaultFuncs))
48
50
  .then(function (resData) {
49
- if (resData.errors) {
51
+ if (resData && resData.errors) {
50
52
  throw resData;
51
53
  }
52
54
 
55
+ // [Hardened] Request worked but Facebook has no theme with this ID for this account.
56
+ // Report as failure instead of a false "success" with null theme.
57
+ if (!resData || !resData.data || !resData.data.messenger_thread_theme) {
58
+ const notFound = {
59
+ error: "Theme not found: Facebook returned no theme for ID " + id + ". Check the ID (use the theme_fbid of a real theme).",
60
+ themeID: id,
61
+ raw: resData
62
+ };
63
+ log.error("getThemePictures", notFound.error);
64
+ return callback(notFound);
65
+ }
66
+
53
67
  return callback(null, resData);
54
68
  })
55
69
  .catch(function (err) {
@@ -73,14 +73,9 @@ class E2EEBridge {
73
73
 
74
74
  userId = userId || this.ctx.userID;
75
75
 
76
- // Default to .fca-nx/e2ee_device.json in the user's project directory.
77
- // [Fixed by xalman] On hosts with an ephemeral filesystem (Railway, Heroku...) the
78
- // device file is wiped on every deploy, which registers a brand-new E2EE device each
79
- // time and leaves stale devices behind. Set FCA_NX_E2EE_DEVICE_PATH to a path on a
80
- // persistent volume (e.g. /data/e2ee_device.json) to keep the same device forever.
76
+ // Default to .fca-nx/e2ee_device.json in the user's project directory
81
77
  if (!deviceStorePath) {
82
- deviceStorePath = process.env.FCA_NX_E2EE_DEVICE_PATH
83
- || path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
78
+ deviceStorePath = path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
84
79
  }
85
80
 
86
81
  // Auto-create parent directory — users don't need to create it manually
@@ -207,49 +202,36 @@ class E2EEBridge {
207
202
  // Auto-reconnect the Noise WebSocket whenever it drops unexpectedly.
208
203
  // `this.connected` stays true through reconnect cycles; it's only set
209
204
  // false by an explicit api.e2ee.disconnect() call.
210
- // [Fixed by xalman] Previous version gave up after 2 failed attempts (bot stayed "connected"
211
- // but deaf forever), could start several reconnects in parallel (duplicate sockets ->
212
- // duplicate messages), and reacted to non-E2EE "disconnected" events too.
213
205
  const _self = this;
214
- this._reconnecting = false;
215
- this.client.onEvent("disconnected", function _onE2EEDisconnected(data) {
206
+ this.client.onEvent("disconnected", function _onE2EEDisconnected() {
216
207
  if (!_self.connected) return; // intentional disconnect — skip
217
- if (data && data.isE2EE === false) return; // MQTT/gateway drop, E2EE socket is fine
218
- if (_self._reconnecting) return;
219
- _self._reconnecting = true;
220
208
  logger.warn("E2EE", "Noise WebSocket disconnected — reconnecting in 5s...");
221
- let attempt = 0;
222
- const tryReconnect = async function () {
223
- if (!_self.connected) { _self._reconnecting = false; return; }
224
- attempt++;
209
+ setTimeout(async function () {
210
+ if (!_self.connected) return;
225
211
  try {
226
212
  await _self.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
227
- _self._reconnecting = false;
228
- logger.success("E2EE", "E2EE WebSocket reconnected" + (attempt > 1 ? " (attempt " + attempt + ")" : "") + ".");
213
+ logger.success("E2EE", "E2EE WebSocket reconnected.");
229
214
  } catch (err) {
230
- const delay = Math.min(5000 * Math.pow(2, attempt - 1), 60000);
231
- logger.error("E2EE", "E2EE reconnect failed (attempt " + attempt + "): " + (err && err.message ? err.message : String(err)) + " — retrying in " + Math.round(delay / 1000) + "s");
232
- setTimeout(tryReconnect, delay);
215
+ logger.error("E2EE", "E2EE reconnect failed: " + (err && err.message ? err.message : String(err)));
216
+ // Retry again after another 10s if reconnect failed
217
+ if (_self.connected) {
218
+ setTimeout(async function () {
219
+ if (!_self.connected) return;
220
+ try {
221
+ await _self.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
222
+ logger.success("E2EE", "E2EE WebSocket reconnected (retry).");
223
+ } catch (err2) {
224
+ logger.error("E2EE", "E2EE reconnect retry failed: " + (err2 && err2.message ? err2.message : String(err2)));
225
+ }
226
+ }, 10000);
227
+ }
233
228
  }
234
- };
235
- setTimeout(tryReconnect, 5000);
229
+ }, 5000);
236
230
  });
237
231
 
238
232
  // Forward incoming E2EE messages to the registered callback.
239
- this._recentIds = this._recentIds || new Set();
240
233
  this.client.onEvent("e2ee_message", (msg) => {
241
- if (!this._messageCallback) {
242
- logger.warn("E2EE", "Incoming E2EE message dropped: no listener registered yet");
243
- return;
244
- }
245
-
246
- // [Fixed by xalman] never deliver the same message twice (reconnect replay / overlapping
247
- // sockets) — a duplicate would make the bot answer a command twice.
248
- if (msg && msg.id) {
249
- if (this._recentIds.has(msg.id)) return;
250
- this._recentIds.add(msg.id);
251
- if (this._recentIds.size > 2000) this._recentIds.delete(this._recentIds.values().next().value);
252
- }
234
+ if (!this._messageCallback) return;
253
235
 
254
236
  const senderID =
255
237
  msg.senderId ||
@@ -306,19 +288,7 @@ class E2EEBridge {
306
288
  };
307
289
  }
308
290
 
309
- event.e2eeKind = msg.kind || "text";
310
-
311
- // [Fixed by xalman] The callback runs synchronously inside the vendor's
312
- // decrypt pipeline. If the bot handler threw here, the vendor treated it as a
313
- // decryption failure (retry receipt + dropped message). Isolate it.
314
- try {
315
- const r = this._messageCallback(null, event);
316
- if (r && typeof r.catch === "function") {
317
- r.catch((e) => logger.error("E2EE", "Message callback rejected: " + (e && e.message ? e.message : String(e))));
318
- }
319
- } catch (e) {
320
- logger.error("E2EE", "Message callback threw: " + (e && e.message ? e.message : String(e)));
321
- }
291
+ this._messageCallback(null, event);
322
292
  });
323
293
 
324
294
  // Surface connection errors so the bot log shows them.
@@ -339,20 +309,6 @@ class E2EEBridge {
339
309
  }
340
310
  }
341
311
 
342
- // [Fixed by xalman] `connected` stays true while the Noise socket reconnects, so sends made in
343
- // that window used to fail (or fall back to MQTT, which cannot deliver to E2EE threads).
344
- // Wait (up to timeoutMs) for the live socket instead of failing immediately.
345
- async _waitReady(timeoutMs) {
346
- const ctl = this.client && this.client.controller;
347
- const isReady = () => !ctl || ctl.e2eeConnected !== false;
348
- const deadline = Date.now() + (timeoutMs || 20000);
349
- while (!isReady()) {
350
- if (!this.connected) throw new Error("E2EE disconnected.");
351
- if (Date.now() > deadline) throw new Error("E2EE socket is reconnecting; message not sent (timeout).");
352
- await new Promise((r) => setTimeout(r, 250));
353
- }
354
- }
355
-
356
312
  isConnected() {
357
313
  return this.connected;
358
314
  }
@@ -373,25 +329,11 @@ class E2EEBridge {
373
329
  */
374
330
  async sendMessage(threadId, msg, replyToMessageId) {
375
331
  this.ensureConnected();
376
- await this._waitReady();
377
- await require("../../../utils/sendThrottle").waitTurn(); // human-like pacing
378
332
 
379
333
  const text = typeof msg === "string" ? msg : (msg && msg.body != null ? String(msg.body) : "");
380
334
  const attachment = (msg && typeof msg === "object") ? (msg.attachment || null) : null;
381
335
 
382
336
  if (!attachment) {
383
- // Call the controller's E2EE senders directly: client.sendMessage() silently falls
384
- // back to the regular (MQTT) sender when the socket flag is down, and that sender
385
- // routes back into this bridge -> endless recursion / message never delivered.
386
- const ctl = this.client.controller;
387
- const tid = String(threadId);
388
- if (ctl && typeof ctl.sendE2EEText === "function" && typeof ctl.sendE2EEGroupText === "function") {
389
- const isGroupJid = tid.includes("@g.us") || tid.includes(".g.");
390
- const messageId = isGroupJid
391
- ? await ctl.sendE2EEGroupText(tid, text, replyToMessageId, undefined)
392
- : await ctl.sendE2EEText(tid, text, replyToMessageId, undefined);
393
- return { messageId, timestampMs: Date.now() };
394
- }
395
337
  return this.client.sendMessage({ threadId, text, replyToMessageId });
396
338
  }
397
339
 
@@ -440,25 +382,21 @@ class E2EEBridge {
440
382
 
441
383
  async sendReaction(threadId, messageId, reaction, senderJid) {
442
384
  this.ensureConnected();
443
- await this._waitReady();
444
385
  return this.client.sendReaction({ threadId, messageId, reaction, senderJid });
445
386
  }
446
387
 
447
388
  async sendTyping(threadId, isTyping) {
448
389
  this.ensureConnected();
449
- await this._waitReady(3000);
450
390
  return this.client.sendTyping({ threadId, isTyping: isTyping !== false });
451
391
  }
452
392
 
453
393
  async unsendMessage(messageId, threadId) {
454
394
  this.ensureConnected();
455
- await this._waitReady();
456
395
  return this.client.unsendMessage({ messageId, threadId });
457
396
  }
458
397
 
459
398
  async editMessage(threadId, messageId, newText) {
460
399
  this.ensureConnected();
461
- await this._waitReady();
462
400
  return this.client.editMessage({ threadId, messageId, newText });
463
401
  }
464
402
 
@@ -62,49 +62,26 @@ function encodeFrame(type, senderID, threadID, header, payload) {
62
62
  }
63
63
 
64
64
  function decodeFrame(buf) {
65
- if (Buffer.isBuffer(buf)) {
66
- // Use the caller's buffer directly.
67
- } else if (buf instanceof Uint8Array) {
68
- buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
69
- } else {
70
- throw new TypeError("Frame must be a Buffer or Uint8Array");
71
- }
65
+ if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
72
66
  if (buf.length < 8) throw new Error("Frame too short");
73
67
  let offset = 0;
74
68
 
75
- function requireBytes(length, label) {
76
- if (!Number.isSafeInteger(length) || length < 0 || length > buf.length - offset) {
77
- throw new Error(`Invalid or truncated frame ${label}`);
78
- }
79
- }
80
-
81
- function readLength(label) {
82
- requireBytes(4, `${label} length`);
83
- const length = buf.readUInt32BE(offset);
84
- offset += 4;
85
- requireBytes(length, label);
86
- return length;
87
- }
88
-
89
69
  const magic = buf.readUInt16BE(offset); offset += 2;
90
70
  if (magic !== MAGIC) throw new Error("Invalid frame magic: " + magic.toString(16));
91
71
  const version = buf.readUInt8(offset); offset += 1;
92
- if (version !== VERSION) throw new Error("Unsupported frame version: " + version);
93
72
  const type = buf.readUInt8(offset); offset += 1;
94
- if (!Object.values(TYPE).includes(type)) throw new Error("Invalid frame type: " + type);
95
73
 
96
- const sidLen = readLength("sender ID");
97
- const senderID = buf.subarray(offset, offset + sidLen).toString("utf8"); offset += sidLen;
74
+ const sidLen = buf.readUInt32BE(offset); offset += 4;
75
+ const senderID = buf.slice(offset, offset + sidLen).toString("utf8"); offset += sidLen;
98
76
 
99
- const tidLen = readLength("thread ID");
100
- const threadID = buf.subarray(offset, offset + tidLen).toString("utf8"); offset += tidLen;
77
+ const tidLen = buf.readUInt32BE(offset); offset += 4;
78
+ const threadID = buf.slice(offset, offset + tidLen).toString("utf8"); offset += tidLen;
101
79
 
102
- const hdrLen = readLength("header");
103
- const header = buf.subarray(offset, offset + hdrLen); offset += hdrLen;
80
+ const hdrLen = buf.readUInt32BE(offset); offset += 4;
81
+ const header = buf.slice(offset, offset + hdrLen); offset += hdrLen;
104
82
 
105
- const payLen = readLength("payload");
106
- const payload = buf.subarray(offset, offset + payLen); offset += payLen;
107
- if (offset !== buf.length) throw new Error("Unexpected trailing bytes in frame");
83
+ const payLen = buf.readUInt32BE(offset); offset += 4;
84
+ const payload = buf.slice(offset, offset + payLen);
108
85
 
109
86
  return { version, type, senderID, threadID, header, payload };
110
87
  }
@@ -95,29 +95,6 @@ class DoubleRatchetSession {
95
95
  * @returns {Buffer} decrypted plaintext
96
96
  */
97
97
  decrypt(header, ciphertext, aad) {
98
- const snapshot = {
99
- DHs: this.DHs,
100
- DHr: this.DHr,
101
- RK: this.RK,
102
- CKs: this.CKs,
103
- CKr: this.CKr,
104
- Ns: this.Ns,
105
- Nr: this.Nr,
106
- PN: this.PN,
107
- MKSKIPPED: new Map(this.MKSKIPPED)
108
- };
109
-
110
- try {
111
- return this._decryptAndAdvance(header, ciphertext, aad);
112
- } catch (error) {
113
- // Authentication failure must not consume a skipped key or advance
114
- // the ratchet. A later valid copy of the message can then succeed.
115
- Object.assign(this, snapshot);
116
- throw error;
117
- }
118
- }
119
-
120
- _decryptAndAdvance(header, ciphertext, aad) {
121
98
  const { dh_pub, pn, n } = this._parseHeader(header);
122
99
  const aadFull = aad ? Buffer.concat([aad, header]) : header;
123
100
 
@@ -150,9 +127,6 @@ class DoubleRatchetSession {
150
127
  if (this.Nr + MAX_SKIP < until) throw new Error("Too many skipped messages: " + until);
151
128
  if (this.CKr) {
152
129
  while (this.Nr < until) {
153
- if (this.MKSKIPPED.size >= MAX_SKIP) {
154
- throw new Error("Skipped message key limit exceeded");
155
- }
156
130
  const { ck, mk } = kdfCK(this.CKr);
157
131
  this.CKr = ck;
158
132
  const key = `${this.DHr.toString("hex")}:${this.Nr}`;
@@ -191,9 +165,7 @@ class DoubleRatchetSession {
191
165
  }
192
166
 
193
167
  _parseHeader(header) {
194
- if (!Buffer.isBuffer(header) || header.length !== 40) {
195
- throw new Error("Invalid ratchet header length");
196
- }
168
+ if (header.length < 40) throw new Error("Invalid ratchet header length");
197
169
  return {
198
170
  dh_pub: header.slice(0, 32),
199
171
  pn: header.readUInt32BE(32),
@@ -2,12 +2,8 @@
2
2
 
3
3
  /**
4
4
  * E2EE Device/Session Store
5
- * Persists key material to a JSON file (encrypted with an external secret).
5
+ * Persists key material to a JSON file (encrypted with a device secret).
6
6
  * Each E2EE session (thread) is stored separately.
7
- *
8
- * Set FCA_NX_E2EE_STORE_KEY to a high-entropy secret, or pass
9
- * { encryptionKey } as the third constructor argument. The key is never saved
10
- * beside the encrypted data.
11
7
  */
12
8
 
13
9
  const fs = require("fs");
@@ -15,26 +11,15 @@ const path = require("path");
15
11
  const crypto = require("crypto");
16
12
 
17
13
  class E2EEStore {
18
- constructor(storePath, userID, options = {}) {
19
- if (typeof storePath !== "string" || !storePath.trim()) {
20
- throw new TypeError("E2EE store path must be a non-empty string.");
21
- }
22
- if ((typeof userID !== "string" && typeof userID !== "number") ||
23
- !/^[A-Za-z0-9._-]{1,128}$/.test(String(userID))) {
24
- throw new TypeError("E2EE user ID contains unsupported path characters.");
25
- }
26
- if (!options || typeof options !== "object" || Array.isArray(options)) options = {};
27
-
14
+ constructor(storePath, userID) {
28
15
  this.storePath = storePath;
29
- this.userID = String(userID);
30
- this.encryptionKey = Object.prototype.hasOwnProperty.call(options, "encryptionKey")
31
- ? options.encryptionKey
32
- : (process.env.FCA_NX_E2EE_STORE_KEY || "");
16
+ this.userID = userID;
33
17
  this.data = {
34
18
  identityKey: null,
35
19
  signedPreKey: null,
36
20
  oneTimePreKeys: [],
37
- sessions: {} // threadID -> serialized DoubleRatchetSession
21
+ sessions: {}, // threadID -> serialized DoubleRatchetSession
22
+ deviceSecret: null // 32-byte random secret for local encryption
38
23
  };
39
24
  this._loaded = false;
40
25
  }
@@ -43,96 +28,36 @@ class E2EEStore {
43
28
  return path.join(this.storePath, `fcanx_e2ee_${this.userID}.json`);
44
29
  }
45
30
 
46
- _requireEncryptionKey() {
47
- if (typeof this.encryptionKey !== "string" || this.encryptionKey.length < 32) {
48
- throw new Error(
49
- "E2EE store encryption key is missing or too short. Set FCA_NX_E2EE_STORE_KEY to a secret of at least 32 characters."
50
- );
51
- }
52
- }
53
-
54
- _deriveStorageKey(salt) {
55
- this._requireEncryptionKey();
56
- return crypto.scryptSync(this.encryptionKey, salt, 32, {
57
- N: 16384,
58
- r: 8,
59
- p: 1,
60
- maxmem: 32 * 1024 * 1024
61
- });
62
- }
63
-
64
- _associatedData() {
65
- return Buffer.from(`fca-nx-e2ee-store:v2:${this.userID}`, "utf8");
31
+ _salt() {
32
+ return Buffer.from(this.userID.padEnd(16, "0").slice(0, 16), "utf8");
66
33
  }
67
34
 
68
35
  _localEncrypt(data) {
69
- const salt = crypto.randomBytes(16);
70
- const key = this._deriveStorageKey(salt);
36
+ if (!this.data.deviceSecret) return data;
37
+ const key = Buffer.from(this.data.deviceSecret, "base64");
38
+ if (key.length !== 32) return data;
71
39
  const iv = crypto.randomBytes(12);
72
40
  const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
73
- cipher.setAAD(this._associatedData());
74
41
  const enc = Buffer.concat([cipher.update(Buffer.from(data, "utf8")), cipher.final()]);
75
42
  const tag = cipher.getAuthTag();
76
- return {
77
- version: 2,
78
- salt: salt.toString("base64"),
79
- iv: iv.toString("base64"),
80
- tag: tag.toString("base64"),
81
- payload: enc.toString("base64")
82
- };
83
- }
84
-
85
- _localDecrypt(envelope) {
86
- if (!envelope || envelope.version !== 2) {
87
- throw new Error("Unsupported E2EE store format.");
88
- }
89
- const salt = decodeBase64(envelope.salt, "salt");
90
- const iv = decodeBase64(envelope.iv, "IV");
91
- const tag = decodeBase64(envelope.tag, "authentication tag");
92
- const encrypted = decodeBase64(envelope.payload, "payload");
93
- if (salt.length !== 16 || iv.length !== 12 || tag.length !== 16) {
94
- throw new Error("Invalid E2EE store encryption metadata.");
95
- }
96
-
97
- const key = this._deriveStorageKey(salt);
98
- const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
99
- decipher.setAAD(this._associatedData());
100
- decipher.setAuthTag(tag);
101
- return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");
102
- }
103
-
104
- _decryptLegacy(parsed) {
105
- this._requireEncryptionKey();
106
- const legacyKey = decodeBase64(parsed.deviceSecret, "legacy device secret");
107
- const packed = decodeBase64(parsed.payload, "legacy payload");
108
- if (legacyKey.length !== 32 || packed.length < 28) {
109
- throw new Error("Invalid legacy E2EE store.");
110
- }
111
-
112
- const decipher = crypto.createDecipheriv("aes-256-gcm", legacyKey, packed.subarray(0, 12));
113
- decipher.setAuthTag(packed.subarray(12, 28));
114
- return Buffer.concat([
115
- decipher.update(packed.subarray(28)),
116
- decipher.final()
117
- ]).toString("utf8");
43
+ return Buffer.concat([iv, tag, enc]).toString("base64");
118
44
  }
119
45
 
120
- _applyPayload(payload) {
121
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
122
- throw new Error("Invalid E2EE store payload.");
123
- }
124
- if (payload.oneTimePreKeys !== undefined && !Array.isArray(payload.oneTimePreKeys)) {
125
- throw new Error("Invalid E2EE one-time pre-key list.");
126
- }
127
- if (payload.sessions !== undefined &&
128
- (!payload.sessions || typeof payload.sessions !== "object" || Array.isArray(payload.sessions))) {
129
- throw new Error("Invalid E2EE session map.");
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;
130
60
  }
131
-
132
- this.data.identityKey = payload.identityKey || null;
133
- this.data.signedPreKey = payload.signedPreKey || null;
134
- this.data.oneTimePreKeys = payload.oneTimePreKeys || [];
135
- this.data.sessions = payload.sessions || {};
136
61
  }
137
62
 
138
63
  load() {
@@ -141,50 +66,35 @@ class E2EEStore {
141
66
  try {
142
67
  const raw = fs.readFileSync(file, "utf8");
143
68
  const parsed = JSON.parse(raw);
144
- const isLegacy = parsed && parsed.version === undefined &&
145
- typeof parsed.deviceSecret === "string";
146
- const decrypted = isLegacy
147
- ? this._decryptLegacy(parsed)
148
- : this._localDecrypt(parsed);
149
- this._applyPayload(JSON.parse(decrypted));
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 || {};
150
76
  this._loaded = true;
151
-
152
- // Upgrade legacy files immediately so future writes do not keep the
153
- // old colocated-key format.
154
- if (isLegacy) this.save();
155
77
  return true;
156
- } catch (error) {
157
- throw new Error(`Unable to load E2EE store: ${error.message}`);
78
+ } catch (_) {
79
+ return false;
158
80
  }
159
81
  }
160
82
 
161
83
  save() {
162
- this._requireEncryptionKey();
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
+ }
163
90
  const payload = JSON.stringify({
164
91
  identityKey: this.data.identityKey,
165
92
  signedPreKey: this.data.signedPreKey,
166
93
  oneTimePreKeys: this.data.oneTimePreKeys,
167
94
  sessions: this.data.sessions
168
95
  });
169
- const encrypted = JSON.stringify(this._localEncrypt(payload));
170
- fs.mkdirSync(this.storePath, { recursive: true, mode: 0o700 });
171
-
172
- const file = this._storeFile();
173
- const tempFile = `${file}.${process.pid}.${crypto.randomBytes(8).toString("hex")}.tmp`;
174
- let fd;
175
- try {
176
- fd = fs.openSync(tempFile, "wx", 0o600);
177
- fs.writeFileSync(fd, encrypted, "utf8");
178
- fs.fsyncSync(fd);
179
- fs.closeSync(fd);
180
- fd = undefined;
181
- fs.renameSync(tempFile, file);
182
- } finally {
183
- if (fd !== undefined) fs.closeSync(fd);
184
- try {
185
- if (fs.existsSync(tempFile)) fs.unlinkSync(tempFile);
186
- } catch (_) {}
187
- }
96
+ const encrypted = this._localEncrypt(payload);
97
+ fs.writeFileSync(this._storeFile(), JSON.stringify({ deviceSecret: this.data.deviceSecret, payload: encrypted }, null, 2), "utf8");
188
98
  }
189
99
 
190
100
  hasIdentityKey() { return !!this.data.identityKey; }
@@ -269,12 +179,4 @@ class E2EEStore {
269
179
  deleteSession(threadID) { delete this.data.sessions[threadID]; }
270
180
  }
271
181
 
272
- function decodeBase64(value, label) {
273
- if (typeof value !== "string" ||
274
- !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
275
- throw new Error(`Invalid E2EE store ${label}.`);
276
- }
277
- return Buffer.from(value, "base64");
278
- }
279
-
280
182
  module.exports = { E2EEStore };