@cexy/hoonfca 1.0.7 → 2.0.1

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 (191) hide show
  1. package/LICENSE +3 -0
  2. package/examples/login-with-cookies.js +102 -0
  3. package/examples/verify.js +70 -0
  4. package/index.js +2 -8
  5. package/package.json +82 -61
  6. package/src/{api/action → apis}/addExternalModule.js +24 -25
  7. package/src/apis/addUserToGroup.js +108 -0
  8. package/src/apis/changeAdminStatus.js +148 -0
  9. package/src/apis/changeArchivedStatus.js +61 -0
  10. package/src/apis/changeAvatar.js +103 -0
  11. package/src/apis/changeBio.js +69 -0
  12. package/src/apis/changeBlockedStatus.js +54 -0
  13. package/src/apis/changeGroupImage.js +136 -0
  14. package/src/apis/changeThreadColor.js +116 -0
  15. package/src/apis/changeThreadEmoji.js +53 -0
  16. package/src/apis/comment.js +207 -0
  17. package/src/apis/createAITheme.js +129 -0
  18. package/src/apis/createNewGroup.js +79 -0
  19. package/src/apis/createPoll.js +73 -0
  20. package/src/apis/deleteMessage.js +44 -0
  21. package/src/apis/deleteThread.js +52 -0
  22. package/src/apis/e2ee.js +17 -0
  23. package/src/apis/editMessage.js +70 -0
  24. package/src/apis/emoji.js +124 -0
  25. package/src/apis/fetchThemeData.js +82 -0
  26. package/src/apis/follow.js +81 -0
  27. package/src/apis/forwardMessage.js +52 -0
  28. package/src/apis/friend.js +243 -0
  29. package/src/apis/gcmember.js +122 -0
  30. package/src/apis/gcname.js +123 -0
  31. package/src/apis/gcrule.js +119 -0
  32. package/src/apis/getAccess.js +111 -0
  33. package/src/apis/getBotInfo.js +88 -0
  34. package/src/apis/getBotInitialData.js +43 -0
  35. package/src/apis/getFriendsList.js +79 -0
  36. package/src/apis/getMessage.js +423 -0
  37. package/src/apis/getTheme.js +95 -0
  38. package/src/apis/getThemeInfo.js +116 -0
  39. package/src/apis/getThreadHistory.js +239 -0
  40. package/src/apis/getThreadInfo.js +267 -0
  41. package/src/apis/getThreadList.js +232 -0
  42. package/src/apis/getThreadPictures.js +58 -0
  43. package/src/apis/getUserID.js +117 -0
  44. package/src/apis/getUserInfo.js +513 -0
  45. package/src/{api/users → apis}/getUserInfoV2.js +146 -134
  46. package/src/apis/handleMessageRequest.js +50 -0
  47. package/src/apis/httpGet.js +63 -0
  48. package/src/apis/httpPost.js +89 -0
  49. package/src/apis/httpPostFormData.js +69 -0
  50. package/src/apis/listenMqtt.js +1236 -0
  51. package/src/apis/listenSpeed.js +179 -0
  52. package/src/apis/logout.js +87 -0
  53. package/src/apis/markAsDelivered.js +47 -0
  54. package/src/{api/messaging → apis}/markAsRead.js +99 -88
  55. package/src/apis/markAsReadAll.js +40 -0
  56. package/src/apis/markAsSeen.js +70 -0
  57. package/src/apis/mqttDeltaValue.js +278 -0
  58. package/src/apis/muteThread.js +45 -0
  59. package/src/apis/nickname.js +132 -0
  60. package/src/apis/notes.js +163 -0
  61. package/src/apis/pinMessage.js +150 -0
  62. package/src/apis/produceMetaTheme.js +180 -0
  63. package/src/apis/realtime.js +182 -0
  64. package/src/apis/removeUserFromGroup.js +117 -0
  65. package/src/apis/resolvePhotoUrl.js +58 -0
  66. package/src/apis/searchForThread.js +154 -0
  67. package/src/apis/sendMessage.js +354 -0
  68. package/src/apis/sendMessageMqtt.js +249 -0
  69. package/src/apis/sendTypingIndicator.js +91 -0
  70. package/src/apis/setMessageReaction.js +27 -0
  71. package/src/apis/setMessageReactionMqtt.js +61 -0
  72. package/src/apis/setThreadTheme.js +260 -0
  73. package/src/apis/setThreadThemeMqtt.js +94 -0
  74. package/src/apis/share.js +107 -0
  75. package/src/apis/shareContact.js +66 -0
  76. package/src/apis/stickers.js +257 -0
  77. package/src/apis/story.js +181 -0
  78. package/src/apis/theme.js +233 -0
  79. package/src/apis/unfriend.js +47 -0
  80. package/src/apis/unsendMessage.js +17 -0
  81. package/src/engine/client.js +92 -0
  82. package/src/engine/models/buildAPI.js +152 -0
  83. package/src/engine/models/loginHelper.js +519 -0
  84. package/src/engine/models/setOptions.js +88 -0
  85. package/src/security/e2ee.js +109 -0
  86. package/src/types/index.d.ts +498 -0
  87. package/src/utils/antiSuspension.js +506 -0
  88. package/src/utils/auth-helpers.js +149 -0
  89. package/src/utils/autoReLogin.js +336 -0
  90. package/src/utils/axios.js +436 -0
  91. package/src/utils/cache.js +54 -0
  92. package/src/utils/clients.js +282 -0
  93. package/src/utils/constants.js +410 -23
  94. package/src/utils/formatters/data/formatAttachment.js +370 -0
  95. package/src/utils/formatters/data/formatDelta.js +109 -0
  96. package/src/utils/formatters/index.js +159 -0
  97. package/src/utils/formatters/value/formatCookie.js +91 -0
  98. package/src/utils/formatters/value/formatDate.js +36 -0
  99. package/src/utils/formatters/value/formatID.js +16 -0
  100. package/src/utils/formatters.js +1373 -0
  101. package/src/utils/headers.js +214 -99
  102. package/src/utils/index.js +153 -0
  103. package/src/utils/monitoring.js +333 -0
  104. package/src/utils/rateLimiter.js +319 -0
  105. package/src/utils/tokenRefresh.js +657 -0
  106. package/src/utils/user-agents.js +238 -0
  107. package/src/utils/validation.js +157 -0
  108. package/CHANGELOG.md +0 -181
  109. package/DOCS.md +0 -2636
  110. package/LICENSE-MIT +0 -21
  111. package/README.md +0 -632
  112. package/func/checkUpdate.js +0 -233
  113. package/func/logger.js +0 -48
  114. package/index.d.ts +0 -746
  115. package/module/config.js +0 -67
  116. package/module/login.js +0 -154
  117. package/module/loginHelper.js +0 -1034
  118. package/module/options.js +0 -54
  119. package/src/api/action/changeAvatar.js +0 -137
  120. package/src/api/action/changeBio.js +0 -75
  121. package/src/api/action/enableAutoSaveAppState.js +0 -73
  122. package/src/api/action/getCurrentUserID.js +0 -7
  123. package/src/api/action/handleFriendRequest.js +0 -57
  124. package/src/api/action/logout.js +0 -76
  125. package/src/api/action/refreshFb_dtsg.js +0 -48
  126. package/src/api/action/setPostReaction.js +0 -106
  127. package/src/api/action/unfriend.js +0 -54
  128. package/src/api/http/httpGet.js +0 -46
  129. package/src/api/http/httpPost.js +0 -52
  130. package/src/api/http/postFormData.js +0 -47
  131. package/src/api/messaging/addUserToGroup.js +0 -68
  132. package/src/api/messaging/changeAdminStatus.js +0 -122
  133. package/src/api/messaging/changeArchivedStatus.js +0 -55
  134. package/src/api/messaging/changeBlockedStatus.js +0 -48
  135. package/src/api/messaging/changeGroupImage.js +0 -90
  136. package/src/api/messaging/changeNickname.js +0 -70
  137. package/src/api/messaging/changeThreadColor.js +0 -79
  138. package/src/api/messaging/changeThreadEmoji.js +0 -106
  139. package/src/api/messaging/createNewGroup.js +0 -88
  140. package/src/api/messaging/createPoll.js +0 -43
  141. package/src/api/messaging/createThemeAI.js +0 -98
  142. package/src/api/messaging/deleteMessage.js +0 -56
  143. package/src/api/messaging/deleteThread.js +0 -56
  144. package/src/api/messaging/editMessage.js +0 -68
  145. package/src/api/messaging/forwardAttachment.js +0 -51
  146. package/src/api/messaging/getEmojiUrl.js +0 -29
  147. package/src/api/messaging/getFriendsList.js +0 -82
  148. package/src/api/messaging/getMessage.js +0 -829
  149. package/src/api/messaging/getThemePictures.js +0 -62
  150. package/src/api/messaging/handleMessageRequest.js +0 -65
  151. package/src/api/messaging/markAsDelivered.js +0 -57
  152. package/src/api/messaging/markAsReadAll.js +0 -49
  153. package/src/api/messaging/markAsSeen.js +0 -61
  154. package/src/api/messaging/muteThread.js +0 -50
  155. package/src/api/messaging/removeUserFromGroup.js +0 -106
  156. package/src/api/messaging/resolvePhotoUrl.js +0 -43
  157. package/src/api/messaging/scheduler.js +0 -264
  158. package/src/api/messaging/searchForThread.js +0 -52
  159. package/src/api/messaging/sendMessage.js +0 -272
  160. package/src/api/messaging/sendTypingIndicator.js +0 -67
  161. package/src/api/messaging/setMessageReaction.js +0 -76
  162. package/src/api/messaging/setTitle.js +0 -119
  163. package/src/api/messaging/shareContact.js +0 -49
  164. package/src/api/messaging/threadColors.js +0 -128
  165. package/src/api/messaging/unsendMessage.js +0 -81
  166. package/src/api/messaging/uploadAttachment.js +0 -94
  167. package/src/api/socket/core/connectMqtt.js +0 -255
  168. package/src/api/socket/core/emitAuth.js +0 -106
  169. package/src/api/socket/core/getSeqID.js +0 -40
  170. package/src/api/socket/core/getTaskResponseData.js +0 -22
  171. package/src/api/socket/core/markDelivery.js +0 -12
  172. package/src/api/socket/core/parseDelta.js +0 -391
  173. package/src/api/socket/detail/buildStream.js +0 -208
  174. package/src/api/socket/detail/constants.js +0 -24
  175. package/src/api/socket/listenMqtt.js +0 -364
  176. package/src/api/socket/middleware/index.js +0 -216
  177. package/src/api/threads/getThreadHistory.js +0 -664
  178. package/src/api/threads/getThreadInfo.js +0 -438
  179. package/src/api/threads/getThreadList.js +0 -293
  180. package/src/api/threads/getThreadPictures.js +0 -78
  181. package/src/api/users/getUserID.js +0 -65
  182. package/src/api/users/getUserInfo.js +0 -327
  183. package/src/core/sendReqMqtt.js +0 -96
  184. package/src/database/models/index.js +0 -87
  185. package/src/database/models/thread.js +0 -45
  186. package/src/database/models/user.js +0 -46
  187. package/src/database/threadData.js +0 -98
  188. package/src/database/userData.js +0 -89
  189. package/src/utils/client.js +0 -320
  190. package/src/utils/format.js +0 -1115
  191. package/src/utils/request.js +0 -305
