Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Add file manager and FTP server backend and frontend

Juan Denis12a969bf8026
diff --git a/README.md b/README.md
index 4617cb15..f4bc527e 100644
--- a/README.md
+++ b/README.md
@@ -24,12 +24,6 @@ ServerKit is a lightweight, modern server control panel for managing web applica
---
-## Screenshots
-
-*(Coming soon)*
-
----
-
## Tech Stack
| Layer | Technology |
@@ -77,9 +71,16 @@ npm run dev
### Production Installation
+Install command:
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/jhd3197/serverkit/main/install.sh | bash
+```
+
+Update command:
+
```bash
-# One-liner installation (coming soon)
-curl -sSL https://get.serverkit.io | bash
+curl -fsSL https://raw.githubusercontent.com/jhd3197/serverkit/main/install.sh | bash
```
---
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 61b6f6a0..8605eb20 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -91,6 +91,14 @@ def create_app(config_name=None):
from app.api.deploy import deploy_bp
app.register_blueprint(deploy_bp, url_prefix='/api/v1/deploy')
+ # Register blueprints - File Manager
+ from app.api.files import files_bp
+ app.register_blueprint(files_bp, url_prefix='/api/v1/files')
+
+ # Register blueprints - FTP Server
+ from app.api.ftp import ftp_bp
+ app.register_blueprint(ftp_bp, url_prefix='/api/v1/ftp')
+
# Create database tables
with app.app_context():
db.create_all()
diff --git a/backend/app/api/files.py b/backend/app/api/files.py
new file mode 100644
index 00000000..291fc23b
--- /dev/null
+++ b/backend/app/api/files.py
@@ -0,0 +1,372 @@
+"""File Manager API endpoints for browsing, editing, and managing files."""
+
+from flask import Blueprint, request, jsonify, send_file
+from flask_jwt_extended import jwt_required
+from ..services.file_service import FileService
+import os
+import tempfile
+
+files_bp = Blueprint('files', __name__)
+
+
+@files_bp.route('/browse', methods=['GET'])
+@jwt_required()
+def browse_directory():
+ """List directory contents."""
+ path = request.args.get('path', '/home')
+ show_hidden = request.args.get('show_hidden', 'false').lower() == 'true'
+
+ result = FileService.list_directory(path, show_hidden=show_hidden)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@files_bp.route('/info', methods=['GET'])
+@jwt_required()
+def get_file_info():
+ """Get information about a file or directory."""
+ path = request.args.get('path')
+
+ if not path:
+ return jsonify({'success': False, 'error': 'Path is required'}), 400
+
+ if not FileService.is_path_allowed(path):
+ return jsonify({'success': False, 'error': 'Access denied'}), 403
+
+ info = FileService.get_file_info(path)
+
+ if info and 'error' not in info:
+ return jsonify({'success': True, 'file': info}), 200
+
+ error = info.get('error', 'File not found') if info else 'File not found'
+ return jsonify({'success': False, 'error': error}), 404
+
+
+@files_bp.route('/read', methods=['GET'])
+@jwt_required()
+def read_file():
+ """Read file contents."""
+ path = request.args.get('path')
+
+ if not path:
+ return jsonify({'success': False, 'error': 'Path is required'}), 400
+
+ result = FileService.read_file(path)
+
+ if result.get('success'):
+ return jsonify(result), 200
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/write', methods=['POST'])
+@jwt_required()
+def write_file():
+ """Write content to a file."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body is required'}), 400
+
+ path = data.get('path')
+ content = data.get('content')
+ create_backup = data.get('create_backup', True)
+
+ if not path:
+ return jsonify({'success': False, 'error': 'Path is required'}), 400
+
+ if content is None:
+ return jsonify({'success': False, 'error': 'Content is required'}), 400
+
+ result = FileService.write_file(path, content, create_backup=create_backup)
+
+ if result.get('success'):
+ return jsonify(result), 200
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/create', methods=['POST'])
+@jwt_required()
+def create_file():
+ """Create a new file."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body is required'}), 400
+
+ path = data.get('path')
+ content = data.get('content', '')
+
+ if not path:
+ return jsonify({'success': False, 'error': 'Path is required'}), 400
+
+ result = FileService.create_file(path, content)
+
+ if result.get('success'):
+ return jsonify(result), 201
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/mkdir', methods=['POST'])
+@jwt_required()
+def create_directory():
+ """Create a new directory."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body is required'}), 400
+
+ path = data.get('path')
+
+ if not path:
+ return jsonify({'success': False, 'error': 'Path is required'}), 400
+
+ result = FileService.create_directory(path)
+
+ if result.get('success'):
+ return jsonify(result), 201
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/delete', methods=['DELETE'])
+@jwt_required()
+def delete_path():
+ """Delete a file or directory."""
+ path = request.args.get('path')
+
+ if not path:
+ return jsonify({'success': False, 'error': 'Path is required'}), 400
+
+ result = FileService.delete(path)
+
+ if result.get('success'):
+ return jsonify(result), 200
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/rename', methods=['POST'])
+@jwt_required()
+def rename_path():
+ """Rename a file or directory."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body is required'}), 400
+
+ path = data.get('path')
+ new_name = data.get('new_name')
+
+ if not path or not new_name:
+ return jsonify({'success': False, 'error': 'Path and new_name are required'}), 400
+
+ result = FileService.rename(path, new_name)
+
+ if result.get('success'):
+ return jsonify(result), 200
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/copy', methods=['POST'])
+@jwt_required()
+def copy_path():
+ """Copy a file or directory."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body is required'}), 400
+
+ src = data.get('src')
+ dest = data.get('dest')
+
+ if not src or not dest:
+ return jsonify({'success': False, 'error': 'Source and destination paths are required'}), 400
+
+ result = FileService.copy(src, dest)
+
+ if result.get('success'):
+ return jsonify(result), 200
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/move', methods=['POST'])
+@jwt_required()
+def move_path():
+ """Move a file or directory."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body is required'}), 400
+
+ src = data.get('src')
+ dest = data.get('dest')
+
+ if not src or not dest:
+ return jsonify({'success': False, 'error': 'Source and destination paths are required'}), 400
+
+ result = FileService.move(src, dest)
+
+ if result.get('success'):
+ return jsonify(result), 200
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/chmod', methods=['POST'])
+@jwt_required()
+def change_permissions():
+ """Change file/directory permissions."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body is required'}), 400
+
+ path = data.get('path')
+ mode = data.get('mode')
+
+ if not path or not mode:
+ return jsonify({'success': False, 'error': 'Path and mode are required'}), 400
+
+ result = FileService.change_permissions(path, mode)
+
+ if result.get('success'):
+ return jsonify(result), 200
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/search', methods=['GET'])
+@jwt_required()
+def search_files():
+ """Search for files matching a pattern."""
+ directory = request.args.get('directory', '/home')
+ pattern = request.args.get('pattern')
+ max_results = request.args.get('max_results', 100, type=int)
+
+ if not pattern:
+ return jsonify({'success': False, 'error': 'Search pattern is required'}), 400
+
+ result = FileService.search(directory, pattern, max_results=max_results)
+
+ if result.get('success'):
+ return jsonify(result), 200
+
+ status = 403 if 'denied' in result.get('error', '').lower() else 400
+ return jsonify(result), status
+
+
+@files_bp.route('/disk-usage', methods=['GET'])
+@jwt_required()
+def get_disk_usage():
+ """Get disk usage for a path."""
+ path = request.args.get('path', '/')
+
+ result = FileService.get_disk_usage(path)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@files_bp.route('/download', methods=['GET'])
+@jwt_required()
+def download_file():
+ """Download a file."""
+ path = request.args.get('path')
+
+ if not path:
+ return jsonify({'success': False, 'error': 'Path is required'}), 400
+
+ if not FileService.is_path_allowed(path):
+ return jsonify({'success': False, 'error': 'Access denied'}), 403
+
+ if not os.path.exists(path):
+ return jsonify({'success': False, 'error': 'File not found'}), 404
+
+ if os.path.isdir(path):
+ return jsonify({'success': False, 'error': 'Cannot download directory'}), 400
+
+ try:
+ return send_file(
+ path,
+ as_attachment=True,
+ download_name=os.path.basename(path)
+ )
+ except Exception as e:
+ return jsonify({'success': False, 'error': str(e)}), 500
+
+
+@files_bp.route('/upload', methods=['POST'])
+@jwt_required()
+def upload_file():
+ """Upload a file."""
+ if 'file' not in request.files:
+ return jsonify({'success': False, 'error': 'No file provided'}), 400
+
+ file = request.files['file']
+ destination = request.form.get('destination')
+
+ if not destination:
+ return jsonify({'success': False, 'error': 'Destination path is required'}), 400
+
+ if not FileService.is_path_allowed(destination):
+ return jsonify({'success': False, 'error': 'Access denied'}), 403
+
+ if file.filename == '':
+ return jsonify({'success': False, 'error': 'No file selected'}), 400
+
+ # Check file size
+ file.seek(0, 2)
+ size = file.tell()
+ file.seek(0)
+
+ if size > FileService.MAX_UPLOAD_SIZE:
+ return jsonify({
+ 'success': False,
+ 'error': f'File too large. Maximum size is {FileService._format_size(FileService.MAX_UPLOAD_SIZE)}'
+ }), 400
+
+ try:
+ # Determine full path
+ if os.path.isdir(destination):
+ full_path = os.path.join(destination, file.filename)
+ else:
+ full_path = destination
+
+ if not FileService.is_path_allowed(full_path):
+ return jsonify({'success': False, 'error': 'Access denied'}), 403
+
+ # Ensure parent directory exists
+ parent = os.path.dirname(full_path)
+ if not os.path.exists(parent):
+ os.makedirs(parent)
+
+ # Save file
+ file.save(full_path)
+
+ return jsonify({
+ 'success': True,
+ 'path': full_path,
+ 'size': size
+ }), 201
+
+ except PermissionError:
+ return jsonify({'success': False, 'error': 'Permission denied'}), 403
+ except Exception as e:
+ return jsonify({'success': False, 'error': str(e)}), 500
diff --git a/backend/app/api/ftp.py b/backend/app/api/ftp.py
new file mode 100644
index 00000000..87d084e3
--- /dev/null
+++ b/backend/app/api/ftp.py
@@ -0,0 +1,223 @@
+"""FTP Server API endpoints for managing FTP services and users."""
+
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required
+from ..services.ftp_service import FTPService
+
+ftp_bp = Blueprint('ftp', __name__)
+
+
+@ftp_bp.route('/status', methods=['GET'])
+@jwt_required()
+def get_status():
+ """Get FTP server status."""
+ result = FTPService.get_status()
+ return jsonify(result), 200
+
+
+@ftp_bp.route('/service/<action>', methods=['POST'])
+@jwt_required()
+def control_service(action):
+ """Start, stop, restart, or reload FTP service."""
+ if action not in ['start', 'stop', 'restart', 'reload']:
+ return jsonify({
+ 'success': False,
+ 'error': 'Invalid action. Use: start, stop, restart, or reload'
+ }), 400
+
+ data = request.get_json() or {}
+ service = data.get('service') # Optional: specify vsftpd or proftpd
+
+ result = FTPService.control_service(service, action)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/config', methods=['GET'])
+@jwt_required()
+def get_config():
+ """Get FTP server configuration."""
+ service = request.args.get('service') # Optional
+ result = FTPService.get_config(service)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/config', methods=['POST'])
+@jwt_required()
+def update_config():
+ """Update FTP server configuration."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body is required'}), 400
+
+ service = data.get('service')
+ config_content = data.get('config')
+
+ if not config_content:
+ return jsonify({'success': False, 'error': 'Configuration content is required'}), 400
+
+ result = FTPService.update_config(service, config_content)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/users', methods=['GET'])
+@jwt_required()
+def list_users():
+ """List FTP users."""
+ result = FTPService.list_users()
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/users', methods=['POST'])
+@jwt_required()
+def create_user():
+ """Create a new FTP user."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'success': False, 'error': 'Request body is required'}), 400
+
+ username = data.get('username')
+ password = data.get('password') # Optional, can be auto-generated
+ home_dir = data.get('home_dir') # Optional
+
+ if not username:
+ return jsonify({'success': False, 'error': 'Username is required'}), 400
+
+ # Validate username
+ if not username.isalnum() and '_' not in username:
+ return jsonify({
+ 'success': False,
+ 'error': 'Username must contain only alphanumeric characters and underscores'
+ }), 400
+
+ result = FTPService.create_user(username, password, home_dir)
+
+ if result.get('success'):
+ return jsonify(result), 201
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/users/<username>', methods=['DELETE'])
+@jwt_required()
+def delete_user(username):
+ """Delete an FTP user."""
+ delete_home = request.args.get('delete_home', 'false').lower() == 'true'
+
+ result = FTPService.delete_user(username, delete_home=delete_home)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/users/<username>/password', methods=['POST'])
+@jwt_required()
+def change_password(username):
+ """Change FTP user password."""
+ data = request.get_json() or {}
+ new_password = data.get('password') # Optional, can be auto-generated
+
+ result = FTPService.change_password(username, new_password)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/users/<username>/toggle', methods=['POST'])
+@jwt_required()
+def toggle_user(username):
+ """Enable or disable an FTP user."""
+ data = request.get_json() or {}
+ enabled = data.get('enabled', True)
+
+ result = FTPService.toggle_user(username, enabled)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/connections', methods=['GET'])
+@jwt_required()
+def get_connections():
+ """Get active FTP connections."""
+ result = FTPService.get_connections()
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/connections/<int:pid>', methods=['DELETE'])
+@jwt_required()
+def disconnect_user(pid):
+ """Disconnect an active FTP session."""
+ result = FTPService.disconnect_session(pid)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/logs', methods=['GET'])
+@jwt_required()
+def get_logs():
+ """Get FTP server logs."""
+ lines = request.args.get('lines', 100, type=int)
+
+ result = FTPService.get_logs(lines)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/install', methods=['POST'])
+@jwt_required()
+def install_ftp():
+ """Install FTP server (vsftpd or proftpd)."""
+ data = request.get_json() or {}
+ service = data.get('service', 'vsftpd')
+
+ if service not in ['vsftpd', 'proftpd']:
+ return jsonify({
+ 'success': False,
+ 'error': 'Invalid service. Use: vsftpd or proftpd'
+ }), 400
+
+ result = FTPService.install_ftp_server(service)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
+
+
+@ftp_bp.route('/test', methods=['POST'])
+@jwt_required()
+def test_connection():
+ """Test FTP connection."""
+ data = request.get_json() or {}
+ host = data.get('host', 'localhost')
+ port = data.get('port', 21)
+ username = data.get('username')
+ password = data.get('password')
+
+ result = FTPService.test_connection(host, port, username, password)
+
+ if result.get('success'):
+ return jsonify(result), 200
+ return jsonify(result), 400
diff --git a/backend/app/services/file_service.py b/backend/app/services/file_service.py
new file mode 100644
index 00000000..916fc83a
--- /dev/null
+++ b/backend/app/services/file_service.py
@@ -0,0 +1,457 @@
+"""File management service for browsing, editing, and managing files."""
+
+import os
+import shutil
+import stat
+import mimetypes
+import hashlib
+from pathlib import Path
+from typing import Dict, List, Optional, Tuple
+from datetime import datetime
+import pwd
+import grp
+
+
+class FileService:
+ """Service for file system operations."""
+
+ # Allowed root directories for browsing (security)
+ ALLOWED_ROOTS = ['/home', '/var/www', '/opt', '/srv', '/var/log']
+
+ # File extensions that can be edited in browser
+ EDITABLE_EXTENSIONS = {
+ '.txt', '.md', '.json', '.xml', '.yml', '.yaml', '.ini', '.conf', '.cfg',
+ '.py', '.js', '.jsx', '.ts', '.tsx', '.html', '.css', '.less', '.scss',
+ '.php', '.rb', '.go', '.rs', '.java', '.c', '.cpp', '.h', '.sh', '.bash',
+ '.sql', '.env', '.htaccess', '.gitignore', '.dockerfile', '.toml'
+ }
+
+ # Maximum file size for editing (5MB)
+ MAX_EDIT_SIZE = 5 * 1024 * 1024
+
+ # Maximum file size for upload (100MB)
+ MAX_UPLOAD_SIZE = 100 * 1024 * 1024
+
+ @classmethod
+ def is_path_allowed(cls, path: str) -> bool:
+ """Check if path is within allowed directories."""
+ try:
+ real_path = os.path.realpath(path)
+ return any(real_path.startswith(root) for root in cls.ALLOWED_ROOTS)
+ except (ValueError, OSError):
+ return False
+
+ @classmethod
+ def get_file_info(cls, path: str) -> Optional[Dict]:
+ """Get detailed information about a file or directory."""
+ try:
+ if not os.path.exists(path):
+ return None
+
+ stat_info = os.stat(path)
+ is_dir = os.path.isdir(path)
+
+ # Get owner and group names
+ try:
+ owner = pwd.getpwuid(stat_info.st_uid).pw_name
+ except (KeyError, AttributeError):
+ owner = str(stat_info.st_uid)
+
+ try:
+ group = grp.getgrgid(stat_info.st_gid).gr_name
+ except (KeyError, AttributeError):
+ group = str(stat_info.st_gid)
+
+ # Get permissions string
+ mode = stat_info.st_mode
+ perms = stat.filemode(mode)
+
+ # Get MIME type for files
+ mime_type = None
+ if not is_dir:
+ mime_type, _ = mimetypes.guess_type(path)
+
+ return {
+ 'name': os.path.basename(path),
+ 'path': path,
+ 'is_dir': is_dir,
+ 'is_file': not is_dir,
+ 'is_link': os.path.islink(path),
+ 'size': stat_info.st_size if not is_dir else cls._get_dir_size(path),
+ 'size_human': cls._format_size(stat_info.st_size),
+ 'modified': datetime.fromtimestamp(stat_info.st_mtime).isoformat(),
+ 'created': datetime.fromtimestamp(stat_info.st_ctime).isoformat(),
+ 'accessed': datetime.fromtimestamp(stat_info.st_atime).isoformat(),
+ 'permissions': perms,
+ 'permissions_octal': oct(mode)[-3:],
+ 'owner': owner,
+ 'group': group,
+ 'mime_type': mime_type,
+ 'is_editable': cls._is_editable(path),
+ 'is_readable': os.access(path, os.R_OK),
+ 'is_writable': os.access(path, os.W_OK),
+ 'is_executable': os.access(path, os.X_OK),
+ }
+ except (OSError, PermissionError) as e:
+ return {'error': str(e), 'path': path}
+
+ @classmethod
+ def list_directory(cls, path: str, show_hidden: bool = False) -> Dict:
+ """List contents of a directory."""
+ if not cls.is_path_allowed(path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if not os.path.exists(path):
+ return {'success': False, 'error': 'Directory not found'}
+
+ if not os.path.isdir(path):
+ return {'success': False, 'error': 'Not a directory'}
+
+ try:
+ entries = []
+ for name in os.listdir(path):
+ if not show_hidden and name.startswith('.'):
+ continue
+
+ full_path = os.path.join(path, name)
+ info = cls.get_file_info(full_path)
+ if info:
+ entries.append(info)
+
+ # Sort: directories first, then by name
+ entries.sort(key=lambda x: (not x.get('is_dir', False), x.get('name', '').lower()))
+
+ # Get parent directory
+ parent = os.path.dirname(path)
+ if not cls.is_path_allowed(parent):
+ parent = None
+
+ return {
+ 'success': True,
+ 'path': path,
+ 'parent': parent,
+ 'entries': entries,
+ 'total': len(entries)
+ }
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def read_file(cls, path: str) -> Dict:
+ """Read file contents."""
+ if not cls.is_path_allowed(path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if not os.path.exists(path):
+ return {'success': False, 'error': 'File not found'}
+
+ if os.path.isdir(path):
+ return {'success': False, 'error': 'Cannot read directory'}
+
+ try:
+ size = os.path.getsize(path)
+ if size > cls.MAX_EDIT_SIZE:
+ return {
+ 'success': False,
+ 'error': f'File too large to edit ({cls._format_size(size)}). Maximum is {cls._format_size(cls.MAX_EDIT_SIZE)}'
+ }
+
+ # Try to read as text
+ try:
+ with open(path, 'r', encoding='utf-8') as f:
+ content = f.read()
+ return {
+ 'success': True,
+ 'path': path,
+ 'content': content,
+ 'encoding': 'utf-8',
+ 'size': size,
+ 'is_binary': False
+ }
+ except UnicodeDecodeError:
+ # File is binary
+ return {
+ 'success': False,
+ 'error': 'Binary file cannot be edited',
+ 'is_binary': True
+ }
+
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def write_file(cls, path: str, content: str, create_backup: bool = True) -> Dict:
+ """Write content to file."""
+ if not cls.is_path_allowed(path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ try:
+ # Create backup if file exists
+ if create_backup and os.path.exists(path):
+ backup_path = f"{path}.bak"
+ shutil.copy2(path, backup_path)
+
+ # Write file
+ with open(path, 'w', encoding='utf-8') as f:
+ f.write(content)
+
+ return {
+ 'success': True,
+ 'path': path,
+ 'size': len(content.encode('utf-8'))
+ }
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def create_file(cls, path: str, content: str = '') -> Dict:
+ """Create a new file."""
+ if not cls.is_path_allowed(path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if os.path.exists(path):
+ return {'success': False, 'error': 'File already exists'}
+
+ try:
+ # Ensure parent directory exists
+ parent = os.path.dirname(path)
+ if not os.path.exists(parent):
+ os.makedirs(parent)
+
+ with open(path, 'w', encoding='utf-8') as f:
+ f.write(content)
+
+ return {'success': True, 'path': path}
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def create_directory(cls, path: str) -> Dict:
+ """Create a new directory."""
+ if not cls.is_path_allowed(path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if os.path.exists(path):
+ return {'success': False, 'error': 'Directory already exists'}
+
+ try:
+ os.makedirs(path)
+ return {'success': True, 'path': path}
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def delete(cls, path: str) -> Dict:
+ """Delete a file or directory."""
+ if not cls.is_path_allowed(path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if not os.path.exists(path):
+ return {'success': False, 'error': 'Path not found'}
+
+ try:
+ if os.path.isdir(path):
+ shutil.rmtree(path)
+ else:
+ os.remove(path)
+ return {'success': True, 'path': path}
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def rename(cls, old_path: str, new_name: str) -> Dict:
+ """Rename a file or directory."""
+ if not cls.is_path_allowed(old_path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if not os.path.exists(old_path):
+ return {'success': False, 'error': 'Path not found'}
+
+ new_path = os.path.join(os.path.dirname(old_path), new_name)
+
+ if not cls.is_path_allowed(new_path):
+ return {'success': False, 'error': 'Access denied: target path not allowed'}
+
+ if os.path.exists(new_path):
+ return {'success': False, 'error': 'Target already exists'}
+
+ try:
+ os.rename(old_path, new_path)
+ return {'success': True, 'old_path': old_path, 'new_path': new_path}
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def copy(cls, src_path: str, dest_path: str) -> Dict:
+ """Copy a file or directory."""
+ if not cls.is_path_allowed(src_path) or not cls.is_path_allowed(dest_path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if not os.path.exists(src_path):
+ return {'success': False, 'error': 'Source not found'}
+
+ if os.path.exists(dest_path):
+ return {'success': False, 'error': 'Destination already exists'}
+
+ try:
+ if os.path.isdir(src_path):
+ shutil.copytree(src_path, dest_path)
+ else:
+ shutil.copy2(src_path, dest_path)
+ return {'success': True, 'src': src_path, 'dest': dest_path}
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def move(cls, src_path: str, dest_path: str) -> Dict:
+ """Move a file or directory."""
+ if not cls.is_path_allowed(src_path) or not cls.is_path_allowed(dest_path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if not os.path.exists(src_path):
+ return {'success': False, 'error': 'Source not found'}
+
+ if os.path.exists(dest_path):
+ return {'success': False, 'error': 'Destination already exists'}
+
+ try:
+ shutil.move(src_path, dest_path)
+ return {'success': True, 'src': src_path, 'dest': dest_path}
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def change_permissions(cls, path: str, mode: str) -> Dict:
+ """Change file/directory permissions."""
+ if not cls.is_path_allowed(path):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if not os.path.exists(path):
+ return {'success': False, 'error': 'Path not found'}
+
+ try:
+ # Convert octal string to int
+ mode_int = int(mode, 8)
+ os.chmod(path, mode_int)
+ return {'success': True, 'path': path, 'mode': mode}
+ except ValueError:
+ return {'success': False, 'error': 'Invalid permission mode'}
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def search(cls, directory: str, pattern: str, max_results: int = 100) -> Dict:
+ """Search for files matching pattern."""
+ if not cls.is_path_allowed(directory):
+ return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+
+ if not os.path.isdir(directory):
+ return {'success': False, 'error': 'Directory not found'}
+
+ try:
+ results = []
+ pattern_lower = pattern.lower()
+
+ for root, dirs, files in os.walk(directory):
+ # Skip hidden directories
+ dirs[:] = [d for d in dirs if not d.startswith('.')]
+
+ for name in files + dirs:
+ if pattern_lower in name.lower():
+ full_path = os.path.join(root, name)
+ if cls.is_path_allowed(full_path):
+ info = cls.get_file_info(full_path)
+ if info:
+ results.append(info)
+ if len(results) >= max_results:
+ return {
+ 'success': True,
+ 'results': results,
+ 'truncated': True
+ }
+
+ return {'success': True, 'results': results, 'truncated': False}
+ except PermissionError:
+ return {'success': False, 'error': 'Permission denied'}
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_disk_usage(cls, path: str) -> Dict:
+ """Get disk usage for a path."""
+ try:
+ usage = shutil.disk_usage(path)
+ return {
+ 'success': True,
+ 'total': usage.total,
+ 'used': usage.used,
+ 'free': usage.free,
+ 'percent': round((usage.used / usage.total) * 100, 1),
+ 'total_human': cls._format_size(usage.total),
+ 'used_human': cls._format_size(usage.used),
+ 'free_human': cls._format_size(usage.free)
+ }
+ except OSError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _is_editable(cls, path: str) -> bool:
+ """Check if file can be edited in browser."""
+ if os.path.isdir(path):
+ return False
+
+ ext = os.path.splitext(path)[1].lower()
+ if ext in cls.EDITABLE_EXTENSIONS:
+ return os.path.getsize(path) <= cls.MAX_EDIT_SIZE
+
+ # Check if file has no extension but is text
+ if not ext:
+ try:
+ with open(path, 'r', encoding='utf-8') as f:
+ f.read(1024)
+ return os.path.getsize(path) <= cls.MAX_EDIT_SIZE
+ except (UnicodeDecodeError, PermissionError):
+ return False
+
+ return False
+
+ @classmethod
+ def _get_dir_size(cls, path: str) -> int:
+ """Get total size of directory (non-recursive for performance)."""
+ try:
+ total = 0
+ for entry in os.scandir(path):
+ if entry.is_file():
+ total += entry.stat().st_size
+ return total
+ except (OSError, PermissionError):
+ return 0
+
+ @staticmethod
+ def _format_size(size: int) -> str:
+ """Format size in human-readable format."""
+ for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
+ if size < 1024:
+ return f"{size:.1f} {unit}"
+ size /= 1024
+ return f"{size:.1f} PB"
diff --git a/backend/app/services/ftp_service.py b/backend/app/services/ftp_service.py
new file mode 100644
index 00000000..3c11e4db
--- /dev/null
+++ b/backend/app/services/ftp_service.py
@@ -0,0 +1,721 @@
+"""FTP server management service for vsftpd and proftpd."""
+
+import os
+import subprocess
+import re
+import pwd
+import crypt
+import secrets
+from typing import Dict, List, Optional
+from datetime import datetime
+
+
+class FTPService:
+ """Service for managing FTP servers (vsftpd, proftpd)."""
+
+ # Configuration file locations
+ VSFTPD_CONF = '/etc/vsftpd.conf'
+ VSFTPD_USER_LIST = '/etc/vsftpd.userlist'
+ PROFTPD_CONF = '/etc/proftpd/proftpd.conf'
+
+ # FTP user home base directory
+ FTP_HOME_BASE = '/home/ftp'
+
+ @classmethod
+ def get_status(cls) -> Dict:
+ """Get FTP server status and information."""
+ vsftpd = cls._check_service('vsftpd')
+ proftpd = cls._check_service('proftpd')
+
+ # Determine which server is installed/active
+ active_server = None
+ if vsftpd['installed'] and vsftpd['running']:
+ active_server = 'vsftpd'
+ elif proftpd['installed'] and proftpd['running']:
+ active_server = 'proftpd'
+ elif vsftpd['installed']:
+ active_server = 'vsftpd'
+ elif proftpd['installed']:
+ active_server = 'proftpd'
+
+ return {
+ 'vsftpd': vsftpd,
+ 'proftpd': proftpd,
+ 'active_server': active_server,
+ 'any_installed': vsftpd['installed'] or proftpd['installed'],
+ 'any_running': vsftpd['running'] or proftpd['running']
+ }
+
+ @classmethod
+ def _check_service(cls, service: str) -> Dict:
+ """Check if a service is installed and running."""
+ installed = False
+ running = False
+ enabled = False
+ version = None
+
+ try:
+ # Check if installed
+ result = subprocess.run(
+ ['which', service if service != 'proftpd' else 'proftpd'],
+ capture_output=True, text=True
+ )
+ installed = result.returncode == 0
+
+ if not installed:
+ # Try checking if package is installed
+ result = subprocess.run(
+ ['dpkg', '-l', service],
+ capture_output=True, text=True
+ )
+ installed = 'ii' in result.stdout
+
+ if installed:
+ # Check if running
+ result = subprocess.run(
+ ['systemctl', 'is-active', service],
+ capture_output=True, text=True
+ )
+ running = result.stdout.strip() == 'active'
+
+ # Check if enabled
+ result = subprocess.run(
+ ['systemctl', 'is-enabled', service],
+ capture_output=True, text=True
+ )
+ enabled = result.stdout.strip() == 'enabled'
+
+ # Get version
+ if service == 'vsftpd':
+ result = subprocess.run(
+ ['vsftpd', '-v'],
+ capture_output=True, text=True, stderr=subprocess.STDOUT
+ )
+ version_match = re.search(r'version (\d+\.\d+\.\d+)', result.stdout)
+ if version_match:
+ version = version_match.group(1)
+ elif service == 'proftpd':
+ result = subprocess.run(
+ ['proftpd', '-v'],
+ capture_output=True, text=True
+ )
+ version_match = re.search(r'ProFTPD Version (\d+\.\d+\.\d+)', result.stdout)
+ if version_match:
+ version = version_match.group(1)
+
+ except (subprocess.SubprocessError, FileNotFoundError):
+ pass
+
+ return {
+ 'installed': installed,
+ 'running': running,
+ 'enabled': enabled,
+ 'version': version
+ }
+
+ @classmethod
+ def control_service(cls, service: str, action: str) -> Dict:
+ """Control FTP service (start, stop, restart, enable, disable)."""
+ if service not in ['vsftpd', 'proftpd']:
+ return {'success': False, 'error': 'Invalid service name'}
+
+ if action not in ['start', 'stop', 'restart', 'enable', 'disable']:
+ return {'success': False, 'error': 'Invalid action'}
+
+ try:
+ result = subprocess.run(
+ ['sudo', 'systemctl', action, service],
+ capture_output=True, text=True, timeout=30
+ )
+
+ if result.returncode == 0:
+ return {'success': True, 'service': service, 'action': action}
+ else:
+ return {'success': False, 'error': result.stderr or 'Operation failed'}
+
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Operation timed out'}
+ except subprocess.SubprocessError as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_config(cls, service: str = None) -> Dict:
+ """Get FTP server configuration."""
+ if service is None:
+ status = cls.get_status()
+ service = status['active_server']
+
+ if service == 'vsftpd':
+ return cls._get_vsftpd_config()
+ elif service == 'proftpd':
+ return cls._get_proftpd_config()
+ else:
+ return {'success': False, 'error': 'No FTP server found'}
+
+ @classmethod
+ def _get_vsftpd_config(cls) -> Dict:
+ """Parse vsftpd configuration."""
+ if not os.path.exists(cls.VSFTPD_CONF):
+ return {'success': False, 'error': 'vsftpd.conf not found'}
+
+ try:
+ config = {}
+ with open(cls.VSFTPD_CONF, 'r') as f:
+ for line in f:
+ line = line.strip()
+ if line and not line.startswith('#'):
+ if '=' in line:
+ key, value = line.split('=', 1)
+ config[key.strip()] = value.strip()
+
+ return {
+ 'success': True,
+ 'service': 'vsftpd',
+ 'config_file': cls.VSFTPD_CONF,
+ 'config': config,
+ 'settings': {
+ 'anonymous_enable': config.get('anonymous_enable', 'NO') == 'YES',
+ 'local_enable': config.get('local_enable', 'NO') == 'YES',
+ 'write_enable': config.get('write_enable', 'NO') == 'YES',
+ 'chroot_local_user': config.get('chroot_local_user', 'NO') == 'YES',
+ 'ssl_enable': config.get('ssl_enable', 'NO') == 'YES',
+ 'pasv_enable': config.get('pasv_enable', 'YES') == 'YES',
+ 'listen_port': int(config.get('listen_port', 21)),
+ 'max_clients': int(config.get('max_clients', 0)),
+ 'max_per_ip': int(config.get('max_per_ip', 0)),
+ 'local_umask': config.get('local_umask', '022'),
+ }
+ }
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _get_proftpd_config(cls) -> Dict:
+ """Parse proftpd configuration."""
+ if not os.path.exists(cls.PROFTPD_CONF):
+ return {'success': False, 'error': 'proftpd.conf not found'}
+
+ try:
+ config = {}
+ with open(cls.PROFTPD_CONF, 'r') as f:
+ content = f.read()
+
+ # Parse basic directives
+ directives = [
+ 'ServerName', 'ServerType', 'Port', 'MaxClients',
+ 'MaxClientsPerHost', 'DefaultRoot', 'RequireValidShell'
+ ]
+ for directive in directives:
+ match = re.search(rf'^{directive}\s+(.+)$', content, re.MULTILINE)
+ if match:
+ config[directive] = match.group(1).strip().strip('"')
+
+ return {
+ 'success': True,
+ 'service': 'proftpd',
+ 'config_file': cls.PROFTPD_CONF,
+ 'config': config,
+ 'settings': {
+ 'server_name': config.get('ServerName', 'ProFTPD'),
+ 'port': int(config.get('Port', 21)),
+ 'max_clients': int(config.get('MaxClients', 0)) if config.get('MaxClients') else 0,
+ 'max_per_ip': int(config.get('MaxClientsPerHost', 0)) if config.get('MaxClientsPerHost') else 0,
+ 'default_root': config.get('DefaultRoot', '~'),
+ 'require_valid_shell': config.get('RequireValidShell', 'on') == 'on',
+ }
+ }
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def update_config(cls, service: str, settings: Dict) -> Dict:
+ """Update FTP server configuration."""
+ if service == 'vsftpd':
+ return cls._update_vsftpd_config(settings)
+ elif service == 'proftpd':
+ return cls._update_proftpd_config(settings)
+ else:
+ return {'success': False, 'error': 'Invalid service'}
+
+ @classmethod
+ def _update_vsftpd_config(cls, settings: Dict) -> Dict:
+ """Update vsftpd configuration."""
+ if not os.path.exists(cls.VSFTPD_CONF):
+ return {'success': False, 'error': 'vsftpd.conf not found'}
+
+ try:
+ # Read current config
+ with open(cls.VSFTPD_CONF, 'r') as f:
+ lines = f.readlines()
+
+ # Map settings to config keys
+ mapping = {
+ 'anonymous_enable': ('anonymous_enable', lambda v: 'YES' if v else 'NO'),
+ 'local_enable': ('local_enable', lambda v: 'YES' if v else 'NO'),
+ 'write_enable': ('write_enable', lambda v: 'YES' if v else 'NO'),
+ 'chroot_local_user': ('chroot_local_user', lambda v: 'YES' if v else 'NO'),
+ 'ssl_enable': ('ssl_enable', lambda v: 'YES' if v else 'NO'),
+ 'listen_port': ('listen_port', str),
+ 'max_clients': ('max_clients', str),
+ 'max_per_ip': ('max_per_ip', str),
+ 'local_umask': ('local_umask', str),
+ }
+
+ # Update lines
+ updated_keys = set()
+ for i, line in enumerate(lines):
+ stripped = line.strip()
+ if stripped and not stripped.startswith('#') and '=' in stripped:
+ key = stripped.split('=')[0].strip()
+ for setting_key, (config_key, transform) in mapping.items():
+ if key == config_key and setting_key in settings:
+ lines[i] = f"{config_key}={transform(settings[setting_key])}\n"
+ updated_keys.add(config_key)
+
+ # Add missing settings
+ for setting_key, (config_key, transform) in mapping.items():
+ if setting_key in settings and config_key not in updated_keys:
+ lines.append(f"{config_key}={transform(settings[setting_key])}\n")
+
+ # Write config
+ with open(cls.VSFTPD_CONF, 'w') as f:
+ f.writelines(lines)
+
+ return {'success': True, 'message': 'Configuration updated. Restart vsftpd to apply changes.'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _update_proftpd_config(cls, settings: Dict) -> Dict:
+ """Update proftpd configuration."""
+ # Similar implementation for proftpd
+ return {'success': False, 'error': 'ProFTPD configuration update not yet implemented'}
+
+ @classmethod
+ def list_users(cls) -> Dict:
+ """List FTP users."""
+ try:
+ users = []
+
+ # Get system users that have FTP access
+ # Check vsftpd userlist if exists
+ allowed_users = set()
+ if os.path.exists(cls.VSFTPD_USER_LIST):
+ with open(cls.VSFTPD_USER_LIST, 'r') as f:
+ allowed_users = set(line.strip() for line in f if line.strip())
+
+ # Get users from /etc/passwd with home in FTP directories
+ for user in pwd.getpwall():
+ # Skip system users
+ if user.pw_uid < 1000 or user.pw_uid == 65534:
+ continue
+
+ # Check if user has FTP-related home directory or is in userlist
+ is_ftp_user = (
+ user.pw_dir.startswith(cls.FTP_HOME_BASE) or
+ user.pw_name in allowed_users or
+ '/ftp' in user.pw_dir.lower()
+ )
+
+ if is_ftp_user or allowed_users:
+ home_exists = os.path.exists(user.pw_dir)
+ home_size = 0
+ if home_exists:
+ try:
+ for root, dirs, files in os.walk(user.pw_dir):
+ for f in files:
+ home_size += os.path.getsize(os.path.join(root, f))
+ except (OSError, PermissionError):
+ pass
+
+ users.append({
+ 'username': user.pw_name,
+ 'uid': user.pw_uid,
+ 'gid': user.pw_gid,
+ 'home': user.pw_dir,
+ 'shell': user.pw_shell,
+ 'home_exists': home_exists,
+ 'home_size': home_size,
+ 'home_size_human': cls._format_size(home_size),
+ 'in_userlist': user.pw_name in allowed_users,
+ 'is_active': user.pw_shell not in ['/usr/sbin/nologin', '/bin/false']
+ })
+
+ return {'success': True, 'users': users}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def create_user(cls, username: str, password: str = None, home_dir: str = None) -> Dict:
+ """Create a new FTP user."""
+ # Validate username
+ if not re.match(r'^[a-z][a-z0-9_-]{2,31}$', username):
+ return {'success': False, 'error': 'Invalid username. Use lowercase letters, numbers, underscore, hyphen. 3-32 chars.'}
+
+ # Check if user exists
+ try:
+ pwd.getpwnam(username)
+ return {'success': False, 'error': 'User already exists'}
+ except KeyError:
+ pass
+
+ # Generate password if not provided
+ if not password:
+ password = secrets.token_urlsafe(16)
+
+ # Set home directory
+ if not home_dir:
+ home_dir = os.path.join(cls.FTP_HOME_BASE, username)
+
+ try:
+ # Create user with restricted shell
+ result = subprocess.run([
+ 'sudo', 'useradd',
+ '-m', # Create home directory
+ '-d', home_dir,
+ '-s', '/usr/sbin/nologin', # No shell access
+ '-c', f'FTP User {username}',
+ username
+ ], capture_output=True, text=True)
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Failed to create user'}
+
+ # Set password
+ proc = subprocess.Popen(
+ ['sudo', 'chpasswd'],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE
+ )
+ proc.communicate(input=f'{username}:{password}'.encode())
+
+ # Add to vsftpd userlist if it exists
+ if os.path.exists(cls.VSFTPD_USER_LIST):
+ with open(cls.VSFTPD_USER_LIST, 'a') as f:
+ f.write(f'{username}\n')
+
+ # Set proper permissions on home directory
+ subprocess.run(['sudo', 'chmod', '755', home_dir], capture_output=True)
+
+ return {
+ 'success': True,
+ 'username': username,
+ 'password': password,
+ 'home': home_dir,
+ 'message': 'FTP user created successfully'
+ }
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def delete_user(cls, username: str, delete_home: bool = False) -> Dict:
+ """Delete an FTP user."""
+ try:
+ # Check if user exists
+ try:
+ pwd.getpwnam(username)
+ except KeyError:
+ return {'success': False, 'error': 'User not found'}
+
+ # Delete user
+ cmd = ['sudo', 'userdel']
+ if delete_home:
+ cmd.append('-r')
+ cmd.append(username)
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Failed to delete user'}
+
+ # Remove from vsftpd userlist if exists
+ if os.path.exists(cls.VSFTPD_USER_LIST):
+ with open(cls.VSFTPD_USER_LIST, 'r') as f:
+ users = [line.strip() for line in f if line.strip() != username]
+ with open(cls.VSFTPD_USER_LIST, 'w') as f:
+ f.write('\n'.join(users) + '\n')
+
+ return {'success': True, 'message': f'User {username} deleted'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def change_password(cls, username: str, new_password: str = None) -> Dict:
+ """Change FTP user password."""
+ try:
+ # Check if user exists
+ try:
+ pwd.getpwnam(username)
+ except KeyError:
+ return {'success': False, 'error': 'User not found'}
+
+ # Generate password if not provided
+ if not new_password:
+ new_password = secrets.token_urlsafe(16)
+
+ # Set password
+ proc = subprocess.Popen(
+ ['sudo', 'chpasswd'],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE
+ )
+ stdout, stderr = proc.communicate(input=f'{username}:{new_password}'.encode())
+
+ if proc.returncode != 0:
+ return {'success': False, 'error': stderr.decode() or 'Failed to change password'}
+
+ return {
+ 'success': True,
+ 'username': username,
+ 'password': new_password,
+ 'message': 'Password changed successfully'
+ }
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_connections(cls) -> Dict:
+ """Get active FTP connections."""
+ try:
+ connections = []
+
+ # Check for vsftpd connections
+ result = subprocess.run(
+ ['ss', '-tnp', 'state', 'established', 'sport', '=', ':21'],
+ capture_output=True, text=True
+ )
+
+ for line in result.stdout.strip().split('\n')[1:]: # Skip header
+ if line:
+ parts = line.split()
+ if len(parts) >= 5:
+ local = parts[3]
+ remote = parts[4]
+ connections.append({
+ 'local': local,
+ 'remote': remote,
+ 'state': 'ESTABLISHED'
+ })
+
+ return {'success': True, 'connections': connections, 'count': len(connections)}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_logs(cls, lines: int = 100) -> Dict:
+ """Get FTP server logs."""
+ log_files = [
+ '/var/log/vsftpd.log',
+ '/var/log/proftpd/proftpd.log',
+ '/var/log/xferlog',
+ '/var/log/syslog'
+ ]
+
+ for log_file in log_files:
+ if os.path.exists(log_file):
+ try:
+ result = subprocess.run(
+ ['tail', '-n', str(lines), log_file],
+ capture_output=True, text=True
+ )
+ # Filter FTP-related entries if using syslog
+ log_content = result.stdout
+ if 'syslog' in log_file:
+ log_content = '\n'.join(
+ line for line in log_content.split('\n')
+ if 'ftp' in line.lower() or 'vsftpd' in line.lower() or 'proftpd' in line.lower()
+ )
+
+ return {
+ 'success': True,
+ 'log_file': log_file,
+ 'content': log_content
+ }
+ except Exception as e:
+ continue
+
+ return {'success': False, 'error': 'No FTP log files found'}
+
+ @classmethod
+ def toggle_user(cls, username: str, enabled: bool) -> Dict:
+ """Enable or disable an FTP user."""
+ try:
+ # Check if user exists
+ try:
+ pwd.getpwnam(username)
+ except KeyError:
+ return {'success': False, 'error': 'User not found'}
+
+ if enabled:
+ # Change shell to allow FTP (but still no login)
+ shell = '/usr/sbin/nologin'
+ else:
+ # Change shell to /bin/false to disable
+ shell = '/bin/false'
+
+ result = subprocess.run(
+ ['sudo', 'usermod', '-s', shell, username],
+ capture_output=True, text=True
+ )
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Failed to update user'}
+
+ return {
+ 'success': True,
+ 'username': username,
+ 'enabled': enabled,
+ 'message': f'User {username} {"enabled" if enabled else "disabled"}'
+ }
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def disconnect_session(cls, pid: int) -> Dict:
+ """Disconnect an active FTP session by PID."""
+ try:
+ result = subprocess.run(
+ ['sudo', 'kill', str(pid)],
+ capture_output=True, text=True
+ )
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Failed to disconnect session'}
+
+ return {'success': True, 'message': f'Session {pid} disconnected'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def install_ftp_server(cls, service: str = 'vsftpd') -> Dict:
+ """Install FTP server (vsftpd or proftpd)."""
+ if service not in ['vsftpd', 'proftpd']:
+ return {'success': False, 'error': 'Invalid service. Use vsftpd or proftpd'}
+
+ try:
+ # Update package list
+ subprocess.run(['sudo', 'apt-get', 'update'], capture_output=True, timeout=120)
+
+ # Install the service
+ result = subprocess.run(
+ ['sudo', 'apt-get', 'install', '-y', service],
+ capture_output=True, text=True, timeout=300
+ )
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr or 'Installation failed'}
+
+ # Create FTP home base directory
+ os.makedirs(cls.FTP_HOME_BASE, exist_ok=True)
+
+ # Create default configuration for vsftpd
+ if service == 'vsftpd':
+ default_config = """# vsftpd configuration
+listen=YES
+listen_ipv6=NO
+anonymous_enable=NO
+local_enable=YES
+write_enable=YES
+local_umask=022
+dirmessage_enable=YES
+use_localtime=YES
+xferlog_enable=YES
+connect_from_port_20=YES
+chroot_local_user=YES
+allow_writeable_chroot=YES
+secure_chroot_dir=/var/run/vsftpd/empty
+pam_service_name=vsftpd
+rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
+rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
+ssl_enable=NO
+userlist_enable=YES
+userlist_file=/etc/vsftpd.userlist
+userlist_deny=NO
+"""
+ with open(cls.VSFTPD_CONF, 'w') as f:
+ f.write(default_config)
+
+ # Create empty userlist
+ with open(cls.VSFTPD_USER_LIST, 'w') as f:
+ f.write('')
+
+ # Enable and start the service
+ subprocess.run(['sudo', 'systemctl', 'enable', service], capture_output=True)
+ subprocess.run(['sudo', 'systemctl', 'start', service], capture_output=True)
+
+ return {
+ 'success': True,
+ 'service': service,
+ 'message': f'{service} installed and started successfully'
+ }
+
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Installation timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def test_connection(cls, host: str = 'localhost', port: int = 21,
+ username: str = None, password: str = None) -> Dict:
+ """Test FTP connection."""
+ import socket
+
+ try:
+ # Basic connection test
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.settimeout(10)
+ result = sock.connect_ex((host, port))
+ sock.close()
+
+ if result != 0:
+ return {
+ 'success': False,
+ 'error': f'Cannot connect to {host}:{port}'
+ }
+
+ # If credentials provided, try to authenticate
+ if username and password:
+ try:
+ from ftplib import FTP
+ ftp = FTP()
+ ftp.connect(host, port, timeout=10)
+ ftp.login(username, password)
+ ftp.quit()
+ return {
+ 'success': True,
+ 'message': f'Successfully connected and authenticated to {host}:{port}'
+ }
+ except Exception as e:
+ return {
+ 'success': False,
+ 'error': f'Connection succeeded but authentication failed: {str(e)}'
+ }
+
+ return {
+ 'success': True,
+ 'message': f'FTP server is reachable at {host}:{port}'
+ }
+
+ except socket.timeout:
+ return {'success': False, 'error': 'Connection timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @staticmethod
+ def _format_size(size: int) -> str:
+ """Format size in human-readable format."""
+ for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
+ if size < 1024:
+ return f"{size:.1f} {unit}"
+ size /= 1024
+ return f"{size:.1f} PB"
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 5153433b..eea0eb43 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -16,6 +16,8 @@ import Monitoring from './pages/Monitoring';
import Backups from './pages/Backups';
import Terminal from './pages/Terminal';
import Settings from './pages/Settings';
+import FileManager from './pages/FileManager';
+import FTPServer from './pages/FTPServer';
function PrivateRoute({ children }) {
const { isAuthenticated, loading } = useAuth();
@@ -62,6 +64,8 @@ function AppRoutes() {
<Route path="databases" element={<Databases />} />
<Route path="ssl" element={<div className="page">SSL Certificates</div>} />
<Route path="docker" element={<Docker />} />
+ <Route path="files" element={<FileManager />} />
+ <Route path="ftp" element={<FTPServer />} />
<Route path="monitoring" element={<Monitoring />} />
<Route path="backups" element={<Backups />} />
<Route path="terminal" element={<Terminal />} />
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 3b76a009..361dbdcf 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -76,6 +76,20 @@ const Sidebar = () => {
<div className="menu-label">Operations</div>
<nav className="nav">
+ <NavLink to="/files" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
+ </svg>
+ File Manager
+ </NavLink>
+ <NavLink to="/ftp" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
+ <polyline points="17 8 12 3 7 8"/>
+ <line x1="12" y1="3" x2="12" y2="15"/>
+ </svg>
+ FTP Server
+ </NavLink>
<NavLink to="/monitoring" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
<svg viewBox="0 0 24 24">
<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>
diff --git a/frontend/src/pages/FTPServer.jsx b/frontend/src/pages/FTPServer.jsx
new file mode 100644
index 00000000..53ae74af
--- /dev/null
+++ b/frontend/src/pages/FTPServer.jsx
@@ -0,0 +1,736 @@
+import { useState, useEffect } from 'react';
+import { api } from '../services/api';
+import { useToast } from '../contexts/ToastContext';
+import Spinner from '../components/Spinner';
+import ConfirmDialog from '../components/ConfirmDialog';
+
+function FTPServer() {
+ const [status, setStatus] = useState(null);
+ const [users, setUsers] = useState([]);
+ const [connections, setConnections] = useState([]);
+ const [config, setConfig] = useState(null);
+ const [logs, setLogs] = useState('');
+ const [loading, setLoading] = useState(true);
+ const [activeTab, setActiveTab] = useState('overview');
+ const [showUserModal, setShowUserModal] = useState(false);
+ const [showPasswordModal, setShowPasswordModal] = useState(false);
+ const [showInstallModal, setShowInstallModal] = useState(false);
+ const [newUser, setNewUser] = useState({ username: '', password: '', homeDir: '' });
+ const [passwordTarget, setPasswordTarget] = useState(null);
+ const [newPassword, setNewPassword] = useState('');
+ const [selectedService, setSelectedService] = useState('vsftpd');
+ const [confirmDialog, setConfirmDialog] = useState(null);
+ const [actionLoading, setActionLoading] = useState(false);
+ const toast = useToast();
+
+ useEffect(() => {
+ loadData();
+ }, []);
+
+ const loadData = async () => {
+ setLoading(true);
+ try {
+ await Promise.all([
+ loadStatus(),
+ loadUsers(),
+ loadConnections()
+ ]);
+ } catch (error) {
+ console.error('Failed to load FTP data:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const loadStatus = async () => {
+ try {
+ const data = await api.getFTPStatus();
+ setStatus(data);
+ if (data.active_server) {
+ loadConfig(data.active_server);
+ }
+ } catch (error) {
+ console.error('Failed to load FTP status:', error);
+ }
+ };
+
+ const loadConfig = async (service) => {
+ try {
+ const data = await api.getFTPConfig(service);
+ setConfig(data);
+ } catch (error) {
+ console.error('Failed to load FTP config:', error);
+ }
+ };
+
+ const loadUsers = async () => {
+ try {
+ const data = await api.getFTPUsers();
+ setUsers(data.users || []);
+ } catch (error) {
+ console.error('Failed to load FTP users:', error);
+ }
+ };
+
+ const loadConnections = async () => {
+ try {
+ const data = await api.getFTPConnections();
+ setConnections(data.connections || []);
+ } catch (error) {
+ console.error('Failed to load FTP connections:', error);
+ }
+ };
+
+ const loadLogs = async () => {
+ try {
+ const data = await api.getFTPLogs(200);
+ setLogs(data.content || 'No logs available');
+ } catch (error) {
+ setLogs('Failed to load logs');
+ }
+ };
+
+ const handleServiceAction = async (action) => {
+ if (!status?.active_server) return;
+ setActionLoading(true);
+ try {
+ await api.controlFTPService(action, status.active_server);
+ toast.success(`FTP server ${action}ed successfully`);
+ await loadStatus();
+ } catch (error) {
+ toast.error(`Failed to ${action} FTP server: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleInstall = async () => {
+ setActionLoading(true);
+ try {
+ await api.installFTPServer(selectedService);
+ toast.success(`${selectedService} installed successfully`);
+ setShowInstallModal(false);
+ await loadData();
+ } catch (error) {
+ toast.error(`Failed to install: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleCreateUser = async () => {
+ if (!newUser.username.trim()) return;
+ setActionLoading(true);
+ try {
+ const result = await api.createFTPUser(
+ newUser.username,
+ newUser.password || null,
+ newUser.homeDir || null
+ );
+ toast.success(`User created. Password: ${result.password}`);
+ setShowUserModal(false);
+ setNewUser({ username: '', password: '', homeDir: '' });
+ await loadUsers();
+ } catch (error) {
+ toast.error(`Failed to create user: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleDeleteUser = async (username) => {
+ setConfirmDialog({
+ title: 'Delete FTP User',
+ message: `Are you sure you want to delete user "${username}"?`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ onConfirm: async () => {
+ try {
+ await api.deleteFTPUser(username, false);
+ toast.success('User deleted successfully');
+ await loadUsers();
+ } catch (error) {
+ toast.error(`Failed to delete user: ${error.message}`);
+ }
+ setConfirmDialog(null);
+ },
+ onCancel: () => setConfirmDialog(null)
+ });
+ };
+
+ const handleToggleUser = async (username, currentStatus) => {
+ try {
+ await api.toggleFTPUser(username, !currentStatus);
+ toast.success(`User ${currentStatus ? 'disabled' : 'enabled'} successfully`);
+ await loadUsers();
+ } catch (error) {
+ toast.error(`Failed to toggle user: ${error.message}`);
+ }
+ };
+
+ const handleChangePassword = async () => {
+ if (!passwordTarget) return;
+ setActionLoading(true);
+ try {
+ const result = await api.changeFTPPassword(passwordTarget, newPassword || null);
+ toast.success(`Password changed. New password: ${result.password}`);
+ setShowPasswordModal(false);
+ setPasswordTarget(null);
+ setNewPassword('');
+ } catch (error) {
+ toast.error(`Failed to change password: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleDisconnect = async (pid) => {
+ try {
+ await api.disconnectFTPSession(pid);
+ toast.success('Session disconnected');
+ await loadConnections();
+ } catch (error) {
+ toast.error(`Failed to disconnect: ${error.message}`);
+ }
+ };
+
+ const handleTestConnection = async () => {
+ setActionLoading(true);
+ try {
+ const result = await api.testFTPConnection('localhost', 21);
+ if (result.success) {
+ toast.success(result.message);
+ } else {
+ toast.error(result.error);
+ }
+ } catch (error) {
+ toast.error(`Connection test failed: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const openPasswordModal = (username) => {
+ setPasswordTarget(username);
+ setNewPassword('');
+ setShowPasswordModal(true);
+ };
+
+ if (loading) {
+ return (
+ <div className="page-loading">
+ <Spinner size="lg" />
+ </div>
+ );
+ }
+
+ const isInstalled = status?.any_installed;
+ const isRunning = status?.any_running;
+ const activeServer = status?.active_server;
+
+ return (
+ <div className="ftp-server">
+ <div className="page-header">
+ <div className="page-header-content">
+ <h1>FTP Server</h1>
+ <p className="page-description">Manage FTP users and file transfer settings</p>
+ </div>
+ <div className="page-header-actions">
+ {!isInstalled ? (
+ <button className="btn btn-primary" onClick={() => setShowInstallModal(true)}>
+ Install FTP Server
+ </button>
+ ) : (
+ <>
+ <button
+ className="btn btn-secondary"
+ onClick={handleTestConnection}
+ disabled={actionLoading}
+ >
+ Test Connection
+ </button>
+ {isRunning ? (
+ <>
+ <button
+ className="btn btn-secondary"
+ onClick={() => handleServiceAction('restart')}
+ disabled={actionLoading}
+ >
+ Restart
+ </button>
+ <button
+ className="btn btn-danger"
+ onClick={() => handleServiceAction('stop')}
+ disabled={actionLoading}
+ >
+ Stop
+ </button>
+ </>
+ ) : (
+ <button
+ className="btn btn-primary"
+ onClick={() => handleServiceAction('start')}
+ disabled={actionLoading}
+ >
+ Start
+ </button>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+
+ {!isInstalled ? (
+ <div className="empty-state-large">
+ <span className="icon">cloud_upload</span>
+ <h2>No FTP Server Installed</h2>
+ <p>Install an FTP server to enable file transfers on your server.</p>
+ <button className="btn btn-primary btn-lg" onClick={() => setShowInstallModal(true)}>
+ Install FTP Server
+ </button>
+ </div>
+ ) : (
+ <>
+ <div className="status-cards">
+ <div className={`status-card ${isRunning ? 'success' : 'warning'}`}>
+ <div className="status-icon">
+ <span className="icon">{isRunning ? 'check_circle' : 'pause_circle'}</span>
+ </div>
+ <div className="status-info">
+ <span className="status-label">Server Status</span>
+ <span className="status-value">{isRunning ? 'Running' : 'Stopped'}</span>
+ </div>
+ </div>
+ <div className="status-card">
+ <div className="status-icon">
+ <span className="icon">dns</span>
+ </div>
+ <div className="status-info">
+ <span className="status-label">Active Server</span>
+ <span className="status-value">{activeServer || 'None'}</span>
+ </div>
+ </div>
+ <div className="status-card">
+ <div className="status-icon">
+ <span className="icon">people</span>
+ </div>
+ <div className="status-info">
+ <span className="status-label">FTP Users</span>
+ <span className="status-value">{users.length}</span>
+ </div>
+ </div>
+ <div className="status-card">
+ <div className="status-icon">
+ <span className="icon">lan</span>
+ </div>
+ <div className="status-info">
+ <span className="status-label">Active Connections</span>
+ <span className="status-value">{connections.length}</span>
+ </div>
+ </div>
+ </div>
+
+ <div className="tabs">
+ <button
+ className={`tab ${activeTab === 'overview' ? 'active' : ''}`}
+ onClick={() => setActiveTab('overview')}
+ >
+ Overview
+ </button>
+ <button
+ className={`tab ${activeTab === 'users' ? 'active' : ''}`}
+ onClick={() => setActiveTab('users')}
+ >
+ Users
+ </button>
+ <button
+ className={`tab ${activeTab === 'connections' ? 'active' : ''}`}
+ onClick={() => { setActiveTab('connections'); loadConnections(); }}
+ >
+ Connections
+ </button>
+ <button
+ className={`tab ${activeTab === 'logs' ? 'active' : ''}`}
+ onClick={() => { setActiveTab('logs'); loadLogs(); }}
+ >
+ Logs
+ </button>
+ </div>
+
+ <div className="tab-content">
+ {activeTab === 'overview' && (
+ <div className="overview-tab">
+ <div className="config-section">
+ <h3>Server Configuration</h3>
+ {config?.settings ? (
+ <div className="config-grid">
+ <div className="config-item">
+ <span className="config-label">Port</span>
+ <span className="config-value">{config.settings.listen_port || config.settings.port || 21}</span>
+ </div>
+ <div className="config-item">
+ <span className="config-label">Anonymous Access</span>
+ <span className={`config-value ${config.settings.anonymous_enable ? 'warning' : 'success'}`}>
+ {config.settings.anonymous_enable ? 'Enabled' : 'Disabled'}
+ </span>
+ </div>
+ <div className="config-item">
+ <span className="config-label">Local Users</span>
+ <span className="config-value">
+ {config.settings.local_enable ? 'Enabled' : 'Disabled'}
+ </span>
+ </div>
+ <div className="config-item">
+ <span className="config-label">Write Permission</span>
+ <span className="config-value">
+ {config.settings.write_enable ? 'Enabled' : 'Disabled'}
+ </span>
+ </div>
+ <div className="config-item">
+ <span className="config-label">Chroot Users</span>
+ <span className="config-value">
+ {config.settings.chroot_local_user ? 'Yes' : 'No'}
+ </span>
+ </div>
+ <div className="config-item">
+ <span className="config-label">SSL/TLS</span>
+ <span className={`config-value ${config.settings.ssl_enable ? 'success' : 'warning'}`}>
+ {config.settings.ssl_enable ? 'Enabled' : 'Disabled'}
+ </span>
+ </div>
+ </div>
+ ) : (
+ <p className="text-muted">Configuration not available</p>
+ )}
+ </div>
+
+ <div className="info-section">
+ <h3>Connection Information</h3>
+ <div className="info-grid">
+ <div className="info-item">
+ <span className="info-label">Host</span>
+ <code>Your server IP or domain</code>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Port</span>
+ <code>21</code>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Protocol</span>
+ <code>FTP{config?.settings?.ssl_enable ? 'S' : ''}</code>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {activeTab === 'users' && (
+ <div className="users-tab">
+ <div className="section-header">
+ <h3>FTP Users</h3>
+ <button className="btn btn-primary" onClick={() => setShowUserModal(true)}>
+ Add User
+ </button>
+ </div>
+ {users.length === 0 ? (
+ <div className="empty-state">
+ <span className="icon">person_add</span>
+ <p>No FTP users configured</p>
+ <button className="btn btn-primary" onClick={() => setShowUserModal(true)}>
+ Create First User
+ </button>
+ </div>
+ ) : (
+ <div className="users-table">
+ <table>
+ <thead>
+ <tr>
+ <th>Username</th>
+ <th>Home Directory</th>
+ <th>Usage</th>
+ <th>Status</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {users.map((user) => (
+ <tr key={user.username}>
+ <td>
+ <span className="user-name">{user.username}</span>
+ {user.in_userlist && (
+ <span className="badge badge-info">FTP</span>
+ )}
+ </td>
+ <td>
+ <code>{user.home}</code>
+ {!user.home_exists && (
+ <span className="badge badge-warning">Missing</span>
+ )}
+ </td>
+ <td>{user.home_size_human}</td>
+ <td>
+ <span className={`status-badge ${user.is_active ? 'active' : 'inactive'}`}>
+ {user.is_active ? 'Active' : 'Disabled'}
+ </span>
+ </td>
+ <td className="actions">
+ <button
+ className="btn btn-sm btn-secondary"
+ onClick={() => openPasswordModal(user.username)}
+ title="Change Password"
+ >
+ <span className="icon">key</span>
+ </button>
+ <button
+ className={`btn btn-sm ${user.is_active ? 'btn-warning' : 'btn-success'}`}
+ onClick={() => handleToggleUser(user.username, user.is_active)}
+ title={user.is_active ? 'Disable' : 'Enable'}
+ >
+ <span className="icon">{user.is_active ? 'block' : 'check'}</span>
+ </button>
+ <button
+ className="btn btn-sm btn-danger"
+ onClick={() => handleDeleteUser(user.username)}
+ title="Delete"
+ >
+ <span className="icon">delete</span>
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ )}
+
+ {activeTab === 'connections' && (
+ <div className="connections-tab">
+ <div className="section-header">
+ <h3>Active Connections</h3>
+ <button className="btn btn-secondary" onClick={loadConnections}>
+ <span className="icon">refresh</span>
+ Refresh
+ </button>
+ </div>
+ {connections.length === 0 ? (
+ <div className="empty-state">
+ <span className="icon">lan</span>
+ <p>No active connections</p>
+ </div>
+ ) : (
+ <div className="connections-table">
+ <table>
+ <thead>
+ <tr>
+ <th>Local Address</th>
+ <th>Remote Address</th>
+ <th>State</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {connections.map((conn, index) => (
+ <tr key={index}>
+ <td><code>{conn.local}</code></td>
+ <td><code>{conn.remote}</code></td>
+ <td>
+ <span className="status-badge active">{conn.state}</span>
+ </td>
+ <td>
+ <button
+ className="btn btn-sm btn-danger"
+ onClick={() => handleDisconnect(conn.pid)}
+ title="Disconnect"
+ >
+ <span className="icon">close</span>
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ )}
+
+ {activeTab === 'logs' && (
+ <div className="logs-tab">
+ <div className="section-header">
+ <h3>Server Logs</h3>
+ <button className="btn btn-secondary" onClick={loadLogs}>
+ <span className="icon">refresh</span>
+ Refresh
+ </button>
+ </div>
+ <div className="log-viewer">
+ <pre>{logs}</pre>
+ </div>
+ </div>
+ )}
+ </div>
+ </>
+ )}
+
+ {/* Install Modal */}
+ {showInstallModal && (
+ <div className="modal-overlay" onClick={() => setShowInstallModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Install FTP Server</h2>
+ <button className="btn btn-icon" onClick={() => setShowInstallModal(false)}>
+ <span className="icon">close</span>
+ </button>
+ </div>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>Select FTP Server</label>
+ <select
+ value={selectedService}
+ onChange={(e) => setSelectedService(e.target.value)}
+ >
+ <option value="vsftpd">vsftpd (Recommended)</option>
+ <option value="proftpd">ProFTPD</option>
+ </select>
+ </div>
+ <div className="install-info">
+ {selectedService === 'vsftpd' ? (
+ <p>
+ <strong>vsftpd</strong> is a secure, fast, and stable FTP server.
+ It's the default choice for most Ubuntu/Debian systems.
+ </p>
+ ) : (
+ <p>
+ <strong>ProFTPD</strong> is a highly configurable FTP server with
+ advanced features and Apache-like configuration syntax.
+ </p>
+ )}
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowInstallModal(false)}>
+ Cancel
+ </button>
+ <button
+ className="btn btn-primary"
+ onClick={handleInstall}
+ disabled={actionLoading}
+ >
+ {actionLoading ? 'Installing...' : 'Install'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Create User Modal */}
+ {showUserModal && (
+ <div className="modal-overlay" onClick={() => setShowUserModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Create FTP User</h2>
+ <button className="btn btn-icon" onClick={() => setShowUserModal(false)}>
+ <span className="icon">close</span>
+ </button>
+ </div>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>Username *</label>
+ <input
+ type="text"
+ value={newUser.username}
+ onChange={(e) => setNewUser({ ...newUser, username: e.target.value })}
+ placeholder="ftpuser"
+ />
+ </div>
+ <div className="form-group">
+ <label>Password (leave empty to auto-generate)</label>
+ <input
+ type="password"
+ value={newUser.password}
+ onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
+ placeholder="Auto-generated if empty"
+ />
+ </div>
+ <div className="form-group">
+ <label>Home Directory (optional)</label>
+ <input
+ type="text"
+ value={newUser.homeDir}
+ onChange={(e) => setNewUser({ ...newUser, homeDir: e.target.value })}
+ placeholder="/home/ftp/username"
+ />
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowUserModal(false)}>
+ Cancel
+ </button>
+ <button
+ className="btn btn-primary"
+ onClick={handleCreateUser}
+ disabled={actionLoading || !newUser.username.trim()}
+ >
+ {actionLoading ? 'Creating...' : 'Create User'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Change Password Modal */}
+ {showPasswordModal && (
+ <div className="modal-overlay" onClick={() => setShowPasswordModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Change Password</h2>
+ <button className="btn btn-icon" onClick={() => setShowPasswordModal(false)}>
+ <span className="icon">close</span>
+ </button>
+ </div>
+ <div className="modal-body">
+ <p>Changing password for user: <strong>{passwordTarget}</strong></p>
+ <div className="form-group">
+ <label>New Password (leave empty to auto-generate)</label>
+ <input
+ type="password"
+ value={newPassword}
+ onChange={(e) => setNewPassword(e.target.value)}
+ placeholder="Auto-generated if empty"
+ />
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowPasswordModal(false)}>
+ Cancel
+ </button>
+ <button
+ className="btn btn-primary"
+ onClick={handleChangePassword}
+ disabled={actionLoading}
+ >
+ {actionLoading ? 'Changing...' : 'Change Password'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Confirm Dialog */}
+ {confirmDialog && (
+ <ConfirmDialog
+ title={confirmDialog.title}
+ message={confirmDialog.message}
+ confirmText={confirmDialog.confirmText}
+ variant={confirmDialog.variant}
+ onConfirm={confirmDialog.onConfirm}
+ onCancel={confirmDialog.onCancel}
+ />
+ )}
+ </div>
+ );
+}
+
+export default FTPServer;
diff --git a/frontend/src/pages/FileManager.jsx b/frontend/src/pages/FileManager.jsx
new file mode 100644
index 00000000..a24babf9
--- /dev/null
+++ b/frontend/src/pages/FileManager.jsx
@@ -0,0 +1,634 @@
+import { useState, useEffect, useRef } from 'react';
+import { api } from '../services/api';
+import { useToast } from '../contexts/ToastContext';
+import Spinner from '../components/Spinner';
+import ConfirmDialog from '../components/ConfirmDialog';
+
+function FileManager() {
+ const [currentPath, setCurrentPath] = useState('/home');
+ const [entries, setEntries] = useState([]);
+ const [parentPath, setParentPath] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [showHidden, setShowHidden] = useState(false);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [searchResults, setSearchResults] = useState(null);
+ const [diskUsage, setDiskUsage] = useState(null);
+ const [selectedFile, setSelectedFile] = useState(null);
+ const [fileContent, setFileContent] = useState('');
+ const [editingFile, setEditingFile] = useState(null);
+ const [showNewFileModal, setShowNewFileModal] = useState(false);
+ const [showNewFolderModal, setShowNewFolderModal] = useState(false);
+ const [showRenameModal, setShowRenameModal] = useState(false);
+ const [showPermissionsModal, setShowPermissionsModal] = useState(false);
+ const [newFileName, setNewFileName] = useState('');
+ const [newFolderName, setNewFolderName] = useState('');
+ const [renameTarget, setRenameTarget] = useState(null);
+ const [newName, setNewName] = useState('');
+ const [permissionsTarget, setPermissionsTarget] = useState(null);
+ const [newPermissions, setNewPermissions] = useState('');
+ const [uploadProgress, setUploadProgress] = useState(null);
+ const [confirmDialog, setConfirmDialog] = useState(null);
+ const fileInputRef = useRef(null);
+ const toast = useToast();
+
+ useEffect(() => {
+ loadDirectory(currentPath);
+ loadDiskUsage();
+ }, [currentPath, showHidden]);
+
+ const loadDirectory = async (path) => {
+ setLoading(true);
+ setSearchResults(null);
+ try {
+ const data = await api.browseFiles(path, showHidden);
+ setEntries(data.entries || []);
+ setParentPath(data.parent);
+ setCurrentPath(data.path);
+ } catch (error) {
+ toast.error(`Failed to load directory: ${error.message}`);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const loadDiskUsage = async () => {
+ try {
+ const data = await api.getDiskUsage(currentPath);
+ setDiskUsage(data);
+ } catch (error) {
+ console.error('Failed to load disk usage:', error);
+ }
+ };
+
+ const handleSearch = async () => {
+ if (!searchQuery.trim()) {
+ setSearchResults(null);
+ return;
+ }
+ setLoading(true);
+ try {
+ const data = await api.searchFiles(currentPath, searchQuery);
+ setSearchResults(data.results || []);
+ } catch (error) {
+ toast.error(`Search failed: ${error.message}`);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleNavigate = (entry) => {
+ if (entry.is_dir) {
+ setCurrentPath(entry.path);
+ setSelectedFile(null);
+ setEditingFile(null);
+ } else {
+ handleFileClick(entry);
+ }
+ };
+
+ const handleFileClick = async (entry) => {
+ setSelectedFile(entry);
+ if (entry.is_editable) {
+ try {
+ const data = await api.readFile(entry.path);
+ setFileContent(data.content);
+ } catch (error) {
+ toast.error(`Failed to read file: ${error.message}`);
+ }
+ }
+ };
+
+ const handleEditFile = () => {
+ if (selectedFile && selectedFile.is_editable) {
+ setEditingFile(selectedFile);
+ }
+ };
+
+ const handleSaveFile = async () => {
+ if (!editingFile) return;
+ try {
+ await api.writeFile(editingFile.path, fileContent);
+ toast.success('File saved successfully');
+ setEditingFile(null);
+ loadDirectory(currentPath);
+ } catch (error) {
+ toast.error(`Failed to save file: ${error.message}`);
+ }
+ };
+
+ const handleCreateFile = async () => {
+ if (!newFileName.trim()) return;
+ const filePath = `${currentPath}/${newFileName}`;
+ try {
+ await api.createFile(filePath);
+ toast.success('File created successfully');
+ setShowNewFileModal(false);
+ setNewFileName('');
+ loadDirectory(currentPath);
+ } catch (error) {
+ toast.error(`Failed to create file: ${error.message}`);
+ }
+ };
+
+ const handleCreateFolder = async () => {
+ if (!newFolderName.trim()) return;
+ const folderPath = `${currentPath}/${newFolderName}`;
+ try {
+ await api.createDirectory(folderPath);
+ toast.success('Folder created successfully');
+ setShowNewFolderModal(false);
+ setNewFolderName('');
+ loadDirectory(currentPath);
+ } catch (error) {
+ toast.error(`Failed to create folder: ${error.message}`);
+ }
+ };
+
+ const handleDelete = async (entry) => {
+ setConfirmDialog({
+ title: 'Delete Confirmation',
+ message: `Are you sure you want to delete "${entry.name}"? ${entry.is_dir ? 'This will delete all contents inside.' : ''}`,
+ confirmText: 'Delete',
+ variant: 'danger',
+ onConfirm: async () => {
+ try {
+ await api.deleteFile(entry.path);
+ toast.success(`${entry.is_dir ? 'Folder' : 'File'} deleted successfully`);
+ setSelectedFile(null);
+ loadDirectory(currentPath);
+ } catch (error) {
+ toast.error(`Failed to delete: ${error.message}`);
+ }
+ setConfirmDialog(null);
+ },
+ onCancel: () => setConfirmDialog(null)
+ });
+ };
+
+ const handleRename = async () => {
+ if (!renameTarget || !newName.trim()) return;
+ try {
+ await api.renameFile(renameTarget.path, newName);
+ toast.success('Renamed successfully');
+ setShowRenameModal(false);
+ setRenameTarget(null);
+ setNewName('');
+ loadDirectory(currentPath);
+ } catch (error) {
+ toast.error(`Failed to rename: ${error.message}`);
+ }
+ };
+
+ const handleChangePermissions = async () => {
+ if (!permissionsTarget || !newPermissions.trim()) return;
+ try {
+ await api.changeFilePermissions(permissionsTarget.path, newPermissions);
+ toast.success('Permissions changed successfully');
+ setShowPermissionsModal(false);
+ setPermissionsTarget(null);
+ setNewPermissions('');
+ loadDirectory(currentPath);
+ } catch (error) {
+ toast.error(`Failed to change permissions: ${error.message}`);
+ }
+ };
+
+ const handleUpload = async (e) => {
+ const file = e.target.files[0];
+ if (!file) return;
+
+ try {
+ await api.uploadFile(currentPath, file, (progress) => {
+ setUploadProgress(progress);
+ });
+ toast.success('File uploaded successfully');
+ loadDirectory(currentPath);
+ } catch (error) {
+ toast.error(`Upload failed: ${error.message}`);
+ } finally {
+ setUploadProgress(null);
+ if (fileInputRef.current) {
+ fileInputRef.current.value = '';
+ }
+ }
+ };
+
+ const handleDownload = (entry) => {
+ api.downloadFile(entry.path);
+ };
+
+ const openRenameModal = (entry) => {
+ setRenameTarget(entry);
+ setNewName(entry.name);
+ setShowRenameModal(true);
+ };
+
+ const openPermissionsModal = (entry) => {
+ setPermissionsTarget(entry);
+ setNewPermissions(entry.permissions_octal || '755');
+ setShowPermissionsModal(true);
+ };
+
+ const getFileIcon = (entry) => {
+ if (entry.is_dir) return 'folder';
+ const ext = entry.name.split('.').pop().toLowerCase();
+ const iconMap = {
+ js: 'javascript', jsx: 'javascript', ts: 'javascript', tsx: 'javascript',
+ py: 'python', rb: 'ruby', php: 'php', java: 'java',
+ html: 'html', css: 'css', less: 'css', scss: 'css',
+ json: 'json', xml: 'xml', yaml: 'yaml', yml: 'yaml',
+ md: 'markdown', txt: 'text', log: 'text',
+ sh: 'terminal', bash: 'terminal',
+ jpg: 'image', jpeg: 'image', png: 'image', gif: 'image', svg: 'image',
+ pdf: 'pdf', doc: 'document', docx: 'document',
+ zip: 'archive', tar: 'archive', gz: 'archive', rar: 'archive'
+ };
+ return iconMap[ext] || 'file';
+ };
+
+ const displayedEntries = searchResults || entries;
+
+ return (
+ <div className="file-manager">
+ <div className="page-header">
+ <div className="page-header-content">
+ <h1>File Manager</h1>
+ <p className="page-description">Browse, edit, and manage your server files</p>
+ </div>
+ <div className="page-header-actions">
+ <button className="btn btn-secondary" onClick={() => fileInputRef.current?.click()}>
+ Upload
+ </button>
+ <button className="btn btn-secondary" onClick={() => setShowNewFolderModal(true)}>
+ New Folder
+ </button>
+ <button className="btn btn-primary" onClick={() => setShowNewFileModal(true)}>
+ New File
+ </button>
+ <input
+ type="file"
+ ref={fileInputRef}
+ style={{ display: 'none' }}
+ onChange={handleUpload}
+ />
+ </div>
+ </div>
+
+ {uploadProgress !== null && (
+ <div className="upload-progress">
+ <div className="progress-bar">
+ <div className="progress-fill" style={{ width: `${uploadProgress}%` }}></div>
+ </div>
+ <span>{Math.round(uploadProgress)}%</span>
+ </div>
+ )}
+
+ <div className="file-manager-toolbar">
+ <div className="path-breadcrumb">
+ <button
+ className="btn btn-icon"
+ onClick={() => parentPath && setCurrentPath(parentPath)}
+ disabled={!parentPath}
+ >
+ <span className="icon">arrow_back</span>
+ </button>
+ <span className="current-path">{currentPath}</span>
+ </div>
+ <div className="toolbar-actions">
+ <div className="search-box">
+ <input
+ type="text"
+ placeholder="Search files..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
+ />
+ <button className="btn btn-icon" onClick={handleSearch}>
+ <span className="icon">search</span>
+ </button>
+ {searchResults && (
+ <button className="btn btn-icon" onClick={() => setSearchResults(null)}>
+ <span className="icon">close</span>
+ </button>
+ )}
+ </div>
+ <label className="checkbox-label">
+ <input
+ type="checkbox"
+ checked={showHidden}
+ onChange={(e) => setShowHidden(e.target.checked)}
+ />
+ Show hidden
+ </label>
+ <button className="btn btn-icon" onClick={() => loadDirectory(currentPath)}>
+ <span className="icon">refresh</span>
+ </button>
+ </div>
+ </div>
+
+ {diskUsage && (
+ <div className="disk-usage-bar">
+ <div className="disk-usage-info">
+ <span>Disk Usage: {diskUsage.used_human} / {diskUsage.total_human}</span>
+ <span>{diskUsage.percent}% used</span>
+ </div>
+ <div className="disk-progress">
+ <div
+ className={`disk-progress-fill ${diskUsage.percent > 90 ? 'critical' : diskUsage.percent > 75 ? 'warning' : ''}`}
+ style={{ width: `${diskUsage.percent}%` }}
+ ></div>
+ </div>
+ </div>
+ )}
+
+ <div className="file-manager-content">
+ <div className="file-list-container">
+ {loading ? (
+ <div className="loading-state">
+ <Spinner />
+ </div>
+ ) : displayedEntries.length === 0 ? (
+ <div className="empty-state">
+ <span className="icon">folder_open</span>
+ <p>{searchResults ? 'No files found matching your search' : 'This directory is empty'}</p>
+ </div>
+ ) : (
+ <div className="file-list">
+ <div className="file-list-header">
+ <span className="col-name">Name</span>
+ <span className="col-size">Size</span>
+ <span className="col-modified">Modified</span>
+ <span className="col-permissions">Permissions</span>
+ <span className="col-actions">Actions</span>
+ </div>
+ {displayedEntries.map((entry) => (
+ <div
+ key={entry.path}
+ className={`file-item ${selectedFile?.path === entry.path ? 'selected' : ''}`}
+ onClick={() => handleNavigate(entry)}
+ >
+ <span className="col-name">
+ <span className={`file-icon ${getFileIcon(entry)}`}></span>
+ {entry.name}
+ {entry.is_link && <span className="link-indicator">→</span>}
+ </span>
+ <span className="col-size">{entry.is_dir ? '-' : entry.size_human}</span>
+ <span className="col-modified">
+ {new Date(entry.modified).toLocaleDateString()}
+ </span>
+ <span className="col-permissions">{entry.permissions}</span>
+ <span className="col-actions" onClick={(e) => e.stopPropagation()}>
+ {!entry.is_dir && (
+ <button
+ className="btn btn-icon btn-sm"
+ onClick={() => handleDownload(entry)}
+ title="Download"
+ >
+ <span className="icon">download</span>
+ </button>
+ )}
+ <button
+ className="btn btn-icon btn-sm"
+ onClick={() => openRenameModal(entry)}
+ title="Rename"
+ >
+ <span className="icon">edit</span>
+ </button>
+ <button
+ className="btn btn-icon btn-sm"
+ onClick={() => openPermissionsModal(entry)}
+ title="Permissions"
+ >
+ <span className="icon">lock</span>
+ </button>
+ <button
+ className="btn btn-icon btn-sm btn-danger"
+ onClick={() => handleDelete(entry)}
+ title="Delete"
+ >
+ <span className="icon">delete</span>
+ </button>
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {selectedFile && !selectedFile.is_dir && (
+ <div className="file-preview">
+ <div className="preview-header">
+ <h3>{selectedFile.name}</h3>
+ <div className="preview-actions">
+ {selectedFile.is_editable && !editingFile && (
+ <button className="btn btn-primary btn-sm" onClick={handleEditFile}>
+ Edit
+ </button>
+ )}
+ {editingFile && (
+ <>
+ <button className="btn btn-secondary btn-sm" onClick={() => setEditingFile(null)}>
+ Cancel
+ </button>
+ <button className="btn btn-primary btn-sm" onClick={handleSaveFile}>
+ Save
+ </button>
+ </>
+ )}
+ <button className="btn btn-icon btn-sm" onClick={() => setSelectedFile(null)}>
+ <span className="icon">close</span>
+ </button>
+ </div>
+ </div>
+ <div className="preview-info">
+ <span>Size: {selectedFile.size_human}</span>
+ <span>Owner: {selectedFile.owner}</span>
+ <span>Group: {selectedFile.group}</span>
+ {selectedFile.mime_type && <span>Type: {selectedFile.mime_type}</span>}
+ </div>
+ {selectedFile.is_editable ? (
+ <textarea
+ className="file-editor"
+ value={fileContent}
+ onChange={(e) => setFileContent(e.target.value)}
+ readOnly={!editingFile}
+ spellCheck={false}
+ />
+ ) : (
+ <div className="preview-unavailable">
+ <span className="icon">visibility_off</span>
+ <p>Preview not available for this file type</p>
+ <button className="btn btn-primary" onClick={() => handleDownload(selectedFile)}>
+ Download File
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* New File Modal */}
+ {showNewFileModal && (
+ <div className="modal-overlay" onClick={() => setShowNewFileModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Create New File</h2>
+ <button className="btn btn-icon" onClick={() => setShowNewFileModal(false)}>
+ <span className="icon">close</span>
+ </button>
+ </div>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>File Name</label>
+ <input
+ type="text"
+ value={newFileName}
+ onChange={(e) => setNewFileName(e.target.value)}
+ placeholder="example.txt"
+ autoFocus
+ />
+ </div>
+ <p className="text-muted">File will be created in: {currentPath}</p>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowNewFileModal(false)}>
+ Cancel
+ </button>
+ <button className="btn btn-primary" onClick={handleCreateFile}>
+ Create File
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* New Folder Modal */}
+ {showNewFolderModal && (
+ <div className="modal-overlay" onClick={() => setShowNewFolderModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Create New Folder</h2>
+ <button className="btn btn-icon" onClick={() => setShowNewFolderModal(false)}>
+ <span className="icon">close</span>
+ </button>
+ </div>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>Folder Name</label>
+ <input
+ type="text"
+ value={newFolderName}
+ onChange={(e) => setNewFolderName(e.target.value)}
+ placeholder="new-folder"
+ autoFocus
+ />
+ </div>
+ <p className="text-muted">Folder will be created in: {currentPath}</p>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowNewFolderModal(false)}>
+ Cancel
+ </button>
+ <button className="btn btn-primary" onClick={handleCreateFolder}>
+ Create Folder
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Rename Modal */}
+ {showRenameModal && (
+ <div className="modal-overlay" onClick={() => setShowRenameModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Rename {renameTarget?.is_dir ? 'Folder' : 'File'}</h2>
+ <button className="btn btn-icon" onClick={() => setShowRenameModal(false)}>
+ <span className="icon">close</span>
+ </button>
+ </div>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>New Name</label>
+ <input
+ type="text"
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ autoFocus
+ />
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowRenameModal(false)}>
+ Cancel
+ </button>
+ <button className="btn btn-primary" onClick={handleRename}>
+ Rename
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Permissions Modal */}
+ {showPermissionsModal && (
+ <div className="modal-overlay" onClick={() => setShowPermissionsModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Change Permissions</h2>
+ <button className="btn btn-icon" onClick={() => setShowPermissionsModal(false)}>
+ <span className="icon">close</span>
+ </button>
+ </div>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>Permissions (Octal)</label>
+ <input
+ type="text"
+ value={newPermissions}
+ onChange={(e) => setNewPermissions(e.target.value)}
+ placeholder="755"
+ maxLength={4}
+ autoFocus
+ />
+ </div>
+ <p className="text-muted">
+ Current: {permissionsTarget?.permissions} ({permissionsTarget?.permissions_octal})
+ </p>
+ <div className="permissions-help">
+ <p>Common permissions:</p>
+ <ul>
+ <li><code>755</code> - Owner: rwx, Group/Other: rx (directories)</li>
+ <li><code>644</code> - Owner: rw, Group/Other: r (files)</li>
+ <li><code>600</code> - Owner: rw only (private files)</li>
+ </ul>
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowPermissionsModal(false)}>
+ Cancel
+ </button>
+ <button className="btn btn-primary" onClick={handleChangePermissions}>
+ Apply
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Confirm Dialog */}
+ {confirmDialog && (
+ <ConfirmDialog
+ title={confirmDialog.title}
+ message={confirmDialog.message}
+ confirmText={confirmDialog.confirmText}
+ variant={confirmDialog.variant}
+ onConfirm={confirmDialog.onConfirm}
+ onCancel={confirmDialog.onCancel}
+ />
+ )}
+ </div>
+ );
+}
+
+export default FileManager;
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 942f478e..b78988b0 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -1160,6 +1160,210 @@ class ApiService {
body: { app_path: appPath, repo_url: repoUrl, branch }
});
}
+
+ // ========================================
+ // File Manager endpoints
+ // ========================================
+ async browseFiles(path = '/home', showHidden = false) {
+ const params = new URLSearchParams({ path, show_hidden: showHidden });
+ return this.request(`/files/browse?${params}`);
+ }
+
+ async getFileInfo(path) {
+ return this.request(`/files/info?path=${encodeURIComponent(path)}`);
+ }
+
+ async readFile(path) {
+ return this.request(`/files/read?path=${encodeURIComponent(path)}`);
+ }
+
+ async writeFile(path, content, createBackup = true) {
+ return this.request('/files/write', {
+ method: 'POST',
+ body: { path, content, create_backup: createBackup }
+ });
+ }
+
+ async createFile(path, content = '') {
+ return this.request('/files/create', {
+ method: 'POST',
+ body: { path, content }
+ });
+ }
+
+ async createDirectory(path) {
+ return this.request('/files/mkdir', {
+ method: 'POST',
+ body: { path }
+ });
+ }
+
+ async deleteFile(path) {
+ return this.request(`/files/delete?path=${encodeURIComponent(path)}`, {
+ method: 'DELETE'
+ });
+ }
+
+ async renameFile(path, newName) {
+ return this.request('/files/rename', {
+ method: 'POST',
+ body: { path, new_name: newName }
+ });
+ }
+
+ async copyFile(src, dest) {
+ return this.request('/files/copy', {
+ method: 'POST',
+ body: { src, dest }
+ });
+ }
+
+ async moveFile(src, dest) {
+ return this.request('/files/move', {
+ method: 'POST',
+ body: { src, dest }
+ });
+ }
+
+ async changeFilePermissions(path, mode) {
+ return this.request('/files/chmod', {
+ method: 'POST',
+ body: { path, mode }
+ });
+ }
+
+ async searchFiles(directory, pattern, maxResults = 100) {
+ const params = new URLSearchParams({ directory, pattern, max_results: maxResults });
+ return this.request(`/files/search?${params}`);
+ }
+
+ async getDiskUsage(path = '/') {
+ return this.request(`/files/disk-usage?path=${encodeURIComponent(path)}`);
+ }
+
+ async downloadFile(path) {
+ const token = this.getToken();
+ const url = `${this.baseUrl}/files/download?path=${encodeURIComponent(path)}`;
+ window.open(`${url}&token=${token}`, '_blank');
+ }
+
+ async uploadFile(destination, file, onProgress = null) {
+ const token = this.getToken();
+ const formData = new FormData();
+ formData.append('file', file);
+ formData.append('destination', destination);
+
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('POST', `${this.baseUrl}/files/upload`);
+ xhr.setRequestHeader('Authorization', `Bearer ${token}`);
+
+ if (onProgress) {
+ xhr.upload.onprogress = (e) => {
+ if (e.lengthComputable) {
+ onProgress((e.loaded / e.total) * 100);
+ }
+ };
+ }
+
+ xhr.onload = () => {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ resolve(JSON.parse(xhr.responseText));
+ } else {
+ reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));
+ }
+ };
+
+ xhr.onerror = () => reject(new Error('Upload failed'));
+ xhr.send(formData);
+ });
+ }
+
+ // ========================================
+ // FTP Server endpoints
+ // ========================================
+ async getFTPStatus() {
+ return this.request('/ftp/status');
+ }
+
+ async controlFTPService(action, service = null) {
+ return this.request(`/ftp/service/${action}`, {
+ method: 'POST',
+ body: service ? { service } : {}
+ });
+ }
+
+ async getFTPConfig(service = null) {
+ const params = service ? `?service=${service}` : '';
+ return this.request(`/ftp/config${params}`);
+ }
+
+ async updateFTPConfig(config, service = null) {
+ return this.request('/ftp/config', {
+ method: 'POST',
+ body: { config, service }
+ });
+ }
+
+ async getFTPUsers() {
+ return this.request('/ftp/users');
+ }
+
+ async createFTPUser(username, password = null, homeDir = null) {
+ return this.request('/ftp/users', {
+ method: 'POST',
+ body: { username, password, home_dir: homeDir }
+ });
+ }
+
+ async deleteFTPUser(username, deleteHome = false) {
+ const params = deleteHome ? '?delete_home=true' : '';
+ return this.request(`/ftp/users/${username}${params}`, {
+ method: 'DELETE'
+ });
+ }
+
+ async changeFTPPassword(username, password = null) {
+ return this.request(`/ftp/users/${username}/password`, {
+ method: 'POST',
+ body: password ? { password } : {}
+ });
+ }
+
+ async toggleFTPUser(username, enabled) {
+ return this.request(`/ftp/users/${username}/toggle`, {
+ method: 'POST',
+ body: { enabled }
+ });
+ }
+
+ async getFTPConnections() {
+ return this.request('/ftp/connections');
+ }
+
+ async disconnectFTPSession(pid) {
+ return this.request(`/ftp/connections/${pid}`, {
+ method: 'DELETE'
+ });
+ }
+
+ async getFTPLogs(lines = 100) {
+ return this.request(`/ftp/logs?lines=${lines}`);
+ }
+
+ async installFTPServer(service = 'vsftpd') {
+ return this.request('/ftp/install', {
+ method: 'POST',
+ body: { service }
+ });
+ }
+
+ async testFTPConnection(host = 'localhost', port = 21, username = null, password = null) {
+ return this.request('/ftp/test', {
+ method: 'POST',
+ body: { host, port, username, password }
+ });
+ }
}
export const api = new ApiService();
diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.less
index 61f78479..1a9dd14b 100644
--- a/frontend/src/styles/main.less
+++ b/frontend/src/styles/main.less
@@ -53,3 +53,5 @@
@import 'pages/_backups';
@import 'pages/_terminal';
@import 'pages/_settings';
+@import 'pages/_file-manager';
+@import 'pages/_ftp-server';
diff --git a/frontend/src/styles/pages/_file-manager.less b/frontend/src/styles/pages/_file-manager.less
new file mode 100644
index 00000000..0cfe3698
--- /dev/null
+++ b/frontend/src/styles/pages/_file-manager.less
@@ -0,0 +1,415 @@
+// File Manager Page Styles
+
+.file-manager {
+ .page-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ margin-bottom: 24px;
+ flex-wrap: wrap;
+ gap: 16px;
+
+ .page-header-content {
+ h1 {
+ font-size: 24px;
+ font-weight: 600;
+ margin: 0 0 4px 0;
+ }
+
+ .page-description {
+ color: var(--text-secondary);
+ margin: 0;
+ }
+ }
+
+ .page-header-actions {
+ display: flex;
+ gap: 8px;
+ }
+ }
+
+ .upload-progress {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 12px 16px;
+ background: var(--card-bg);
+ border-radius: 8px;
+ margin-bottom: 16px;
+
+ .progress-bar {
+ flex: 1;
+ height: 8px;
+ background: var(--border-color);
+ border-radius: 4px;
+ overflow: hidden;
+
+ .progress-fill {
+ height: 100%;
+ background: var(--primary);
+ transition: width 0.3s ease;
+ }
+ }
+
+ span {
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ min-width: 40px;
+ }
+ }
+
+ .file-manager-toolbar {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 12px 16px;
+ background: var(--card-bg);
+ border-radius: 8px;
+ margin-bottom: 16px;
+ gap: 16px;
+ flex-wrap: wrap;
+
+ .path-breadcrumb {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ .current-path {
+ font-family: var(--font-mono);
+ font-size: 13px;
+ color: var(--text-primary);
+ background: var(--bg-tertiary);
+ padding: 6px 12px;
+ border-radius: 4px;
+ }
+ }
+
+ .toolbar-actions {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+
+ .search-box {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ background: var(--bg-tertiary);
+ border-radius: 6px;
+ padding: 0 4px;
+
+ input {
+ background: transparent;
+ border: none;
+ padding: 8px 12px;
+ font-size: 13px;
+ width: 200px;
+
+ &:focus {
+ outline: none;
+ }
+ }
+ }
+
+ .checkbox-label {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 13px;
+ color: var(--text-secondary);
+ cursor: pointer;
+
+ input[type="checkbox"] {
+ width: 16px;
+ height: 16px;
+ }
+ }
+ }
+ }
+
+ .disk-usage-bar {
+ padding: 12px 16px;
+ background: var(--card-bg);
+ border-radius: 8px;
+ margin-bottom: 16px;
+
+ .disk-usage-info {
+ display: flex;
+ justify-content: space-between;
+ font-size: 13px;
+ color: var(--text-secondary);
+ margin-bottom: 8px;
+ }
+
+ .disk-progress {
+ height: 6px;
+ background: var(--border-color);
+ border-radius: 3px;
+ overflow: hidden;
+
+ .disk-progress-fill {
+ height: 100%;
+ background: var(--primary);
+ transition: width 0.3s ease;
+
+ &.warning {
+ background: var(--warning);
+ }
+
+ &.critical {
+ background: var(--danger);
+ }
+ }
+ }
+ }
+
+ .file-manager-content {
+ display: grid;
+ grid-template-columns: 1fr 400px;
+ gap: 16px;
+
+ @media (max-width: 1200px) {
+ grid-template-columns: 1fr;
+ }
+ }
+
+ .file-list-container {
+ background: var(--card-bg);
+ border-radius: 8px;
+ overflow: hidden;
+
+ .loading-state,
+ .empty-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 48px;
+ color: var(--text-tertiary);
+
+ .icon {
+ font-size: 48px;
+ margin-bottom: 16px;
+ }
+ }
+ }
+
+ .file-list {
+ .file-list-header {
+ display: grid;
+ grid-template-columns: 1fr 100px 120px 120px 120px;
+ padding: 12px 16px;
+ background: var(--bg-tertiary);
+ font-size: 12px;
+ font-weight: 600;
+ text-transform: uppercase;
+ color: var(--text-tertiary);
+ border-bottom: 1px solid var(--border-color);
+ }
+
+ .file-item {
+ display: grid;
+ grid-template-columns: 1fr 100px 120px 120px 120px;
+ padding: 12px 16px;
+ border-bottom: 1px solid var(--border-color);
+ cursor: pointer;
+ transition: background 0.2s;
+
+ &:hover {
+ background: var(--bg-tertiary);
+ }
+
+ &.selected {
+ background: rgba(var(--primary-rgb), 0.1);
+ }
+
+ .col-name {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+
+ .file-icon {
+ width: 20px;
+ height: 20px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ &.folder::before {
+ content: "📁";
+ }
+
+ &.file::before {
+ content: "📄";
+ }
+
+ &.javascript::before {
+ content: "📜";
+ }
+
+ &.python::before {
+ content: "🐍";
+ }
+
+ &.image::before {
+ content: "🖼️";
+ }
+
+ &.text::before {
+ content: "📝";
+ }
+
+ &.archive::before {
+ content: "📦";
+ }
+
+ &.terminal::before {
+ content: "⚡";
+ }
+ }
+
+ .link-indicator {
+ color: var(--text-tertiary);
+ font-size: 12px;
+ }
+ }
+
+ .col-size,
+ .col-modified,
+ .col-permissions {
+ font-size: 13px;
+ color: var(--text-secondary);
+ }
+
+ .col-permissions {
+ font-family: var(--font-mono);
+ font-size: 12px;
+ }
+
+ .col-actions {
+ display: flex;
+ gap: 4px;
+ justify-content: flex-end;
+
+ .btn-icon {
+ opacity: 0;
+ transition: opacity 0.2s;
+ }
+ }
+
+ &:hover .col-actions .btn-icon {
+ opacity: 1;
+ }
+ }
+ }
+
+ .file-preview {
+ background: var(--card-bg);
+ border-radius: 8px;
+ display: flex;
+ flex-direction: column;
+ max-height: calc(100vh - 300px);
+
+ .preview-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 16px;
+ border-bottom: 1px solid var(--border-color);
+
+ h3 {
+ margin: 0;
+ font-size: 14px;
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .preview-actions {
+ display: flex;
+ gap: 8px;
+ }
+ }
+
+ .preview-info {
+ display: flex;
+ gap: 16px;
+ padding: 12px 16px;
+ background: var(--bg-tertiary);
+ font-size: 12px;
+ color: var(--text-secondary);
+ flex-wrap: wrap;
+ }
+
+ .file-editor {
+ flex: 1;
+ padding: 16px;
+ font-family: var(--font-mono);
+ font-size: 13px;
+ line-height: 1.5;
+ background: var(--bg-primary);
+ border: none;
+ resize: none;
+ color: var(--text-primary);
+
+ &:focus {
+ outline: none;
+ }
+
+ &[readonly] {
+ background: var(--bg-tertiary);
+ }
+ }
+
+ .preview-unavailable {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 48px;
+ color: var(--text-tertiary);
+
+ .icon {
+ font-size: 48px;
+ margin-bottom: 16px;
+ }
+
+ p {
+ margin-bottom: 16px;
+ }
+ }
+ }
+
+ .permissions-help {
+ margin-top: 16px;
+ padding: 12px;
+ background: var(--bg-tertiary);
+ border-radius: 6px;
+ font-size: 13px;
+
+ p {
+ margin: 0 0 8px 0;
+ font-weight: 500;
+ }
+
+ ul {
+ margin: 0;
+ padding-left: 20px;
+
+ li {
+ margin-bottom: 4px;
+ }
+
+ code {
+ background: var(--bg-primary);
+ padding: 2px 6px;
+ border-radius: 4px;
+ }
+ }
+ }
+}
diff --git a/frontend/src/styles/pages/_ftp-server.less b/frontend/src/styles/pages/_ftp-server.less
new file mode 100644
index 00000000..31d53510
--- /dev/null
+++ b/frontend/src/styles/pages/_ftp-server.less
@@ -0,0 +1,395 @@
+// FTP Server Page Styles
+
+.ftp-server {
+ .page-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ margin-bottom: 24px;
+ flex-wrap: wrap;
+ gap: 16px;
+
+ .page-header-content {
+ h1 {
+ font-size: 24px;
+ font-weight: 600;
+ margin: 0 0 4px 0;
+ }
+
+ .page-description {
+ color: var(--text-secondary);
+ margin: 0;
+ }
+ }
+
+ .page-header-actions {
+ display: flex;
+ gap: 8px;
+ }
+ }
+
+ .page-loading {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ min-height: 400px;
+ }
+
+ .empty-state-large {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 80px 24px;
+ background: var(--card-bg);
+ border-radius: 12px;
+ text-align: center;
+
+ .icon {
+ font-size: 64px;
+ color: var(--text-tertiary);
+ margin-bottom: 24px;
+ }
+
+ h2 {
+ margin: 0 0 12px 0;
+ font-size: 24px;
+ font-weight: 600;
+ }
+
+ p {
+ margin: 0 0 24px 0;
+ color: var(--text-secondary);
+ max-width: 400px;
+ }
+ }
+
+ .status-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ gap: 16px;
+ margin-bottom: 24px;
+ }
+
+ .status-card {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ padding: 20px;
+ background: var(--card-bg);
+ border-radius: 12px;
+ border-left: 4px solid var(--border-color);
+
+ &.success {
+ border-left-color: var(--success);
+
+ .status-icon {
+ color: var(--success);
+ }
+ }
+
+ &.warning {
+ border-left-color: var(--warning);
+
+ .status-icon {
+ color: var(--warning);
+ }
+ }
+
+ .status-icon {
+ .icon {
+ font-size: 32px;
+ }
+ }
+
+ .status-info {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+
+ .status-label {
+ font-size: 13px;
+ color: var(--text-secondary);
+ }
+
+ .status-value {
+ font-size: 18px;
+ font-weight: 600;
+ }
+ }
+ }
+
+ .tabs {
+ display: flex;
+ gap: 4px;
+ margin-bottom: 24px;
+ border-bottom: 1px solid var(--border-color);
+
+ .tab {
+ padding: 12px 20px;
+ background: none;
+ border: none;
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ cursor: pointer;
+ position: relative;
+ transition: color 0.2s;
+
+ &:hover {
+ color: var(--text-primary);
+ }
+
+ &.active {
+ color: var(--primary);
+
+ &::after {
+ content: '';
+ position: absolute;
+ bottom: -1px;
+ left: 0;
+ right: 0;
+ height: 2px;
+ background: var(--primary);
+ }
+ }
+ }
+ }
+
+ .tab-content {
+ .section-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 16px;
+
+ h3 {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 600;
+ }
+ }
+
+ .empty-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 48px;
+ background: var(--card-bg);
+ border-radius: 8px;
+ color: var(--text-tertiary);
+
+ .icon {
+ font-size: 48px;
+ margin-bottom: 16px;
+ }
+
+ p {
+ margin-bottom: 16px;
+ }
+ }
+ }
+
+ .overview-tab {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 24px;
+
+ @media (max-width: 900px) {
+ grid-template-columns: 1fr;
+ }
+
+ .config-section,
+ .info-section {
+ background: var(--card-bg);
+ border-radius: 8px;
+ padding: 20px;
+
+ h3 {
+ margin: 0 0 16px 0;
+ font-size: 16px;
+ font-weight: 600;
+ }
+ }
+
+ .config-grid,
+ .info-grid {
+ display: grid;
+ gap: 12px;
+ }
+
+ .config-item,
+ .info-item {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 8px 0;
+ border-bottom: 1px solid var(--border-color);
+
+ &:last-child {
+ border-bottom: none;
+ }
+
+ .config-label,
+ .info-label {
+ font-size: 13px;
+ color: var(--text-secondary);
+ }
+
+ .config-value {
+ font-size: 13px;
+ font-weight: 500;
+
+ &.success {
+ color: var(--success);
+ }
+
+ &.warning {
+ color: var(--warning);
+ }
+ }
+
+ code {
+ font-family: var(--font-mono);
+ font-size: 13px;
+ background: var(--bg-tertiary);
+ padding: 4px 8px;
+ border-radius: 4px;
+ }
+ }
+ }
+
+ .users-tab,
+ .connections-tab {
+ .users-table,
+ .connections-table {
+ background: var(--card-bg);
+ border-radius: 8px;
+ overflow: hidden;
+
+ table {
+ width: 100%;
+ border-collapse: collapse;
+
+ th,
+ td {
+ padding: 12px 16px;
+ text-align: left;
+ }
+
+ th {
+ background: var(--bg-tertiary);
+ font-size: 12px;
+ font-weight: 600;
+ text-transform: uppercase;
+ color: var(--text-tertiary);
+ }
+
+ td {
+ border-bottom: 1px solid var(--border-color);
+ font-size: 13px;
+
+ &:last-child {
+ border-bottom: none;
+ }
+
+ code {
+ font-family: var(--font-mono);
+ font-size: 12px;
+ background: var(--bg-tertiary);
+ padding: 2px 6px;
+ border-radius: 4px;
+ }
+ }
+
+ tr:last-child td {
+ border-bottom: none;
+ }
+ }
+
+ .user-name {
+ font-weight: 500;
+ margin-right: 8px;
+ }
+
+ .badge {
+ display: inline-block;
+ padding: 2px 8px;
+ font-size: 11px;
+ font-weight: 500;
+ border-radius: 4px;
+
+ &.badge-info {
+ background: rgba(var(--primary-rgb), 0.1);
+ color: var(--primary);
+ }
+
+ &.badge-warning {
+ background: rgba(255, 193, 7, 0.1);
+ color: #f59e0b;
+ }
+ }
+
+ .status-badge {
+ display: inline-block;
+ padding: 4px 10px;
+ font-size: 12px;
+ font-weight: 500;
+ border-radius: 4px;
+
+ &.active {
+ background: rgba(34, 197, 94, 0.1);
+ color: var(--success);
+ }
+
+ &.inactive {
+ background: rgba(156, 163, 175, 0.1);
+ color: var(--text-tertiary);
+ }
+ }
+
+ .actions {
+ display: flex;
+ gap: 4px;
+ }
+ }
+ }
+
+ .logs-tab {
+ .log-viewer {
+ background: var(--card-bg);
+ border-radius: 8px;
+ padding: 16px;
+ max-height: 500px;
+ overflow: auto;
+
+ pre {
+ margin: 0;
+ font-family: var(--font-mono);
+ font-size: 12px;
+ line-height: 1.6;
+ white-space: pre-wrap;
+ word-break: break-all;
+ color: var(--text-secondary);
+ }
+ }
+ }
+
+ .install-info {
+ padding: 16px;
+ background: var(--bg-tertiary);
+ border-radius: 8px;
+ margin-top: 16px;
+
+ p {
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.6;
+
+ strong {
+ color: var(--primary);
+ }
+ }
+ }
+}