@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,131 @@
1
+ "use strict";
2
+
3
+ const DEFAULT_MAX_BINARY_PAYLOAD_BYTES = 1024 * 1024;
4
+
5
+ function findJsonObject(text) {
6
+ for (let start = text.indexOf("{"); start !== -1; start = text.indexOf("{", start + 1)) {
7
+ let depth = 0, quoted = false, escaped = false;
8
+ for (let i = start; i < text.length; i++) {
9
+ const c = text[i];
10
+ if (quoted) {
11
+ if (escaped) escaped = false;
12
+ else if (c === "\\") escaped = true;
13
+ else if (c === '"') quoted = false;
14
+ } else if (c === '"') quoted = true;
15
+ else if (c === "{") depth++;
16
+ else if (c === "}" && --depth === 0) {
17
+ try {
18
+ const value = JSON.parse(text.slice(start, i + 1));
19
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
20
+ } catch {}
21
+ break;
22
+ }
23
+ }
24
+ }
25
+ return null;
26
+ }
27
+
28
+ function readVarint(bytes, state) {
29
+ let value = 0n;
30
+ for (let shift = 0n; shift <= 63n; shift += 7n) {
31
+ if (state.offset >= bytes.length) throw new Error("truncated varint");
32
+ const byte = bytes[state.offset++];
33
+ // A protobuf varint is at most 64 bits; the tenth byte may only
34
+ // contribute bit 63. Reject over-wide encodings instead of accepting
35
+ // arbitrary BigInt values as structurally valid protobuf fields.
36
+ if (shift === 63n && byte > 1) throw new Error("varint overflow");
37
+ value |= BigInt(byte & 0x7f) << shift;
38
+ if ((byte & 0x80) === 0) return value;
39
+ }
40
+ throw new Error("varint overflow");
41
+ }
42
+
43
+ // Structural inspection only: field values are deliberately never returned.
44
+ function inspectWireFields(bytes, maxFields = 512) {
45
+ const state = { offset: 0 };
46
+ const fields = [];
47
+ while (state.offset < bytes.length) {
48
+ if (fields.length >= maxFields) throw new Error("field limit exceeded");
49
+ const tag = Number(readVarint(bytes, state));
50
+ const number = Math.floor(tag / 8), wireType = tag & 7;
51
+ if (number < 1 || number > 0x1fffffff ||
52
+ wireType === 3 || wireType === 4 || wireType > 5) {
53
+ throw new Error("invalid wire tag");
54
+ }
55
+ let byteLength = null;
56
+ if (wireType === 0) readVarint(bytes, state);
57
+ else if (wireType === 1 || wireType === 5) {
58
+ byteLength = wireType === 1 ? 8 : 4;
59
+ state.offset += byteLength;
60
+ if (state.offset > bytes.length) throw new Error("truncated fixed field");
61
+ } else if (wireType === 2) {
62
+ const length = Number(readVarint(bytes, state));
63
+ if (!Number.isSafeInteger(length) || length < 0 || state.offset + length > bytes.length) throw new Error("invalid length field");
64
+ byteLength = length;
65
+ state.offset += length;
66
+ }
67
+ fields.push(Object.freeze({ number, wireType, byteLength }));
68
+ }
69
+ return Object.freeze(fields);
70
+ }
71
+
72
+ function inspectRealtimeBinaryPayload(frame, options = {}) {
73
+ const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_BINARY_PAYLOAD_BYTES;
74
+ const maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_BINARY_PAYLOAD_BYTES;
75
+ for (const [name, value] of Object.entries({ maxFrameBytes, maxPayloadBytes })) {
76
+ if (!Number.isInteger(value) || value < 1 || value > 16 * 1024 * 1024) {
77
+ throw new TypeError(name + " must be an integer between 1 and 16777216");
78
+ }
79
+ }
80
+ if (!(Buffer.isBuffer(frame) || frame instanceof Uint8Array)) throw new TypeError("Realtime frame must be a Buffer or Uint8Array");
81
+ const bytes = Buffer.from(frame);
82
+ if (!bytes.length || bytes.length > maxFrameBytes) {
83
+ const error = new Error("Realtime frame is empty or exceeds the configured size limit");
84
+ error.code = "FCA_REALTIME_FRAME_SIZE_INVALID";
85
+ throw error;
86
+ }
87
+ const envelope = findJsonObject(bytes.toString("utf8"));
88
+ if (!envelope || !Object.prototype.hasOwnProperty.call(envelope, "payload")) {
89
+ const error = new Error("Realtime frame does not contain a supported payload envelope");
90
+ error.code = "FCA_REALTIME_PAYLOAD_ENVELOPE_UNSUPPORTED";
91
+ throw error;
92
+ }
93
+ if (typeof envelope.payload !== "string") {
94
+ return Object.freeze({
95
+ envelopeKind: Array.isArray(envelope.events) ? "events" : "payload",
96
+ requestIdPresent: envelope.request_id !== undefined && envelope.request_id !== null,
97
+ payloadEncoding: "non-string",
98
+ payloadBytes: null,
99
+ wireFields: Object.freeze([])
100
+ });
101
+ }
102
+ const encoded = envelope.payload;
103
+ if (!encoded || encoded.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) {
104
+ return Object.freeze({ envelopeKind: "payload", requestIdPresent: envelope.request_id != null, payloadEncoding: "non-base64-string", payloadBytes: null, wireFields: Object.freeze([]) });
105
+ }
106
+ const payload = Buffer.from(encoded, "base64");
107
+ if (payload.length > maxPayloadBytes) {
108
+ const error = new Error("Realtime binary payload exceeds the configured size limit");
109
+ error.code = "FCA_REALTIME_PAYLOAD_SIZE_INVALID";
110
+ throw error;
111
+ }
112
+ let wireFields = [];
113
+ let payloadEncoding = "base64-binary-unclassified";
114
+ try {
115
+ wireFields = inspectWireFields(payload);
116
+ payloadEncoding = "protobuf-wire-compatible";
117
+ } catch {
118
+ // Keep unknown binary payloads opaque; do not guess their format.
119
+ }
120
+ const nestedJson = findJsonObject(payload.toString("utf8"));
121
+ if (nestedJson) payloadEncoding = "base64-json";
122
+ return Object.freeze({
123
+ envelopeKind: "payload",
124
+ requestIdPresent: envelope.request_id !== undefined && envelope.request_id !== null,
125
+ payloadEncoding,
126
+ payloadBytes: payload.length,
127
+ wireFields: Object.freeze(wireFields)
128
+ });
129
+ }
130
+
131
+ module.exports = { DEFAULT_MAX_BINARY_PAYLOAD_BYTES, inspectRealtimeBinaryPayload };
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+
3
+ const REQUIRED_DRIVER_METHODS = Object.freeze(["listen"]);
4
+ const OPTIONAL_DRIVER_METHODS = Object.freeze([
5
+ "disconnect", "getCurrentUserID", "sendRequest", "sendMessage", "getUserInfo", "getThreadInfo",
6
+ "getThreadList", "markAsRead", "setMessageReaction", "sendTypingIndicator",
7
+ "unsendMessage", "changeNickname", "addUserToGroup", "removeUserFromGroup",
8
+ "createNewGroup", "getThreadHistory", "getMessage", "getFriendsList", "getUserID"
9
+ ]);
10
+
11
+ function validateTransportDriver(driver) {
12
+ if (!driver || typeof driver !== "object" || Array.isArray(driver)) {
13
+ throw new TypeError("Transport provider must return a driver object");
14
+ }
15
+ for (const method of REQUIRED_DRIVER_METHODS) {
16
+ if (typeof driver[method] !== "function") {
17
+ const error = new Error("Transport driver is missing required method: " + method);
18
+ error.code = "FCA_TRANSPORT_CONTRACT_INVALID";
19
+ error.retryable = false;
20
+ throw error;
21
+ }
22
+ }
23
+ for (const method of OPTIONAL_DRIVER_METHODS) {
24
+ if (driver[method] !== undefined && typeof driver[method] !== "function") {
25
+ const error = new Error("Transport driver method must be a function: " + method);
26
+ error.code = "FCA_TRANSPORT_CONTRACT_INVALID";
27
+ error.retryable = false;
28
+ throw error;
29
+ }
30
+ }
31
+ return driver;
32
+ }
33
+
34
+ function createTransportFactory(provider) {
35
+ if (typeof provider !== "function") throw new TypeError("Transport provider must be a function");
36
+ return async context => validateTransportDriver(await provider(context));
37
+ }
38
+
39
+ module.exports = { REQUIRED_DRIVER_METHODS, OPTIONAL_DRIVER_METHODS, validateTransportDriver, createTransportFactory };
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+
3
+ const DEFAULT_GATEWAY_URL = "wss://gateway.facebook.com/ws/realtime";
4
+ const DEFAULT_APP_ID = "2220391788200892";
5
+
6
+ // Public FCA implementations use this gateway subscription family for
7
+ // Facebook web realtime notifications/presence. It is not Messenger's
8
+ // private message-sync protocol and is exposed separately for that reason.
9
+ const SUBSCRIPTIONS = Object.freeze([
10
+ '{"x-dgw-app-XRSS-method":"Falco","x-dgw-app-xrs-body":"true","x-dgw-app-XRS-Accept-Ack":"RSAck","x-dgw-app-XRSS-http_referer":"https://www.facebook.com"}',
11
+ '{"x-dgw-app-XRSS-method":"FBGQLS:USER_ACTIVITY_UPDATE_SUBSCRIBE","x-dgw-app-XRSS-doc_id":"9525970914181809","x-dgw-app-XRSS-routing_hint":"UserActivitySubscription","x-dgw-app-xrs-body":"true","x-dgw-app-XRS-Accept-Ack":"RSAck","x-dgw-app-XRSS-http_referer":"https://www.facebook.com"}',
12
+ '{"x-dgw-app-XRSS-method":"FBGQLS:ACTOR_GATEWAY_EXPERIENCE_SUBSCRIBE","x-dgw-app-XRSS-doc_id":"24191710730466150","x-dgw-app-XRSS-routing_hint":"CometActorGatewayExperienceSubscription","x-dgw-app-xrs-body":"true","x-dgw-app-XRS-Accept-Ack":"RSAck","x-dgw-app-XRSS-http_referer":"https://www.facebook.com"}',
13
+ '{"x-dgw-app-XRSS-method":"FBLQ:comet_notifications_live_query_experimental","x-dgw-app-XRSS-doc_id":"9784489068321501","x-dgw-app-XRSS-actor_id":"{{USER_ID}}","x-dgw-app-XRSS-page_id":"{{USER_ID}}","x-dgw-app-XRSS-request_stream_retry":"false","x-dgw-app-xrs-body":"true","x-dgw-app-XRS-Accept-Ack":"RSAck","x-dgw-app-XRSS-http_referer":"https://www.facebook.com"}',
14
+ '{"x-dgw-app-XRSS-method":"FBGQLS:FRIEND_REQUEST_CONFIRM_SUBSCRIBE","x-dgw-app-XRSS-doc_id":"9687616244672204","x-dgw-app-XRSS-routing_hint":"FriendingCometFriendRequestConfirmSubscription","x-dgw-app-xrs-body":"true","x-dgw-app-XRS-Accept-Ack":"RSAck","x-dgw-app-XRSS-http_referer":"https://www.facebook.com"}',
15
+ '{"x-dgw-app-XRSS-method":"FBGQLS:FRIEND_REQUEST_RECEIVE_SUBSCRIBE","x-dgw-app-XRSS-doc_id":"24047008371656912","x-dgw-app-XRSS-routing_hint":"FriendingCometFriendRequestReceiveSubscription","x-dgw-app-xrs-body":"true","x-dgw-app-XRS-Accept-Ack":"RSAck","x-dgw-app-XRSS-http_referer":"https://www.facebook.com"}',
16
+ '{"x-dgw-app-XRSS-method":"FBGQLS:RTWEB_CALL_BLOCKED_SETTING_SUBSCRIBE","x-dgw-app-XRSS-doc_id":"24429620016626810","x-dgw-app-XRSS-routing_hint":"RTWebCallBlockedSettingSubscription_CallBlockSettingSubscription","x-dgw-app-xrs-body":"true","x-dgw-app-XRS-Accept-Ack":"RSAck","x-dgw-app-XRSS-http_referer":"https://www.facebook.com"}',
17
+ '{"x-dgw-app-XRSS-method":"PresenceUnifiedJSON","x-dgw-app-xrs-body":"true","x-dgw-app-XRS-Accept-Ack":"RSAck","x-dgw-app-XRSS-http_referer":"https://www.facebook.com/friends"}'
18
+ ]);
19
+
20
+ function validateId(value, name) {
21
+ const id = String(value ?? "");
22
+ if (!/^\d{1,30}$/.test(id)) throw new TypeError(name + " must be a numeric Facebook ID");
23
+ return id;
24
+ }
25
+
26
+ function encodeGatewaySubscription(payload, index) {
27
+ if (typeof payload !== "string" || !Number.isInteger(index) || index < 0 || index > 255) {
28
+ throw new TypeError("Invalid realtime subscription");
29
+ }
30
+ const body = Buffer.from(payload, "utf8");
31
+ if (body.length > 65535) throw new RangeError("Realtime subscription exceeds two-byte length");
32
+ return Buffer.concat([Buffer.from([14, index, (body.length >> 8) & 0xff, body.length & 0xff]), body, Buffer.from([0, 0])]);
33
+ }
34
+
35
+ function decodeGatewayFrame(frame, { maxFrameBytes = 1024 * 1024 } = {}) {
36
+ let bytes;
37
+ if (typeof frame === "string") bytes = Buffer.from(frame, "utf8");
38
+ else if (Buffer.isBuffer(frame) || frame instanceof Uint8Array) bytes = Buffer.from(frame);
39
+ else if (frame instanceof ArrayBuffer) bytes = Buffer.from(frame);
40
+ else throw new TypeError("Unsupported Facebook realtime frame type");
41
+ if (!bytes.length || bytes.length > maxFrameBytes) throw new RangeError("Facebook realtime frame size is invalid");
42
+
43
+ const text = bytes.toString("utf8");
44
+ const start = text.indexOf("{");
45
+ if (start < 0) return { events: [{ type: "raw", byteLength: bytes.length }] };
46
+ let payload;
47
+ try { payload = JSON.parse(text.slice(start)); }
48
+ catch {
49
+ const end = text.lastIndexOf("}");
50
+ if (end < start) throw new Error("Facebook realtime frame contains invalid JSON");
51
+ payload = JSON.parse(text.slice(start, end + 1));
52
+ }
53
+ const events = [];
54
+ if (payload?.code === 200) events.push({ type: "subscription_success", payload });
55
+ const notification = payload?.data?.viewer?.notifications_page?.edges?.[1]?.node?.notif;
56
+ if (notification) {
57
+ const senders = notification.tracking?.from_uids || {};
58
+ events.push({
59
+ type: "notification",
60
+ notificationId: notification.notif_id ?? null,
61
+ body: notification.body?.text ?? null,
62
+ senderId: Object.keys(senders)[0] ?? null,
63
+ url: notification.url ?? null,
64
+ timestamp: notification.creation_time?.timestamp ?? null,
65
+ seenState: notification.seen_state ?? null,
66
+ raw: payload
67
+ });
68
+ }
69
+ if (!events.length) events.push({ type: "payload", payload });
70
+ return { events };
71
+ }
72
+
73
+ function createFacebookGatewayProtocol(options = {}) {
74
+ const userId = validateId(options.userId, "userId");
75
+ const deviceId = String(options.deviceId ?? userId);
76
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(deviceId)) throw new TypeError("deviceId is invalid");
77
+ const appId = String(options.appId ?? DEFAULT_APP_ID);
78
+ if (!/^\d{1,30}$/.test(appId)) throw new TypeError("appId is invalid");
79
+ const subscriptions = options.subscriptions ?? SUBSCRIPTIONS;
80
+ if (!Array.isArray(subscriptions) || subscriptions.length < 1 || subscriptions.length > 32) {
81
+ throw new TypeError("subscriptions must contain between 1 and 32 entries");
82
+ }
83
+ const url = new URL(options.url ?? DEFAULT_GATEWAY_URL);
84
+ if (url.protocol !== "wss:" || url.hostname !== "gateway.facebook.com" || url.pathname !== "/ws/realtime") {
85
+ throw new TypeError("Facebook realtime URL must use the verified gateway.facebook.com/ws/realtime endpoint");
86
+ }
87
+ for (const [key, value] of Object.entries({
88
+ "x-dgw-appid": appId,
89
+ "x-dgw-appversion": "0",
90
+ "x-dgw-authtype": "1:0",
91
+ "x-dgw-version": "5",
92
+ "x-dgw-uuid": userId,
93
+ "x-dgw-tier": "prod",
94
+ "x-dgw-deviceid": deviceId,
95
+ "x-dgw-app-stream-group": "group1"
96
+ })) url.searchParams.set(key, value);
97
+
98
+ const headers = {
99
+ Origin: "https://www.facebook.com",
100
+ Referer: "https://www.facebook.com",
101
+ ...(options.userAgent ? { "User-Agent": String(options.userAgent) } : {}),
102
+ ...(options.cookie ? { Cookie: String(options.cookie) } : {})
103
+ };
104
+ if (options.cookie && /[\r\n]/.test(headers.Cookie)) throw new TypeError("cookie header contains invalid characters");
105
+
106
+ return Object.freeze({
107
+ url: url.toString(),
108
+ headers: Object.freeze(headers),
109
+ protocol: Object.freeze({
110
+ async authenticate() {
111
+ // Authentication is performed by the authenticated WebSocket upgrade
112
+ // using the caller's owner-provided Facebook session cookies.
113
+ },
114
+ async subscribe(socket) {
115
+ for (let index = 0; index < subscriptions.length; index++) {
116
+ const payload = String(subscriptions[index]).replaceAll("{{USER_ID}}", userId);
117
+ socket.send(encodeGatewaySubscription(payload, index));
118
+ }
119
+ },
120
+ decodeFrame: decodeGatewayFrame,
121
+ async encodeAction() {
122
+ throw new Error("This gateway subscription transport does not support Messenger send actions");
123
+ }
124
+ })
125
+ });
126
+ }
127
+
128
+ module.exports = {
129
+ DEFAULT_GATEWAY_URL,
130
+ DEFAULT_APP_ID,
131
+ FACEBOOK_GATEWAY_SUBSCRIPTIONS: SUBSCRIPTIONS,
132
+ encodeGatewaySubscription,
133
+ decodeGatewayFrame,
134
+ createFacebookGatewayProtocol
135
+ };
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+
3
+ const { createPersonalSession } = require("../auth/personalSession");
4
+ const { createFacebookMqttProtocol } = require("./facebookMqttProtocol");
5
+ const { createNativeRealtimeTransport } = require("./nativeRealtimeTransport");
6
+ const { createFacebookThreadApi } = require("./facebookThreadApi");
7
+
8
+ /**
9
+ * Builds an owner-authorized personal Messenger MQTT driver.
10
+ * Thread and group methods use the same authenticated Facebook web session
11
+ * and public FCA request conventions; their private endpoints can change.
12
+ */
13
+ async function createFacebookMqttDriver({
14
+ appState, socketFactory, fetchImpl, userAgent, timeoutMs = 20000,
15
+ connectTimeoutMs = 15000, closeTimeoutMs = 3000, protocolSetupTimeoutMs = 15000,
16
+ maxFrameBytes, syncCursorStore, onSyncCursor, requestTimeoutMs, maxPendingRequests,
17
+ mqtt = {}, onDiagnostic
18
+ } = {}) {
19
+ if (typeof socketFactory !== "function") throw new TypeError("socketFactory is required");
20
+ const session = await createPersonalSession({ appState, fetchImpl, userAgent, timeoutMs, onDiagnostic });
21
+ let closed = false;
22
+ let transport;
23
+ try {
24
+ const protocolConfig = createFacebookMqttProtocol({
25
+ ...mqtt, userId: session.userId,
26
+ url: mqtt.url || session.realtime.endpoint || undefined,
27
+ region: mqtt.region || session.realtime.region || undefined,
28
+ lastSeqId: mqtt.lastSeqId || session.realtime.lastSeqId || undefined,
29
+ cookie: session.getCookieHeader("https://edge-chat.facebook.com/chat"),
30
+ userAgent, syncCursorStore, onSyncCursor, requestTimeoutMs, maxPendingRequests
31
+ });
32
+ transport = createNativeRealtimeTransport({
33
+ url: protocolConfig.url, headers: protocolConfig.headers, socketFactory,
34
+ protocol: protocolConfig.protocol, connectTimeoutMs, closeTimeoutMs,
35
+ protocolSetupTimeoutMs,
36
+ ...(maxFrameBytes === undefined ? {} : { maxFrameBytes }), onDiagnostic
37
+ });
38
+ await transport.connect();
39
+ const driver = transport.getDriver();
40
+ const threadApi = createFacebookThreadApi({ session });
41
+ return Object.freeze({
42
+ ...driver,
43
+ ...threadApi,
44
+ getCurrentUserID: () => session.userId,
45
+ getSessionState: () => session.state,
46
+ disconnect: async () => {
47
+ if (closed) return;
48
+ closed = true;
49
+ try { await transport.disconnect(); }
50
+ finally { session.close(); }
51
+ }
52
+ });
53
+ } catch (error) {
54
+ try { if (transport) await transport.disconnect(); } catch {}
55
+ session.close();
56
+ throw error;
57
+ }
58
+ }
59
+
60
+ module.exports = { createFacebookMqttDriver };
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+
3
+ const MAX_JSON_BYTES = 2 * 1024 * 1024;
4
+ const MAX_DELTAS = 500;
5
+ const MAX_DEPTH = 24;
6
+
7
+ function parsePayload(input) {
8
+ if (typeof input === "string" || Buffer.isBuffer(input) || input instanceof Uint8Array) {
9
+ const bytes = Buffer.isBuffer(input) ? input : Buffer.from(input);
10
+ if (bytes.byteLength > MAX_JSON_BYTES) return null;
11
+ try { return JSON.parse(bytes.toString("utf8")); } catch { return null; }
12
+ }
13
+ return input && typeof input === "object" ? input : null;
14
+ }
15
+
16
+ function withinDepth(value, depth = 0) {
17
+ if (depth > MAX_DEPTH) return false;
18
+ if (!value || typeof value !== "object") return true;
19
+ for (const child of Object.values(value)) if (!withinDepth(child, depth + 1)) return false;
20
+ return true;
21
+ }
22
+
23
+ function firstString(...values) {
24
+ return values.find(value => typeof value === "string" && value.length > 0) ?? null;
25
+ }
26
+
27
+ function firstId(...values) {
28
+ for (const value of values) {
29
+ if (typeof value === "string" && value.length > 0) return value;
30
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return String(value);
31
+ }
32
+ return null;
33
+ }
34
+
35
+ function normalizeDelta(delta) {
36
+ if (!delta || typeof delta !== "object" || Array.isArray(delta)) return null;
37
+ const kind = firstString(delta.class, delta.type, delta.deltaType);
38
+ if (!kind) return null;
39
+ const metadata = delta.messageMetadata && typeof delta.messageMetadata === "object"
40
+ ? delta.messageMetadata : {};
41
+ const threadID = firstId(metadata.threadKey?.threadFbId, metadata.threadKey?.otherUserFbId,
42
+ metadata.thread_id, delta.threadID, delta.threadId);
43
+ const messageID = firstId(metadata.messageId, metadata.message_id, delta.messageId, delta.message_id);
44
+ const senderID = firstId(metadata.actorFbId, metadata.senderId, delta.senderId, delta.actorId);
45
+ const timestamp = metadata.timestamp ?? metadata.timestampMs ?? delta.timestamp;
46
+ const base = { threadID, messageID, senderID, timestamp: timestamp ?? null, rawDelta: delta };
47
+
48
+ switch (kind) {
49
+ case "NewMessage":
50
+ case "Message": {
51
+ const replyTo = firstString(metadata.replySourceMessageId, metadata.replyToMessageId, delta.replyToMessageId);
52
+ return {
53
+ ...base, type: replyTo ? "message_reply" : "message",
54
+ body: typeof delta.body === "string" ? delta.body : "",
55
+ attachments: Array.isArray(delta.attachments) ? delta.attachments.slice(0, 100) : [],
56
+ isGroup: Boolean(metadata.threadKey?.threadFbId)
57
+ };
58
+ }
59
+ case "MessageReaction":
60
+ case "Reaction": {
61
+ const reaction = firstString(delta.reaction, delta.reactionEmoji, delta.reactionString);
62
+ return { ...base, type: "message_reaction", reaction, userID: senderID };
63
+ }
64
+ case "MessageUnsend":
65
+ case "UnsendMessage":
66
+ return { ...base, type: "message_unsend" };
67
+ case "Typing":
68
+ case "TypingNotification":
69
+ return { ...base, type: "typ", isTyping: delta.isTyping !== false };
70
+ case "ReadReceipt":
71
+ case "MarkRead":
72
+ return { ...base, type: "read", watermarkTimestamp: delta.watermarkTimestamp ?? timestamp };
73
+ case "Presence":
74
+ case "PresenceUpdate":
75
+ return { ...base, type: "presence", status: delta.status ?? delta.presence ?? null };
76
+ case "ThreadEvent":
77
+ case "ThreadName":
78
+ case "ParticipantAdded":
79
+ case "ParticipantRemoved":
80
+ return { ...base, type: "event", logMessageType: kind, logMessageData: delta };
81
+ default:
82
+ return { ...base, type: "unknown_delta", deltaType: kind };
83
+ }
84
+ }
85
+
86
+ function extractDeltas(envelope) {
87
+ if (!envelope || typeof envelope !== "object" || !withinDepth(envelope)) return [];
88
+ const candidates = [
89
+ envelope.deltas,
90
+ envelope.payload?.deltas,
91
+ envelope.data?.deltas,
92
+ envelope.sync_payload?.deltas,
93
+ envelope.syncPayload?.deltas
94
+ ];
95
+ const deltas = candidates.find(Array.isArray);
96
+ return deltas ? deltas.slice(0, MAX_DELTAS) : [];
97
+ }
98
+
99
+ function parseMessengerSyncPayload(input) {
100
+ const envelope = parsePayload(input);
101
+ if (!envelope || typeof envelope !== "object" || !withinDepth(envelope)) {
102
+ return { events: [], envelope: null, cursor: null };
103
+ }
104
+ const deltas = extractDeltas(envelope);
105
+ const events = deltas.map(normalizeDelta).filter(Boolean);
106
+ const cursor = {
107
+ syncToken: firstString(envelope.syncToken, envelope.sync_token, envelope.payload?.syncToken, envelope.payload?.sync_token),
108
+ lastSeqId: envelope.lastIssuedSeqId ?? envelope.last_seq_id ?? envelope.lastSeqId ?? envelope.firstDeltaSeqId ?? envelope.seq ?? null
109
+ };
110
+ if (cursor.syncToken === null && cursor.lastSeqId === null) return { events, envelope, cursor: null };
111
+ return { events, envelope, cursor };
112
+ }
113
+
114
+ module.exports = { parseMessengerSyncPayload, normalizeMessengerDelta: normalizeDelta, MAX_JSON_BYTES, MAX_DELTAS };