surya-sahil-fca 1.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.
@@ -0,0 +1,320 @@
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
+ };
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ const { getType } = require("./format");
3
+ const stream = require("stream");
4
+ function getFrom(html, a, b) {
5
+ const i = html.indexOf(a);
6
+ if (i < 0) return;
7
+ const start = i + a.length;
8
+ const j = html.indexOf(b, start);
9
+ return j < 0 ? undefined : html.slice(start, j);
10
+ }
11
+ function isReadableStream(obj) {
12
+ return (
13
+ obj instanceof stream.Stream &&
14
+ (getType(obj._read) === "Function" ||
15
+ getType(obj._read) === "AsyncFunction") &&
16
+ getType(obj._readableState) === "Object"
17
+ );
18
+ }
19
+
20
+ module.exports = {
21
+ getFrom,
22
+ isReadableStream
23
+ };