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,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,26 @@
1
+ "use strict";
2
+
3
+ const axios = require("axios");
4
+ const { CookieJar } = require("tough-cookie");
5
+ const { wrapper } = require("axios-cookiejar-support");
6
+
7
+ const jar = new CookieJar();
8
+ const client = wrapper(
9
+ axios.create({
10
+ jar,
11
+ withCredentials: true,
12
+ timeout: 60000,
13
+ validateStatus: (s) => s >= 200 && s < 600,
14
+ maxRedirects: 5,
15
+ maxContentLength: Infinity,
16
+ maxBodyLength: Infinity,
17
+ })
18
+ );
19
+
20
+ const delay = (ms) => new Promise((r) => setTimeout(r, ms));
21
+
22
+ module.exports = {
23
+ jar,
24
+ client,
25
+ delay,
26
+ };
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+
3
+ const { sanitizeHeaders } = require("./sanitize");
4
+ const { jar, client } = require("./client");
5
+ const { getAgentForProxy } = require("./proxy");
6
+
7
+ function cfg(base = {}) {
8
+ const { reqJar, headers, params, agent, timeout, proxyUrl } = base;
9
+ // Prefer an explicit per-session proxy (ctx.globalOptions.proxy, threaded
10
+ // in from methods.js) over the process-wide default set by setProxy().
11
+ // This keeps one account's proxy/IP change from silently affecting
12
+ // another account's in-flight session in the same process.
13
+ const resolvedAgent = agent || (proxyUrl !== undefined ? getAgentForProxy(proxyUrl) : undefined);
14
+ return {
15
+ headers: sanitizeHeaders(headers),
16
+ params,
17
+ jar: reqJar || jar,
18
+ withCredentials: true,
19
+ timeout: timeout || 60000,
20
+ httpAgent: resolvedAgent || client.defaults.httpAgent,
21
+ httpsAgent: resolvedAgent || client.defaults.httpsAgent,
22
+ proxy: false,
23
+ validateStatus: (s) => s >= 200 && s < 600,
24
+ };
25
+ }
26
+
27
+ module.exports = {
28
+ cfg,
29
+ };
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ const constMod = require("../constants");
4
+ const getFrom = constMod.getFrom || constMod;
5
+ const { get, post, postFormData } = require("./methods");
6
+
7
+ function makeDefaults(html, userID, ctx) {
8
+ let reqCounter = 1;
9
+ const revision =
10
+ getFrom(html || "", 'revision":', ",") ||
11
+ getFrom(html || "", '"client_revision":', ",") ||
12
+ "";
13
+ function mergeWithDefaults(obj) {
14
+ const base = {
15
+ av: userID,
16
+ __user: userID,
17
+ __req: (reqCounter++).toString(36),
18
+ __rev: revision,
19
+ __a: 1,
20
+ };
21
+ if (ctx?.fb_dtsg) base.fb_dtsg = ctx.fb_dtsg;
22
+ if (ctx?.jazoest) base.jazoest = ctx.jazoest;
23
+ if (!obj) return base;
24
+ for (const k of Object.keys(obj)) if (!(k in base)) base[k] = obj[k];
25
+ return base;
26
+ }
27
+ return {
28
+ get: (url, j, qs, ctxx, customHeader = {}) =>
29
+ get(url, j, mergeWithDefaults(qs), ctx?.globalOptions, ctxx || ctx, customHeader),
30
+ post: (url, j, form, ctxx, customHeader = {}) =>
31
+ post(url, j, mergeWithDefaults(form), ctx?.globalOptions, ctxx || ctx, customHeader),
32
+ postFormData: (url, j, form, qs, ctxx) =>
33
+ postFormData(
34
+ url,
35
+ j,
36
+ mergeWithDefaults(form),
37
+ mergeWithDefaults(qs),
38
+ ctx?.globalOptions,
39
+ ctxx || ctx
40
+ ),
41
+ };
42
+ }
43
+
44
+ module.exports = {
45
+ makeDefaults,
46
+ };
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ const formatMod = require("../format");
4
+ const getType = formatMod.getType || formatMod;
5
+
6
+ function toStringVal(v) {
7
+ if (v === undefined || v === null) return "";
8
+ if (typeof v === "bigint") return v.toString();
9
+ if (typeof v === "boolean") return v ? "true" : "false";
10
+ return String(v);
11
+ }
12
+
13
+ function isStream(v) {
14
+ return (
15
+ v &&
16
+ typeof v === "object" &&
17
+ typeof v.pipe === "function" &&
18
+ typeof v.on === "function"
19
+ );
20
+ }
21
+
22
+ function isBlobLike(v) {
23
+ return (
24
+ v &&
25
+ typeof v.arrayBuffer === "function" &&
26
+ (typeof v.type === "string" || typeof v.name === "string")
27
+ );
28
+ }
29
+
30
+ function isPairArrayList(arr) {
31
+ return (
32
+ Array.isArray(arr) &&
33
+ arr.length > 0 &&
34
+ arr.every(
35
+ (x) => Array.isArray(x) && x.length === 2 && typeof x[0] === "string"
36
+ )
37
+ );
38
+ }
39
+
40
+ module.exports = {
41
+ getType,
42
+ toStringVal,
43
+ isStream,
44
+ isBlobLike,
45
+ isPairArrayList,
46
+ };
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+
3
+ const { jar, client } = require("./client");
4
+ const { cleanGet, get, post, postFormData } = require("./methods");
5
+ const { makeDefaults } = require("./defaults");
6
+ const { setProxy } = require("./proxy");
7
+
8
+ module.exports = {
9
+ cleanGet,
10
+ get,
11
+ post,
12
+ postFormData,
13
+ jar,
14
+ setProxy,
15
+ makeDefaults,
16
+ client,
17
+ };
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+
3
+ const FormData = require("form-data");
4
+ const headersMod = require("../headers");
5
+ const getHeaders = headersMod.getHeaders || headersMod;
6
+ const { client } = require("./client");
7
+ const { cfg } = require("./config");
8
+ const { requestWithRetry } = require("./retry");
9
+ const {
10
+ getType,
11
+ toStringVal,
12
+ isStream,
13
+ isBlobLike,
14
+ isPairArrayList,
15
+ } = require("./helpers");
16
+
17
+ function cleanGet(url, ctx) {
18
+ return requestWithRetry(() => client.get(url, cfg()), 3, 1000, ctx);
19
+ }
20
+
21
+ function get(url, reqJar, qs, options, ctx, customHeader) {
22
+ const headers = getHeaders(url, options, ctx, customHeader);
23
+ return requestWithRetry(
24
+ () => client.get(url, cfg({ reqJar, headers, params: qs, proxyUrl: options?.proxy })),
25
+ 3,
26
+ 1000,
27
+ ctx
28
+ );
29
+ }
30
+
31
+ function post(url, reqJar, form, options, ctx, customHeader) {
32
+ const headers = getHeaders(url, options, ctx, customHeader);
33
+ const ct = String(
34
+ headers["Content-Type"] || headers["content-type"] || "application/x-www-form-urlencoded"
35
+ ).toLowerCase();
36
+ let data;
37
+ if (ct.includes("json")) {
38
+ data = JSON.stringify(form || {});
39
+ headers["Content-Type"] = "application/json";
40
+ } else {
41
+ const p = new URLSearchParams();
42
+ if (form && typeof form === "object") {
43
+ for (const k of Object.keys(form)) {
44
+ let v = form[k];
45
+ if (isPairArrayList(v)) {
46
+ for (const [kk, vv] of v) p.append(`${k}[${kk}]`, toStringVal(vv));
47
+ continue;
48
+ }
49
+ if (Array.isArray(v)) {
50
+ for (const x of v) {
51
+ if (Array.isArray(x) && x.length === 2 && typeof x[1] !== "object")
52
+ p.append(k, toStringVal(x[1]));
53
+ else p.append(k, toStringVal(x));
54
+ }
55
+ continue;
56
+ }
57
+ if (getType(v) === "Object") v = JSON.stringify(v);
58
+ p.append(k, toStringVal(v));
59
+ }
60
+ }
61
+ data = p.toString();
62
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
63
+ }
64
+ return requestWithRetry(
65
+ () => client.post(url, data, cfg({ reqJar, headers, proxyUrl: options?.proxy })),
66
+ 3,
67
+ 1000,
68
+ ctx
69
+ );
70
+ }
71
+
72
+ async function postFormData(url, reqJar, form, qs, options, ctx) {
73
+ const fd = new FormData();
74
+ if (form && typeof form === "object") {
75
+ for (const k of Object.keys(form)) {
76
+ const v = form[k];
77
+ if (v === undefined || v === null) continue;
78
+ if (isPairArrayList(v)) {
79
+ for (const [kk, vv] of v)
80
+ fd.append(
81
+ `${k}[${kk}]`,
82
+ typeof vv === "object" && !Buffer.isBuffer(vv) && !isStream(vv)
83
+ ? JSON.stringify(vv)
84
+ : vv
85
+ );
86
+ continue;
87
+ }
88
+ if (Array.isArray(v)) {
89
+ for (const x of v) {
90
+ if (
91
+ Array.isArray(x) &&
92
+ x.length === 2 &&
93
+ x[1] &&
94
+ typeof x[1] === "object" &&
95
+ !Buffer.isBuffer(x[1]) &&
96
+ !isStream(x[1])
97
+ ) {
98
+ fd.append(k, x[0], x[1]);
99
+ } else if (
100
+ Array.isArray(x) &&
101
+ x.length === 2 &&
102
+ typeof x[1] !== "object"
103
+ ) {
104
+ fd.append(k, toStringVal(x[1]));
105
+ } else if (
106
+ x &&
107
+ typeof x === "object" &&
108
+ "value" in x &&
109
+ "options" in x
110
+ ) {
111
+ fd.append(k, x.value, x.options || {});
112
+ } else if (isStream(x) || Buffer.isBuffer(x) || typeof x === "string") {
113
+ fd.append(k, x);
114
+ } else if (isBlobLike(x)) {
115
+ const buf = Buffer.from(await x.arrayBuffer());
116
+ fd.append(k, buf, {
117
+ filename: x.name || k,
118
+ contentType: x.type || undefined,
119
+ });
120
+ } else {
121
+ fd.append(k, JSON.stringify(x));
122
+ }
123
+ }
124
+ continue;
125
+ }
126
+ if (v && typeof v === "object" && "value" in v && "options" in v) {
127
+ fd.append(k, v.value, v.options || {});
128
+ continue;
129
+ }
130
+ if (isStream(v) || Buffer.isBuffer(v) || typeof v === "string") {
131
+ fd.append(k, v);
132
+ continue;
133
+ }
134
+ if (isBlobLike(v)) {
135
+ const buf = Buffer.from(await v.arrayBuffer());
136
+ fd.append(k, buf, {
137
+ filename: v.name || k,
138
+ contentType: v.type || undefined,
139
+ });
140
+ continue;
141
+ }
142
+ if (typeof v === "number" || typeof v === "boolean") {
143
+ fd.append(k, toStringVal(v));
144
+ continue;
145
+ }
146
+ fd.append(k, JSON.stringify(v));
147
+ }
148
+ }
149
+ const headers = { ...getHeaders(url, options, ctx), ...fd.getHeaders() };
150
+ return requestWithRetry(
151
+ () => client.post(url, fd, cfg({ reqJar, headers, params: qs, proxyUrl: options?.proxy })),
152
+ 3,
153
+ 1000,
154
+ ctx
155
+ );
156
+ }
157
+
158
+ module.exports = {
159
+ cleanGet,
160
+ get,
161
+ post,
162
+ postFormData,
163
+ };
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ const { HttpsProxyAgent } = require("https-proxy-agent");
4
+ const { client } = require("./client");
5
+
6
+ // Per-proxy-URL agent cache so we don't create a new agent (and socket pool)
7
+ // on every single request, while still letting different sessions in the
8
+ // same process use different proxies (or no proxy) without stepping on each
9
+ // other. Keyed by the proxy URL string; "" represents "no proxy".
10
+ const agentCache = new Map();
11
+
12
+ function getAgentForProxy(proxyUrl) {
13
+ const key = proxyUrl || "";
14
+ if (!key) return undefined;
15
+ if (agentCache.has(key)) return agentCache.get(key);
16
+ const agent = new HttpsProxyAgent(key);
17
+ agentCache.set(key, agent);
18
+ return agent;
19
+ }
20
+
21
+ // Global default proxy setter, kept for backward compatibility with
22
+ // existing callers (api.setOptions({ proxy })) and single-account use.
23
+ // NOTE: this changes the DEFAULT used only when a request doesn't specify
24
+ // its own per-session proxy (see cfg() in ./config.js, which now prefers
25
+ // ctx.globalOptions.proxy when present). In a multi-account process, each
26
+ // account's requests should carry their own ctx.globalOptions.proxy so
27
+ // calling setProxy() for one account can no longer change another running
28
+ // account's outbound IP mid-session - that accidental cross-session proxy
29
+ // change was flagged as a real risk for "abnormal session" detection.
30
+ function setProxy(proxyUrl) {
31
+ if (!proxyUrl) {
32
+ client.defaults.httpAgent = undefined;
33
+ client.defaults.httpsAgent = undefined;
34
+ client.defaults.proxy = false;
35
+ return;
36
+ }
37
+ const agent = getAgentForProxy(proxyUrl);
38
+ client.defaults.httpAgent = agent;
39
+ client.defaults.httpsAgent = agent;
40
+ client.defaults.proxy = false;
41
+ }
42
+
43
+ module.exports = {
44
+ setProxy,
45
+ getAgentForProxy,
46
+ };