Spaces:
Paused
Paused
File size: 6,310 Bytes
aaaaa79 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
#!/usr/bin/env python3
"""
Virtual ISP Stack with OpenVPN Integration
HuggingFace Spaces Entry Point
This application provides a complete Virtual ISP stack with OpenVPN server integration,
allowing users to manage VPN connections, generate client configurations, and monitor
network traffic through a RESTful API.
"""
import os
import sys
import logging
# Add current directory to Python path
sys.path.insert(0, os.path.dirname(__file__))
from flask import Flask, send_from_directory, jsonify
from flask_cors import CORS
from models.enhanced_user import db
from routes.auth import auth_bp
from routes.vpn_client import vpn_client_bp
from routes.vpn_server import vpn_server_bp
from routes.isp_api import init_engines, isp_api
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Create Flask application
app = Flask(__name__, static_folder=os.path.join(os.path.dirname(__file__), 'static'))
# Enable CORS for all routes
CORS(app, origins="*")
# Configuration
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'vpn-isp-stack-secret-key-change-in-production')
# Database configuration
database_path = os.path.join(os.path.dirname(__file__), 'database', 'app.db')
app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{database_path}"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize database
db.init_app(app)
# Register blueprints
app.register_blueprint(auth_bp, url_prefix='/api')
app.register_blueprint(vpn_client_bp, url_prefix='/api')
app.register_blueprint(vpn_server_bp, url_prefix='/api')
app.register_blueprint(isp_api, url_prefix='/api')
# Engine configuration
app.config.update({
"dhcp": {
"network": "10.0.0.0/24",
"range_start": "10.0.0.10",
"range_end": "10.0.0.100",
"lease_time": 3600,
"gateway": "10.0.0.1",
"dns_servers": ["8.8.8.8", "8.8.4.4"]
},
"nat": {
"port_range_start": 10000,
"port_range_end": 65535,
"session_timeout": 300
},
"firewall": {
"default_policy": "ACCEPT",
"log_blocked": True
},
"tcp": {
"initial_window": 65535,
"max_retries": 3,
"timeout": 30
},
"openvpn": {
"server_ip": "10.8.0.1",
"server_port": 1194,
"network": "10.8.0.0/24"
},
"logger": {
"log_level": "INFO",
"log_file": "/tmp/virtual_isp.log"
}
})
# Add VPN server configuration
app.config.update({
'VPN_SERVER_IP': os.environ.get('VPN_SERVER_IP', '127.0.0.1'),
'OPENVPN_PORT': int(os.environ.get('OPENVPN_PORT', 1194)),
'IKEV2_PORT': int(os.environ.get('IKEV2_PORT', 500)),
'WIREGUARD_PORT': int(os.environ.get('WIREGUARD_PORT', 51820)),
'WIREGUARD_SERVER_PUBLIC_KEY': os.environ.get('WIREGUARD_SERVER_PUBLIC_KEY', 'SERVER_PUBLIC_KEY_HERE')
})
# Initialize database tables
with app.app_context():
try:
db.create_all()
logger.info("Database tables created successfully")
except Exception as e:
logger.error(f"Error creating database tables: {e}")
# Initialize engines
try:
init_engines(app.config)
logger.info("All engines initialized successfully")
except Exception as e:
logger.error(f"Error initializing engines: {e}")
@app.route('/')
def index():
"""Main index page - redirect to auth if not logged in"""
return serve_static('auth.html')
@app.route('/auth')
def auth_page():
"""Authentication page"""
return serve_static('auth.html')
@app.route('/dashboard')
def dashboard_page():
"""Dashboard page"""
return serve_static('index.html')
@app.route('/health')
def health_check():
"""Health check endpoint for monitoring"""
return jsonify({
'status': 'healthy',
'service': 'Virtual ISP Stack with OpenVPN',
'version': '1.0.0'
})
@app.route('/api')
def api_info():
"""API information endpoint"""
return jsonify({
'service': 'Virtual ISP Stack API',
'version': '1.0.0',
'endpoints': {
'openvpn': {
'status': '/api/openvpn/status',
'start': '/api/openvpn/start',
'stop': '/api/openvpn/stop',
'clients': '/api/openvpn/clients',
'config': '/api/openvpn/config/<client_name>',
'stats': '/api/openvpn/stats',
'configs': '/api/openvpn/configs'
},
'dhcp': {
'leases': '/api/dhcp/leases'
},
'nat': {
'sessions': '/api/nat/sessions',
'stats': '/api/nat/stats'
},
'firewall': {
'rules': '/api/firewall/rules',
'logs': '/api/firewall/logs',
'stats': '/api/firewall/stats'
}
}
})
@app.route('/<path:path>')
def serve_static(path):
"""Serve static files"""
static_folder_path = app.static_folder
if static_folder_path is None:
return jsonify({'error': 'Static folder not configured'}), 404
if path != "" and os.path.exists(os.path.join(static_folder_path, path)):
return send_from_directory(static_folder_path, path)
else:
index_path = os.path.join(static_folder_path, 'index.html')
if os.path.exists(index_path):
return send_from_directory(static_folder_path, 'index.html')
else:
return jsonify({
'message': 'Virtual ISP Stack with OpenVPN Integration',
'status': 'running',
'api_docs': '/api'
})
@app.errorhandler(404)
def not_found(error):
"""Handle 404 errors"""
return jsonify({'error': 'Endpoint not found', 'api_docs': '/api'}), 404
@app.errorhandler(500)
def internal_error(error):
"""Handle 500 errors"""
return jsonify({'error': 'Internal server error'}), 500
if __name__ == '__main__':
# Get port from environment variable (HuggingFace Spaces uses PORT)
port = int(os.environ.get('PORT', 7860))
logger.info(f"Starting Virtual ISP Stack with OpenVPN on port {port}")
# Run the application
app.run(
host='0.0.0.0',
port=port,
debug=False,
threaded=True
)
|