@nirzon-islam/omega-fca 0.0.0-stage → 0.1.5

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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +155 -2
  3. package/docs/ARCHITECTURE.md +126 -0
  4. package/docs/AUTHENTICATION-ATTEMPT.md +52 -0
  5. package/docs/BROWSER-CAPTURE.md +74 -0
  6. package/docs/DEPLOYMENT.md +80 -0
  7. package/docs/FACEBOOK-MQTT-TRANSPORT.md +82 -0
  8. package/docs/GOATBOT-COMPATIBILITY-MATRIX.md +58 -0
  9. package/docs/GOATBOT-INTEGRATION-AUDIT.md +64 -0
  10. package/docs/IMPLEMENTATION-STATUS.md +51 -0
  11. package/docs/META-MESSENGER-TRANSPORT.md +78 -0
  12. package/docs/NESTED-REALTIME-PAYLOAD.md +16 -0
  13. package/docs/NTKHANG-REFERENCE-STUDY.md +69 -0
  14. package/docs/PROTOCOL-EVIDENCE.md +69 -0
  15. package/docs/REALTIME-FRAME-EVIDENCE.md +33 -0
  16. package/docs/REFERENCE-AUDIT.md +63 -0
  17. package/docs/SAFE-DIAGNOSTICS.md +39 -0
  18. package/examples/appstate-session-check.js +33 -0
  19. package/examples/meta-messenger-server.js +96 -0
  20. package/index.d.ts +407 -0
  21. package/index.js +62 -0
  22. package/package.json +63 -4
  23. package/src/api/client.js +308 -0
  24. package/src/auth/accountConfig.js +82 -0
  25. package/src/auth/authenticationAttempt.js +193 -0
  26. package/src/auth/facebookResponse.js +93 -0
  27. package/src/auth/facebookWebClient.js +133 -0
  28. package/src/auth/personalSession.js +335 -0
  29. package/src/auth/totp.js +39 -0
  30. package/src/compat/facebookMqttClient.js +74 -0
  31. package/src/compat/goatbotLogin.js +67 -0
  32. package/src/compat/legacyFcaTransport.js +136 -0
  33. package/src/events/dispatcher.js +69 -0
  34. package/src/license/provider.js +37 -0
  35. package/src/license/verify.js +42 -0
  36. package/src/network/cookieJar.js +72 -0
  37. package/src/network/requestClient.js +104 -0
  38. package/src/runtime/connection.js +231 -0
  39. package/src/security/cookies.js +104 -0
  40. package/src/security/diagnostics.js +98 -0
  41. package/src/security/redact.js +23 -0
  42. package/src/security/sessionCrypto.js +61 -0
  43. package/src/security/sessionState.js +23 -0
  44. package/src/security/sessionStore.js +64 -0
  45. package/src/transport/binaryPayloadInspector.js +131 -0
  46. package/src/transport/contract.js +39 -0
  47. package/src/transport/facebookGatewayProtocol.js +135 -0
  48. package/src/transport/facebookMqttDriver.js +60 -0
  49. package/src/transport/facebookMqttEvents.js +114 -0
  50. package/src/transport/facebookMqttProtocol.js +213 -0
  51. package/src/transport/facebookThreadApi.js +284 -0
  52. package/src/transport/messengerActions.js +64 -0
  53. package/src/transport/messengerSyncCursorStore.js +53 -0
  54. package/src/transport/metaMessenger.js +294 -0
  55. package/src/transport/mqtt311Codec.js +254 -0
  56. package/src/transport/mqtt311StreamDecoder.js +57 -0
  57. package/src/transport/mqttRequestTracker.js +60 -0
  58. package/src/transport/nativeRealtimeTransport.js +388 -0
  59. package/src/transport/realtimeFrameDecoder.js +92 -0
  60. package/src/transport/realtimeSyncEnvelope.js +84 -0
  61. package/src/update/manifest.js +102 -0
  62. package/tools/browser-capture.js +130 -0
  63. package/tools/termux-capture-setup.sh +26 -0
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+
3
+ const { normalizeFacebookResponse, createFacebookError } = require("./facebookResponse");
4
+
5
+ const ALLOWED_HOST = /(^|\.)facebook\.com$|(^|\.)messenger\.com$/;
6
+ const MAX_BODY_BYTES = 2 * 1024 * 1024;
7
+
8
+ function assertFacebookUrl(input) {
9
+ const url = input instanceof URL ? new URL(input.href) : new URL(input);
10
+ if (url.protocol !== "https:" || !ALLOWED_HOST.test(url.hostname)) {
11
+ throw new TypeError("Facebook web actions require an HTTPS Facebook/Messenger URL");
12
+ }
13
+ if (url.username || url.password) throw new TypeError("Facebook action URL must not contain credentials");
14
+ return url;
15
+ }
16
+
17
+ function toFormBody(data, tokens, userId) {
18
+ const form = new URLSearchParams();
19
+ for (const [key, value] of Object.entries(data || {})) {
20
+ if (!/^[A-Za-z0-9_.:[\]-]{1,128}$/.test(key)) {
21
+ throw new TypeError("Facebook form field name is invalid");
22
+ }
23
+ if (value === undefined || value === null) continue;
24
+ if (typeof value === "object") form.set(key, JSON.stringify(value));
25
+ else form.set(key, String(value));
26
+ }
27
+ if (userId) form.set("av", String(userId));
28
+ if (tokens.fbDtsg) form.set("fb_dtsg", tokens.fbDtsg);
29
+ if (tokens.lsd) form.set("lsd", tokens.lsd);
30
+ if (tokens.jazoest) form.set("jazoest", tokens.jazoest);
31
+ if (tokens.hsi) form.set("hsi", tokens.hsi);
32
+ if (tokens.spinR) form.set("__spin_r", tokens.spinR);
33
+ if (tokens.spinB) form.set("__spin_b", tokens.spinB);
34
+ if (tokens.spinT) form.set("__spin_t", tokens.spinT);
35
+ return form;
36
+ }
37
+
38
+ /**
39
+ * Low-level authenticated web request layer. It intentionally does not guess
40
+ * private action endpoints or payload schemas; callers must supply a known,
41
+ * owner-authorized Facebook web path and its documented/current form fields.
42
+ */
43
+ function createFacebookWebClient({ session, fetchImpl, normalizeResponse = normalizeFacebookResponse } = {}) {
44
+ if (!session || typeof session.request !== "function" ||
45
+ typeof session.getTokens !== "function" || typeof session.getCookieHeader !== "function") {
46
+ throw new TypeError("An active OmegA personal session is required");
47
+ }
48
+ if (typeof normalizeResponse !== "function") throw new TypeError("normalizeResponse must be a function");
49
+
50
+ async function request(input, { method = "GET", query, body, headers, signal } = {}) {
51
+ const url = assertFacebookUrl(input);
52
+ const verb = String(method).toUpperCase();
53
+ if (!["GET", "HEAD", "POST"].includes(verb)) {
54
+ throw new TypeError("Facebook web client supports GET, HEAD, and POST only");
55
+ }
56
+ if (query && typeof query === "object") {
57
+ for (const [key, value] of Object.entries(query)) {
58
+ if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
59
+ }
60
+ }
61
+ const requestHeaders = new Headers(headers || {});
62
+ requestHeaders.set("accept", "application/json, text/javascript, */*; q=0.01");
63
+ let requestBody;
64
+ if (verb === "POST") {
65
+ if (body instanceof URLSearchParams || typeof body === "string" || body instanceof Uint8Array) {
66
+ requestBody = body;
67
+ } else {
68
+ requestBody = toFormBody(body, session.getTokens(), session.userId);
69
+ if (!requestHeaders.has("content-type")) {
70
+ requestHeaders.set("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
71
+ }
72
+ }
73
+ } else if (body !== undefined) {
74
+ throw new TypeError("GET and HEAD requests cannot include a body");
75
+ }
76
+ if (requestBody !== undefined) {
77
+ const size = typeof requestBody === "string" ? Buffer.byteLength(requestBody, "utf8")
78
+ : requestBody instanceof URLSearchParams ? Buffer.byteLength(requestBody.toString(), "utf8")
79
+ : requestBody instanceof Uint8Array ? requestBody.byteLength : 0;
80
+ if (size > MAX_BODY_BYTES) {
81
+ throw createFacebookError("Facebook request body exceeded the 2 MiB safety limit", {
82
+ code: "FCA_REQUEST_TOO_LARGE", retryable: false
83
+ });
84
+ }
85
+ }
86
+ const response = await session.request(url, {
87
+ method: verb, headers: requestHeaders, body: requestBody, signal, redirect: "manual"
88
+ });
89
+ if (response.status >= 300 && response.status < 400) {
90
+ const location = response.headers?.get?.("location") || "";
91
+ if (/checkpoint|challenge/i.test(location)) {
92
+ throw createFacebookError("Facebook requires the account owner to complete a checkpoint", {
93
+ code: "FCA_CHECKPOINT_REQUIRED", status: response.status, sessionState: "checkpoint", retryable: false
94
+ });
95
+ }
96
+ if (/login\.php|\/login(?:[/?]|$)/i.test(location)) {
97
+ throw createFacebookError("Facebook session is no longer authenticated", {
98
+ code: "FCA_SESSION_EXPIRED", status: response.status, sessionState: "logged_out", retryable: false
99
+ });
100
+ }
101
+ throw createFacebookError("Facebook returned an unexpected redirect; it was not followed", {
102
+ code: "FCA_UNEXPECTED_REDIRECT", status: response.status, retryable: false
103
+ });
104
+ }
105
+ const declared = Number(response.headers?.get?.("content-length") || 0);
106
+ if (declared > MAX_BODY_BYTES) {
107
+ throw createFacebookError("Facebook response exceeded the 2 MiB safety limit", {
108
+ code: "FCA_RESPONSE_TOO_LARGE", status: response.status, retryable: false
109
+ });
110
+ }
111
+ const raw = await response.text();
112
+ if (Buffer.byteLength(raw, "utf8") > MAX_BODY_BYTES) {
113
+ throw createFacebookError("Facebook response exceeded the 2 MiB safety limit", {
114
+ code: "FCA_RESPONSE_TOO_LARGE", status: response.status, retryable: false
115
+ });
116
+ }
117
+ const contentType = response.headers?.get?.("content-type") || "";
118
+ const payload = normalizeResponse(raw, { status: response.status, contentType });
119
+ return Object.freeze({ status: response.status, headers: response.headers, payload, raw });
120
+ }
121
+
122
+ return Object.freeze({
123
+ request,
124
+ get(path, options = {}) {
125
+ return request(path, { ...options, method: "GET" });
126
+ },
127
+ post(path, body, options = {}) {
128
+ return request(path, { ...options, method: "POST", body });
129
+ }
130
+ });
131
+ }
132
+
133
+ module.exports = { createFacebookWebClient, assertFacebookUrl, toFormBody };
@@ -0,0 +1,335 @@
1
+ "use strict";
2
+
3
+ const { CookieJar } = require("../network/cookieJar");
4
+ const { validateSessionCookies } = require("../security/cookies");
5
+ const { classifySessionState } = require("../security/sessionState");
6
+
7
+ const FACEBOOK_ORIGIN = "https://www.facebook.com";
8
+ const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
9
+
10
+ function sessionError(message, code, state) {
11
+ const error = new Error(message);
12
+ error.code = code;
13
+ error.sessionState = state;
14
+ error.retryable = false;
15
+ return error;
16
+ }
17
+
18
+ function detectSessionChallenge(response, html) {
19
+ const location = response.headers?.get?.("location") || "";
20
+ const target = location.toLowerCase();
21
+ if (/checkpoint|challenge/.test(target) || /checkpoint|checkpoint_required|challenge_required/i.test(html)) {
22
+ return "checkpoint";
23
+ }
24
+ if (/login\.php|\/login(?:[/?]|$)/.test(target) ||
25
+ /name=["'](?:email|pass)["']|id=["']login_form["']/i.test(html)) {
26
+ return "logged_out";
27
+ }
28
+ return "active";
29
+ }
30
+
31
+ function extractFacebookTokens(html) {
32
+ if (typeof html !== "string" || html.length > MAX_RESPONSE_BYTES) {
33
+ throw new TypeError("Facebook HTML must be text within the response size limit");
34
+ }
35
+ const read = patterns => {
36
+ for (const pattern of patterns) {
37
+ const match = pattern.exec(html);
38
+ if (match && typeof match[1] === "string" && match[1].length <= 4096) return match[1];
39
+ }
40
+ return null;
41
+ };
42
+ return Object.freeze({
43
+ fbDtsg: read([
44
+ /<input[^>]+name=["']fb_dtsg["'][^>]+value=["']([^"']+)["']/i,
45
+ /"DTSGInitialData"[^]*?"token"\s*:\s*"([^"]+)"/,
46
+ /"fb_dtsg"\s*:\s*"([^"]+)"/
47
+ ]),
48
+ lsd: read([
49
+ /<input[^>]+name=["']lsd["'][^>]+value=["']([^"']+)["']/i,
50
+ /"LSD"\s*,\s*\[\s*\]\s*,\s*\{\s*"token"\s*:\s*"([^"]+)"/
51
+ ]),
52
+ jazoest: read([
53
+ /<input[^>]+name=["']jazoest["'][^>]+value=["']([^"']+)["']/i,
54
+ /"jazoest"\s*:\s*"([^"]+)"/
55
+ ]),
56
+ hsi: read([/"hsi"\s*:\s*"([0-9]+)"/]),
57
+ spinR: read([/"__spin_r"\s*:\s*"?([0-9]+)"?/]),
58
+ spinB: read([/"__spin_b"\s*:\s*"([^"]+)"/]),
59
+ spinT: read([/"__spin_t"\s*:\s*"?([0-9]+)"?/])
60
+ });
61
+ }
62
+
63
+ function extractRealtimeConfig(html) {
64
+ // Search both known inline shapes and the bounded MqttWebConfig object.
65
+ // Facebook markup is mutable; field order is not treated as significant.
66
+ if (typeof html !== "string" || html.length > MAX_RESPONSE_BYTES) {
67
+ return Object.freeze({ endpoint: null, region: null, lastSeqId: null });
68
+ }
69
+ const scopes = [html];
70
+ const configPattern = /MqttWebConfig[^{}]{0,256}\{([^{}]{0,4096})\}/g;
71
+ let configMatch;
72
+ while ((configMatch = configPattern.exec(html)) !== null) scopes.push(configMatch[1]);
73
+
74
+ const read = (scope, patterns) => {
75
+ for (const pattern of patterns) {
76
+ const match = pattern.exec(scope);
77
+ if (match && match[1]) return match[1].replace(/\\\//g, "/");
78
+ }
79
+ return null;
80
+ };
81
+ for (const scope of scopes) {
82
+ const appId = read(scope, [
83
+ /(?:appID|app_id)\s*:\s*"?(\d+)"?/,
84
+ /["'](?:appID|app_id)["']\s*:\s*["'](\d+)["']/
85
+ ]);
86
+ if (appId && appId !== "219994525426954") continue;
87
+
88
+ const endpoint = read(scope, [
89
+ /(?:endpoint|mqttEndpoint)\s*:\s*"([^"]+)"/,
90
+ /["'](?:endpoint|mqttEndpoint)["']\s*:\s*"([^"]+)"/
91
+ ]);
92
+ if (!endpoint) continue;
93
+ let url;
94
+ try { url = new URL(endpoint); } catch { continue; }
95
+ if (url.protocol !== "wss:" || url.hostname !== "edge-chat.facebook.com" ||
96
+ url.pathname !== "/chat" || url.username || url.password ||
97
+ (url.port && url.port !== "443")) continue;
98
+
99
+ const sequence = read(scope, [
100
+ /(?:irisSeqID|iris_seq_id|lastSeqId|last_seq_id)\s*:\s*"?([0-9]{1,30})"?/,
101
+ /["'](?:irisSeqID|iris_seq_id|lastSeqId|last_seq_id)["']\s*:\s*["']([0-9]{1,30})["']/
102
+ ]);
103
+ const region = url.searchParams.get("region");
104
+ if (region && !/^[a-z]{2,8}$/i.test(region)) continue;
105
+ return Object.freeze({
106
+ endpoint: url.toString(),
107
+ region: region ? region.toLowerCase() : null,
108
+ lastSeqId: sequence
109
+ });
110
+ }
111
+ return Object.freeze({ endpoint: null, region: null, lastSeqId: null });
112
+ }
113
+
114
+ function collectResponseCookies(response, requestUrl) {
115
+ const raw = typeof response.headers?.getSetCookie === "function"
116
+ ? response.headers.getSetCookie()
117
+ : (response.headers?.get?.("set-cookie") ? [response.headers.get("set-cookie")] : []);
118
+ const host = requestUrl.hostname.toLowerCase();
119
+ const accepted = [];
120
+ const deletions = [];
121
+ for (const line of raw) {
122
+ if (typeof line !== "string" || line.length > 16_384) continue;
123
+ const parts = line.split(";");
124
+ const first = parts.shift();
125
+ const equals = first.indexOf("=");
126
+ if (equals <= 0) continue;
127
+ const key = first.slice(0, equals).trim();
128
+ const value = first.slice(equals + 1).trim();
129
+ const cookie = { key, value: value || "deleted", domain: host, path: "/", hostOnly: true, secure: false, httpOnly: false };
130
+ let maxAge = null;
131
+ for (const rawAttribute of parts) {
132
+ const index = rawAttribute.indexOf("=");
133
+ const name = (index < 0 ? rawAttribute : rawAttribute.slice(0, index)).trim().toLowerCase();
134
+ const attributeValue = index < 0 ? "" : rawAttribute.slice(index + 1).trim();
135
+ if (name === "domain") {
136
+ const domain = attributeValue.replace(/^\./, "").toLowerCase();
137
+ if (!domain || !(host === domain || host.endsWith("." + domain))) {
138
+ cookie.invalidDomain = true;
139
+ break;
140
+ }
141
+ cookie.domain = domain;
142
+ cookie.hostOnly = false;
143
+ } else if (name === "path" && attributeValue.startsWith("/")) {
144
+ cookie.path = attributeValue;
145
+ } else if (name === "secure") cookie.secure = true;
146
+ else if (name === "httponly") cookie.httpOnly = true;
147
+ else if (name === "samesite" && attributeValue) cookie.sameSite = attributeValue;
148
+ else if (name === "max-age" && /^-?\d+$/.test(attributeValue)) maxAge = Number(attributeValue);
149
+ else if (name === "expires" && attributeValue) {
150
+ const timestamp = Date.parse(attributeValue);
151
+ if (Number.isFinite(timestamp)) cookie.expires = Math.floor(timestamp / 1000);
152
+ }
153
+ }
154
+ if (cookie.invalidDomain || !/^[A-Za-z0-9_-]{1,80}$/.test(key)) continue;
155
+ const expiredByDate = Number.isFinite(cookie.expires) && cookie.expires <= Math.floor(Date.now() / 1000);
156
+ if (!value || maxAge !== null && maxAge <= 0 || expiredByDate) {
157
+ deletions.push({ key, domain: cookie.domain, path: cookie.path });
158
+ continue;
159
+ }
160
+ if (maxAge !== null) cookie.expires = Math.floor(Date.now() / 1000) + maxAge;
161
+ accepted.push(cookie);
162
+ }
163
+ return { accepted, deletions };
164
+ }
165
+
166
+ function extractIdentity(html) {
167
+ const patterns = [
168
+ /"USER_ID"\s*:\s*"?([0-9]{5,30})"?/,
169
+ /"actorID"\s*:\s*"?([0-9]{5,30})"?/,
170
+ /"ACCOUNT_ID"\s*:\s*"?([0-9]{5,30})"?/
171
+ ];
172
+ for (const pattern of patterns) {
173
+ const match = pattern.exec(html);
174
+ if (match) return match[1];
175
+ }
176
+ return null;
177
+ }
178
+
179
+ /**
180
+ * Establishes and validates an owner-supplied personal Facebook web session.
181
+ * This is a session bootstrap layer, not a password-login or MQTT implementation.
182
+ */
183
+ async function createPersonalSession({
184
+ appState,
185
+ fetchImpl = globalThis.fetch,
186
+ userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
187
+ timeoutMs = 20000,
188
+ onDiagnostic = null
189
+ } = {}) {
190
+ if (typeof fetchImpl !== "function") throw new TypeError("A Fetch-compatible implementation is required");
191
+ if (onDiagnostic !== null && typeof onDiagnostic !== "function") throw new TypeError("onDiagnostic must be a function");
192
+ const emitDiagnostic = event => { if (onDiagnostic) { try { onDiagnostic(event); } catch {} } };
193
+ if (typeof userAgent !== "string" || !userAgent.trim() || userAgent.length > 1024) {
194
+ throw new TypeError("A valid User-Agent is required");
195
+ }
196
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 120000) {
197
+ throw new TypeError("timeoutMs must be between 1000 and 120000");
198
+ }
199
+
200
+ const cookies = validateSessionCookies(appState);
201
+ const jar = new CookieJar(cookies);
202
+ const userId = cookies.find(cookie => cookie.key === "c_user")?.value;
203
+ const controller = new AbortController();
204
+ const timer = setTimeout(() => controller.abort(new Error("Facebook session validation timed out")), timeoutMs);
205
+ let closed = false;
206
+
207
+ try {
208
+ const bootstrapStartedAt = Date.now();
209
+ const bootstrapResponse = await fetchImpl(FACEBOOK_ORIGIN + "/", {
210
+ method: "GET",
211
+ redirect: "manual",
212
+ headers: {
213
+ accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
214
+ "accept-language": "en-US,en;q=0.9",
215
+ cookie: jar.getCookieHeader(FACEBOOK_ORIGIN + "/"),
216
+ "user-agent": userAgent
217
+ },
218
+ signal: controller.signal
219
+ });
220
+
221
+ const response = bootstrapResponse;
222
+ const { accepted: bootstrapCookies, deletions: bootstrapDeletions } = collectResponseCookies(response, new URL(FACEBOOK_ORIGIN + "/"));
223
+ if (bootstrapCookies.length) jar.setCookies(bootstrapCookies);
224
+ if (bootstrapDeletions.length) jar.deleteCookies(bootstrapDeletions);
225
+ emitDiagnostic({ phase: "response", request: { url: FACEBOOK_ORIGIN + "/", method: "GET" }, response: { status: response.status, contentType: response.headers?.get?.("content-type") || "", bodyBytes: Number(response.headers?.get?.("content-length") || 0) }, durationMs: Date.now() - bootstrapStartedAt });
226
+ if (response.status >= 500) {
227
+ throw sessionError("Facebook is temporarily unavailable while validating the session", "FCA_UPSTREAM_UNAVAILABLE", "error");
228
+ }
229
+ const declaredLength = Number(response.headers?.get?.("content-length") || 0);
230
+ if (declaredLength > MAX_RESPONSE_BYTES) {
231
+ throw sessionError("Facebook session response exceeded the safety limit", "FCA_RESPONSE_TOO_LARGE", "error");
232
+ }
233
+ const html = await response.text();
234
+ if (Buffer.byteLength(html, "utf8") > MAX_RESPONSE_BYTES) {
235
+ throw sessionError("Facebook session response exceeded the safety limit", "FCA_RESPONSE_TOO_LARGE", "error");
236
+ }
237
+ const state = detectSessionChallenge(response, html);
238
+ if (state === "checkpoint") {
239
+ throw sessionError("Facebook requires the account owner to complete a checkpoint", "FCA_CHECKPOINT_REQUIRED", state);
240
+ }
241
+ if (state === "logged_out" || response.status === 401 || response.status === 403) {
242
+ throw sessionError("The supplied Facebook AppState is expired or not authenticated", "FCA_SESSION_EXPIRED", "logged_out");
243
+ }
244
+ if (!response.ok) {
245
+ throw sessionError("Facebook session validation failed with HTTP " + response.status, "FCA_SESSION_VALIDATION_FAILED", "error");
246
+ }
247
+
248
+ const pageUserId = extractIdentity(html);
249
+ const pageTokens = extractFacebookTokens(html);
250
+ const realtime = extractRealtimeConfig(html);
251
+ if (pageUserId && pageUserId !== userId) {
252
+ throw sessionError("Facebook returned a different account than the supplied c_user session", "FCA_SESSION_IDENTITY_MISMATCH", "error");
253
+ }
254
+
255
+ return Object.freeze({
256
+ userId,
257
+ state: "active",
258
+ validatedAt: Date.now(),
259
+ realtime,
260
+ getTokens() {
261
+ if (closed) throw new Error("Facebook session is closed");
262
+ return { ...pageTokens };
263
+ },
264
+ getCookieHeader(url = FACEBOOK_ORIGIN + "/") {
265
+ if (closed) throw new Error("Facebook session is closed");
266
+ const target = url instanceof URL ? url : new URL(url);
267
+ if (target.protocol !== "https:" || !/(^|\.)facebook\.com$|(^|\.)messenger\.com$/.test(target.hostname)) {
268
+ throw new TypeError("Personal session cookies may only be used with Facebook/Messenger HTTPS hosts");
269
+ }
270
+ return jar.getCookieHeader(target);
271
+ },
272
+ async request(input, options = {}) {
273
+ if (closed) throw new Error("Facebook session is closed");
274
+ const target = input instanceof URL ? new URL(input.href) : new URL(input);
275
+ if (target.protocol !== "https:" || !/(^|\.)facebook\.com$|(^|\.)messenger\.com$/.test(target.hostname)) {
276
+ throw new TypeError("Personal session requests are restricted to Facebook/Messenger HTTPS hosts");
277
+ }
278
+ const method = String(options.method || "GET").toUpperCase();
279
+ if (!["GET", "HEAD", "POST"].includes(method)) {
280
+ throw new TypeError("Personal session request method is not supported");
281
+ }
282
+ const headers = new Headers(options.headers || {});
283
+ if (headers.has("cookie") || headers.has("host")) {
284
+ throw new TypeError("Cookie and Host headers are managed by the personal session");
285
+ }
286
+ headers.set("cookie", jar.getCookieHeader(target));
287
+ headers.set("user-agent", userAgent);
288
+ const requestController = new AbortController();
289
+ const timeout = setTimeout(() => requestController.abort(new Error("Facebook request timed out")), timeoutMs);
290
+ const onAbort = () => requestController.abort(options.signal.reason);
291
+ if (options.signal) {
292
+ if (options.signal.aborted) onAbort();
293
+ else options.signal.addEventListener("abort", onAbort, { once: true });
294
+ }
295
+ const requestStartedAt = Date.now();
296
+ try {
297
+ const response = await fetchImpl(target, {
298
+ ...options,
299
+ method,
300
+ headers,
301
+ redirect: "manual",
302
+ signal: requestController.signal
303
+ });
304
+ emitDiagnostic({ phase: "response", request: { url: target.origin + target.pathname, method }, response: { status: response.status, contentType: response.headers?.get?.("content-type") || "", bodyBytes: Number(response.headers?.get?.("content-length") || 0) }, durationMs: Date.now() - requestStartedAt });
305
+ const { accepted, deletions } = collectResponseCookies(response, target);
306
+ if (accepted.length) jar.setCookies(accepted);
307
+ if (deletions.length) jar.deleteCookies(deletions);
308
+ return response;
309
+ } catch (error) {
310
+ emitDiagnostic({ phase: "error", request: { url: target.origin + target.pathname, method }, errorCode: typeof error?.code === "string" ? error.code : undefined });
311
+ throw error;
312
+ } finally {
313
+ clearTimeout(timeout);
314
+ options.signal?.removeEventListener("abort", onAbort);
315
+ }
316
+ },
317
+ getAppState() {
318
+ if (closed) throw new Error("Facebook session is closed");
319
+ return jar.cookies.map(cookie => ({ ...cookie }));
320
+ },
321
+ close() { closed = true; jar.clear(); }
322
+ });
323
+ } catch (error) {
324
+ if (error?.name === "AbortError" || controller.signal.aborted) {
325
+ throw sessionError("Facebook session validation timed out", "FCA_SESSION_TIMEOUT", "error");
326
+ }
327
+ const state = classifySessionState(error);
328
+ if (state === "checkpoint" || state === "logged_out") throw error;
329
+ throw error;
330
+ } finally {
331
+ clearTimeout(timer);
332
+ }
333
+ }
334
+
335
+ module.exports = { createPersonalSession, detectSessionChallenge, extractIdentity, extractFacebookTokens, extractRealtimeConfig };
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+
5
+ function decodeBase32(secret) {
6
+ if (typeof secret !== "string" || !secret.trim()) throw new TypeError("TOTP secret must be non-empty Base32 text");
7
+ const normalized = secret.toUpperCase().replace(/[\s=-]/g, "");
8
+ if (!/^[A-Z2-7]+$/.test(normalized)) throw new TypeError("TOTP secret must use Base32 characters A-Z and 2-7");
9
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
10
+ let bits = "";
11
+ for (const char of normalized) bits += alphabet.indexOf(char).toString(2).padStart(5, "0");
12
+ const bytes = [];
13
+ for (let offset = 0; offset + 8 <= bits.length; offset += 8) bytes.push(parseInt(bits.slice(offset, offset + 8), 2));
14
+ if (!bytes.length) throw new TypeError("TOTP secret is too short");
15
+ return Buffer.from(bytes);
16
+ }
17
+
18
+ function generateTotp(secret, options = {}) {
19
+ const digits = options.digits === undefined ? 6 : options.digits;
20
+ const period = options.period === undefined ? 30 : options.period;
21
+ const algorithm = String(options.algorithm || "sha1").toLowerCase();
22
+ const timestamp = options.timestamp === undefined ? Date.now() : options.timestamp;
23
+ if (!Number.isInteger(digits) || digits < 6 || digits > 8) throw new RangeError("TOTP digits must be between 6 and 8");
24
+ if (!Number.isInteger(period) || period < 1 || period > 300) throw new RangeError("TOTP period must be between 1 and 300 seconds");
25
+ if (!Number.isFinite(timestamp) || timestamp < 0) throw new TypeError("TOTP timestamp must be a non-negative number");
26
+ if (!["sha1", "sha256", "sha512"].includes(algorithm)) throw new TypeError("Unsupported TOTP algorithm");
27
+ const counter = BigInt(Math.floor(timestamp / 1000 / period));
28
+ const message = Buffer.alloc(8);
29
+ message.writeBigUInt64BE(counter);
30
+ const digest = crypto.createHmac(algorithm, decodeBase32(secret)).update(message).digest();
31
+ const offset = digest[digest.length - 1] & 0x0f;
32
+ const binary = ((digest[offset] & 0x7f) << 24) |
33
+ ((digest[offset + 1] & 0xff) << 16) |
34
+ ((digest[offset + 2] & 0xff) << 8) |
35
+ (digest[offset + 3] & 0xff);
36
+ return String(binary % (10 ** digits)).padStart(digits, "0");
37
+ }
38
+
39
+ module.exports = { generateTotp };
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+
3
+ const { createClient } = require("../api/client");
4
+ const { createFacebookMqttDriver } = require("../transport/facebookMqttDriver");
5
+
6
+ function defaultSocketFactory({ url, protocols, headers } = {}) {
7
+ // Keep the WebSocket implementation inside the package so applications do
8
+ // not need to provide an adapter or install a separate transport dependency.
9
+ const WebSocket = require("ws");
10
+ return new WebSocket(url, protocols, { headers });
11
+ }
12
+
13
+ /**
14
+ * Creates the first-party AppState-only personal Messenger client.
15
+ * The package owns its WebSocket implementation; tests and advanced users
16
+ * may still inject a compatible socketFactory.
17
+ */
18
+ function createFacebookMqttClient(options = {}) {
19
+ const {
20
+ socketFactory = defaultSocketFactory,
21
+ fetchImpl,
22
+ userAgent,
23
+ timeoutMs,
24
+ connectTimeoutMs,
25
+ closeTimeoutMs,
26
+ protocolSetupTimeoutMs,
27
+ maxFrameBytes,
28
+ syncCursorStore,
29
+ onSyncCursor,
30
+ requestTimeoutMs,
31
+ maxPendingRequests,
32
+ mqtt,
33
+ onDiagnostic,
34
+ reconnect,
35
+ license,
36
+ requireLicense,
37
+ onLicenseError
38
+ } = options;
39
+
40
+ if (typeof socketFactory !== "function") {
41
+ throw new TypeError("socketFactory must be a function");
42
+ }
43
+
44
+ return createClient({
45
+ reconnect,
46
+ license,
47
+ requireLicense,
48
+ onLicenseError,
49
+ authenticate: ({ mode, credentials }) => {
50
+ if (mode !== "appstate") {
51
+ throw new TypeError("Native Messenger client currently supports AppState login only");
52
+ }
53
+ return createFacebookMqttDriver({
54
+ appState: credentials,
55
+ socketFactory,
56
+ fetchImpl,
57
+ userAgent,
58
+ timeoutMs,
59
+ connectTimeoutMs,
60
+ closeTimeoutMs,
61
+ protocolSetupTimeoutMs,
62
+ maxFrameBytes,
63
+ syncCursorStore,
64
+ onSyncCursor,
65
+ requestTimeoutMs,
66
+ maxPendingRequests,
67
+ mqtt,
68
+ onDiagnostic
69
+ });
70
+ }
71
+ });
72
+ }
73
+
74
+ module.exports = { createFacebookMqttClient };
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+
3
+ const { loadAccountConfig } = require("../auth/accountConfig");
4
+ const { generateTotp } = require("../auth/totp");
5
+
6
+ function fromAccountConfig(config) {
7
+ if (config.mode === "appstate") return { mode: "appstate", appState: config.appState };
8
+ return {
9
+ mode: "credentials",
10
+ ...(config.username ? { username: config.username } : { email: config.email }),
11
+ password: config.password,
12
+ twoFactorSecret: config.twoFactorSecret || null,
13
+ twoFactorCode: config.twoFactorSecret ? generateTotp(config.twoFactorSecret) : null,
14
+ userAgent: config.userAgent || null,
15
+ proxy: config.proxy || null
16
+ };
17
+ }
18
+
19
+ function createGoatBotLogin(client, accountConfigOptions = {}) {
20
+ if (!client || typeof client.login !== "function") throw new TypeError("OmegA-FCA client is required");
21
+
22
+ return function goatBotLogin(credentials, options, callback) {
23
+ if (typeof options === "function") {
24
+ callback = options;
25
+ options = {};
26
+ }
27
+ if (typeof callback !== "function") throw new TypeError("GoatBot login callback is required");
28
+ const input = credentials && typeof credentials === "object" ? credentials : {};
29
+ let loginInput;
30
+ if (Array.isArray(input.appState)) {
31
+ loginInput = { mode: "appstate", appState: input.appState };
32
+ } else if ((typeof input.username === "string" || typeof input.email === "string") &&
33
+ typeof (input.password || input.pass) === "string") {
34
+ loginInput = {
35
+ mode: "credentials",
36
+ ...(typeof input.username === "string" && input.username.trim()
37
+ ? { username: input.username.trim() }
38
+ : { email: input.email }),
39
+ password: input.password || input.pass,
40
+ twoFactorSecret: input.twoFactorSecret || input["2FASecret"] || null,
41
+ twoFactorCode: input.twoFactorCode || input.twoFactorCodeOrCode || input.twoFactorSecretOrCode || input["2FACode"] || ((input.twoFactorSecret || input["2FASecret"]) ? generateTotp(input.twoFactorSecret || input["2FASecret"]) : null),
42
+ userAgent: input.userAgent || null,
43
+ proxy: input.proxy || null
44
+ };
45
+ } else if (Object.keys(input).length === 0) {
46
+ try {
47
+ // account.txt is cookie-only; credentials and TOTP configuration live in config.json.
48
+ loginInput = fromAccountConfig(loadAccountConfig(accountConfigOptions));
49
+ } catch (error) {
50
+ callback(error);
51
+ return Promise.resolve(null);
52
+ }
53
+ } else {
54
+ const error = new TypeError("GoatBot login requires AppState, credentials, or an empty input to load account.txt/config.json");
55
+ error.retryable = false;
56
+ callback(error);
57
+ return Promise.resolve(null);
58
+ }
59
+
60
+ return client.login(loginInput, options || {}).then(
61
+ api => { callback(null, api); return api; },
62
+ error => { callback(error); return null; }
63
+ );
64
+ };
65
+ }
66
+
67
+ module.exports = { createGoatBotLogin };