hridoy-ultimate 9.0.0 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +346 -69
  2. package/{docs/UPSTREAM_API_DOCS.md → DOCS.md} +3 -3
  3. package/README.md +536 -161
  4. package/func/checkUpdate.js +1 -0
  5. package/index.d.ts +13 -74
  6. package/index.js +0 -6
  7. package/module/config.js +2 -5
  8. package/module/login.js +1 -2
  9. package/module/loginHelper.js +9 -41
  10. package/module/options.js +6 -6
  11. package/package.json +44 -39
  12. package/src/api/action/logout.js +0 -19
  13. package/src/api/messaging/sendMessage.js +1 -1
  14. package/src/api/messaging/sessionGuard.js +8 -0
  15. package/src/api/messaging/setMessageReaction.js +2 -7
  16. package/src/api/socket/core/connectMqtt.js +72 -99
  17. package/src/api/socket/core/emitAuth.js +17 -9
  18. package/src/api/socket/e2ee/index.js +15 -33
  19. package/src/api/socket/e2ee/native/NOTICE.md +2 -2
  20. package/src/api/socket/e2ee/native/lib/index.mjs +1 -2
  21. package/src/api/socket/e2ee/native/nativeMediaBridge.js +4 -4
  22. package/src/api/socket/listenE2EE.js +1 -3
  23. package/src/api/socket/listenMqtt.js +60 -67
  24. package/src/utils/antiSuspension.js +3 -3
  25. package/src/utils/fingerprint.js +35 -16
  26. package/src/utils/headers.js +1 -1
  27. package/src/utils/versionCheck.js +47 -0
  28. package/LICENSE +0 -23
  29. package/MERGE_REPORT.md +0 -54
  30. package/THIRD_PARTY_NOTICES.md +0 -36
  31. package/docs/TEST_RESULTS.md +0 -68
  32. package/scripts/run-tests.js +0 -19
  33. package/scripts/syntax-check.js +0 -22
  34. package/src/api/socket/core/lifecycle.js +0 -117
  35. package/src/api/socket/e2ee/proto/proto-writer.ts +0 -76
  36. package/src/utils/typingIndicator.js +0 -202
  37. package/test/helpers/stub-modules.js +0 -122
  38. package/test/integration/logout.test.js +0 -69
  39. package/test/integration/mqtt-lifecycle.test.js +0 -195
  40. package/test/integration/package.test.js +0 -116
  41. package/test/integration/typing-wiring.test.js +0 -71
  42. package/test/unit/fingerprint.test.js +0 -19
  43. package/test/unit/humanizer.test.js +0 -32
  44. package/test/unit/lifecycle.test.js +0 -92
  45. package/test/unit/parsers.test.js +0 -43
  46. package/test/unit/typing.test.js +0 -136
