======================== CODE SNIPPETS ======================== TITLE: Add Inbound Response Example DESCRIPTION: Provides an example of a successful response when adding a new inbound, including the inbound's ID, traffic statistics, configuration details, and protocol-specific settings. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Inbound-Management.md#_snippet_6 LANGUAGE: json CODE: ``` { "success": true, "msg": "Inbound has been successfully created.", "obj": { "id": 15, "up": 0, "down": 0, "total": 0, "remark": "Test_Inbound_Example", "enable": true, "expiryTime": 0, "clientStats": null, "listen": "", "port": 8443, "protocol": "vless", "settings": "{\"clients\":[{\"id\":\"example-uuid-here\",\"email\":\"test23c5n7\"}],\"decryption\":\"none\"}", "streamSettings": "{\"network\":\"tcp\",\"security\":\"reality\",\"realitySettings\":{\"show\":false,\"dest\":\"google.com:443\",\"xver\":0,\"serverNames\":[\"google.com\"],\"privateKey\":\"example-private-key\",\"shortIds\":[\"\"],\"settings\":{\"publicKey\":\"example-public-key\",\"fingerprint\":\"chrome\"}},\"tcpSettings\":{\"acceptProxyProtocol\":false,\"header\":{\"type\":\"none\"}}}", "tag": "inbound-8443", "sniffing": "{\"enabled\":true,\"destOverride\":[\"http\",\"tls\",\"quic\",\"fakedns\"]}", "allocate": "{\"strategy\":\"always\",\"refresh\":5,\"concurrency\":3}" } } ``` ---------------------------------------- TITLE: Quick Start Example DESCRIPTION: Demonstrates how to initialize the client and fetch all inbounds from a 3x-ui server. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/README.md#_snippet_1 LANGUAGE: javascript CODE: ``` const ThreeXUI = require('3xui-api-client'); const client = new ThreeXUI('https://your-3xui-server.com', 'username', 'password'); // Get all inbounds client.getInbounds() .then(inbounds => { console.log('Inbounds:', inbounds); }) .catch(error => { console.error('Error:', error.message); }); ``` ---------------------------------------- TITLE: Add Inbound Response Example DESCRIPTION: Provides an example of a successful response when adding a new inbound, including the inbound's ID, traffic statistics, configuration details, and protocol-specific settings. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Inbound-Management.md#_snippet_6 LANGUAGE: json CODE: ``` { "success": true, "msg": "Inbound has been successfully created.", "obj": { "id": 15, "up": 0, "down": 0, "total": 0, "remark": "Test_Inbound_Example", "enable": true, "expiryTime": 0, "clientStats": null, "listen": "", "port": 8443, "protocol": "vless", "settings": "{\"clients\":[{\"id\":\"example-uuid-here\",\"email\":\"test23c5n7\"}],\"decryption\":\"none\"}", "streamSettings": "{\"network\":\"tcp\",\"security\":\"reality\",\"realitySettings\":{\"show\":false,\"dest\":\"google.com:443\",\"xver\":0,\"serverNames\":[\"google.com\"],\"privateKey\":\"example-private-key\",\"shortIds\":[\"\"],\"settings\":{\"publicKey\":\"example-public-key\",\"fingerprint\":\"chrome\"}},\"tcpSettings\":{\"acceptProxyProtocol\":false,\"header\":{\"type\":\"none\"}}}", "tag": "inbound-8443", "sniffing": "{\"enabled\":true,\"destOverride\":[\"http\",\"tls\",\"quic\",\"fakedns\"]}", "allocate": "{\"strategy\":\"always\",\"refresh\":5,\"concurrency\":3}" } } ``` ---------------------------------------- TITLE: Basic Authentication DESCRIPTION: Demonstrates basic client setup with automatic session management. The client handles authentication on the first API call without manual login steps. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Authentication-Guide.md#_snippet_0 LANGUAGE: javascript CODE: ``` const ThreeXUI = require('3xui-api-client'); // Simple setup - sessions handled automatically const client = new ThreeXUI( 'https://your-3xui-server.com', 'your-username', 'your-password' ); // No manual login needed - auto-authenticates on first API call const inbounds = await client.getInbounds(); ``` ---------------------------------------- TITLE: Next.js API Route for 3x-ui Operations DESCRIPTION: Provides an example of a Next.js API route handler that interacts with the 3xui client. It demonstrates handling different HTTP methods (GET, POST) to fetch inbounds or add clients, utilizing environment variables for configuration and a database session manager. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Authentication-Guide.md#_snippet_15 LANGUAGE: javascript CODE: ``` // pages/api/3xui/[...path].js import { ThreeXUI } from '3xui-api-client'; const xui = new ThreeXUI( process.env.XUI_URL, process.env.XUI_USERNAME, process.env.XUI_PASSWORD, { sessionManager: { type: 'database', database: prisma // Prisma client } } ); export default async function handler(req, res) { try { switch (req.method) { case 'GET': const inbounds = await xui.getInbounds(); res.json(inbounds); break; case 'POST': const result = await xui.addClientWithCredentials( req.body.inboundId, 'vless' ); res.json(result); break; } } catch (error) { res.status(500).json({ error: error.message }); } } ``` ---------------------------------------- TITLE: Install 3xui-api-client DESCRIPTION: Installs the 3xui-api-client package using npm. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Home.md#_snippet_0 LANGUAGE: bash CODE: ``` npm install 3xui-api-client ``` ---------------------------------------- TITLE: Install 3xui-api-client DESCRIPTION: Installs the 3xui-api-client package using npm. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Home.md#_snippet_0 LANGUAGE: bash CODE: ``` npm install 3xui-api-client ``` ---------------------------------------- TITLE: Basic Authentication DESCRIPTION: Demonstrates basic client setup with automatic session management. The client handles authentication on the first API call without manual login steps. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Authentication-Guide.md#_snippet_0 LANGUAGE: javascript CODE: ``` const ThreeXUI = require('3xui-api-client'); // Simple setup - sessions handled automatically const client = new ThreeXUI( 'https://your-3xui-server.com', 'your-username', 'your-password' ); // No manual login needed - auto-authenticates on first API call const inbounds = await client.getInbounds(); ``` ---------------------------------------- TITLE: Installation DESCRIPTION: Installs the 3xui-api-client package using npm. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/README.md#_snippet_0 LANGUAGE: bash CODE: ``` npm install 3xui-api-client ``` ---------------------------------------- TITLE: Enhanced Security and Session Management Setup DESCRIPTION: Illustrates an enhanced client setup with detailed security options such as rate limiting, login attempt limiting, development mode, Content Security Policy, request timeouts, and various session management configurations (memory, Redis, database). SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Authentication-Guide.md#_snippet_1 LANGUAGE: javascript CODE: ``` const client = new ThreeXUI(url, username, password, { // Security options maxRequestsPerMinute: 60, // Rate limiting maxLoginAttemptsPerHour: 10, // Login attempt limiting isDevelopment: false, // Production mode (sanitized errors) enableCSP: true, // Content Security Policy timeout: 30000, // Request timeout // Session management sessionManager: { type: 'redis', // Storage type: 'memory', 'redis', 'database' redis: redisClient, // Redis client instance defaultTTL: 3600, // Session TTL (1 hour) autoRefresh: true // Auto-refresh at 80% expiry } }); ``` ---------------------------------------- TITLE: Adding New Inbounds - Basic VLESS Example DESCRIPTION: Demonstrates how to add a new inbound with VLESS protocol, TCP network, and REALITY security settings. Includes configuration for destination, server names, private key, and short IDs. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Inbound-Management.md#_snippet_5 LANGUAGE: javascript CODE: ``` const inboundConfig = { remark: "My New VPN Server", port: 8443, protocol: "vless", settings: { clients: [], decryption: "none", fallbacks: [] }, streamSettings: { network: "tcp", security: "reality", realitySettings: { dest: "google.com:443", serverNames: ["google.com"], privateKey: "your-private-key", shortIds: [""] } }, sniffing: { enabled: true, destOverride: ["http", "tls"] } }; try { const result = await client.addInbound(inboundConfig); console.log('Inbound added successfully:', result); } catch (error) { console.error('Failed to add inbound:', error.message); } ``` ---------------------------------------- TITLE: Inbound Response Example DESCRIPTION: An example of the JSON response structure when retrieving inbound configurations. It details the fields returned for each inbound, including its ID, traffic statistics, remark, protocol, and nested JSON strings for settings, stream settings, and sniffing. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Inbound-Management.md#_snippet_2 LANGUAGE: json CODE: ``` { "success": true, "msg": "", "obj": [ { "id": 10, "up": 0, "down": 0, "total": 0, "remark": "Example Inbound", "enable": true, "expiryTime": 0, "clientStats": [ { "id": 20, "inboundId": 10, "enable": true, "email": "example23c5n7", "up": 0, "down": 0, "expiryTime": 0, "total": 0, "reset": 0 } ], "listen": "", "port": 11726, "protocol": "vless", "settings": "{\"clients\":[{\"id\":\"example-uuid-here\",\"email\":\"example23c5n7\"}],\"decryption\":\"none\"}", "streamSettings": "{\"network\":\"tcp\",\"security\":\"reality\",\"realitySettings\":{\"show\":false,\"dest\":\"google.com:443\",\"xver\":0,\"serverNames\":[\"google.com\"],\"privateKey\":\"example-private-key\",\"shortIds\":[\"\"],\"settings\":{\"publicKey\":\"example-public-key\",\"fingerprint\":\"chrome\"}},\"tcpSettings\":{\"acceptProxyProtocol\":false,\"header\":{\"type\":\"none\"}}}", "tag": "inbound-11726", "sniffing": "{\"enabled\":false,\"destOverride\":[\"http\",\"tls\",\"quic\",\"fakedns\"],\"metadataOnly\":false,\"routeOnly\":false}", "allocate": "{\"strategy\":\"always\",\"refresh\":5,\"concurrency\":3}" } ] } ``` ---------------------------------------- TITLE: Enhanced Security and Session Management Setup DESCRIPTION: Illustrates an enhanced client setup with detailed security options such as rate limiting, login attempt limiting, development mode, Content Security Policy, request timeouts, and various session management configurations (memory, Redis, database). SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Authentication-Guide.md#_snippet_1 LANGUAGE: javascript CODE: ``` const client = new ThreeXUI(url, username, password, { // Security options maxRequestsPerMinute: 60, // Rate limiting maxLoginAttemptsPerHour: 10, // Login attempt limiting isDevelopment: false, // Production mode (sanitized errors) enableCSP: true, // Content Security Policy timeout: 30000, // Request timeout // Session management sessionManager: { type: 'redis', // Storage type: 'memory', 'redis', 'database' redis: redisClient, // Redis client instance defaultTTL: 3600, // Session TTL (1 hour) autoRefresh: true // Auto-refresh at 80% expiry } }); ``` ---------------------------------------- TITLE: Next.js API Route for 3x-ui Operations DESCRIPTION: Provides an example of a Next.js API route handler that interacts with the 3xui client. It demonstrates handling different HTTP methods (GET, POST) to fetch inbounds or add clients, utilizing environment variables for configuration and a database session manager. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Authentication-Guide.md#_snippet_15 LANGUAGE: javascript CODE: ``` // pages/api/3xui/[...path].js import { ThreeXUI } from '3xui-api-client'; const xui = new ThreeXUI( process.env.XUI_URL, process.env.XUI_USERNAME, process.env.XUI_PASSWORD, { sessionManager: { type: 'database', database: prisma // Prisma client } } ); export default async function handler(req, res) { try { switch (req.method) { case 'GET': const inbounds = await xui.getInbounds(); res.json(inbounds); break; case 'POST': const result = await xui.addClientWithCredentials( req.body.inboundId, 'vless' ); res.json(result); break; } } catch (error) { res.status(500).json({ error: error.message }); } } ``` ---------------------------------------- TITLE: Inbound Response Example DESCRIPTION: An example of the JSON response structure when retrieving inbound configurations. It details the fields returned for each inbound, including its ID, traffic statistics, remark, protocol, and nested JSON strings for settings, stream settings, and sniffing. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Inbound-Management.md#_snippet_2 LANGUAGE: json CODE: ``` { "success": true, "msg": "", "obj": [ { "id": 10, "up": 0, "down": 0, "total": 0, "remark": "Example Inbound", "enable": true, "expiryTime": 0, "clientStats": [ { "id": 20, "inboundId": 10, "enable": true, "email": "example23c5n7", "up": 0, "down": 0, "expiryTime": 0, "total": 0, "reset": 0 } ], "listen": "", "port": 11726, "protocol": "vless", "settings": "{\"clients\":[{\"id\":\"example-uuid-here\",\"email\":\"example23c5n7\"}],\"decryption\":\"none\"}", "streamSettings": "{\"network\":\"tcp\",\"security\":\"reality\",\"realitySettings\":{\"show\":false,\"dest\":\"google.com:443\",\"xver\":0,\"serverNames\":[\"google.com\"],\"privateKey\":\"example-private-key\",\"shortIds\":[\"\"],\"settings\":{\"publicKey\":\"example-public-key\",\"fingerprint\":\"chrome\"}},\"tcpSettings\":{\"acceptProxyProtocol\":false,\"header\":{\"type\":\"none\"}}}", "tag": "inbound-11726", "sniffing": "{\"enabled\":false,\"destOverride\":[\"http\",\"tls\",\"quic\",\"fakedns\"],\"metadataOnly\":false,\"routeOnly\":false}", "allocate": "{\"strategy\":\"always\",\"refresh\":5,\"concurrency\":3}" } ] } ``` ---------------------------------------- TITLE: Adding New Inbounds - Basic VLESS Example DESCRIPTION: Demonstrates how to add a new inbound with VLESS protocol, TCP network, and REALITY security settings. Includes configuration for destination, server names, private key, and short IDs. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Inbound-Management.md#_snippet_5 LANGUAGE: javascript CODE: ``` const inboundConfig = { remark: "My New VPN Server", port: 8443, protocol: "vless", settings: { clients: [], decryption: "none", fallbacks: [] }, streamSettings: { network: "tcp", security: "reality", realitySettings: { dest: "google.com:443", serverNames: ["google.com"], privateKey: "your-private-key", shortIds: [""] } }, sniffing: { enabled: true, destOverride: ["http", "tls"] } }; try { const result = await client.addInbound(inboundConfig); console.log('Inbound added successfully:', result); } catch (error) { console.error('Failed to add inbound:', error.message); } ``` ---------------------------------------- TITLE: Update Inbound Response Example DESCRIPTION: Provides an example of the JSON response received after successfully updating an inbound configuration. It details the structure of the response, including success status, messages, and the updated inbound object. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Inbound-Management.md#_snippet_9 LANGUAGE: javascript CODE: ``` { "success": true, "msg": "Inbound has been successfully updated.", "obj": { "id": 15, "up": 0, "down": 0, "total": 0, "remark": "Updated_Test_Inbound_Example", "enable": true, "expiryTime": 0, "clientStats": null, "listen": "", "port": 8443, "protocol": "vless", "settings": "{\"clients\":[{\"id\":\"example-uuid-here\",\"email\":\"test23c5n7\"}],\"decryption\":\"none\"}", "streamSettings": "{\"network\":\"tcp\",\"security\":\"reality\",\"realitySettings\":{\"show\":false,\"dest\":\"google.com:443\",\"xver\":0,\"serverNames\":[\"google.com\"],\"privateKey\":\"example-private-key\",\"shortIds\":[\"\"],\"settings\":{\"publicKey\":\"example-public-key\",\"fingerprint\":\"chrome\"}},\"tcpSettings\":{\"acceptProxyProtocol\":false,\"header\":{\"type\":\"none\"}}}", "tag": "inbound-8443", "sniffing": "{\"enabled\":true,\"destOverride\":[\"http\",\"tls\",\"quic\",\"fakedns\"]}", "allocate": "{\"strategy\":\"always\",\"refresh\":5,\"concurrency\":3}" } } ``` ---------------------------------------- TITLE: Update Inbound Response Example DESCRIPTION: Provides an example of the JSON response received after successfully updating an inbound configuration. It details the structure of the response, including success status, messages, and the updated inbound object. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Inbound-Management.md#_snippet_9 LANGUAGE: javascript CODE: ``` { "success": true, "msg": "Inbound has been successfully updated.", "obj": { "id": 15, "up": 0, "down": 0, "total": 0, "remark": "Updated_Test_Inbound_Example", "enable": true, "expiryTime": 0, "clientStats": null, "listen": "", "port": 8443, "protocol": "vless", "settings": "{\"clients\":[{\"id\":\"example-uuid-here\",\"email\":\"test23c5n7\"}],\"decryption\":\"none\"}", "streamSettings": "{\"network\":\"tcp\",\"security\":\"reality\",\"realitySettings\":{\"show\":false,\"dest\":\"google.com:443\",\"xver\":0,\"serverNames\":[\"google.com\"],\"privateKey\":\"example-private-key\",\"shortIds\":[\"\"],\"settings\":{\"publicKey\":\"example-public-key\",\"fingerprint\":\"chrome\"}},\"tcpSettings\":{\"acceptProxyProtocol\":false,\"header\":{\"type\":\"none\"}}}", "tag": "inbound-8443", "sniffing": "{\"enabled\":true,\"destOverride\":[\"http\",\"tls\",\"quic\",\"fakedns\"]}", "allocate": "{\"strategy\":\"always\",\"refresh\":5,\"concurrency\":3}" } } ``` ---------------------------------------- TITLE: Adding New Inbounds - Trojan Example DESCRIPTION: Provides an example of adding a new inbound using the Trojan protocol. It configures the server with TLS security, specifying the server name and certificate paths. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Inbound-Management.md#_snippet_7 LANGUAGE: javascript CODE: ``` const trojanConfig = { remark: "Trojan Server", port: 443, protocol: "trojan", settings: { clients: [], fallbacks: [] }, streamSettings: { network: "tcp", security: "tls", tlsSettings: { serverName: "your-domain.com", certificates: [ { certificateFile: "/path/to/cert.pem", keyFile: "/path/to/key.pem" } ] } } }; try { const result = await client.addInbound(trojanConfig); console.log('Trojan inbound added:', result); } catch (error) { console.error('Failed to add trojan inbound:', error.message); } ``` ---------------------------------------- TITLE: Adding New Inbounds - Trojan Example DESCRIPTION: Provides an example of adding a new inbound using the Trojan protocol. It configures the server with TLS security, specifying the server name and certificate paths. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Inbound-Management.md#_snippet_7 LANGUAGE: javascript CODE: ``` const trojanConfig = { remark: "Trojan Server", port: 443, protocol: "trojan", settings: { clients: [], fallbacks: [] }, streamSettings: { network: "tcp", security: "tls", tlsSettings: { serverName: "your-domain.com", certificates: [ { certificateFile: "/path/to/cert.pem", keyFile: "/path/to/key.pem" } ] } } }; try { const result = await client.addInbound(trojanConfig); console.log('Trojan inbound added:', result); } catch (error) { console.error('Failed to add trojan inbound:', error.message); } ``` ---------------------------------------- TITLE: Enterprise Server Setup DESCRIPTION: Demonstrates setting up optimal servers for enterprise configurations, including handling different protocols and security settings. It iterates through a list of enterprise server configurations and attempts to set up each one, logging success or failure. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Use-Cases.md#_snippet_20 LANGUAGE: javascript CODE: ``` const enterpriseConfigs = [ { protocol: 'vless', port: 443, remark: 'Enterprise-VLESS-Primary', security: 'reality' }, { protocol: 'trojan', port: 8443, remark: 'Enterprise-Trojan-Secondary', security: 'tls' } ]; for (const config of enterpriseConfigs) { try { await this.setupOptimalServer(config); console.log(`✅ Enterprise server setup: ${config.remark}`); } catch (error) { console.error(`❌ Failed to setup ${config.remark}:`, error); } } ``` ---------------------------------------- TITLE: Enterprise Server Setup DESCRIPTION: Demonstrates setting up optimal servers for enterprise configurations, including handling different protocols and security settings. It iterates through a list of enterprise server configurations and attempts to set up each one, logging success or failure. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Use-Cases.md#_snippet_20 LANGUAGE: javascript CODE: ``` const enterpriseConfigs = [ { protocol: 'vless', port: 443, remark: 'Enterprise-VLESS-Primary', security: 'reality' }, { protocol: 'trojan', port: 8443, remark: 'Enterprise-Trojan-Secondary', security: 'tls' } ]; for (const config of enterpriseConfigs) { try { await this.setupOptimalServer(config); console.log(`✅ Enterprise server setup: ${config.remark}`); } catch (error) { console.error(`❌ Failed to setup ${config.remark}:`, error); } } ``` ---------------------------------------- TITLE: Testing Commands DESCRIPTION: Provides examples of npm commands used for running tests, including specific tests like login tests and running all available tests. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/README.md#_snippet_16 LANGUAGE: bash CODE: ``` # Run login test npm run test:login # Run all tests npm test ``` ---------------------------------------- TITLE: Production Security Setup DESCRIPTION: Configures the 3xui client for a production environment with strict security settings. This includes rate limiting, disabling development mode, enabling Content Security Policy (CSP), and configuring enterprise-grade database session management with encryption and cleanup. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Authentication-Guide.md#_snippet_12 LANGUAGE: javascript CODE: ``` const client = new ThreeXUI(url, username, password, { // Strict security settings maxRequestsPerMinute: 30, maxLoginAttemptsPerHour: 5, isDevelopment: false, enableCSP: true, timeout: 15000, // Enterprise session management sessionManager: { type: 'database', database: dbConnection, databaseOptions: { tableName: 'xui_sessions', defaultTTL: 3600, encryptSessions: true, // Encrypt session data cleanupInterval: 300 // Cleanup expired sessions every 5 min } } }); ``` ---------------------------------------- TITLE: Troubleshoot Authentication Issues DESCRIPTION: Provides a code example for diagnosing authentication problems with the client. It includes attempting a manual login and checking security statistics for potential IP blocks or rate limiting issues. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Authentication-Guide.md#_snippet_18 LANGUAGE: javascript CODE: ``` // Check if authentication is the problem try { await client.login(); console.log('✅ Manual login successful'); } catch (error) { console.error('❌ Authentication failed:', error.message); // Check security stats for rate limiting const stats = await client.getSecurityStats(); if (stats.blockedIPs > 0) { console.warn('IP may be blocked due to security violations'); // Clear blocks if necessary: await client.clearBlockedIPs(); } } ``` ---------------------------------------- TITLE: Troubleshoot Authentication Issues DESCRIPTION: Provides a code example for diagnosing authentication problems with the client. It includes attempting a manual login and checking security statistics for potential IP blocks or rate limiting issues. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Authentication-Guide.md#_snippet_18 LANGUAGE: javascript CODE: ``` // Check if authentication is the problem try { await client.login(); console.log('✅ Manual login successful'); } catch (error) { console.error('❌ Authentication failed:', error.message); // Check security stats for rate limiting const stats = await client.getSecurityStats(); if (stats.blockedIPs > 0) { console.warn('IP may be blocked due to security violations'); // Clear blocks if necessary: await client.clearBlockedIPs(); } } ``` ---------------------------------------- TITLE: Production Security Setup DESCRIPTION: Configures the 3xui client for a production environment with strict security settings. This includes rate limiting, disabling development mode, enabling Content Security Policy (CSP), and configuring enterprise-grade database session management with encryption and cleanup. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Authentication-Guide.md#_snippet_12 LANGUAGE: javascript CODE: ``` const client = new ThreeXUI(url, username, password, { // Strict security settings maxRequestsPerMinute: 30, maxLoginAttemptsPerHour: 5, isDevelopment: false, enableCSP: true, timeout: 15000, // Enterprise session management sessionManager: { type: 'database', database: dbConnection, databaseOptions: { tableName: 'xui_sessions', defaultTTL: 3600, encryptSessions: true, // Encrypt session data cleanupInterval: 300 // Cleanup expired sessions every 5 min } } }); ``` ---------------------------------------- TITLE: Secure 3xui-api-client Implementation DESCRIPTION: Demonstrates a secure way to initialize the 3xui-api-client using environment variables and configuring advanced security options like rate limiting, login attempt limits, and Content Security Policy. It also shows a class for managing authenticated sessions and adding clients securely. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Authentication-Guide.md#_snippet_4 LANGUAGE: javascript CODE: ``` const ThreeXUI = require('3xui-api-client'); // ✅ Good: Use environment variables with security options const client = new ThreeXUI( process.env.XUI_URL, process.env.XUI_USERNAME, process.env.XUI_PASSWORD, { // Security configuration maxRequestsPerMinute: 30, // Stricter rate limiting maxLoginAttemptsPerHour: 5, // Stricter login attempts isDevelopment: false, // Production mode (sanitized errors) enableCSP: true, // Enable Content Security Policy timeout: 15000, // 15 second timeout // Session management sessionManager: { type: 'redis', // Use Redis for session storage redis: redisClient, keyPrefix: 'xui:session:', defaultTTL: 3600 } } ); // ✅ Good: Store sessions securely with monitoring class SecureXUIManager { constructor(database) { this.client = client; this.db = database; } async ensureAuthenticated() { // Check security statistics const securityStats = this.client.getSecurityStats(); if (securityStats.blockedIPs > 0) { console.warn('Security Alert: Blocked IPs detected', securityStats); } const session = await this.db.getValidSession(); if (!session) { await this.client.login(); await this.db.storeSession(this.client.cookie); } } async addSecureClient(inboundId, protocol) { // Use built-in credential generation with validation const credentials = this.client.generateCredentials(protocol); const validation = this.client.validateCredentialStrength( credentials.password || credentials.uuid, protocol === 'trojan' ? 'password' : 'uuid' ); if (!validation.isValid) { throw new Error(`Weak credentials: ${validation.issues.join(', ')}`); } return await this.client.addClientWithCredentials(inboundId, protocol, { credentials, enableSecurity: true }); } } ``` ---------------------------------------- TITLE: Secure 3xui-api-client Implementation DESCRIPTION: Demonstrates a secure way to initialize the 3xui-api-client using environment variables and configuring advanced security options like rate limiting, login attempt limits, and Content Security Policy. It also shows a class for managing authenticated sessions and adding clients securely. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Authentication-Guide.md#_snippet_4 LANGUAGE: javascript CODE: ``` const ThreeXUI = require('3xui-api-client'); // ✅ Good: Use environment variables with security options const client = new ThreeXUI( process.env.XUI_URL, process.env.XUI_USERNAME, process.env.XUI_PASSWORD, { // Security configuration maxRequestsPerMinute: 30, // Stricter rate limiting maxLoginAttemptsPerHour: 5, // Stricter login attempts isDevelopment: false, // Production mode (sanitized errors) enableCSP: true, // Enable Content Security Policy timeout: 15000, // 15 second timeout // Session management sessionManager: { type: 'redis', // Use Redis for session storage redis: redisClient, keyPrefix: 'xui:session:', defaultTTL: 3600 } } ); // ✅ Good: Store sessions securely with monitoring class SecureXUIManager { constructor(database) { this.client = client; this.db = database; } async ensureAuthenticated() { // Check security statistics const securityStats = this.client.getSecurityStats(); if (securityStats.blockedIPs > 0) { console.warn('Security Alert: Blocked IPs detected', securityStats); } const session = await this.db.getValidSession(); if (!session) { await this.client.login(); await this.db.storeSession(this.client.cookie); } } async addSecureClient(inboundId, protocol) { // Use built-in credential generation with validation const credentials = this.client.generateCredentials(protocol); const validation = this.client.validateCredentialStrength( credentials.password || credentials.uuid, protocol === 'trojan' ? 'password' : 'uuid' ); if (!validation.isValid) { throw new Error(`Weak credentials: ${validation.issues.join(', ')}`); } return await this.client.addClientWithCredentials(inboundId, protocol, { credentials, enableSecurity: true }); } } ``` ---------------------------------------- TITLE: Client Traffic Management API Responses DESCRIPTION: API response examples for resetting client traffic and deleting depleted clients. These examples show the structure of successful responses, including the 'success' flag, a message, and an optional 'obj' field. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Traffic-Management.md#_snippet_4 LANGUAGE: APIDOC CODE: ``` Reset All Client Traffics API Response: { "success": true, "msg": "All traffic from the client has been reset.", "obj": null } Delete Depleted Clients API Response: { "success": true, "msg": "All depleted clients are deleted.", "obj": null } ``` ---------------------------------------- TITLE: Get All Inbounds DESCRIPTION: Retrieves a list of all configured inbounds from the 3xUI server. It demonstrates how to initialize the client, make the API call, handle the response, and parse detailed inbound configurations including protocol-specific settings, stream settings, and sniffing configurations. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Inbound-Management.md#_snippet_1 LANGUAGE: javascript CODE: ``` const ThreeXUI = require('3xui-api-client'); const client = new ThreeXUI('https://your-server.com', 'username', 'password'); try { const response = await client.getInbounds(); console.log('Inbounds response:', response); if (response.success) { const inbounds = response.obj; console.log(`Found ${inbounds.length} inbounds`); inbounds.forEach(inbound => { console.log(`Inbound ${inbound.id}:`); console.log(` Port: ${inbound.port}`); console.log(` Protocol: ${inbound.protocol}`); console.log(` Enabled: ${inbound.enable}`); console.log(` Clients: ${inbound.clientStats.length}`); console.log(` Traffic: ↑${inbound.up} ↓${inbound.down} bytes`); // Parse JSON strings for detailed configuration const settings = JSON.parse(inbound.settings); const streamSettings = JSON.parse(inbound.streamSettings); const sniffing = JSON.parse(inbound.sniffing); console.log(` Security: ${streamSettings.security}`); console.log(` Network: ${streamSettings.network}`); }); } else { console.error('Failed to get inbounds:', response.msg); } } catch (error) { console.error('Failed to get inbounds:', error.message); } ``` ---------------------------------------- TITLE: Get All Inbounds DESCRIPTION: Retrieves a list of all configured inbounds from the 3xUI server. It demonstrates how to initialize the client, make the API call, handle the response, and parse detailed inbound configurations including protocol-specific settings, stream settings, and sniffing configurations. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Inbound-Management.md#_snippet_1 LANGUAGE: javascript CODE: ``` const ThreeXUI = require('3xui-api-client'); const client = new ThreeXUI('https://your-server.com', 'username', 'password'); try { const response = await client.getInbounds(); console.log('Inbounds response:', response); if (response.success) { const inbounds = response.obj; console.log(`Found ${inbounds.length} inbounds`); inbounds.forEach(inbound => { console.log(`Inbound ${inbound.id}:`); console.log(` Port: ${inbound.port}`); console.log(` Protocol: ${inbound.protocol}`); console.log(` Enabled: ${inbound.enable}`); console.log(` Clients: ${inbound.clientStats.length}`); console.log(` Traffic: ↑${inbound.up} ↓${inbound.down} bytes`); // Parse JSON strings for detailed configuration const settings = JSON.parse(inbound.settings); const streamSettings = JSON.parse(inbound.streamSettings); const sniffing = JSON.parse(inbound.sniffing); console.log(` Security: ${streamSettings.security}`); console.log(` Network: ${streamSettings.network}`); }); } else { console.error('Failed to get inbounds:', response.msg); } } catch (error) { console.error('Failed to get inbounds:', error.message); } ``` ---------------------------------------- TITLE: Enterprise Security Setup Class DESCRIPTION: Defines a class for configuring and managing enterprise-level security settings. It initializes the 3XUI client with maximum security configurations and provides methods for setting up the environment, auditing credentials, monitoring security, and managing backups and servers. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Use-Cases.md#_snippet_19 LANGUAGE: javascript CODE: ``` class EnterpriseSecuritySetup { constructor() { this.client = new ThreeXUI( process.env.XUI_URL, process.env.XUI_USERNAME, process.env.XUI_PASSWORD, { // Maximum security configuration maxRequestsPerMinute: 10, maxLoginAttemptsPerHour: 3, isDevelopment: false, enableCSP: true, timeout: 10000, // Encrypted database session storage sessionManager: { type: 'database', database: secureDbConnection, databaseOptions: { tableName: 'secure_sessions', encryptSessions: true, defaultTTL: 900, // 15 minutes cleanupInterval: 60 } } } ); } async setupEnterpriseEnvironment() { console.log('🔒 Setting up enterprise security environment...'); // 1. Validate all existing credentials const credentialAudit = await this.auditAllCredentials(); console.log(`Credential audit: ${credentialAudit.strongCredentials}/${credentialAudit.totalCredentials} strong`); // 2. Set up monitoring and alerting await this.setupSecurityMonitoring(); // 3. Configure automated backups await this.setupAutomatedBackups(); // 4. Create enterprise-grade servers await this.setupEnterpriseServers(); console.log('✅ Enterprise security setup completed'); } async auditAllCredentials() { const inbounds = await this.client.getInbounds(); const results = { totalCredentials: 0, strongCredentials: 0, weakCredentials: 0, issues: [] }; for (const inbound of inbounds.obj) { if (inbound.settings) { const settings = JSON.parse(inbound.settings); if (settings.clients) { for (const client of settings.clients) { results.totalCredentials++; let validation; if (inbound.protocol === 'vless' || inbound.protocol === 'vmess') { validation = this.client.validateCredentialStrength(client.id, 'uuid'); } else if (inbound.protocol === 'trojan') { validation = this.client.validateCredentialStrength(client.password, 'password'); } if (validation) { if (validation.strength === 'strong') { results.strongCredentials++; } else { results.weakCredentials++; results.issues.push({ inbound: inbound.id, client: client.email, strength: validation.strength, issues: validation.issues }); } } } } } } return results; } async setupSecurityMonitoring() { // Set up automated security monitoring setInterval(async () => { const stats = await this.client.getSecurityStats(); // Alert on high-severity events const highSeverityEvents = stats.recentActivities.filter( activity => activity.severity === 'high' ); if (highSeverityEvents.length > 0) { await this.sendSecurityAlert(highSeverityEvents); } // Log security metrics await this.logSecurityMetrics(stats); }, 60000); // Check every minute } async setupAutomatedBackups() { // Daily automated backups const scheduleBackup = () => { setInterval(async () => { try { const backupResult = await this.client.createBackup(); if (backupResult.success) { console.log('✅ Automated backup completed'); } } catch (error) { console.error('❌ Automated backup failed:', error); } }, 24 * 60 * 60 * 1000); // Daily }; scheduleBackup(); } async setupEnterpriseServers() { const enterpriseConfigs = [ { protocol: 'vless', ``` ---------------------------------------- TITLE: Secure Error Handling Configuration DESCRIPTION: Demonstrates how to switch between production (sanitized errors) and development (detailed errors) modes for error handling. Includes a try-catch block to show how errors are handled. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Authentication-Guide.md#_snippet_3 LANGUAGE: javascript CODE: ``` // Production mode (default) - sanitized errors client.setDevelopmentMode(false); // Development mode - detailed errors client.setDevelopmentMode(true); try { await client.login(); } catch (error) { // Error messages are sanitized in production mode console.error('Login error:', error.message); } ``` ---------------------------------------- TITLE: Enterprise Security Setup Class DESCRIPTION: Defines a class for configuring and managing enterprise-level security settings. It initializes the 3XUI client with maximum security configurations and provides methods for setting up the environment, auditing credentials, monitoring security, and managing backups and servers. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Use-Cases.md#_snippet_19 LANGUAGE: javascript CODE: ``` class EnterpriseSecuritySetup { constructor() { this.client = new ThreeXUI( process.env.XUI_URL, process.env.XUI_USERNAME, process.env.XUI_PASSWORD, { // Maximum security configuration maxRequestsPerMinute: 10, maxLoginAttemptsPerHour: 3, isDevelopment: false, enableCSP: true, timeout: 10000, // Encrypted database session storage sessionManager: { type: 'database', database: secureDbConnection, databaseOptions: { tableName: 'secure_sessions', encryptSessions: true, defaultTTL: 900, // 15 minutes cleanupInterval: 60 } } } ); } async setupEnterpriseEnvironment() { console.log('🔒 Setting up enterprise security environment...'); // 1. Validate all existing credentials const credentialAudit = await this.auditAllCredentials(); console.log(`Credential audit: ${credentialAudit.strongCredentials}/${credentialAudit.totalCredentials} strong`); // 2. Set up monitoring and alerting await this.setupSecurityMonitoring(); // 3. Configure automated backups await this.setupAutomatedBackups(); // 4. Create enterprise-grade servers await this.setupEnterpriseServers(); console.log('✅ Enterprise security setup completed'); } async auditAllCredentials() { const inbounds = await this.client.getInbounds(); const results = { totalCredentials: 0, strongCredentials: 0, weakCredentials: 0, issues: [] }; for (const inbound of inbounds.obj) { if (inbound.settings) { const settings = JSON.parse(inbound.settings); if (settings.clients) { for (const client of settings.clients) { results.totalCredentials++; let validation; if (inbound.protocol === 'vless' || inbound.protocol === 'vmess') { validation = this.client.validateCredentialStrength(client.id, 'uuid'); } else if (inbound.protocol === 'trojan') { validation = this.client.validateCredentialStrength(client.password, 'password'); } if (validation) { if (validation.strength === 'strong') { results.strongCredentials++; } else { results.weakCredentials++; results.issues.push({ inbound: inbound.id, client: client.email, strength: validation.strength, issues: validation.issues }); } } } } } } return results; } async setupSecurityMonitoring() { // Set up automated security monitoring setInterval(async () => { const stats = await this.client.getSecurityStats(); // Alert on high-severity events const highSeverityEvents = stats.recentActivities.filter( activity => activity.severity === 'high' ); if (highSeverityEvents.length > 0) { await this.sendSecurityAlert(highSeverityEvents); } // Log security metrics await this.logSecurityMetrics(stats); }, 60000); // Check every minute } async setupAutomatedBackups() { // Daily automated backups const scheduleBackup = () => { setInterval(async () => { try { const backupResult = await this.client.createBackup(); if (backupResult.success) { console.log('✅ Automated backup completed'); } } catch (error) { console.error('❌ Automated backup failed:', error); } }, 24 * 60 * 60 * 1000); // Daily }; scheduleBackup(); } async setupEnterpriseServers() { const enterpriseConfigs = [ { protocol: 'vless', ``` ---------------------------------------- TITLE: Secure Error Handling Configuration DESCRIPTION: Demonstrates how to switch between production (sanitized errors) and development (detailed errors) modes for error handling. Includes a try-catch block to show how errors are handled. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/wiki/Authentication-Guide.md#_snippet_3 LANGUAGE: javascript CODE: ``` // Production mode (default) - sanitized errors client.setDevelopmentMode(false); // Development mode - detailed errors client.setDevelopmentMode(true); try { await client.login(); } catch (error) { // Error messages are sanitized in production mode console.error('Login error:', error.message); } ``` ---------------------------------------- TITLE: Session Cookie Details DESCRIPTION: Provides an example of the `Set-Cookie` HTTP header for managing user sessions. It details the cookie's name, path, expiration, maximum age, and security attributes like `HttpOnly`. SOURCE: https://github.com/iamhelitha/3xui-api-client/blob/main/__wiki__/Authentication-Guide.md#_snippet_10 LANGUAGE: http CODE: ``` Set-Cookie: 3x-ui=MTczNTUyMzMyN3xEWDhFQVFMX2dBQUJFQUVRQUFCMV80QUFBUVp6ZEhKcGJtY01EQUFJVEU5SFNVNWZWVk5GVWhoNExYVnBMMlJoZEdGaVlYTmxMMjF2WkdWc0xsVnpaWExfZ1FNQkFRUlZjMlZ5QWYtQ0FBRUVBUUpKWkFFRUFBRUlWWE5sY201aGJXVUJEQUFCQ0ZCaGMzTjNiM0prQVF3QUFRdE1iMmRwYmxObFkzSmxkQUVNQUFBQUZQLUNFUUVDQVFWaFpHMXBiZ0VGWVdSdGFXNEF8y6Y2EKU4tk9ljoHdsA7Hb8TqYbZZclkP6EfZlCy1-bs=; Path=/; Expires=Mon, 30 Dec 2024 02:48:47 GMT; Max-Age=3600; HttpOnly ```