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.
Files changed (281) hide show
  1. package/CHANGELOG.md +68 -40
  2. package/LICENSE +23 -0
  3. package/MERGE_REPORT.md +54 -0
  4. package/README.md +158 -113
  5. package/THIRD_PARTY_NOTICES.md +36 -0
  6. package/docs/TEST_RESULTS.md +68 -0
  7. package/docs/UPSTREAM_API_DOCS.md +2712 -0
  8. package/func/checkUpdate.js +6 -0
  9. package/func/logAdapter.js +33 -0
  10. package/func/logger.js +48 -0
  11. package/index.d.ts +812 -0
  12. package/index.js +30 -824
  13. package/module/config.js +46 -0
  14. package/module/login.js +136 -0
  15. package/module/loginHelper.js +1413 -0
  16. package/module/options.js +55 -0
  17. package/package.json +75 -22
  18. package/scripts/run-tests.js +19 -0
  19. package/scripts/syntax-check.js +22 -0
  20. package/src/{addExternalModule.js → api/action/addExternalModule.js} +8 -8
  21. package/src/{changeAvatar.js → api/action/changeAvatar.js} +32 -33
  22. package/src/{changeBio.js → api/action/changeBio.js} +19 -22
  23. package/src/api/action/dismissScrapingWarning.js +50 -0
  24. package/src/api/action/enableAutoSaveAppState.js +73 -0
  25. package/src/{getCurrentUserID.js → api/action/getCurrentUserID.js} +1 -1
  26. package/src/api/action/handleFriendRequest.js +57 -0
  27. package/src/api/action/logout.js +95 -0
  28. package/src/api/action/refreshFb_dtsg.js +47 -0
  29. package/src/{setPostReaction.js → api/action/setPostReaction.js} +23 -31
  30. package/src/{unfriend.js → api/action/unfriend.js} +14 -14
  31. package/src/api/http/httpGet.js +46 -0
  32. package/src/api/http/httpPost.js +52 -0
  33. package/src/api/http/postFormData.js +47 -0
  34. package/src/api/messaging/addUserToGroup.js +68 -0
  35. package/src/api/messaging/changeAdminStatus.js +126 -0
  36. package/src/{changeArchivedStatus.js → api/messaging/changeArchivedStatus.js} +15 -17
  37. package/src/{changeBlockedStatus.js → api/messaging/changeBlockedStatus.js} +13 -16
  38. package/src/api/messaging/changeGroupImage.js +91 -0
  39. package/src/api/messaging/changeNickname.js +70 -0
  40. package/src/api/messaging/changeThreadColor.js +79 -0
  41. package/src/api/messaging/changeThreadEmoji.js +111 -0
  42. package/src/{createNewGroup.js → api/messaging/createNewGroup.js} +24 -26
  43. package/src/api/messaging/createPoll.js +46 -0
  44. package/src/api/messaging/createThemeAI.js +98 -0
  45. package/src/api/messaging/deleteMessage.js +136 -0
  46. package/src/{deleteThread.js → api/messaging/deleteThread.js} +14 -16
  47. package/src/api/messaging/editMessage.js +105 -0
  48. package/src/api/messaging/forwardAttachment.js +57 -0
  49. package/src/api/messaging/forwardMessage.js +134 -0
  50. package/src/{getEmojiUrl.js → api/messaging/getEmojiUrl.js} +2 -2
  51. package/src/{getFriendsList.js → api/messaging/getFriendsList.js} +16 -19
  52. package/src/{getMessage.js → api/messaging/getMessage.js} +160 -180
  53. package/src/api/messaging/getThemePictures.js +62 -0
  54. package/src/api/messaging/handleMessageRequest.js +65 -0
  55. package/src/api/messaging/markAsDelivered.js +69 -0
  56. package/src/api/messaging/markAsRead.js +110 -0
  57. package/src/api/messaging/markAsReadAll.js +56 -0
  58. package/src/api/messaging/markAsSeen.js +68 -0
  59. package/src/api/messaging/muteThread.js +50 -0
  60. package/src/api/messaging/pinMessage.js +115 -0
  61. package/src/api/messaging/removeUserFromGroup.js +62 -0
  62. package/src/{resolvePhotoUrl.js → api/messaging/resolvePhotoUrl.js} +11 -15
  63. package/src/api/messaging/scheduler.js +264 -0
  64. package/src/{searchForThread.js → api/messaging/searchForThread.js} +12 -12
  65. package/src/api/messaging/sendBroadcast.js +93 -0
  66. package/src/api/messaging/sendMessage.js +269 -0
  67. package/src/api/messaging/sendTypingIndicator.js +90 -0
  68. package/src/api/messaging/sessionGuard.js +130 -0
  69. package/src/api/messaging/setMessageReaction.js +114 -0
  70. package/src/api/messaging/setTitle.js +124 -0
  71. package/src/api/messaging/shareContact.js +98 -0
  72. package/src/{threadColors.js → api/messaging/threadColors.js} +2 -5
  73. package/src/api/messaging/unsendMessage.js +105 -0
  74. package/src/api/messaging/uploadAttachment.js +493 -0
  75. package/src/api/socket/OldMessage.js +199 -0
  76. package/src/api/socket/core/connectMqtt.js +304 -0
  77. package/src/api/socket/core/emitAuth.js +95 -0
  78. package/src/api/socket/core/getSeqID.js +331 -0
  79. package/src/api/socket/core/getTaskResponseData.js +25 -0
  80. package/src/api/socket/core/lifecycle.js +117 -0
  81. package/src/api/socket/core/parseDelta.js +387 -0
  82. package/src/api/socket/detail/buildStream.js +215 -0
  83. package/src/api/socket/detail/constants.js +28 -0
  84. package/src/api/socket/e2ee/crypto.js +173 -0
  85. package/src/api/socket/e2ee/index.js +977 -0
  86. package/src/api/socket/e2ee/localMediaServer.js +59 -0
  87. package/src/api/socket/e2ee/mediaDecode.js +155 -0
  88. package/src/api/socket/e2ee/native/NOTICE.md +29 -0
  89. package/{lib → src/api/socket/e2ee/native/lib}/index.mjs +109 -66
  90. package/src/api/socket/e2ee/native/nativeMediaBridge.js +273 -0
  91. package/src/api/socket/e2ee/proto/ArmadilloApplication.proto +281 -0
  92. package/src/api/socket/e2ee/proto/ArmadilloICDC.proto +14 -0
  93. package/src/api/socket/e2ee/proto/ConsumerApplication.proto +232 -0
  94. package/src/api/socket/e2ee/proto/MessageApplication.proto +82 -0
  95. package/src/api/socket/e2ee/proto/MessageTransport.proto +77 -0
  96. package/src/api/socket/e2ee/proto/WACommon.proto +66 -0
  97. package/src/api/socket/e2ee/proto/WAMediaTransport.proto +176 -0
  98. package/src/api/socket/e2ee/proto/proto-writer.ts +76 -0
  99. package/src/api/socket/e2ee/protocol.js +196 -0
  100. package/src/api/socket/e2ee/ratchet.js +219 -0
  101. package/src/api/socket/e2ee/store.js +182 -0
  102. package/src/api/socket/e2ee/vendor/fme/dist/index.cjs +6477 -0
  103. package/src/api/socket/e2ee/vendor/fme/proto/ArmadilloApplication.proto +281 -0
  104. package/src/api/socket/e2ee/vendor/fme/proto/ArmadilloICDC.proto +14 -0
  105. package/src/api/socket/e2ee/vendor/fme/proto/ConsumerApplication.proto +232 -0
  106. package/src/api/socket/e2ee/vendor/fme/proto/MessageApplication.proto +82 -0
  107. package/src/api/socket/e2ee/vendor/fme/proto/MessageTransport.proto +77 -0
  108. package/src/api/socket/e2ee/vendor/fme/proto/WACommon.proto +66 -0
  109. package/src/api/socket/e2ee/vendor/fme/proto/WAMediaTransport.proto +176 -0
  110. package/src/api/socket/listenE2EE.js +87 -0
  111. package/src/api/socket/listenMqtt.js +499 -0
  112. package/src/api/socket/middleware/index.js +216 -0
  113. package/src/api/socket/sendMessage.js +331 -0
  114. package/src/api/socket/sendMessageMqtt.js +69 -0
  115. package/src/{getThreadHistory.js → api/threads/getThreadHistory.js} +114 -132
  116. package/src/api/threads/getThreadInfo.js +329 -0
  117. package/src/api/threads/getThreadList.js +293 -0
  118. package/src/api/threads/getThreadPictures.js +78 -0
  119. package/src/{getUserID.js → api/users/getUserID.js} +22 -18
  120. package/src/api/users/getUserInfo.js +402 -0
  121. package/src/api/users/getUserInfoV2.js +134 -0
  122. package/src/app/MessengerBot.js +209 -0
  123. package/src/app/MessengerContext.js +32 -0
  124. package/src/app/createFcaClient.js +136 -0
  125. package/src/app/threadInfoRealtimeSync.js +284 -0
  126. package/src/core/sendReqMqtt.js +96 -0
  127. package/src/database/helpers.js +53 -0
  128. package/src/database/models/index.js +88 -0
  129. package/src/database/models/thread.js +50 -0
  130. package/src/database/models/user.js +46 -0
  131. package/src/database/threadData.js +94 -0
  132. package/src/database/userData.js +98 -0
  133. package/src/remote/remoteClient.js +123 -0
  134. package/src/utils/antiSuspension.js +219 -0
  135. package/src/utils/broadcast.js +51 -0
  136. package/src/utils/client.js +10 -0
  137. package/src/utils/constants.js +23 -0
  138. package/src/utils/cookies.js +85 -0
  139. package/src/utils/fingerprint.js +110 -0
  140. package/src/utils/format/attachment.js +357 -0
  141. package/src/utils/format/cookie.js +9 -0
  142. package/src/utils/format/date.js +50 -0
  143. package/src/utils/format/decode.js +44 -0
  144. package/src/utils/format/delta.js +195 -0
  145. package/src/utils/format/ids.js +64 -0
  146. package/src/utils/format/index.js +64 -0
  147. package/src/utils/format/message.js +88 -0
  148. package/src/utils/format/presence.js +132 -0
  149. package/src/utils/format/readTyp.js +44 -0
  150. package/src/utils/format/thread.js +42 -0
  151. package/src/utils/format/utils.js +141 -0
  152. package/src/utils/headers.js +125 -0
  153. package/src/utils/humanizer.js +256 -0
  154. package/src/utils/loginParser/autoLogin.js +125 -0
  155. package/src/utils/loginParser/extractDtsg.js +44 -0
  156. package/src/utils/loginParser/helpers.js +43 -0
  157. package/src/utils/loginParser/index.js +10 -0
  158. package/src/utils/loginParser/parseAndCheckLogin.js +241 -0
  159. package/src/utils/loginParser/textUtils.js +28 -0
  160. package/src/utils/nexca-logger.js +144 -0
  161. package/src/utils/nexca-utils.js +687 -0
  162. package/src/utils/request/client.js +26 -0
  163. package/src/utils/request/config.js +23 -0
  164. package/src/utils/request/defaults.js +46 -0
  165. package/src/utils/request/helpers.js +46 -0
  166. package/src/utils/request/index.js +17 -0
  167. package/src/utils/request/methods.js +163 -0
  168. package/src/utils/request/proxy.js +21 -0
  169. package/src/utils/request/retry.js +77 -0
  170. package/src/utils/request/sanitize.js +49 -0
  171. package/src/utils/typingIndicator.js +202 -0
  172. package/test/helpers/stub-modules.js +122 -0
  173. package/test/integration/logout.test.js +69 -0
  174. package/test/integration/mqtt-lifecycle.test.js +195 -0
  175. package/test/integration/package.test.js +116 -0
  176. package/test/integration/typing-wiring.test.js +71 -0
  177. package/test/unit/fingerprint.test.js +19 -0
  178. package/test/unit/humanizer.test.js +32 -0
  179. package/test/unit/lifecycle.test.js +92 -0
  180. package/test/unit/parsers.test.js +43 -0
  181. package/test/unit/typing.test.js +136 -0
  182. package/ANALYSIS.md +0 -31
  183. package/AUDIT_REPORT.md +0 -57
  184. package/advancedSystem.js +0 -95
  185. package/checkUpdate.js +0 -47
  186. package/config.json +0 -51
  187. package/e2ee.js +0 -738
  188. package/examples/basic-bot.js +0 -122
  189. package/examples/e2ee-bot.js +0 -141
  190. package/fca-config.example.json +0 -73
  191. package/scripts/check.js +0 -38
  192. package/src/OldMessage.js +0 -357
  193. package/src/addUserToGroup.js +0 -117
  194. package/src/changeAdminStatus.js +0 -105
  195. package/src/changeAvatarV2.js +0 -86
  196. package/src/changeAvt.js +0 -85
  197. package/src/changeBlockedStatusMqtt.js +0 -75
  198. package/src/changeCover.js +0 -73
  199. package/src/changeGroupImage.js +0 -137
  200. package/src/changeName.js +0 -79
  201. package/src/changeNickname.js +0 -61
  202. package/src/changeThreadColor.js +0 -67
  203. package/src/changeThreadEmoji.js +0 -57
  204. package/src/changeUsername.js +0 -59
  205. package/src/createCommentPost.js +0 -232
  206. package/src/createPoll.js +0 -73
  207. package/src/createPost.js +0 -276
  208. package/src/deleteMessage.js +0 -58
  209. package/src/editMessage.js +0 -76
  210. package/src/editMessageOld.js +0 -62
  211. package/src/follow.js +0 -74
  212. package/src/forwardAttachment.js +0 -62
  213. package/src/friendList.js +0 -104
  214. package/src/getAccess.js +0 -112
  215. package/src/getAvatarUser.js +0 -78
  216. package/src/getBotInitialData.js +0 -42
  217. package/src/getCtx.js +0 -5
  218. package/src/getOptions.js +0 -5
  219. package/src/getRegion.js +0 -7
  220. package/src/getThreadHistoryDeprecated.js +0 -71
  221. package/src/getThreadInfo.js +0 -232
  222. package/src/getThreadInfoDeprecated.js +0 -56
  223. package/src/getThreadList.js +0 -213
  224. package/src/getThreadListDeprecated.js +0 -46
  225. package/src/getThreadPictures.js +0 -59
  226. package/src/getThreadTheme.js +0 -81
  227. package/src/getUID.js +0 -119
  228. package/src/getUserInfo.js +0 -66
  229. package/src/handleFriendRequest.js +0 -46
  230. package/src/handleMessageRequest.js +0 -47
  231. package/src/httpGet.js +0 -49
  232. package/src/httpPost.js +0 -48
  233. package/src/httpPostFormData.js +0 -70
  234. package/src/listenMqtt.js +0 -1081
  235. package/src/listenNotification.js +0 -85
  236. package/src/logout.js +0 -18
  237. package/src/markAsDelivered.js +0 -47
  238. package/src/markAsRead.js +0 -72
  239. package/src/markAsReadAll.js +0 -40
  240. package/src/markAsSeen.js +0 -48
  241. package/src/metaTheme.js +0 -189
  242. package/src/muteThread.js +0 -45
  243. package/src/note.js +0 -228
  244. package/src/pinMessage.js +0 -54
  245. package/src/refreshFb_dtsg.js +0 -49
  246. package/src/removeSuspiciousAccount.js +0 -78
  247. package/src/removeUserFromGroup.js +0 -81
  248. package/src/reply.js +0 -442
  249. package/src/searchFriends.js +0 -140
  250. package/src/searchStickers.js +0 -53
  251. package/src/send.js +0 -46
  252. package/src/sendButtons.js +0 -163
  253. package/src/sendComment.js +0 -159
  254. package/src/sendFriendRequest.js +0 -112
  255. package/src/sendMessage.js +0 -441
  256. package/src/sendMessageMqtt.js +0 -323
  257. package/src/sendTypingIndicator.js +0 -68
  258. package/src/sendTypingIndicatorV2.js +0 -22
  259. package/src/setActiveStatus.js +0 -92
  260. package/src/setMessageReaction.js +0 -150
  261. package/src/setMessageReactionMqtt.js +0 -104
  262. package/src/setMessageReactionSafe.js +0 -44
  263. package/src/setProfileGuard.js +0 -44
  264. package/src/setProfileLock.js +0 -97
  265. package/src/setStoryReaction.js +0 -133
  266. package/src/setStorySeen.js +0 -108
  267. package/src/setThreadTheme.js +0 -102
  268. package/src/setTitle.js +0 -92
  269. package/src/shareContact.js +0 -110
  270. package/src/shareLink.js +0 -59
  271. package/src/stopListenMqtt.js +0 -60
  272. package/src/storyManager.js +0 -357
  273. package/src/suggestFriend.js +0 -132
  274. package/src/unsendMessage.js +0 -68
  275. package/src/uploadAttachment.js +0 -115
  276. package/test/fixes-1_2_4.test.js +0 -118
  277. package/test/mqtt-stop.test.js +0 -32
  278. package/test/reaction-mqtt.test.js +0 -57
  279. package/utils.js +0 -3056
  280. /package/{build → src/api/socket/e2ee/native/build}/messagix.dll +0 -0
  281. /package/{build → src/api/socket/e2ee/native/build}/messagix.so +0 -0
