3xui-api-client 2.0.0 → 2.1.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.
@@ -1,311 +1,311 @@
1
- /**
2
- * Web Middleware for Express.js and Next.js integration
3
- * Provides session management and authentication handling for web applications
4
- */
5
-
6
- /* global fetch */
7
-
8
- const ThreeXUI = require('../../index');
9
- const { createSessionManager } = require('../session/SessionManager');
10
-
11
- /**
12
- * Express.js middleware for 3x-ui API integration
13
- * @param {Object} config - Middleware configuration
14
- * @param {string} config.baseURL - 3x-ui server URL
15
- * @param {string} config.username - Admin username
16
- * @param {string} config.password - Admin password
17
- * @param {Object} config.sessionManager - Session manager configuration
18
- * @param {string} config.sessionKey - Session key name (default: '3xui_client')
19
- * @returns {Function} Express middleware function
20
- */
21
- function createExpressMiddleware(config) {
22
- if (!config.baseURL || !config.username || !config.password) {
23
- throw new Error('baseURL, username, and password are required');
24
- }
25
-
26
- const sessionKey = config.sessionKey || '3xui_client';
27
- const sessionManager = config.sessionManager || createSessionManager();
28
-
29
- return async(req, res, next) => {
30
- try {
31
- // Check if client already exists in request
32
- if (req[sessionKey]) {
33
- return next();
34
- }
35
-
36
- // Create or retrieve 3x-ui client
37
- const client = new ThreeXUI(
38
- config.baseURL,
39
- config.username,
40
- config.password,
41
- { sessionManager }
42
- );
43
-
44
- // Ensure authentication
45
- await client.login();
46
-
47
- // Attach client to request object
48
- req[sessionKey] = client;
49
-
50
- // Add helper methods to response
51
- res.generate3xuiCredentials = (protocol, options = {}) => {
52
- return client.generateCredentials(protocol, options);
53
- };
54
-
55
- res.add3xuiClient = async(inboundId, protocol, options = {}) => {
56
- return await client.addClientWithCredentials(inboundId, protocol, options);
57
- };
58
-
59
- next();
60
- } catch (error) {
61
- console.error('3x-ui middleware error:', error);
62
- res.status(500).json({
63
- error: '3x-ui authentication failed',
64
- message: error.message
65
- });
66
- }
67
- };
68
- }
69
-
70
- /**
71
- * Next.js API route handler wrapper
72
- * @param {Object} config - Configuration object
73
- * @param {Function} handler - API route handler function
74
- * @returns {Function} Wrapped Next.js API handler
75
- */
76
- function withThreeXUI(config, handler) {
77
- if (!config.baseURL || !config.username || !config.password) {
78
- throw new Error('baseURL, username, and password are required');
79
- }
80
-
81
- const sessionManager = config.sessionManager || createSessionManager();
82
- const client = new ThreeXUI(
83
- config.baseURL,
84
- config.username,
85
- config.password,
86
- { sessionManager }
87
- );
88
-
89
- return async(req, res) => {
90
- try {
91
- // Ensure authentication
92
- await client.login();
93
-
94
- // Attach client and helper methods to request
95
- req.threeXUI = client;
96
- req.generateCredentials = (protocol, options = {}) => {
97
- return client.generateCredentials(protocol, options);
98
- };
99
- req.addClientWithCredentials = async(inboundId, protocol, options = {}) => {
100
- return await client.addClientWithCredentials(inboundId, protocol, options);
101
- };
102
-
103
- // Call the original handler
104
- return await handler(req, res);
105
- } catch (error) {
106
- console.error('3x-ui Next.js wrapper error:', error);
107
- return res.status(500).json({
108
- error: '3x-ui authentication failed',
109
- message: error.message
110
- });
111
- }
112
- };
113
- }
114
-
115
- /**
116
- * React Hook for client-side 3x-ui integration
117
- * Note: This requires server-side proxy endpoints for security
118
- */
119
- function createReactHook(apiEndpoint = '/api/3xui') {
120
- return {
121
- /**
122
- * Generate credentials via API call
123
- * @param {string} protocol - Protocol name
124
- * @param {Object} options - Generation options
125
- * @returns {Promise<Object>} Generated credentials
126
- */
127
- async generateCredentials(protocol, options = {}) {
128
- const response = await fetch(`${apiEndpoint}/generate-credentials`, {
129
- method: 'POST',
130
- headers: {
131
- 'Content-Type': 'application/json'
132
- },
133
- body: JSON.stringify({ protocol, options })
134
- });
135
-
136
- if (!response.ok) {
137
- throw new Error(`HTTP error! status: ${response.status}`);
138
- }
139
-
140
- return await response.json();
141
- },
142
-
143
- /**
144
- * Add client with credentials via API call
145
- * @param {number} inboundId - Inbound ID
146
- * @param {string} protocol - Protocol type
147
- * @param {Object} options - Client options
148
- * @returns {Promise<Object>} Created client
149
- */
150
- async addClientWithCredentials(inboundId, protocol, options = {}) {
151
- const response = await fetch(`${apiEndpoint}/add-client`, {
152
- method: 'POST',
153
- headers: {
154
- 'Content-Type': 'application/json'
155
- },
156
- body: JSON.stringify({ inboundId, protocol, options })
157
- });
158
-
159
- if (!response.ok) {
160
- throw new Error(`HTTP error! status: ${response.status}`);
161
- }
162
-
163
- return await response.json();
164
- },
165
-
166
- /**
167
- * Get inbounds list via API call
168
- * @returns {Promise<Array>} Inbounds list
169
- */
170
- async getInbounds() {
171
- const response = await fetch(`${apiEndpoint}/inbounds`);
172
-
173
- if (!response.ok) {
174
- throw new Error(`HTTP error! status: ${response.status}`);
175
- }
176
-
177
- return await response.json();
178
- },
179
-
180
- /**
181
- * Get client traffic information
182
- * @param {string} email - Client email
183
- * @returns {Promise<Object>} Traffic information
184
- */
185
- async getClientTraffic(email) {
186
- const response = await fetch(`${apiEndpoint}/client-traffic/${encodeURIComponent(email)}`);
187
-
188
- if (!response.ok) {
189
- throw new Error(`HTTP error! status: ${response.status}`);
190
- }
191
-
192
- return await response.json();
193
- }
194
- };
195
- }
196
-
197
- /**
198
- * Create session management configuration helpers
199
- */
200
- const SessionConfig = {
201
- /**
202
- * Memory-based session configuration (development)
203
- * @returns {Object} Memory session config
204
- */
205
- memory() {
206
- return {
207
- sessionManager: createSessionManager()
208
- };
209
- },
210
-
211
- /**
212
- * Redis-based session configuration (production)
213
- * @param {Object} redisClient - Redis client instance
214
- * @param {Object} options - Redis options
215
- * @returns {Object} Redis session config
216
- */
217
- redis(redisClient, options = {}) {
218
- return {
219
- sessionManager: createSessionManager({
220
- redis: redisClient,
221
- redisOptions: options
222
- })
223
- };
224
- },
225
-
226
- /**
227
- * Database-based session configuration
228
- * @param {Object} database - Database client instance
229
- * @param {Object} options - Database options
230
- * @returns {Object} Database session config
231
- */
232
- database(database, options = {}) {
233
- return {
234
- sessionManager: createSessionManager({
235
- database: database,
236
- databaseOptions: options
237
- })
238
- };
239
- },
240
-
241
- /**
242
- * Custom session handler configuration
243
- * @param {Object} handlers - Custom handler functions
244
- * @returns {Object} Custom session config
245
- */
246
- custom(handlers) {
247
- return {
248
- sessionManager: createSessionManager({
249
- customHandler: handlers
250
- })
251
- };
252
- }
253
- };
254
-
255
- /**
256
- * Example Next.js API routes generator
257
- */
258
- const createNextjsRoutes = (config) => {
259
- return {
260
- // GET /api/3xui/inbounds
261
- inbounds: withThreeXUI(config, async(req, res) => {
262
- try {
263
- const inbounds = await req.threeXUI.getInbounds();
264
- res.status(200).json(inbounds);
265
- } catch (error) {
266
- res.status(500).json({ error: error.message });
267
- }
268
- }),
269
-
270
- // POST /api/3xui/generate-credentials
271
- generateCredentials: withThreeXUI(config, async(req, res) => {
272
- try {
273
- const { protocol, options } = req.body;
274
- const credentials = req.generateCredentials(protocol, options);
275
- res.status(200).json(credentials);
276
- } catch (error) {
277
- res.status(500).json({ error: error.message });
278
- }
279
- }),
280
-
281
- // POST /api/3xui/add-client
282
- addClient: withThreeXUI(config, async(req, res) => {
283
- try {
284
- const { inboundId, protocol, options } = req.body;
285
- const result = await req.addClientWithCredentials(inboundId, protocol, options);
286
- res.status(200).json(result);
287
- } catch (error) {
288
- res.status(500).json({ error: error.message });
289
- }
290
- }),
291
-
292
- // GET /api/3xui/client-traffic/[email]
293
- clientTraffic: withThreeXUI(config, async(req, res) => {
294
- try {
295
- const { email } = req.query;
296
- const traffic = await req.threeXUI.getClientTrafficsByEmail(email);
297
- res.status(200).json(traffic);
298
- } catch (error) {
299
- res.status(500).json({ error: error.message });
300
- }
301
- })
302
- };
303
- };
304
-
305
- module.exports = {
306
- createExpressMiddleware,
307
- withThreeXUI,
308
- createReactHook,
309
- SessionConfig,
310
- createNextjsRoutes
1
+ /**
2
+ * Web Middleware for Express.js and Next.js integration
3
+ * Provides session management and authentication handling for web applications
4
+ */
5
+
6
+ /* global fetch */
7
+
8
+ const ThreeXUI = require('../../index');
9
+ const { createSessionManager } = require('../session/SessionManager');
10
+
11
+ /**
12
+ * Express.js middleware for 3x-ui API integration
13
+ * @param {Object} config - Middleware configuration
14
+ * @param {string} config.baseURL - 3x-ui server URL
15
+ * @param {string} config.username - Admin username
16
+ * @param {string} config.password - Admin password
17
+ * @param {Object} config.sessionManager - Session manager configuration
18
+ * @param {string} config.sessionKey - Session key name (default: '3xui_client')
19
+ * @returns {Function} Express middleware function
20
+ */
21
+ function createExpressMiddleware(config) {
22
+ if (!config.baseURL || !config.username || !config.password) {
23
+ throw new Error('baseURL, username, and password are required');
24
+ }
25
+
26
+ const sessionKey = config.sessionKey || '3xui_client';
27
+ const sessionManager = config.sessionManager || createSessionManager();
28
+
29
+ return async(req, res, next) => {
30
+ try {
31
+ // Check if client already exists in request
32
+ if (req[sessionKey]) {
33
+ return next();
34
+ }
35
+
36
+ // Create or retrieve 3x-ui client
37
+ const client = new ThreeXUI(
38
+ config.baseURL,
39
+ config.username,
40
+ config.password,
41
+ { sessionManager }
42
+ );
43
+
44
+ // Ensure authentication
45
+ await client.login();
46
+
47
+ // Attach client to request object
48
+ req[sessionKey] = client;
49
+
50
+ // Add helper methods to response
51
+ res.generate3xuiCredentials = (protocol, options = {}) => {
52
+ return client.generateCredentials(protocol, options);
53
+ };
54
+
55
+ res.add3xuiClient = async(inboundId, protocol, options = {}) => {
56
+ return await client.addClientWithCredentials(inboundId, protocol, options);
57
+ };
58
+
59
+ next();
60
+ } catch (error) {
61
+ console.error('3x-ui middleware error:', error);
62
+ res.status(500).json({
63
+ error: '3x-ui authentication failed',
64
+ message: error.message
65
+ });
66
+ }
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Next.js API route handler wrapper
72
+ * @param {Object} config - Configuration object
73
+ * @param {Function} handler - API route handler function
74
+ * @returns {Function} Wrapped Next.js API handler
75
+ */
76
+ function withThreeXUI(config, handler) {
77
+ if (!config.baseURL || !config.username || !config.password) {
78
+ throw new Error('baseURL, username, and password are required');
79
+ }
80
+
81
+ const sessionManager = config.sessionManager || createSessionManager();
82
+ const client = new ThreeXUI(
83
+ config.baseURL,
84
+ config.username,
85
+ config.password,
86
+ { sessionManager }
87
+ );
88
+
89
+ return async(req, res) => {
90
+ try {
91
+ // Ensure authentication
92
+ await client.login();
93
+
94
+ // Attach client and helper methods to request
95
+ req.threeXUI = client;
96
+ req.generateCredentials = (protocol, options = {}) => {
97
+ return client.generateCredentials(protocol, options);
98
+ };
99
+ req.addClientWithCredentials = async(inboundId, protocol, options = {}) => {
100
+ return await client.addClientWithCredentials(inboundId, protocol, options);
101
+ };
102
+
103
+ // Call the original handler
104
+ return await handler(req, res);
105
+ } catch (error) {
106
+ console.error('3x-ui Next.js wrapper error:', error);
107
+ return res.status(500).json({
108
+ error: '3x-ui authentication failed',
109
+ message: error.message
110
+ });
111
+ }
112
+ };
113
+ }
114
+
115
+ /**
116
+ * React Hook for client-side 3x-ui integration
117
+ * Note: This requires server-side proxy endpoints for security
118
+ */
119
+ function createReactHook(apiEndpoint = '/api/3xui') {
120
+ return {
121
+ /**
122
+ * Generate credentials via API call
123
+ * @param {string} protocol - Protocol name
124
+ * @param {Object} options - Generation options
125
+ * @returns {Promise<Object>} Generated credentials
126
+ */
127
+ async generateCredentials(protocol, options = {}) {
128
+ const response = await fetch(`${apiEndpoint}/generate-credentials`, {
129
+ method: 'POST',
130
+ headers: {
131
+ 'Content-Type': 'application/json'
132
+ },
133
+ body: JSON.stringify({ protocol, options })
134
+ });
135
+
136
+ if (!response.ok) {
137
+ throw new Error(`HTTP error! status: ${response.status}`);
138
+ }
139
+
140
+ return await response.json();
141
+ },
142
+
143
+ /**
144
+ * Add client with credentials via API call
145
+ * @param {number} inboundId - Inbound ID
146
+ * @param {string} protocol - Protocol type
147
+ * @param {Object} options - Client options
148
+ * @returns {Promise<Object>} Created client
149
+ */
150
+ async addClientWithCredentials(inboundId, protocol, options = {}) {
151
+ const response = await fetch(`${apiEndpoint}/add-client`, {
152
+ method: 'POST',
153
+ headers: {
154
+ 'Content-Type': 'application/json'
155
+ },
156
+ body: JSON.stringify({ inboundId, protocol, options })
157
+ });
158
+
159
+ if (!response.ok) {
160
+ throw new Error(`HTTP error! status: ${response.status}`);
161
+ }
162
+
163
+ return await response.json();
164
+ },
165
+
166
+ /**
167
+ * Get inbounds list via API call
168
+ * @returns {Promise<Array>} Inbounds list
169
+ */
170
+ async getInbounds() {
171
+ const response = await fetch(`${apiEndpoint}/inbounds`);
172
+
173
+ if (!response.ok) {
174
+ throw new Error(`HTTP error! status: ${response.status}`);
175
+ }
176
+
177
+ return await response.json();
178
+ },
179
+
180
+ /**
181
+ * Get client traffic information
182
+ * @param {string} email - Client email
183
+ * @returns {Promise<Object>} Traffic information
184
+ */
185
+ async getClientTraffic(email) {
186
+ const response = await fetch(`${apiEndpoint}/client-traffic/${encodeURIComponent(email)}`);
187
+
188
+ if (!response.ok) {
189
+ throw new Error(`HTTP error! status: ${response.status}`);
190
+ }
191
+
192
+ return await response.json();
193
+ }
194
+ };
195
+ }
196
+
197
+ /**
198
+ * Create session management configuration helpers
199
+ */
200
+ const SessionConfig = {
201
+ /**
202
+ * Memory-based session configuration (development)
203
+ * @returns {Object} Memory session config
204
+ */
205
+ memory() {
206
+ return {
207
+ sessionManager: createSessionManager()
208
+ };
209
+ },
210
+
211
+ /**
212
+ * Redis-based session configuration (production)
213
+ * @param {Object} redisClient - Redis client instance
214
+ * @param {Object} options - Redis options
215
+ * @returns {Object} Redis session config
216
+ */
217
+ redis(redisClient, options = {}) {
218
+ return {
219
+ sessionManager: createSessionManager({
220
+ redis: redisClient,
221
+ redisOptions: options
222
+ })
223
+ };
224
+ },
225
+
226
+ /**
227
+ * Database-based session configuration
228
+ * @param {Object} database - Database client instance
229
+ * @param {Object} options - Database options
230
+ * @returns {Object} Database session config
231
+ */
232
+ database(database, options = {}) {
233
+ return {
234
+ sessionManager: createSessionManager({
235
+ database: database,
236
+ databaseOptions: options
237
+ })
238
+ };
239
+ },
240
+
241
+ /**
242
+ * Custom session handler configuration
243
+ * @param {Object} handlers - Custom handler functions
244
+ * @returns {Object} Custom session config
245
+ */
246
+ custom(handlers) {
247
+ return {
248
+ sessionManager: createSessionManager({
249
+ customHandler: handlers
250
+ })
251
+ };
252
+ }
253
+ };
254
+
255
+ /**
256
+ * Example Next.js API routes generator
257
+ */
258
+ const createNextjsRoutes = (config) => {
259
+ return {
260
+ // GET /api/3xui/inbounds
261
+ inbounds: withThreeXUI(config, async(req, res) => {
262
+ try {
263
+ const inbounds = await req.threeXUI.getInbounds();
264
+ res.status(200).json(inbounds);
265
+ } catch (error) {
266
+ res.status(500).json({ error: error.message });
267
+ }
268
+ }),
269
+
270
+ // POST /api/3xui/generate-credentials
271
+ generateCredentials: withThreeXUI(config, async(req, res) => {
272
+ try {
273
+ const { protocol, options } = req.body;
274
+ const credentials = req.generateCredentials(protocol, options);
275
+ res.status(200).json(credentials);
276
+ } catch (error) {
277
+ res.status(500).json({ error: error.message });
278
+ }
279
+ }),
280
+
281
+ // POST /api/3xui/add-client
282
+ addClient: withThreeXUI(config, async(req, res) => {
283
+ try {
284
+ const { inboundId, protocol, options } = req.body;
285
+ const result = await req.addClientWithCredentials(inboundId, protocol, options);
286
+ res.status(200).json(result);
287
+ } catch (error) {
288
+ res.status(500).json({ error: error.message });
289
+ }
290
+ }),
291
+
292
+ // GET /api/3xui/client-traffic/[email]
293
+ clientTraffic: withThreeXUI(config, async(req, res) => {
294
+ try {
295
+ const { email } = req.query;
296
+ const traffic = await req.threeXUI.getClientTrafficsByEmail(email);
297
+ res.status(200).json(traffic);
298
+ } catch (error) {
299
+ res.status(500).json({ error: error.message });
300
+ }
301
+ })
302
+ };
303
+ };
304
+
305
+ module.exports = {
306
+ createExpressMiddleware,
307
+ withThreeXUI,
308
+ createReactHook,
309
+ SessionConfig,
310
+ createNextjsRoutes
311
311
  };