299 lines
11 KiB
Python
299 lines
11 KiB
Python
from flask import Flask, render_template, request, jsonify, abort
|
|
import requests
|
|
import threading
|
|
import os
|
|
import jwt
|
|
import logging
|
|
import json
|
|
from datetime import datetime, timedelta
|
|
from dotenv import load_dotenv
|
|
import re
|
|
import signal
|
|
import sys
|
|
|
|
# Load environment variables
|
|
load_dotenv()
|
|
|
|
# Configuration with fixed Caddyfile path
|
|
API_KEY = os.getenv('API_KEY')
|
|
DEBUG_MODE = os.getenv('DEBUG_MODE', 'false').lower() == 'true'
|
|
CADDYFILE_PATH = "/app/Caddyfile" # Fixed internal path
|
|
NGINX_CONFIG_PATH = os.getenv('NGINX_CONFIG_PATH', '/app/nginx/conf.d') # Path to nginx config directory
|
|
|
|
# Add SERVER_NAME environment variable near the top with other configs
|
|
SERVER_NAME = os.getenv('SERVER_NAME', 'Local Server') # Get server name from env variable
|
|
|
|
# Setup logging
|
|
logging.basicConfig(
|
|
level=logging.DEBUG if DEBUG_MODE else logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
)
|
|
logger = logging.getLogger('caddy-dashboard')
|
|
|
|
# Determine if we should use local configuration files
|
|
USE_LOCAL_CADDYFILE = os.path.exists(CADDYFILE_PATH)
|
|
USE_LOCAL_NGINX = os.path.exists(NGINX_CONFIG_PATH) and os.path.isdir(NGINX_CONFIG_PATH)
|
|
|
|
if not USE_LOCAL_CADDYFILE:
|
|
logger.warning(f"Caddyfile not found at the standard path: {CADDYFILE_PATH}")
|
|
|
|
if not USE_LOCAL_NGINX:
|
|
logger.warning(f"Nginx config directory not found at: {NGINX_CONFIG_PATH}")
|
|
|
|
if not API_KEY:
|
|
logger.warning("API_KEY not set - running without authentication! This is insecure.")
|
|
|
|
app = Flask(__name__)
|
|
app.config['SECRET_KEY'] = os.urandom(24)
|
|
|
|
# Global data storage
|
|
caddy_proxies = {} # Server name -> {domain: target}
|
|
nginx_proxies = {} # Server name -> {domain: target}
|
|
timestamps = {} # Server name -> timestamp
|
|
|
|
def verify_token(token):
|
|
"""Verify the JWT token from an agent"""
|
|
if not API_KEY:
|
|
logger.error("API_KEY is not configured - authentication disabled")
|
|
return None
|
|
|
|
try:
|
|
return jwt.decode(token, API_KEY, algorithms=['HS256'])
|
|
except jwt.ExpiredSignatureError:
|
|
logger.warning("Authentication token has expired")
|
|
return None
|
|
except jwt.InvalidTokenError as e:
|
|
logger.warning(f"Invalid authentication token: {e}")
|
|
return None
|
|
|
|
def parse_local_caddyfile():
|
|
"""Parse a local Caddyfile to extract domains and their proxy targets"""
|
|
entries = {}
|
|
try:
|
|
if not os.path.exists(CADDYFILE_PATH):
|
|
logger.error(f"Local Caddyfile not found at {CADDYFILE_PATH}")
|
|
return entries
|
|
|
|
with open(CADDYFILE_PATH, "r") as file:
|
|
content = file.read()
|
|
|
|
# Revert to simpler pattern that was working previously
|
|
pattern = re.compile(r"(?P<domains>[^\s{]+(?:,\s*[^\s{]+)*)\s*{.*?reverse_proxy\s+(?P<target>https?:\/\/[\d\.]+:\d+|[\d\.]+:\d+).*?}", re.DOTALL)
|
|
matches = pattern.findall(content)
|
|
|
|
logger.info(f"Found {len(matches)} matches in local Caddyfile")
|
|
|
|
for domains, target in matches:
|
|
for domain in re.split(r',\s*', domains):
|
|
domain = domain.strip()
|
|
if domain and domain.lower() != "host": # Skip entries named "host"
|
|
entries[domain] = target.strip()
|
|
|
|
logger.info(f"Extracted {len(entries)} domain entries from local Caddyfile")
|
|
|
|
# Debug output of parsed entries
|
|
for domain, target in entries.items():
|
|
logger.debug(f"Domain: {domain} -> {target}")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error parsing local Caddyfile: {e}")
|
|
import traceback
|
|
logger.error(traceback.format_exc())
|
|
|
|
return entries
|
|
|
|
def parse_nginx_configs():
|
|
"""Parse nginx config files to extract server_name and proxy_pass directives"""
|
|
entries = {}
|
|
|
|
if not os.path.exists(NGINX_CONFIG_PATH) or not os.path.isdir(NGINX_CONFIG_PATH):
|
|
logger.warning(f"Nginx config directory not found at: {NGINX_CONFIG_PATH}")
|
|
return entries
|
|
|
|
try:
|
|
# Get all .conf files in the nginx config directory
|
|
for filename in os.listdir(NGINX_CONFIG_PATH):
|
|
if not filename.endswith('.conf'):
|
|
continue
|
|
|
|
filepath = os.path.join(NGINX_CONFIG_PATH, filename)
|
|
with open(filepath, 'r') as file:
|
|
content = file.read()
|
|
|
|
# Pattern to extract server_name and proxy_pass
|
|
server_blocks = re.findall(r'server\s*{(.*?)}', content, re.DOTALL)
|
|
|
|
for block in server_blocks:
|
|
# Extract server_name
|
|
server_name_match = re.search(r'server_name\s+(.+?);', block)
|
|
if not server_name_match:
|
|
continue
|
|
|
|
server_names = server_name_match.group(1).split()
|
|
|
|
# Extract proxy_pass
|
|
proxy_pass_match = re.search(r'proxy_pass\s+(https?://[^;]+);', block)
|
|
if not proxy_pass_match:
|
|
continue
|
|
|
|
proxy_target = proxy_pass_match.group(1)
|
|
|
|
# Add each server name with its proxy target
|
|
for name in server_names:
|
|
if name != '_' and name.lower() != 'host': # Skip default server and "host"
|
|
entries[name] = proxy_target
|
|
|
|
logger.info(f"Extracted {len(entries)} domain entries from Nginx configs")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error parsing Nginx configs: {e}")
|
|
import traceback
|
|
logger.error(traceback.format_exc())
|
|
|
|
return entries
|
|
|
|
def validate_token(auth_header):
|
|
"""Validate the JWT token from the Authorization header"""
|
|
if not auth_header or not auth_header.startswith("Bearer "):
|
|
return False
|
|
|
|
token = auth_header.split(" ")[1]
|
|
|
|
try:
|
|
payload = jwt.decode(token, API_KEY, algorithms=["HS256"])
|
|
return True
|
|
except jwt.InvalidTokenError:
|
|
return False
|
|
|
|
def get_server_stats():
|
|
"""Get basic server statistics"""
|
|
stats = {
|
|
'caddy_servers': len(caddy_proxies),
|
|
'nginx_servers': len(nginx_proxies),
|
|
'total_domains': sum(len(entries) for entries in caddy_proxies.values()) +
|
|
sum(len(entries) for entries in nginx_proxies.values()),
|
|
'last_update': max(timestamps.values(), default=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
|
|
}
|
|
return stats
|
|
|
|
@app.route('/')
|
|
def index():
|
|
"""Dashboard home page"""
|
|
stats = get_server_stats()
|
|
return render_template('dashboard.html',
|
|
caddy_count=stats['caddy_servers'],
|
|
nginx_count=stats['nginx_servers'],
|
|
domain_count=stats['total_domains'],
|
|
last_update=stats['last_update'],
|
|
caddy_proxies=caddy_proxies, # Pass all proxies data
|
|
nginx_proxies=nginx_proxies) # Pass all proxies data
|
|
|
|
@app.route('/caddy')
|
|
def caddy_dashboard():
|
|
"""Caddy specific dashboard"""
|
|
return render_template('index.html', proxies=caddy_proxies, timestamps=timestamps, server_type="Caddy")
|
|
|
|
@app.route('/nginx')
|
|
def nginx_dashboard():
|
|
"""Nginx specific dashboard"""
|
|
return render_template('index.html', proxies=nginx_proxies, timestamps=timestamps, server_type="Nginx")
|
|
|
|
@app.route('/api/update', methods=['POST'])
|
|
def update_proxies():
|
|
"""API endpoint for agents to update proxy data"""
|
|
# Verify token if API_KEY is set
|
|
if API_KEY:
|
|
auth_header = request.headers.get("Authorization")
|
|
if not validate_token(auth_header):
|
|
return jsonify({"status": "error", "message": "Invalid or missing token"}), 401
|
|
|
|
# Get data from request
|
|
data = request.json
|
|
if not data or not isinstance(data, dict):
|
|
return jsonify({"status": "error", "message": "Invalid data format"}), 400
|
|
|
|
server_name = data.get("server", SERVER_NAME) # Default to SERVER_NAME if not provided
|
|
entries = data.get("entries", {})
|
|
server_type = data.get("type", "caddy").lower() # Default to caddy if not specified
|
|
|
|
# Update the appropriate store based on server type
|
|
if server_type == "nginx":
|
|
nginx_proxies[server_name] = entries
|
|
else:
|
|
caddy_proxies[server_name] = entries
|
|
|
|
# Update timestamp
|
|
timestamps[server_name] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
# Log the update
|
|
logger.info(f"Updated {server_type} proxy data for {server_name}: {len(entries)} entries")
|
|
|
|
return jsonify({"status": "success", "message": f"Updated {len(entries)} entries for {server_name}"})
|
|
|
|
@app.route('/delete', methods=['POST'])
|
|
def delete_server():
|
|
"""Delete a server from the dashboard"""
|
|
data = request.json
|
|
if not data or "server" not in data:
|
|
return jsonify({"status": "error", "message": "Server name required"}), 400
|
|
|
|
server_name = data["server"]
|
|
|
|
# Remove from both stores and timestamps
|
|
caddy_removed = server_name in caddy_proxies
|
|
nginx_removed = server_name in nginx_proxies
|
|
|
|
if server_name in caddy_proxies:
|
|
del caddy_proxies[server_name]
|
|
|
|
if server_name in nginx_proxies:
|
|
del nginx_proxies[server_name]
|
|
|
|
if server_name in timestamps:
|
|
del timestamps[server_name]
|
|
|
|
if not caddy_removed and not nginx_removed:
|
|
return jsonify({"status": "error", "message": f"Server {server_name} not found"}), 404
|
|
|
|
logger.info(f"Deleted server: {server_name}")
|
|
return jsonify({"status": "success", "message": f"Server {server_name} deleted"})
|
|
|
|
# Initialize with local files if available
|
|
if USE_LOCAL_CADDYFILE:
|
|
entries = parse_local_caddyfile()
|
|
if entries:
|
|
caddy_proxies[SERVER_NAME] = entries
|
|
timestamps[SERVER_NAME] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
logger.info(f"Loaded {len(entries)} entries from local Caddyfile")
|
|
|
|
if USE_LOCAL_NGINX:
|
|
entries = parse_nginx_configs()
|
|
if entries:
|
|
nginx_proxies[f"{SERVER_NAME} Nginx"] = entries
|
|
timestamps[f"{SERVER_NAME} Nginx"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
logger.info(f"Loaded {len(entries)} entries from local Nginx configs")
|
|
|
|
def signal_handler(sig, frame):
|
|
logger.info("Shutdown signal received, exiting gracefully...")
|
|
sys.exit(0)
|
|
|
|
signal.signal(signal.SIGTERM, signal_handler)
|
|
signal.signal(signal.SIGINT, signal_handler)
|
|
|
|
if __name__ == '__main__':
|
|
if USE_LOCAL_CADDYFILE:
|
|
logger.info(f"Local Caddyfile found at {CADDYFILE_PATH} - will display its data")
|
|
# Load it initially
|
|
local_data = parse_local_caddyfile()
|
|
if local_data:
|
|
caddy_proxies[SERVER_NAME] = local_data
|
|
timestamps[SERVER_NAME] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
if not API_KEY:
|
|
logger.warning("API_KEY not set - running without authentication!")
|
|
|
|
# Use HTTPS in production
|
|
if DEBUG_MODE:
|
|
app.run(host='0.0.0.0', port=5000, debug=True)
|
|
else:
|
|
app.run(host='0.0.0.0', port=5000)
|