ayman-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.
Files changed (124) hide show
  1. package/README.md +81 -0
  2. package/func/checkUpdate.js +13 -0
  3. package/func/logAdapter.js +30 -0
  4. package/func/logger.js +66 -0
  5. package/index.d.ts +751 -0
  6. package/index.js +15 -0
  7. package/module/config.js +38 -0
  8. package/module/login.js +111 -0
  9. package/module/loginHelper.js +1296 -0
  10. package/module/options.js +37 -0
  11. package/package.json +78 -0
  12. package/src/api/action/addExternalModule.js +19 -0
  13. package/src/api/action/changeAvatar.js +137 -0
  14. package/src/api/action/changeBio.js +48 -0
  15. package/src/api/action/enableAutoSaveAppState.js +72 -0
  16. package/src/api/action/getCurrentUserID.js +11 -0
  17. package/src/api/action/handleFriendRequest.js +33 -0
  18. package/src/api/action/logout.js +76 -0
  19. package/src/api/action/refreshFb_dtsg.js +62 -0
  20. package/src/api/action/setPostReaction.js +106 -0
  21. package/src/api/action/story.js +118 -0
  22. package/src/api/action/unfriend.js +30 -0
  23. package/src/api/http/httpGet.js +28 -0
  24. package/src/api/http/httpPost.js +32 -0
  25. package/src/api/http/postFormData.js +23 -0
  26. package/src/api/messaging/J +1 -0
  27. package/src/api/messaging/addUserToGroup.js +70 -0
  28. package/src/api/messaging/changeAdminStatus.js +72 -0
  29. package/src/api/messaging/changeArchivedStatus.js +31 -0
  30. package/src/api/messaging/changeBlockedStatus.js +27 -0
  31. package/src/api/messaging/changeGroupImage.js +91 -0
  32. package/src/api/messaging/changeNickname.js +70 -0
  33. package/src/api/messaging/changeThreadColor.js +44 -0
  34. package/src/api/messaging/changeThreadEmoji.js +111 -0
  35. package/src/api/messaging/createNewGroup.js +50 -0
  36. package/src/api/messaging/createPoll.js +52 -0
  37. package/src/api/messaging/createThemeAI.js +98 -0
  38. package/src/api/messaging/deleteMessage.js +73 -0
  39. package/src/api/messaging/deleteThread.js +29 -0
  40. package/src/api/messaging/editMessage.js +67 -0
  41. package/src/api/messaging/forwardAttachment.js +55 -0
  42. package/src/api/messaging/forwardMessage.js +73 -0
  43. package/src/api/messaging/getEmojiUrl.js +29 -0
  44. package/src/api/messaging/getFriendsList.js +82 -0
  45. package/src/api/messaging/getMessage.js +829 -0
  46. package/src/api/messaging/getThemePictures.js +62 -0
  47. package/src/api/messaging/groupActions.js +119 -0
  48. package/src/api/messaging/handleMessageRequest.js +31 -0
  49. package/src/api/messaging/markAsDelivered.js +31 -0
  50. package/src/api/messaging/markAsRead.js +88 -0
  51. package/src/api/messaging/markAsReadAll.js +28 -0
  52. package/src/api/messaging/markAsSeen.js +30 -0
  53. package/src/api/messaging/muteThread.js +27 -0
  54. package/src/api/messaging/notes.js +101 -0
  55. package/src/api/messaging/removeUserFromGroup.js +51 -0
  56. package/src/api/messaging/resolvePhotoUrl.js +29 -0
  57. package/src/api/messaging/scheduler.js +100 -0
  58. package/src/api/messaging/searchForThread.js +32 -0
  59. package/src/api/messaging/sendMessage.js +270 -0
  60. package/src/api/messaging/sendTypingIndicator.js +62 -0
  61. package/src/api/messaging/setMessageReaction.js +91 -0
  62. package/src/api/messaging/setTitle.js +86 -0
  63. package/src/api/messaging/shareContact.js +47 -0
  64. package/src/api/messaging/threadColors.js +128 -0
  65. package/src/api/messaging/unsendMessage.js +73 -0
  66. package/src/api/messaging/uploadAttachment.js +492 -0
  67. package/src/api/socket/core/connectMqtt.js +259 -0
  68. package/src/api/socket/core/emitAuth.js +79 -0
  69. package/src/api/socket/core/getSeqID.js +170 -0
  70. package/src/api/socket/core/getTaskResponseData.js +27 -0
  71. package/src/api/socket/core/parseDelta.js +377 -0
  72. package/src/api/socket/detail/buildStream.js +215 -0
  73. package/src/api/socket/detail/constants.js +29 -0
  74. package/src/api/socket/listenMqtt.js +377 -0
  75. package/src/api/socket/middleware/index.js +80 -0
  76. package/src/api/threads/getThreadHistory.js +664 -0
  77. package/src/api/threads/getThreadInfo.js +296 -0
  78. package/src/api/threads/getThreadList.js +293 -0
  79. package/src/api/threads/getThreadPictures.js +43 -0
  80. package/src/api/user/J +1 -0
  81. package/src/api/user/getUserID.js +48 -0
  82. package/src/api/user/getUserInfo.js +402 -0
  83. package/src/api/user/getUserInfoV2.js +134 -0
  84. package/src/core/sendReqMqtt.js +69 -0
  85. package/src/database/helpers.js +36 -0
  86. package/src/database/models/index.js +55 -0
  87. package/src/database/models/thread.js +44 -0
  88. package/src/database/models/user.js +39 -0
  89. package/src/database/threadData.js +92 -0
  90. package/src/database/userData.js +88 -0
  91. package/src/remote/remoteClient.js +71 -0
  92. package/src/utils/broadcast.js +62 -0
  93. package/src/utils/client.js +10 -0
  94. package/src/utils/constants.js +53 -0
  95. package/src/utils/cookies.js +73 -0
  96. package/src/utils/format/attachment.js +357 -0
  97. package/src/utils/format/cookie.js +9 -0
  98. package/src/utils/format/date.js +50 -0
  99. package/src/utils/format/decode.js +44 -0
  100. package/src/utils/format/delta.js +194 -0
  101. package/src/utils/format/ids.js +64 -0
  102. package/src/utils/format/index.js +64 -0
  103. package/src/utils/format/message.js +88 -0
  104. package/src/utils/format/presence.js +132 -0
  105. package/src/utils/format/readTyp.js +44 -0
  106. package/src/utils/format/thread.js +42 -0
  107. package/src/utils/format/utils.js +141 -0
  108. package/src/utils/headers.js +96 -0
  109. package/src/utils/loginParser/autoLogin.js +125 -0
  110. package/src/utils/loginParser/helpers.js +43 -0
  111. package/src/utils/loginParser/index.js +10 -0
  112. package/src/utils/loginParser/parseAndCheckLogin.js +220 -0
  113. package/src/utils/loginParser/textUtils.js +28 -0
  114. package/src/utils/request/H +1 -0
  115. package/src/utils/request/client.js +33 -0
  116. package/src/utils/request/config.js +25 -0
  117. package/src/utils/request/defaults.js +40 -0
  118. package/src/utils/request/helpers.js +31 -0
  119. package/src/utils/request/index.js +12 -0
  120. package/src/utils/request/methods.js +92 -0
  121. package/src/utils/request/proxy.js +23 -0
  122. package/src/utils/request/retry.js +87 -0
  123. package/src/utils/request/sanitize.js +41 -0
  124. package/src/utils/sessionKeeper.js +275 -0
