fca-neokex-fix 1.0.1

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 (114) hide show
  1. package/CHANGELOG.md +220 -0
  2. package/LICENSE +26 -0
  3. package/README.md +346 -0
  4. package/THEME_FEATURES.md +137 -0
  5. package/examples/README.md +131 -0
  6. package/examples/apply-ai-theme.js +127 -0
  7. package/examples/check-current-theme.js +74 -0
  8. package/examples/simple-bot.js +114 -0
  9. package/examples/test-bot.js +752 -0
  10. package/examples/test-logging.js +85 -0
  11. package/examples/theme-usage-example.js +53 -0
  12. package/index.js +2 -0
  13. package/package.json +105 -0
  14. package/src/apis/addExternalModule.js +24 -0
  15. package/src/apis/addUserToGroup.js +108 -0
  16. package/src/apis/changeAdminStatus.js +148 -0
  17. package/src/apis/changeArchivedStatus.js +61 -0
  18. package/src/apis/changeAvatar.js +103 -0
  19. package/src/apis/changeBio.js +69 -0
  20. package/src/apis/changeBlockedStatus.js +54 -0
  21. package/src/apis/changeGroupImage.js +136 -0
  22. package/src/apis/changeThreadColor.js +116 -0
  23. package/src/apis/comment.js +207 -0
  24. package/src/apis/createAITheme.js +129 -0
  25. package/src/apis/createNewGroup.js +79 -0
  26. package/src/apis/createPoll.js +73 -0
  27. package/src/apis/deleteMessage.js +44 -0
  28. package/src/apis/deleteThread.js +52 -0
  29. package/src/apis/editMessage.js +70 -0
  30. package/src/apis/emoji.js +124 -0
  31. package/src/apis/fetchThemeData.js +65 -0
  32. package/src/apis/follow.js +81 -0
  33. package/src/apis/forwardMessage.js +52 -0
  34. package/src/apis/friend.js +243 -0
  35. package/src/apis/gcmember.js +122 -0
  36. package/src/apis/gcname.js +123 -0
  37. package/src/apis/gcrule.js +119 -0
  38. package/src/apis/getAccess.js +111 -0
  39. package/src/apis/getBotInfo.js +88 -0
  40. package/src/apis/getBotInitialData.js +43 -0
  41. package/src/apis/getFriendsList.js +79 -0
  42. package/src/apis/getMessage.js +423 -0
  43. package/src/apis/getTheme.js +104 -0
  44. package/src/apis/getThemeInfo.js +96 -0
  45. package/src/apis/getThreadHistory.js +239 -0
  46. package/src/apis/getThreadInfo.js +257 -0
  47. package/src/apis/getThreadList.js +222 -0
  48. package/src/apis/getThreadPictures.js +58 -0
  49. package/src/apis/getUserID.js +83 -0
  50. package/src/apis/getUserInfo.js +495 -0
  51. package/src/apis/getUserInfoV2.js +146 -0
  52. package/src/apis/handleMessageRequest.js +50 -0
  53. package/src/apis/httpGet.js +63 -0
  54. package/src/apis/httpPost.js +89 -0
  55. package/src/apis/httpPostFormData.js +69 -0
  56. package/src/apis/listenMqtt.js +796 -0
  57. package/src/apis/listenSpeed.js +170 -0
  58. package/src/apis/logout.js +63 -0
  59. package/src/apis/markAsDelivered.js +47 -0
  60. package/src/apis/markAsRead.js +95 -0
  61. package/src/apis/markAsReadAll.js +41 -0
  62. package/src/apis/markAsSeen.js +70 -0
  63. package/src/apis/mqttDeltaValue.js +330 -0
  64. package/src/apis/muteThread.js +45 -0
  65. package/src/apis/nickname.js +132 -0
  66. package/src/apis/notes.js +163 -0
  67. package/src/apis/pinMessage.js +141 -0
  68. package/src/apis/produceMetaTheme.js +180 -0
  69. package/src/apis/realtime.js +161 -0
  70. package/src/apis/removeUserFromGroup.js +117 -0
  71. package/src/apis/resolvePhotoUrl.js +58 -0
  72. package/src/apis/searchForThread.js +154 -0
  73. package/src/apis/sendMessage.js +281 -0
  74. package/src/apis/sendMessageMqtt.js +188 -0
  75. package/src/apis/sendTypingIndicator.js +41 -0
  76. package/src/apis/setMessageReaction.js +27 -0
  77. package/src/apis/setMessageReactionMqtt.js +61 -0
  78. package/src/apis/setThreadTheme.js +260 -0
  79. package/src/apis/setThreadThemeMqtt.js +94 -0
  80. package/src/apis/share.js +107 -0
  81. package/src/apis/shareContact.js +66 -0
  82. package/src/apis/stickers.js +257 -0
  83. package/src/apis/story.js +181 -0
  84. package/src/apis/theme.js +233 -0
  85. package/src/apis/unfriend.js +47 -0
  86. package/src/apis/unsendMessage.js +17 -0
  87. package/src/database/appStateBackup.js +189 -0
  88. package/src/database/models/index.js +56 -0
  89. package/src/database/models/thread.js +31 -0
  90. package/src/database/models/user.js +32 -0
  91. package/src/database/threadData.js +101 -0
  92. package/src/database/userData.js +90 -0
  93. package/src/engine/client.js +91 -0
  94. package/src/engine/models/buildAPI.js +109 -0
  95. package/src/engine/models/loginHelper.js +326 -0
  96. package/src/engine/models/setOptions.js +53 -0
  97. package/src/utils/auth-helpers.js +149 -0
  98. package/src/utils/autoReLogin.js +169 -0
  99. package/src/utils/axios.js +290 -0
  100. package/src/utils/clients.js +270 -0
  101. package/src/utils/constants.js +396 -0
  102. package/src/utils/formatters/data/formatAttachment.js +370 -0
  103. package/src/utils/formatters/data/formatDelta.js +153 -0
  104. package/src/utils/formatters/index.js +159 -0
  105. package/src/utils/formatters/value/formatCookie.js +91 -0
  106. package/src/utils/formatters/value/formatDate.js +36 -0
  107. package/src/utils/formatters/value/formatID.js +16 -0
  108. package/src/utils/formatters.js +1067 -0
  109. package/src/utils/headers.js +199 -0
  110. package/src/utils/index.js +151 -0
  111. package/src/utils/monitoring.js +358 -0
  112. package/src/utils/rateLimiter.js +380 -0
  113. package/src/utils/tokenRefresh.js +311 -0
  114. package/src/utils/user-agents.js +238 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,220 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## [4.4.3] - 2025-11-15
