### Production Environment .env File Example Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Example of a .env file for production deployment, including essential configuration variables. ```bash # .env.production AdminUsername=admin AdminPassword= CookieSecretKey= SessionTimeoutMinutes=30 SUBSCRIPTION_URL_TEMPLATE=https://your-airport.com/sub/{userId} ASPNETCORE_ENVIRONMENT=Production LOG_LEVEL=Information ``` -------------------------------- ### Docker Run Command for ClashSubManager Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/environment-variables-CN.md Example of a direct docker run command to start ClashSubManager, specifying ports, environment variables, and volume mounts. ```bash docker run -d \ --name clash-sub-manager \ -p 80:80 \ -e ADMIN_USERNAME=admin \ -e ADMIN_PASSWORD=SecurePassword123! \ -e COOKIE_SECRET_KEY=your-very-long-and-secure-secret-key-for-hmac-signing \ -e SESSION_TIMEOUT_MINUTES=30 \ -e DATA_PATH=/app/data \ -e SUBSCRIPTION_URL_TEMPLATE=https://api.example.com/sub/{userId} \ -v $(pwd)/data:/app/data \ -v $(pwd)/logs:/app/logs \ --restart always \ clash-sub-manager:latest ``` -------------------------------- ### Example DATA_PATH Environment Variable Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/environment-variables.md Illustrates how to set the DATA_PATH environment variable to specify a custom data storage directory. This is a system-level configuration example. ```bash DATA_PATH=/custom/data/path ``` -------------------------------- ### Optimize Mock Setup Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/test/unit-test-development-plan.md Provides a unified pattern for configuring mock localizers, simplifying setup in tests. ```csharp // Unified Mock configuration pattern private static Mock> CreateMockLocalizer() { var mock = new Mock>(); mock.Setup(l => l[It.IsAny()]).Returns(new LocalizedString("key", "value", false)); return mock; } ``` -------------------------------- ### Basic Clash Template Example Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/FAQ.md A simple example of a Clash configuration template, demonstrating proxy group and rule configurations. ```yaml # /app/data/clash.yaml # Proxy group configuration proxy-groups: - name: "Auto" type: url-test url: 'http://www.gstatic.com/generate_204' interval: 300 # Rule configuration rules: - DOMAIN-SUFFIX,cn,DIRECT - GEOIP,CN,DIRECT - MATCH,Auto ``` -------------------------------- ### Configuration File Setup Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/node-naming-template-design.md Demonstrates how to set the node naming template and custom variables within a JSON configuration file. This allows for persistent and organized configuration. ```json { "NodeNamingTemplate": "自定义名称-节点-{index}", "NodeNamingVariables": { "CustomPrefix": "MyProxy", "Location": "HK" } } ``` -------------------------------- ### User-Specific Optimized IP File Structure Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/FAQ.md Example file structure demonstrating how to organize global and user-specific optimized IP configuration files. ```text /app/data/ ├── cloudflare-ip.csv # Global optimized IPs ├── user123/ │ └── cloudflare-ip.csv # user123 specific └── user456/ └── cloudflare-ip.csv # user456 specific ``` -------------------------------- ### Troubleshoot Container Startup Failures Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Commands to check container logs, inspect configuration, and restart the container when it fails to start. ```bash # Check logs docker logs clashsubmanager # Check configuration docker inspect clashsubmanager # Restart docker restart clashsubmanager ``` -------------------------------- ### Basic Template Examples Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/node-naming-template-design.md Provides examples of simple node naming templates. These templates use basic variables like index, server, and name to construct node identifiers. ```json # Simple naming "自定义名称-{index}" "Node-{index}-{server}" "{name}-CF-{index}" # Protocol-specific "VLESS-{index}-{server}" "VMess-{name}-{port}" # Location-based "HK-{index}-VLESS" "US-{name}-Node" ``` -------------------------------- ### Test Fixture Setup and Cleanup Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/test/mvp-unit-test.md Initializes a temporary directory for test data and sets environment variables. Cleans up the temporary directory upon disposal. ```csharp public class TestFixture : IDisposable { public string TestDataPath { get; private set; } public TestFixture() { // Create unique temporary test directory TestDataPath = Path.Combine(Path.GetTempPath(), "ClashSubManagerTests", Guid.NewGuid().ToString()); Directory.CreateDirectory(TestDataPath); // Set test environment variables Environment.SetEnvironmentVariable("DataPath", TestDataPath); Environment.SetEnvironmentVariable("AdminUsername", "test_admin"); Environment.SetEnvironmentVariable("AdminPassword", "test_password"); Environment.SetEnvironmentVariable("CookieSecretKey", "test-key-32-chars-long-for-hmac"); Environment.SetEnvironmentVariable("SessionTimeoutMinutes", "30"); } public void Dispose() { // Clean up test directory if (Directory.Exists(TestDataPath)) { Directory.Delete(TestDataPath, true); } } } ``` -------------------------------- ### Example Clash Subscription URL Source: https://github.com/soren-work/clash-sub-manager/blob/main/README.md This is an example of how to format the subscription URL for your Clash client. Replace 'your-server' and 'your_user_id' with your actual server address and user identifier. ```text http://your-server:8080/sub/your_user_id ``` -------------------------------- ### Localhost Example Clash Subscription URL Source: https://github.com/soren-work/clash-sub-manager/blob/main/README.md A specific example of a Clash subscription URL using localhost, useful for local testing and development. ```text http://localhost:8080/sub/user123 ``` -------------------------------- ### Configure ClashSubManager with Command Line Arguments Source: https://github.com/soren-work/clash-sub-manager/blob/main/README.md This example shows how to launch ClashSubManager using command-line arguments to specify configuration settings. This method offers the highest priority in the configuration system. ```bash ./ClashSubManager \ --AdminUsername admin \ --AdminPassword your_password \ --DataPath /custom/data/path ``` -------------------------------- ### Docker Compose Commands for Quick Test Deployment Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Commands to set up directories, start the service in detached mode, and view logs for a Docker Compose deployment. ```bash # Create data directories mkdir -p data logs # Start service docker-compose up -d # View logs docker-compose logs -f clashsubmanager # Access service # Open in browser: http://localhost:8080 ``` -------------------------------- ### Global and User-Specific Configuration Strategy 1 Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/advanced-guide.md Example of merging global configurations with user-specific fine-tuning, suitable when most users share common settings but a few require exceptions. ```yaml # Global /app/data/clash.yaml rules: - DOMAIN-SUFFIX,cn,DIRECT - GEOIP,CN,DIRECT - MATCH,Proxy # User user123 specific config rules: - DOMAIN-SUFFIX,company.com,DIRECT # Add company domain direct connection ``` -------------------------------- ### Configuration Expansion Example Source: https://github.com/soren-work/clash-sub-manager/blob/main/README.md Demonstrates how a domain node is expanded into multiple preferred IP address nodes based on a provided IP list. This allows Clash to select the node with the lowest latency. ```yaml proxies: - name: "US-Node" type: vmess server: cdn.example.com port: 443 ``` ```csv IP Address,Average Latency 104.29.125.182,152.45ms 104.26.0.188,158.10ms 104.20.20.191,161.38ms ``` ```yaml proxies: - name: "US-Node" type: vmess server: cdn.example.com port: 443 - name: "US-Node [104.29.125.182]" type: vmess server: 104.29.125.182 port: 443 - name: "US-Node [104.26.0.188]" type: vmess server: 104.26.0.188 port: 443 - name: "US-Node [104.20.20.191]" type: vmess server: 104.20.20.191 port: 443 ``` -------------------------------- ### Multi-level Configuration Examples Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/node-naming-template-design.md Demonstrates how to access nested properties for node naming templates. These variables can be used to construct dynamic node names based on proxy and node-specific attributes. ```bash # Access nested properties {proxy.name} # Original proxy name {proxy.type} # Service type {proxy.network} # Network type {node.index} # Node index {proxy.server} # Server address ``` -------------------------------- ### Troubleshoot Password Errors Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/env-config.md Guides on regenerating a password, updating environment variables by stopping and running a new container instance, and cleaning up the old container. ```bash # Regenerate password NEW_PASSWORD=$(openssl rand -base64 16 | tr -d "=+/" | cut -c1-16) # Update environment variables docker stop clashsubmanager docker run -d --name clashsubmanager-new \ -e AdminUsername=admin \ -e AdminPassword=$NEW_PASSWORD \ -e CookieSecretKey=$CookieSecretKey \ -e SessionTimeoutMinutes=30 \ -e SUBSCRIPTION_URL_TEMPLATE=$SUBSCRIPTION_URL_TEMPLATE \ clashsubmanager:latest # Clean up old container docker rm clashsubmanager docker rename clashsubmanager-new clashsubmanager ``` -------------------------------- ### Advanced Clash Template Example Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/FAQ.md An advanced Clash configuration template including DNS settings, multiple proxy groups, and more specific rules. ```yaml # DNS configuration dns: enable: true nameserver: - 223.5.5.5 - 119.29.29.29 fallback: - 8.8.8.8 - 1.1.1.1 # Proxy groups proxy-groups: - name: "Proxy" type: select proxies: - Auto - DIRECT - name: "Auto" type: url-test url: 'http://www.gstatic.com/generate_204' interval: 300 # Rules rules: - DOMAIN-SUFFIX,openai.com,Proxy - DOMAIN-SUFFIX,github.com,Proxy - GEOIP,CN,DIRECT - MATCH,Proxy ``` -------------------------------- ### Docker Compose Configuration for ClashSubManager Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/environment-variables-CN.md Example of a docker-compose.yml file to deploy ClashSubManager with essential environment variables and volume mounts for data persistence. ```yaml version: '3.8' services: clash-sub-manager: build: . ports: - "80:80" environment: - ADMIN_USERNAME=admin - ADMIN_PASSWORD=your_secure_password_here - COOKIE_SECRET_KEY=your_hmac_key_at_least_32_chars_long - SESSION_TIMEOUT_MINUTES=30 - DATA_PATH=/app/data - SUBSCRIPTION_URL_TEMPLATE=https://api.example.com/sub/{userId} volumes: - ./data:/app/data - ./logs:/app/logs restart: always healthcheck: test: ["CMD", "curl", "-f", "http://localhost:80/health"] interval: 30s timeout: 10s retries: 3 start_period: 40s ``` -------------------------------- ### Configure Log Rotation Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Set up log rotation for application logs using logrotate. This example configures daily rotation, keeps 30 compressed logs, and notifies the service on rotation. ```bash # Create logrotate configuration cat > /etc/logrotate.d/clashsubmanager << EOF /app/logs/*.log { daily rotate 30 compress delaycompress missingok notifempty create 644 root root postrotate docker kill -s USR1 clashsubmanager endscript } EOF ``` -------------------------------- ### Configure ClashSubManager with User Configuration File Source: https://github.com/soren-work/clash-sub-manager/blob/main/README.md Example of an 'appsettings.User.json' file used to configure ClashSubManager settings. This file should be placed in the program's directory. It allows overriding default and environment-specific configurations. ```json { "AdminUsername": "admin", "AdminPassword": "your_password", "CookieSecretKey": "your_32_character_minimum_key", "SessionTimeoutMinutes": 30, "DataPath": "/custom/data/path", "SubscriptionUrlTemplate": "https://api.example.com/sub/{userId}" } ``` -------------------------------- ### Docker Compose Service Management Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Commands to start, check the status of, and view logs for the Docker Compose service. ```bash # Start docker-compose up -d # Check status docker-compose ps # View logs docker-compose logs -f ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/node-naming-template-design.md Shows how to configure node naming templates using environment variables. Includes examples for direct template assignment and backward compatibility with older flags. ```bash # Template configuration NODE_NAMING_TEMPLATE="自定义名称-节点-{index}" NODE_NAMING_TEMPLATE="{name}-CF-{index}-{server}" # Backward compatibility USE_IP_IN_NODE_NAME=true # Maps to "{name}-{server}" ``` -------------------------------- ### Run Clash Sub Manager with Docker (Full Configuration) Source: https://github.com/soren-work/clash-sub-manager/blob/main/README.md This command demonstrates a more comprehensive Docker setup, including session timeout and a custom data path. Remember to generate a strong, unique CookieSecretKey. ```bash docker run -d \ -p 8080:80 \ -e AdminUsername=admin \ -e AdminPassword=MySecurePassword123 \ -e CookieSecretKey=abcdef1234567890abcdef1234567890 \ -e SUBSCRIPTION_URL_TEMPLATE=https://api.example.com/sub/{userId} \ -e SessionTimeoutMinutes=30 \ -e DataPath=/app/data \ -v $(pwd)/data:/app/data \ --name clash-sub-manager \ --restart unless-stopped \ clashsubmanager:latest ``` -------------------------------- ### Advanced Template Examples Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/node-naming-template-design.md Illustrates advanced node naming templates, including multi-variable combinations and a placeholder for conditional naming logic. These allow for more complex and dynamic naming schemes. ```json # Multi-variable combinations "{name}-{type}-{index}-{server}" "Custom-{proxy.type}-Node-{node.index}" # Conditional naming (future enhancement) "{name}{#if network == 'vless'}-VLESS{#else}-{type}{/if}-{index}" ``` -------------------------------- ### Multi-Instance Docker Compose Setup Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Deploy multiple instances of ClashSubManager using Docker Compose for high availability. Each instance is configured with separate ports, volumes for data and logs, and environment files. ```yaml version: '3.8' services: clashsubmanager-1: image: clashsubmanager:latest container_name: clashsubmanager-1 ports: - "127.0.0.1:8080:80" volumes: - ./data:/app/data:ro # Read-only mount - ./logs/instance-1:/app/logs env_file: - .env.production restart: unless-stopped clashsubmanager-2: image: clashsubmanager:latest container_name: clashsubmanager-2 ports: - "127.0.0.1:8081:80" volumes: - ./data:/app/data:ro - ./logs/instance-2:/app/logs env_file: - .env.production restart: unless-stopped clashsubmanager-3: image: clashsubmanager:latest container_name: clashsubmanager-3 ports: - "127.0.0.1:8082:80" volumes: - ./data:/app/data:ro - ./logs/instance-3:/app/logs env_file: - .env.production restart: unless-stopped ``` -------------------------------- ### Implement Configuration Validation Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/modules/cross-platform-config-mvp-detail.md Validates application configuration settings, throwing an exception if any required settings are missing or invalid. Use this to ensure the application starts with a valid configuration. ```csharp public class ConfigurationValidator : IConfigurationValidator { public void Validate(IConfiguration configuration) { var errors = GetValidationErrors(configuration); if (errors.Any()) { throw new InvalidOperationException( $"Configuration validation failed: {string.Join(", ", errors)}"); } } public List GetValidationErrors(IConfiguration configuration) { var errors = new List(); // Validate required settings if (string.IsNullOrEmpty(configuration["AdminUsername"])) errors.Add("AdminUsername is required"); if (string.IsNullOrEmpty(configuration["AdminPassword"])) errors.Add("AdminPassword is required"); var secretKey = configuration["CookieSecretKey"]; if (string.IsNullOrEmpty(secretKey) || secretKey.Length < 32) errors.Add("CookieSecretKey must be at least 32 characters"); // Validate session timeout if (int.TryParse(configuration["SessionTimeoutMinutes"], out var timeout)) { if (timeout < 5 || timeout > 1440) errors.Add("SessionTimeoutMinutes must be between 5 and 1440"); } // Validate data path var dataPath = configuration["DataPath"]; if (!string.IsNullOrEmpty(dataPath)) { try { var fullPath = Path.IsPathRooted(dataPath) ? dataPath : Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ".", dataPath); Directory.CreateDirectory(fullPath); } catch (Exception ex) { errors.Add($"Cannot create data directory '{dataPath}': {ex.Message}"); } } return errors; } } ``` -------------------------------- ### Single Docker Command for Quick Test Deployment Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md A single Docker command to run the Clash Sub Manager container, mapping ports, mounting volumes, and setting environment variables for a quick test setup. ```bash # One-command startup (test environment) docker run -d \ --name clashsubmanager \ -p 8080:80 \ -v $(pwd)/data:/app/data \ -e AdminUsername=admin \ -e AdminPassword=test123 \ -e CookieSecretKey=test_secret_key_32_chars_long \ -e SessionTimeoutMinutes=120 \ -e SUBSCRIPTION_URL_TEMPLATE=https://api.example.com/sub/{userId} \ clashsubmanager:latest # View logs docker logs -f clashsubmanager ``` -------------------------------- ### Install Nginx Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Installs the Nginx web server on Ubuntu/Debian or CentOS/RHEL systems. ```bash # Ubuntu/Debian sudo apt update sudo apt install nginx -y # CentOS/RHEL sudo yum install nginx -y ``` -------------------------------- ### Core Architecture Diagram Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/cross-platform-config-mvp-outline.md Illustrates the application startup flow, including environment detection, configuration loading from various sources with priority, validation, and service registration. ```text Application Startup ├── Environment Detection │ ├── Docker Environment Check │ └── Platform Detection (Windows/Linux/macOS) ├── Configuration Loading │ ├── Base Configuration (appsettings.json) │ ├── Environment-Specific Config │ ├── User Configuration (appsettings.User.json) │ ├── Environment Variables │ └── Command Line Arguments ├── Configuration Validation └── Service Registration ``` -------------------------------- ### Create Project Directory Structure Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Creates the necessary directories for data, logs, and configuration, and sets appropriate permissions for the data and logs directories. ```bash # Create project directory mkdir -p /opt/clashsubmanager/{data,logs,config} cd /opt/clashsubmanager # Set permissions chmod 755 data logs ``` -------------------------------- ### Install Certbot for SSL Certificates Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Installs Certbot and the Nginx plugin for Ubuntu/Debian or CentOS/RHEL systems to manage Let's Encrypt SSL certificates. ```bash # Ubuntu/Debian sudo apt install certbot python3-certbot-nginx -y # CentOS/RHEL sudo yum install certbot python3-certbot-nginx -y ``` -------------------------------- ### POST /sub/[id] Request Data Example Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/mvp-core-features.md Example of data format for submitting CloudflareST results via POST to the /sub/[id] endpoint. Supports CSV or plain text, with IP validation. ```csv IP Address,Sent,Received,Packet Loss,Average Latency,Download Speed (MB/s) 104.16.1.1,10,10,0%,45.2,12.5 104.16.2.1,10,9,10%,52.1,8.3 ``` -------------------------------- ### Example Preferred IP List CSV Format Source: https://github.com/soren-work/clash-sub-manager/blob/main/README.md This is an example of the CSV format required for uploading preferred IP lists. It includes columns for IP address, sent/received data, packet loss, latency, and download speed. ```csv IP Address,Sent,Received,Packet Loss Rate,Average Latency,Download Speed 104.29.125.182,4,4,0.00%,152.45ms,0.00 104.26.0.188,4,4,0.00%,158.10ms,0.00 ``` -------------------------------- ### GET /sub/[id] User Validation Failure Test Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/test/mvp-unit-test.md Tests the scenario where user validation fails for the GET /sub/[id] endpoint. It verifies that an invalid or nonexistent user ID returns a 401 Unauthorized status. ```APIDOC ## GET /sub/[id] - User Validation Failure ### Description Handles cases where the provided user ID is invalid or does not exist, resulting in an authorization failure. ### Method GET ### Endpoint /sub/[id] ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. ### Request Example (No request body for GET requests) ### Response #### Error Response (401) - **Success**: false - **Message**: User ID validation failed #### Response Example ```json { "success": false, "message": "User ID validation failed" } ``` ``` -------------------------------- ### Apache Reverse Proxy Configuration Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Example Apache configuration for proxying HTTP and HTTPS traffic to the application. ```apache ServerName your-domain.com ProxyPreserveHost On ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ ServerName your-domain.com SSLEngine on SSLCertificateFile /path/to/your/cert.pem SSLCertificateKeyFile /path/to/your/key.pem ProxyPreserveHost On ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ ``` -------------------------------- ### Configure Configuration Loading in Program.cs Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/modules/cross-platform-config-mvp-detail.md Sets up the configuration builder in a .NET application, including adding JSON files based on environment, user settings, environment variables, and command-line arguments. Ensures configuration validation is performed. ```csharp var builder = WebApplication.CreateBuilder(args); // Get environment type var environmentDetector = new EnvironmentDetector(); var environmentType = environmentDetector.GetEnvironmentType(); // Configure configuration loading with priority builder.Configuration .SetBasePath(builder.Environment.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{environmentType}.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.User.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .AddCommandLine(args); // Validate configuration var validator = new ConfigurationValidator(); validator.Validate(builder.Configuration); // Register services builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); ``` -------------------------------- ### Nginx Reverse Proxy Configuration Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Example Nginx configuration for proxying HTTP and HTTPS traffic to the application. ```nginx server { listen 80; server_name your-domain.com; location / { proxy_pass http://localhost:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } server { listen 443 ssl; server_name your-domain.com; ssl_certificate /path/to/your/cert.pem; ssl_certificate_key /path/to/your/key.pem; location / { proxy_pass http://localhost:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } ``` -------------------------------- ### GET /sub/[user id] Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/mvp-core-features.md Retrieves the overwritten subscription data for a given user ID. The response is in YAML format. ```APIDOC ## GET /sub/[user id] ### Description Retrieves the overwritten subscription data for a given user ID. The response is in YAML format. ### Method GET ### Endpoint /sub/[user id] ### Parameters #### Path Parameters - **user id** (string) - Required - The unique identifier for the user. ### Response #### Success Response (200) - **Content-Type**: text/yaml - Returns the complete YAML configuration for the user. #### Response Example ```yaml # Example YAML configuration proxies: - name: "ExampleProxy" server: "example.com" port: 8080 type: "http" ``` ``` -------------------------------- ### Storage Structure Overview Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/requirements/server-requirements.md Illustrates the directory and file structure for storing default and user-specific configurations within the application's data directory. ```text /app/data/ ├── cloudflare-ip.csv # Default optimized IPs ├── clash.yaml # Default Clash template ├── users.txt # User records └── [user id]/ ├── cloudflare-ip.csv # User-specific optimized IPs └── clash.yaml # User-specific template ``` -------------------------------- ### Troubleshoot Configuration Not Taking Effect Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/FAQ.md Verify the existence and format of the optimized IP file, confirm node server fields are domains, and inspect the final generated configuration. ```bash # 1. Check if optimized IP file exists docker exec clashsubmanager ls -la /app/data/cloudflare-ip.csv # 2. Check file content format docker exec clashsubmanager cat /app/data/cloudflare-ip.csv # 3. Confirm node server field is domain not IP # Only domain nodes will be expanded, IP nodes remain unchanged # 4. View final generated configuration curl http://localhost:8080/sub/user123 > final-config.yaml cat final-config.yaml | grep -A 5 "proxies:" ``` -------------------------------- ### Perform Health Check Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/advanced-guide.md Check the health status of the service by sending a GET request to the /health endpoint. The expected response indicates a healthy status. ```bash # Check service health status curl http://localhost:8080/health # Expected response { "status": "Healthy", "totalDuration": "00:00:00.0123456" } ``` -------------------------------- ### Global and User-Specific Configuration Strategy 2 Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/advanced-guide.md Demonstrates a strategy for completely independent configurations per user, where each user has distinct settings. ```yaml # User user123 rules: - DOMAIN-SUFFIX,openai.com,US-Proxy - MATCH,Proxy # User user456 rules: - DOMAIN-SUFFIX,netflix.com,HK-Proxy - MATCH,DIRECT ``` -------------------------------- ### Change Docker Port Mapping Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/FAQ.md If Docker fails to start due to a port conflict, change the mapped port in your docker-compose.yml or Docker run command. ```yaml ports: - "8081:80" ``` -------------------------------- ### File Storage Structure Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/mvp-core-features.md Illustrates the directory and file structure for storing configuration and user data. User-specific files override global configurations. ```text /app/data/ ├── cloudflare-ip.csv # Global IP file ├── clash.yaml # Global configuration file ├── users.txt # User ID records (auto-deduplication) └── [user id]/ ├── cloudflare-ip.csv # User-specific IP file └── clash.yaml # User-specific configuration file ``` -------------------------------- ### FileService Integration with Configuration Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/modules/cross-platform-config-mvp-detail.md Demonstrates how FileService integrates with IConfigurationService to retrieve the data path and ensures the data directory exists upon initialization. Assumes other methods remain unchanged. ```csharp public class FileService { private readonly IConfigurationService _configurationService; private readonly string _dataPath; public FileService(IConfigurationService configurationService, ILogger logger) { _configurationService = configurationService; _logger = logger; _dataPath = _configurationService.GetDataPath(); // Ensure data directory exists Directory.CreateDirectory(_dataPath); } // All existing methods remain the same, using _dataPath } ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/env-config.md Use this .env file for local development. It includes default settings and debug logging. ```bash # .env.development AdminUsername=admin AdminPassword=DevPass123! CookieSecretKey=dev_secret_key_32_characters_long SessionTimeoutMinutes=120 ASPNETCORE_ENVIRONMENT=Development LOG_LEVEL=Debug DataPath=./data SUBSCRIPTION_URL_TEMPLATE=https://api.example.com/sub/{userId} ``` -------------------------------- ### Get User Clash Subscription Configuration Source: https://github.com/soren-work/clash-sub-manager/blob/main/README.md Retrieves the Clash subscription configuration for a specific user. This endpoint is used by Clash clients to fetch their subscription details. ```APIDOC ## GET /sub/{id} ### Description Retrieves the Clash subscription configuration for a specific user. ### Method GET ### Endpoint /sub/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier for the user. ### Response #### Success Response (200) - **subscription_config** (object) - The user's Clash subscription configuration. ``` -------------------------------- ### Run Clash Sub Manager with Docker (Minimal) Source: https://github.com/soren-work/clash-sub-manager/blob/main/README.md Use this command for a basic Docker deployment. Ensure you customize the AdminPassword and CookieSecretKey. The SUBSCRIPTION_URL_TEMPLATE requires your specific subscription URL with a {userId} placeholder. ```bash docker run -d \ -p 8080:80 \ -e AdminUsername=admin \ -e AdminPassword=your_password \ -e CookieSecretKey=your_32_character_minimum_secret_key_here \ -e SUBSCRIPTION_URL_TEMPLATE=https://your-airport.com/sub/{userId} \ -v $(pwd)/data:/app/data \ --name clash-sub-manager \ clashsubmanager:latest ``` -------------------------------- ### Route Different Services to Different Proxy Groups Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/advanced-guide.md Example of routing specific domains to different proxy groups based on their service. This allows for granular control over traffic. ```yaml proxy-groups: - name: "AI-Services" type: select proxies: - US-Node - name: "Streaming" type: select proxies: - HK-Node rules: - DOMAIN-SUFFIX,openai.com,AI-Services - DOMAIN-SUFFIX,netflix.com,Streaming - MATCH,General ``` -------------------------------- ### Get IP File Path Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/modules/ip-management-detail.md Determines the file path for IP data, using a default path for null or empty user IDs or a user-specific path otherwise. ```csharp return string.IsNullOrEmpty(userId) ? Path.Combine(_basePath, "cloudflare-ip.csv") : Path.Combine(_basePath, userId, "cloudflare-ip.csv"); ``` -------------------------------- ### Set ASP.NET Core Environment Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/env-config.md Configure the ASP.NET Core runtime environment. Defaults to 'Production'. ```bash ASPNETCORE_ENVIRONMENT=Production ``` -------------------------------- ### Get Clash YAML File Path Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/modules/clash-template-detail.md Constructs the file path for a Clash YAML file, either in the base path for a null/empty user ID or in a user-specific subdirectory. ```csharp return string.IsNullOrEmpty(userId) ? Path.Combine(_basePath, "clash.yaml") : Path.Combine(_basePath, userId, "clash.yaml"); ``` -------------------------------- ### Download and Run CloudflareST Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/FAQ.md Steps to download the CloudflareST tool, run a speed test, and view the results. This is useful for obtaining optimized Cloudflare IPs. ```bash # 1. Download CloudflareST wget https://github.com/XIU2/CloudflareSpeedTest/releases/download/v2.2.5/CloudflareST_linux_amd64.tar.gz tar -zxvf CloudflareST_linux_amd64.tar.gz # 2. Run speed test ./CloudflareST -n 200 -t 10 -o result.csv # 3. View results cat result.csv ``` -------------------------------- ### Get Final Generated Configuration (Bash) Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/examples/README.md This command retrieves the final generated Clash configuration from the Clash Sub Manager. The output can be saved to a file for further validation or testing. ```bash # 1. Get final generated configuration curl http://localhost:8080/sub/user123 > final-config.yaml # 2. Check configuration format # Use online YAML validator # 3. Test in Clash client # Import configuration, check for errors ``` -------------------------------- ### Troubleshoot Subscription URL 404 Errors Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/FAQ.md Use these commands to check subscription URL format, test upstream service availability, view container logs, and verify environment variables. ```bash # 1. Check subscription URL format # Correct format: http://your-domain:8080/sub/user123 # 2. Test if upstream subscription is available curl -A "clash" https://your-airport.com/sub/user123 # 3. View container logs docker logs clashsubmanager | grep "user123" # 4. Verify upstream subscription URL in environment variables docker exec clashsubmanager printenv | grep SUBSCRIPTION_URL ``` -------------------------------- ### Basic Clash Template Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/examples/README.md A minimal configuration suitable for personal use or simple setup needs. It includes basic proxy groups and rules for direct connections and general proxying. ```yaml # Basic Clash Template # Suitable for: Personal use, simple configuration needs # Proxy group configuration proxy-groups: # Auto-select node with lowest latency - name: "Auto" type: url-test url: 'http://www.gstatic.com/generate_204' interval: 300 tolerance: 50 # Manual proxy selection - name: "Proxy" type: select proxies: - Auto - DIRECT # Rule configuration rules: # LAN direct connection - DOMAIN-SUFFIX,local,DIRECT - IP-CIDR,192.168.0.0/16,DIRECT - IP-CIDR,10.0.0.0/8,DIRECT - IP-CIDR,172.16.0.0/12,DIRECT # China mainland direct connection - GEOIP,CN,DIRECT # Others use proxy - MATCH,Proxy ``` -------------------------------- ### Configuration Priority Order Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/FAQ.md Illustrates the priority order for Clash configuration files and explains the merge rules for different field types. ```text User-specific config > Global default config > Original subscription # File paths: # Global config: /app/data/clash.yaml # User config: /app/data/user123/clash.yaml # Merge rules: # 1. Array fields (proxies, rules): Append merge # 2. Object fields (dns, tun): Override merge # 3. Simple fields (port, mode): Direct override ``` -------------------------------- ### Troubleshooting User-Specific Configuration Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/FAQ.md Steps to troubleshoot why user-specific configurations might not be taking effect, including checking directory existence, file content, and logs. ```bash # 1. Check if user directory exists docker exec clashsubmanager ls -la /app/data/user123/ # 2. Check if config file exists docker exec clashsubmanager cat /app/data/user123/clash.yaml # 3. Validate YAML format # Use online YAML validator # 4. View logs docker logs clashsubmanager | grep "user123" # 5. Get final config to verify curl http://localhost:8080/sub/user123 > final.yaml ``` -------------------------------- ### File Test Helper Methods Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/test/mvp-unit-test.md Provides utility methods for setting up and cleaning up test files, including creating user-specific directories and files, and counting pattern occurrences within text. Assumes MockDataBuilder is available. ```csharp public static class FileTestHelper { public static async Task SetupTestFiles(string userId, string testDataPath) { var userDir = Path.Combine(testDataPath, userId); Directory.CreateDirectory(userDir); // Create user-specific IP file var userIPPath = Path.Combine(userDir, "cloudflare-ip.csv"); await File.WriteAllTextAsync(userIPPath, MockDataBuilder.GetValidCSVContent()); // Create user-specific template file var userTemplatePath = Path.Combine(userDir, "clash.yaml"); await File.WriteAllTextAsync(userTemplatePath, MockDataBuilder.GetValidYAMLContent()); } public static async Task CleanupTestFiles(string userId, string testDataPath) { var userDir = Path.Combine(testDataPath, userId); if (Directory.Exists(userDir)) { Directory.Delete(userDir, true); } } public static int CountOccurrences(string text, string pattern) { var count = 0; var index = 0; while ((index = text.IndexOf(pattern, index, StringComparison.OrdinalIgnoreCase)) != -1) { count++; index += pattern.Length; } return count; } } ``` -------------------------------- ### Get Naming Template with Migration Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/architecture/node-naming-template-design.md Retrieves the node naming template, migrating from the old 'UseIpInNodeName' setting if the new 'NodeNamingTemplate' configuration is not present. Use this to ensure backward compatibility. ```csharp // Automatic migration from old configuration private string GetNamingTemplate() { // Check for new template configuration var template = GetValue("NodeNamingTemplate"); if (!string.IsNullOrEmpty(template)) return template; // Migrate from old UseIpInNodeName setting var useIpFormat = GetValue("UseIpInNodeName", false); return useIpFormat ? "{name}-{server}" : "{name}-Node-{index}"; } ``` -------------------------------- ### Development Environment Variables Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/environment-variables.md Sets up essential environment variables for local development and testing. These include administrative credentials, a secret key for cookies, session duration, and a template for subscription URLs. Use these only in non-production environments. ```bash ADMIN_USERNAME=admin ADMIN_PASSWORD=dev123 COOKIE_SECRET_KEY=dev-secret-key-for-development-only SESSION_TIMEOUT_MINUTES=120 SUBSCRIPTION_URL_TEMPLATE=https://api.example.com/sub/{userId} ``` -------------------------------- ### Nginx Load Balancing Configuration Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Configure Nginx to load balance traffic across multiple ClashSubManager instances. This setup uses the least connections algorithm and includes SSL/TLS configuration. ```nginx upstream clashsubmanager_backend { least_conn; # Least connections algorithm server 127.0.0.1:8080 weight=1 max_fails=3 fail_timeout=30s; server 127.0.0.1:8081 weight=1 max_fails=3 fail_timeout=30s; server 127.0.0.1:8082 weight=1 max_fails=3 fail_timeout=30s; } server { listen 443 ssl http2; server_name your-domain.com; ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem; location / { proxy_pass http://clashsubmanager_backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # Health check proxy_next_upstream error timeout http_500 http_502 http_503; } } ``` -------------------------------- ### Configuration File Format Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/spec/design/requirements/client-requirements.md Specifies the format for storing user subscription addresses. This file should be named 'sub.txt' and placed in the script directory. ```plaintext https://sub.domain.com/sub/your-id ``` -------------------------------- ### Configure Cron Job for Health Checks Source: https://github.com/soren-work/clash-sub-manager/blob/main/doc/deployment/deployment-guide.md Schedule the health check script to run at regular intervals using cron. This example configures the check to run every 5 minutes. ```bash # Check every 5 minutes */5 * * * * /opt/clashsubmanager/scripts/health-check.sh ```