fca-nx 7.0.5 → 7.1.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/module/config.js +0 -1
- package/module/loginHelper.js +46 -24
- package/package.json +2 -2
- package/src/api/socket/core/getSeqID.js +29 -25
- package/src/api/socket/e2ee/index.js +84 -22
- package/src/api/socket/e2ee/protocol.js +32 -9
- package/src/api/socket/e2ee/ratchet.js +29 -1
- package/src/api/socket/e2ee/store.js +140 -42
- package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +140 -18
- package/src/api/socket/listenE2EE.js +14 -1
- package/src/api/users/getUserInfoV2.js +3 -59
package/module/config.js
CHANGED
package/module/loginHelper.js
CHANGED
|
@@ -12,18 +12,6 @@ const { getFrom } = require("../src/utils/constants");
|
|
|
12
12
|
const { loadConfig } = require("./config");
|
|
13
13
|
const { createRemoteClient } = require("../src/remote/remoteClient");
|
|
14
14
|
const { config } = loadConfig();
|
|
15
|
-
|
|
16
|
-
function e2eeEnabled() {
|
|
17
|
-
const on = (v) => v === true || v === "true";
|
|
18
|
-
try {
|
|
19
|
-
const botPath = path.join(process.cwd(), "config.json");
|
|
20
|
-
if (fs.existsSync(botPath)) {
|
|
21
|
-
const bot = JSON.parse(fs.readFileSync(botPath, "utf8"));
|
|
22
|
-
if (bot && Object.prototype.hasOwnProperty.call(bot, "e2ee")) return on(bot.e2ee);
|
|
23
|
-
}
|
|
24
|
-
} catch (_) {}
|
|
25
|
-
return on(config.e2ee);
|
|
26
|
-
}
|
|
27
15
|
const axiosBase = require("axios");
|
|
28
16
|
const regions = [
|
|
29
17
|
{ code: "PRN", name: "Pacific Northwest Region", location: "Khu vực Tây Bắc Thái Bình Dương" },
|
|
@@ -41,6 +29,24 @@ const regions = [
|
|
|
41
29
|
|
|
42
30
|
const REGION_MAP = new Map(regions.map(r => [r.code, r]));
|
|
43
31
|
|
|
32
|
+
// E2EE on/off switch. Reads "e2ee" from the bot's config.json (process.cwd()),
|
|
33
|
+
// then from the fca-nx config. Default is OFF so E2EE only starts when asked for.
|
|
34
|
+
function e2eeEnabled() {
|
|
35
|
+
const on = (v) => v === true || v === "true";
|
|
36
|
+
const off = (v) => v === false || v === "false";
|
|
37
|
+
try {
|
|
38
|
+
const botPath = path.join(process.cwd(), "config.json");
|
|
39
|
+
if (fs.existsSync(botPath)) {
|
|
40
|
+
const bot = JSON.parse(fs.readFileSync(botPath, "utf8"));
|
|
41
|
+
if (bot && Object.prototype.hasOwnProperty.call(bot, "e2ee")) {
|
|
42
|
+
return on(bot.e2ee);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
} catch (_) {}
|
|
46
|
+
if (off(config.e2ee)) return false;
|
|
47
|
+
return on(config.e2ee);
|
|
48
|
+
}
|
|
49
|
+
|
|
44
50
|
function parseRegion(html) {
|
|
45
51
|
try {
|
|
46
52
|
const m1 = html.match(/"endpoint":"([^"]+)"/);
|
|
@@ -1353,34 +1359,50 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1353
1359
|
}, 86400000);
|
|
1354
1360
|
}
|
|
1355
1361
|
// ✅ fca-nx core features register
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
} else {
|
|
1362
|
+
if (!e2eeEnabled()) {
|
|
1363
|
+
logger("E2EE off. Set \"e2ee\": true in config.json to enable it.", "info");
|
|
1364
|
+
} else try {
|
|
1360
1365
|
const e2eeModule = require("../src/api/socket/e2ee");
|
|
1361
1366
|
api.e2ee = new e2eeModule.E2EEBridge(ctxMain, api, defaultFuncs);
|
|
1362
1367
|
ctxMain.e2ee = api.e2ee;
|
|
1363
1368
|
api.connectE2EE = (deviceStorePath) => api.e2ee.connect(deviceStorePath, ctxMain.userID);
|
|
1364
1369
|
api.listenE2EE = require("../src/api/socket/listenE2EE")(defaultFuncs, api, ctxMain);
|
|
1370
|
+
|
|
1371
|
+
// Auto-connect E2EE and make it the default listener so existing
|
|
1372
|
+
// bots calling api.listen() OR api.listenMqtt() directly also
|
|
1373
|
+
// receive E2EE (Secret Conversation) messages without any extra
|
|
1374
|
+
// setup or changes on the bot side.
|
|
1375
|
+
//
|
|
1376
|
+
// [Fixed by xalman] IMPORTANT: assign api.listen/api.listenMqtt to the combined
|
|
1377
|
+
// listener SYNCHRONOUSLY, before connectE2EE() resolves. Bots
|
|
1378
|
+
// commonly call api.listenMqtt(callback) immediately in the login
|
|
1379
|
+
// callback - if we waited for the async connectE2EE() promise to
|
|
1380
|
+
// swap these over, that call would already have captured the old
|
|
1381
|
+
// plain-MQTT-only function, permanently missing E2EE (inbox)
|
|
1382
|
+
// messages even after E2EE finished connecting moments later.
|
|
1365
1383
|
api.listen = api.listenE2EE;
|
|
1366
1384
|
api.listenMqtt = api.listenE2EE;
|
|
1385
|
+
|
|
1386
|
+
// [Fixed by xalman] Retry E2EE auto-connect with backoff instead of
|
|
1387
|
+
// giving up forever after one failed attempt - a transient network
|
|
1388
|
+
// blip or momentary FB rate-limit on device registration used to
|
|
1389
|
+
// leave the bot stuck in group-only mode until a full restart.
|
|
1367
1390
|
const connectE2EEWithRetry = async (attempt = 0) => {
|
|
1368
1391
|
try {
|
|
1369
1392
|
await api.connectE2EE();
|
|
1370
1393
|
logger("E2EE auto-connected and merged into api.listen()/api.listenMqtt()");
|
|
1371
1394
|
} catch (e) {
|
|
1372
1395
|
const msg = e && e.message ? e.message : String(e);
|
|
1373
|
-
if (attempt
|
|
1374
|
-
|
|
1375
|
-
|
|
1396
|
+
if (attempt < 3) {
|
|
1397
|
+
const delayMs = 5000 * Math.pow(3, attempt); // 5s, 15s, 45s
|
|
1398
|
+
logger(`E2EE auto-connect failed (attempt ${attempt + 1}/4): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
|
|
1399
|
+
setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
|
|
1400
|
+
} else {
|
|
1401
|
+
logger(`E2EE auto-connect failed after 4 attempts (non-fatal, continuing without E2EE): ${msg}`, "warn");
|
|
1376
1402
|
}
|
|
1377
|
-
const delayMs = 15000 * (attempt + 1);
|
|
1378
|
-
logger(`E2EE auto-connect failed (attempt ${attempt + 1}): ${msg} - retrying in ${Math.round(delayMs / 1000)}s`, "warn");
|
|
1379
|
-
setTimeout(() => connectE2EEWithRetry(attempt + 1), delayMs);
|
|
1380
1403
|
}
|
|
1381
1404
|
};
|
|
1382
1405
|
connectE2EEWithRetry();
|
|
1383
|
-
}
|
|
1384
1406
|
} catch (e) {
|
|
1385
1407
|
logger(`E2EE init failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
|
|
1386
1408
|
}
|
|
@@ -1416,7 +1438,7 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
|
|
|
1416
1438
|
// used to silently discard it, so only group messages arriving over
|
|
1417
1439
|
// plain MQTT reached bot handlers.
|
|
1418
1440
|
api._listenMqttRaw = stableListenMqtt;
|
|
1419
|
-
if (
|
|
1441
|
+
if (typeof api.listenE2EE === "function") {
|
|
1420
1442
|
api.listenMqtt = api.listen = api.listenE2EE;
|
|
1421
1443
|
} else {
|
|
1422
1444
|
api.listenMqtt = api.listen = stableListenMqtt;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fca-nx",
|
|
3
|
-
"version": "7.0
|
|
4
|
-
"description": "Facebook Messenger API for Node.js Fast, Secure, and Feature-Rich",
|
|
3
|
+
"version": "7.1.0",
|
|
4
|
+
"description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
7
7
|
"exports": {
|
|
@@ -296,39 +296,43 @@ module.exports = function createGetSeqID(deps) {
|
|
|
296
296
|
if (isAuthError) {
|
|
297
297
|
if (retryCount < MAX_RETRIES) {
|
|
298
298
|
const delay = RETRY_DELAY * (retryCount + 1);
|
|
299
|
-
logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms
|
|
299
|
+
logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (error: ${msg})`, "warn");
|
|
300
300
|
await new Promise(resolve => setTimeout(resolve, delay));
|
|
301
|
+
|
|
302
|
+
if (retryCount === 0 && ctx.loggedIn) {
|
|
303
|
+
try {
|
|
304
|
+
logger("getSeqID: refreshing session before retry...", "info");
|
|
305
|
+
const { get } = require("../../../utils/request");
|
|
306
|
+
const { saveCookies } = require("../../../utils/client");
|
|
307
|
+
await get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, ctx).then(saveCookies(ctx.jar));
|
|
308
|
+
} catch (refreshErr) {
|
|
309
|
+
logger(`getSeqID: session refresh failed: ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
301
313
|
return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
|
|
302
314
|
}
|
|
303
315
|
|
|
304
|
-
|
|
305
|
-
|
|
316
|
+
logger("getSeqID: all retries failed, attempting auto re-login...", "warn");
|
|
317
|
+
const config = getConfig();
|
|
318
|
+
const loginResult = await tryAutoLogin(logger, config, ctx, defaultFuncs);
|
|
319
|
+
|
|
320
|
+
if (loginResult) {
|
|
321
|
+
logger("getSeqID: retrying with new session...", "info");
|
|
322
|
+
await new Promise(resolve => setTimeout(resolve, 3000));
|
|
323
|
+
return getSeqID(defaultFuncs, api, ctx, globalCallback, form, 0);
|
|
306
324
|
}
|
|
307
325
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
}
|
|
314
|
-
setTimeout(() => {
|
|
315
|
-
if (ctx._ending) return;
|
|
316
|
-
try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
|
|
317
|
-
}, 120000);
|
|
318
|
-
return;
|
|
326
|
+
if (/blocked/i.test(msg)) {
|
|
327
|
+
return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
|
|
328
|
+
}
|
|
329
|
+
if (/Not logged in/i.test(msg)) {
|
|
330
|
+
return emitAuth(ctx, api, globalCallback, "not_logged_in", msg);
|
|
331
|
+
}
|
|
319
332
|
}
|
|
320
333
|
|
|
321
|
-
logger(`getSeqID error
|
|
322
|
-
|
|
323
|
-
if (typeof globalCallback === "function") {
|
|
324
|
-
globalCallback({ type: "session_recovering", error: msg, timestamp: Date.now() }, null);
|
|
325
|
-
}
|
|
326
|
-
} catch (_) {}
|
|
327
|
-
setTimeout(() => {
|
|
328
|
-
if (ctx._ending) return;
|
|
329
|
-
try { getSeqID(defaultFuncs, api, ctx, globalCallback, null, 0); } catch (_) {}
|
|
330
|
-
}, 120000);
|
|
331
|
-
return;
|
|
334
|
+
logger(`getSeqID error: ${msg}`, "error");
|
|
335
|
+
return emitAuth(ctx, api, globalCallback, "auth_error", msg);
|
|
332
336
|
});
|
|
333
337
|
};
|
|
334
338
|
};
|
|
@@ -73,9 +73,14 @@ 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
|
|
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.
|
|
77
81
|
if (!deviceStorePath) {
|
|
78
|
-
deviceStorePath =
|
|
82
|
+
deviceStorePath = process.env.FCA_NX_E2EE_DEVICE_PATH
|
|
83
|
+
|| path.join(process.cwd(), ".fca-nx", "e2ee_device.json");
|
|
79
84
|
}
|
|
80
85
|
|
|
81
86
|
// Auto-create parent directory — users don't need to create it manually
|
|
@@ -202,36 +207,49 @@ class E2EEBridge {
|
|
|
202
207
|
// Auto-reconnect the Noise WebSocket whenever it drops unexpectedly.
|
|
203
208
|
// `this.connected` stays true through reconnect cycles; it's only set
|
|
204
209
|
// 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.
|
|
205
213
|
const _self = this;
|
|
206
|
-
this.
|
|
214
|
+
this._reconnecting = false;
|
|
215
|
+
this.client.onEvent("disconnected", function _onE2EEDisconnected(data) {
|
|
207
216
|
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;
|
|
208
220
|
logger.warn("E2EE", "Noise WebSocket disconnected — reconnecting in 5s...");
|
|
209
|
-
|
|
210
|
-
|
|
221
|
+
let attempt = 0;
|
|
222
|
+
const tryReconnect = async function () {
|
|
223
|
+
if (!_self.connected) { _self._reconnecting = false; return; }
|
|
224
|
+
attempt++;
|
|
211
225
|
try {
|
|
212
226
|
await _self.client.connectE2EE(_e2eeDevicePath, _e2eeUserId);
|
|
213
|
-
|
|
227
|
+
_self._reconnecting = false;
|
|
228
|
+
logger.success("E2EE", "E2EE WebSocket reconnected" + (attempt > 1 ? " (attempt " + attempt + ")" : "") + ".");
|
|
214
229
|
} catch (err) {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
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
|
-
}
|
|
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);
|
|
228
233
|
}
|
|
229
|
-
}
|
|
234
|
+
};
|
|
235
|
+
setTimeout(tryReconnect, 5000);
|
|
230
236
|
});
|
|
231
237
|
|
|
232
238
|
// Forward incoming E2EE messages to the registered callback.
|
|
239
|
+
this._recentIds = this._recentIds || new Set();
|
|
233
240
|
this.client.onEvent("e2ee_message", (msg) => {
|
|
234
|
-
if (!this._messageCallback)
|
|
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
|
+
}
|
|
235
253
|
|
|
236
254
|
const senderID =
|
|
237
255
|
msg.senderId ||
|
|
@@ -288,7 +306,19 @@ class E2EEBridge {
|
|
|
288
306
|
};
|
|
289
307
|
}
|
|
290
308
|
|
|
291
|
-
|
|
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
|
+
}
|
|
292
322
|
});
|
|
293
323
|
|
|
294
324
|
// Surface connection errors so the bot log shows them.
|
|
@@ -309,6 +339,20 @@ class E2EEBridge {
|
|
|
309
339
|
}
|
|
310
340
|
}
|
|
311
341
|
|
|
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
|
+
|
|
312
356
|
isConnected() {
|
|
313
357
|
return this.connected;
|
|
314
358
|
}
|
|
@@ -329,11 +373,25 @@ class E2EEBridge {
|
|
|
329
373
|
*/
|
|
330
374
|
async sendMessage(threadId, msg, replyToMessageId) {
|
|
331
375
|
this.ensureConnected();
|
|
376
|
+
await this._waitReady();
|
|
377
|
+
await require("../../../utils/sendThrottle").waitTurn(); // human-like pacing
|
|
332
378
|
|
|
333
379
|
const text = typeof msg === "string" ? msg : (msg && msg.body != null ? String(msg.body) : "");
|
|
334
380
|
const attachment = (msg && typeof msg === "object") ? (msg.attachment || null) : null;
|
|
335
381
|
|
|
336
382
|
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
|
+
}
|
|
337
395
|
return this.client.sendMessage({ threadId, text, replyToMessageId });
|
|
338
396
|
}
|
|
339
397
|
|
|
@@ -382,21 +440,25 @@ class E2EEBridge {
|
|
|
382
440
|
|
|
383
441
|
async sendReaction(threadId, messageId, reaction, senderJid) {
|
|
384
442
|
this.ensureConnected();
|
|
443
|
+
await this._waitReady();
|
|
385
444
|
return this.client.sendReaction({ threadId, messageId, reaction, senderJid });
|
|
386
445
|
}
|
|
387
446
|
|
|
388
447
|
async sendTyping(threadId, isTyping) {
|
|
389
448
|
this.ensureConnected();
|
|
449
|
+
await this._waitReady(3000);
|
|
390
450
|
return this.client.sendTyping({ threadId, isTyping: isTyping !== false });
|
|
391
451
|
}
|
|
392
452
|
|
|
393
453
|
async unsendMessage(messageId, threadId) {
|
|
394
454
|
this.ensureConnected();
|
|
455
|
+
await this._waitReady();
|
|
395
456
|
return this.client.unsendMessage({ messageId, threadId });
|
|
396
457
|
}
|
|
397
458
|
|
|
398
459
|
async editMessage(threadId, messageId, newText) {
|
|
399
460
|
this.ensureConnected();
|
|
461
|
+
await this._waitReady();
|
|
400
462
|
return this.client.editMessage({ threadId, messageId, newText });
|
|
401
463
|
}
|
|
402
464
|
|
|
@@ -62,26 +62,49 @@ function encodeFrame(type, senderID, threadID, header, payload) {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
function decodeFrame(buf) {
|
|
65
|
-
if (
|
|
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
|
+
}
|
|
66
72
|
if (buf.length < 8) throw new Error("Frame too short");
|
|
67
73
|
let offset = 0;
|
|
68
74
|
|
|
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
|
+
|
|
69
89
|
const magic = buf.readUInt16BE(offset); offset += 2;
|
|
70
90
|
if (magic !== MAGIC) throw new Error("Invalid frame magic: " + magic.toString(16));
|
|
71
91
|
const version = buf.readUInt8(offset); offset += 1;
|
|
92
|
+
if (version !== VERSION) throw new Error("Unsupported frame version: " + version);
|
|
72
93
|
const type = buf.readUInt8(offset); offset += 1;
|
|
94
|
+
if (!Object.values(TYPE).includes(type)) throw new Error("Invalid frame type: " + type);
|
|
73
95
|
|
|
74
|
-
const sidLen =
|
|
75
|
-
const senderID = buf.
|
|
96
|
+
const sidLen = readLength("sender ID");
|
|
97
|
+
const senderID = buf.subarray(offset, offset + sidLen).toString("utf8"); offset += sidLen;
|
|
76
98
|
|
|
77
|
-
const tidLen =
|
|
78
|
-
const threadID = buf.
|
|
99
|
+
const tidLen = readLength("thread ID");
|
|
100
|
+
const threadID = buf.subarray(offset, offset + tidLen).toString("utf8"); offset += tidLen;
|
|
79
101
|
|
|
80
|
-
const hdrLen =
|
|
81
|
-
const header = buf.
|
|
102
|
+
const hdrLen = readLength("header");
|
|
103
|
+
const header = buf.subarray(offset, offset + hdrLen); offset += hdrLen;
|
|
82
104
|
|
|
83
|
-
const payLen =
|
|
84
|
-
const payload = buf.
|
|
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");
|
|
85
108
|
|
|
86
109
|
return { version, type, senderID, threadID, header, payload };
|
|
87
110
|
}
|
|
@@ -95,6 +95,29 @@ 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) {
|
|
98
121
|
const { dh_pub, pn, n } = this._parseHeader(header);
|
|
99
122
|
const aadFull = aad ? Buffer.concat([aad, header]) : header;
|
|
100
123
|
|
|
@@ -127,6 +150,9 @@ class DoubleRatchetSession {
|
|
|
127
150
|
if (this.Nr + MAX_SKIP < until) throw new Error("Too many skipped messages: " + until);
|
|
128
151
|
if (this.CKr) {
|
|
129
152
|
while (this.Nr < until) {
|
|
153
|
+
if (this.MKSKIPPED.size >= MAX_SKIP) {
|
|
154
|
+
throw new Error("Skipped message key limit exceeded");
|
|
155
|
+
}
|
|
130
156
|
const { ck, mk } = kdfCK(this.CKr);
|
|
131
157
|
this.CKr = ck;
|
|
132
158
|
const key = `${this.DHr.toString("hex")}:${this.Nr}`;
|
|
@@ -165,7 +191,9 @@ class DoubleRatchetSession {
|
|
|
165
191
|
}
|
|
166
192
|
|
|
167
193
|
_parseHeader(header) {
|
|
168
|
-
if (header.length
|
|
194
|
+
if (!Buffer.isBuffer(header) || header.length !== 40) {
|
|
195
|
+
throw new Error("Invalid ratchet header length");
|
|
196
|
+
}
|
|
169
197
|
return {
|
|
170
198
|
dh_pub: header.slice(0, 32),
|
|
171
199
|
pn: header.readUInt32BE(32),
|
|
@@ -2,8 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* E2EE Device/Session Store
|
|
5
|
-
* Persists key material to a JSON file (encrypted with
|
|
5
|
+
* Persists key material to a JSON file (encrypted with an external 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.
|
|
7
11
|
*/
|
|
8
12
|
|
|
9
13
|
const fs = require("fs");
|
|
@@ -11,15 +15,26 @@ const path = require("path");
|
|
|
11
15
|
const crypto = require("crypto");
|
|
12
16
|
|
|
13
17
|
class E2EEStore {
|
|
14
|
-
constructor(storePath, userID) {
|
|
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
|
+
|
|
15
28
|
this.storePath = storePath;
|
|
16
|
-
this.userID = userID;
|
|
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 || "");
|
|
17
33
|
this.data = {
|
|
18
34
|
identityKey: null,
|
|
19
35
|
signedPreKey: null,
|
|
20
36
|
oneTimePreKeys: [],
|
|
21
|
-
sessions: {}
|
|
22
|
-
deviceSecret: null // 32-byte random secret for local encryption
|
|
37
|
+
sessions: {} // threadID -> serialized DoubleRatchetSession
|
|
23
38
|
};
|
|
24
39
|
this._loaded = false;
|
|
25
40
|
}
|
|
@@ -28,36 +43,96 @@ class E2EEStore {
|
|
|
28
43
|
return path.join(this.storePath, `fcanx_e2ee_${this.userID}.json`);
|
|
29
44
|
}
|
|
30
45
|
|
|
31
|
-
|
|
32
|
-
|
|
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");
|
|
33
66
|
}
|
|
34
67
|
|
|
35
68
|
_localEncrypt(data) {
|
|
36
|
-
|
|
37
|
-
const key =
|
|
38
|
-
if (key.length !== 32) return data;
|
|
69
|
+
const salt = crypto.randomBytes(16);
|
|
70
|
+
const key = this._deriveStorageKey(salt);
|
|
39
71
|
const iv = crypto.randomBytes(12);
|
|
40
72
|
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
|
|
73
|
+
cipher.setAAD(this._associatedData());
|
|
41
74
|
const enc = Buffer.concat([cipher.update(Buffer.from(data, "utf8")), cipher.final()]);
|
|
42
75
|
const tag = cipher.getAuthTag();
|
|
43
|
-
return
|
|
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
|
+
};
|
|
44
83
|
}
|
|
45
84
|
|
|
46
|
-
_localDecrypt(
|
|
47
|
-
if (!
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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.");
|
|
60
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");
|
|
118
|
+
}
|
|
119
|
+
|
|
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.");
|
|
130
|
+
}
|
|
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 || {};
|
|
61
136
|
}
|
|
62
137
|
|
|
63
138
|
load() {
|
|
@@ -66,35 +141,50 @@ class E2EEStore {
|
|
|
66
141
|
try {
|
|
67
142
|
const raw = fs.readFileSync(file, "utf8");
|
|
68
143
|
const parsed = JSON.parse(raw);
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
this.
|
|
75
|
-
this.data.sessions = payload.sessions || {};
|
|
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));
|
|
76
150
|
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();
|
|
77
155
|
return true;
|
|
78
|
-
} catch (
|
|
79
|
-
|
|
156
|
+
} catch (error) {
|
|
157
|
+
throw new Error(`Unable to load E2EE store: ${error.message}`);
|
|
80
158
|
}
|
|
81
159
|
}
|
|
82
160
|
|
|
83
161
|
save() {
|
|
84
|
-
|
|
85
|
-
fs.mkdirSync(this.storePath, { recursive: true });
|
|
86
|
-
}
|
|
87
|
-
if (!this.data.deviceSecret) {
|
|
88
|
-
this.data.deviceSecret = crypto.randomBytes(32).toString("base64");
|
|
89
|
-
}
|
|
162
|
+
this._requireEncryptionKey();
|
|
90
163
|
const payload = JSON.stringify({
|
|
91
164
|
identityKey: this.data.identityKey,
|
|
92
165
|
signedPreKey: this.data.signedPreKey,
|
|
93
166
|
oneTimePreKeys: this.data.oneTimePreKeys,
|
|
94
167
|
sessions: this.data.sessions
|
|
95
168
|
});
|
|
96
|
-
const encrypted = this._localEncrypt(payload);
|
|
97
|
-
fs.
|
|
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
|
+
}
|
|
98
188
|
}
|
|
99
189
|
|
|
100
190
|
hasIdentityKey() { return !!this.data.identityKey; }
|
|
@@ -179,4 +269,12 @@ class E2EEStore {
|
|
|
179
269
|
deleteSession(threadID) { delete this.data.sessions[threadID]; }
|
|
180
270
|
}
|
|
181
271
|
|
|
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
|
+
|
|
182
280
|
module.exports = { E2EEStore };
|
|
@@ -5099,6 +5099,30 @@ function decryptMedia(opts) {
|
|
|
5099
5099
|
}
|
|
5100
5100
|
|
|
5101
5101
|
// src/e2ee/signal/signal-manager.ts
|
|
5102
|
+
// ── [Fixed by xalman] Global Signal session lock ───────────────────────────
|
|
5103
|
+
// libsignal's load-session -> encrypt/decrypt -> save-session cycle is NOT atomic
|
|
5104
|
+
// in Node. Incoming frames and outgoing sends ran concurrently, so two operations
|
|
5105
|
+
// on the same session could read the same record and the later save overwrote the
|
|
5106
|
+
// earlier one (lost ratchet state -> "old counter" errors -> dropped messages).
|
|
5107
|
+
// Every operation that touches the Signal stores now runs through this queue.
|
|
5108
|
+
var _iqSeq = 0;
|
|
5109
|
+
function nextIqId(prefix) {
|
|
5110
|
+
// [Fixed by xalman] ids built from Date.now() alone collide when two requests start in the
|
|
5111
|
+
// same millisecond (pendingIQs entry overwritten -> that IQ never resolves -> send fails).
|
|
5112
|
+
_iqSeq = (_iqSeq + 1) % 1e9;
|
|
5113
|
+
return `${prefix}${Date.now()}-${_iqSeq.toString(36)}`;
|
|
5114
|
+
}
|
|
5115
|
+
var _signalLockTail = Promise.resolve();
|
|
5116
|
+
function withSignalLock(fn) {
|
|
5117
|
+
const run = _signalLockTail.then(fn);
|
|
5118
|
+
_signalLockTail = new Promise((resolve) => {
|
|
5119
|
+
const t = setTimeout(resolve, 3e4); // safety: never block the queue forever
|
|
5120
|
+
if (t.unref) t.unref();
|
|
5121
|
+
const done = () => { clearTimeout(t); resolve(); };
|
|
5122
|
+
run.then(done, done);
|
|
5123
|
+
});
|
|
5124
|
+
return run;
|
|
5125
|
+
}
|
|
5102
5126
|
init_cjs_shims();
|
|
5103
5127
|
var import_libsignal_client5 = require("@signalapp/libsignal-client");
|
|
5104
5128
|
var import_node_crypto8 = require("crypto");
|
|
@@ -5344,32 +5368,38 @@ function listSenderKeyDistributionIds(store, senderAddr) {
|
|
|
5344
5368
|
const list = store.listSenderKeyDistributionIds;
|
|
5345
5369
|
return typeof list === "function" ? list.call(store, senderAddr) : [];
|
|
5346
5370
|
}
|
|
5347
|
-
|
|
5371
|
+
function establishSession(...a) { return withSignalLock(() => _establishSession_unlocked(...a)); }
|
|
5372
|
+
async function _establishSession_unlocked(store, recipient, rawBundle) {
|
|
5348
5373
|
const bundle = buildPreKeyBundle(rawBundle);
|
|
5349
5374
|
await (0, import_libsignal_client5.processPreKeyBundle)(bundle, recipient, store, store);
|
|
5350
5375
|
}
|
|
5351
|
-
|
|
5376
|
+
function encryptDM(...a) { return withSignalLock(() => _encryptDM_unlocked(...a)); }
|
|
5377
|
+
async function _encryptDM_unlocked(store, recipient, selfAddress, plaintext) {
|
|
5352
5378
|
const cipherMsg = await (0, import_libsignal_client5.signalEncrypt)(u83(plaintext), recipient, store, store);
|
|
5353
5379
|
const type = cipherMsg.type() === import_libsignal_client5.CiphertextMessageType.Whisper ? "msg" : "pkmsg";
|
|
5354
5380
|
return { type, ciphertext: cipherMsg.serialize() };
|
|
5355
5381
|
}
|
|
5356
|
-
|
|
5382
|
+
function decryptDM(...a) { return withSignalLock(() => _decryptDM_unlocked(...a)); }
|
|
5383
|
+
async function _decryptDM_unlocked(store, sender, ciphertext) {
|
|
5357
5384
|
const msg = import_libsignal_client5.SignalMessage.deserialize(u83(ciphertext));
|
|
5358
5385
|
return Buffer.from(await (0, import_libsignal_client5.signalDecrypt)(msg, sender, store, store));
|
|
5359
5386
|
}
|
|
5360
|
-
|
|
5387
|
+
function decryptDMPreKey(...a) { return withSignalLock(() => _decryptDMPreKey_unlocked(...a)); }
|
|
5388
|
+
async function _decryptDMPreKey_unlocked(store, sender, selfAddress, ciphertext) {
|
|
5361
5389
|
const msg = import_libsignal_client5.PreKeySignalMessage.deserialize(u83(ciphertext));
|
|
5362
5390
|
return Buffer.from(
|
|
5363
5391
|
await (0, import_libsignal_client5.signalDecryptPreKey)(msg, sender, store, store, store, store, store)
|
|
5364
5392
|
);
|
|
5365
5393
|
}
|
|
5366
|
-
|
|
5394
|
+
function createSenderKeyDistributionMessage(...a) { return withSignalLock(() => _createSenderKeyDistributionMessage_unlocked(...a)); }
|
|
5395
|
+
async function _createSenderKeyDistributionMessage_unlocked(store, groupJid, senderJid) {
|
|
5367
5396
|
const distributionId = (0, import_node_crypto8.randomUUID)();
|
|
5368
5397
|
const senderAddr = jidToAddress(senderJid);
|
|
5369
5398
|
const skdm = await import_libsignal_client5.SenderKeyDistributionMessage.create(senderAddr, distributionId, store);
|
|
5370
5399
|
return { skdm, distributionId };
|
|
5371
5400
|
}
|
|
5372
|
-
|
|
5401
|
+
function processSKDM(...a) { return withSignalLock(() => _processSKDM_unlocked(...a)); }
|
|
5402
|
+
async function _processSKDM_unlocked(store, senderJid, skdmBytes, groupJid) {
|
|
5373
5403
|
const senderAddr = jidToAddress(senderJid);
|
|
5374
5404
|
const buf = u83(skdmBytes);
|
|
5375
5405
|
const processAndAlias = async (skdm) => {
|
|
@@ -5397,7 +5427,8 @@ async function processSKDM(store, senderJid, skdmBytes, groupJid) {
|
|
|
5397
5427
|
throw primaryErr;
|
|
5398
5428
|
}
|
|
5399
5429
|
}
|
|
5400
|
-
|
|
5430
|
+
function encryptGroup(...a) { return withSignalLock(() => _encryptGroup_unlocked(...a)); }
|
|
5431
|
+
async function _encryptGroup_unlocked(store, groupJid, senderJid, plaintext, distributionId) {
|
|
5401
5432
|
const activeDistributionId = distributionId ?? (0, import_node_crypto8.randomUUID)();
|
|
5402
5433
|
const senderAddr = jidToAddress(senderJid);
|
|
5403
5434
|
const cipherMsg = await (0, import_libsignal_client5.groupEncrypt)(senderAddr, activeDistributionId, store, u83(plaintext));
|
|
@@ -5422,7 +5453,8 @@ async function encryptGroup(store, groupJid, senderJid, plaintext, distributionI
|
|
|
5422
5453
|
}
|
|
5423
5454
|
return buf;
|
|
5424
5455
|
}
|
|
5425
|
-
|
|
5456
|
+
function decryptGroup(...a) { return withSignalLock(() => _decryptGroup_unlocked(...a)); }
|
|
5457
|
+
async function _decryptGroup_unlocked(store, senderJid, ciphertext, groupJid) {
|
|
5426
5458
|
const senderAddrs = addressCandidatesForJid(senderJid);
|
|
5427
5459
|
const senderAddr = senderAddrs[0];
|
|
5428
5460
|
let buf = u83(ciphertext);
|
|
@@ -6118,10 +6150,33 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6118
6150
|
url;
|
|
6119
6151
|
heartbeatInterval = null;
|
|
6120
6152
|
isConnected = false;
|
|
6153
|
+
lastInboundAt = Date.now();
|
|
6154
|
+
_disconnectedEmitted = false;
|
|
6121
6155
|
constructor(endpoint) {
|
|
6122
6156
|
super();
|
|
6123
6157
|
this.url = endpoint;
|
|
6124
6158
|
}
|
|
6159
|
+
// [Fixed by xalman] emit "disconnected" exactly once per socket (close event, watchdog and
|
|
6160
|
+
// read-loop failure could all fire it -> several parallel reconnects -> duplicate sockets).
|
|
6161
|
+
_emitDisconnectedOnce() {
|
|
6162
|
+
if (this._disconnectedEmitted) return;
|
|
6163
|
+
this._disconnectedEmitted = true;
|
|
6164
|
+
this.emit("disconnected");
|
|
6165
|
+
}
|
|
6166
|
+
// [Fixed by xalman] A half-open TCP connection (NAT/proxy dropped it) never fires "close", so
|
|
6167
|
+
// the bot looked connected but was deaf. Force the socket down so the reconnect logic runs.
|
|
6168
|
+
forceDisconnect(reason) {
|
|
6169
|
+
logger.warn("FacebookE2EESocket", `Forcing E2EE socket down: ${reason}`);
|
|
6170
|
+
this.isConnected = false;
|
|
6171
|
+
this.stopHeartbeat();
|
|
6172
|
+
try {
|
|
6173
|
+
if (this.ws && typeof this.ws.terminate === "function") this.ws.terminate();
|
|
6174
|
+
else this.ws?.close();
|
|
6175
|
+
} catch (_) {
|
|
6176
|
+
}
|
|
6177
|
+
const t = setTimeout(() => this._emitDisconnectedOnce(), 3e3);
|
|
6178
|
+
if (t.unref) t.unref();
|
|
6179
|
+
}
|
|
6125
6180
|
async connect(noisePrivKey, authPayload) {
|
|
6126
6181
|
return new Promise((resolve, reject) => {
|
|
6127
6182
|
try {
|
|
@@ -6163,6 +6218,7 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6163
6218
|
let waitingResolver = null;
|
|
6164
6219
|
let waitingLen = 0;
|
|
6165
6220
|
this.ws.addEventListener("message", (ev) => {
|
|
6221
|
+
this.lastInboundAt = Date.now();
|
|
6166
6222
|
const frame = Buffer.from(ev.data);
|
|
6167
6223
|
streamBuffer.push(frame);
|
|
6168
6224
|
streamLen += frame.length;
|
|
@@ -6209,7 +6265,7 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6209
6265
|
waitingResolver(null);
|
|
6210
6266
|
waitingResolver = null;
|
|
6211
6267
|
}
|
|
6212
|
-
this.
|
|
6268
|
+
this._emitDisconnectedOnce();
|
|
6213
6269
|
});
|
|
6214
6270
|
this.ws.addEventListener("open", async () => {
|
|
6215
6271
|
try {
|
|
@@ -6237,8 +6293,14 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6237
6293
|
}
|
|
6238
6294
|
startHeartbeat() {
|
|
6239
6295
|
this.stopHeartbeat();
|
|
6296
|
+
this.lastInboundAt = Date.now();
|
|
6240
6297
|
this.heartbeatInterval = setInterval(async () => {
|
|
6241
6298
|
try {
|
|
6299
|
+
const idleLimit = Number(process.env.FCA_NX_E2EE_IDLE_TIMEOUT_MS ?? "120000");
|
|
6300
|
+
if (idleLimit > 0 && this.isConnected && Date.now() - this.lastInboundAt > idleLimit) {
|
|
6301
|
+
this.forceDisconnect(`no data received for ${Math.round((Date.now() - this.lastInboundAt) / 1e3)}s`);
|
|
6302
|
+
return;
|
|
6303
|
+
}
|
|
6242
6304
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
6243
6305
|
logger.debug("NoiseSocket", "Sending Noise heartbeat (0,0,0)...");
|
|
6244
6306
|
this.ws.send(Buffer.from([0, 0, 0]));
|
|
@@ -6285,6 +6347,9 @@ var FacebookE2EESocket = class extends import_node_events2.EventEmitter {
|
|
|
6285
6347
|
logger.error("FacebookE2EESocket", "Read loop stopped due to error:", err);
|
|
6286
6348
|
this.isConnected = false;
|
|
6287
6349
|
this.emit("error", err);
|
|
6350
|
+
// [Fixed by xalman] the read loop is dead: without this the websocket stayed open but
|
|
6351
|
+
// nothing was ever read again (silent deaf bot). Drop the socket so it reconnects.
|
|
6352
|
+
this.forceDisconnect("read loop died");
|
|
6288
6353
|
}
|
|
6289
6354
|
}
|
|
6290
6355
|
async sendFrame(data) {
|
|
@@ -6999,6 +7064,15 @@ var E2EEHandler = class {
|
|
|
6999
7064
|
pendingIQs = /* @__PURE__ */ new Map();
|
|
7000
7065
|
retryReceipts = /* @__PURE__ */ new Map();
|
|
7001
7066
|
maxRetryReceiptsPerMessage = 2;
|
|
7067
|
+
seenMessageIds = /* @__PURE__ */ new Set();
|
|
7068
|
+
markSeen(id) {
|
|
7069
|
+
if (!id) return;
|
|
7070
|
+
this.seenMessageIds.add(id);
|
|
7071
|
+
if (this.seenMessageIds.size > 5e3) {
|
|
7072
|
+
const oldest = this.seenMessageIds.values().next().value;
|
|
7073
|
+
this.seenMessageIds.delete(oldest);
|
|
7074
|
+
}
|
|
7075
|
+
}
|
|
7002
7076
|
async handleEncryptedMessage(node, selfUserId, e2eeClient) {
|
|
7003
7077
|
const fromJid = node.attrs.from;
|
|
7004
7078
|
const participantJid = node.attrs.participant || node.attrs.from;
|
|
@@ -7097,7 +7171,11 @@ var E2EEHandler = class {
|
|
|
7097
7171
|
const transport = decodeMessageTransport(decrypted);
|
|
7098
7172
|
logger.debug("E2EEHandler", "Decrypted transport:", JSON.stringify(transport, null, 2));
|
|
7099
7173
|
chatJid = this.chatJidFromTransport(transport, chatJid);
|
|
7100
|
-
this.emitTransportApplication(transport, senderJid, chatJid, node.attrs.id);
|
|
7174
|
+
const emittedApp = this.emitTransportApplication(transport, senderJid, chatJid, node.attrs.id);
|
|
7175
|
+
this.markSeen(node.attrs.id);
|
|
7176
|
+
if (!emittedApp && !transport?.protocol?.ancillary?.skdm) {
|
|
7177
|
+
logger.warn("E2EEHandler", `Decrypted message ${node.attrs.id} from ${senderJid} but it produced no event (unsupported/empty payload)`);
|
|
7178
|
+
}
|
|
7101
7179
|
if (transport?.protocol?.ancillary?.skdm) {
|
|
7102
7180
|
const skdm = transport.protocol.ancillary.skdm;
|
|
7103
7181
|
const gid = skdm.groupID || skdm.groupId || fromJid;
|
|
@@ -7110,6 +7188,19 @@ var E2EEHandler = class {
|
|
|
7110
7188
|
} catch (err) {
|
|
7111
7189
|
const isDuplicate = err.code === 1 || (err.message && err.message.includes("old counter"));
|
|
7112
7190
|
if (isDuplicate) {
|
|
7191
|
+
// [Fixed by xalman] Do not silently drop. A real replay (id already delivered) is
|
|
7192
|
+
// ignored, but a fresh message we have NEVER delivered means our session state is
|
|
7193
|
+
// out of sync -> log it and ask the sender to re-send with fresh keys (retry receipt).
|
|
7194
|
+
const msgId = node.attrs.id;
|
|
7195
|
+
if (this.seenMessageIds.has(msgId)) {
|
|
7196
|
+
logger.debug("E2EEHandler", `Ignoring replayed message ${msgId} from ${senderJid}`);
|
|
7197
|
+
} else {
|
|
7198
|
+
const ageSec = node.attrs.t ? Math.floor(now() / 1e3) - Number(node.attrs.t) : 0;
|
|
7199
|
+
logger.warn("E2EEHandler", `Old-counter error on UNSEEN message ${msgId} from ${senderJid} (age ${ageSec}s): ${err.message}`);
|
|
7200
|
+
if (!node.attrs.t || (ageSec >= -60 && ageSec <= 120)) {
|
|
7201
|
+
await this.maybeSendRetryReceipt(node, senderJid, chatJid, err);
|
|
7202
|
+
}
|
|
7203
|
+
}
|
|
7113
7204
|
this.sendAck(node);
|
|
7114
7205
|
return;
|
|
7115
7206
|
}
|
|
@@ -7340,7 +7431,7 @@ var E2EEHandler = class {
|
|
|
7340
7431
|
}
|
|
7341
7432
|
}
|
|
7342
7433
|
async getMediaUploadConfig() {
|
|
7343
|
-
const id =
|
|
7434
|
+
const id = nextIqId("mc-");
|
|
7344
7435
|
const iq = encodeIQ({ id, to: "s.whatsapp.net", type: "set", xmlns: "w:m" }, [
|
|
7345
7436
|
encodeNode("media_conn", {}, void 0)
|
|
7346
7437
|
]);
|
|
@@ -7390,7 +7481,7 @@ var E2EEHandler = class {
|
|
|
7390
7481
|
};
|
|
7391
7482
|
}
|
|
7392
7483
|
async getServerPreKeyCount() {
|
|
7393
|
-
const id =
|
|
7484
|
+
const id = nextIqId("pkc-");
|
|
7394
7485
|
const iq = encodeIQ({ id, to: "s.whatsapp.net", type: "get", xmlns: "encrypt" }, [
|
|
7395
7486
|
encodeNode("count", {}, void 0)
|
|
7396
7487
|
]);
|
|
@@ -7406,7 +7497,7 @@ var E2EEHandler = class {
|
|
|
7406
7497
|
});
|
|
7407
7498
|
}
|
|
7408
7499
|
async getGroupParticipants(groupJid) {
|
|
7409
|
-
const id =
|
|
7500
|
+
const id = nextIqId("gp-");
|
|
7410
7501
|
const iq = encodeIQ({ id, to: groupJid, type: "get", xmlns: "w:g2" }, [
|
|
7411
7502
|
encodeNode("query", { request: "interactive" }, void 0)
|
|
7412
7503
|
]);
|
|
@@ -7437,7 +7528,7 @@ var E2EEHandler = class {
|
|
|
7437
7528
|
}
|
|
7438
7529
|
async getDeviceList(userJids) {
|
|
7439
7530
|
if (userJids.length === 0) return [];
|
|
7440
|
-
const id =
|
|
7531
|
+
const id = nextIqId("dl-");
|
|
7441
7532
|
const iq = encodeIQ({
|
|
7442
7533
|
id,
|
|
7443
7534
|
to: "s.whatsapp.net",
|
|
@@ -7483,7 +7574,7 @@ var E2EEHandler = class {
|
|
|
7483
7574
|
return deviceJids;
|
|
7484
7575
|
}
|
|
7485
7576
|
async getPreKeyBundle(jid) {
|
|
7486
|
-
const id =
|
|
7577
|
+
const id = nextIqId("pkb-");
|
|
7487
7578
|
const iq = encodeIQ({ id, to: "s.whatsapp.net", type: "get", xmlns: "encrypt" }, [
|
|
7488
7579
|
encodeNode("key", {}, [
|
|
7489
7580
|
encodeNode("user", { jid }, void 0)
|
|
@@ -7596,7 +7687,7 @@ var E2EEHandler = class {
|
|
|
7596
7687
|
async sendCleanIQ(type, timestamp) {
|
|
7597
7688
|
const socket = this.getSocket();
|
|
7598
7689
|
if (!socket) return;
|
|
7599
|
-
const id =
|
|
7690
|
+
const id = nextIqId("clean-");
|
|
7600
7691
|
const cleanIQ = encodeIQ({ id, to: "s.whatsapp.net", type: "set", xmlns: "urn:xmpp:whatsapp:dirty" }, [
|
|
7601
7692
|
encodeNode("clean", { type, timestamp }, void 0)
|
|
7602
7693
|
]);
|
|
@@ -8039,11 +8130,22 @@ var ClientController = class {
|
|
|
8039
8130
|
auth: ""
|
|
8040
8131
|
});
|
|
8041
8132
|
const endpoint = "wss://web-chat-e2ee.facebook.com/ws/chat?cid=client-" + now();
|
|
8133
|
+
// [Fixed by xalman] retire the previous socket so its late close/frames cannot flip the
|
|
8134
|
+
// state of the new connection (e2eeConnected=false, heartbeat stopped, duplicate messages).
|
|
8135
|
+
const previousSocket = this.e2eeSocket;
|
|
8136
|
+
if (previousSocket) {
|
|
8137
|
+
previousSocket._stale = true;
|
|
8138
|
+
try {
|
|
8139
|
+
previousSocket.close();
|
|
8140
|
+
} catch (_) {
|
|
8141
|
+
}
|
|
8142
|
+
}
|
|
8042
8143
|
const noiseSocket = new FacebookE2EESocket(endpoint);
|
|
8043
8144
|
noiseSocket.on("connected", () => {
|
|
8044
8145
|
this.eventMapper.emit({ type: "e2ee_connected", data: {} });
|
|
8045
8146
|
});
|
|
8046
8147
|
noiseSocket.on("disconnected", () => {
|
|
8148
|
+
if (noiseSocket._stale) return;
|
|
8047
8149
|
this.cleanup();
|
|
8048
8150
|
this.eventMapper.emit({ type: "disconnected", data: { isE2EE: true } });
|
|
8049
8151
|
});
|
|
@@ -8068,8 +8170,10 @@ var ClientController = class {
|
|
|
8068
8170
|
deviceId: ds.jidDevice ?? 0,
|
|
8069
8171
|
fbCatBase64: fbCat
|
|
8070
8172
|
});
|
|
8173
|
+
let messageChain = Promise.resolve(); // [Fixed by xalman] keep incoming messages in arrival order
|
|
8071
8174
|
noiseSocket.on("frame", async (rawFrame) => {
|
|
8072
8175
|
if (rawFrame.length === 0) return;
|
|
8176
|
+
if (noiseSocket._stale) return;
|
|
8073
8177
|
try {
|
|
8074
8178
|
const node = unmarshal(rawFrame);
|
|
8075
8179
|
if (["receipt", "notification", "iq", "presence", "call", "chatstate"].includes(node.tag) && node.attrs.id) {
|
|
@@ -8095,11 +8199,19 @@ var ClientController = class {
|
|
|
8095
8199
|
break;
|
|
8096
8200
|
case "message":
|
|
8097
8201
|
case "appdata":
|
|
8098
|
-
|
|
8202
|
+
messageChain = messageChain.then(() => this.e2eeHandler.handleEncryptedMessage(node, userId, client)).catch((err) => {
|
|
8203
|
+
logger.error("E2EE", "Message frame error:", err);
|
|
8204
|
+
});
|
|
8099
8205
|
break;
|
|
8100
8206
|
case "ib":
|
|
8101
8207
|
this.e2eeHandler.handleIB(node);
|
|
8102
8208
|
break;
|
|
8209
|
+
case "ack":
|
|
8210
|
+
// [Fixed by xalman] server-side rejections of our sends were silently ignored.
|
|
8211
|
+
if (node.attrs.error) {
|
|
8212
|
+
logger.warn("E2EE", `Server rejected ${node.attrs.class || "stanza"} id=${node.attrs.id} error=${node.attrs.error}`);
|
|
8213
|
+
}
|
|
8214
|
+
break;
|
|
8103
8215
|
}
|
|
8104
8216
|
} catch (err) {
|
|
8105
8217
|
logger.error("E2EE", "Frame error:", err);
|
|
@@ -8276,7 +8388,17 @@ var ClientController = class {
|
|
|
8276
8388
|
await e2eeClient.establishSession(deviceJid, bundle);
|
|
8277
8389
|
}
|
|
8278
8390
|
const payload = sameMessengerUser(deviceJid, selfJid) ? result.selfDevicePayload : result.devicePayload;
|
|
8279
|
-
|
|
8391
|
+
let encrypted;
|
|
8392
|
+
try {
|
|
8393
|
+
encrypted = await e2eeClient.encryptDevicePayload(deviceJid, selfJid, payload);
|
|
8394
|
+
} catch (firstErr) {
|
|
8395
|
+
// [Fixed by xalman] a stale/broken session used to silently drop that device from the
|
|
8396
|
+
// fanout. Rebuild the session from a fresh prekey bundle and try once more.
|
|
8397
|
+
logger.warn("ClientController", `Encrypt to ${deviceJid} failed (${firstErr && firstErr.message}); rebuilding session and retrying`);
|
|
8398
|
+
const freshBundle = await this.e2eeHandler.getPreKeyBundle(deviceJid);
|
|
8399
|
+
await e2eeClient.establishSession(deviceJid, freshBundle);
|
|
8400
|
+
encrypted = await e2eeClient.encryptDevicePayload(deviceJid, selfJid, payload);
|
|
8401
|
+
}
|
|
8280
8402
|
participantNodes.push(encodeNode("to", { jid: deviceJid }, [
|
|
8281
8403
|
encodeNode("enc", { v: "3", type: encrypted.type }, encrypted.ciphertext)
|
|
8282
8404
|
]));
|
|
@@ -48,7 +48,20 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
48
48
|
if (typeof mqttListener !== "function") {
|
|
49
49
|
throw new Error("listenE2EE: MQTT listener is not available");
|
|
50
50
|
}
|
|
51
|
-
|
|
51
|
+
// [Fixed by xalman] A DM message arriving over plain MQTT means the user is currently in the
|
|
52
|
+
// normal (non-E2EE) chat, so replies must NOT be diverted to the E2EE bridge. An E2EE message
|
|
53
|
+
// flips it back to 'dm' (see e2ee/index.js). Latest activity decides where the reply goes.
|
|
54
|
+
var mqttCallback = function (err, event) {
|
|
55
|
+
try {
|
|
56
|
+
if (!err && event && event.type === "message" && event.isGroup === false && !event.isE2EE &&
|
|
57
|
+
event.threadID && event.senderID !== ctx.userID) {
|
|
58
|
+
ctx.threadTypes = ctx.threadTypes || {};
|
|
59
|
+
ctx.threadTypes[String(event.threadID)] = "mqtt-dm";
|
|
60
|
+
}
|
|
61
|
+
} catch (_) { }
|
|
62
|
+
return globalCallback(err, event);
|
|
63
|
+
};
|
|
64
|
+
var mqttEmitter = mqttListener(mqttCallback);
|
|
52
65
|
api._mqttEmitter = mqttEmitter;
|
|
53
66
|
|
|
54
67
|
// [Fixed by xalman] Hook E2EE incoming messages (FCA-NX native Noise WebSocket).
|
|
@@ -114,38 +114,6 @@ function pickMeta(user) {
|
|
|
114
114
|
return { friendshipStatus, gender, shortName };
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
-
|
|
118
|
-
function findCoverUri(node, depth = 0) {
|
|
119
|
-
if (!node || depth > 12) return null;
|
|
120
|
-
if (typeof node === "string" || typeof node !== "object") return null;
|
|
121
|
-
for (const key of ["cover_photo", "coverPhoto", "profile_cover_photo", "timeline_cover_photo", "cover"]) {
|
|
122
|
-
if (node[key] != null) {
|
|
123
|
-
const direct = extractPhotoUrl(node[key]);
|
|
124
|
-
if (direct) return direct;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
const list = Array.isArray(node) ? node : Object.keys(node).filter(k => k !== "extensions" && k !== "errors").map(k => node[k]);
|
|
128
|
-
for (const child of list) {
|
|
129
|
-
const found = findCoverUri(child, depth + 1);
|
|
130
|
-
if (found) return found;
|
|
131
|
-
}
|
|
132
|
-
return null;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
function coverFromHtml(html) {
|
|
136
|
-
const text = String(html || "");
|
|
137
|
-
const patterns = [
|
|
138
|
-
/"cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
|
|
139
|
-
/"profile_cover_photo"\s*:\s*\{[\s\S]{0,800}?"uri"\s*:\s*"([^"]+)"/,
|
|
140
|
-
/"timeline_cover_photo"\s*:\s*\{[\s\S]{0,400}?"uri"\s*:\s*"([^"]+)"/
|
|
141
|
-
];
|
|
142
|
-
for (const re of patterns) {
|
|
143
|
-
const match = text.match(re);
|
|
144
|
-
if (match && match[1]) return match[1].replace(/\\\//g, "/").replace(/\\u0026/g, "&");
|
|
145
|
-
}
|
|
146
|
-
return null;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
117
|
function extractCoverPhoto(user) {
|
|
150
118
|
const cover = user?.cover_photo;
|
|
151
119
|
if (!cover) return null;
|
|
@@ -266,8 +234,6 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
266
234
|
const parsed = toJSONMaybe(response) || response;
|
|
267
235
|
const root = Array.isArray(parsed) ? parsed[0] : parsed;
|
|
268
236
|
const normalized = normalizeUser(findUser(root));
|
|
269
|
-
const cover = findCoverUri(parsed) || findCoverUri(root);
|
|
270
|
-
if (normalized && cover && !normalized.coverPhoto) normalized.coverPhoto = cover;
|
|
271
237
|
if (!normalized?.id) continue;
|
|
272
238
|
if (!bestUser) {
|
|
273
239
|
bestUser = normalized;
|
|
@@ -286,24 +252,6 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
286
252
|
return bestUser;
|
|
287
253
|
}
|
|
288
254
|
|
|
289
|
-
async function fetchCoverFromProfile(userID) {
|
|
290
|
-
const urls = [
|
|
291
|
-
`https://www.facebook.com/profile.php?id=${userID}`,
|
|
292
|
-
`https://mbasic.facebook.com/profile.php?id=${userID}`
|
|
293
|
-
];
|
|
294
|
-
for (const url of urls) {
|
|
295
|
-
try {
|
|
296
|
-
const response = await defaultFuncs.get(url, ctx.jar);
|
|
297
|
-
const html = typeof response === "string" ? response : (response && (response.body || response.data)) || "";
|
|
298
|
-
const cover = coverFromHtml(html);
|
|
299
|
-
if (cover) return cover;
|
|
300
|
-
} catch (error) {
|
|
301
|
-
logger(`getUserInfoV2 cover page: ${error.message || error}`, "warn");
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
return null;
|
|
305
|
-
}
|
|
306
|
-
|
|
307
255
|
async function fetchLegacy(userIDs) {
|
|
308
256
|
const form = {};
|
|
309
257
|
userIDs.forEach((id, index) => {
|
|
@@ -326,7 +274,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
326
274
|
lastName: nameParts.length > 1? nameParts.slice(1).join(" ") : null,
|
|
327
275
|
vanity: profile.vanity || null,
|
|
328
276
|
thumbSrc: null,
|
|
329
|
-
coverPhoto: extractPhotoUrl(profile.cover_photo
|
|
277
|
+
coverPhoto: extractPhotoUrl(profile.cover_photo),
|
|
330
278
|
profileUrl: profile.uri || `https://www.facebook.com/profile.php?id=${id}`,
|
|
331
279
|
gender: profile.gender === 1? "male" : profile.gender === 2? "female" : "no specific gender",
|
|
332
280
|
type: profile.type || "User",
|
|
@@ -363,7 +311,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
363
311
|
if (!ids.length) {
|
|
364
312
|
const error = new Error("Invalid user ID(s)");
|
|
365
313
|
callback(error);
|
|
366
|
-
|
|
314
|
+
returnPromise;
|
|
367
315
|
}
|
|
368
316
|
(async () => {
|
|
369
317
|
try {
|
|
@@ -373,11 +321,7 @@ module.exports = function (defaultFuncs, api, ctx) {
|
|
|
373
321
|
for (let i = 0; i < ids.length; i++) {
|
|
374
322
|
const id = ids[i];
|
|
375
323
|
if (results[i].status === "fulfilled" && results[i].value?.id) {
|
|
376
|
-
|
|
377
|
-
if (!user.coverPhoto) {
|
|
378
|
-
user.coverPhoto = await fetchCoverFromProfile(id);
|
|
379
|
-
}
|
|
380
|
-
retObj[id] = formatUser(user, id);
|
|
324
|
+
retObj[id] = formatUser(results[i].value, id);
|
|
381
325
|
} else {
|
|
382
326
|
needFallback.push(id);
|
|
383
327
|
}
|