fca-nx 6.6.6

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 (196) hide show
  1. package/LICENCE +21 -0
  2. package/README.md +446 -0
  3. package/e2ee/config.json +0 -0
  4. package/e2ee/crypto.js +173 -0
  5. package/e2ee/index.js +1032 -0
  6. package/e2ee/proto/ArmadilloApplication.proto +281 -0
  7. package/e2ee/proto/ArmadilloICDC.proto +14 -0
  8. package/e2ee/proto/ConsumerApplication.proto +232 -0
  9. package/e2ee/proto/MessageApplication.proto +82 -0
  10. package/e2ee/proto/MessageTransport.proto +77 -0
  11. package/e2ee/proto/WACommon.proto +66 -0
  12. package/e2ee/proto/WAMediaTransport.proto +176 -0
  13. package/e2ee/protocol.js +196 -0
  14. package/e2ee/ratchet.js +219 -0
  15. package/e2ee/store.js +182 -0
  16. package/e2ee/vendor/fb-e2ee.cjs +9159 -0
  17. package/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  18. package/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  19. package/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  20. package/e2ee/vendor/proto/MessageApplication.proto +82 -0
  21. package/e2ee/vendor/proto/MessageTransport.proto +77 -0
  22. package/e2ee/vendor/proto/WACommon.proto +66 -0
  23. package/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  24. package/func/checkUpdate.js +7 -0
  25. package/func/logAdapter.js +33 -0
  26. package/func/logger.js +134 -0
  27. package/index.js +22 -0
  28. package/module/config.js +45 -0
  29. package/module/login.js +183 -0
  30. package/module/loginHelper.js +1382 -0
  31. package/module/options.js +52 -0
  32. package/package.json +101 -0
  33. package/src/api/action/addExternalModule.js +25 -0
  34. package/src/api/action/addFriend.js +145 -0
  35. package/src/api/action/changeAvatar.js +137 -0
  36. package/src/api/action/changeBio.js +75 -0
  37. package/src/api/action/changeCover.js +277 -0
  38. package/src/api/action/enableAutoSaveAppState.js +73 -0
  39. package/src/api/action/getCurrentUserID.js +7 -0
  40. package/src/api/action/handleFriendRequest.js +57 -0
  41. package/src/api/action/logout.js +76 -0
  42. package/src/api/action/refreshFb_dtsg.js +48 -0
  43. package/src/api/action/setPostReaction.js +106 -0
  44. package/src/api/action/unfriend.js +54 -0
  45. package/src/api/http/httpGet.js +46 -0
  46. package/src/api/http/httpPost.js +52 -0
  47. package/src/api/http/postFormData.js +47 -0
  48. package/src/api/messaging/addUserToGroup.js +68 -0
  49. package/src/api/messaging/changeAdminStatus.js +126 -0
  50. package/src/api/messaging/changeArchivedStatus.js +55 -0
  51. package/src/api/messaging/changeBlockedStatus.js +48 -0
  52. package/src/api/messaging/changeGroupImage.js +91 -0
  53. package/src/api/messaging/changeNickname.js +70 -0
  54. package/src/api/messaging/changeThreadColor.js +79 -0
  55. package/src/api/messaging/changeThreadEmoji.js +111 -0
  56. package/src/api/messaging/createNewGroup.js +88 -0
  57. package/src/api/messaging/createPoll.js +46 -0
  58. package/src/api/messaging/createThemeAI.js +98 -0
  59. package/src/api/messaging/deleteMessage.js +136 -0
  60. package/src/api/messaging/deleteThread.js +56 -0
  61. package/src/api/messaging/editMessage.js +90 -0
  62. package/src/api/messaging/forwardAttachment.js +57 -0
  63. package/src/api/messaging/forwardMessage.js +134 -0
  64. package/src/api/messaging/getEmojiUrl.js +29 -0
  65. package/src/api/messaging/getFriendsList.js +82 -0
  66. package/src/api/messaging/getMessage.js +829 -0
  67. package/src/api/messaging/getThemePictures.js +62 -0
  68. package/src/api/messaging/handleMessageRequest.js +65 -0
  69. package/src/api/messaging/markAsDelivered.js +57 -0
  70. package/src/api/messaging/markAsRead.js +88 -0
  71. package/src/api/messaging/markAsReadAll.js +49 -0
  72. package/src/api/messaging/markAsSeen.js +61 -0
  73. package/src/api/messaging/muteThread.js +50 -0
  74. package/src/api/messaging/pinMessage.js +115 -0
  75. package/src/api/messaging/removeUserFromGroup.js +62 -0
  76. package/src/api/messaging/resolvePhotoUrl.js +43 -0
  77. package/src/api/messaging/scheduler.js +264 -0
  78. package/src/api/messaging/searchForThread.js +53 -0
  79. package/src/api/messaging/sendBroadcast.js +93 -0
  80. package/src/api/messaging/sendMessage.js +269 -0
  81. package/src/api/messaging/sendTypingIndicator.js +74 -0
  82. package/src/api/messaging/sessionGuard.js +208 -0
  83. package/src/api/messaging/setMessageReaction.js +95 -0
  84. package/src/api/messaging/setTitle.js +124 -0
  85. package/src/api/messaging/shareContact.js +49 -0
  86. package/src/api/messaging/threadColors.js +128 -0
  87. package/src/api/messaging/unsendMessage.js +81 -0
  88. package/src/api/messaging/uploadAttachment.js +523 -0
  89. package/src/api/socket/OldMessage.js +186 -0
  90. package/src/api/socket/core/connectMqtt.js +320 -0
  91. package/src/api/socket/core/emitAuth.js +103 -0
  92. package/src/api/socket/core/getSeqID.js +338 -0
  93. package/src/api/socket/core/getTaskResponseData.js +25 -0
  94. package/src/api/socket/core/parseDelta.js +387 -0
  95. package/src/api/socket/detail/buildStream.js +215 -0
  96. package/src/api/socket/detail/constants.js +28 -0
  97. package/src/api/socket/e2ee/crypto.js +173 -0
  98. package/src/api/socket/e2ee/e2ee/crypto.js +173 -0
  99. package/src/api/socket/e2ee/e2ee/index.js +421 -0
  100. package/src/api/socket/e2ee/e2ee/proto/ArmadilloApplication.proto +281 -0
  101. package/src/api/socket/e2ee/e2ee/proto/ArmadilloICDC.proto +14 -0
  102. package/src/api/socket/e2ee/e2ee/proto/ConsumerApplication.proto +232 -0
  103. package/src/api/socket/e2ee/e2ee/proto/MessageApplication.proto +82 -0
  104. package/src/api/socket/e2ee/e2ee/proto/MessageTransport.proto +77 -0
  105. package/src/api/socket/e2ee/e2ee/proto/WACommon.proto +66 -0
  106. package/src/api/socket/e2ee/e2ee/proto/WAMediaTransport.proto +176 -0
  107. package/src/api/socket/e2ee/e2ee/protocol.js +196 -0
  108. package/src/api/socket/e2ee/e2ee/ratchet.js +219 -0
  109. package/src/api/socket/e2ee/e2ee/store.js +182 -0
  110. package/src/api/socket/e2ee/e2ee/vendor/fb-e2ee.cjs +9162 -0
  111. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  112. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  113. package/src/api/socket/e2ee/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  114. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageApplication.proto +82 -0
  115. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageTransport.proto +77 -0
  116. package/src/api/socket/e2ee/e2ee/vendor/proto/WACommon.proto +66 -0
  117. package/src/api/socket/e2ee/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  118. package/src/api/socket/e2ee/index.js +437 -0
  119. package/src/api/socket/e2ee/proto/ArmadilloApplication.proto +281 -0
  120. package/src/api/socket/e2ee/proto/ArmadilloICDC.proto +14 -0
  121. package/src/api/socket/e2ee/proto/ConsumerApplication.proto +232 -0
  122. package/src/api/socket/e2ee/proto/MessageApplication.proto +82 -0
  123. package/src/api/socket/e2ee/proto/MessageTransport.proto +77 -0
  124. package/src/api/socket/e2ee/proto/WACommon.proto +66 -0
  125. package/src/api/socket/e2ee/proto/WAMediaTransport.proto +176 -0
  126. package/src/api/socket/e2ee/protocol.js +196 -0
  127. package/src/api/socket/e2ee/ratchet.js +219 -0
  128. package/src/api/socket/e2ee/store.js +182 -0
  129. package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +9162 -0
  130. package/src/api/socket/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  131. package/src/api/socket/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  132. package/src/api/socket/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  133. package/src/api/socket/e2ee/vendor/proto/MessageApplication.proto +82 -0
  134. package/src/api/socket/e2ee/vendor/proto/MessageTransport.proto +77 -0
  135. package/src/api/socket/e2ee/vendor/proto/WACommon.proto +66 -0
  136. package/src/api/socket/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  137. package/src/api/socket/listenE2EE.js +75 -0
  138. package/src/api/socket/listenMqtt.js +551 -0
  139. package/src/api/socket/middleware/index.js +216 -0
  140. package/src/api/socket/sendMessage.js +309 -0
  141. package/src/api/socket/sendMessageMqtt.js +69 -0
  142. package/src/api/threads/getThreadHistory.js +664 -0
  143. package/src/api/threads/getThreadInfo.js +296 -0
  144. package/src/api/threads/getThreadList.js +293 -0
  145. package/src/api/threads/getThreadPictures.js +78 -0
  146. package/src/api/users/getUserID.js +65 -0
  147. package/src/api/users/getUserInfo.js +402 -0
  148. package/src/api/users/getUserInfoV2.js +911 -0
  149. package/src/app/MessengerBot.js +209 -0
  150. package/src/app/MessengerContext.js +32 -0
  151. package/src/app/createFcaClient.js +139 -0
  152. package/src/app/threadInfoRealtimeSync.js +284 -0
  153. package/src/core/sendReqMqtt.js +96 -0
  154. package/src/database/helpers.js +53 -0
  155. package/src/database/models/index.js +88 -0
  156. package/src/database/models/thread.js +50 -0
  157. package/src/database/models/user.js +46 -0
  158. package/src/database/threadData.js +94 -0
  159. package/src/database/userData.js +98 -0
  160. package/src/remote/remoteClient.js +123 -0
  161. package/src/utils/broadcast.js +51 -0
  162. package/src/utils/client.js +10 -0
  163. package/src/utils/clientIdentity.js +118 -0
  164. package/src/utils/constants.js +23 -0
  165. package/src/utils/cookies.js +68 -0
  166. package/src/utils/format/attachment.js +357 -0
  167. package/src/utils/format/cookie.js +9 -0
  168. package/src/utils/format/date.js +50 -0
  169. package/src/utils/format/decode.js +44 -0
  170. package/src/utils/format/delta.js +194 -0
  171. package/src/utils/format/ids.js +64 -0
  172. package/src/utils/format/index.js +64 -0
  173. package/src/utils/format/message.js +88 -0
  174. package/src/utils/format/presence.js +132 -0
  175. package/src/utils/format/readTyp.js +44 -0
  176. package/src/utils/format/thread.js +42 -0
  177. package/src/utils/format/utils.js +141 -0
  178. package/src/utils/headers.js +124 -0
  179. package/src/utils/logger.js +144 -0
  180. package/src/utils/loginParser/autoLogin.js +125 -0
  181. package/src/utils/loginParser/helpers.js +43 -0
  182. package/src/utils/loginParser/index.js +10 -0
  183. package/src/utils/loginParser/parseAndCheckLogin.js +220 -0
  184. package/src/utils/loginParser/textUtils.js +28 -0
  185. package/src/utils/request/client.js +26 -0
  186. package/src/utils/request/config.js +29 -0
  187. package/src/utils/request/defaults.js +46 -0
  188. package/src/utils/request/helpers.js +46 -0
  189. package/src/utils/request/index.js +17 -0
  190. package/src/utils/request/methods.js +163 -0
  191. package/src/utils/request/proxy.js +46 -0
  192. package/src/utils/request/retry.js +77 -0
  193. package/src/utils/request/sanitize.js +49 -0
  194. package/src/utils/utils.js +686 -0
  195. package/src/utils/versionCheck.js +47 -0
  196. package/src/vendor/fca-unofficial/index.js +11 -0
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+
3
+ function getType(obj) {
4
+ return Object.prototype.toString.call(obj).slice(8, -1);
5
+ }
6
+
7
+ function formatID(id) {
8
+ if (id != undefined && id != null) return id.replace(/(fb)?id[:.]/, "");
9
+ else return id;
10
+ }
11
+
12
+ function padZeros(val, len) {
13
+ val = String(val);
14
+ len = len || 2;
15
+ while (val.length < len) val = "0" + val;
16
+ return val;
17
+ }
18
+
19
+ function arrayToObject(arr, getKey, getValue) {
20
+ return arr.reduce(function (acc, val) {
21
+ acc[getKey(val)] = getValue(val);
22
+ return acc;
23
+ }, {});
24
+ }
25
+
26
+ function arrToForm(form) {
27
+ return arrayToObject(
28
+ form,
29
+ function (v) {
30
+ return v.name;
31
+ },
32
+ function (v) {
33
+ return v.val;
34
+ },
35
+ );
36
+ }
37
+
38
+ function getData_Path(Obj, Arr, Stt) {
39
+ if (Arr.length === 0 && Obj != undefined) {
40
+ return Obj;
41
+ } else if (Obj == undefined) {
42
+ return Stt;
43
+ }
44
+ const head = Arr[0];
45
+ if (head == undefined) {
46
+ return Stt;
47
+ }
48
+ const tail = Arr.slice(1);
49
+ return getData_Path(Obj[head], tail, Stt++);
50
+ }
51
+
52
+ function setData_Path(obj, path, value) {
53
+ if (!path.length) {
54
+ return obj;
55
+ }
56
+ const currentKey = path[0];
57
+ let currentObj = obj[currentKey];
58
+
59
+ if (!currentObj) {
60
+ obj[currentKey] = value;
61
+ currentObj = obj[currentKey];
62
+ }
63
+ path.shift();
64
+ if (!path.length) {
65
+ currentObj = value;
66
+ } else {
67
+ currentObj = setData_Path(currentObj, path, value);
68
+ }
69
+
70
+ return obj;
71
+ }
72
+
73
+ function getPaths(obj, parentPath = []) {
74
+ let paths = [];
75
+ for (let prop in obj) {
76
+ if (typeof obj[prop] === "object") {
77
+ paths = paths.concat(getPaths(obj[prop], [...parentPath, prop]));
78
+ } else {
79
+ paths.push([...parentPath, prop]);
80
+ }
81
+ }
82
+ return paths;
83
+ }
84
+
85
+ function cleanHTML(text) {
86
+ text = text.replace(
87
+ /(<br>)|(<\/?i>)|(<\/?em>)|(<\/?b>)|(!?~)|(&amp;)|(&#039;)|(&lt;)|(&gt;)|(&quot;)/g,
88
+ (match) => {
89
+ switch (match) {
90
+ case "<br>":
91
+ return "\n";
92
+ case "<i>":
93
+ case "<em>":
94
+ case "</i>":
95
+ case "</em>":
96
+ return "*";
97
+ case "<b>":
98
+ case "</b>":
99
+ return "**";
100
+ case "~!":
101
+ case "!~":
102
+ return "||";
103
+ case "&amp;":
104
+ return "&";
105
+ case "&#039;":
106
+ return "'";
107
+ case "&lt;":
108
+ return "<";
109
+ case "&gt;":
110
+ return ">";
111
+ case "&quot;":
112
+ return '"';
113
+ }
114
+ },
115
+ );
116
+ return text;
117
+ }
118
+
119
+ function getCurrentTimestamp() {
120
+ const date = new Date();
121
+ const unixTime = date.getTime();
122
+ return unixTime;
123
+ }
124
+
125
+ function getSignatureID() {
126
+ return Math.floor(Math.random() * 2147483648).toString(16);
127
+ }
128
+
129
+ module.exports = {
130
+ getType,
131
+ formatID,
132
+ padZeros,
133
+ arrayToObject,
134
+ arrToForm,
135
+ getData_Path,
136
+ setData_Path,
137
+ getPaths,
138
+ cleanHTML,
139
+ getCurrentTimestamp,
140
+ getSignatureID,
141
+ };
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+
3
+ const { getIdentity } = require("./clientIdentity");
4
+
5
+ // Sanitize header value to remove invalid characters
6
+ function sanitizeHeaderValue(value) {
7
+ if (value === null || value === undefined) return "";
8
+ let str = String(value);
9
+
10
+ // Remove array-like strings (e.g., "["performAutoLogin"]")
11
+ // This handles cases where arrays were accidentally stringified
12
+ if (str.trim().startsWith("[") && str.trim().endsWith("]")) {
13
+ // Try to detect if it's a stringified array and remove it
14
+ try {
15
+ const parsed = JSON.parse(str);
16
+ if (Array.isArray(parsed)) {
17
+ // If it's an array, return empty string (invalid header value)
18
+ return "";
19
+ }
20
+ } catch {
21
+ // Not valid JSON, continue with normal sanitization
22
+ }
23
+ }
24
+
25
+ // Remove invalid characters for HTTP headers:
26
+ // - Control characters (0x00-0x1F, except HTAB 0x09)
27
+ // - DEL character (0x7F)
28
+ // - Newlines and carriage returns
29
+ // - Square brackets (often indicate array stringification issues)
30
+ str = str.replace(/[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F\r\n\[\]]/g, "").trim();
31
+
32
+ return str;
33
+ }
34
+
35
+ // Sanitize header name to ensure it's valid
36
+ function sanitizeHeaderName(name) {
37
+ if (!name || typeof name !== "string") return "";
38
+ // Remove invalid characters for HTTP header names
39
+ return name.replace(/[^\x21-\x7E]/g, "").trim();
40
+ }
41
+
42
+ function getHeaders(url, options, ctx, customHeader) {
43
+ const u = new URL(url);
44
+ // Resolve one internally-consistent identity (UA + matching client hints)
45
+ // instead of hard-coding a browser version here that could contradict
46
+ // what other subsystems (MQTT, upload) claim to be.
47
+ const identity = getIdentity(options?.userAgent);
48
+ const ua = identity.userAgent;
49
+ const referer = options?.referer || "https://www.facebook.com/";
50
+ const origin = referer.replace(/\/+$/, "");
51
+ const contentType = options?.contentType || "application/x-www-form-urlencoded";
52
+ const acceptLang = options?.acceptLanguage || identity.acceptLanguage;
53
+ const headers = {
54
+ Host: sanitizeHeaderValue(u.host),
55
+ Origin: sanitizeHeaderValue(origin),
56
+ Referer: sanitizeHeaderValue(referer),
57
+ "User-Agent": sanitizeHeaderValue(ua),
58
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,application/json;q=0.8,*/*;q=0.7",
59
+ "Accept-Language": sanitizeHeaderValue(acceptLang),
60
+ "Accept-Encoding": "gzip, deflate, br",
61
+ "Content-Type": sanitizeHeaderValue(contentType),
62
+ Connection: "keep-alive",
63
+ DNT: "1",
64
+ "Upgrade-Insecure-Requests": "1",
65
+ "Sec-Fetch-Site": "same-origin",
66
+ "Sec-Fetch-Mode": "cors",
67
+ "Sec-Fetch-Dest": "empty",
68
+ "X-Requested-With": "XMLHttpRequest",
69
+ Pragma: "no-cache",
70
+ "Cache-Control": "no-cache"
71
+ };
72
+ // Only attach Chromium client hints when the identity actually has them
73
+ // (a non-Chrome UA supplied by the caller intentionally omits these, so we
74
+ // never claim client hints that contradict the User-Agent string).
75
+ if (identity.secChUa) headers["sec-ch-ua"] = identity.secChUa;
76
+ if (identity.secChUaMobile) headers["sec-ch-ua-mobile"] = identity.secChUaMobile;
77
+ if (identity.secChUaPlatform) headers["sec-ch-ua-platform"] = identity.secChUaPlatform;
78
+ if (identity.secChUaArch) headers["sec-ch-ua-arch"] = identity.secChUaArch;
79
+ if (identity.secChUaBitness) headers["sec-ch-ua-bitness"] = identity.secChUaBitness;
80
+ if (identity.secChUaFullVersionList) headers["sec-ch-ua-full-version-list"] = identity.secChUaFullVersionList;
81
+ if (identity.secChUaPlatformVersion) headers["sec-ch-ua-platform-version"] = identity.secChUaPlatformVersion;
82
+ if (ctx?.region) {
83
+ const regionValue = sanitizeHeaderValue(ctx.region);
84
+ if (regionValue) headers["X-MSGR-Region"] = regionValue;
85
+ }
86
+ if (customHeader && typeof customHeader === "object") {
87
+ // Filter customHeader to only include valid HTTP header values (strings, numbers, booleans)
88
+ // Exclude functions, objects, arrays, and other non-serializable values
89
+ for (const [key, value] of Object.entries(customHeader)) {
90
+ // Skip null, undefined, functions, objects, and arrays
91
+ if (value === null || value === undefined || typeof value === "function") {
92
+ continue;
93
+ }
94
+ if (typeof value === "object") {
95
+ // Arrays are objects in JavaScript, so check for arrays explicitly
96
+ if (Array.isArray(value)) {
97
+ continue;
98
+ }
99
+ // Skip plain objects (but allow null which is already handled above)
100
+ continue;
101
+ }
102
+ // Only allow strings, numbers, and booleans - convert to string and sanitize
103
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
104
+ const sanitizedKey = sanitizeHeaderName(key);
105
+ const sanitizedValue = sanitizeHeaderValue(value);
106
+ if (sanitizedKey && sanitizedValue !== "") {
107
+ headers[sanitizedKey] = sanitizedValue;
108
+ }
109
+ }
110
+ }
111
+ }
112
+ // Final pass: sanitize all header values to ensure no invalid characters
113
+ const sanitizedHeaders = {};
114
+ for (const [key, value] of Object.entries(headers)) {
115
+ const sanitizedKey = sanitizeHeaderName(key);
116
+ const sanitizedValue = sanitizeHeaderValue(value);
117
+ if (sanitizedKey && sanitizedValue !== "") {
118
+ sanitizedHeaders[sanitizedKey] = sanitizedValue;
119
+ }
120
+ }
121
+ return sanitizedHeaders;
122
+ }
123
+
124
+ module.exports = { getHeaders };
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+
3
+ const C = {
4
+ reset: '\x1b[0m',
5
+ bold: '\x1b[1m',
6
+ dim: '\x1b[2m',
7
+ black: '\x1b[30m',
8
+ red: '\x1b[31m',
9
+ green: '\x1b[32m',
10
+ yellow: '\x1b[33m',
11
+ blue: '\x1b[34m',
12
+ magenta: '\x1b[35m',
13
+ cyan: '\x1b[36m',
14
+ white: '\x1b[37m',
15
+ bBlack: '\x1b[90m',
16
+ bRed: '\x1b[91m',
17
+ bGreen: '\x1b[92m',
18
+ bYellow: '\x1b[93m',
19
+ bBlue: '\x1b[94m',
20
+ bMagenta: '\x1b[95m',
21
+ bCyan: '\x1b[96m',
22
+ bWhite: '\x1b[97m',
23
+ bgRed: '\x1b[41m',
24
+ bgGreen: '\x1b[42m',
25
+ bgYellow: '\x1b[43m',
26
+ bgBlue: '\x1b[44m',
27
+ bgMagenta:'\x1b[45m',
28
+ bgCyan: '\x1b[46m',
29
+ };
30
+
31
+ function ts() {
32
+ const d = new Date();
33
+ const hh = String(d.getHours()).padStart(2, '0');
34
+ const mm = String(d.getMinutes()).padStart(2, '0');
35
+ const ss = String(d.getSeconds()).padStart(2, '0');
36
+ const ms = String(d.getMilliseconds()).padStart(3, '0');
37
+ return `${C.dim}${hh}:${mm}:${ss}.${ms}${C.reset}`;
38
+ }
39
+
40
+ function tag(label, color) {
41
+ return `${color}${C.bold}[ ${label} ]${C.reset}`;
42
+ }
43
+
44
+ function fmt(msg) {
45
+ if (typeof msg === 'object' && msg !== null) {
46
+ try { return JSON.stringify(msg, null, 2); } catch (_) { return String(msg); }
47
+ }
48
+ return String(msg);
49
+ }
50
+
51
+ const logger = {
52
+ info(label, msg) {
53
+ if (msg === undefined) { msg = label; label = 'INFO'; }
54
+ console.log(`${ts()} ${tag(label, C.bCyan)} ${C.white}${fmt(msg)}${C.reset}`);
55
+ },
56
+ success(label, msg) {
57
+ if (msg === undefined) { msg = label; label = 'OK'; }
58
+ console.log(`${ts()} ${tag(label, C.bGreen)} ${C.bWhite}${fmt(msg)}${C.reset}`);
59
+ },
60
+ warn(label, msg) {
61
+ if (msg === undefined) { msg = label; label = 'WARN'; }
62
+ console.warn(`${ts()} ${tag(label, C.bYellow)} ${C.yellow}${fmt(msg)}${C.reset}`);
63
+ },
64
+ error(label, msg) {
65
+ if (msg === undefined) { msg = label; label = 'ERR'; }
66
+ const body = msg instanceof Error ? msg.stack || msg.message : fmt(msg);
67
+ console.error(`${ts()} ${tag(label, C.bRed)} ${C.red}${body}${C.reset}`);
68
+ },
69
+ debug(label, msg) {
70
+ if (msg === undefined) { msg = label; label = 'DBG'; }
71
+ console.log(`${ts()} ${tag(label, C.bBlack)} ${C.dim}${fmt(msg)}${C.reset}`);
72
+ },
73
+ event(label, msg) {
74
+ if (msg === undefined) { msg = label; label = 'EVT'; }
75
+ console.log(`${ts()} ${tag(label, C.bMagenta)} ${C.magenta}${fmt(msg)}${C.reset}`);
76
+ },
77
+
78
+ banner(name, version, userID, botName, region, autoReconnect) {
79
+ const W = 56;
80
+ const bar = (l, r) => `${C.dim}${l}${'─'.repeat(W)}${r}${C.reset}`;
81
+ const mid = `${C.dim}│${C.reset}`;
82
+ const dot = `${C.bold}${C.bCyan}◈${C.reset}`;
83
+
84
+ const lbl = (s) => `${C.bold}${C.white}${s}${C.reset}`;
85
+ const ok = `${C.bGreen}✔${C.reset}`;
86
+ const warn = `${C.bYellow}⚠${C.reset}`;
87
+
88
+ const displayName = botName
89
+ ? `${C.bWhite}${C.bold}${botName}${C.reset} ${C.dim}${userID}${C.reset}`
90
+ : `${C.bYellow}${userID}${C.reset}`;
91
+
92
+ const reconnectStr = autoReconnect
93
+ ? `${ok} ${C.bGreen}Enabled${C.reset} ${C.dim}(MQTT + E2EE)${C.reset}`
94
+ : `${warn} ${C.bYellow}Disabled${C.reset}`;
95
+
96
+ const row = (content) => ` ${mid} ${content}`;
97
+
98
+ const rows = [
99
+ '',
100
+ ` ${bar('╭', '')}`,
101
+ ` ${mid}`,
102
+ ` ${mid} ${C.bold}${C.bCyan}⚡ ${name}${C.reset} ${C.dim}v${version}${C.reset}`,
103
+ ` ${mid}`,
104
+ ` ${bar('├', '')}`,
105
+ row(`${dot} ${lbl('Bot ')} ${displayName}`),
106
+ row(`${dot} ${lbl('Region ')} ${C.bGreen}${C.bold}${(region || 'AUTO').toUpperCase()}${C.reset}`),
107
+ row(`${dot} ${lbl('E2EE ')} ${ok} ${C.bGreen}Signal Protocol${C.reset}`),
108
+ row(`${dot} ${lbl('Transport ')} ${C.bCyan}MQTT${C.reset} ${C.dim}⟶${C.reset} ${C.bCyan}WebSocket${C.reset}`),
109
+ row(`${dot} ${lbl('Auto-Reconnect ')} ${reconnectStr}`),
110
+ ` ${bar('├', '')}`,
111
+ ` ${mid} ${C.dim} Developed by ${C.reset}${C.bold}${C.bMagenta}X${C.reset}`,
112
+ ` ${bar('╰', '')}`,
113
+ '',
114
+ ];
115
+ rows.forEach(r => console.log(r));
116
+ },
117
+
118
+ mqttSpinner: null,
119
+
120
+ startSpinner(region) {
121
+ const frames = ['⠋','⠙','⠹','⠸','⠴','⠦','⠧','⠇','⠏'];
122
+ let fi = 0;
123
+ const regionStr = region ? ` ${C.dim}${C.bCyan}[${region.toUpperCase()}]${C.reset}` : '';
124
+ process.stdout.write('\n');
125
+ logger.mqttSpinner = setInterval(() => {
126
+ const f = frames[fi++ % frames.length];
127
+ process.stdout.write(
128
+ `\r ${C.bold}${C.bCyan}${f}${C.reset} ${C.cyan}FCA-NX${C.reset} ` +
129
+ `${C.dim}connecting to MQTT${C.reset}${regionStr}${C.dim} ...${C.reset} `
130
+ );
131
+ }, 80);
132
+ },
133
+
134
+ stopSpinner() {
135
+ if (logger.mqttSpinner) {
136
+ clearInterval(logger.mqttSpinner);
137
+ logger.mqttSpinner = null;
138
+ }
139
+ process.stdout.write('\r\x1b[2K');
140
+ },
141
+ };
142
+
143
+ module.exports = logger;
144
+ module.exports.C = C;
@@ -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,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
+ };