@@ -1,117 +0,0 @@
1
- "use strict";
2
- /**
3
- * hridoy-ultimate lifecycle helpers (new in 8.0.5).
4
- *
5
- * Root causes addressed here (see MERGE_REPORT.md, "Bugs fixed"):
6
- * - reconnects used a fixed delay forever (no backoff, no cap, no jitter)
7
- * - pending reconnect/retry timers were untracked, and endQuietly() reset
8
- * `_ending=false`, so a timer could revive a listener AFTER stopListening()
9
- * - logout()/emitAuth() left heartbeat / session-keeper / dtsg timers alive
10
- *
11
- * Everything in this file is dependency-free so it can be unit tested without
12
- * network access or third-party modules.
13
- */
14
-
15
- const DEFAULTS = {
16
- reconnectDelayMs: 2000,
17
- maxReconnectDelayMs: 5 * 60 * 1000,
18
- reconnectJitter: 0.3,
19
- maxReconnectAttempts: 10 // 0 = unlimited (explicit opt-in only)
20
- };
21
-
22
- /**
23
- * Bounded exponential backoff with symmetric jitter.
24
- * delay = clamp(base * 2^attempt) +/- jitter*delay, never above maxMs, never < 0.
25
- */
26
- function computeBackoff(attempt, opts) {
27
- const o = opts || {};
28
- const base = Number.isFinite(o.baseMs) && o.baseMs > 0 ? o.baseMs : DEFAULTS.reconnectDelayMs;
29
- const max = Number.isFinite(o.maxMs) && o.maxMs > 0 ? o.maxMs : DEFAULTS.maxReconnectDelayMs;
30
- const jitter = Number.isFinite(o.jitter) && o.jitter >= 0 ? Math.min(o.jitter, 1) : DEFAULTS.reconnectJitter;
31
- const rand = typeof o.random === "function" ? o.random : Math.random;
32
- const n = Math.max(0, Math.floor(attempt) || 0);
33
- const exp = Math.min(max, base * Math.pow(2, Math.min(n, 30)));
34
- const spread = exp * jitter;
35
- const value = exp - spread + rand() * 2 * spread;
36
- return Math.min(max, Math.max(0, Math.round(value)));
37
- }
38
-
39
- /**
40
- * Schedule exactly one reconnect callback.
41
- * Returns:
42
- * "scheduled" - a timer was created
43
- * "debounced" - a reconnect is already pending
44
- * "stopped" - listener was stopped; nothing scheduled
45
- * "exhausted" - attempt budget used up; caller must surface the failure
46
- */
47
- function scheduleReconnect(ctx, logger, fn, reason) {
48
- if (ctx._stopped) return "stopped";
49
- if (ctx._reconnectTimer) return "debounced";
50
- const opt = ctx._mqttOpt || {};
51
- const attempt = ctx._reconnectAttempt || 0;
52
- const maxAttempts = opt.maxReconnectAttempts === undefined ? DEFAULTS.maxReconnectAttempts : opt.maxReconnectAttempts;
53
- if (maxAttempts > 0 && attempt >= maxAttempts) return "exhausted";
54
- const delay = computeBackoff(attempt, {
55
- baseMs: opt.reconnectDelayMs,
56
- maxMs: opt.maxReconnectDelayMs,
57
- jitter: opt.reconnectJitter
58
- });
59
- ctx._reconnectAttempt = attempt + 1;
60
- if (logger) logger(`mqtt reconnect #${attempt + 1}${maxAttempts > 0 ? "/" + maxAttempts : ""} in ${delay}ms (${reason || "unspecified"})`, "warn");
61
- ctx._reconnectTimer = setTimeout(function () {
62
- ctx._reconnectTimer = null;
63
- if (ctx._stopped) return; // stopListening()/logout()/emitAuth() won the race
64
- try {
65
- fn();
66
- } catch (err) {
67
- if (logger) logger(`mqtt reconnect callback threw: ${err && err.message ? err.message : String(err)}`, "error");
68
- }
69
- }, delay);
70
- return "scheduled";
71
- }
72
-
73
- function clearReconnect(ctx) {
74
- if (ctx._reconnectTimer) {
75
- clearTimeout(ctx._reconnectTimer);
76
- ctx._reconnectTimer = null;
77
- }
78
- }
79
-
80
- /**
81
- * Detach every listener from an mqtt client but keep a no-op "error" handler.
82
- * EventEmitter throws on an unhandled "error" event, and mqtt.js can still
83
- * emit one asynchronously (late socket error) after removeAllListeners().
84
- */
85
- function detachClient(client) {
86
- if (!client) return;
87
- try { client.removeAllListeners(); } catch (_) { /* nothing to detach */ }
88
- try { client.on("error", function () { /* swallowed on purpose: client is detached and no longer ours */ }); } catch (_) { /* not an emitter */ }
89
- }
90
-
91
- /**
92
- * Clear every timer this library keeps on ctx. Idempotent.
93
- * `includeSession` also clears the per-login dtsg refresh interval (logout / auth loss).
94
- */
95
- function clearListenerTimers(ctx, includeSession) {
96
- const clear = function (key, fn) {
97
- if (ctx[key]) {
98
- try { fn(ctx[key]); } catch (_) { /* timer already gone */ }
99
- ctx[key] = null;
100
- }
101
- };
102
- clear("_autoCycleTimer", clearInterval);
103
- clear("_heartbeatInterval", clearInterval);
104
- clear("_sessionKeeperInterval", clearTimeout);
105
- clear("_rTimeout", clearTimeout);
106
- clearReconnect(ctx);
107
- if (includeSession) clear("_dtsgRefreshInterval", clearInterval);
108
- }
109
-
110
- module.exports = {
111
- DEFAULTS,
112
- computeBackoff,
113
- scheduleReconnect,
114
- clearReconnect,
115
- detachClient,
116
- clearListenerTimers
117
- };
@@ -1,76 +0,0 @@
1
- /** Minimal protobuf writer - only what we need */
2
- export class ProtoWriter {
3
- private chunks: Buffer[] = [];
4
-
5
- private encodeVarint(value: number): Buffer {
6
- const bytes: number[] = [];
7
- let v = value >>> 0;
8
- while (v > 127) {
9
- bytes.push((v & 0x7f) | 0x80);
10
- v >>>= 7;
11
- }
12
- bytes.push(v);
13
- return Buffer.from(bytes);
14
- }
15
-
16
- private fieldHeader(fieldNum: number, wireType: number): Buffer {
17
- return this.encodeVarint((fieldNum << 3) | wireType);
18
- }
19
-
20
- /** Wire type 0 (varint) but supports bigint */
21
- private encodeVarintBigInt(value: bigint): Buffer {
22
- const bytes: number[] = [];
23
- let v = value;
24
- while (v > 127n) {
25
- bytes.push(Number((v & 0x7fn) | 0x80n));
26
- v >>= 7n;
27
- }
28
- bytes.push(Number(v));
29
- return Buffer.from(bytes);
30
- }
31
-
32
- /** Wire type 0 (varint) for uint64 fields */
33
- uint64_varint(fieldNum: number, value: bigint): this {
34
- this.chunks.push(this.fieldHeader(fieldNum, 0));
35
- this.chunks.push(this.encodeVarintBigInt(value));
36
- return this;
37
- }
38
-
39
- /** Wire type 2 (length-delimited) - bytes, string, embedded message */
40
- bytes(fieldNum: number, data: Uint8Array): this {
41
- const d = Buffer.from(data);
42
- this.chunks.push(this.fieldHeader(fieldNum, 2));
43
- this.chunks.push(this.encodeVarint(d.length));
44
- this.chunks.push(d);
45
- return this;
46
- }
47
-
48
- string(fieldNum: number, value: string): this {
49
- return this.bytes(fieldNum, Buffer.from(value, "utf8"));
50
- }
51
-
52
- /** Wire type 0 (varint) */
53
- varint(fieldNum: number, value: number): this {
54
- this.chunks.push(this.fieldHeader(fieldNum, 0));
55
- this.chunks.push(this.encodeVarint(value));
56
- return this;
57
- }
58
-
59
- /** Wire type 0, bool */
60
- bool(fieldNum: number, value: boolean): this {
61
- return this.varint(fieldNum, value ? 1 : 0);
62
- }
63
-
64
- /** Wire type 1 (64-bit fixed) - uint64 */
65
- uint64(fieldNum: number, value: bigint): this {
66
- const buf = Buffer.alloc(8);
67
- buf.writeBigUInt64LE(value);
68
- this.chunks.push(this.fieldHeader(fieldNum, 1));
69
- this.chunks.push(buf);
70
- return this;
71
- }
72
-
73
- build(): Buffer {
74
- return Buffer.concat(this.chunks);
75
- }
76
- }
@@ -1,202 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Typing indicator (hridoy-ultimate 9.0.0).
5
- *
6
- * Shows "typing…" in a thread as soon as a command-like message arrives and
7
- * clears it when the bot sends its reply (or after a safety timeout). It never
8
- * delays event delivery or the reply itself: next() is called first, the
9
- * typing signal is fire-and-forget.
10
- *
11
- * Works for MQTT threads and E2EE threads (api.sendTypingIndicator routes to
12
- * api.e2ee.sendTyping for connected E2EE DMs).
13
- */
14
-
15
- const { isCommandLike, isNoPrefixAdminCommand } = require("./humanizer");
16
-
17
- const DEFAULTS = Object.freeze({
18
- enabled: true,
19
- onlyCommands: true, // type only when the incoming message looks like a command
20
- commands: [], // extra prefixes (GoatBot prefix and "/", "!", "." are always used)
21
- maxMs: 8000, // safety stop when no reply is sent
22
- minGapMs: 1500, // never re-send "typing" for the same thread inside this window
23
- groups: true,
24
- dms: true
25
- });
26
-
27
- function goatBotConfig() {
28
- try {
29
- return typeof global !== "undefined" && global.GoatBot && global.GoatBot.config ? global.GoatBot.config : null;
30
- } catch (_) {
31
- return null;
32
- }
33
- }
34
-
35
- /** Normalise the user option: undefined/true -> defaults, false -> disabled, object -> merged. */
36
- function normalizeOptions(opt) {
37
- if (opt === false) return Object.assign({}, DEFAULTS, { enabled: false });
38
- const merged = Object.assign({}, DEFAULTS, opt && typeof opt === "object" ? opt : {});
39
- // A GoatBot config that explicitly turns the feature off wins unless the caller
40
- // passed an explicit option.
41
- if (opt === undefined || opt === null) {
42
- const cfg = goatBotConfig();
43
- if (cfg && cfg.enableTypingIndicator === false) merged.enabled = false;
44
- }
45
- merged.maxMs = Math.max(1000, Number(merged.maxMs) || DEFAULTS.maxMs);
46
- merged.minGapMs = Math.max(0, Number(merged.minGapMs) || 0);
47
- merged.commands = Array.isArray(merged.commands) ? merged.commands.filter((p) => typeof p === "string" && p) : [];
48
- return merged;
49
- }
50
-
51
- class TypingIndicator {
52
- constructor(api, ctx, options, log) {
53
- this.api = api;
54
- this.ctx = ctx || {};
55
- this.log = typeof log === "function" ? log : () => {};
56
- this.options = normalizeOptions(options);
57
- this.active = new Map(); // threadID -> { timer, startedAt }
58
- }
59
-
60
- configure(options) {
61
- this.options = normalizeOptions(options);
62
- if (!this.options.enabled) this.stopAll();
63
- return this.options;
64
- }
65
-
66
- get enabled() {
67
- return this.options.enabled === true;
68
- }
69
-
70
- isTyping(threadID) {
71
- return this.active.has(String(threadID));
72
- }
73
-
74
- _prefixes() {
75
- const list = ["/", "!", "."].concat(this.options.commands);
76
- const cfg = goatBotConfig();
77
- if (cfg && typeof cfg.prefix === "string" && cfg.prefix) list.push(cfg.prefix);
78
- return list;
79
- }
80
-
81
- /** Should this incoming event trigger a typing indicator? */
82
- wants(event) {
83
- if (!this.enabled || !event || typeof event !== "object") return false;
84
- if (event.type !== "message" && event.type !== "message_reply") return false;
85
- if (!event.threadID || typeof event.body !== "string" || !event.body.trim()) return false;
86
- if (this.ctx.userID && String(event.senderID) === String(this.ctx.userID)) return false;
87
- if (event.isGroup === true && !this.options.groups) return false;
88
- if (event.isGroup === false && !this.options.dms) return false;
89
- if (!this.options.onlyCommands) return true;
90
- return isCommandLike(event.body, this._prefixes()) || isNoPrefixAdminCommand(event);
91
- }
92
-
93
- _publish(threadID, state) {
94
- const fn = this.api && this.api.sendTypingIndicator;
95
- if (typeof fn !== "function") return;
96
- try {
97
- // autoStop:false -> we own the stop; duration keeps Facebook's own timeout just past ours.
98
- const r = fn.call(this.api, threadID, state, { autoStop: false, duration: this.options.maxMs + 2000 });
99
- if (r && typeof r.catch === "function") r.catch(() => {});
100
- } catch (_) { /* typing is cosmetic: never throw into the bot */ }
101
- }
102
-
103
- start(threadID) {
104
- if (!this.enabled || !threadID) return false;
105
- const tid = String(threadID);
106
- const now = Date.now();
107
- const cur = this.active.get(tid);
108
- if (cur) {
109
- // Already typing: just push the safety stop out, and do not re-send inside minGapMs.
110
- clearTimeout(cur.timer);
111
- cur.timer = this._arm(tid);
112
- if (now - cur.startedAt < this.options.minGapMs) return false;
113
- cur.startedAt = now;
114
- this._publish(tid, true);
115
- return true;
116
- }
117
- this.active.set(tid, { timer: this._arm(tid), startedAt: now });
118
- this._publish(tid, true);
119
- return true;
120
- }
121
-
122
- _arm(tid) {
123
- const t = setTimeout(() => this.stop(tid), this.options.maxMs);
124
- if (t && typeof t.unref === "function") t.unref();
125
- return t;
126
- }
127
-
128
- stop(threadID) {
129
- if (!threadID) return false;
130
- const tid = String(threadID);
131
- const cur = this.active.get(tid);
132
- if (!cur) return false;
133
- clearTimeout(cur.timer);
134
- this.active.delete(tid);
135
- this._publish(tid, false);
136
- return true;
137
- }
138
-
139
- /** Clear every timer without publishing (used on logout / stopListening: the socket is going away). */
140
- stopAll() {
141
- for (const cur of this.active.values()) clearTimeout(cur.timer);
142
- this.active.clear();
143
- }
144
-
145
- /** Called by the sendMessage wrapper: clear typing once the message has gone out. */
146
- noteSend(threadID, result) {
147
- const ids = Array.isArray(threadID) ? threadID : [threadID];
148
- const stopAfter = () => ids.forEach((id) => { if (id) this.stop(id); });
149
- if (!ids.some((id) => id && this.isTyping(id))) return;
150
- if (result && typeof result.then === "function") result.then(stopAfter, stopAfter);
151
- else {
152
- const t = setTimeout(stopAfter, 300);
153
- if (t && typeof t.unref === "function") t.unref();
154
- }
155
- }
156
-
157
- /** Run fn while "typing…" is shown in threadID; always clears afterwards. */
158
- async withTyping(threadID, fn) {
159
- this.start(threadID);
160
- try {
161
- return await fn();
162
- } finally {
163
- this.stop(threadID);
164
- }
165
- }
166
-
167
- /** Middleware for ctx._middleware (shared by MQTT and E2EE listeners). */
168
- middleware() {
169
- return (event, next) => {
170
- next(); // never delay event delivery
171
- try {
172
- if (this.wants(event)) this.start(event.threadID);
173
- } catch (_) { /* cosmetic */ }
174
- };
175
- }
176
- }
177
-
178
- /** Wrap api.sendMessage so a reply clears the typing indicator of its thread. */
179
- function wrapSendMessage(api, typing) {
180
- if (!api || typeof api.sendMessage !== "function" || api.sendMessage.__typingWrapped) return false;
181
- const original = api.sendMessage;
182
- const wrapped = function (msg, threadID) {
183
- const result = original.apply(this, arguments);
184
- try { typing.noteSend(threadID, result); } catch (_) { /* cosmetic */ }
185
- return result;
186
- };
187
- wrapped.__typingWrapped = true;
188
- api.sendMessage = wrapped;
189
- return true;
190
- }
191
-
192
- function createTypingIndicator(api, ctx, options, log) {
193
- return new TypingIndicator(api, ctx, options, log);
194
- }
195
-
196
- module.exports = {
197
- TypingIndicator,
198
- createTypingIndicator,
199
- wrapSendMessage,
200
- normalizeOptions,
201
- DEFAULTS
202
- };
@@ -1,122 +0,0 @@
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 };
@@ -1,69 +0,0 @@
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
- });