@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,231 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { EventEmitter } = require("node:events");
|
|
4
|
+
|
|
5
|
+
const DEFAULTS = Object.freeze({ minDelayMs: 1000, maxDelayMs: 30000, factor: 2, jitter: 0.2, maxAttempts: 8 });
|
|
6
|
+
|
|
7
|
+
class ConnectionSupervisor extends EventEmitter {
|
|
8
|
+
constructor({ connect, disconnect, options = {}, random = Math.random, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) } = {}) {
|
|
9
|
+
super();
|
|
10
|
+
if (typeof connect !== "function") throw new TypeError("connect function is required");
|
|
11
|
+
this.connectDriver = connect;
|
|
12
|
+
this.disconnectDriver = typeof disconnect === "function" ? disconnect : async () => {};
|
|
13
|
+
this.options = { ...DEFAULTS, ...options };
|
|
14
|
+
this.random = random;
|
|
15
|
+
this.sleep = sleep;
|
|
16
|
+
this.state = "idle";
|
|
17
|
+
this.driver = null;
|
|
18
|
+
this.generation = 0;
|
|
19
|
+
this.startPromise = null;
|
|
20
|
+
this.stopPromise = null;
|
|
21
|
+
this.stopRequested = false;
|
|
22
|
+
this.listenerAttached = false;
|
|
23
|
+
this.recovering = false;
|
|
24
|
+
this.eventCallback = null;
|
|
25
|
+
this.detachDriverListener = null;
|
|
26
|
+
this.connectAbortController = null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
snapshot() { return Object.freeze({ state: this.state, connected: Boolean(this.driver), generation: this.generation }); }
|
|
30
|
+
|
|
31
|
+
async start() {
|
|
32
|
+
// A new connection must not clear stopRequested while the previous
|
|
33
|
+
// driver's disconnect is still in flight.
|
|
34
|
+
if (this.stopPromise) await this.stopPromise;
|
|
35
|
+
if (this.startPromise) return this.startPromise;
|
|
36
|
+
if (this.state === "connected") return this.driver;
|
|
37
|
+
this.stopRequested = false;
|
|
38
|
+
this.startPromise = this.#startLoop().finally(() => { this.startPromise = null; });
|
|
39
|
+
return this.startPromise;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async #startLoop() {
|
|
43
|
+
let attempt = 0;
|
|
44
|
+
while (!this.stopRequested && attempt < this.options.maxAttempts) {
|
|
45
|
+
this.#setState(attempt ? "reconnecting" : "connecting");
|
|
46
|
+
const generation = ++this.generation;
|
|
47
|
+
try {
|
|
48
|
+
const controller = new AbortController();
|
|
49
|
+
this.connectAbortController = controller;
|
|
50
|
+
const connectPromise = Promise.resolve().then(() =>
|
|
51
|
+
this.connectDriver({ attempt, generation, signal: controller.signal })
|
|
52
|
+
);
|
|
53
|
+
let connectResultConsumed = false;
|
|
54
|
+
let rejectAbort;
|
|
55
|
+
const abortPromise = new Promise((_, reject) => {
|
|
56
|
+
rejectAbort = () => reject(controller.signal.reason ||
|
|
57
|
+
Object.assign(new Error("Connection attempt aborted"), { name: "AbortError", retryable: false }));
|
|
58
|
+
if (controller.signal.aborted) rejectAbort();
|
|
59
|
+
else controller.signal.addEventListener("abort", rejectAbort, { once: true });
|
|
60
|
+
});
|
|
61
|
+
let driver;
|
|
62
|
+
try {
|
|
63
|
+
driver = await Promise.race([connectPromise, abortPromise]);
|
|
64
|
+
connectResultConsumed = true;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
// Providers should honor the signal. If one does not and resolves
|
|
67
|
+
// later, dispose its driver instead of leaking an orphaned session.
|
|
68
|
+
void connectPromise.then(lateDriver => {
|
|
69
|
+
if (!connectResultConsumed && lateDriver) {
|
|
70
|
+
return Promise.resolve().then(() => this.disconnectDriver(lateDriver)).catch(disconnectError => {
|
|
71
|
+
try { this.emit("connectionError", disconnectError); } catch {}
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}, () => {});
|
|
75
|
+
throw error;
|
|
76
|
+
} finally {
|
|
77
|
+
if (rejectAbort) controller.signal.removeEventListener("abort", rejectAbort);
|
|
78
|
+
if (this.connectAbortController === controller) this.connectAbortController = null;
|
|
79
|
+
}
|
|
80
|
+
if (this.stopRequested || generation !== this.generation) {
|
|
81
|
+
await this.disconnectDriver(driver);
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
if (!driver || typeof driver.listen !== "function") {
|
|
85
|
+
const error = new Error("Transport driver must expose listen(callback)");
|
|
86
|
+
error.retryable = false;
|
|
87
|
+
if (driver && typeof driver === "object") {
|
|
88
|
+
try { await this.disconnectDriver(driver); }
|
|
89
|
+
catch (cleanupError) { error.cleanupError = cleanupError; }
|
|
90
|
+
}
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
this.driver = driver;
|
|
94
|
+
this.listenerAttached = false;
|
|
95
|
+
this.#setState("connected");
|
|
96
|
+
this.emit("connected", this.snapshot());
|
|
97
|
+
return driver;
|
|
98
|
+
} catch (error) {
|
|
99
|
+
this.#setState("disconnected");
|
|
100
|
+
this.emit("connectionError", error);
|
|
101
|
+
if (this.stopRequested || error?.retryable === false) break;
|
|
102
|
+
const base = Math.min(this.options.maxDelayMs, this.options.minDelayMs * Math.pow(this.options.factor, attempt));
|
|
103
|
+
attempt++;
|
|
104
|
+
const jitter = base * this.options.jitter * ((this.random() * 2) - 1);
|
|
105
|
+
if (attempt < this.options.maxAttempts) await this.sleep(Math.max(0, Math.round(base + jitter)));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!this.stopRequested && this.state !== "stopped") this.#setState("failed");
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
listen(callback) {
|
|
113
|
+
if (typeof callback !== "function") throw new TypeError("listener callback is required");
|
|
114
|
+
if (!this.driver) throw new Error("Connection is not ready");
|
|
115
|
+
if (this.listenerAttached) throw new Error("A listener is already attached");
|
|
116
|
+
this.eventCallback = callback;
|
|
117
|
+
this.#attachListener();
|
|
118
|
+
let detached = false;
|
|
119
|
+
return () => {
|
|
120
|
+
if (detached) return;
|
|
121
|
+
detached = true;
|
|
122
|
+
this.eventCallback = null;
|
|
123
|
+
this.#detachListener();
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
#attachListener() {
|
|
128
|
+
if (!this.driver || !this.eventCallback || this.listenerAttached) return;
|
|
129
|
+
this.listenerAttached = true;
|
|
130
|
+
const generation = this.generation;
|
|
131
|
+
const callback = this.eventCallback;
|
|
132
|
+
try {
|
|
133
|
+
const detach = this.driver.listen((error, event) => {
|
|
134
|
+
if (generation !== this.generation || this.stopRequested) return;
|
|
135
|
+
if (error) {
|
|
136
|
+
this.emit("listenerError", error);
|
|
137
|
+
void this.#recover(generation);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
callback(event);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
// Application callback failures must not escape the transport event
|
|
144
|
+
// loop or be mistaken for a broken socket that needs reconnecting.
|
|
145
|
+
try { this.emit("listenerCallbackError", error); } catch {}
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
try { this.emit("event", event); }
|
|
149
|
+
catch (error) {
|
|
150
|
+
try { this.emit("observerError", error); } catch {}
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
this.detachDriverListener = typeof detach === "function" ? detach : null;
|
|
154
|
+
} catch (error) {
|
|
155
|
+
this.listenerAttached = false;
|
|
156
|
+
this.emit("listenerError", error);
|
|
157
|
+
void this.#recover(generation);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
#detachListener() {
|
|
162
|
+
const detach = this.detachDriverListener;
|
|
163
|
+
this.detachDriverListener = null;
|
|
164
|
+
this.listenerAttached = false;
|
|
165
|
+
if (detach) {
|
|
166
|
+
try { detach(); } catch (error) { this.emit("listenerError", error); }
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async #recover(failedGeneration) {
|
|
171
|
+
if (this.recovering || this.stopRequested || failedGeneration !== this.generation) return;
|
|
172
|
+
this.recovering = true;
|
|
173
|
+
const previous = this.driver;
|
|
174
|
+
this.driver = null;
|
|
175
|
+
this.#detachListener();
|
|
176
|
+
this.#setState("disconnected");
|
|
177
|
+
try {
|
|
178
|
+
if (previous) await this.disconnectDriver(previous);
|
|
179
|
+
// stop() may run while the previous driver is being disposed. Do not
|
|
180
|
+
// let recovery call start() afterward, because start() clears stopRequested.
|
|
181
|
+
if (this.stopRequested || failedGeneration !== this.generation) return;
|
|
182
|
+
const driver = await this.start();
|
|
183
|
+
if (driver && !this.stopRequested && this.eventCallback) this.#attachListener();
|
|
184
|
+
} catch (error) {
|
|
185
|
+
this.emit("connectionError", error);
|
|
186
|
+
} finally {
|
|
187
|
+
this.recovering = false;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
stop() {
|
|
192
|
+
if (this.stopPromise) return this.stopPromise;
|
|
193
|
+
this.stopRequested = true;
|
|
194
|
+
this.connectAbortController?.abort(
|
|
195
|
+
Object.assign(new Error("Connection stopped"), { name: "AbortError", retryable: false })
|
|
196
|
+
);
|
|
197
|
+
++this.generation;
|
|
198
|
+
this.eventCallback = null;
|
|
199
|
+
this.#detachListener();
|
|
200
|
+
const driver = this.driver;
|
|
201
|
+
const pendingStart = this.startPromise;
|
|
202
|
+
this.driver = null;
|
|
203
|
+
this.stopPromise = (async () => {
|
|
204
|
+
let disconnectError = null;
|
|
205
|
+
if (driver) {
|
|
206
|
+
try { await this.disconnectDriver(driver); }
|
|
207
|
+
catch (error) { disconnectError = error; }
|
|
208
|
+
}
|
|
209
|
+
// A connect attempt may still be resolving. #startLoop owns disposal of
|
|
210
|
+
// any driver that arrives after stopRequested; wait for that cleanup
|
|
211
|
+
// before reporting the supervisor as fully stopped.
|
|
212
|
+
if (pendingStart) {
|
|
213
|
+
try { await pendingStart; }
|
|
214
|
+
catch (error) { if (!disconnectError) disconnectError = error; }
|
|
215
|
+
}
|
|
216
|
+
this.#setState("stopped");
|
|
217
|
+
this.emit("stopped", this.snapshot());
|
|
218
|
+
if (disconnectError) throw disconnectError;
|
|
219
|
+
})().finally(() => {
|
|
220
|
+
this.stopPromise = null;
|
|
221
|
+
});
|
|
222
|
+
return this.stopPromise;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
#setState(next) {
|
|
226
|
+
this.state = next;
|
|
227
|
+
this.emit("state", this.snapshot());
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
module.exports = { ConnectionSupervisor };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const MAX_COOKIE_COUNT = 500;
|
|
4
|
+
const MAX_COOKIE_VALUE_LENGTH = 16_000;
|
|
5
|
+
const FACEBOOK_DOMAINS = new Set(["facebook.com", "www.facebook.com", "m.facebook.com", "messenger.com"]);
|
|
6
|
+
|
|
7
|
+
function normalizeDomain(domain) {
|
|
8
|
+
if (typeof domain !== "string" || !domain.trim()) throw new TypeError("Cookie domain is required");
|
|
9
|
+
const value = domain.trim().toLowerCase().replace(/^\./, "");
|
|
10
|
+
if (!FACEBOOK_DOMAINS.has(value) && !value.endsWith(".facebook.com") && !value.endsWith(".messenger.com")) {
|
|
11
|
+
throw new TypeError("Only Facebook/Messenger cookie domains are accepted");
|
|
12
|
+
}
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function normalizeCookies(input) {
|
|
17
|
+
if (!Array.isArray(input) || input.length < 1 || input.length > MAX_COOKIE_COUNT) {
|
|
18
|
+
throw new TypeError("Cookies must be a non-empty array (maximum 500 entries)");
|
|
19
|
+
}
|
|
20
|
+
const seen = new Set();
|
|
21
|
+
const result = input.map((item) => {
|
|
22
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) throw new TypeError("Invalid cookie entry");
|
|
23
|
+
const key = typeof item.key === "string" ? item.key : item.name;
|
|
24
|
+
if (typeof key !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(key)) throw new TypeError("Invalid cookie name");
|
|
25
|
+
if (typeof item.value !== "string" || !item.value || item.value.length > MAX_COOKIE_VALUE_LENGTH || !/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/.test(item.value)) throw new TypeError("Invalid cookie value");
|
|
26
|
+
const rawDomain = item.domain || "facebook.com";
|
|
27
|
+
const domain = normalizeDomain(rawDomain);
|
|
28
|
+
const path = item.path === undefined ? "/" : item.path;
|
|
29
|
+
if (typeof path !== "string" || !path.startsWith("/") || path.length > 1024) throw new TypeError("Invalid cookie path");
|
|
30
|
+
const expires = item.expires === undefined || item.expires === null || item.expires === 0
|
|
31
|
+
? null : item.expires;
|
|
32
|
+
if (expires !== null && (!Number.isSafeInteger(expires) || expires < 0)) {
|
|
33
|
+
throw new TypeError("Invalid cookie expiry");
|
|
34
|
+
}
|
|
35
|
+
const identity = [domain, path, key].join("\n");
|
|
36
|
+
if (seen.has(identity)) throw new TypeError("Duplicate cookie entry");
|
|
37
|
+
seen.add(identity);
|
|
38
|
+
return {
|
|
39
|
+
key,
|
|
40
|
+
value: item.value,
|
|
41
|
+
domain,
|
|
42
|
+
path,
|
|
43
|
+
hostOnly: item.hostOnly === undefined ? !(typeof rawDomain === "string" && rawDomain.trim().startsWith(".")) : Boolean(item.hostOnly),
|
|
44
|
+
secure: Boolean(item.secure),
|
|
45
|
+
httpOnly: Boolean(item.httpOnly),
|
|
46
|
+
...(typeof item.sameSite === "string" ? { sameSite: item.sameSite } : {}),
|
|
47
|
+
...(expires !== null ? { expires } : {})
|
|
48
|
+
};
|
|
49
|
+
});
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function validateSessionCookies(input) {
|
|
54
|
+
const cookies = normalizeCookies(input);
|
|
55
|
+
const values = new Map(cookies.map(cookie => [cookie.key, cookie.value]));
|
|
56
|
+
if (!/^\d{5,30}$/.test(values.get("c_user") || "") || !values.get("xs")) {
|
|
57
|
+
throw new TypeError("Facebook session requires valid c_user and xs cookies");
|
|
58
|
+
}
|
|
59
|
+
return cookies;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function parseCookieHeader(header) {
|
|
63
|
+
if (typeof header !== "string" || !header.trim() || header.length > 64 * 1024) {
|
|
64
|
+
throw new TypeError("Cookie header must be non-empty text up to 64 KiB");
|
|
65
|
+
}
|
|
66
|
+
const entries = header.split(";").map(part => part.trim()).filter(Boolean).map(part => {
|
|
67
|
+
const index = part.indexOf("=");
|
|
68
|
+
if (index <= 0) throw new TypeError("Malformed cookie header");
|
|
69
|
+
return { key: part.slice(0, index).trim(), value: part.slice(index + 1).trim(), domain: "facebook.com", path: "/", hostOnly: true };
|
|
70
|
+
});
|
|
71
|
+
return normalizeCookies(entries);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function parseNetscapeCookies(text) {
|
|
75
|
+
if (typeof text !== "string" || !text.trim() || text.length > 256 * 1024) throw new TypeError("Netscape cookie file must be non-empty text up to 256 KiB");
|
|
76
|
+
const rows = [];
|
|
77
|
+
for (const line of text.split(/\r?\n/)) {
|
|
78
|
+
const trimmed = line.trimStart();
|
|
79
|
+
if (!trimmed) continue;
|
|
80
|
+
|
|
81
|
+
// Netscape cookie files use a special comment-like domain prefix for
|
|
82
|
+
// HttpOnly cookies. It is data, not a comment: dropping it silently
|
|
83
|
+
// removes session cookies exported by browsers and cookie managers.
|
|
84
|
+
const httpOnly = trimmed.startsWith("#HttpOnly_");
|
|
85
|
+
if (trimmed.startsWith("#") && !httpOnly) continue;
|
|
86
|
+
|
|
87
|
+
const fields = (httpOnly ? trimmed.slice("#HttpOnly_".length) : trimmed).split("\t");
|
|
88
|
+
if (fields.length < 7) throw new TypeError("Malformed Netscape cookie row");
|
|
89
|
+
const [domain, includeSubdomains, path, secure, expires, key, ...valueParts] = fields;
|
|
90
|
+
rows.push({
|
|
91
|
+
key,
|
|
92
|
+
value: valueParts.join("\t"),
|
|
93
|
+
domain,
|
|
94
|
+
path,
|
|
95
|
+
hostOnly: includeSubdomains.toUpperCase() !== "TRUE",
|
|
96
|
+
secure: secure.toUpperCase() === "TRUE",
|
|
97
|
+
httpOnly,
|
|
98
|
+
expires: Number(expires)
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return normalizeCookies(rows);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
module.exports = { normalizeCookies, validateSessionCookies, parseCookieHeader, parseNetscapeCookies };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const SECRET_KEY = /(?:pass(?:word)?|cookie|token|secret|authorization|appstate|session|credential|fb_dtsg|lsd|jazoest|xs|c_user|access.?key|api.?key|2fa|otp|verification.?code|challenge.?answer|auth.?code)/i;
|
|
4
|
+
const SAFE_HEADER_NAMES = new Set(["accept", "content-type", "accept-language", "x-requested-with", "origin", "referer"]);
|
|
5
|
+
|
|
6
|
+
function byteLength(value) {
|
|
7
|
+
if (value == null) return 0;
|
|
8
|
+
if (typeof value === "string") return Buffer.byteLength(value, "utf8");
|
|
9
|
+
if (value instanceof URLSearchParams) return Buffer.byteLength(value.toString(), "utf8");
|
|
10
|
+
if (value instanceof Uint8Array) return value.byteLength;
|
|
11
|
+
return 0;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function safeUrl(input) {
|
|
15
|
+
try {
|
|
16
|
+
const url = input instanceof URL ? input : new URL(String(input));
|
|
17
|
+
const path = url.pathname.split("/").map(part => part.length > 64 ? "[redacted]" : part).join("/");
|
|
18
|
+
return Object.freeze({ origin: url.origin, path, queryParameterNames: [...new Set([...url.searchParams.keys()].filter(key => !SECRET_KEY.test(key)))].slice(0, 40) });
|
|
19
|
+
} catch {
|
|
20
|
+
return Object.freeze({ origin: null, path: null, queryParameterNames: [] });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function safeFieldNames(body) {
|
|
25
|
+
let entries = [];
|
|
26
|
+
if (body instanceof URLSearchParams) entries = [...new Set([...body.keys()])];
|
|
27
|
+
else if (body && typeof body === "object" && !ArrayBuffer.isView(body) && !(body instanceof ArrayBuffer)) entries = Object.keys(body);
|
|
28
|
+
const safe = [];
|
|
29
|
+
let sensitiveCount = 0;
|
|
30
|
+
for (const key of entries.slice(0, 100)) {
|
|
31
|
+
if (SECRET_KEY.test(key)) sensitiveCount++;
|
|
32
|
+
else if (/^[A-Za-z0-9_.:[\]-]{1,128}$/.test(key)) safe.push(key);
|
|
33
|
+
}
|
|
34
|
+
return { fieldNames: safe, sensitiveFieldCount: sensitiveCount, truncated: entries.length > 100 };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function safeHeaderNames(headers) {
|
|
38
|
+
const names = [];
|
|
39
|
+
try {
|
|
40
|
+
for (const [name] of new Headers(headers || {})) {
|
|
41
|
+
const lower = name.toLowerCase();
|
|
42
|
+
if (SAFE_HEADER_NAMES.has(lower)) names.push(lower);
|
|
43
|
+
}
|
|
44
|
+
} catch {}
|
|
45
|
+
return [...new Set(names)].sort();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Collects request metadata only. Header values, query values, body values,
|
|
50
|
+
* response bodies, cookies and credentials are never stored.
|
|
51
|
+
*/
|
|
52
|
+
function createDiagnosticRecorder({ maxEvents = 100, clock = Date.now } = {}) {
|
|
53
|
+
if (!Number.isInteger(maxEvents) || maxEvents < 1 || maxEvents > 1000) {
|
|
54
|
+
throw new TypeError("maxEvents must be an integer between 1 and 1000");
|
|
55
|
+
}
|
|
56
|
+
if (typeof clock !== "function") throw new TypeError("clock must be a function");
|
|
57
|
+
const events = [];
|
|
58
|
+
|
|
59
|
+
function record(input = {}) {
|
|
60
|
+
const request = input.request || {};
|
|
61
|
+
const response = input.response || {};
|
|
62
|
+
const fields = safeFieldNames(request.body);
|
|
63
|
+
const event = Object.freeze({
|
|
64
|
+
at: new Date(clock()).toISOString(),
|
|
65
|
+
phase: input.phase === "response" ? "response" : input.phase === "error" ? "error" : "request",
|
|
66
|
+
method: /^(GET|HEAD|POST|PUT|PATCH|DELETE)$/i.test(String(request.method || "")) ? String(request.method).toUpperCase() : "OTHER",
|
|
67
|
+
url: safeUrl(request.url),
|
|
68
|
+
requestHeaders: safeHeaderNames(request.headers),
|
|
69
|
+
requestBodyBytes: byteLength(request.body),
|
|
70
|
+
requestFieldNames: fields.fieldNames,
|
|
71
|
+
sensitiveFieldCount: fields.sensitiveFieldCount,
|
|
72
|
+
fieldsTruncated: fields.truncated,
|
|
73
|
+
...(Number.isInteger(response.status) ? { status: response.status } : {}),
|
|
74
|
+
...(typeof response.contentType === "string" ? { contentType: response.contentType.split(";")[0].slice(0, 100) } : {}),
|
|
75
|
+
...(Number.isFinite(response.bodyBytes) ? { responseBodyBytes: Math.max(0, response.bodyBytes) } : {}),
|
|
76
|
+
...(Number.isFinite(input.durationMs) ? { durationMs: Math.max(0, input.durationMs) } : {}),
|
|
77
|
+
...(typeof input.errorCode === "string" && /^[A-Z0-9_-]{1,64}$/.test(input.errorCode) ? { errorCode: input.errorCode } : {})
|
|
78
|
+
});
|
|
79
|
+
events.push(event);
|
|
80
|
+
if (events.length > maxEvents) events.shift();
|
|
81
|
+
return event;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function snapshot() {
|
|
85
|
+
return Object.freeze({ version: 1, generatedAt: new Date(clock()).toISOString(), events: events.slice() });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return Object.freeze({
|
|
89
|
+
record,
|
|
90
|
+
snapshot,
|
|
91
|
+
toJSON() {
|
|
92
|
+
return JSON.stringify(snapshot(), null, 2);
|
|
93
|
+
},
|
|
94
|
+
clear() { events.length = 0; }
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
module.exports = { createDiagnosticRecorder, safeUrl, safeFieldNames, safeHeaderNames };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const SECRET_KEYS = new Set([
|
|
4
|
+
"cookie", "cookies", "appstate", "password", "pass", "xs", "cuser",
|
|
5
|
+
"token", "accesstoken", "authorization", "secret", "appsecret",
|
|
6
|
+
"clientsecret", "pageaccesstoken", "licensekey", "twofasecret",
|
|
7
|
+
"twofactorsecret", "verifytoken", "webhookverifytoken", "sessionkey",
|
|
8
|
+
"encryptionkey", "privatekey", "authorizationcode"
|
|
9
|
+
]);
|
|
10
|
+
|
|
11
|
+
function redactSecrets(value, key = "") {
|
|
12
|
+
const normalizedKey = String(key).toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
13
|
+
if (SECRET_KEYS.has(normalizedKey)) return "[REDACTED]";
|
|
14
|
+
if (Array.isArray(value)) return value.map(item => redactSecrets(item));
|
|
15
|
+
if (!value || typeof value !== "object") return value;
|
|
16
|
+
const output = {};
|
|
17
|
+
for (const [childKey, childValue] of Object.entries(value)) {
|
|
18
|
+
output[childKey] = redactSecrets(childValue, childKey);
|
|
19
|
+
}
|
|
20
|
+
return output;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
module.exports = { redactSecrets };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const crypto = require("node:crypto");
|
|
4
|
+
|
|
5
|
+
const FORMAT = "omega-fca-session:v1";
|
|
6
|
+
|
|
7
|
+
function resolveKey(key) {
|
|
8
|
+
if ((Buffer.isBuffer(key) || key instanceof Uint8Array) && key.byteLength === 32) {
|
|
9
|
+
return Buffer.from(key);
|
|
10
|
+
}
|
|
11
|
+
if (typeof key !== "string" || !/^[a-f0-9]{64}$/i.test(key)) {
|
|
12
|
+
throw new TypeError("Session encryption key must be 32 bytes or exactly 64 hexadecimal characters");
|
|
13
|
+
}
|
|
14
|
+
return Buffer.from(key, "hex");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function encryptSession(session, key) {
|
|
18
|
+
if (!session || typeof session !== "object" || Array.isArray(session)) throw new TypeError("Session must be an object");
|
|
19
|
+
const iv = crypto.randomBytes(12);
|
|
20
|
+
const cipher = crypto.createCipheriv("aes-256-gcm", resolveKey(key), iv);
|
|
21
|
+
cipher.setAAD(Buffer.from(FORMAT));
|
|
22
|
+
const serialized = JSON.stringify(session);
|
|
23
|
+
if (typeof serialized !== "string") throw new TypeError("Session must be JSON-serializable");
|
|
24
|
+
const plaintext = Buffer.from(serialized, "utf8");
|
|
25
|
+
if (plaintext.length > 1024 * 1024) throw new RangeError("Session data exceeds the 1 MiB limit");
|
|
26
|
+
const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
|
27
|
+
return Object.freeze({
|
|
28
|
+
format: FORMAT,
|
|
29
|
+
iv: iv.toString("base64url"),
|
|
30
|
+
tag: cipher.getAuthTag().toString("base64url"),
|
|
31
|
+
data: encrypted.toString("base64url")
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function decryptSession(envelope, key) {
|
|
36
|
+
if (!envelope || typeof envelope !== "object" || envelope.format !== FORMAT ||
|
|
37
|
+
typeof envelope.iv !== "string" || typeof envelope.tag !== "string" || typeof envelope.data !== "string") {
|
|
38
|
+
throw new TypeError("Unsupported encrypted session format");
|
|
39
|
+
}
|
|
40
|
+
const decode = value => {
|
|
41
|
+
if (!/^[A-Za-z0-9_-]*$/.test(value) || value.length % 4 === 1) {
|
|
42
|
+
throw new TypeError("Invalid encrypted session envelope");
|
|
43
|
+
}
|
|
44
|
+
const decoded = Buffer.from(value, "base64url");
|
|
45
|
+
if (decoded.toString("base64url") !== value) throw new TypeError("Invalid encrypted session envelope");
|
|
46
|
+
return decoded;
|
|
47
|
+
};
|
|
48
|
+
const iv = decode(envelope.iv);
|
|
49
|
+
const tag = decode(envelope.tag);
|
|
50
|
+
const data = decode(envelope.data);
|
|
51
|
+
if (iv.length !== 12 || tag.length !== 16 || data.length > 1024 * 1024) throw new TypeError("Invalid encrypted session envelope");
|
|
52
|
+
const decipher = crypto.createDecipheriv("aes-256-gcm", resolveKey(key), iv);
|
|
53
|
+
decipher.setAAD(Buffer.from(FORMAT));
|
|
54
|
+
decipher.setAuthTag(tag);
|
|
55
|
+
const plaintext = Buffer.concat([decipher.update(data), decipher.final()]);
|
|
56
|
+
const session = JSON.parse(plaintext.toString("utf8"));
|
|
57
|
+
if (!session || typeof session !== "object" || Array.isArray(session)) throw new TypeError("Decrypted session is invalid");
|
|
58
|
+
return session;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
module.exports = { encryptSession, decryptSession };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const CHECKPOINT = /checkpoint|two[\s-]?factor|approvals_code|security code|confirm your identity|login approval/i;
|
|
4
|
+
const LOGGED_OUT = /not logged in|account_inactive|login_blocked|invalid session|session expired|logged out|login required|1357001/i;
|
|
5
|
+
const TRANSIENT = /timeout|timed out|connection reset|connection refused|server unavailable|temporarily unavailable|econnreset|enotfound|429|rate limit/i;
|
|
6
|
+
|
|
7
|
+
function describeError(error) {
|
|
8
|
+
if (typeof error === "string") return error;
|
|
9
|
+
if (!error || typeof error !== "object") return "";
|
|
10
|
+
return [error.type, error.error, error.message, error.code].filter(Boolean).map(String).join(" ");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function classifySessionState(input) {
|
|
14
|
+
if (input === null || input === undefined || input === "") return "unknown";
|
|
15
|
+
if (typeof input === "string" && ["online", "logged_out", "checkpoint", "error", "unknown"].includes(input)) return input;
|
|
16
|
+
const message = describeError(input);
|
|
17
|
+
if (CHECKPOINT.test(message)) return "checkpoint";
|
|
18
|
+
if (LOGGED_OUT.test(message)) return "logged_out";
|
|
19
|
+
if (TRANSIENT.test(message)) return "error";
|
|
20
|
+
return message ? "error" : "unknown";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
module.exports = { classifySessionState, describeError };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { randomUUID } = require("node:crypto");
|
|
4
|
+
|
|
5
|
+
const fs = require("node:fs");
|
|
6
|
+
const path = require("node:path");
|
|
7
|
+
const { encryptSession, decryptSession } = require("./sessionCrypto");
|
|
8
|
+
|
|
9
|
+
function saveSession(filePath, session, key) {
|
|
10
|
+
const target = path.resolve(filePath);
|
|
11
|
+
const directory = path.dirname(target);
|
|
12
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
13
|
+
const temp = path.join(directory, ".omega-session-" + randomUUID() + ".tmp");
|
|
14
|
+
const envelope = JSON.stringify(encryptSession(session, key));
|
|
15
|
+
let fd;
|
|
16
|
+
try {
|
|
17
|
+
fd = fs.openSync(temp, "wx", 0o600);
|
|
18
|
+
fs.writeFileSync(fd, envelope, "utf8");
|
|
19
|
+
fs.fsyncSync(fd);
|
|
20
|
+
fs.closeSync(fd);
|
|
21
|
+
fd = undefined;
|
|
22
|
+
fs.renameSync(temp, target);
|
|
23
|
+
try { fs.chmodSync(target, 0o600); } catch {}
|
|
24
|
+
// Persist the directory entry where supported; file contents were fsynced above.
|
|
25
|
+
let directoryFd;
|
|
26
|
+
try {
|
|
27
|
+
directoryFd = fs.openSync(directory, fs.constants.O_RDONLY);
|
|
28
|
+
fs.fsyncSync(directoryFd);
|
|
29
|
+
} catch {
|
|
30
|
+
// Some platforms/filesystems do not support fsync on directories.
|
|
31
|
+
} finally {
|
|
32
|
+
if (directoryFd !== undefined) try { fs.closeSync(directoryFd); } catch {}
|
|
33
|
+
}
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (fd !== undefined) try { fs.closeSync(fd); } catch {}
|
|
36
|
+
try { fs.unlinkSync(temp); } catch {}
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
return target;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function loadSession(filePath, key) {
|
|
43
|
+
const target = path.resolve(filePath);
|
|
44
|
+
const noFollow = fs.constants.O_NOFOLLOW || 0;
|
|
45
|
+
const fd = fs.openSync(target, fs.constants.O_RDONLY | noFollow);
|
|
46
|
+
try {
|
|
47
|
+
const stat = fs.fstatSync(fd);
|
|
48
|
+
if (!stat.isFile() || stat.size > 1024 * 1024) {
|
|
49
|
+
throw new Error("Encrypted session file is invalid or too large");
|
|
50
|
+
}
|
|
51
|
+
const contents = fs.readFileSync(fd, "utf8");
|
|
52
|
+
const envelope = JSON.parse(contents);
|
|
53
|
+
return decryptSession(envelope, key);
|
|
54
|
+
} finally {
|
|
55
|
+
fs.closeSync(fd);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function deleteSession(filePath) {
|
|
60
|
+
try { fs.unlinkSync(path.resolve(filePath)); }
|
|
61
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
module.exports = { saveSession, loadSession, deleteSession };
|