@@ -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
+ };
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+
3
+ const logger = require("../../../func/logger");
4
+ const { makeParsable } = require("./textUtils");
5
+ const { delay, createEmit, headerOf, buildUrl, formatCookie } = require("./helpers");
6
+ const { createMaybeAutoLogin } = require("./autoLogin");
7
+
8
+ /**
9
+ * Trả về hàm async (res) => parsed | throw.
10
+ * Xử lý: retry 5xx, parse JSON, redirect, cookie/DTSG, checkpoint và auto login.
11
+ */
12
+ function parseAndCheckLogin(ctx, http, retryCount = 0) {
13
+ const emit = createEmit(ctx);
14
+ const helpers = { buildUrl, headerOf, formatCookie };
15
+ const maybeAutoLogin = createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin);
16
+
17
+ return async function handleResponse(res) {
18
+ const status = res?.status ?? 0;
19
+
20
+ // Retry khi 5xx
21
+ if (status >= 500 && status < 600) {
22
+ if (retryCount >= 5) {
23
+ const err = new Error(
24
+ "Request retry failed. Check the `res` and `statusCode` property on this error."
25
+ );
26
+ err.statusCode = status;
27
+ err.res = res?.data;
28
+ err.error =
29
+ "Request retry failed. Check the `res` and `statusCode` property on this error.";
30
+ logger(`parseAndCheckLogin: Max retries (5) reached for status ${status}`, "error");
31
+ throw err;
32
+ }
33
+ const baseDelay = retryCount === 0 ? 1500 : 1000 * Math.pow(2, retryCount);
34
+ const jitter = Math.floor(Math.random() * 200);
35
+ const retryTime = Math.min(baseDelay + jitter, 10000);
36
+ const method = String(res?.config?.method || "GET").toUpperCase();
37
+ const url = buildUrl(res?.config);
38
+ logger(
39
+ `parseAndCheckLogin: [${method}] ${url || "(no url)"} -> Retrying request (attempt ${
40
+ retryCount + 1
41
+ }/5) after ${retryTime}ms for status ${status}`,
42
+ "warn"
43
+ );
44
+ await delay(retryTime);
45
+ const ctype = String(
46
+ headerOf(res?.config?.headers, "content-type") || ""
47
+ ).toLowerCase();
48
+ const isMultipart = ctype.includes("multipart/form-data");
49
+ const payload = res?.config?.data;
50
+ const params = res?.config?.params;
51
+ const nextRetry = retryCount + 1;
52
+ try {
53
+ if (method === "GET") {
54
+ const newData = await http.get(url, ctx.jar, params || null, ctx.globalOptions, ctx);
55
+ return await parseAndCheckLogin(ctx, http, nextRetry)(newData);
56
+ }
57
+ if (isMultipart) {
58
+ const newData = await http.postFormData(
59
+ url,
60
+ ctx.jar,
61
+ payload,
62
+ params,
63
+ ctx.globalOptions,
64
+ ctx
65
+ );
66
+ return await parseAndCheckLogin(ctx, http, nextRetry)(newData);
67
+ }
68
+ const newData = await http.post(url, ctx.jar, payload, ctx.globalOptions, ctx);
69
+ return await parseAndCheckLogin(ctx, http, nextRetry)(newData);
70
+ } catch (retryErr) {
71
+ if (
72
+ retryErr?.code === "ERR_INVALID_CHAR" ||
73
+ (retryErr?.message && retryErr.message.includes("Invalid character in header"))
74
+ ) {
75
+ logger(
76
+ `parseAndCheckLogin: Invalid header detected, aborting retry. Error: ${retryErr.message}`,
77
+ "error"
78
+ );
79
+ const err = new Error(
80
+ "Invalid header content detected. Request aborted to prevent crash."
81
+ );
82
+ err.error = "Invalid header content";
83
+ err.statusCode = status;
84
+ err.res = res?.data;
85
+ err.originalError = retryErr;
86
+ throw err;
87
+ }
88
+ if (nextRetry >= 5) {
89
+ logger(
90
+ `parseAndCheckLogin: Max retries reached, returning error instead of crashing`,
91
+ "error"
92
+ );
93
+ const err = new Error(
94
+ "Request retry failed after 5 attempts. Check the `res` and `statusCode` property on this error."
95
+ );
96
+ err.statusCode = status;
97
+ err.res = res?.data;
98
+ err.error = "Request retry failed after 5 attempts";
99
+ err.originalError = retryErr;
100
+ throw err;
101
+ }
102
+ return await parseAndCheckLogin(ctx, http, nextRetry)(res);
103
+ }
104
+ }
105
+
106
+ if (status === 404) return;
107
+ if (status !== 200) {
108
+ const err = new Error(
109
+ "parseAndCheckLogin got status code: " +
110
+ status +
111
+ ". Bailing out of trying to parse response."
112
+ );
113
+ err.statusCode = status;
114
+ err.res = res?.data;
115
+ throw err;
116
+ }
117
+
118
+ const resBodyRaw = res?.data;
119
+ const body = typeof resBodyRaw === "string" ? makeParsable(resBodyRaw) : resBodyRaw;
120
+ let parsed;
121
+ try {
122
+ parsed = typeof body === "object" && body !== null ? body : JSON.parse(body);
123
+ } catch (e) {
124
+ const err = new Error("JSON.parse error. Check the `detail` property on this error.");
125
+ err.error = "JSON.parse error. Check the `detail` property on this error.";
126
+ err.detail = e;
127
+ err.res = resBodyRaw;
128
+ throw err;
129
+ }
130
+
131
+ const method = String(res?.config?.method || "GET").toUpperCase();
132
+ if (parsed?.redirect && method === "GET") {
133
+ const redirectRes = await http.get(parsed.redirect, ctx.jar, null, ctx.globalOptions, ctx);
134
+ return await parseAndCheckLogin(ctx, http)(redirectRes);
135
+ }
136
+
137
+ // Cookie từ jsmods
138
+ if (
139
+ parsed?.jsmods &&
140
+ parsed.jsmods.require &&
141
+ Array.isArray(parsed.jsmods.require[0]) &&
142
+ parsed.jsmods.require[0][0] === "Cookie"
143
+ ) {
144
+ parsed.jsmods.require[0][3][0] = String(parsed.jsmods.require[0][3][0] || "").replace(
145
+ "_js_",
146
+ ""
147
+ );
148
+ const requireCookie = parsed.jsmods.require[0][3];
149
+ await ctx.jar.setCookie(
150
+ formatCookie(requireCookie, "facebook"),
151
+ "https://www.facebook.com"
152
+ );
153
+ await ctx.jar.setCookie(
154
+ formatCookie(requireCookie, "messenger"),
155
+ "https://www.messenger.com"
156
+ );
157
+ }
158
+
159
+ // DTSG token
160
+ if (parsed?.jsmods && Array.isArray(parsed.jsmods.require)) {
161
+ for (const item of parsed.jsmods.require) {
162
+ if (item[0] === "DTSG" && item[1] === "setToken") {
163
+ ctx.fb_dtsg = item[3][0];
164
+ ctx.ttstamp = "2";
165
+ for (let j = 0; j < ctx.fb_dtsg.length; j++) ctx.ttstamp += ctx.fb_dtsg.charCodeAt(j);
166
+ break;
167
+ }
168
+ }
169
+ }
170
+
171
+ if (parsed?.error === 1357001) {
172
+ const err = new Error("Facebook blocked the login");
173
+ err.error = "login_blocked";
174
+ err.res = parsed;
175
+ emit("loginBlocked", { res: parsed });
176
+ throw err;
177
+ }
178
+
179
+ const resData = parsed;
180
+ const resStr = JSON.stringify(resData);
181
+
182
+ if (
183
+ resStr.includes("XCheckpointFBScrapingWarningController") ||
184
+ resStr.includes("601051028565049")
185
+ ) {
186
+ emit("checkpoint", { type: "scraping_warning", res: resData });
187
+ return await maybeAutoLogin(resData, res?.config);
188
+ }
189
+ if (
190
+ resStr.includes("https://www.facebook.com/login.php?") ||
191
+ String(parsed?.redirect || "").includes("login.php?")
192
+ ) {
193
+ return await maybeAutoLogin(resData, res?.config);
194
+ }
195
+ if (resStr.includes("1501092823525282")) {
196
+ logger("Bot checkpoint 282 detected, please check the account!", "error");
197
+ const err = new Error("Checkpoint 282 detected");
198
+ err.error = "checkpoint_282";
199
+ err.res = resData;
200
+ emit("checkpoint", { type: "282", res: resData });
201
+ emit("checkpoint_282", { res: resData });
202
+ throw err;
203
+ }
204
+ if (resStr.includes("828281030927956")) {
205
+ logger("Bot checkpoint 956 detected, please check the account!", "error");
206
+ const err = new Error("Checkpoint 956 detected");
207
+ err.error = "checkpoint_956";
208
+ err.res = resData;
209
+ emit("checkpoint", { type: "956", res: resData });
210
+ emit("checkpoint_956", { res: resData });
211
+ throw err;
212
+ }
213
+
214
+ return parsed;
215
+ };
216
+ }
217
+
218
+ module.exports = {
219
+ parseAndCheckLogin
220
+ };
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Loại bỏ XSSI prefix và ký tự thừa từ chuỗi response.
5
+ */
6
+ function cleanXssi(t) {
7
+ if (t == null) return "";
8
+ let s = String(t);
9
+ s = s.replace(/^[\uFEFF\xEF\xBB\xBF]+/, "");
10
+ s = s.replace(/^\)\]\}',?\s*/, "");
11
+ s = s.replace(/^\s*for\s*\(;;\);\s*/i, "");
12
+ return s;
13
+ }
14
+
15
+ /**
16
+ * Chuẩn hóa HTML/JSON response thành chuỗi có thể parse (nối nhiều object thành array).
17
+ */
18
+ function makeParsable(html) {
19
+ const raw = cleanXssi(String(html || ""));
20
+ const split = raw.split(/\}\r?\n\s*\{/);
21
+ if (split.length === 1) return raw;
22
+ return "[" + split.join("},{") + "]";
23
+ }
24
+
25
+ module.exports = {
26
+ cleanXssi,
27
+ makeParsable
28
+ };
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,33 @@
1
+ // ============================================================
2
+ // AYMAN-FCA v2.0 — HTTP Client
3
+ // © 2025 Ayman. All Rights Reserved.
4
+ //
5
+ // ملاحظة مهمة: لا نستخدم httpAgent/httpsAgent مخصص
6
+ // لأن axios-cookiejar-support لا يدعمه
7
+ // ============================================================
8
+ "use strict";
9
+
10
+ const axios = require("axios");
11
+ const { CookieJar } = require("tough-cookie");
12
+ const { wrapper } = require("axios-cookiejar-support");
13
+
14
+ const jar = new CookieJar();
15
+
16
+ // ✅ Client نظيف — timeout 30s أسرع من الافتراضي 60s
17
+ const client = wrapper(
18
+ axios.create({
19
+ jar,
20
+ withCredentials: true,
21
+ timeout: 30000,
22
+ validateStatus: s => s >= 200 && s < 600,
23
+ maxRedirects: 5,
24
+ maxContentLength: Infinity,
25
+ maxBodyLength: Infinity,
26
+ decompress: true
27
+ })
28
+ );
29
+
30
+ // ✅ delay utility
31
+ const delay = ms => new Promise(r => setTimeout(r, ms));
32
+
33
+ module.exports = { jar, client, delay };
@@ -0,0 +1,25 @@
1
+ // ============================================================
2
+ // AYMAN-FCA v2.0 — Request Config
3
+ // © 2025 Ayman. All Rights Reserved.
4
+ // ============================================================
5
+ "use strict";
6
+
7
+ const { sanitizeHeaders } = require("./sanitize");
8
+ const { jar } = require("./client");
9
+
10
+ function cfg(base = {}) {
11
+ const { reqJar, headers, params, agent, timeout } = base;
12
+ return {
13
+ headers: sanitizeHeaders(headers),
14
+ params,
15
+ jar: reqJar || jar,
16
+ withCredentials: true,
17
+ timeout: timeout || 30000,
18
+ ...(agent ? { httpAgent: agent, httpsAgent: agent } : {}),
19
+ proxy: false,
20
+ validateStatus: s => s >= 200 && s < 600,
21
+ decompress: true
22
+ };
23
+ }
24
+
25
+ module.exports = { cfg };
@@ -0,0 +1,40 @@
1
+ // ============================================================
2
+ // AYMAN-FCA v2.0 — Request Defaults Builder
3
+ // © 2025 Ayman. All Rights Reserved.
4
+ // ============================================================
5
+ "use strict";
6
+
7
+ const constMod = require("../constants");
8
+ const getFrom = constMod.getFrom;
9
+ const { get, post, postFormData } = require("./methods");
10
+
11
+ function makeDefaults(html, userID, ctx) {
12
+ let reqCounter = 1;
13
+ const revision =
14
+ getFrom(html || "", 'revision":', ",") ||
15
+ getFrom(html || "", '"client_revision":', ",") || "";
16
+
17
+ function merge(obj) {
18
+ const base = {
19
+ av: userID,
20
+ __user: userID,
21
+ __req: (reqCounter++).toString(36),
22
+ __rev: revision,
23
+ __a: 1,
24
+ };
25
+ if (ctx?.fb_dtsg) base.fb_dtsg = ctx.fb_dtsg;
26
+ if (ctx?.jazoest) base.jazoest = ctx.jazoest;
27
+ if (!obj) return base;
28
+ for (const k of Object.keys(obj)) if (!(k in base)) base[k] = obj[k];
29
+ return base;
30
+ }
31
+
32
+ return {
33
+ get: (url, j, qs, ctxx, h = {}) => get(url, j, merge(qs), ctx?.globalOptions, ctxx || ctx, h),
34
+ post: (url, j, form, ctxx, h = {}) => post(url, j, merge(form), ctx?.globalOptions, ctxx || ctx, h),
35
+ postFormData:(url, j, form, qs, ctxx) =>
36
+ postFormData(url, j, merge(form), merge(qs), ctx?.globalOptions, ctxx || ctx),
37
+ };
38
+ }
39
+
40
+ module.exports = { makeDefaults };
@@ -0,0 +1,31 @@
1
+ // ============================================================
2
+ // AYMAN-FCA v2.0 — Request Helpers
3
+ // © 2025 Ayman. All Rights Reserved.
4
+ // ============================================================
5
+ "use strict";
6
+
7
+ const formatMod = require("../format");
8
+ const getType = formatMod.getType;
9
+
10
+ function toStringVal(v) {
11
+ if (v === undefined || v === null) return "";
12
+ if (typeof v === "bigint") return v.toString();
13
+ if (typeof v === "boolean") return v ? "true" : "false";
14
+ return String(v);
15
+ }
16
+
17
+ function isStream(v) {
18
+ return v && typeof v === "object" && typeof v.pipe === "function" && typeof v.on === "function";
19
+ }
20
+
21
+ function isBlobLike(v) {
22
+ return v && typeof v.arrayBuffer === "function" &&
23
+ (typeof v.type === "string" || typeof v.name === "string");
24
+ }
25
+
26
+ function isPairArrayList(arr) {
27
+ return Array.isArray(arr) && arr.length > 0 &&
28
+ arr.every(x => Array.isArray(x) && x.length === 2 && typeof x[0] === "string");
29
+ }
30
+
31
+ module.exports = { getType, toStringVal, isStream, isBlobLike, isPairArrayList };
@@ -0,0 +1,12 @@
1
+ // ============================================================
2
+ // AYMAN-FCA v2.0 — Request Index
3
+ // © 2025 Ayman. All Rights Reserved.
4
+ // ============================================================
5
+ "use strict";
6
+
7
+ const { jar, client } = require("./client");
8
+ const { cleanGet, get, post, postFormData } = require("./methods");
9
+ const { makeDefaults } = require("./defaults");
10
+ const { setProxy } = require("./proxy");
11
+
12
+ module.exports = { cleanGet, get, post, postFormData, jar, setProxy, makeDefaults, client };
@@ -0,0 +1,92 @@
1
+ // ============================================================
2
+ // AYMAN-FCA v2.0 — HTTP Methods
3
+ // © 2025 Ayman. All Rights Reserved.
4
+ // ============================================================
5
+ "use strict";
6
+
7
+ const FormData = require("form-data");
8
+ const { getHeaders } = require("../headers");
9
+ const { client } = require("./client");
10
+ const { cfg } = require("./config");
11
+ const { requestWithRetry } = require("./retry");
12
+ const { getType, toStringVal, isStream, isBlobLike, isPairArrayList } = require("./helpers");
13
+
14
+ function cleanGet(url, ctx) {
15
+ return requestWithRetry(() => client.get(url, cfg()), 3, 800, ctx);
16
+ }
17
+
18
+ function get(url, reqJar, qs, options, ctx, customHeader) {
19
+ const headers = getHeaders(url, options, ctx, customHeader);
20
+ return requestWithRetry(
21
+ () => client.get(url, cfg({ reqJar, headers, params: qs })),
22
+ 3, 800, ctx
23
+ );
24
+ }
25
+
26
+ function post(url, reqJar, form, options, ctx, customHeader) {
27
+ const headers = getHeaders(url, options, ctx, customHeader);
28
+ const ct = String(headers["Content-Type"] || "application/x-www-form-urlencoded").toLowerCase();
29
+ let data;
30
+
31
+ if (ct.includes("json")) {
32
+ data = JSON.stringify(form || {});
33
+ headers["Content-Type"] = "application/json";
34
+ } else {
35
+ const p = new URLSearchParams();
36
+ if (form && typeof form === "object") {
37
+ for (const k of Object.keys(form)) {
38
+ let v = form[k];
39
+ if (isPairArrayList(v)) {
40
+ for (const [kk, vv] of v) p.append(`${k}[${kk}]`, toStringVal(vv));
41
+ continue;
42
+ }
43
+ if (Array.isArray(v)) {
44
+ for (const x of v) {
45
+ if (Array.isArray(x) && x.length === 2 && typeof x[1] !== "object")
46
+ p.append(k, toStringVal(x[1]));
47
+ else p.append(k, toStringVal(x));
48
+ }
49
+ continue;
50
+ }
51
+ if (getType(v) === "Object") v = JSON.stringify(v);
52
+ p.append(k, toStringVal(v));
53
+ }
54
+ }
55
+ data = p.toString();
56
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
57
+ }
58
+
59
+ return requestWithRetry(
60
+ () => client.post(url, data, cfg({ reqJar, headers })),
61
+ 3, 800, ctx
62
+ );
63
+ }
64
+
65
+ async function postFormData(url, reqJar, form, qs, options, ctx) {
66
+ const fd = new FormData();
67
+ if (form && typeof form === "object") {
68
+ for (const k of Object.keys(form)) {
69
+ const v = form[k];
70
+ if (v === undefined || v === null) continue;
71
+ if (isStream(v) || Buffer.isBuffer(v) || typeof v === "string") {
72
+ fd.append(k, v); continue;
73
+ }
74
+ if (isBlobLike(v)) {
75
+ const buf = Buffer.from(await v.arrayBuffer());
76
+ fd.append(k, buf, { filename: v.name || k, contentType: v.type || undefined });
77
+ continue;
78
+ }
79
+ if (typeof v === "number" || typeof v === "boolean") {
80
+ fd.append(k, toStringVal(v)); continue;
81
+ }
82
+ fd.append(k, JSON.stringify(v));
83
+ }
84
+ }
85
+ const headers = { ...getHeaders(url, options, ctx), ...fd.getHeaders() };
86
+ return requestWithRetry(
87
+ () => client.post(url, fd, cfg({ reqJar, headers, params: qs })),
88
+ 3, 800, ctx
89
+ );
90
+ }
91
+
92
+ module.exports = { cleanGet, get, post, postFormData };