hridoy-ultimate 8.0.2 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +68 -40
- package/LICENSE +23 -0
- package/MERGE_REPORT.md +54 -0
- package/README.md +158 -113
- package/THIRD_PARTY_NOTICES.md +36 -0
- package/docs/TEST_RESULTS.md +68 -0
- package/docs/UPSTREAM_API_DOCS.md +2712 -0
- package/func/checkUpdate.js +6 -0
- package/func/logAdapter.js +33 -0
- package/func/logger.js +48 -0
- package/index.d.ts +812 -0
- package/index.js +30 -824
- package/module/config.js +46 -0
- package/module/login.js +136 -0
- package/module/loginHelper.js +1413 -0
- package/module/options.js +55 -0
- package/package.json +75 -22
- package/scripts/run-tests.js +19 -0
- package/scripts/syntax-check.js +22 -0
- package/src/{addExternalModule.js → api/action/addExternalModule.js} +8 -8
- package/src/{changeAvatar.js → api/action/changeAvatar.js} +32 -33
- package/src/{changeBio.js → api/action/changeBio.js} +19 -22
- package/src/api/action/dismissScrapingWarning.js +50 -0
- package/src/api/action/enableAutoSaveAppState.js +73 -0
- package/src/{getCurrentUserID.js → api/action/getCurrentUserID.js} +1 -1
- package/src/api/action/handleFriendRequest.js +57 -0
- package/src/api/action/logout.js +95 -0
- package/src/api/action/refreshFb_dtsg.js +47 -0
- package/src/{setPostReaction.js → api/action/setPostReaction.js} +23 -31
- package/src/{unfriend.js → api/action/unfriend.js} +14 -14
- package/src/api/http/httpGet.js +46 -0
- package/src/api/http/httpPost.js +52 -0
- package/src/api/http/postFormData.js +47 -0
- package/src/api/messaging/addUserToGroup.js +68 -0
- package/src/api/messaging/changeAdminStatus.js +126 -0
- package/src/{changeArchivedStatus.js → api/messaging/changeArchivedStatus.js} +15 -17
- package/src/{changeBlockedStatus.js → api/messaging/changeBlockedStatus.js} +13 -16
- package/src/api/messaging/changeGroupImage.js +91 -0
- package/src/api/messaging/changeNickname.js +70 -0
- package/src/api/messaging/changeThreadColor.js +79 -0
- package/src/api/messaging/changeThreadEmoji.js +111 -0
- package/src/{createNewGroup.js → api/messaging/createNewGroup.js} +24 -26
- package/src/api/messaging/createPoll.js +46 -0
- package/src/api/messaging/createThemeAI.js +98 -0
- package/src/api/messaging/deleteMessage.js +136 -0
- package/src/{deleteThread.js → api/messaging/deleteThread.js} +14 -16
- package/src/api/messaging/editMessage.js +105 -0
- package/src/api/messaging/forwardAttachment.js +57 -0
- package/src/api/messaging/forwardMessage.js +134 -0
- package/src/{getEmojiUrl.js → api/messaging/getEmojiUrl.js} +2 -2
- package/src/{getFriendsList.js → api/messaging/getFriendsList.js} +16 -19
- package/src/{getMessage.js → api/messaging/getMessage.js} +160 -180
- package/src/api/messaging/getThemePictures.js +62 -0
- package/src/api/messaging/handleMessageRequest.js +65 -0
- package/src/api/messaging/markAsDelivered.js +69 -0
- package/src/api/messaging/markAsRead.js +110 -0
- package/src/api/messaging/markAsReadAll.js +56 -0
- package/src/api/messaging/markAsSeen.js +68 -0
- package/src/api/messaging/muteThread.js +50 -0
- package/src/api/messaging/pinMessage.js +115 -0
- package/src/api/messaging/removeUserFromGroup.js +62 -0
- package/src/{resolvePhotoUrl.js → api/messaging/resolvePhotoUrl.js} +11 -15
- package/src/api/messaging/scheduler.js +264 -0
- package/src/{searchForThread.js → api/messaging/searchForThread.js} +12 -12
- package/src/api/messaging/sendBroadcast.js +93 -0
- package/src/api/messaging/sendMessage.js +269 -0
- package/src/api/messaging/sendTypingIndicator.js +90 -0
- package/src/api/messaging/sessionGuard.js +130 -0
- package/src/api/messaging/setMessageReaction.js +114 -0
- package/src/api/messaging/setTitle.js +124 -0
- package/src/api/messaging/shareContact.js +98 -0
- package/src/{threadColors.js → api/messaging/threadColors.js} +2 -5
- package/src/api/messaging/unsendMessage.js +105 -0
- package/src/api/messaging/uploadAttachment.js +493 -0
- package/src/api/socket/OldMessage.js +199 -0
- package/src/api/socket/core/connectMqtt.js +304 -0
- package/src/api/socket/core/emitAuth.js +95 -0
- package/src/api/socket/core/getSeqID.js +331 -0
- package/src/api/socket/core/getTaskResponseData.js +25 -0
- package/src/api/socket/core/lifecycle.js +117 -0
- package/src/api/socket/core/parseDelta.js +387 -0
- package/src/api/socket/detail/buildStream.js +215 -0
- package/src/api/socket/detail/constants.js +28 -0
- package/src/api/socket/e2ee/crypto.js +173 -0
- package/src/api/socket/e2ee/index.js +977 -0
- package/src/api/socket/e2ee/localMediaServer.js +59 -0
- package/src/api/socket/e2ee/mediaDecode.js +155 -0
- package/src/api/socket/e2ee/native/NOTICE.md +29 -0
- package/{lib → src/api/socket/e2ee/native/lib}/index.mjs +109 -66
- package/src/api/socket/e2ee/native/nativeMediaBridge.js +273 -0
- package/src/api/socket/e2ee/proto/ArmadilloApplication.proto +281 -0
- package/src/api/socket/e2ee/proto/ArmadilloICDC.proto +14 -0
- package/src/api/socket/e2ee/proto/ConsumerApplication.proto +232 -0
- package/src/api/socket/e2ee/proto/MessageApplication.proto +82 -0
- package/src/api/socket/e2ee/proto/MessageTransport.proto +77 -0
- package/src/api/socket/e2ee/proto/WACommon.proto +66 -0
- package/src/api/socket/e2ee/proto/WAMediaTransport.proto +176 -0
- package/src/api/socket/e2ee/proto/proto-writer.ts +76 -0
- package/src/api/socket/e2ee/protocol.js +196 -0
- package/src/api/socket/e2ee/ratchet.js +219 -0
- package/src/api/socket/e2ee/store.js +182 -0
- package/src/api/socket/e2ee/vendor/fme/dist/index.cjs +6477 -0
- package/src/api/socket/e2ee/vendor/fme/proto/ArmadilloApplication.proto +281 -0
- package/src/api/socket/e2ee/vendor/fme/proto/ArmadilloICDC.proto +14 -0
- package/src/api/socket/e2ee/vendor/fme/proto/ConsumerApplication.proto +232 -0
- package/src/api/socket/e2ee/vendor/fme/proto/MessageApplication.proto +82 -0
- package/src/api/socket/e2ee/vendor/fme/proto/MessageTransport.proto +77 -0
- package/src/api/socket/e2ee/vendor/fme/proto/WACommon.proto +66 -0
- package/src/api/socket/e2ee/vendor/fme/proto/WAMediaTransport.proto +176 -0
- package/src/api/socket/listenE2EE.js +87 -0
- package/src/api/socket/listenMqtt.js +499 -0
- package/src/api/socket/middleware/index.js +216 -0
- package/src/api/socket/sendMessage.js +331 -0
- package/src/api/socket/sendMessageMqtt.js +69 -0
- package/src/{getThreadHistory.js → api/threads/getThreadHistory.js} +114 -132
- package/src/api/threads/getThreadInfo.js +329 -0
- package/src/api/threads/getThreadList.js +293 -0
- package/src/api/threads/getThreadPictures.js +78 -0
- package/src/{getUserID.js → api/users/getUserID.js} +22 -18
- package/src/api/users/getUserInfo.js +402 -0
- package/src/api/users/getUserInfoV2.js +134 -0
- package/src/app/MessengerBot.js +209 -0
- package/src/app/MessengerContext.js +32 -0
- package/src/app/createFcaClient.js +136 -0
- package/src/app/threadInfoRealtimeSync.js +284 -0
- package/src/core/sendReqMqtt.js +96 -0
- package/src/database/helpers.js +53 -0
- package/src/database/models/index.js +88 -0
- package/src/database/models/thread.js +50 -0
- package/src/database/models/user.js +46 -0
- package/src/database/threadData.js +94 -0
- package/src/database/userData.js +98 -0
- package/src/remote/remoteClient.js +123 -0
- package/src/utils/antiSuspension.js +219 -0
- package/src/utils/broadcast.js +51 -0
- package/src/utils/client.js +10 -0
- package/src/utils/constants.js +23 -0
- package/src/utils/cookies.js +85 -0
- package/src/utils/fingerprint.js +110 -0
- package/src/utils/format/attachment.js +357 -0
- package/src/utils/format/cookie.js +9 -0
- package/src/utils/format/date.js +50 -0
- package/src/utils/format/decode.js +44 -0
- package/src/utils/format/delta.js +195 -0
- package/src/utils/format/ids.js +64 -0
- package/src/utils/format/index.js +64 -0
- package/src/utils/format/message.js +88 -0
- package/src/utils/format/presence.js +132 -0
- package/src/utils/format/readTyp.js +44 -0
- package/src/utils/format/thread.js +42 -0
- package/src/utils/format/utils.js +141 -0
- package/src/utils/headers.js +125 -0
- package/src/utils/humanizer.js +256 -0
- package/src/utils/loginParser/autoLogin.js +125 -0
- package/src/utils/loginParser/extractDtsg.js +44 -0
- package/src/utils/loginParser/helpers.js +43 -0
- package/src/utils/loginParser/index.js +10 -0
- package/src/utils/loginParser/parseAndCheckLogin.js +241 -0
- package/src/utils/loginParser/textUtils.js +28 -0
- package/src/utils/nexca-logger.js +144 -0
- package/src/utils/nexca-utils.js +687 -0
- package/src/utils/request/client.js +26 -0
- package/src/utils/request/config.js +23 -0
- package/src/utils/request/defaults.js +46 -0
- package/src/utils/request/helpers.js +46 -0
- package/src/utils/request/index.js +17 -0
- package/src/utils/request/methods.js +163 -0
- package/src/utils/request/proxy.js +21 -0
- package/src/utils/request/retry.js +77 -0
- package/src/utils/request/sanitize.js +49 -0
- package/src/utils/typingIndicator.js +202 -0
- package/test/helpers/stub-modules.js +122 -0
- package/test/integration/logout.test.js +69 -0
- package/test/integration/mqtt-lifecycle.test.js +195 -0
- package/test/integration/package.test.js +116 -0
- package/test/integration/typing-wiring.test.js +71 -0
- package/test/unit/fingerprint.test.js +19 -0
- package/test/unit/humanizer.test.js +32 -0
- package/test/unit/lifecycle.test.js +92 -0
- package/test/unit/parsers.test.js +43 -0
- package/test/unit/typing.test.js +136 -0
- package/ANALYSIS.md +0 -31
- package/AUDIT_REPORT.md +0 -57
- package/advancedSystem.js +0 -95
- package/checkUpdate.js +0 -47
- package/config.json +0 -51
- package/e2ee.js +0 -738
- package/examples/basic-bot.js +0 -122
- package/examples/e2ee-bot.js +0 -141
- package/fca-config.example.json +0 -73
- package/scripts/check.js +0 -38
- package/src/OldMessage.js +0 -357
- package/src/addUserToGroup.js +0 -117
- package/src/changeAdminStatus.js +0 -105
- package/src/changeAvatarV2.js +0 -86
- package/src/changeAvt.js +0 -85
- package/src/changeBlockedStatusMqtt.js +0 -75
- package/src/changeCover.js +0 -73
- package/src/changeGroupImage.js +0 -137
- package/src/changeName.js +0 -79
- package/src/changeNickname.js +0 -61
- package/src/changeThreadColor.js +0 -67
- package/src/changeThreadEmoji.js +0 -57
- package/src/changeUsername.js +0 -59
- package/src/createCommentPost.js +0 -232
- package/src/createPoll.js +0 -73
- package/src/createPost.js +0 -276
- package/src/deleteMessage.js +0 -58
- package/src/editMessage.js +0 -76
- package/src/editMessageOld.js +0 -62
- package/src/follow.js +0 -74
- package/src/forwardAttachment.js +0 -62
- package/src/friendList.js +0 -104
- package/src/getAccess.js +0 -112
- package/src/getAvatarUser.js +0 -78
- package/src/getBotInitialData.js +0 -42
- package/src/getCtx.js +0 -5
- package/src/getOptions.js +0 -5
- package/src/getRegion.js +0 -7
- package/src/getThreadHistoryDeprecated.js +0 -71
- package/src/getThreadInfo.js +0 -232
- package/src/getThreadInfoDeprecated.js +0 -56
- package/src/getThreadList.js +0 -213
- package/src/getThreadListDeprecated.js +0 -46
- package/src/getThreadPictures.js +0 -59
- package/src/getThreadTheme.js +0 -81
- package/src/getUID.js +0 -119
- package/src/getUserInfo.js +0 -66
- package/src/handleFriendRequest.js +0 -46
- package/src/handleMessageRequest.js +0 -47
- package/src/httpGet.js +0 -49
- package/src/httpPost.js +0 -48
- package/src/httpPostFormData.js +0 -70
- package/src/listenMqtt.js +0 -1081
- package/src/listenNotification.js +0 -85
- package/src/logout.js +0 -18
- package/src/markAsDelivered.js +0 -47
- package/src/markAsRead.js +0 -72
- package/src/markAsReadAll.js +0 -40
- package/src/markAsSeen.js +0 -48
- package/src/metaTheme.js +0 -189
- package/src/muteThread.js +0 -45
- package/src/note.js +0 -228
- package/src/pinMessage.js +0 -54
- package/src/refreshFb_dtsg.js +0 -49
- package/src/removeSuspiciousAccount.js +0 -78
- package/src/removeUserFromGroup.js +0 -81
- package/src/reply.js +0 -442
- package/src/searchFriends.js +0 -140
- package/src/searchStickers.js +0 -53
- package/src/send.js +0 -46
- package/src/sendButtons.js +0 -163
- package/src/sendComment.js +0 -159
- package/src/sendFriendRequest.js +0 -112
- package/src/sendMessage.js +0 -441
- package/src/sendMessageMqtt.js +0 -323
- package/src/sendTypingIndicator.js +0 -68
- package/src/sendTypingIndicatorV2.js +0 -22
- package/src/setActiveStatus.js +0 -92
- package/src/setMessageReaction.js +0 -150
- package/src/setMessageReactionMqtt.js +0 -104
- package/src/setMessageReactionSafe.js +0 -44
- package/src/setProfileGuard.js +0 -44
- package/src/setProfileLock.js +0 -97
- package/src/setStoryReaction.js +0 -133
- package/src/setStorySeen.js +0 -108
- package/src/setThreadTheme.js +0 -102
- package/src/setTitle.js +0 -92
- package/src/shareContact.js +0 -110
- package/src/shareLink.js +0 -59
- package/src/stopListenMqtt.js +0 -60
- package/src/storyManager.js +0 -357
- package/src/suggestFriend.js +0 -132
- package/src/unsendMessage.js +0 -68
- package/src/uploadAttachment.js +0 -115
- package/test/fixes-1_2_4.test.js +0 -118
- package/test/mqtt-stop.test.js +0 -32
- package/test/reaction-mqtt.test.js +0 -57
- package/utils.js +0 -3056
- /package/{build → src/api/socket/e2ee/native/build}/messagix.dll +0 -0
- /package/{build → src/api/socket/e2ee/native/build}/messagix.so +0 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Offline test harness.
|
|
4
|
+
*
|
|
5
|
+
* The sandbox that built this package had NO network, so third-party modules
|
|
6
|
+
* (mqtt, ws, axios, sequelize, ...) could not be installed. These stubs stand in
|
|
7
|
+
* for them at the Module._load boundary ONLY. Anything that passes using these
|
|
8
|
+
* stubs is a MOCKED test: it proves our logic against a fake transport, not
|
|
9
|
+
* that Facebook accepts the traffic. Tests print which stubs they used.
|
|
10
|
+
*
|
|
11
|
+
* If a real copy of a module is installed (npm install), pass
|
|
12
|
+
* HRIDOY_REAL_DEPS=1 to skip stubbing it.
|
|
13
|
+
*/
|
|
14
|
+
const Module = require("module");
|
|
15
|
+
const EventEmitter = require("events");
|
|
16
|
+
const stream = require("stream");
|
|
17
|
+
const util = require("util");
|
|
18
|
+
|
|
19
|
+
const used = new Set();
|
|
20
|
+
|
|
21
|
+
class FakeMqttClient extends EventEmitter {
|
|
22
|
+
constructor(streamBuilder, options) {
|
|
23
|
+
super();
|
|
24
|
+
this.options = options;
|
|
25
|
+
this.connected = false;
|
|
26
|
+
this.ended = false;
|
|
27
|
+
this.subscribed = [];
|
|
28
|
+
this.published = [];
|
|
29
|
+
this.log = []; // ordered "subscribe:<t>" / "publish:<t>" / "suback:<t>" entries
|
|
30
|
+
FakeMqttClient.instances.push(this);
|
|
31
|
+
}
|
|
32
|
+
subscribe(topic, cb) {
|
|
33
|
+
this.subscribed.push(topic);
|
|
34
|
+
this.log.push("subscribe:" + topic);
|
|
35
|
+
// SUBACK arrives asynchronously, like a real broker
|
|
36
|
+
setImmediate(() => { this.log.push("suback:" + topic); if (cb) cb(null, [{ topic, qos: 0 }]); });
|
|
37
|
+
}
|
|
38
|
+
unsubscribe(topic, cb) { setImmediate(() => cb && cb()); }
|
|
39
|
+
publish(topic, payload, opts, cb) {
|
|
40
|
+
this.published.push({ topic, payload });
|
|
41
|
+
this.log.push("publish:" + topic);
|
|
42
|
+
if (typeof opts === "function") opts(); else if (cb) cb();
|
|
43
|
+
}
|
|
44
|
+
end(force, cb) {
|
|
45
|
+
if (typeof force === "function") { cb = force; }
|
|
46
|
+
this.ended = true;
|
|
47
|
+
this.connected = false;
|
|
48
|
+
setImmediate(() => { this.emit("close"); if (cb) cb(); });
|
|
49
|
+
}
|
|
50
|
+
// test helpers
|
|
51
|
+
simulateConnect() { this.connected = true; this.emit("connect"); }
|
|
52
|
+
simulateClose() { this.connected = false; this.emit("close"); }
|
|
53
|
+
}
|
|
54
|
+
FakeMqttClient.instances = [];
|
|
55
|
+
|
|
56
|
+
function chainProxy() {
|
|
57
|
+
const fn = function () { return proxy; };
|
|
58
|
+
const proxy = new Proxy(fn, { get: (t, k) => (k === Symbol.toPrimitive ? () => "" : k === "then" ? undefined : proxy), apply: () => proxy });
|
|
59
|
+
return proxy;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
class FakeCookieJar {
|
|
63
|
+
constructor() { this.store = {}; }
|
|
64
|
+
setCookieSync(c) { const [kv] = String(c).split(";"); const i = kv.indexOf("="); this.store[kv.slice(0, i).trim()] = kv.slice(i + 1); }
|
|
65
|
+
getCookieStringSync() { return Object.entries(this.store).map(([k, v]) => k + "=" + v).join("; "); }
|
|
66
|
+
getCookiesSync() { return Object.entries(this.store).map(([key, value]) => ({ key, value, domain: "facebook.com", path: "/" })); }
|
|
67
|
+
async setCookie(c, u) { return this.setCookieSync(c, u); }
|
|
68
|
+
async getCookieString() { return this.getCookieStringSync(); }
|
|
69
|
+
async getCookies() { return this.getCookiesSync(); }
|
|
70
|
+
toJSON() { return { cookies: this.getCookiesSync() }; }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
class FakeModel { static init() { return this; } static associate() {} static hasMany() {} static belongsTo() {} }
|
|
74
|
+
class FakeSequelize {
|
|
75
|
+
constructor() { this.models = {}; }
|
|
76
|
+
async sync() {} async authenticate() {} async close() {}
|
|
77
|
+
define() { return class extends FakeModel {}; }
|
|
78
|
+
}
|
|
79
|
+
FakeSequelize.Transaction = { ISOLATION_LEVELS: { READ_COMMITTED: "READ COMMITTED" } };
|
|
80
|
+
|
|
81
|
+
function axiosStub() {
|
|
82
|
+
const f = async () => { throw new Error("axios stub: network is not available in tests"); };
|
|
83
|
+
f.create = () => f; f.get = f; f.post = f; f.request = f;
|
|
84
|
+
f.defaults = { headers: { common: {} } }; f.interceptors = { request: { use() {} }, response: { use() {} } };
|
|
85
|
+
return f;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const MOCKS = {
|
|
89
|
+
mqtt: () => ({ Client: FakeMqttClient, connect: () => new FakeMqttClient() }),
|
|
90
|
+
ws: () => class FakeWebSocket extends EventEmitter {},
|
|
91
|
+
"https-proxy-agent": () => class FakeProxyAgent { constructor(u) { this.url = u; } },
|
|
92
|
+
axios: axiosStub,
|
|
93
|
+
"axios-cookiejar-support": () => ({ wrapper: (x) => x }),
|
|
94
|
+
"tough-cookie": () => ({ CookieJar: FakeCookieJar, Cookie: class {} }),
|
|
95
|
+
"form-data": () => class FakeFormData { append() {} getHeaders() { return {}; } },
|
|
96
|
+
bluebird: () => { const P = function (fn) { return new Promise(fn); }; P.promisify = util.promisify; P.all = Promise.all.bind(Promise); P.resolve = Promise.resolve.bind(Promise); P.reject = Promise.reject.bind(Promise); return P; },
|
|
97
|
+
chalk: () => chainProxy(),
|
|
98
|
+
"gradient-string": () => new Proxy(() => (x) => x, { get: (_, k) => (k === "then" ? undefined : (x) => x) }),
|
|
99
|
+
duplexify: () => stream.Duplex,
|
|
100
|
+
sequelize: () => ({ Sequelize: FakeSequelize, Model: FakeModel, DataTypes: new Proxy({}, { get: (_, k) => String(k) }) }),
|
|
101
|
+
request: () => { const r = () => {}; r.defaults = () => r; r.jar = () => new FakeCookieJar(); return r; }
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
function install() {
|
|
105
|
+
if (process.env.HRIDOY_REAL_DEPS === "1") return;
|
|
106
|
+
const origLoad = Module._load;
|
|
107
|
+
Module._load = function (request, parent, isMain) {
|
|
108
|
+
if (Object.prototype.hasOwnProperty.call(MOCKS, request)) {
|
|
109
|
+
used.add(request);
|
|
110
|
+
MOCKS[request].cache = MOCKS[request].cache || MOCKS[request]();
|
|
111
|
+
return MOCKS[request].cache;
|
|
112
|
+
}
|
|
113
|
+
return origLoad.apply(this, arguments);
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Remove all loaded package modules from require.cache so each test gets fresh state. */
|
|
118
|
+
function purge(rootDir) {
|
|
119
|
+
for (const k of Object.keys(require.cache)) if (k.startsWith(rootDir)) delete require.cache[k];
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
module.exports = { install, purge, FakeMqttClient, FakeCookieJar, used, MOCKS };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** MOCKED: real logout.js + real listenMqtt against fake HTTP/MQTT. */
|
|
3
|
+
const test = require("node:test");
|
|
4
|
+
const assert = require("node:assert/strict");
|
|
5
|
+
const path = require("path");
|
|
6
|
+
const os = require("os");
|
|
7
|
+
const fs = require("fs");
|
|
8
|
+
const root = process.env.HRIDOY_TEST_ROOT || path.join(__dirname, "..", "..");
|
|
9
|
+
const stubs = require("../helpers/stub-modules");
|
|
10
|
+
stubs.install();
|
|
11
|
+
process.chdir(fs.mkdtempSync(path.join(os.tmpdir(), "hridoy-logout-")));
|
|
12
|
+
const tick = () => new Promise((r) => setImmediate(r));
|
|
13
|
+
|
|
14
|
+
const MARKUP = '"fb_dtsg" value="DT" "ref" value="RF" "h" value="HH"';
|
|
15
|
+
const menu = { jsmods: { instances: [[0, 0, [[{ value: "logout", markup: { __m: "m1" } }]]]], markup: [["m1", { __html: MARKUP }]] } };
|
|
16
|
+
|
|
17
|
+
function build({ failLogoutPost = false } = {}) {
|
|
18
|
+
stubs.purge(root);
|
|
19
|
+
stubs.FakeMqttClient.instances.length = 0;
|
|
20
|
+
const client = require(path.join(root, "src/utils/client"));
|
|
21
|
+
client.parseAndCheckLogin = () => (res) => res.data; // bypass real HTML/JSON parsing only
|
|
22
|
+
client.saveCookies = () => (res) => res;
|
|
23
|
+
const posts = [];
|
|
24
|
+
const defaultFuncs = {
|
|
25
|
+
get: () => Promise.resolve({ data: "" }),
|
|
26
|
+
post: (url) => {
|
|
27
|
+
posts.push(url);
|
|
28
|
+
if (url.includes("modern_settings_menu")) return Promise.resolve({ data: menu });
|
|
29
|
+
if (failLogoutPost) return Promise.reject(new Error("logout http failed"));
|
|
30
|
+
return Promise.resolve({ headers: { location: "https://www.facebook.com/" } });
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const api = { getCookies: () => "c_user=1", refreshFb_dtsg: () => Promise.resolve() };
|
|
34
|
+
const jar = new stubs.FakeCookieJar();
|
|
35
|
+
const ctx = { userID: "1", clientId: "a", loggedIn: true, firstListen: true, lastSeqId: 1, jar,
|
|
36
|
+
globalOptions: { autoReconnect: true, userAgent: "UA" }, tasks: new Map(), _mqttOpt: {} };
|
|
37
|
+
require(path.join(root, "src/api/socket/listenMqtt.js"))(defaultFuncs, api, ctx, {})(() => {});
|
|
38
|
+
ctx._dtsgRefreshInterval = setInterval(() => {}, 1e6); ctx._dtsgRefreshInterval.unref();
|
|
39
|
+
const logout = require(path.join(root, "src/api/action/logout.js"))(defaultFuncs, api, ctx);
|
|
40
|
+
return { ctx, api, logout, posts, clients: stubs.FakeMqttClient.instances };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
test("[mocked] logout stops MQTT, disconnects E2EE and clears every timer", async () => {
|
|
44
|
+
const s = build();
|
|
45
|
+
s.clients[0].simulateConnect(); await tick(); await tick();
|
|
46
|
+
let e2eeDisconnects = 0;
|
|
47
|
+
s.ctx.e2ee = { disconnect: async () => { e2eeDisconnects++; } };
|
|
48
|
+
await s.logout();
|
|
49
|
+
assert.equal(s.ctx.loggedIn, false);
|
|
50
|
+
assert.equal(s.clients[0].ended, true, "MQTT client ended");
|
|
51
|
+
assert.equal(e2eeDisconnects, 1);
|
|
52
|
+
for (const k of ["_heartbeatInterval", "_sessionKeeperInterval", "_reconnectTimer", "_dtsgRefreshInterval", "_rTimeout", "_autoCycleTimer"]) {
|
|
53
|
+
assert.ok(!s.ctx[k], `${k} cleared`);
|
|
54
|
+
}
|
|
55
|
+
assert.ok(s.posts.some((u) => u.includes("logout.php")));
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("[mocked] logout works when no listener was ever started", async () => {
|
|
59
|
+
const s = build();
|
|
60
|
+
delete s.api.stopListening;
|
|
61
|
+
await s.logout();
|
|
62
|
+
assert.equal(s.ctx.loggedIn, false);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("[mocked] a failed logout request is reported, not swallowed, and the session stays usable", async () => {
|
|
66
|
+
const s = build({ failLogoutPost: true });
|
|
67
|
+
await assert.rejects(s.logout(), /logout http failed/);
|
|
68
|
+
assert.equal(s.ctx.loggedIn, true, "not marked logged out when the server call failed");
|
|
69
|
+
});
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* MOCKED integration tests: real listenMqtt/connectMqtt/emitAuth code driven
|
|
4
|
+
* against a fake mqtt client (test/helpers/stub-modules.js). They prove lifecycle
|
|
5
|
+
* logic, ordering and cleanup. They do NOT prove Facebook accepts the traffic.
|
|
6
|
+
* Set HRIDOY_TEST_ROOT=<other package dir> to run the same file against another tree
|
|
7
|
+
* (used to demonstrate the regressions fail on the original 1.1.9 code).
|
|
8
|
+
*/
|
|
9
|
+
const test = require("node:test");
|
|
10
|
+
const assert = require("node:assert/strict");
|
|
11
|
+
const path = require("path");
|
|
12
|
+
const os = require("os");
|
|
13
|
+
const fs = require("fs");
|
|
14
|
+
const root = process.env.HRIDOY_TEST_ROOT || path.join(__dirname, "..", "..");
|
|
15
|
+
const stubs = require("../helpers/stub-modules");
|
|
16
|
+
stubs.install();
|
|
17
|
+
process.chdir(fs.mkdtempSync(path.join(os.tmpdir(), "hridoy-test-"))); // library creates ./Fca_Database on import
|
|
18
|
+
|
|
19
|
+
const tick = () => new Promise((r) => setImmediate(r));
|
|
20
|
+
const flush = async (n = 6) => { for (let i = 0; i < n; i++) await tick(); };
|
|
21
|
+
|
|
22
|
+
// stopListening uses setTimeout internally; when timers are mocked we must tick them.
|
|
23
|
+
async function stop(s, t) {
|
|
24
|
+
let done = false;
|
|
25
|
+
const p = new Promise((r) => s.emitter.stopListening(() => { done = true; r(); }));
|
|
26
|
+
for (let i = 0; i < 50 && !done; i++) {
|
|
27
|
+
if (t && t.mock && t.mock.timers && t.mock.timers.tick) { try { t.mock.timers.tick(10); } catch (_) { /* timers not mocked */ } }
|
|
28
|
+
await tick();
|
|
29
|
+
}
|
|
30
|
+
await p;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function setup(opts = {}) {
|
|
34
|
+
if (opts.t) opts.t.mock.timers.enable({ apis: ["setTimeout", "setInterval"] }); // BEFORE listen so its timers are mocked
|
|
35
|
+
stubs.purge(root);
|
|
36
|
+
stubs.FakeMqttClient.instances.length = 0;
|
|
37
|
+
const calls = { get: 0, post: 0 };
|
|
38
|
+
const defaultFuncs = {
|
|
39
|
+
get: () => { calls.get++; return Promise.resolve({ data: "" }); },
|
|
40
|
+
post: () => { calls.post++; return Promise.reject(new Error("network down (test)")); }
|
|
41
|
+
};
|
|
42
|
+
const api = { getCookies: () => "c_user=1; xs=abc", refreshFb_dtsg: () => Promise.resolve() };
|
|
43
|
+
const ctx = {
|
|
44
|
+
userID: "100000000000001", clientId: "abcd1234", loggedIn: true, firstListen: true, lastSeqId: 42,
|
|
45
|
+
globalOptions: Object.assign({ autoReconnect: true, emitReady: true, userAgent: "UA" }, opts.globalOptions || {}),
|
|
46
|
+
tasks: new Map(), _mqttOpt: opts.mqtt || {}
|
|
47
|
+
};
|
|
48
|
+
const factory = require(path.join(root, "src/api/socket/listenMqtt.js"));
|
|
49
|
+
const listen = factory(defaultFuncs, api, ctx, opts.mqtt);
|
|
50
|
+
const events = [];
|
|
51
|
+
const emitter = listen((err, msg) => events.push({ err, msg }), opts.listenOptions);
|
|
52
|
+
const clients = stubs.FakeMqttClient.instances;
|
|
53
|
+
return { ctx, api, calls, events, emitter, clients, listen, defaultFuncs };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
test("[mocked] sync queue is published only after every SUBACK", async (t) => {
|
|
57
|
+
const s = setup();
|
|
58
|
+
assert.equal(s.clients.length, 1);
|
|
59
|
+
const c = s.clients[0];
|
|
60
|
+
c.simulateConnect();
|
|
61
|
+
assert.equal(c.published.filter((p) => p.topic.startsWith("/messenger_sync")).length, 0, "must not publish before SUBACK");
|
|
62
|
+
await flush();
|
|
63
|
+
const log = c.log;
|
|
64
|
+
const firstPublish = log.findIndex((e) => e.startsWith("publish:/messenger_sync"));
|
|
65
|
+
const lastSuback = log.map((e, i) => (e.startsWith("suback:") ? i : -1)).filter((i) => i >= 0).pop();
|
|
66
|
+
assert.ok(firstPublish > -1, "sync publish happened");
|
|
67
|
+
assert.ok(lastSuback < firstPublish, `SUBACKs (${lastSuback}) must precede first publish (${firstPublish}): ${log.join(",")}`);
|
|
68
|
+
await stop(s, t);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test("[mocked] reconnect after socket close uses backoff, then recovers", async (t) => {
|
|
72
|
+
const s = setup({ mqtt: { reconnectDelayMs: 1000, reconnectJitter: 0, maxReconnectAttempts: 5 } });
|
|
73
|
+
s.clients[0].simulateConnect(); await flush();
|
|
74
|
+
t.mock.timers.enable({ apis: ["setTimeout"] });
|
|
75
|
+
s.clients[0].simulateClose();
|
|
76
|
+
assert.ok(s.ctx._reconnectTimer, "reconnect timer armed");
|
|
77
|
+
t.mock.timers.tick(999); assert.equal(s.clients.length, 1, "not before the delay");
|
|
78
|
+
t.mock.timers.tick(1); assert.equal(s.clients.length, 2, "reconnected after 1000ms");
|
|
79
|
+
// second failure waits twice as long
|
|
80
|
+
s.clients[1].simulateConnect(); await flush();
|
|
81
|
+
s.clients[1].simulateClose();
|
|
82
|
+
t.mock.timers.tick(1999); assert.equal(s.clients.length, 2);
|
|
83
|
+
t.mock.timers.tick(1); assert.equal(s.clients.length, 3, "second attempt after 2000ms (backoff doubled)");
|
|
84
|
+
t.mock.timers.reset();
|
|
85
|
+
await stop(s, t);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("[mocked] stopListening during a cycle must not be revived by a pending retry (race regression)", async (t) => {
|
|
89
|
+
// Original 1.1.9: after stopListening() completed, endQuietly reset _ending=false and the untracked
|
|
90
|
+
// reconnect/getSeqID retry timers kept firing (observed: 30 getSeqID calls + a session refresh in 60s).
|
|
91
|
+
const s = setup({ t, mqtt: { cycleMs: 1000, reconnectDelayMs: 2000, reconnectJitter: 0 } });
|
|
92
|
+
s.clients[0].simulateConnect(); await flush();
|
|
93
|
+
t.mock.timers.tick(1000); // auto-cycle fires -> forceCycle
|
|
94
|
+
for (let i = 0; i < 8; i++) { await tick(); t.mock.timers.tick(5); }
|
|
95
|
+
assert.equal(s.clients[0].ended, true, "precondition: the cycle really started");
|
|
96
|
+
await stop(s, t); // user stops inside the reconnect window
|
|
97
|
+
const before = { get: s.calls.get, post: s.calls.post, n: s.clients.length };
|
|
98
|
+
for (let i = 0; i < 30; i++) { t.mock.timers.tick(2000); await tick(); await tick(); }
|
|
99
|
+
assert.equal(s.calls.get, before.get, "no session refresh after stop");
|
|
100
|
+
assert.equal(s.calls.post, before.post, "no getSeqID retries after stop");
|
|
101
|
+
assert.equal(s.clients.length, before.n, "no new MQTT client after stop");
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("[mocked] stopListening clears timers, ends the client and is safe to call twice", async (t) => {
|
|
105
|
+
const s = setup();
|
|
106
|
+
s.clients[0].simulateConnect(); await flush();
|
|
107
|
+
await stop(s, t);
|
|
108
|
+
assert.equal(s.clients[0].ended, true);
|
|
109
|
+
assert.equal(s.ctx.mqttClient, undefined);
|
|
110
|
+
for (const k of ["_heartbeatInterval", "_sessionKeeperInterval", "_reconnectTimer", "_rTimeout", "_autoCycleTimer"]) {
|
|
111
|
+
assert.ok(!s.ctx[k], `${k} cleared`);
|
|
112
|
+
}
|
|
113
|
+
await stop(s, t); // second call: must complete, not hang/throw
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test("[mocked] late socket 'error' after stopListening does not throw", async (t) => {
|
|
117
|
+
const s = setup();
|
|
118
|
+
s.clients[0].simulateConnect(); await flush();
|
|
119
|
+
await stop(s, t);
|
|
120
|
+
assert.doesNotThrow(() => s.clients[0].emit("error", new Error("late ECONNRESET")));
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("[mocked] calling listen twice replaces the old client (no duplicate connection)", async (t) => {
|
|
124
|
+
const s = setup();
|
|
125
|
+
s.clients[0].simulateConnect(); await flush();
|
|
126
|
+
const second = s.listen(() => {});
|
|
127
|
+
assert.equal(s.clients.length, 2);
|
|
128
|
+
assert.equal(s.clients[0].ended, true, "old client ended");
|
|
129
|
+
assert.equal(s.ctx.mqttClient, s.clients[1]);
|
|
130
|
+
// events from the stale client are inert
|
|
131
|
+
const timersBefore = s.ctx._reconnectTimer;
|
|
132
|
+
s.clients[0].simulateClose();
|
|
133
|
+
assert.equal(s.ctx._reconnectTimer, timersBefore, "stale close must not schedule a reconnect");
|
|
134
|
+
await stop({ emitter: second }, t);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test("[mocked] gives up after maxReconnectAttempts and reports stop_listen (no infinite loop)", async (t) => {
|
|
138
|
+
const s = setup({ mqtt: { reconnectDelayMs: 10, reconnectJitter: 0, maxReconnectAttempts: 2 } });
|
|
139
|
+
t.mock.timers.enable({ apis: ["setTimeout"] });
|
|
140
|
+
s.clients[0].simulateClose(); t.mock.timers.tick(10); // attempt 1
|
|
141
|
+
assert.equal(s.clients.length, 2);
|
|
142
|
+
s.clients[1].simulateClose(); t.mock.timers.tick(20); // attempt 2
|
|
143
|
+
assert.equal(s.clients.length, 3);
|
|
144
|
+
s.clients[2].simulateClose(); // budget exhausted
|
|
145
|
+
t.mock.timers.tick(100000);
|
|
146
|
+
assert.equal(s.clients.length, 3, "no further reconnects");
|
|
147
|
+
const stop = s.events.find((e) => e.err && e.err.type === "stop_listen");
|
|
148
|
+
assert.ok(stop, "stop_listen surfaced to the caller: " + JSON.stringify(s.events.map((e) => e.err && e.err.type)));
|
|
149
|
+
t.mock.timers.reset();
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test("[mocked] a healthy first sync resets the backoff counter", async (t) => {
|
|
153
|
+
const s = setup({ globalOptions: { emitReady: true } });
|
|
154
|
+
const c = s.clients[0];
|
|
155
|
+
s.ctx._reconnectAttempt = 4;
|
|
156
|
+
c.simulateConnect(); await flush();
|
|
157
|
+
assert.equal(typeof s.ctx.tmsWait, "function");
|
|
158
|
+
c.emit("message", "/t_ms", Buffer.from(JSON.stringify({ firstDeltaSeqId: 1, syncToken: "tok", deltas: [] })));
|
|
159
|
+
assert.equal(s.ctx._reconnectAttempt, 0);
|
|
160
|
+
assert.ok(s.events.some((e) => e.err && e.err.type === "ready"), "ready event emitted: " + JSON.stringify(s.events));
|
|
161
|
+
await stop(s, t);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test("[mocked] humanizer middleware is NOT installed by default, and is when opted in", async (t) => {
|
|
165
|
+
let s = setup();
|
|
166
|
+
assert.equal(s.api.listMiddleware().length, 0, "default: no hidden middleware");
|
|
167
|
+
await stop(s, t);
|
|
168
|
+
s = setup({ globalOptions: { humanize: true } });
|
|
169
|
+
assert.ok(JSON.stringify(s.api.listMiddleware()).includes("humanizer"), "opt-in installs it");
|
|
170
|
+
await stop(s, t);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("[mocked] emitAuth stops everything and reports account_inactive", async (t) => {
|
|
174
|
+
const s = setup();
|
|
175
|
+
s.clients[0].simulateConnect(); await flush();
|
|
176
|
+
const createEmitAuth = require(path.join(root, "src/api/socket/core/emitAuth"));
|
|
177
|
+
const seen = [];
|
|
178
|
+
createEmitAuth({ logger: () => {} })(s.ctx, s.api, (e) => seen.push(e), "not_logged_in", "test");
|
|
179
|
+
assert.equal(seen[0].type, "account_inactive");
|
|
180
|
+
assert.equal(s.ctx.loggedIn, false);
|
|
181
|
+
assert.equal(s.ctx.mqttClient, undefined);
|
|
182
|
+
assert.ok(!s.ctx._heartbeatInterval && !s.ctx._sessionKeeperInterval && !s.ctx._reconnectTimer);
|
|
183
|
+
assert.doesNotThrow(() => s.clients[0].emit("error", new Error("late")));
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
test("[mocked] listen(callback, options) applies reconnect options per call", async (t) => {
|
|
187
|
+
const s = setup({ t, listenOptions: { reconnectDelayMs: 50, reconnectJitter: 0, maxReconnectAttempts: 1 } });
|
|
188
|
+
assert.equal(s.ctx._mqttOpt.maxReconnectAttempts, 1);
|
|
189
|
+
assert.equal(s.ctx._mqttOpt.reconnectDelayMs, 50);
|
|
190
|
+
s.clients[0].simulateClose(); t.mock.timers.tick(50);
|
|
191
|
+
assert.equal(s.clients.length, 2);
|
|
192
|
+
s.clients[1].simulateClose(); t.mock.timers.tick(100000);
|
|
193
|
+
assert.equal(s.clients.length, 2, "budget of 1 attempt honoured");
|
|
194
|
+
assert.ok(s.events.some((e) => e.err && e.err.type === "stop_listen"));
|
|
195
|
+
});
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** Package-surface tests. Third-party modules are stubbed (see stub-modules.js) so these are MOCKED loads. */
|
|
3
|
+
const test = require("node:test");
|
|
4
|
+
const assert = require("node:assert/strict");
|
|
5
|
+
const path = require("path");
|
|
6
|
+
const os = require("os");
|
|
7
|
+
const fs = require("fs");
|
|
8
|
+
const { builtinModules } = require("module");
|
|
9
|
+
const { spawnSync } = require("child_process");
|
|
10
|
+
const root = path.join(__dirname, "..", "..");
|
|
11
|
+
const pkg = require(path.join(root, "package.json"));
|
|
12
|
+
|
|
13
|
+
function walk(dir, out = []) {
|
|
14
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
15
|
+
if (["node_modules", "Fca_Database", "test", ".git"].includes(e.name)) continue;
|
|
16
|
+
const p = path.join(dir, e.name);
|
|
17
|
+
e.isDirectory() ? walk(p, out) : out.push(p);
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
test("package metadata: name, version, owner, entry points exist", () => {
|
|
23
|
+
assert.equal(pkg.name, "hridoy-ultimate");
|
|
24
|
+
assert.equal(pkg.version, "9.0.0");
|
|
25
|
+
assert.equal(pkg.author.name, "HR ID OY");
|
|
26
|
+
assert.ok(pkg.maintainers.some((m) => m.name === "HR ID OY"));
|
|
27
|
+
assert.ok(fs.existsSync(path.join(root, pkg.main)));
|
|
28
|
+
assert.ok(fs.existsSync(path.join(root, pkg.types)));
|
|
29
|
+
assert.ok(!Object.values(pkg.dependencies).some((v) => /^(git|github)/.test(v)), "no git dependencies in hard deps");
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("regression: every third-party module the source requires is declared", () => {
|
|
33
|
+
// 1.1.9 required request/tough-cookie/form-data/undici without declaring them.
|
|
34
|
+
const declared = new Set([...Object.keys(pkg.dependencies), ...Object.keys(pkg.optionalDependencies || {})]);
|
|
35
|
+
const builtins = new Set(builtinModules.flatMap((m) => [m, "node:" + m]));
|
|
36
|
+
const re = /require\(\s*["']([^"'./][^"']*)["']\s*\)|^\s*(?:import|export)[^;\n]*?\sfrom\s+["']([^"'./][^"']*)["']|\bimport\(\s*["']([^"'./][^"']*)["']\s*\)/gm;
|
|
37
|
+
const missing = new Map();
|
|
38
|
+
for (const f of walk(root).filter((p) => /\.(js|cjs|mjs)$/.test(p))) {
|
|
39
|
+
if (f.includes(`${path.sep}vendor${path.sep}`)) continue; // bundled third-party build, checked separately below
|
|
40
|
+
const src = fs.readFileSync(f, "utf8");
|
|
41
|
+
for (const m of src.matchAll(re)) {
|
|
42
|
+
let name = m[1] || m[2] || m[3];
|
|
43
|
+
if (builtins.has(name)) continue;
|
|
44
|
+
name = name.startsWith("@") ? name.split("/").slice(0, 2).join("/") : name.split("/")[0];
|
|
45
|
+
if (builtins.has(name) || declared.has(name)) continue;
|
|
46
|
+
missing.set(name, path.relative(root, f));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
assert.deepEqual([...missing], [], "undeclared modules: " + JSON.stringify([...missing]));
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("vendored E2EE bundle: its external requires are declared too", () => {
|
|
53
|
+
const f = path.join(root, "src/api/socket/e2ee/vendor/fme/dist/index.cjs");
|
|
54
|
+
const declared = new Set([...Object.keys(pkg.dependencies), ...Object.keys(pkg.optionalDependencies || {})]);
|
|
55
|
+
const names = new Set([...fs.readFileSync(f, "utf8").matchAll(/require\("([^".][^"]*)"\)/g)].map((m) => m[1]).filter((n) => !n.startsWith("node:") && !builtinModules.includes(n)));
|
|
56
|
+
for (const n of names) assert.ok(declared.has(n), `${n} used by vendor bundle but undeclared`);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("only the pinned messagix binaries ship, native stays opt-in, no default third-party credential host", () => {
|
|
60
|
+
const crypto = require("crypto");
|
|
61
|
+
const files = walk(root);
|
|
62
|
+
const bin = files.filter((p) => /\.(so|dll|dylib|node|exe)$/.test(p)).map((p) => path.relative(root, p).split(path.sep).join("/")).sort();
|
|
63
|
+
assert.deepEqual(bin, [
|
|
64
|
+
"src/api/socket/e2ee/native/build/messagix.dll",
|
|
65
|
+
"src/api/socket/e2ee/native/build/messagix.so"
|
|
66
|
+
]);
|
|
67
|
+
const sha = (f) => crypto.createHash("sha256").update(fs.readFileSync(path.join(root, f))).digest("hex");
|
|
68
|
+
assert.equal(sha(bin[1]), "6249f50cc23de0b11a710266a2323c306d44cf46530880e58e0cd1cf4b5bf8d9");
|
|
69
|
+
assert.equal(sha(bin[0]), "f8597ba86c90c39cec19b660e75eba59f2022678eb20866b740cfa321036885e");
|
|
70
|
+
const e2ee = fs.readFileSync(path.join(root, "src/api/socket/e2ee/index.js"), "utf8");
|
|
71
|
+
assert.match(e2ee, /process\.env\.FCA_E2EE_NATIVE === "1" && _nativeLibAvailable\(\)/, "native engine must stay opt-in");
|
|
72
|
+
const hits = files.filter((p) => /\.(js|cjs|mjs|json)$/.test(p) && fs.readFileSync(p, "utf8").includes("minhdong.site"));
|
|
73
|
+
assert.deepEqual(hits.map((p) => path.relative(root, p)), []);
|
|
74
|
+
const cfg = fs.readFileSync(path.join(root, "module/config.js"), "utf8");
|
|
75
|
+
assert.match(cfg, /apiServer:\s*""/);
|
|
76
|
+
assert.match(cfg, /autoUpdate:\s*false/);
|
|
77
|
+
assert.match(cfg, /autoLogin:\s*false/);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("every JS file in the package parses", () => {
|
|
81
|
+
const r = spawnSync(process.execPath, [path.join(root, "scripts/syntax-check.js")], { encoding: "utf8" });
|
|
82
|
+
assert.equal(r.status, 0, r.stdout + r.stderr);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("[mocked] package loads with consistent exports", () => {
|
|
86
|
+
const stubs = require("../helpers/stub-modules");
|
|
87
|
+
stubs.install();
|
|
88
|
+
process.chdir(fs.mkdtempSync(path.join(os.tmpdir(), "hridoy-pkg-")));
|
|
89
|
+
const m = require(root);
|
|
90
|
+
assert.equal(typeof m.login, "function");
|
|
91
|
+
assert.equal(m.default, m.login);
|
|
92
|
+
const expected = ["login", "default", "createFcaClient", "MessengerBot", "createMessengerBot", "MessengerContext",
|
|
93
|
+
"attachThreadInfoRealtimeSync", "applyThreadInfoRealtimeEvent", "CommandHumanizer", "createCommandHumanizer",
|
|
94
|
+
"createHumanizerMiddleware", "humanizer", "TypingIndicator", "createTypingIndicator", "typingIndicator"];
|
|
95
|
+
assert.deepEqual(Object.keys(m).sort(), expected.sort(), "export surface changed: update README + this list");
|
|
96
|
+
for (const k of expected) assert.notEqual(m[k], undefined, `${k} is undefined`);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("[mocked] login with empty options reports an error via callback and never throws", async () => {
|
|
100
|
+
const stubs = require("../helpers/stub-modules");
|
|
101
|
+
stubs.install();
|
|
102
|
+
process.chdir(fs.mkdtempSync(path.join(os.tmpdir(), "hridoy-login-")));
|
|
103
|
+
const m = require(root);
|
|
104
|
+
const rejections = [];
|
|
105
|
+
const onRej = (e) => rejections.push(e);
|
|
106
|
+
process.on("unhandledRejection", onRej);
|
|
107
|
+
const result = await new Promise((resolve) => {
|
|
108
|
+
const t = setTimeout(() => resolve({ timeout: true }), 5000);
|
|
109
|
+
m.login({}, {}, (err, api) => { clearTimeout(t); resolve({ err, api }); });
|
|
110
|
+
});
|
|
111
|
+
process.removeListener("unhandledRejection", onRej);
|
|
112
|
+
assert.ok(!result.timeout, "callback was invoked");
|
|
113
|
+
assert.ok(result.err, "error delivered");
|
|
114
|
+
assert.equal(result.api, undefined);
|
|
115
|
+
assert.deepEqual(rejections, []);
|
|
116
|
+
});
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* MOCKED integration: the typing indicator is wired into the real listenMqtt factory through the
|
|
4
|
+
* shared ctx._middleware (also used by listenE2EE) and is torn down by stopListening().
|
|
5
|
+
*/
|
|
6
|
+
const test = require("node:test");
|
|
7
|
+
const assert = require("node:assert/strict");
|
|
8
|
+
const path = require("path");
|
|
9
|
+
const os = require("os");
|
|
10
|
+
const fs = require("fs");
|
|
11
|
+
const root = process.env.HRIDOY_TEST_ROOT || path.join(__dirname, "..", "..");
|
|
12
|
+
const stubs = require("../helpers/stub-modules");
|
|
13
|
+
stubs.install();
|
|
14
|
+
process.chdir(fs.mkdtempSync(path.join(os.tmpdir(), "hridoy-typing-")));
|
|
15
|
+
|
|
16
|
+
function build({ withTyping = true, globalOptions = {} } = {}) {
|
|
17
|
+
stubs.purge(root);
|
|
18
|
+
stubs.FakeMqttClient.instances.length = 0;
|
|
19
|
+
const { TypingIndicator } = require(path.join(root, "src/utils/typingIndicator"));
|
|
20
|
+
const sent = [];
|
|
21
|
+
const api = {
|
|
22
|
+
getCookies: () => "c_user=1; xs=abc",
|
|
23
|
+
refreshFb_dtsg: () => Promise.resolve(),
|
|
24
|
+
sendTypingIndicator: (tid, state) => { sent.push([tid, state]); return Promise.resolve(); }
|
|
25
|
+
};
|
|
26
|
+
const ctx = {
|
|
27
|
+
userID: "100000000000001", clientId: "abcd1234", loggedIn: true, firstListen: true, lastSeqId: 42,
|
|
28
|
+
globalOptions: Object.assign({ autoReconnect: true, emitReady: true, userAgent: "UA" }, globalOptions),
|
|
29
|
+
tasks: new Map(), _mqttOpt: {}
|
|
30
|
+
};
|
|
31
|
+
if (withTyping) ctx._typing = new TypingIndicator(api, ctx, undefined);
|
|
32
|
+
const defaultFuncs = { get: () => Promise.resolve({ data: "" }), post: () => Promise.reject(new Error("network down (test)")) };
|
|
33
|
+
const factory = require(path.join(root, "src/api/socket/listenMqtt.js"));
|
|
34
|
+
const listen = factory(defaultFuncs, api, ctx);
|
|
35
|
+
const events = [];
|
|
36
|
+
const emitter = listen((err, msg) => events.push({ err, msg }));
|
|
37
|
+
return { ctx, api, sent, events, emitter };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const stopAndWait = (s) => new Promise((r) => s.emitter.stopListening(r));
|
|
41
|
+
const msg = (over) => Object.assign({ type: "message", threadID: "t9", senderID: "42", body: "/ping", isGroup: false }, over);
|
|
42
|
+
|
|
43
|
+
test("[mocked] typing middleware is installed by default and shows typing for a command without delaying delivery", async () => {
|
|
44
|
+
const s = build();
|
|
45
|
+
assert.ok(s.ctx._middleware.list().includes("typing"));
|
|
46
|
+
let delivered = null;
|
|
47
|
+
s.ctx._middleware.process(msg(), (err, ev) => { delivered = ev; });
|
|
48
|
+
assert.ok(delivered && delivered.body === "/ping", "event delivered synchronously");
|
|
49
|
+
assert.deepEqual(s.sent, [["t9", true]]);
|
|
50
|
+
await stopAndWait(s);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("[mocked] plain chat does not trigger typing, and stopListening clears pending typing timers", async () => {
|
|
54
|
+
const s = build();
|
|
55
|
+
s.ctx._middleware.process(msg({ body: "hello everyone" }), () => {});
|
|
56
|
+
assert.deepEqual(s.sent, []);
|
|
57
|
+
s.ctx._middleware.process(msg(), () => {});
|
|
58
|
+
assert.equal(s.ctx._typing.isTyping("t9"), true);
|
|
59
|
+
await stopAndWait(s);
|
|
60
|
+
assert.equal(s.ctx._typing.isTyping("t9"), false, "stopListening tears typing down");
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("[mocked] typing middleware is NOT installed when the humanizer owns typing, or when no controller exists", async () => {
|
|
64
|
+
const hz = build({ globalOptions: { humanize: true } });
|
|
65
|
+
assert.ok(!hz.ctx._middleware.list().includes("typing"));
|
|
66
|
+
assert.ok(hz.ctx._middleware.list().includes("humanizer"));
|
|
67
|
+
await stopAndWait(hz);
|
|
68
|
+
const none = build({ withTyping: false });
|
|
69
|
+
assert.ok(!none.ctx._middleware.list().includes("typing"));
|
|
70
|
+
await stopAndWait(none);
|
|
71
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const test = require("node:test");
|
|
3
|
+
const assert = require("node:assert/strict");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const root = process.env.HRIDOY_TEST_ROOT || path.join(__dirname, "..", "..");
|
|
6
|
+
const fp = require(path.join(root, "src/utils/fingerprint"));
|
|
7
|
+
|
|
8
|
+
test("fingerprint: UA is the reduced Chrome/<major>.0.0.0 form and the full build only appears in client hints", () => {
|
|
9
|
+
const ua = fp.getDefaultUserAgent();
|
|
10
|
+
const m = ua.match(/Chrome\/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
|
|
11
|
+
assert.ok(m, ua);
|
|
12
|
+
assert.deepEqual([m[2], m[3], m[4]], ["0", "0", "0"], "UA must not leak the full build");
|
|
13
|
+
const { version, major } = fp.getFingerprint();
|
|
14
|
+
assert.equal(String(major), m[1]);
|
|
15
|
+
const h = fp.clientHintsFromUA(ua);
|
|
16
|
+
assert.ok(h["sec-ch-ua-full-version-list"].includes(`"Google Chrome";v="${version}"`));
|
|
17
|
+
assert.ok(h["sec-ch-ua"].includes(`"Google Chrome";v="${major}"`));
|
|
18
|
+
assert.ok(major >= 149, "pool must not fall back to years-old Chrome builds");
|
|
19
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const test = require("node:test");
|
|
3
|
+
const assert = require("node:assert/strict");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const root = process.env.HRIDOY_TEST_ROOT || path.join(__dirname, "..", "..");
|
|
6
|
+
const { CommandHumanizer } = require(path.join(root, "src/utils/humanizer"));
|
|
7
|
+
|
|
8
|
+
test("humanizer: first command accepted with a bounded delay, burst inside cooldown dropped", (t) => {
|
|
9
|
+
t.mock.timers.enable({ apis: ["Date"], now: 1_000_000 });
|
|
10
|
+
const h = new CommandHumanizer({ reactDelayMs: [2000, 3000], cooldownMs: 5500 });
|
|
11
|
+
const ev = { body: "/help", threadID: "t1" };
|
|
12
|
+
const first = h.shouldProcess(ev);
|
|
13
|
+
assert.equal(first.ok, true);
|
|
14
|
+
assert.ok(first.delayMs >= 2000 && first.delayMs <= 3000, `delay ${first.delayMs}`);
|
|
15
|
+
t.mock.timers.tick(100);
|
|
16
|
+
assert.equal(h.shouldProcess(ev).ok, false, "burst command dropped");
|
|
17
|
+
t.mock.timers.tick(6000);
|
|
18
|
+
assert.equal(h.shouldProcess(ev).ok, true, "accepted again after cooldown/reset");
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("humanizer: non-command messages pass untouched; per-thread isolation", (t) => {
|
|
22
|
+
t.mock.timers.enable({ apis: ["Date"], now: 5_000_000 });
|
|
23
|
+
const h = new CommandHumanizer({});
|
|
24
|
+
assert.equal(h.isCommand({ body: "hello", threadID: "a" }), false);
|
|
25
|
+
assert.equal(h.shouldProcess({ body: "/x", threadID: "a" }).ok, true);
|
|
26
|
+
assert.equal(h.shouldProcess({ body: "/x", threadID: "b" }).ok, true, "other thread unaffected");
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("humanizer: enabled:false never delays or drops", () => {
|
|
30
|
+
const h = new CommandHumanizer({ enabled: false });
|
|
31
|
+
for (let i = 0; i < 50; i++) assert.deepEqual(h.shouldProcess({ body: "/x", threadID: "a" }), { ok: true, delayMs: 0 });
|
|
32
|
+
});
|