@@ -0,0 +1,256 @@
1
+ "use strict";
2
+
3
+ const DEFAULT_OPTIONS = Object.freeze({
4
+ enabled: true,
5
+ reactDelayMs: [2000, 3000],
6
+ cooldownMs: 5500,
7
+ resetMs: 10000,
8
+ maxPerMinute: 20,
9
+ commands: ["/", "!", "."],
10
+ perThread: true
11
+ });
12
+
13
+ function isCommandLike(body, prefixes) {
14
+ if (typeof body !== "string") return false;
15
+ const text = body.trim();
16
+ if (!text || !Array.isArray(prefixes) || !prefixes.length) return false;
17
+ return prefixes.some(p => typeof p === "string" && p.length > 0 && text.startsWith(p));
18
+ }
19
+
20
+ function isNoPrefixAdminCommand(event) {
21
+ try {
22
+ const GoatBot = typeof global !== "undefined" ? global.GoatBot : undefined;
23
+ if (!GoatBot || !GoatBot.config || !GoatBot.commands) return false;
24
+
25
+ const cfg = GoatBot.config;
26
+ if (!cfg.noPrefix || cfg.noPrefix.enable !== true) return false;
27
+ if (!Array.isArray(cfg.adminBot) || !cfg.adminBot.includes(event.senderID)) return false;
28
+
29
+ const body = typeof event.body === "string" ? event.body.trim() : "";
30
+ if (!body) return false;
31
+
32
+ const possibleCmd = body.split(/ +/)[0].toLowerCase();
33
+ if (GoatBot.commands.has(possibleCmd)) return true;
34
+
35
+ const alias = GoatBot.aliases && GoatBot.aliases.get(possibleCmd);
36
+ return Boolean(alias && GoatBot.commands.has(alias));
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ function isGoatBotOnReplyTrigger(event) {
43
+ try {
44
+ const GoatBot = typeof global !== "undefined" ? global.GoatBot : undefined;
45
+ if (!GoatBot || !GoatBot.onReply || !event.messageReply) return false;
46
+
47
+ // Covers GoatBot's stateful "reply with a number" flows (setting.js,
48
+ // and any other command using onReply) — these are plain-text replies
49
+ // (e.g. "1", "2") with no prefix and no command-name match, so neither
50
+ // isCommandLike nor the noPrefix/onChat checks above catch them.
51
+ return GoatBot.onReply.has(event.messageReply.messageID);
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ function isGoatBotOnChatTrigger(event) {
58
+ try {
59
+ const GoatBot = typeof global !== "undefined" ? global.GoatBot : undefined;
60
+ if (!GoatBot || !Array.isArray(GoatBot.onChat) || !GoatBot.onChat.length) return false;
61
+
62
+ const body = typeof event.body === "string" ? event.body.trim().toLowerCase() : "";
63
+ if (!body) return false;
64
+
65
+ // onChat handlers commonly match on the full message text equal to a
66
+ // command name (see prefix.js: body.toLowerCase() === "prefix"), so a
67
+ // whole-body match against a registered onChat command name is the
68
+ // best-effort, low-false-positive signal available here.
69
+ return GoatBot.onChat.some(name => typeof name === "string" && name.toLowerCase() === body);
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ function randomBetween(min, max) {
76
+ if (Array.isArray(min)) {
77
+ const pair = min;
78
+ min = pair[0];
79
+ max = pair[1];
80
+ }
81
+ min = Number(min) || 0;
82
+ max = Number(max) || min;
83
+ if (max < min) { const t = min; min = max; max = t; }
84
+ return min + Math.floor(Math.random() * (max - min + 1));
85
+ }
86
+
87
+ class CommandHumanizer {
88
+ constructor(options) {
89
+ this.setOptions(options);
90
+ this._threads = new Map();
91
+ this._global = { windowStart: 0, count: 0, accepted: 0, dropped: 0 };
92
+ this._eventCount = 0;
93
+ }
94
+
95
+ setOptions(options) {
96
+ const o = options || {};
97
+ this.enabled = o.enabled !== false;
98
+ this.reactDelayMs = o.reactDelayMs || DEFAULT_OPTIONS.reactDelayMs;
99
+ this.cooldownMs = typeof o.cooldownMs === "number" ? o.cooldownMs : DEFAULT_OPTIONS.cooldownMs;
100
+ this.resetMs = typeof o.resetMs === "number" ? o.resetMs : DEFAULT_OPTIONS.resetMs;
101
+ this.maxPerMinute = typeof o.maxPerMinute === "number" ? o.maxPerMinute : DEFAULT_OPTIONS.maxPerMinute;
102
+ this.prefixes = o.commands || o.prefixes || DEFAULT_OPTIONS.commands;
103
+ this.perThread = o.perThread !== false;
104
+ if (o.matcher !== undefined) {
105
+ this.matcher = typeof o.matcher === "function" ? o.matcher : null;
106
+ } else if (this.matcher === undefined) {
107
+ this.matcher = null;
108
+ }
109
+ }
110
+
111
+ setMatcher(fn) {
112
+ this.matcher = typeof fn === "function" ? fn : null;
113
+ }
114
+
115
+ isCommand(event) {
116
+ if (!event) return false;
117
+ if (isCommandLike(event.body, this.prefixes)) return true;
118
+ if (typeof this.matcher === "function") {
119
+ try {
120
+ if (this.matcher(event)) return true;
121
+ } catch {
122
+ // ignore matcher errors, fall through to built-in detection
123
+ }
124
+ }
125
+ return isNoPrefixAdminCommand(event) || isGoatBotOnChatTrigger(event) || isGoatBotOnReplyTrigger(event);
126
+ }
127
+
128
+ _keyFor(event) {
129
+ return this.perThread && event.threadID ? String(event.threadID) : "_global";
130
+ }
131
+
132
+ _globalAllowed() {
133
+ const now = Date.now();
134
+ if (now - this._global.windowStart >= 60000) {
135
+ this._global.windowStart = now;
136
+ this._global.count = 0;
137
+ }
138
+ if (this._global.count >= this.maxPerMinute) return false;
139
+ this._global.count++;
140
+ return true;
141
+ }
142
+
143
+ shouldProcess(event) {
144
+ this._eventCount++;
145
+ if (!this.enabled) return { ok: true, delayMs: 0 };
146
+
147
+ const key = this._keyFor(event);
148
+ const now = Date.now();
149
+
150
+ let st = this._threads.get(key);
151
+ if (!st) {
152
+ st = { acceptedAt: 0, coolUntil: 0, lastCmdAt: 0, accepted: 0, dropped: 0 };
153
+ this._threads.set(key, st);
154
+ }
155
+
156
+ if (st.lastCmdAt > 0 && (now - st.lastCmdAt >= this.resetMs)) {
157
+ st.acceptedAt = 0;
158
+ st.coolUntil = 0;
159
+ }
160
+ st.lastCmdAt = now;
161
+
162
+ if (st.coolUntil > 0 && now < st.coolUntil) {
163
+ st.dropped++;
164
+ this._global.dropped++;
165
+ return { ok: false, delayMs: 0, reason: "cooldown" };
166
+ }
167
+
168
+ if (this.maxPerMinute > 0 && !this._globalAllowed()) {
169
+ st.dropped++;
170
+ this._global.dropped++;
171
+ return { ok: false, delayMs: 0, reason: "global-cap" };
172
+ }
173
+
174
+ st.acceptedAt = now;
175
+ st.coolUntil = now + this.cooldownMs;
176
+ st.accepted++;
177
+ this._global.accepted++;
178
+ return { ok: true, delayMs: randomBetween(this.reactDelayMs) };
179
+ }
180
+
181
+ reset(key) {
182
+ if (key === undefined) { this._threads.clear(); return; }
183
+ this._threads.delete(String(key));
184
+ }
185
+
186
+ stats() {
187
+ const threads = [];
188
+ this._threads.forEach((st, k) => threads.push({ threadID: k, ...st }));
189
+ return {
190
+ enabled: this.enabled,
191
+ global: { ...this._global },
192
+ eventCount: this._eventCount,
193
+ threads
194
+ };
195
+ }
196
+ }
197
+
198
+ function createCommandHumanizer(options) {
199
+ return new CommandHumanizer(options);
200
+ }
201
+
202
+ function createHumanizerMiddleware(humanizer, logger, api) {
203
+ const log = typeof logger === "function"
204
+ ? (msg, level) => logger(msg, level || "info")
205
+ : () => {};
206
+
207
+ function typingWanted() {
208
+ try {
209
+ const GoatBot = typeof global !== "undefined" ? global.GoatBot : undefined;
210
+ if (GoatBot && GoatBot.config) return GoatBot.config.enableTypingIndicator === true;
211
+ return true;
212
+ } catch {
213
+ return true;
214
+ }
215
+ }
216
+
217
+ return function commandHumanizerMiddleware(event, next) {
218
+ if (!humanizer.isCommand(event)) { next(); return; }
219
+
220
+ const decision = humanizer.shouldProcess(event);
221
+
222
+ if (!decision.ok) {
223
+ const snippet = typeof event.body === "string" ? event.body.slice(0, 40) : String(event.body || "");
224
+ log(`Humanizer: dropped command "${snippet}" (${decision.reason})`, "warn");
225
+ next(false);
226
+ return;
227
+ }
228
+
229
+ const delay = Math.max(0, decision.delayMs || 0);
230
+ if (delay <= 0) { next(); return; }
231
+
232
+ const canType = api && typeof api.sendTypingIndicator === "function" && event.threadID && typingWanted();
233
+ if (!canType) {
234
+ setTimeout(() => next(), delay);
235
+ return;
236
+ }
237
+
238
+ Promise.resolve(api.sendTypingIndicator(event.threadID, true)).catch(() => {});
239
+ setTimeout(() => {
240
+ Promise.resolve(api.sendTypingIndicator(event.threadID, false)).catch(() => {});
241
+ next();
242
+ }, delay);
243
+ };
244
+ }
245
+
246
+ module.exports = {
247
+ CommandHumanizer,
248
+ createCommandHumanizer,
249
+ createHumanizerMiddleware,
250
+ randomBetween,
251
+ isCommandLike,
252
+ isNoPrefixAdminCommand,
253
+ isGoatBotOnChatTrigger,
254
+ isGoatBotOnReplyTrigger,
255
+ DEFAULT_OPTIONS
256
+ };
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+
3
+ const logger = require("../../../func/logger");
4
+
5
+ /**
6
+ * Tạo hàm maybeAutoLogin: khi session hết hạn thì thử đăng nhập lại và retry request.
7
+ * @param {Object} ctx - Context (jar, performAutoLogin, globalOptions, ...)
8
+ * @param {Object} http - HTTP client (get, post, postFormData)
9
+ * @param {Object} helpers - { buildUrl, headerOf, formatCookie }
10
+ * @param {Function} emit - createEmit(ctx)
11
+ * @param {Function} parseAndCheckLogin - Hàm parse chính để retry sau khi auto login thành công
12
+ */
13
+ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
14
+ const { buildUrl, headerOf, formatCookie } = helpers;
15
+
16
+ return async function maybeAutoLogin(resData, resConfig) {
17
+ if (ctx.auto_login) {
18
+ const e = new Error("Not logged in. Auto login already in progress.");
19
+ e.error = "Not logged in.";
20
+ e.res = resData;
21
+ throw e;
22
+ }
23
+ if (typeof ctx.performAutoLogin !== "function") {
24
+ const e = new Error("Not logged in. Auto login function not available.");
25
+ e.error = "Not logged in.";
26
+ e.res = resData;
27
+ throw e;
28
+ }
29
+
30
+ ctx.auto_login = true;
31
+ logger("Login session expired, attempting auto login...", "warn");
32
+ emit("sessionExpired", { res: resData });
33
+
34
+ try {
35
+ const ok = await ctx.performAutoLogin();
36
+ if (ok) {
37
+ logger("Auto login successful! Retrying request...", "info");
38
+ emit("autoLoginSuccess", { res: resData });
39
+ ctx.auto_login = false;
40
+
41
+ if (resConfig) {
42
+ const url = buildUrl(resConfig);
43
+ const method = String(resConfig?.method || "GET").toUpperCase();
44
+ const ctype = String(headerOf(resConfig?.headers, "content-type") || "").toLowerCase();
45
+ const isMultipart = ctype.includes("multipart/form-data");
46
+ const payload = resConfig?.data;
47
+ const params = resConfig?.params;
48
+
49
+ try {
50
+ let newData;
51
+ if (method === "GET") {
52
+ newData = await http.get(url, ctx.jar, params || null, ctx.globalOptions, ctx);
53
+ } else if (isMultipart) {
54
+ newData = await http.postFormData(url, ctx.jar, payload, params, ctx.globalOptions, ctx);
55
+ } else {
56
+ newData = await http.post(url, ctx.jar, payload, ctx.globalOptions, ctx);
57
+ }
58
+ return await parseAndCheckLogin(ctx, http)(newData);
59
+ } catch (retryErr) {
60
+ if (
61
+ retryErr?.code === "ERR_INVALID_CHAR" ||
62
+ (retryErr?.message && retryErr.message.includes("Invalid character in header"))
63
+ ) {
64
+ logger(
65
+ `Auto login retry failed: Invalid header detected. Error: ${retryErr.message}`,
66
+ "error"
67
+ );
68
+ const e = new Error("Not logged in. Auto login retry failed due to invalid header.");
69
+ e.error = "Not logged in.";
70
+ e.res = resData;
71
+ e.originalError = retryErr;
72
+ throw e;
73
+ }
74
+ logger(
75
+ `Auto login retry failed: ${
76
+ retryErr && retryErr.message ? retryErr.message : String(retryErr)
77
+ }`,
78
+ "error"
79
+ );
80
+ const e = new Error("Not logged in. Auto login retry failed.");
81
+ e.error = "Not logged in.";
82
+ e.res = resData;
83
+ e.originalError = retryErr;
84
+ throw e;
85
+ }
86
+ } else {
87
+ const e = new Error(
88
+ "Not logged in. Auto login successful but cannot retry request."
89
+ );
90
+ e.error = "Not logged in.";
91
+ e.res = resData;
92
+ throw e;
93
+ }
94
+ } else {
95
+ ctx.auto_login = false;
96
+ const e = new Error("Not logged in. Auto login failed.");
97
+ e.error = "Not logged in.";
98
+ e.res = resData;
99
+ emit("autoLoginFailed", { error: e, res: resData });
100
+ throw e;
101
+ }
102
+ } catch (autoLoginErr) {
103
+ ctx.auto_login = false;
104
+ if (autoLoginErr.error === "Not logged in.") {
105
+ throw autoLoginErr;
106
+ }
107
+ logger(
108
+ `Auto login error: ${
109
+ autoLoginErr && autoLoginErr.message ? autoLoginErr.message : String(autoLoginErr)
110
+ }`,
111
+ "error"
112
+ );
113
+ const e = new Error("Not logged in. Auto login error.");
114
+ e.error = "Not logged in.";
115
+ e.res = resData;
116
+ e.originalError = autoLoginErr;
117
+ emit("autoLoginFailed", { error: e, res: resData });
118
+ throw e;
119
+ }
120
+ };
121
+ }
122
+
123
+ module.exports = {
124
+ createMaybeAutoLogin
125
+ };
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+
3
+ // Multi-pattern fb_dtsg / jazoest extractor.
4
+ // Facebook serves the token in different shapes depending on surface, A/B
5
+ // bucket and login state (DTSGInitialData / DTSGInitData blobs, escaped JSON
6
+ // inside <script>, plain hidden inputs, async_get_token, ...). Matching only
7
+ // one shape is why refreshes intermittently fail with "Could not find
8
+ // fb_dtsg in HTML". Pattern order is first-match-wins.
9
+
10
+ const DTSG_PATTERNS = [
11
+ /\["DTSGInitialData",\[\],\{"token":"([^"]+)"\}\]/,
12
+ /\["DTSGInitData",\[\],\{"token":"([^"]+)"/,
13
+ /"DTSGInitData",\[\],\{"token":"([^"]+)"/,
14
+ /"dtsg":\{"token":"([^"]+)"/,
15
+ /\{\\"token\\":\\"([^\\]+)\\"/,
16
+ /,\{"token":"([^"]+)"\},\d+\]/,
17
+ /"async_get_token":"([^"]+)"/,
18
+ /name="fb_dtsg"\s+value="([^"]+)"/,
19
+ ];
20
+
21
+ const JAZOEST_PATTERNS = [
22
+ /name="jazoest"\s+value="([^"]+)"/,
23
+ /jazoest=(\d+)/,
24
+ /"jazoest":"?(\d+)"?/,
25
+ ];
26
+
27
+ function firstMatch(html, patterns) {
28
+ for (const pattern of patterns) {
29
+ const m = html.match(pattern);
30
+ if (m && m[1]) return m[1];
31
+ }
32
+ return null;
33
+ }
34
+
35
+ function extractDtsg(html) {
36
+ if (!html) return { fb_dtsg: null, jazoest: null };
37
+ const raw = String(html);
38
+ return {
39
+ fb_dtsg: firstMatch(raw, DTSG_PATTERNS),
40
+ jazoest: firstMatch(raw, JAZOEST_PATTERNS),
41
+ };
42
+ }
43
+
44
+ module.exports = { extractDtsg, DTSG_PATTERNS, JAZOEST_PATTERNS };
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+
3
+ const delay = ms => new Promise(r => setTimeout(r, ms));
4
+
5
+ function createEmit(ctx) {
6
+ return (event, payload) => {
7
+ try {
8
+ if (ctx && ctx._emitter && typeof ctx._emitter.emit === "function") {
9
+ ctx._emitter.emit(event, payload);
10
+ }
11
+ } catch { }
12
+ };
13
+ }
14
+
15
+ function headerOf(headers, name) {
16
+ if (!headers) return;
17
+ const k = Object.keys(headers).find(k => k.toLowerCase() === name.toLowerCase());
18
+ return k ? headers[k] : undefined;
19
+ }
20
+
21
+ function buildUrl(cfg) {
22
+ try {
23
+ return cfg?.baseURL
24
+ ? new URL(cfg.url || "/", cfg.baseURL).toString()
25
+ : cfg?.url || "";
26
+ } catch {
27
+ return cfg?.url || "";
28
+ }
29
+ }
30
+
31
+ function formatCookie(arr, service) {
32
+ const n = String(arr?.[0] || "");
33
+ const v = String(arr?.[1] || "");
34
+ return `${n}=${v}; Domain=.${service}.com; Path=/; Secure`;
35
+ }
36
+
37
+ module.exports = {
38
+ delay,
39
+ createEmit,
40
+ headerOf,
41
+ buildUrl,
42
+ formatCookie
43
+ };
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+
3
+ const { parseAndCheckLogin } = require("./parseAndCheckLogin");
4
+ const { cleanXssi, makeParsable } = require("./textUtils");
5
+
6
+ module.exports = {
7
+ parseAndCheckLogin,
8
+ cleanXssi,
9
+ makeParsable
10
+ };