6
+
7
+ ### 🎉 Major Anti-Bot Detection Improvements
8
+ - **Enhanced User-Agent Fingerprinting**: Expanded browser fingerprint pool for better anti-detection
9
+ - Added Microsoft Edge browser support with proper Sec-CH-UA brand metadata
10
+ - Expanded Chrome version coverage: 6 versions per platform (108-113)
11
+ - Added Linux platform support (Ubuntu, Fedora variations)
12
+ - Fixed Edge UA string duplication bug (was appending "Edg/" twice)
13
+ - Total fingerprint pool: 15+ unique combinations across Windows/Mac/Linux
14
+
15
+ - **Multi-Domain Cookie Persistence**: Session cookies now persist across all Facebook domains
16
+ - Cookies automatically set for .facebook.com, .messenger.com, .m.facebook.com
17
+ - Fixed cookie parsing bug that was duplicating domain attributes
18
+ - Better session stability and reduced logout frequency
19
+ - Matches real browser multi-domain cookie behavior
20
+
21
+ - **Critical Header Bug Fix**: Fixed X-Fb-Lsd header missing on some requests
22
+ - Now falls back to ctx.fb_dtsg when ctx.lsd unavailable
23
+ - Prevents requests from failing due to missing required headers
24
+ - Ensures all GraphQL/AJAX requests have proper security tokens
25
+
26
+ ### 🔒 Enhanced Security & Error Handling
27
+ - **Account Lock Detection**: Comprehensive checkpoint and restriction detection
28
+ - Detects error codes: 1357001, 1357004, 1357031, 1357033, 2056003
29
+ - Returns typed error responses with isAccountLocked, isCheckpoint, isRestricted flags
30
+ - Prevents unnecessary retries on locked/restricted accounts
31
+ - Graceful degradation instead of crashes
32
+
33
+ ### 🌍 Locale & Timezone Spoofing
34
+ - **Geographic Fingerprint Randomization**: Realistic locale/timezone headers
35
+ - Randomized Accept-Language headers (en-US, en-GB, es-ES, fr-FR, de-DE, pt-BR, vi-VN, th-TH)
36
+ - X-FB-Timezone-Offset properly calculated in seconds (fixed minutes→seconds conversion)
37
+ - Locale and timezone cached per login session for consistency
38
+ - Prevents timezone/locale mismatch detection
39
+
40
+ ### 📎 Intelligent Attachment Handling
41
+ - **Smart Attachment Type Detection**: Automatic file type recognition
42
+ - Detects image, video, audio, and document file types from MIME type
43
+ - No longer limited to just "voice_clip" detection
44
+ - Proper handling of all attachment categories
45
+
46
+ - **Parallel Attachment Uploads**: Concurrent upload with throttling
47
+ - Uploads 3 attachments simultaneously with batching
48
+ - Reduces total upload time for multi-attachment messages
49
+ - Prevents overwhelming Facebook servers with too many concurrent connections
50
+
51
+ ### 🔄 Token Refresh Management (Integrated)
52
+ - **Automatic Token Refresh**: 24-hour token refresh cycle
53
+ - Auto-refreshes fb_dtsg, lsd, jazoest tokens to prevent expiration
54
+ - Exposed API methods: api.refreshTokens() and api.getTokenRefreshStatus()
55
+ - Integrated into loginHelper for automatic background refresh
56
+ - **Note**: Needs retry/backoff hardening for production (future improvement)
57
+
58
+ ### ⚡ Rate Limiting Infrastructure (Created)
59
+ - **Rate Limiter Class**: Adaptive rate limiting framework created
60
+ - Per-thread, global, and per-minute request tracking structure
61
+ - Cooldown management for error-triggered throttling
62
+ - **Note**: Not yet integrated into request pipeline - deferred for proper testing
63
+
64
+ ### 📊 Competitive Analysis vs ws3-fca & @dongdev/fca-unofficial
65
+ **NeoKEX-FCA Now Surpasses:**
66
+ - ✅ **Fingerprint Stability**: Better than ws3-fca (more diverse UA pool, cached per-session)
67
+ - ✅ **Multi-Domain Cookies**: Better than both (automatic .facebook/.messenger/.m.facebook persistence)
68
+ - ✅ **Attachment Handling**: Better than ws3-fca (parallel uploads, smart type detection)
69
+ - ✅ **Account Lock Detection**: Better than ws3-fca (comprehensive error code handling)
70
+
71
+ **Still Behind On:**
72
+ - ❌ **Integrated Rate Limiting**: ws3-fca has rate limiter in request pipeline
73
+ - ❌ **Auto Re-Login**: ws3-fca has session expiry detection + auto re-login
74
+ - ❌ **MQTT Resilience**: @dongdev has better MQTT backoff and reconnection
75
+
76
+ ### 🔧 Technical Improvements
77
+ - **headers.js**: Fixed timezone offset format (minutes * 60 = seconds)
78
+ - **user-agents.js**: Fixed Edge UA generation, proper brand metadata
79
+ - **loginHelper.js**: Integrated TokenRefreshManager with API object exposure
80
+ - **clients.js**: Enhanced attachment type detection beyond voice_clip
81
+ - **sendMessage.js**: Parallel attachment uploads with concurrency control
82
+
83
+ ### 🚨 Production Readiness Assessment
84
+ - **Status**: Solid for low-volume automation, **NOT production-ready for high-volume bots**
85
+ - **Missing Critical Features**:
86
+ 1. Automatic re-login when session expires
87
+ 2. Integrated rate limiting in HTTP pipeline
88
+ 3. Token refresh retry/backoff logic
89
+ 4. Session expiry detection mechanism
90
+
91
+ ### 📝 Next Priority (Recommended by Architect Review)
92
+ 1. Implement automatic re-login tied to token refresh failures
93
+ 2. Integrate RateLimiter into request pipeline with proper telemetry
94
+ 3. Build session expiry detector to trigger safe re-login workflows
95
+ 4. Harden TokenRefreshManager with retry/backoff mechanisms
96
+
97
+ ## [4.3.0] - 2025-11-14
98
+
99
+ ### 🎉 Fixed - CRITICAL: Automated Behavior Detection & Logout Issues
100
+ - **HTTP Request Fingerprinting**: Completely resolved Facebook's automated behavior detection triggers
101
+ - Fixed User-Agent fingerprint churn that was generating new browser signatures on every request
102
+ - Implemented stable browser fingerprint caching during login session
103
+ - Now maintains consistent browser identity across entire session, matching real browser behavior
104
+
105
+ - **Request Header Correction**: Fixed incorrect HTTP headers causing bot detection
106
+ - XHR/GraphQL requests now send proper AJAX headers (Sec-Fetch-Mode: cors, Sec-Fetch-Dest: empty)
107
+ - Navigation requests send correct browser headers (Sec-Fetch-Mode: navigate, Sec-Fetch-Dest: document)
108
+ - Removed Origin header from navigation requests (browsers don't send it)
109
+ - Fixed Sec-Fetch-Site header to use 'none' for first-page loads instead of 'same-origin'
110
+
111
+ ### 🔧 Improved
112
+ - **loginHelper.js**: Cache stable browser fingerprint at login time
113
+ - Stores User-Agent, Sec-CH-UA, and all related headers in globalOptions
114
+ - Prevents fingerprint churn across session lifetime
115
+
116
+ - **headers.js**: Smart header generation based on request type
117
+ - Added requestType parameter ('xhr' vs 'navigate')
118
+ - Reuses cached fingerprint instead of generating new one each time
119
+ - Emits browser-accurate headers for each request type
120
+
121
+ - **axios.js**: Correct header assignment for API calls
122
+ - POST functions now pass requestType='xhr' for proper AJAX headers
123
+ - GraphQL/AJAX calls get XHR-appropriate headers automatically
124
+
125
+ ### 📊 Impact
126
+ - Eliminates Facebook's automated behavior detection
127
+ - Prevents automatic logout issues
128
+ - Request fingerprints now identical to real Chrome browser
129
+ - Better than ws3-fca (which has the same bugs we fixed)
130
+
131
+ ### 📚 Technical Notes
132
+ - ws3-fca@latest analysis revealed same bugs (ctx.lsd references, fingerprint churn)
133
+ - Our implementation is now superior to ws3-fca for automation detection avoidance
134
+ - All validation tests pass, no regressions detected
135
+
136
+ ## [4.2.5] - 2025-11-11
137
+
138
+ ### 🎉 Fixed
139
+ - **Error 1545012 Advanced Handling**: Major improvements to error 1545012 retry logic and rate limiting protection
140
+ - Increased exponential backoff delays from (1s, 2s, 3s) to (2s, 5s, 10s) for better Facebook API compliance
141
+ - Implemented thread cooldown mechanism (60 seconds) to prevent rate limiting after repeated failures
142
+ - Added error suppression cache (5-minute TTL) to prevent log spam for known failing threads
143
+ - Smart cooldown system immediately blocks sends to threads on cooldown
144
+ - Enhanced error messages with detailed context (suppressed, onCooldown, notMember flags)
145
+
146
+ ### 🔧 Improved
147
+ - **Intelligent Error Logging**: Conditional logging prevents spam while maintaining visibility
148
+ - First error per thread/error combination is logged with full details
149
+ - Subsequent errors within 5 minutes are suppressed from logs
150
+ - Thread cooldown warnings only shown once
151
+ - **Better Rate Limit Protection**:
152
+ - Threads that fail after 3 retries are placed on 60-second cooldown
153
+ - Cooldown prevents further API calls, reducing rate limit risk
154
+ - Automatic cooldown cleanup after timeout
155
+ - **Membership Verification Optimization**:
156
+ - Membership only verified once per retry cycle (not on every attempt)
157
+ - Immediate failure if bot confirmed not in thread
158
+ - Cached verification result reused across retries
159
+
160
+ ### 📚 Documentation
161
+ - Updated error handling to match production debugging patterns
162
+ - Error metadata includes all troubleshooting context needed
163
+
164
+ ## [4.2.4] - 2025-11-11
165
+
166
+ ### 🎉 Fixed
167
+ - **Error 1545012 Retry Logic**: Implemented intelligent retry mechanism for "Not part of conversation" errors
168
+ - Automatically retries up to 3 times with exponential backoff (1s, 2s, 3s)
169
+ - Verifies bot membership using `getThreadInfo` between retries
170
+ - Fails immediately if bot is confirmed not in group
171
+ - Handles temporary Facebook API glitches caused by stale cache or backend hiccups
172
+ - Prevents message duplication by reusing the same offline threading ID
173
+
174
+ ### 🔧 Improved
175
+ - Enhanced error messages for 1545012 with detailed context:
176
+ - `attempts`: Number of retry attempts made
177
+ - `verified`: Whether membership was verified via getThreadInfo
178
+ - Better logging to help diagnose persistent issues
179
+ - Graceful fallback when membership verification fails
180
+
181
+ ### 📚 Documentation
182
+ - Updated THEME_FEATURES.md with detailed error 1545012 retry logic explanation
183
+ - Added examples for handling verified vs unverified failures
184
+ - Documented why Facebook returns 1545012 for bots that ARE in groups
185
+
186
+ ## [4.2.3] - 2025-01-11
187
+
188
+ ### 🎉 Fixed
189
+ - **AI Theme Generation**: Fixed critical bug where LSD token wasn't being extracted during login
190
+ - Added proper LSD token extraction in `buildAPI.js` from Facebook's `DTSGInitialData` and `LSD` config
191
+ - Updated `createAITheme.js` with all required Facebook parameters (lsd, jazoest, session parameters)
192
+ - Added custom headers (`x-fb-lsd`, `x-fb-friendly-name`) for GraphQL requests
193
+ - AI theme generation now works correctly for accounts with feature access
194
+
195
+ ### 🔧 Improved
196
+ - Enhanced `createAITheme` with complete session parameter support:
197
+ - `__user`, `__a`, `__req`, `__hs`, `__rev`, `__s`, `__hsi`
198
+ - `__dyn`, `__csr`, `__comet_req`, `dpr`, `__ccg`
199
+ - Better error handling for accounts without AI theme access
200
+ - Added comprehensive examples for AI theme usage
201
+
202
+ ### 📚 Documentation
203
+ - Updated README with detailed AI theme usage examples
204
+ - Added notes about account-level restrictions for AI features
205
+ - Included standard theme fallback documentation
206
+ - Added examples for theme verification and current theme checking
207
+
208
+ ### 🧹 Cleanup
209
+ - Removed debug files and test scripts
210
+ - Organized examples folder with production-ready code
211
+ - Improved code organization and maintainability
212
+
213
+ ### 🐛 Known Issues
214
+ - AI theme generation is restricted by Facebook to specific accounts/regions
215
+ - Not a code issue - this is a server-side Facebook restriction
216
+ - Standard themes (90+ available) work for all accounts
217
+
218
+ ## [4.2.2] - Previous Release
219
+
220
+ (Previous changelog entries...)
package/LICENSE ADDED
@@ -0,0 +1,26 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024-2025 NeoKEX
4
+
5
+ Inspired by ws3-fca, originally created by:
6
+ - @NethWs3Dev
7
+ - @CommunityExocore
8
+ - Avery, Benjamin, David, Maude (facebook-chat-api)
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in
18
+ all copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,346 @@
1
+ # 🚀 FCA-NeoKEX (fca-neokex)
2
+
3
+ [![npm version](https://img.shields.io/npm/v/fca-neokex.svg)](https://www.npmjs.com/package/fca-neokex)
4
+ [![npm downloads](https://img.shields.io/npm/dm/fca-neokex.svg)](https://www.npmjs.com/package/fca-neokex)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+ [![Node.js Version](https://img.shields.io/node/v/fca-neokex.svg)](https://nodejs.org)
7
+
8
+ 💁 **fca-neokex** is a bug-fixed and production-ready fork of `neokex-fca`, an advanced Facebook Chat API (FCA) client for **reliable**, **real-time**, and **modular** interaction with Facebook Messenger.
9
+
10
+ ## 🔧 What's Fixed in This Fork?
11
+
12
+ This fork addresses **critical production bugs** found in the original `neokex-fca`:
13
+
14
+ ✅ **Memory Leak Fixed** - Old MQTT clients and event listeners are now properly cleaned up
15
+ ✅ **Hot Reconnect Loop Resolved** - No more infinite reconnection loops consuming CPU
16
+ ✅ **Proper Resource Management** - All timers, connections, and listeners are properly released
17
+ ✅ **Maximum Retry Limits** - Bot stops gracefully after reasonable attempts (50 reconnects, 10 getSeqID failures)
18
+ ✅ **Unhandled Promise Rejections Fixed** - Safe promise handling prevents Node.js crashes
19
+ ✅ **Production-Ready Stability** - Proper notifications when bot stops due to connection issues
20
+
21
+ **Before:** Bot would run forever, consuming memory and CPU indefinitely
22
+ **After:** Bot manages resources efficiently and stops gracefully when limits are reached
23
+
24
+ ---
25
+
26
+ ## 📚 Documentation
27
+
28
+ - **[Theme Features](THEME_FEATURES.md)** - Comprehensive guide to theme management
29
+ - **[Changelog](CHANGELOG.md)** - Version history and updates
30
+ - **[Examples](examples/)** - Code examples and usage patterns
31
+
32
+ ### Support & Issues
33
+
34
+ If you encounter issues or want to contribute, please open an issue on GitHub.
35
+
36
+ ---
37
+
38
+ ## ✨ Features
39
+
40
+ * 🔐 **Precise Login Mechanism**
41
+ Dynamically scrapes Facebook's login form and submits tokens for secure authentication.
42
+
43
+ * 💬 **Real-time Messaging**
44
+ Send and receive messages (text, attachments, stickers, replies).
45
+
46
+ * 📝 **Message Editing**
47
+ Edit your bot's messages in-place.
48
+
49
+ * ✍️ **Typing Indicators**
50
+ Detect and send typing status.
51
+
52
+ * ✅ **Message Status Handling**
53
+ Mark messages as delivered, read, or seen.
54
+
55
+ * 📂 **Thread Management**
56
+ * Retrieve thread details
57
+ * Load thread message history
58
+ * Get lists with filtering
59
+ * Pin/unpin messages
60
+
61
+ * 👤 **User Info Retrieval**
62
+ Access name, ID, profile picture, and mutual context.
63
+
64
+ * 🖼️ **Sticker API**
65
+ Search stickers, list packs, fetch store data, AI-generated stickers.
66
+
67
+ * 💬 **Post Interaction**
68
+ Comment and reply to public Facebook posts.
69
+
70
+ * ➕ **Follow/Unfollow Users**
71
+ Automate social interactions.
72
+
73
+ * 🌐 **Proxy Support**
74
+ Full support for custom proxies.
75
+
76
+ * 🧱 **Modular Architecture**
77
+ Organized into pluggable models for maintainability.
78
+
79
+ * 🛡️ **Robust Error Handling**
80
+ Retry logic, consistent logging, and graceful failovers.
81
+
82
+ * 🔄 **Production-Ready Reconnection**
83
+ Smart exponential backoff with maximum retry limits.
84
+
85
+ ---
86
+
87
+ ## ⚙️ Installation
88
+
89
+ > **Requirements:** Node.js v18.0.0 or higher
90
+
91
+ ```bash
92
+ npm install fca-neokex
93
+ ```
94
+
95
+ Or use the latest version:
96
+
97
+ ```bash
98
+ npm install fca-neokex@latest
99
+ ```
100
+
101
+ ---
102
+
103
+ ## 🔒 Security Warning
104
+
105
+ **IMPORTANT:** `appstate.json` contains your Facebook session credentials and should be treated as sensitive information.
106
+
107
+ - ⚠️ **Never commit `appstate.json` to version control**
108
+ - ⚠️ **Never share your `appstate.json` file publicly**
109
+ - ⚠️ **Keep it in `.gitignore`** (already configured in this project)
110
+ - ⚠️ **Use environment-specific credentials** for production deployments
111
+
112
+ Your `appstate.json` gives full access to your Facebook account. Treat it like a password!
113
+
114
+ ---
115
+
116
+ ## 🚀 Getting Started
117
+
118
+ ### 1. Generate `appstate.json`
119
+
120
+ This file contains your Facebook session cookies. Follow these steps:
121
+
122
+ 1. **Install a cookie export extension** for your browser:
123
+ - Chrome/Edge: "C3C FbState" or "CookieEditor"
124
+ - Firefox: "Cookie-Editor"
125
+
126
+ 2. **Log in to Facebook** in your browser
127
+
128
+ 3. **Export cookies** using the extension and save them in this format:
129
+
130
+ ```json
131
+ [
132
+ {
133
+ "key": "c_user",
134
+ "value": "your-user-id"
135
+ },
136
+ {
137
+ "key": "xs",
138
+ "value": "your-xs-token"
139
+ },
140
+ {
141
+ "key": "datr",
142
+ "value": "your-datr-token"
143
+ }
144
+ ]
145
+ ```
146
+
147
+ Save this as `appstate.json` in your project directory.
148
+
149
+ ### 2. Basic Usage Example
150
+
151
+ ```javascript
152
+ const { login } = require("fca-neokex");
153
+
154
+ login({ appState: require("./appstate.json") }, (err, api) => {
155
+ if (err) {
156
+ console.error("Login failed:", err);
157
+ return;
158
+ }
159
+
160
+ console.log("✅ Logged in successfully!");
161
+
162
+ // Listen for messages
163
+ api.listenMqtt((err, message) => {
164
+ if (err) {
165
+ console.error("Listen error:", err);
166
+ return;
167
+ }
168
+
169
+ if (message.type === "message") {
170
+ console.log(`Message from ${message.senderID}: ${message.body}`);
171
+
172
+ // Reply to the message
173
+ api.sendMessage(
174
+ `You said: ${message.body}`,
175
+ message.threadID,
176
+ (err) => {
177
+ if (err) console.error("Send error:", err);
178
+ }
179
+ );
180
+ }
181
+ });
182
+ });
183
+ ```
184
+
185
+ ### 3. Advanced Usage with Options
186
+
187
+ ```javascript
188
+ const { login } = require("fca-neokex");
189
+
190
+ const loginOptions = {
191
+ selfListen: false, // Don't listen to own messages
192
+ listenEvents: true, // Listen to events (joins, leaves, etc.)
193
+ autoReconnect: true, // Auto-reconnect on disconnect
194
+ autoMarkRead: true, // Auto-mark messages as read
195
+ online: true, // Show as online
196
+ emitReady: true, // Emit ready event when connected
197
+ userAgent: "Mozilla/5.0 ..." // Custom user agent
198
+ };
199
+
200
+ login({ appState: require("./appstate.json") }, loginOptions, (err, api) => {
201
+ if (err) {
202
+ console.error("Login failed:", err);
203
+ return;
204
+ }
205
+
206
+ api.listenMqtt((err, event) => {
207
+ if (err) {
208
+ // Handle errors - bot will auto-reconnect
209
+ if (err.type === "stop_listen") {
210
+ console.error("Bot stopped due to:", err.error);
211
+ }
212
+ return;
213
+ }
214
+
215
+ // Handle different event types
216
+ switch (event.type) {
217
+ case "message":
218
+ console.log("New message:", event);
219
+ break;
220
+ case "message_reaction":
221
+ console.log("New reaction:", event);
222
+ break;
223
+ case "ready":
224
+ console.log("Bot is ready!");
225
+ break;
226
+ default:
227
+ console.log("Event:", event);
228
+ }
229
+ });
230
+ });
231
+ ```
232
+
233
+ ---
234
+
235
+ ## 📦 API Methods
236
+
237
+ ### Messaging
238
+ - `sendMessage(message, threadID, callback)` - Send a message
239
+ - `sendTypingIndicator(threadID, callback)` - Send typing indicator
240
+ - `markAsRead(threadID, callback)` - Mark thread as read
241
+ - `markAsDelivered(messageID, threadID, callback)` - Mark message as delivered
242
+ - `editMessage(text, messageID, callback)` - Edit a message
243
+
244
+ ### Thread Management
245
+ - `getThreadInfo(threadID, callback)` - Get thread information
246
+ - `getThreadHistory(threadID, amount, timestamp, callback)` - Get message history
247
+ - `getThreadList(limit, timestamp, tags, callback)` - Get thread list
248
+ - `changeThreadColor(color, threadID, callback)` - Change thread color
249
+ - `changeGroupImage(image, threadID, callback)` - Change group image
250
+
251
+ ### User Information
252
+ - `getUserInfo(ids, callback)` - Get user information
253
+ - `getUserID(name, callback)` - Get user ID from name
254
+ - `getFriendsList(callback)` - Get friends list
255
+
256
+ ### Other
257
+ - `logout(callback)` - Logout and cleanup
258
+ - `setOptions(options)` - Update API options
259
+
260
+ ---
261
+
262
+ ## 🎨 AI Theme Generation
263
+
264
+ fca-neokex includes advanced AI theme generation capabilities. See [THEME_FEATURES.md](THEME_FEATURES.md) for details.
265
+
266
+ ```javascript
267
+ // Create a custom AI-generated theme
268
+ api.createAITheme({
269
+ threadID: "thread_id_here",
270
+ themePrompt: "ocean sunset with purple gradients",
271
+ callback: (err, result) => {
272
+ if (err) console.error(err);
273
+ else console.log("Theme created:", result);
274
+ }
275
+ });
276
+ ```
277
+
278
+ ---
279
+
280
+ ## 🔧 Configuration Options
281
+
282
+ | Option | Type | Default | Description |
283
+ |--------|------|---------|-------------|
284
+ | `selfListen` | boolean | false | Listen to your own messages |
285
+ | `listenEvents` | boolean | true | Listen to events (joins, leaves, etc.) |
286
+ | `autoReconnect` | boolean | true | Automatically reconnect on disconnect |
287
+ | `autoMarkRead` | boolean | true | Automatically mark messages as read |
288
+ | `autoMarkDelivery` | boolean | false | Automatically mark messages as delivered |
289
+ | `online` | boolean | true | Show as online |
290
+ | `emitReady` | boolean | false | Emit ready event when connected |
291
+ | `userAgent` | string | (default) | Custom user agent string |
292
+ | `proxy` | string | null | Proxy server URL |
293
+
294
+ ---
295
+
296
+ ## 🐛 Troubleshooting
297
+
298
+ ### Bot Not Receiving Messages
299
+ - Verify your `appstate.json` is valid and up-to-date
300
+ - Check that you're logged in to Facebook in a browser
301
+ - Ensure your account isn't checkpoint restricted
302
+
303
+ ### Login Errors
304
+ - Re-export your cookies using the browser extension
305
+ - Clear Facebook cookies and login again
306
+ - Try using a different browser
307
+
308
+ ### Connection Issues
309
+ - Bot will auto-reconnect up to 50 times with exponential backoff
310
+ - If you see "Max reconnect attempts exceeded", check your network connection
311
+ - If you see "Max consecutive getSeqID failures", your session may be invalid
312
+
313
+ ### Memory/CPU Issues
314
+ - ✅ **FIXED in this fork!** The original `neokex-fca` had memory leaks
315
+ - This version properly cleans up resources and stops after reasonable retry attempts
316
+
317
+ ---
318
+
319
+ ## 📄 License
320
+
321
+ MIT License - see [LICENSE](LICENSE) file for details.
322
+
323
+ ---
324
+
325
+ ## 🙏 Credits
326
+
327
+ - Original `neokex-fca` by **NeoKEX Team**
328
+ - Bug fixes and production improvements in this fork
329
+ - Inspired by `ws3-fca` and the Facebook Chat API community
330
+
331
+ ---
332
+
333
+ ## 🔗 Links
334
+
335
+ - **npm Package:** [https://www.npmjs.com/package/fca-neokex](https://www.npmjs.com/package/fca-neokex)
336
+ - **Original Package:** [https://www.npmjs.com/package/neokex-fca](https://www.npmjs.com/package/neokex-fca)
337
+
338
+ ---
339
+
340
+ ## 📝 Changelog
341
+
342
+ See [CHANGELOG.md](CHANGELOG.md) for version history and updates.
343
+
344
+ ---
345
+
346
+ **Made with ❤️ for the Facebook Chat API community**