@@ -1,89 +0,0 @@
1
- const { User } = require("./models");
2
-
3
- const validateUserID = userID => {
4
- if (typeof userID !== "string" && typeof userID !== "number") {
5
- throw new Error("Invalid userID: must be a string or number.");
6
- }
7
- return String(userID);
8
- };
9
- const validateData = data => {
10
- if (!data || typeof data !== "object" || Array.isArray(data)) {
11
- throw new Error("Invalid data: must be a non-empty object.");
12
- }
13
- };
14
-
15
- module.exports = function (bot) {
16
- return {
17
- async create(userID, data) {
18
- try {
19
- userID = validateUserID(userID);
20
- validateData(data);
21
- let user = await User.findOne({ where: { userID } });
22
- if (user) return { user: user.get(), created: false };
23
- const payload = Object.prototype.hasOwnProperty.call(data, "data") ? data : { data };
24
- user = await User.create({ userID, ...payload });
25
- return { user: user.get(), created: true };
26
- } catch (error) {
27
- throw new Error(`Failed to create user: ${error.message}`);
28
- }
29
- },
30
-
31
- async get(userID) {
32
- try {
33
- userID = validateUserID(userID);
34
- const user = await User.findOne({ where: { userID } });
35
- return user ? user.get() : null;
36
- } catch (error) {
37
- throw new Error(`Failed to get user: ${error.message}`);
38
- }
39
- },
40
-
41
- async update(userID, data) {
42
- try {
43
- userID = validateUserID(userID);
44
- validateData(data);
45
- const payload = Object.prototype.hasOwnProperty.call(data, "data") ? data : { data };
46
- const user = await User.findOne({ where: { userID } });
47
- if (user) {
48
- await user.update(payload);
49
- return { user: user.get(), created: false };
50
- } else {
51
- const newUser = await User.create({ userID, ...payload });
52
- return { user: newUser.get(), created: true };
53
- }
54
- } catch (error) {
55
- throw new Error(`Failed to update user: ${error.message}`);
56
- }
57
- },
58
-
59
- async del(userID) {
60
- try {
61
- if (!userID) throw new Error("userID is required and cannot be undefined");
62
- userID = validateUserID(userID);
63
- const result = await User.destroy({ where: { userID } });
64
- if (result === 0) throw new Error("No user found with the specified userID");
65
- return result;
66
- } catch (error) {
67
- throw new Error(`Failed to delete user: ${error.message}`);
68
- }
69
- },
70
-
71
- async delAll() {
72
- try {
73
- return await User.destroy({ where: {} });
74
- } catch (error) {
75
- throw new Error(`Failed to delete all users: ${error.message}`);
76
- }
77
- },
78
-
79
- async getAll(keys = null) {
80
- try {
81
- const attributes = typeof keys === "string" ? [keys] : Array.isArray(keys) ? keys : undefined;
82
- const users = await User.findAll({ attributes });
83
- return users.map(u => u.get());
84
- } catch (error) {
85
- throw new Error(`Failed to get all users: ${error.message}`);
86
- }
87
- }
88
- };
89
- };
@@ -1,320 +0,0 @@
1
- "use strict";
2
- const logger = require('../../func/logger');
3
-
4
- function saveCookies(jar) {
5
- return res => {
6
- try {
7
- const setCookie = res?.headers?.["set-cookie"];
8
- if (Array.isArray(setCookie) && setCookie.length) {
9
- const url = res?.request?.res?.responseUrl || (res?.config?.baseURL ? new URL(res.config.url || "/", res.config.baseURL).toString() : res?.config?.url || "https://www.facebook.com");
10
- for (const c of setCookie) {
11
- try {
12
- jar.setCookieSync(c, url);
13
- } catch { }
14
- }
15
- }
16
- } catch { }
17
- return res;
18
- };
19
- }
20
-
21
- function getAppState(jar) {
22
- if (!jar || typeof jar.getCookiesSync !== "function") return [];
23
- const urls = ["https://www.facebook.com", "https://www.messenger.com"];
24
- const all = urls.flatMap(u => {
25
- try { return jar.getCookiesSync(u) || []; } catch { return []; }
26
- });
27
- const seen = new Set();
28
- const out = [];
29
- for (const c of all) {
30
- const key = c.key || c.name;
31
- if (!key) continue;
32
- const id = key + "|" + (c.domain || "") + "|" + (c.path || "/");
33
- if (seen.has(id)) continue;
34
- seen.add(id);
35
- out.push({
36
- key,
37
- value: c.value,
38
- domain: c.domain || ".facebook.com",
39
- path: c.path || "/",
40
- hostOnly: !!c.hostOnly,
41
- creation: c.creation || new Date(),
42
- lastAccessed: c.lastAccessed || new Date(),
43
- secure: !!c.secure,
44
- httpOnly: !!c.httpOnly,
45
- expires: c.expires && c.expires !== "Infinity" ? c.expires : "Infinity"
46
- });
47
- }
48
- return out;
49
- }
50
-
51
- function makeParsable(html) {
52
- const raw = cleanXssi(String(html || ""));
53
- const split = raw.split(/\}\r?\n\s*\{/);
54
- if (split.length === 1) return raw;
55
- return "[" + split.join("},{") + "]";
56
- }
57
-
58
- function cleanXssi(t) {
59
- if (t == null) return "";
60
- let s = String(t);
61
- s = s.replace(/^[\uFEFF\xEF\xBB\xBF]+/, "");
62
- s = s.replace(/^\)\]\}',?\s*/, "");
63
- s = s.replace(/^\s*for\s*\(;;\);\s*/i, "");
64
- return s;
65
- }
66
-
67
- function parseAndCheckLogin(ctx, http, retryCount = 0) {
68
- const delay = ms => new Promise(r => setTimeout(r, ms));
69
- const headerOf = (headers, name) => {
70
- if (!headers) return;
71
- const k = Object.keys(headers).find(k => k.toLowerCase() === name.toLowerCase());
72
- return k ? headers[k] : undefined;
73
- };
74
- const buildUrl = cfg => {
75
- try {
76
- return cfg?.baseURL ? new URL(cfg.url || "/", cfg.baseURL).toString() : cfg?.url || "";
77
- } catch {
78
- return cfg?.url || "";
79
- }
80
- };
81
-
82
- const formatCookie = (arr, service) => {
83
- const n = String(arr?.[0] || "");
84
- const v = String(arr?.[1] || "");
85
- return `${n}=${v}; Domain=.${service}.com; Path=/; Secure`;
86
- };
87
-
88
- const maybeAutoLogin = async (resData, resConfig) => {
89
- // Prevent infinite loop if auto login is already in progress
90
- if (ctx.auto_login) {
91
- const e = new Error("Not logged in. Auto login already in progress.");
92
- e.error = "Not logged in.";
93
- e.res = resData;
94
- throw e;
95
- }
96
- // Check if performAutoLogin function exists
97
- if (typeof ctx.performAutoLogin !== "function") {
98
- const e = new Error("Not logged in. Auto login function not available.");
99
- e.error = "Not logged in.";
100
- e.res = resData;
101
- throw e;
102
- }
103
- // Set flag to prevent concurrent auto login attempts
104
- ctx.auto_login = true;
105
- logger("Login session expired, attempting auto login...", "warn");
106
-
107
- try {
108
- const ok = await ctx.performAutoLogin();
109
- if (ok) {
110
- logger("Auto login successful! Retrying request...", "info");
111
- ctx.auto_login = false;
112
-
113
- // After successful auto login, retry the original request
114
- if (resConfig) {
115
- const url = buildUrl(resConfig);
116
- const method = String(resConfig?.method || "GET").toUpperCase();
117
- const ctype = String(headerOf(resConfig?.headers, "content-type") || "").toLowerCase();
118
- const isMultipart = ctype.includes("multipart/form-data");
119
- const payload = resConfig?.data;
120
- const params = resConfig?.params;
121
-
122
- try {
123
- let newData;
124
- if (method === "GET") {
125
- newData = await http.get(url, ctx.jar, params || null, ctx.globalOptions, ctx);
126
- } else if (isMultipart) {
127
- newData = await http.postFormData(url, ctx.jar, payload, params, ctx.globalOptions, ctx);
128
- } else {
129
- newData = await http.post(url, ctx.jar, payload, ctx.globalOptions, ctx);
130
- }
131
- // Retry parsing with the new response
132
- return await parseAndCheckLogin(ctx, http, retryCount)(newData);
133
- } catch (retryErr) {
134
- // Handle ERR_INVALID_CHAR - don't retry, return error immediately
135
- if (retryErr?.code === "ERR_INVALID_CHAR" || (retryErr?.message && retryErr.message.includes("Invalid character in header"))) {
136
- logger(`Auto login retry failed: Invalid header detected. Error: ${retryErr.message}`, "error");
137
- const e = new Error("Not logged in. Auto login retry failed due to invalid header.");
138
- e.error = "Not logged in.";
139
- e.res = resData;
140
- e.originalError = retryErr;
141
- throw e;
142
- }
143
- logger(`Auto login retry failed: ${retryErr && retryErr.message ? retryErr.message : String(retryErr)}`, "error");
144
- const e = new Error("Not logged in. Auto login retry failed.");
145
- e.error = "Not logged in.";
146
- e.res = resData;
147
- e.originalError = retryErr;
148
- throw e;
149
- }
150
- } else {
151
- // No config available, can't retry
152
- const e = new Error("Not logged in. Auto login successful but cannot retry request.");
153
- e.error = "Not logged in.";
154
- e.res = resData;
155
- throw e;
156
- }
157
- } else {
158
- ctx.auto_login = false;
159
- const e = new Error("Not logged in. Auto login failed.");
160
- e.error = "Not logged in.";
161
- e.res = resData;
162
- throw e;
163
- }
164
- } catch (autoLoginErr) {
165
- ctx.auto_login = false;
166
- // If error already has the right format, rethrow it
167
- if (autoLoginErr.error === "Not logged in.") {
168
- throw autoLoginErr;
169
- }
170
- // Otherwise, wrap it
171
- logger(`Auto login error: ${autoLoginErr && autoLoginErr.message ? autoLoginErr.message : String(autoLoginErr)}`, "error");
172
- const e = new Error("Not logged in. Auto login error.");
173
- e.error = "Not logged in.";
174
- e.res = resData;
175
- e.originalError = autoLoginErr;
176
- throw e;
177
- }
178
- };
179
- return async (res) => {
180
- const status = res?.status ?? 0;
181
- if (status >= 500 && status < 600) {
182
- if (retryCount >= 5) {
183
- const err = new Error("Request retry failed. Check the `res` and `statusCode` property on this error.");
184
- err.statusCode = status;
185
- err.res = res?.data;
186
- err.error = "Request retry failed. Check the `res` and `statusCode` property on this error.";
187
- logger(`parseAndCheckLogin: Max retries (5) reached for status ${status}`, "error");
188
- throw err;
189
- }
190
- // Exponential backoff with jitter
191
- // First retry: ~1507ms (1500ms base + small jitter)
192
- // Subsequent retries: exponential backoff
193
- const baseDelay = retryCount === 0 ? 1500 : 1000 * Math.pow(2, retryCount);
194
- const jitter = Math.floor(Math.random() * 200); // 0-199ms jitter
195
- const retryTime = Math.min(
196
- baseDelay + jitter,
197
- 10000 // Max 10 seconds
198
- );
199
- logger(`parseAndCheckLogin: Retrying request (attempt ${retryCount + 1}/5) after ${retryTime}ms for status ${status}`, "warn");
200
- await delay(retryTime);
201
- const url = buildUrl(res?.config);
202
- const method = String(res?.config?.method || "GET").toUpperCase();
203
- const ctype = String(headerOf(res?.config?.headers, "content-type") || "").toLowerCase();
204
- const isMultipart = ctype.includes("multipart/form-data");
205
- const payload = res?.config?.data;
206
- const params = res?.config?.params;
207
- retryCount += 1;
208
- try {
209
- if (method === "GET") {
210
- const newData = await http.get(url, ctx.jar, params || null, ctx.globalOptions, ctx);
211
- return await parseAndCheckLogin(ctx, http, retryCount)(newData);
212
- }
213
- if (isMultipart) {
214
- const newData = await http.postFormData(url, ctx.jar, payload, params, ctx.globalOptions, ctx);
215
- return await parseAndCheckLogin(ctx, http, retryCount)(newData);
216
- } else {
217
- const newData = await http.post(url, ctx.jar, payload, ctx.globalOptions, ctx);
218
- return await parseAndCheckLogin(ctx, http, retryCount)(newData);
219
- }
220
- } catch (retryErr) {
221
- // Handle ERR_INVALID_CHAR - don't retry, return error immediately
222
- if (retryErr?.code === "ERR_INVALID_CHAR" || (retryErr?.message && retryErr.message.includes("Invalid character in header"))) {
223
- logger(`parseAndCheckLogin: Invalid header detected, aborting retry. Error: ${retryErr.message}`, "error");
224
- const err = new Error("Invalid header content detected. Request aborted to prevent crash.");
225
- err.error = "Invalid header content";
226
- err.statusCode = status;
227
- err.res = res?.data;
228
- err.originalError = retryErr;
229
- throw err;
230
- }
231
- // If max retries reached, return error instead of throwing to prevent crash
232
- if (retryCount >= 5) {
233
- logger(`parseAndCheckLogin: Max retries reached, returning error instead of crashing`, "error");
234
- const err = new Error("Request retry failed after 5 attempts. Check the `res` and `statusCode` property on this error.");
235
- err.statusCode = status;
236
- err.res = res?.data;
237
- err.error = "Request retry failed after 5 attempts";
238
- err.originalError = retryErr;
239
- throw err;
240
- }
241
- // Continue retry loop
242
- return await parseAndCheckLogin(ctx, http, retryCount)(res);
243
- }
244
- }
245
- if (status === 404) return;
246
- if (status !== 200) {
247
- const err = new Error("parseAndCheckLogin got status code: " + status + ". Bailing out of trying to parse response.");
248
- err.statusCode = status;
249
- err.res = res?.data;
250
- throw err;
251
- }
252
- const resBodyRaw = res?.data;
253
- const body = typeof resBodyRaw === "string" ? makeParsable(resBodyRaw) : resBodyRaw;
254
- let parsed;
255
- try {
256
- parsed = typeof body === "object" && body !== null ? body : JSON.parse(body);
257
- } catch (e) {
258
- const err = new Error("JSON.parse error. Check the `detail` property on this error.");
259
- err.error = "JSON.parse error. Check the `detail` property on this error.";
260
- err.detail = e;
261
- err.res = resBodyRaw;
262
- throw err;
263
- }
264
- const method = String(res?.config?.method || "GET").toUpperCase();
265
- if (parsed?.redirect && method === "GET") {
266
- const redirectRes = await http.get(parsed.redirect, ctx.jar, null, ctx.globalOptions, ctx);
267
- return await parseAndCheckLogin(ctx, http)(redirectRes);
268
- }
269
- if (parsed?.jsmods && parsed.jsmods.require && Array.isArray(parsed.jsmods.require[0]) && parsed.jsmods.require[0][0] === "Cookie") {
270
- parsed.jsmods.require[0][3][0] = String(parsed.jsmods.require[0][3][0] || "").replace("_js_", "");
271
- const requireCookie = parsed.jsmods.require[0][3];
272
- await ctx.jar.setCookie(formatCookie(requireCookie, "facebook"), "https://www.facebook.com");
273
- await ctx.jar.setCookie(formatCookie(requireCookie, "messenger"), "https://www.messenger.com");
274
- }
275
- if (parsed?.jsmods && Array.isArray(parsed.jsmods.require)) {
276
- for (const item of parsed.jsmods.require) {
277
- if (item[0] === "DTSG" && item[1] === "setToken") {
278
- ctx.fb_dtsg = item[3][0];
279
- ctx.ttstamp = "2";
280
- for (let j = 0; j < ctx.fb_dtsg.length; j++) ctx.ttstamp += ctx.fb_dtsg.charCodeAt(j);
281
- break;
282
- }
283
- }
284
- }
285
- if (parsed?.error === 1357001) {
286
- const err = new Error("Facebook blocked the login");
287
- err.error = "Not logged in.";
288
- throw err;
289
- }
290
- const resData = parsed;
291
- const resStr = JSON.stringify(resData);
292
- if (resStr.includes("XCheckpointFBScrapingWarningController") || resStr.includes("601051028565049")) {
293
- return await maybeAutoLogin(resData, res?.config);
294
- }
295
- if (resStr.includes("https://www.facebook.com/login.php?") || String(parsed?.redirect || "").includes("login.php?")) {
296
- return await maybeAutoLogin(resData, res?.config);
297
- }
298
- if (resStr.includes("1501092823525282")) {
299
- logger("Bot checkpoint 282 detected, please check the account!", "error");
300
- const err = new Error("Checkpoint 282 detected");
301
- err.error = "checkpoint_282";
302
- err.res = resData;
303
- throw err;
304
- }
305
- if (resStr.includes("828281030927956")) {
306
- logger("Bot checkpoint 956 detected, please check the account!", "error");
307
- const err = new Error("Checkpoint 956 detected");
308
- err.error = "checkpoint_956";
309
- err.res = resData;
310
- throw err;
311
- }
312
- return parsed;
313
- };
314
- }
315
-
316
- module.exports = {
317
- saveCookies,
318
- getAppState,
319
- parseAndCheckLogin
320
- };