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,26 @@
1
+ "use strict";
2
+
3
+ const axios = require("axios");
4
+ const { CookieJar } = require("tough-cookie");
5
+ const { wrapper } = require("axios-cookiejar-support");
6
+
7
+ const jar = new CookieJar();
8
+ const client = wrapper(
9
+ axios.create({
10
+ jar,
11
+ withCredentials: true,
12
+ timeout: 60000,
13
+ validateStatus: (s) => s >= 200 && s < 600,
14
+ maxRedirects: 5,
15
+ maxContentLength: Infinity,
16
+ maxBodyLength: Infinity,
17
+ })
18
+ );
19
+
20
+ const delay = (ms) => new Promise((r) => setTimeout(r, ms));
21
+
22
+ module.exports = {
23
+ jar,
24
+ client,
25
+ delay,
26
+ };
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+
3
+ const { sanitizeHeaders } = require("./sanitize");
4
+ const { jar, client } = require("./client");
5
+
6
+ function cfg(base = {}) {
7
+ const { reqJar, headers, params, agent, timeout } = base;
8
+ return {
9
+ headers: sanitizeHeaders(headers),
10
+ params,
11
+ jar: reqJar || jar,
12
+ withCredentials: true,
13
+ timeout: timeout || 60000,
14
+ httpAgent: agent || client.defaults.httpAgent,
15
+ httpsAgent: agent || client.defaults.httpsAgent,
16
+ proxy: false,
17
+ validateStatus: (s) => s >= 200 && s < 600,
18
+ };
19
+ }
20
+
21
+ module.exports = {
22
+ cfg,
23
+ };
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ const constMod = require("../constants");
4
+ const getFrom = constMod.getFrom || constMod;
5
+ const { get, post, postFormData } = require("./methods");
6
+
7
+ function makeDefaults(html, userID, ctx) {
8
+ let reqCounter = 1;
9
+ const revision =
10
+ getFrom(html || "", 'revision":', ",") ||
11
+ getFrom(html || "", '"client_revision":', ",") ||
12
+ "";
13
+ function mergeWithDefaults(obj) {
14
+ const base = {
15
+ av: userID,
16
+ __user: userID,
17
+ __req: (reqCounter++).toString(36),
18
+ __rev: revision,
19
+ __a: 1,
20
+ };
21
+ if (ctx?.fb_dtsg) base.fb_dtsg = ctx.fb_dtsg;
22
+ if (ctx?.jazoest) base.jazoest = ctx.jazoest;
23
+ if (!obj) return base;
24
+ for (const k of Object.keys(obj)) if (!(k in base)) base[k] = obj[k];
25
+ return base;
26
+ }
27
+ return {
28
+ get: (url, j, qs, ctxx, customHeader = {}) =>
29
+ get(url, j, mergeWithDefaults(qs), ctx?.globalOptions, ctxx || ctx, customHeader),
30
+ post: (url, j, form, ctxx, customHeader = {}) =>
31
+ post(url, j, mergeWithDefaults(form), ctx?.globalOptions, ctxx || ctx, customHeader),
32
+ postFormData: (url, j, form, qs, ctxx) =>
33
+ postFormData(
34
+ url,
35
+ j,
36
+ mergeWithDefaults(form),
37
+ mergeWithDefaults(qs),
38
+ ctx?.globalOptions,
39
+ ctxx || ctx
40
+ ),
41
+ };
42
+ }
43
+
44
+ module.exports = {
45
+ makeDefaults,
46
+ };
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ const formatMod = require("../format");
4
+ const getType = formatMod.getType || formatMod;
5
+
6
+ function toStringVal(v) {
7
+ if (v === undefined || v === null) return "";
8
+ if (typeof v === "bigint") return v.toString();
9
+ if (typeof v === "boolean") return v ? "true" : "false";
10
+ return String(v);
11
+ }
12
+
13
+ function isStream(v) {
14
+ return (
15
+ v &&
16
+ typeof v === "object" &&
17
+ typeof v.pipe === "function" &&
18
+ typeof v.on === "function"
19
+ );
20
+ }
21
+
22
+ function isBlobLike(v) {
23
+ return (
24
+ v &&
25
+ typeof v.arrayBuffer === "function" &&
26
+ (typeof v.type === "string" || typeof v.name === "string")
27
+ );
28
+ }
29
+
30
+ function isPairArrayList(arr) {
31
+ return (
32
+ Array.isArray(arr) &&
33
+ arr.length > 0 &&
34
+ arr.every(
35
+ (x) => Array.isArray(x) && x.length === 2 && typeof x[0] === "string"
36
+ )
37
+ );
38
+ }
39
+
40
+ module.exports = {
41
+ getType,
42
+ toStringVal,
43
+ isStream,
44
+ isBlobLike,
45
+ isPairArrayList,
46
+ };
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+
3
+ const { jar, client } = require("./client");
4
+ const { cleanGet, get, post, postFormData } = require("./methods");
5
+ const { makeDefaults } = require("./defaults");
6
+ const { setProxy } = require("./proxy");
7
+
8
+ module.exports = {
9
+ cleanGet,
10
+ get,
11
+ post,
12
+ postFormData,
13
+ jar,
14
+ setProxy,
15
+ makeDefaults,
16
+ client,
17
+ };
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+
3
+ const FormData = require("form-data");
4
+ const headersMod = require("../headers");
5
+ const getHeaders = headersMod.getHeaders || headersMod;
6
+ const { client } = require("./client");
7
+ const { cfg } = require("./config");
8
+ const { requestWithRetry } = require("./retry");
9
+ const {
10
+ getType,
11
+ toStringVal,
12
+ isStream,
13
+ isBlobLike,
14
+ isPairArrayList,
15
+ } = require("./helpers");
16
+
17
+ function cleanGet(url, ctx) {
18
+ return requestWithRetry(() => client.get(url, cfg()), 3, 1000, ctx);
19
+ }
20
+
21
+ function get(url, reqJar, qs, options, ctx, customHeader) {
22
+ const headers = getHeaders(url, options, ctx, customHeader);
23
+ return requestWithRetry(
24
+ () => client.get(url, cfg({ reqJar, headers, params: qs })),
25
+ 3,
26
+ 1000,
27
+ ctx
28
+ );
29
+ }
30
+
31
+ function post(url, reqJar, form, options, ctx, customHeader) {
32
+ const headers = getHeaders(url, options, ctx, customHeader);
33
+ const ct = String(
34
+ headers["Content-Type"] || headers["content-type"] || "application/x-www-form-urlencoded"
35
+ ).toLowerCase();
36
+ let data;
37
+ if (ct.includes("json")) {
38
+ data = JSON.stringify(form || {});
39
+ headers["Content-Type"] = "application/json";
40
+ } else {
41
+ const p = new URLSearchParams();
42
+ if (form && typeof form === "object") {
43
+ for (const k of Object.keys(form)) {
44
+ let v = form[k];
45
+ if (isPairArrayList(v)) {
46
+ for (const [kk, vv] of v) p.append(`${k}[${kk}]`, toStringVal(vv));
47
+ continue;
48
+ }
49
+ if (Array.isArray(v)) {
50
+ for (const x of v) {
51
+ if (Array.isArray(x) && x.length === 2 && typeof x[1] !== "object")
52
+ p.append(k, toStringVal(x[1]));
53
+ else p.append(k, toStringVal(x));
54
+ }
55
+ continue;
56
+ }
57
+ if (getType(v) === "Object") v = JSON.stringify(v);
58
+ p.append(k, toStringVal(v));
59
+ }
60
+ }
61
+ data = p.toString();
62
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
63
+ }
64
+ return requestWithRetry(
65
+ () => client.post(url, data, cfg({ reqJar, headers })),
66
+ 3,
67
+ 1000,
68
+ ctx
69
+ );
70
+ }
71
+
72
+ async function postFormData(url, reqJar, form, qs, options, ctx) {
73
+ const fd = new FormData();
74
+ if (form && typeof form === "object") {
75
+ for (const k of Object.keys(form)) {
76
+ const v = form[k];
77
+ if (v === undefined || v === null) continue;
78
+ if (isPairArrayList(v)) {
79
+ for (const [kk, vv] of v)
80
+ fd.append(
81
+ `${k}[${kk}]`,
82
+ typeof vv === "object" && !Buffer.isBuffer(vv) && !isStream(vv)
83
+ ? JSON.stringify(vv)
84
+ : vv
85
+ );
86
+ continue;
87
+ }
88
+ if (Array.isArray(v)) {
89
+ for (const x of v) {
90
+ if (
91
+ Array.isArray(x) &&
92
+ x.length === 2 &&
93
+ x[1] &&
94
+ typeof x[1] === "object" &&
95
+ !Buffer.isBuffer(x[1]) &&
96
+ !isStream(x[1])
97
+ ) {
98
+ fd.append(k, x[0], x[1]);
99
+ } else if (
100
+ Array.isArray(x) &&
101
+ x.length === 2 &&
102
+ typeof x[1] !== "object"
103
+ ) {
104
+ fd.append(k, toStringVal(x[1]));
105
+ } else if (
106
+ x &&
107
+ typeof x === "object" &&
108
+ "value" in x &&
109
+ "options" in x
110
+ ) {
111
+ fd.append(k, x.value, x.options || {});
112
+ } else if (isStream(x) || Buffer.isBuffer(x) || typeof x === "string") {
113
+ fd.append(k, x);
114
+ } else if (isBlobLike(x)) {
115
+ const buf = Buffer.from(await x.arrayBuffer());
116
+ fd.append(k, buf, {
117
+ filename: x.name || k,
118
+ contentType: x.type || undefined,
119
+ });
120
+ } else {
121
+ fd.append(k, JSON.stringify(x));
122
+ }
123
+ }
124
+ continue;
125
+ }
126
+ if (v && typeof v === "object" && "value" in v && "options" in v) {
127
+ fd.append(k, v.value, v.options || {});
128
+ continue;
129
+ }
130
+ if (isStream(v) || Buffer.isBuffer(v) || typeof v === "string") {
131
+ fd.append(k, v);
132
+ continue;
133
+ }
134
+ if (isBlobLike(v)) {
135
+ const buf = Buffer.from(await v.arrayBuffer());
136
+ fd.append(k, buf, {
137
+ filename: v.name || k,
138
+ contentType: v.type || undefined,
139
+ });
140
+ continue;
141
+ }
142
+ if (typeof v === "number" || typeof v === "boolean") {
143
+ fd.append(k, toStringVal(v));
144
+ continue;
145
+ }
146
+ fd.append(k, JSON.stringify(v));
147
+ }
148
+ }
149
+ const headers = { ...getHeaders(url, options, ctx), ...fd.getHeaders() };
150
+ return requestWithRetry(
151
+ () => client.post(url, fd, cfg({ reqJar, headers, params: qs })),
152
+ 3,
153
+ 1000,
154
+ ctx
155
+ );
156
+ }
157
+
158
+ module.exports = {
159
+ cleanGet,
160
+ get,
161
+ post,
162
+ postFormData,
163
+ };
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+
3
+ const { HttpsProxyAgent } = require("https-proxy-agent");
4
+ const { client } = require("./client");
5
+
6
+ function setProxy(proxyUrl) {
7
+ if (!proxyUrl) {
8
+ client.defaults.httpAgent = undefined;
9
+ client.defaults.httpsAgent = undefined;
10
+ client.defaults.proxy = false;
11
+ return;
12
+ }
13
+ const agent = new HttpsProxyAgent(proxyUrl);
14
+ client.defaults.httpAgent = agent;
15
+ client.defaults.httpsAgent = agent;
16
+ client.defaults.proxy = false;
17
+ }
18
+
19
+ module.exports = {
20
+ setProxy,
21
+ };
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+
3
+ const { delay } = require("./client");
4
+
5
+ async function requestWithRetry(fn, retries = 3, baseDelay = 1000, ctx) {
6
+ let lastError;
7
+ const emit = (event, payload) => {
8
+ try {
9
+ if (ctx && ctx._emitter && typeof ctx._emitter.emit === "function") {
10
+ ctx._emitter.emit(event, payload);
11
+ }
12
+ } catch {}
13
+ };
14
+ for (let i = 0; i < retries; i++) {
15
+ try {
16
+ return await fn();
17
+ } catch (e) {
18
+ lastError = e;
19
+
20
+ if (
21
+ e?.code === "ERR_INVALID_CHAR" ||
22
+ (e?.message && e.message.includes("Invalid character in header"))
23
+ ) {
24
+ const err = new Error(
25
+ "Invalid header content detected. Request aborted to prevent crash."
26
+ );
27
+ err.error = "Invalid header content";
28
+ err.originalError = e;
29
+ err.code = "ERR_INVALID_CHAR";
30
+ return Promise.reject(err);
31
+ }
32
+
33
+ const status = e?.response?.status || e?.statusCode || 0;
34
+ const url = e?.config?.url || "";
35
+ const method = String(e?.config?.method || "").toUpperCase();
36
+ if (status === 429) {
37
+ emit("rateLimit", { status, url, method });
38
+ }
39
+ if (status >= 400 && status < 500 && status !== 429) {
40
+ return e.response || Promise.reject(e);
41
+ }
42
+ if (i === retries - 1) {
43
+ return e.response || Promise.reject(e);
44
+ }
45
+ const netCode = e?.code || "";
46
+ const msg = e && e.message ? e.message : String(e || "");
47
+ if (
48
+ !status &&
49
+ (netCode === "UND_ERR_CONNECT_TIMEOUT" ||
50
+ netCode === "ETIMEDOUT" ||
51
+ netCode === "ECONNRESET" ||
52
+ netCode === "ECONNREFUSED" ||
53
+ netCode === "ENOTFOUND" ||
54
+ /timeout|connect timeout|network error|fetch failed/i.test(msg))
55
+ ) {
56
+ emit("networkError", {
57
+ code: netCode,
58
+ message: msg,
59
+ url,
60
+ method,
61
+ });
62
+ }
63
+
64
+ const backoffDelay = Math.min(
65
+ baseDelay * Math.pow(2, i) + Math.floor(Math.random() * 200),
66
+ 30000
67
+ );
68
+ await delay(backoffDelay);
69
+ }
70
+ }
71
+ const finalError = lastError || new Error("Request failed after retries");
72
+ return Promise.reject(finalError);
73
+ }
74
+
75
+ module.exports = {
76
+ requestWithRetry,
77
+ };
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+
3
+ function sanitizeHeaderValue(value) {
4
+ if (value === null || value === undefined) return "";
5
+ const str = String(value);
6
+ return str.replace(/[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F\r\n]/g, "").trim();
7
+ }
8
+
9
+ function sanitizeHeaderName(name) {
10
+ if (!name || typeof name !== "string") return "";
11
+ return name.replace(/[^\x21-\x7E]/g, "").trim();
12
+ }
13
+
14
+ function sanitizeHeaders(headers) {
15
+ if (!headers || typeof headers !== "object") return {};
16
+ const sanitized = {};
17
+ for (const [key, value] of Object.entries(headers)) {
18
+ const sanitizedKey = sanitizeHeaderName(key);
19
+ if (!sanitizedKey) continue;
20
+
21
+ if (Array.isArray(value)) continue;
22
+ if (value !== null && typeof value === "object") continue;
23
+ if (typeof value === "function") continue;
24
+
25
+ if (typeof value === "string") {
26
+ const trimmed = value.trim();
27
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
28
+ try {
29
+ const parsed = JSON.parse(trimmed);
30
+ if (Array.isArray(parsed)) continue;
31
+ } catch {
32
+ // continue with normal sanitization
33
+ }
34
+ }
35
+ }
36
+
37
+ const sanitizedValue = sanitizeHeaderValue(value);
38
+ if (sanitizedValue !== "") {
39
+ sanitized[sanitizedKey] = sanitizedValue;
40
+ }
41
+ }
42
+ return sanitized;
43
+ }
44
+
45
+ module.exports = {
46
+ sanitizeHeaderValue,
47
+ sanitizeHeaderName,
48
+ sanitizeHeaders,
49
+ };
@@ -0,0 +1,202 @@
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
+ };