@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.
- package/LICENSE +21 -0
- package/README.md +155 -2
- package/docs/ARCHITECTURE.md +126 -0
- package/docs/AUTHENTICATION-ATTEMPT.md +52 -0
- package/docs/BROWSER-CAPTURE.md +74 -0
- package/docs/DEPLOYMENT.md +80 -0
- package/docs/FACEBOOK-MQTT-TRANSPORT.md +82 -0
- package/docs/GOATBOT-COMPATIBILITY-MATRIX.md +58 -0
- package/docs/GOATBOT-INTEGRATION-AUDIT.md +64 -0
- package/docs/IMPLEMENTATION-STATUS.md +51 -0
- package/docs/META-MESSENGER-TRANSPORT.md +78 -0
- package/docs/NESTED-REALTIME-PAYLOAD.md +16 -0
- package/docs/NTKHANG-REFERENCE-STUDY.md +69 -0
- package/docs/PROTOCOL-EVIDENCE.md +69 -0
- package/docs/REALTIME-FRAME-EVIDENCE.md +33 -0
- package/docs/REFERENCE-AUDIT.md +63 -0
- package/docs/SAFE-DIAGNOSTICS.md +39 -0
- package/examples/appstate-session-check.js +33 -0
- package/examples/meta-messenger-server.js +96 -0
- package/index.d.ts +407 -0
- package/index.js +62 -0
- package/package.json +63 -4
- package/src/api/client.js +308 -0
- package/src/auth/accountConfig.js +82 -0
- package/src/auth/authenticationAttempt.js +193 -0
- package/src/auth/facebookResponse.js +93 -0
- package/src/auth/facebookWebClient.js +133 -0
- package/src/auth/personalSession.js +335 -0
- package/src/auth/totp.js +39 -0
- package/src/compat/facebookMqttClient.js +74 -0
- package/src/compat/goatbotLogin.js +67 -0
- package/src/compat/legacyFcaTransport.js +136 -0
- package/src/events/dispatcher.js +69 -0
- package/src/license/provider.js +37 -0
- package/src/license/verify.js +42 -0
- package/src/network/cookieJar.js +72 -0
- package/src/network/requestClient.js +104 -0
- package/src/runtime/connection.js +231 -0
- package/src/security/cookies.js +104 -0
- package/src/security/diagnostics.js +98 -0
- package/src/security/redact.js +23 -0
- package/src/security/sessionCrypto.js +61 -0
- package/src/security/sessionState.js +23 -0
- package/src/security/sessionStore.js +64 -0
- package/src/transport/binaryPayloadInspector.js +131 -0
- package/src/transport/contract.js +39 -0
- package/src/transport/facebookGatewayProtocol.js +135 -0
- package/src/transport/facebookMqttDriver.js +60 -0
- package/src/transport/facebookMqttEvents.js +114 -0
- package/src/transport/facebookMqttProtocol.js +213 -0
- package/src/transport/facebookThreadApi.js +284 -0
- package/src/transport/messengerActions.js +64 -0
- package/src/transport/messengerSyncCursorStore.js +53 -0
- package/src/transport/metaMessenger.js +294 -0
- package/src/transport/mqtt311Codec.js +254 -0
- package/src/transport/mqtt311StreamDecoder.js +57 -0
- package/src/transport/mqttRequestTracker.js +60 -0
- package/src/transport/nativeRealtimeTransport.js +388 -0
- package/src/transport/realtimeFrameDecoder.js +92 -0
- package/src/transport/realtimeSyncEnvelope.js +84 -0
- package/src/update/manifest.js +102 -0
- package/tools/browser-capture.js +130 -0
- package/tools/termux-capture-setup.sh +26 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { validateSessionCookies, parseCookieHeader } = require("../security/cookies");
|
|
4
|
+
const { ConnectionSupervisor } = require("../runtime/connection");
|
|
5
|
+
const { verifyLicenseToken } = require("../license/verify");
|
|
6
|
+
const { validateTransportDriver } = require("../transport/contract");
|
|
7
|
+
const { classifySessionState } = require("../security/sessionState");
|
|
8
|
+
|
|
9
|
+
const METHOD_FEATURES = Object.freeze({
|
|
10
|
+
sendMessage: "messaging", sendRequest: "messaging", unsendMessage: "messaging", markAsRead: "messaging", sendTypingIndicator: "messaging",
|
|
11
|
+
getUserInfo: "threads", getThreadInfo: "threads", getThreadList: "threads", getThreadHistory: "threads", getMessage: "threads", getFriendsList: "threads", getUserID: "threads",
|
|
12
|
+
addUserToGroup: "groups", removeUserFromGroup: "groups", createNewGroup: "groups", changeNickname: "groups",
|
|
13
|
+
setMessageReaction: "reactions"
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const DRIVER_METHODS = [
|
|
17
|
+
"sendRequest", "sendMessage", "getUserInfo", "getThreadInfo", "getThreadList", "getCurrentUserID",
|
|
18
|
+
"markAsRead", "setMessageReaction", "sendTypingIndicator", "unsendMessage",
|
|
19
|
+
"changeNickname", "addUserToGroup", "removeUserFromGroup", "createNewGroup",
|
|
20
|
+
"getThreadHistory", "getMessage", "getFriendsList", "getUserID"
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
function createClient({ authenticate, options = {}, reconnect = {}, license = {}, requireLicense = false, onLicenseError = () => {} } = {}) {
|
|
24
|
+
if (typeof authenticate !== "function") throw new TypeError("authenticate transport factory is required");
|
|
25
|
+
let supervisor = null;
|
|
26
|
+
let api = null;
|
|
27
|
+
let userId = null;
|
|
28
|
+
let verifiedLicense = null;
|
|
29
|
+
let detachMqtt = null;
|
|
30
|
+
let mqttErrorHandler = null;
|
|
31
|
+
let licenseTimer = null;
|
|
32
|
+
let licenseCheckPromise = null;
|
|
33
|
+
let loginPromise = null;
|
|
34
|
+
let logoutPromise = null;
|
|
35
|
+
|
|
36
|
+
async function checkLicense() {
|
|
37
|
+
if (!requireLicense) return null;
|
|
38
|
+
if (licenseCheckPromise) return licenseCheckPromise;
|
|
39
|
+
licenseCheckPromise = (async () => {
|
|
40
|
+
const token = typeof license.refresh === "function" ? await license.refresh() : license.token;
|
|
41
|
+
verifiedLicense = verifyLicenseToken(token, license.publicKey, {
|
|
42
|
+
installationId: license.installationId,
|
|
43
|
+
ownerId: license.ownerId
|
|
44
|
+
});
|
|
45
|
+
return verifiedLicense;
|
|
46
|
+
})().finally(() => { licenseCheckPromise = null; });
|
|
47
|
+
return licenseCheckPromise;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function startLicenseMonitor() {
|
|
51
|
+
if (!requireLicense || licenseTimer) return;
|
|
52
|
+
const interval = Number.isInteger(license.checkIntervalMs) && license.checkIntervalMs >= 30_000
|
|
53
|
+
? license.checkIntervalMs : 5 * 60 * 1000;
|
|
54
|
+
licenseTimer = setInterval(async () => {
|
|
55
|
+
try {
|
|
56
|
+
await checkLicense();
|
|
57
|
+
} catch (error) {
|
|
58
|
+
clearInterval(licenseTimer);
|
|
59
|
+
licenseTimer = null;
|
|
60
|
+
try { if (supervisor) await supervisor.stop(); } catch {}
|
|
61
|
+
supervisor = null;
|
|
62
|
+
api = null;
|
|
63
|
+
userId = null;
|
|
64
|
+
try { onLicenseError(error); } catch {}
|
|
65
|
+
}
|
|
66
|
+
}, interval);
|
|
67
|
+
if (typeof licenseTimer.unref === "function") licenseTimer.unref();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function stopLicenseMonitor() {
|
|
71
|
+
if (licenseTimer) clearInterval(licenseTimer);
|
|
72
|
+
licenseTimer = null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function performLogin(credentials = {}, loginOptions = options) {
|
|
76
|
+
if (supervisor && supervisor.snapshot().connected) return api;
|
|
77
|
+
if (supervisor && ["connecting", "reconnecting"].includes(supervisor.snapshot().state)) {
|
|
78
|
+
throw new Error("A login attempt is already in progress");
|
|
79
|
+
}
|
|
80
|
+
if (supervisor && ["failed", "stopped"].includes(supervisor.snapshot().state)) {
|
|
81
|
+
await supervisor.stop();
|
|
82
|
+
supervisor = null;
|
|
83
|
+
}
|
|
84
|
+
await checkLicense();
|
|
85
|
+
const mode = credentials.mode;
|
|
86
|
+
let normalized;
|
|
87
|
+
if (mode === "appstate") {
|
|
88
|
+
normalized = validateSessionCookies(credentials.appState);
|
|
89
|
+
} else if (mode === "cookie") {
|
|
90
|
+
normalized = validateSessionCookies(parseCookieHeader(credentials.cookie));
|
|
91
|
+
} else if (mode === "credentials") {
|
|
92
|
+
throw new TypeError("Facebook email/username and password login is deferred; use an authorized AppState or cookie");
|
|
93
|
+
} else {
|
|
94
|
+
throw new TypeError("Login mode must be appstate or cookie");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let lastConnectError = null;
|
|
98
|
+
supervisor = new ConnectionSupervisor({
|
|
99
|
+
connect: async context => {
|
|
100
|
+
let result;
|
|
101
|
+
try {
|
|
102
|
+
result = await authenticate({ mode, credentials: normalized, options: loginOptions || {}, context, license: verifiedLicense });
|
|
103
|
+
} catch (caught) {
|
|
104
|
+
// Provider-controlled messages and causes may echo credentials,
|
|
105
|
+
// cookies, challenge answers, or tokens. Classify privately, then
|
|
106
|
+
// expose only a fixed safe error to the application.
|
|
107
|
+
const sessionState = classifySessionState(caught);
|
|
108
|
+
const error = new Error(sessionState === "checkpoint"
|
|
109
|
+
? "Facebook requires the account owner to complete a checkpoint"
|
|
110
|
+
: sessionState === "logged_out"
|
|
111
|
+
? "The Facebook session has expired; supply a fresh authorized AppState"
|
|
112
|
+
: "Authentication failed; inspect provider diagnostics securely");
|
|
113
|
+
if (sessionState === "checkpoint") {
|
|
114
|
+
error.code = "FCA_CHECKPOINT_REQUIRED";
|
|
115
|
+
error.sessionState = sessionState;
|
|
116
|
+
error.retryable = false;
|
|
117
|
+
} else if (sessionState === "logged_out") {
|
|
118
|
+
error.code = "FCA_SESSION_EXPIRED";
|
|
119
|
+
error.sessionState = sessionState;
|
|
120
|
+
error.retryable = false;
|
|
121
|
+
} else {
|
|
122
|
+
error.code = caught?.code === "FCA_CHALLENGE_LIMIT"
|
|
123
|
+
? "FCA_CHALLENGE_LIMIT" : "FCA_AUTHENTICATION_FAILED";
|
|
124
|
+
error.retryable = typeof caught?.retryable === "boolean" ? caught.retryable : true;
|
|
125
|
+
}
|
|
126
|
+
lastConnectError = error;
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
return validateTransportDriver(result);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
// Preserve the local contract error for the caller, while disposing
|
|
133
|
+
// any provider resource allocated before the invalid result.
|
|
134
|
+
lastConnectError = error;
|
|
135
|
+
if (result && typeof result.disconnect === "function") {
|
|
136
|
+
try { await result.disconnect(); }
|
|
137
|
+
catch (cleanupError) { error.cleanupError = cleanupError; }
|
|
138
|
+
}
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
disconnect: async driver => {
|
|
143
|
+
if (typeof driver.disconnect === "function") await driver.disconnect();
|
|
144
|
+
},
|
|
145
|
+
options: reconnect
|
|
146
|
+
});
|
|
147
|
+
const driver = await supervisor.start();
|
|
148
|
+
if (!driver) throw lastConnectError || new Error("Connection stopped before authentication completed");
|
|
149
|
+
let currentUserId;
|
|
150
|
+
try {
|
|
151
|
+
currentUserId = typeof driver.getCurrentUserID === "function" ? await driver.getCurrentUserID() : null;
|
|
152
|
+
} catch (error) {
|
|
153
|
+
// A driver that connects but cannot complete identity initialization must
|
|
154
|
+
// not leave an unreachable live session behind.
|
|
155
|
+
try { await supervisor.stop(); }
|
|
156
|
+
catch (cleanupError) { error.cleanupError = cleanupError; }
|
|
157
|
+
finally { supervisor = null; }
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
userId = currentUserId == null ? null : String(currentUserId);
|
|
161
|
+
const facade = {};
|
|
162
|
+
for (const method of DRIVER_METHODS) {
|
|
163
|
+
if (typeof driver[method] === "function") {
|
|
164
|
+
facade[method] = (...args) => {
|
|
165
|
+
const feature = METHOD_FEATURES[method];
|
|
166
|
+
if (requireLicense && feature && !verifiedLicense.features.includes(feature)) {
|
|
167
|
+
const error = new Error("License does not include the " + feature + " feature");
|
|
168
|
+
error.code = "FCA_LICENSE_FEATURE_DENIED";
|
|
169
|
+
return Promise.reject(error);
|
|
170
|
+
}
|
|
171
|
+
return driver[method](...args);
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (typeof driver.sendMessage === "function") {
|
|
176
|
+
facade.sendMessage = (message, threadID, callback, replyToMessageID) => {
|
|
177
|
+
let input;
|
|
178
|
+
let done;
|
|
179
|
+
let requestOptions;
|
|
180
|
+
if (typeof threadID === "string" || typeof threadID === "number") {
|
|
181
|
+
input = { threadID, message };
|
|
182
|
+
done = typeof callback === "function" ? callback : null;
|
|
183
|
+
if (replyToMessageID != null) input.replyToMessageID = replyToMessageID;
|
|
184
|
+
} else {
|
|
185
|
+
input = message;
|
|
186
|
+
done = typeof threadID === "function" ? threadID : null;
|
|
187
|
+
requestOptions = threadID && typeof threadID === "object" ? threadID : undefined;
|
|
188
|
+
}
|
|
189
|
+
const operation = Promise.resolve().then(() => driver.sendMessage(input, requestOptions));
|
|
190
|
+
if (done) {
|
|
191
|
+
operation.then(value => done(null, value), error => done(error));
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
return operation;
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
if (typeof driver.getUserID !== "function") {
|
|
198
|
+
facade.getUserID = () => userId;
|
|
199
|
+
}
|
|
200
|
+
facade.getCurrentUserID = () => userId;
|
|
201
|
+
facade.listen = callback => {
|
|
202
|
+
if (requireLicense && !verifiedLicense.features.includes("events")) throw new Error("License does not include the events feature");
|
|
203
|
+
return supervisor.listen(callback);
|
|
204
|
+
};
|
|
205
|
+
facade.listenMqtt = callback => {
|
|
206
|
+
if (requireLicense && !verifiedLicense.features.includes("events")) throw new Error("License does not include the events feature");
|
|
207
|
+
if (typeof callback !== "function") throw new TypeError("MQTT callback is required");
|
|
208
|
+
if (detachMqtt) throw new Error("MQTT listener is already active");
|
|
209
|
+
mqttErrorHandler = error => callback(error, null);
|
|
210
|
+
supervisor.on("listenerError", mqttErrorHandler);
|
|
211
|
+
try {
|
|
212
|
+
const detach = supervisor.listen(event => callback(null, event));
|
|
213
|
+
detachMqtt = () => {
|
|
214
|
+
supervisor.off("listenerError", mqttErrorHandler);
|
|
215
|
+
mqttErrorHandler = null;
|
|
216
|
+
detach();
|
|
217
|
+
detachMqtt = null;
|
|
218
|
+
};
|
|
219
|
+
// FCA-compatible readiness signal: the native driver has already
|
|
220
|
+
// completed AppState validation, MQTT CONNACK and topic subscription
|
|
221
|
+
// before the client is exposed. This lets GoatBot gate startup/recovery
|
|
222
|
+
// on an explicit ready event instead of guessing from socket creation.
|
|
223
|
+
queueMicrotask(() => {
|
|
224
|
+
if (detachMqtt) {
|
|
225
|
+
try {
|
|
226
|
+
callback(null, Object.freeze({
|
|
227
|
+
type: "ready",
|
|
228
|
+
source: "omega-fca",
|
|
229
|
+
connectionState: supervisor.snapshot()
|
|
230
|
+
}));
|
|
231
|
+
} catch (error) {
|
|
232
|
+
try { supervisor.emit("listenerCallbackError", error); } catch {}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
return detachMqtt;
|
|
237
|
+
} catch (error) {
|
|
238
|
+
// Roll back the error subscription if listener attachment fails.
|
|
239
|
+
supervisor.off("listenerError", mqttErrorHandler);
|
|
240
|
+
mqttErrorHandler = null;
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
facade.stopListening = callback => {
|
|
245
|
+
if (detachMqtt) detachMqtt();
|
|
246
|
+
if (typeof callback === "function") callback();
|
|
247
|
+
return true;
|
|
248
|
+
};
|
|
249
|
+
facade.stopSessionGuard = typeof driver.stopSessionGuard === "function" ? driver.stopSessionGuard.bind(driver) : undefined;
|
|
250
|
+
facade.sessionGuard = typeof driver.sessionGuard === "function" ? driver.sessionGuard.bind(driver) : undefined;
|
|
251
|
+
facade.setOptions = typeof driver.setOptions === "function" ? driver.setOptions.bind(driver) : undefined;
|
|
252
|
+
facade.getCapabilities = () => Object.freeze({
|
|
253
|
+
methods: Object.freeze(DRIVER_METHODS.filter(method => typeof driver[method] === "function")),
|
|
254
|
+
events: typeof driver.listen === "function",
|
|
255
|
+
sessionGuard: typeof driver.sessionGuard === "function",
|
|
256
|
+
e2ee: false
|
|
257
|
+
});
|
|
258
|
+
facade.getConnectionState = () => supervisor.snapshot();
|
|
259
|
+
facade.getLicense = () => verifiedLicense;
|
|
260
|
+
api = Object.freeze(facade);
|
|
261
|
+
startLicenseMonitor();
|
|
262
|
+
return api;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function login(credentials = {}, loginOptions = options) {
|
|
266
|
+
if (logoutPromise) {
|
|
267
|
+
return Promise.reject(new Error("Logout is already in progress"));
|
|
268
|
+
}
|
|
269
|
+
if (loginPromise) {
|
|
270
|
+
return Promise.reject(new Error("A login attempt is already in progress"));
|
|
271
|
+
}
|
|
272
|
+
// Reserve the login slot synchronously, before performLogin reaches its
|
|
273
|
+
// first await, so concurrent callers cannot create two live supervisors.
|
|
274
|
+
loginPromise = performLogin(credentials, loginOptions).finally(() => {
|
|
275
|
+
loginPromise = null;
|
|
276
|
+
});
|
|
277
|
+
return loginPromise;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return Object.freeze({
|
|
281
|
+
login,
|
|
282
|
+
logout() {
|
|
283
|
+
if (logoutPromise) return logoutPromise;
|
|
284
|
+
stopLicenseMonitor();
|
|
285
|
+
const pendingLogin = loginPromise;
|
|
286
|
+
logoutPromise = (async () => {
|
|
287
|
+
// If logout races authentication, wait for that attempt to settle and
|
|
288
|
+
// then dispose any session it managed to establish.
|
|
289
|
+
if (pendingLogin) {
|
|
290
|
+
try { await pendingLogin; } catch {}
|
|
291
|
+
}
|
|
292
|
+
if (detachMqtt) detachMqtt();
|
|
293
|
+
if (supervisor) await supervisor.stop();
|
|
294
|
+
supervisor = null;
|
|
295
|
+
api = null;
|
|
296
|
+
userId = null;
|
|
297
|
+
verifiedLicense = null;
|
|
298
|
+
})().finally(() => {
|
|
299
|
+
logoutPromise = null;
|
|
300
|
+
});
|
|
301
|
+
return logoutPromise;
|
|
302
|
+
},
|
|
303
|
+
getConnectionState: () => supervisor ? supervisor.snapshot() : Object.freeze({ state: "idle", connected: false, generation: 0 }),
|
|
304
|
+
getLicense: () => verifiedLicense
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
module.exports = { createClient };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { parseCookieHeader, parseNetscapeCookies, normalizeCookies } = require("../security/cookies");
|
|
6
|
+
|
|
7
|
+
function resolveProjectFile(root, filePath, label) {
|
|
8
|
+
const target = path.resolve(root, filePath);
|
|
9
|
+
const relative = path.relative(root, target);
|
|
10
|
+
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
|
|
11
|
+
throw new TypeError(label + " must be inside the project root");
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
const real = fs.realpathSync(target);
|
|
15
|
+
const realRelative = path.relative(root, real);
|
|
16
|
+
if (!realRelative || realRelative.startsWith("..") || path.isAbsolute(realRelative)) {
|
|
17
|
+
throw new TypeError(label + " must resolve inside the project root");
|
|
18
|
+
}
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error.code !== "ENOENT") throw error;
|
|
21
|
+
}
|
|
22
|
+
return target;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function parseAccountText(text) {
|
|
26
|
+
if (typeof text !== "string" || !text.trim()) throw new TypeError("account.txt must contain cookie data");
|
|
27
|
+
const source = text.trim();
|
|
28
|
+
if (source.length > 256 * 1024) throw new TypeError("account.txt exceeds 256 KiB");
|
|
29
|
+
if (/^(?:fb_email|email|fb_username|username|fb_password|password|fb_2fa_secret|2FASecret)\s*=/im.test(source)) {
|
|
30
|
+
throw new TypeError("account.txt is AppState/cookie-only; put fb_email, password and 2FASecret in config.json → facebookAccount");
|
|
31
|
+
}
|
|
32
|
+
if (source.startsWith("[") || source.startsWith("{")) {
|
|
33
|
+
const parsed = JSON.parse(source);
|
|
34
|
+
const cookies = Array.isArray(parsed) ? parsed : parsed && (parsed.appState || parsed.cookies);
|
|
35
|
+
if (!Array.isArray(cookies)) throw new TypeError("account.txt JSON must contain a cookie array");
|
|
36
|
+
return normalizeCookies(cookies);
|
|
37
|
+
}
|
|
38
|
+
if (source.startsWith("#") || source.includes("\t")) return parseNetscapeCookies(source);
|
|
39
|
+
return parseCookieHeader(source.replace(/\|/g, ";"));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
function loadAccountConfig({
|
|
44
|
+
cwd = process.cwd(),
|
|
45
|
+
accountFile = "account.txt",
|
|
46
|
+
configFile = "config.json", // Reserved for the later credential-login phase; not read here.
|
|
47
|
+
appStateFile = null,
|
|
48
|
+
env = process.env
|
|
49
|
+
} = {}) {
|
|
50
|
+
const root = path.resolve(cwd);
|
|
51
|
+
const accountPath = resolveProjectFile(root, accountFile, "accountFile");
|
|
52
|
+
try {
|
|
53
|
+
const stat = fs.statSync(accountPath);
|
|
54
|
+
if (!stat.isFile()) throw new Error("account.txt must be a regular file");
|
|
55
|
+
const raw = fs.readFileSync(accountPath, "utf8").trim();
|
|
56
|
+
if (raw) return Object.freeze({ mode: "appstate", appState: parseAccountText(raw), source: "account.txt" });
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (error.code !== "ENOENT") throw error;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// This release path is intentionally AppState-only. Credential login is
|
|
62
|
+
// deferred; config.json and FB_* environment values are not read here.
|
|
63
|
+
|
|
64
|
+
const statePath = resolveProjectFile(root, appStateFile || "appstate.json", "AppState file");
|
|
65
|
+
try {
|
|
66
|
+
const stat = fs.statSync(statePath);
|
|
67
|
+
if (!stat.isFile() || stat.size > 1024 * 1024) throw new Error("AppState file must be a regular file no larger than 1 MiB");
|
|
68
|
+
const parsed = JSON.parse(fs.readFileSync(statePath, "utf8"));
|
|
69
|
+
const appState = Array.isArray(parsed) ? parsed : parsed && (parsed.appState || parsed.cookies);
|
|
70
|
+
if (!Array.isArray(appState) || appState.length === 0) throw new Error("AppState file must contain a non-empty cookie array");
|
|
71
|
+
return Object.freeze({ mode: "appstate", appState: normalizeCookies(appState), source: "appstate.json" });
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (error.code === "ENOENT") {
|
|
74
|
+
const missing = new Error("No Facebook AppState found: add cookies to account.txt or appstate.json");
|
|
75
|
+
missing.code = "FCA_ACCOUNT_CONFIG_MISSING";
|
|
76
|
+
throw missing;
|
|
77
|
+
}
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
module.exports = { parseAccountText, loadAccountConfig, resolveProjectFile };
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const STATES = Object.freeze([
|
|
4
|
+
"idle", "authenticating", "challenge_required", "verifying_challenge",
|
|
5
|
+
"authenticated", "failed", "closed"
|
|
6
|
+
]);
|
|
7
|
+
|
|
8
|
+
function publicFailure() {
|
|
9
|
+
// Never return provider-controlled messages, names, codes, or causes to callers.
|
|
10
|
+
return new Error("Authentication failed; inspect the provider error securely");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function publicChallenge(value) {
|
|
14
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
15
|
+
throw new TypeError("Authentication provider returned an invalid challenge");
|
|
16
|
+
}
|
|
17
|
+
const type = typeof value.type === "string" && /^[a-z0-9_-]{1,64}$/i.test(value.type.trim())
|
|
18
|
+
? value.type.trim() : "verification";
|
|
19
|
+
// Provider messages may echo credentials, cookies, or challenge answers.
|
|
20
|
+
// Keep the public prompt generic; the provider retains richer private state.
|
|
21
|
+
const message = "Additional account verification is required.";
|
|
22
|
+
const methods = Array.isArray(value.methods)
|
|
23
|
+
? value.methods.filter(item => typeof item === "string" && /^[a-z0-9_-]{1,64}$/i.test(item.trim())).map(item => item.trim()).slice(0, 10) : [];
|
|
24
|
+
return Object.freeze({ type, message, methods: Object.freeze(methods) });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Owns one authentication attempt and its owner-mediated challenge handoff.
|
|
29
|
+
*
|
|
30
|
+
* A provider returns { status: "authenticated", session } or
|
|
31
|
+
* { status: "challenge_required", challenge, resume(answer), cancel?() }.
|
|
32
|
+
* The resume and optional cancel functions remain private to this attempt.
|
|
33
|
+
*/
|
|
34
|
+
function createAuthenticationAttempt({ authenticate, maxChallengeRounds = 3 } = {}) {
|
|
35
|
+
if (typeof authenticate !== "function") throw new TypeError("authenticate must be a function");
|
|
36
|
+
if (!Number.isInteger(maxChallengeRounds) || maxChallengeRounds < 1 || maxChallengeRounds > 5) {
|
|
37
|
+
throw new RangeError("maxChallengeRounds must be between 1 and 5");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let state = "idle";
|
|
41
|
+
let challenge = null;
|
|
42
|
+
let resumeProvider = null;
|
|
43
|
+
let cancelProvider = null;
|
|
44
|
+
let credentials = null;
|
|
45
|
+
let options = null;
|
|
46
|
+
let session = null;
|
|
47
|
+
let operation = null;
|
|
48
|
+
let challengeRounds = 0;
|
|
49
|
+
let lastError = null;
|
|
50
|
+
|
|
51
|
+
function snapshot() {
|
|
52
|
+
return Object.freeze({
|
|
53
|
+
state,
|
|
54
|
+
challenge,
|
|
55
|
+
challengeRounds,
|
|
56
|
+
authenticated: state === "authenticated",
|
|
57
|
+
error: lastError ? Object.freeze({
|
|
58
|
+
name: "Error",
|
|
59
|
+
code: null,
|
|
60
|
+
// Provider-controlled codes can also contain echoed secrets; expose none.
|
|
61
|
+
message: "Authentication failed; inspect the provider error securely"
|
|
62
|
+
}) : null
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function ensureOpen() {
|
|
67
|
+
if (state === "closed") throw new Error("Authentication attempt is closed");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function consume(result) {
|
|
71
|
+
if (!result || typeof result !== "object") {
|
|
72
|
+
throw new TypeError("Authentication provider returned an invalid result");
|
|
73
|
+
}
|
|
74
|
+
if (result.status === "authenticated") {
|
|
75
|
+
if (!result.session || typeof result.session !== "object") {
|
|
76
|
+
throw new TypeError("Authenticated result must include a session object");
|
|
77
|
+
}
|
|
78
|
+
session = result.session;
|
|
79
|
+
resumeProvider = null;
|
|
80
|
+
cancelProvider = null;
|
|
81
|
+
challenge = null;
|
|
82
|
+
credentials = null;
|
|
83
|
+
options = null;
|
|
84
|
+
state = "authenticated";
|
|
85
|
+
return session;
|
|
86
|
+
}
|
|
87
|
+
if (result.status === "challenge_required") {
|
|
88
|
+
if (typeof result.resume !== "function") {
|
|
89
|
+
throw new TypeError("Challenge result must include a resume(answer) function");
|
|
90
|
+
}
|
|
91
|
+
challengeRounds += 1;
|
|
92
|
+
if (challengeRounds > maxChallengeRounds) {
|
|
93
|
+
if (typeof result.cancel === "function") {
|
|
94
|
+
try { await result.cancel(); } catch {}
|
|
95
|
+
}
|
|
96
|
+
throw Object.assign(new Error("Authentication challenge limit exceeded"), {
|
|
97
|
+
code: "FCA_CHALLENGE_LIMIT", retryable: false
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
challenge = publicChallenge(result.challenge);
|
|
101
|
+
resumeProvider = result.resume;
|
|
102
|
+
cancelProvider = typeof result.cancel === "function" ? result.cancel : null;
|
|
103
|
+
state = "challenge_required";
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
throw new TypeError("Authentication provider status must be authenticated or challenge_required");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function begin(input, loginOptions = {}) {
|
|
110
|
+
ensureOpen();
|
|
111
|
+
if (state !== "idle") return Promise.reject(new Error("Authentication attempt has already started"));
|
|
112
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) {
|
|
113
|
+
return Promise.reject(new TypeError("Authentication credentials must be an object"));
|
|
114
|
+
}
|
|
115
|
+
credentials = input;
|
|
116
|
+
options = loginOptions && typeof loginOptions === "object" ? loginOptions : {};
|
|
117
|
+
state = "authenticating";
|
|
118
|
+
operation = Promise.resolve().then(() => authenticate({ credentials, options }))
|
|
119
|
+
.then(consume)
|
|
120
|
+
.catch(error => {
|
|
121
|
+
lastError = error instanceof Error ? error : new Error("Authentication provider failed");
|
|
122
|
+
state = "failed";
|
|
123
|
+
resumeProvider = null;
|
|
124
|
+
cancelProvider = null;
|
|
125
|
+
challenge = null;
|
|
126
|
+
credentials = null;
|
|
127
|
+
options = null;
|
|
128
|
+
if (lastError.code === "FCA_CHALLENGE_LIMIT") throw Object.assign(new Error("Authentication challenge limit exceeded"), { code: "FCA_CHALLENGE_LIMIT", retryable: false });
|
|
129
|
+
throw publicFailure();
|
|
130
|
+
})
|
|
131
|
+
.finally(() => { operation = null; });
|
|
132
|
+
return operation;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function submitChallenge(answer) {
|
|
136
|
+
ensureOpen();
|
|
137
|
+
if (state !== "challenge_required" || typeof resumeProvider !== "function") {
|
|
138
|
+
return Promise.reject(new Error("No authentication challenge is waiting for an answer"));
|
|
139
|
+
}
|
|
140
|
+
if (operation) return Promise.reject(new Error("Authentication operation is already in progress"));
|
|
141
|
+
if (answer == null || (typeof answer !== "string" && (typeof answer !== "object" || Array.isArray(answer)))) {
|
|
142
|
+
return Promise.reject(new TypeError("Challenge answer must be a string or an object"));
|
|
143
|
+
}
|
|
144
|
+
const resume = resumeProvider;
|
|
145
|
+
const cancelPending = cancelProvider;
|
|
146
|
+
resumeProvider = null;
|
|
147
|
+
state = "verifying_challenge";
|
|
148
|
+
operation = Promise.resolve().then(() => resume(answer))
|
|
149
|
+
.then(consume)
|
|
150
|
+
.catch(async error => {
|
|
151
|
+
if (cancelPending) {
|
|
152
|
+
try { await cancelPending(); } catch {}
|
|
153
|
+
}
|
|
154
|
+
lastError = error instanceof Error ? error : new Error("Challenge verification failed");
|
|
155
|
+
state = "failed";
|
|
156
|
+
resumeProvider = null;
|
|
157
|
+
cancelProvider = null;
|
|
158
|
+
challenge = null;
|
|
159
|
+
credentials = null;
|
|
160
|
+
options = null;
|
|
161
|
+
if (lastError.code === "FCA_CHALLENGE_LIMIT") throw Object.assign(new Error("Authentication challenge limit exceeded"), { code: "FCA_CHALLENGE_LIMIT", retryable: false });
|
|
162
|
+
throw publicFailure();
|
|
163
|
+
})
|
|
164
|
+
.finally(() => { operation = null; });
|
|
165
|
+
return operation;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function close() {
|
|
169
|
+
if (state === "closed") return;
|
|
170
|
+
if (operation) {
|
|
171
|
+
try { await operation; } catch {}
|
|
172
|
+
}
|
|
173
|
+
const active = session;
|
|
174
|
+
const cancel = cancelProvider;
|
|
175
|
+
session = null;
|
|
176
|
+
resumeProvider = null;
|
|
177
|
+
cancelProvider = null;
|
|
178
|
+
challenge = null;
|
|
179
|
+
credentials = null;
|
|
180
|
+
options = null;
|
|
181
|
+
lastError = null;
|
|
182
|
+
state = "closed";
|
|
183
|
+
try {
|
|
184
|
+
if (cancel) await cancel();
|
|
185
|
+
} finally {
|
|
186
|
+
if (active && typeof active.close === "function") await active.close();
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return Object.freeze({ begin, submitChallenge, close, snapshot });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
module.exports = { createAuthenticationAttempt, AUTHENTICATION_ATTEMPT_STATES: STATES };
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { classifySessionState } = require("../security/sessionState");
|
|
4
|
+
|
|
5
|
+
function createFacebookError(message, { code, status, sessionState = "error", retryable } = {}) {
|
|
6
|
+
const error = new Error(message || "Facebook request failed");
|
|
7
|
+
error.code = code || "FCA_FACEBOOK_REQUEST_FAILED";
|
|
8
|
+
error.status = Number.isInteger(status) ? status : null;
|
|
9
|
+
error.sessionState = sessionState;
|
|
10
|
+
error.retryable = typeof retryable === "boolean" ? retryable : sessionState === "error";
|
|
11
|
+
return error;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function stripFacebookJsonPrefix(body) {
|
|
15
|
+
return body.replace(/^\uFEFF/, "").replace(/^\s*(?:for\s*\(;;\)\s*;|while\s*\(\s*1\s*\)\s*;|\)\]\}',?)/, "").trim();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function normalizeFacebookResponse(body, { status = 200, contentType = "application/json" } = {}) {
|
|
19
|
+
if (typeof body !== "string" || body.length > 8 * 1024 * 1024) {
|
|
20
|
+
throw createFacebookError("Facebook response body is missing or exceeds 8 MiB", {
|
|
21
|
+
code: "FCA_RESPONSE_INVALID", status, retryable: false
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
const text = stripFacebookJsonPrefix(body);
|
|
25
|
+
if (/checkpoint|challenge_required|checkpoint_required/i.test(text)) {
|
|
26
|
+
throw createFacebookError("Facebook requires the account owner to complete a checkpoint", {
|
|
27
|
+
code: "FCA_CHECKPOINT_REQUIRED", status, sessionState: "checkpoint", retryable: false
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
if (/login\.php|login_required|invalid session|not logged in/i.test(text)) {
|
|
31
|
+
throw createFacebookError("Facebook session is no longer authenticated", {
|
|
32
|
+
code: "FCA_SESSION_EXPIRED", status, sessionState: "logged_out", retryable: false
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
let payload;
|
|
36
|
+
try {
|
|
37
|
+
payload = JSON.parse(text);
|
|
38
|
+
} catch {
|
|
39
|
+
if (status === 429) {
|
|
40
|
+
throw createFacebookError("Facebook rate-limited the request", {
|
|
41
|
+
code: "FCA_RATE_LIMITED", status, retryable: true
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
if (status >= 500) {
|
|
45
|
+
throw createFacebookError("Facebook server request failed with HTTP " + status, {
|
|
46
|
+
code: "FCA_UPSTREAM_UNAVAILABLE", status, retryable: true
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
throw createFacebookError("Facebook returned a non-JSON response (" + String(contentType).slice(0, 100) + ")", {
|
|
50
|
+
code: "FCA_RESPONSE_NOT_JSON", status, retryable: false
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const errorData = payload && typeof payload === "object"
|
|
55
|
+
? (payload.error || payload.errors?.[0] || null)
|
|
56
|
+
: null;
|
|
57
|
+
if (errorData) {
|
|
58
|
+
const message = [
|
|
59
|
+
errorData.message,
|
|
60
|
+
errorData.error_user_msg,
|
|
61
|
+
errorData.errorDescription,
|
|
62
|
+
errorData.errorSummary
|
|
63
|
+
].filter(value => typeof value === "string" && value.trim()).join(": ") || "Facebook rejected the request";
|
|
64
|
+
const state = classifySessionState({
|
|
65
|
+
message,
|
|
66
|
+
code: errorData.code || errorData.error_code
|
|
67
|
+
});
|
|
68
|
+
const code = state === "checkpoint" ? "FCA_CHECKPOINT_REQUIRED"
|
|
69
|
+
: state === "logged_out" ? "FCA_SESSION_EXPIRED"
|
|
70
|
+
: Number(errorData.code || errorData.error_code) === 429 ? "FCA_RATE_LIMITED"
|
|
71
|
+
: "FCA_FACEBOOK_REQUEST_REJECTED";
|
|
72
|
+
throw createFacebookError(message, {
|
|
73
|
+
code,
|
|
74
|
+
status,
|
|
75
|
+
sessionState: state,
|
|
76
|
+
retryable: state === "error" && (status === 429 || status >= 500)
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
if (status === 429 || status >= 500) {
|
|
80
|
+
throw createFacebookError("Facebook server request failed with HTTP " + status, {
|
|
81
|
+
code: status === 429 ? "FCA_RATE_LIMITED" : "FCA_UPSTREAM_UNAVAILABLE",
|
|
82
|
+
status, retryable: true
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
if (status < 200 || status >= 300) {
|
|
86
|
+
throw createFacebookError("Facebook request failed with HTTP " + status, {
|
|
87
|
+
code: "FCA_HTTP_ERROR", status, retryable: false
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return payload;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
module.exports = { normalizeFacebookResponse, stripFacebookJsonPrefix, createFacebookError };
|