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 template management API and frontend integration

Juan Denis6d0b84bc9103
diff --git a/.planning/ROADMAP.md b/.planning/ROADMAP.md
deleted file mode 100644
index 772e2810..00000000
--- a/.planning/ROADMAP.md
+++ /dev/null
@@ -1,293 +0,0 @@
-# ServerKit Roadmap
-
-A modern, self-hosted server management panel - alternative to ServerPilot/CyberPanel.
-
----
-
-## Phase 1: Foundation & Core Infrastructure
-
-### 1.1 Project Setup
-- [x] Initialize React frontend with Vite
-- [x] Create admin dashboard mockup/design system
-- [ ] Set up Flask backend structure
-- [ ] Configure SQLAlchemy with SQLite/PostgreSQL
-- [ ] Set up Docker development environment
-- [ ] Configure CORS and API routing
-- [ ] Implement JWT authentication system
-
-### 1.2 User Management
-- [ ] User registration and login
-- [ ] Role-based access control (Admin, User)
-- [ ] Session management
-- [ ] Password reset functionality
-- [ ] API token generation for CLI access
-
-### 1.3 Core API Structure
-```
-/api/v1/
-├── auth/ # Authentication endpoints
-├── servers/ # Server management
-├── apps/ # Application management
-├── domains/ # Domain configuration
-├── databases/ # Database management
-├── ssl/ # SSL certificate management
-└── system/ # System metrics and logs
-```
-
----
-
-## Phase 2: Server Agent & System Integration
-
-### 2.1 Server Agent (Python)
-- [ ] System metrics collection (CPU, RAM, Disk, Load)
-- [ ] Process monitoring and management
-- [ ] Service control (start, stop, restart)
-- [ ] Log aggregation and streaming
-- [ ] WebSocket connection for real-time updates
-
-### 2.2 Nginx Management
-- [ ] Nginx configuration generator
-- [ ] Virtual host management
-- [ ] Reverse proxy configuration
-- [ ] Load balancing setup
-- [ ] Configuration validation and reload
-
-### 2.3 SSL/TLS Management
-- [ ] Let's Encrypt integration (Certbot)
-- [ ] Auto-renewal setup
-- [ ] Custom certificate upload
-- [ ] SSL status monitoring
-- [ ] Force HTTPS redirects
-
----
-
-## Phase 3: PHP & WordPress Support
-
-### 3.1 PHP-FPM Management
-- [ ] PHP 8.2 FPM pool configuration
-- [ ] Multiple PHP version support (8.0, 8.1, 8.2, 8.3)
-- [ ] Per-site PHP configuration
-- [ ] PHP extensions management
-- [ ] OPcache configuration
-
-### 3.2 WordPress Toolkit
-- [ ] One-click WordPress installation
-- [ ] WP-CLI integration
-- [ ] Automatic updates management
-- [ ] Backup and restore
-- [ ] Staging environment creation
-- [ ] Database optimization tools
-
-### 3.3 WordPress-Specific Features
-- [ ] Plugin/theme management
-- [ ] wp-config.php editor
-- [ ] Security hardening
-- [ ] Performance optimization
-- [ ] Search & replace tool
-
----
-
-## Phase 4: Python Application Support
-
-### 4.1 Python Runtime Management
-- [ ] Multiple Python version support (3.9, 3.10, 3.11, 3.12)
-- [ ] Virtual environment management
-- [ ] pip package management
-- [ ] Requirements.txt handling
-
-### 4.2 Flask Application Deployment
-- [ ] Gunicorn/uWSGI configuration
-- [ ] Environment variables management
-- [ ] Application process management
-- [ ] Log routing and monitoring
-- [ ] Static file serving
-
-### 4.3 Django Application Deployment
-- [ ] Django-specific configuration
-- [ ] Static/media file handling
-- [ ] Database migrations support
-- [ ] Celery worker management
-- [ ] Django admin access
-
----
-
-## Phase 5: Docker Container Management
-
-### 5.1 Docker Integration
-- [ ] Docker daemon connection
-- [ ] Container listing and management
-- [ ] Image management (pull, remove)
-- [ ] Container logs streaming
-- [ ] Resource usage monitoring
-
-### 5.2 Docker Compose Support
-- [ ] Compose file editor
-- [ ] Stack deployment
-- [ ] Service scaling
-- [ ] Network management
-- [ ] Volume management
-
-### 5.3 Container Features
-- [ ] Container shell access (WebSocket terminal)
-- [ ] Environment variable management
-- [ ] Port mapping configuration
-- [ ] Container health checks
-- [ ] Auto-restart policies
-
----
-
-## Phase 6: Database Management
-
-### 6.1 MySQL/MariaDB
-- [ ] Database creation and management
-- [ ] User and privilege management
-- [ ] phpMyAdmin integration
-- [ ] Backup and restore
-- [ ] Query execution interface
-
-### 6.2 PostgreSQL
-- [ ] Database creation and management
-- [ ] User and privilege management
-- [ ] pgAdmin integration (optional)
-- [ ] Backup and restore
-
-### 6.3 Redis (Optional)
-- [ ] Redis server management
-- [ ] Key browser
-- [ ] Memory usage monitoring
-
----
-
-## Phase 7: Frontend Dashboard (React)
-
-### 7.1 Dashboard Components
-- [ ] Server overview with real-time metrics
-- [ ] Application cards with status indicators
-- [ ] Quick actions panel
-- [ ] Activity feed
-- [ ] Resource usage charts (Recharts)
-
-### 7.2 Application Management UI
-- [ ] Application list view
-- [ ] Application detail page
-- [ ] Deployment wizard
-- [ ] Configuration editor
-- [ ] Log viewer
-
-### 7.3 Domain Management UI
-- [ ] Domain list and management
-- [ ] DNS records editor (if applicable)
-- [ ] SSL certificate status
-- [ ] Domain routing configuration
-
-### 7.4 System Pages
-- [ ] Web-based terminal (xterm.js)
-- [ ] File manager
-- [ ] Cron job manager
-- [ ] Firewall configuration
-- [ ] Settings and preferences
-
----
-
-## Phase 8: Advanced Features
-
-### 8.1 Monitoring & Alerts
-- [ ] Uptime monitoring
-- [ ] Resource threshold alerts
-- [ ] Email/webhook notifications
-- [ ] Custom alert rules
-- [ ] Incident history
-
-### 8.2 Backup System
-- [ ] Scheduled backups
-- [ ] Multiple backup destinations (local, S3, etc.)
-- [ ] One-click restore
-- [ ] Backup encryption
-- [ ] Retention policies
-
-### 8.3 Git Deployment
-- [ ] GitHub/GitLab webhook integration
-- [ ] Auto-deploy on push
-- [ ] Deploy hooks (pre/post)
-- [ ] Rollback functionality
-- [ ] Deployment history
-
----
-
-## Phase 9: Security & Hardening
-
-### 9.1 Security Features
-- [ ] Fail2ban integration
-- [ ] UFW firewall management
-- [ ] SSH key management
-- [ ] Two-factor authentication
-- [ ] Audit logging
-
-### 9.2 Malware Protection
-- [ ] File integrity monitoring
-- [ ] Malware scanning (ClamAV)
-- [ ] Suspicious activity detection
-
----
-
-## Phase 10: Polish & Production
-
-### 10.1 Documentation
-- [ ] User documentation
-- [ ] API documentation
-- [ ] Installation guide
-- [ ] Troubleshooting guide
-
-### 10.2 Testing
-- [ ] Unit tests (pytest)
-- [ ] Integration tests
-- [ ] E2E tests (Playwright/Cypress)
-- [ ] Load testing
-
-### 10.3 Production Readiness
-- [ ] Production Docker image
-- [ ] One-liner installation script
-- [ ] Update mechanism
-- [ ] Migration tools
-- [ ] CLI tool for management
-
----
-
-## Tech Stack Summary
-
-| Component | Technology |
-|-----------|------------|
-| **Backend** | Python 3.11+, Flask, SQLAlchemy |
-| **Frontend** | React 18, Vite, TailwindCSS |
-| **Database** | SQLite (dev), PostgreSQL (prod) |
-| **Web Server** | Nginx |
-| **Process Manager** | Supervisor/systemd |
-| **Container Runtime** | Docker |
-| **Task Queue** | Celery + Redis (optional) |
-| **Real-time** | WebSocket (Flask-SocketIO) |
-
----
-
-## Milestones
-
-| Milestone | Target | Status |
-|-----------|--------|--------|
-| **v0.1 - Alpha** | Core API + Auth + Basic Dashboard | Not Started |
-| **v0.2 - PHP Support** | PHP-FPM + WordPress | Not Started |
-| **v0.3 - Python Apps** | Flask/Django deployment | Not Started |
-| **v0.4 - Docker** | Container management | Not Started |
-| **v0.5 - Databases** | MySQL/PostgreSQL management | Not Started |
-| **v1.0 - Stable** | Production ready | Not Started |
-
----
-
-## Contributing
-
-1. Pick an unchecked item from the roadmap
-2. Create a feature branch
-3. Implement with tests
-4. Submit a PR
-
----
-
-*Last updated: January 2026*
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index b69a6a7d..2e74ce2f 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -113,6 +113,10 @@ def create_app(config_name=None):
from app.api.builds import builds_bp
app.register_blueprint(builds_bp, url_prefix='/api/v1/builds')
+ # Register blueprints - Templates
+ from app.api.templates import templates_bp
+ app.register_blueprint(templates_bp, url_prefix='/api/v1/templates')
+
# Register blueprints - File Manager
from app.api.files import files_bp
app.register_blueprint(files_bp, url_prefix='/api/v1/files')
diff --git a/backend/app/api/templates.py b/backend/app/api/templates.py
new file mode 100644
index 00000000..a1f1583a
--- /dev/null
+++ b/backend/app/api/templates.py
@@ -0,0 +1,313 @@
+"""
+Template API Endpoints
+
+Provides REST endpoints for:
+- Listing and browsing templates
+- Template installation
+- App updates from templates
+- Template repository management
+"""
+
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required, get_jwt_identity
+from app.models import User, Application
+from app.services.template_service import TemplateService
+
+templates_bp = Blueprint('templates', __name__)
+
+
+def admin_required(fn):
+ """Decorator to require admin role."""
+ from functools import wraps
+
+ @wraps(fn)
+ def wrapper(*args, **kwargs):
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ if not user or user.role != 'admin':
+ return jsonify({'error': 'Admin access required'}), 403
+ return fn(*args, **kwargs)
+ return wrapper
+
+
+# ==================== TEMPLATE BROWSING ====================
+
+@templates_bp.route('/', methods=['GET'])
+@jwt_required()
+def list_templates():
+ """List all available templates."""
+ category = request.args.get('category')
+ search = request.args.get('search')
+
+ templates = TemplateService.list_all_templates(category=category, search=search)
+
+ return jsonify({
+ 'templates': templates,
+ 'count': len(templates)
+ }), 200
+
+
+@templates_bp.route('/categories', methods=['GET'])
+@jwt_required()
+def get_categories():
+ """Get all template categories."""
+ categories = TemplateService.get_categories()
+ return jsonify({'categories': categories}), 200
+
+
+@templates_bp.route('/<template_id>', methods=['GET'])
+@jwt_required()
+def get_template(template_id):
+ """Get detailed template information."""
+ result = TemplateService.get_template(template_id)
+
+ if not result.get('success'):
+ return jsonify(result), 404
+
+ template = result['template']
+
+ # Add processed variable info
+ variables = []
+ for var_name, var_config in template.get('variables', {}).items():
+ variables.append({
+ 'name': var_name,
+ 'description': var_config.get('description', ''),
+ 'type': var_config.get('type', 'string'),
+ 'default': var_config.get('default', ''),
+ 'required': var_config.get('required', False),
+ 'options': var_config.get('options', None)
+ })
+
+ return jsonify({
+ 'template': {
+ 'id': template_id,
+ 'name': template.get('name'),
+ 'version': template.get('version'),
+ 'description': template.get('description'),
+ 'icon': template.get('icon'),
+ 'categories': template.get('categories', []),
+ 'source': template.get('source'),
+ 'documentation': template.get('documentation'),
+ 'website': template.get('website'),
+ 'variables': variables,
+ 'has_compose': 'compose' in template,
+ 'has_dockerfile': 'dockerfile' in template,
+ 'scripts': list(template.get('scripts', {}).keys()),
+ 'requirements': template.get('requirements', {}),
+ 'ports': template.get('ports', [])
+ }
+ }), 200
+
+
+# ==================== TEMPLATE INSTALLATION ====================
+
+@templates_bp.route('/<template_id>/install', methods=['POST'])
+@jwt_required()
+@admin_required
+def install_template(template_id):
+ """Install a template as a new application."""
+ current_user_id = get_jwt_identity()
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ app_name = data.get('app_name')
+ if not app_name:
+ return jsonify({'error': 'app_name is required'}), 400
+
+ # Validate app name
+ import re
+ if not re.match(r'^[a-z0-9][a-z0-9-]*[a-z0-9]$', app_name) or len(app_name) < 3:
+ return jsonify({
+ 'error': 'App name must be lowercase alphanumeric with hyphens, at least 3 characters'
+ }), 400
+
+ user_variables = data.get('variables', {})
+
+ result = TemplateService.install_template(
+ template_id=template_id,
+ app_name=app_name,
+ user_variables=user_variables,
+ user_id=current_user_id
+ )
+
+ return jsonify(result), 201 if result.get('success') else 400
+
+
+@templates_bp.route('/validate-install', methods=['POST'])
+@jwt_required()
+def validate_installation():
+ """Validate template installation parameters before installing."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ template_id = data.get('template_id')
+ app_name = data.get('app_name')
+ user_variables = data.get('variables', {})
+
+ errors = []
+
+ # Validate app name
+ import re
+ if not app_name:
+ errors.append('App name is required')
+ elif not re.match(r'^[a-z0-9][a-z0-9-]*[a-z0-9]$', app_name) or len(app_name) < 3:
+ errors.append('App name must be lowercase alphanumeric with hyphens, at least 3 characters')
+
+ # Check if app name is taken
+ existing = Application.query.filter_by(name=app_name).first()
+ if existing:
+ errors.append(f'An application named "{app_name}" already exists')
+
+ # Validate template exists and check required variables
+ result = TemplateService.get_template(template_id)
+ if not result.get('success'):
+ errors.append('Template not found')
+ else:
+ template = result['template']
+ for var_name, var_config in template.get('variables', {}).items():
+ if var_config.get('required', False) and var_name not in user_variables:
+ errors.append(f'Required variable "{var_name}" is not provided')
+
+ if errors:
+ return jsonify({'valid': False, 'errors': errors}), 400
+
+ return jsonify({'valid': True}), 200
+
+
+# ==================== APP UPDATES ====================
+
+@templates_bp.route('/apps/<int:app_id>/check-update', methods=['GET'])
+@jwt_required()
+def check_app_update(app_id):
+ """Check if an installed app has updates available."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ result = TemplateService.check_updates(app_id)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@templates_bp.route('/apps/<int:app_id>/update', methods=['POST'])
+@jwt_required()
+@admin_required
+def update_app(app_id):
+ """Update an app to the latest template version."""
+ current_user_id = get_jwt_identity()
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ result = TemplateService.update_app(app_id, user_id=current_user_id)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@templates_bp.route('/apps/<int:app_id>/template-info', methods=['GET'])
+@jwt_required()
+def get_app_template_info(app_id):
+ """Get template installation info for an app."""
+ current_user_id = get_jwt_identity()
+ user = User.query.get(current_user_id)
+ app = Application.query.get(app_id)
+
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+
+ if user.role != 'admin' and app.user_id != current_user_id:
+ return jsonify({'error': 'Access denied'}), 403
+
+ info = TemplateService.get_installed_info(app_id)
+ if info:
+ return jsonify({'installed_from_template': True, 'info': info}), 200
+
+ return jsonify({'installed_from_template': False}), 200
+
+
+# ==================== REPOSITORY MANAGEMENT ====================
+
+@templates_bp.route('/repos', methods=['GET'])
+@jwt_required()
+def list_repositories():
+ """List configured template repositories."""
+ repos = TemplateService.list_repositories()
+ return jsonify({'repositories': repos}), 200
+
+
+@templates_bp.route('/repos', methods=['POST'])
+@jwt_required()
+@admin_required
+def add_repository():
+ """Add a template repository."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ name = data.get('name')
+ url = data.get('url')
+
+ if not name or not url:
+ return jsonify({'error': 'name and url are required'}), 400
+
+ result = TemplateService.add_repository(name, url)
+ return jsonify(result), 201 if result.get('success') else 400
+
+
+@templates_bp.route('/repos', methods=['DELETE'])
+@jwt_required()
+@admin_required
+def remove_repository():
+ """Remove a template repository."""
+ data = request.get_json()
+ url = data.get('url') if data else None
+
+ if not url:
+ return jsonify({'error': 'url is required'}), 400
+
+ result = TemplateService.remove_repository(url)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
+@templates_bp.route('/sync', methods=['POST'])
+@jwt_required()
+@admin_required
+def sync_templates():
+ """Sync templates from all repositories."""
+ result = TemplateService.sync_templates()
+ return jsonify(result), 200
+
+
+# ==================== LOCAL TEMPLATE MANAGEMENT ====================
+
+@templates_bp.route('/local', methods=['POST'])
+@jwt_required()
+@admin_required
+def create_local_template():
+ """Create a local template."""
+ data = request.get_json()
+
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ result = TemplateService.create_local_template(data)
+ return jsonify(result), 201 if result.get('success') else 400
+
+
+@templates_bp.route('/local/<template_id>', methods=['DELETE'])
+@jwt_required()
+@admin_required
+def delete_local_template(template_id):
+ """Delete a local template."""
+ result = TemplateService.delete_local_template(template_id)
+ return jsonify(result), 200 if result.get('success') else 404
diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.py
new file mode 100644
index 00000000..14a6cd6e
--- /dev/null
+++ b/backend/app/services/template_service.py
@@ -0,0 +1,730 @@
+"""
+Template Service - Manages application templates for one-click deployment.
+
+Supports:
+- YAML-based template schema
+- Docker Compose compatibility
+- Variable substitution
+- Post-install scripts
+- Template repositories (local + remote)
+- Update mechanism
+"""
+
+import os
+import re
+import yaml
+import json
+import shutil
+import secrets
+import string
+import hashlib
+import subprocess
+from datetime import datetime
+from typing import Dict, List, Optional, Any
+from pathlib import Path
+import requests
+
+
+class TemplateService:
+ """Service for managing and deploying application templates."""
+
+ CONFIG_DIR = '/etc/serverkit'
+ TEMPLATES_DIR = '/etc/serverkit/templates'
+ INSTALLED_DIR = '/var/serverkit/apps'
+ TEMPLATE_CONFIG = os.path.join(CONFIG_DIR, 'templates.json')
+
+ # Default template repository
+ DEFAULT_REPOS = [
+ {
+ 'name': 'serverkit-official',
+ 'url': 'https://raw.githubusercontent.com/serverkit/templates/main',
+ 'enabled': True
+ }
+ ]
+
+ # Template schema version
+ SCHEMA_VERSION = '1.0'
+
+ @classmethod
+ def get_config(cls) -> Dict:
+ """Get template configuration."""
+ if os.path.exists(cls.TEMPLATE_CONFIG):
+ try:
+ with open(cls.TEMPLATE_CONFIG, 'r') as f:
+ return json.load(f)
+ except Exception:
+ pass
+ return {
+ 'repos': cls.DEFAULT_REPOS,
+ 'installed': {},
+ 'last_sync': None
+ }
+
+ @classmethod
+ def save_config(cls, config: Dict) -> Dict:
+ """Save template configuration."""
+ try:
+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)
+ with open(cls.TEMPLATE_CONFIG, 'w') as f:
+ json.dump(config, f, indent=2)
+ return {'success': True}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def validate_template(cls, template: Dict) -> Dict:
+ """Validate a template against the schema."""
+ errors = []
+
+ # Required fields
+ required = ['name', 'version', 'description']
+ for field in required:
+ if field not in template:
+ errors.append(f"Missing required field: {field}")
+
+ # Must have either compose or dockerfile
+ if 'compose' not in template and 'dockerfile' not in template:
+ errors.append("Template must have either 'compose' or 'dockerfile'")
+
+ # Validate compose structure
+ if 'compose' in template:
+ compose = template['compose']
+ if 'services' not in compose:
+ errors.append("Compose section must have 'services'")
+
+ # Validate variables
+ if 'variables' in template:
+ for var_name, var_config in template['variables'].items():
+ if not isinstance(var_config, dict):
+ errors.append(f"Variable {var_name} must be a dictionary")
+
+ if errors:
+ return {'valid': False, 'errors': errors}
+ return {'valid': True}
+
+ @classmethod
+ def parse_template(cls, template_path: str) -> Dict:
+ """Parse a template file."""
+ try:
+ with open(template_path, 'r') as f:
+ template = yaml.safe_load(f)
+
+ validation = cls.validate_template(template)
+ if not validation['valid']:
+ return {'success': False, 'errors': validation['errors']}
+
+ return {'success': True, 'template': template}
+ except yaml.YAMLError as e:
+ return {'success': False, 'error': f"YAML parse error: {e}"}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def generate_value(cls, var_config: Dict) -> str:
+ """Generate a value for a variable based on its configuration."""
+ var_type = var_config.get('type', 'string')
+ default = var_config.get('default', '')
+
+ if var_type == 'password':
+ length = var_config.get('length', 32)
+ chars = string.ascii_letters + string.digits
+ if var_config.get('special_chars', False):
+ chars += '!@#$%^&*'
+ return ''.join(secrets.choice(chars) for _ in range(length))
+
+ elif var_type == 'port':
+ # Find available port starting from default
+ import socket
+ start_port = int(default) if default else 8000
+ for port in range(start_port, start_port + 100):
+ try:
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.bind(('', port))
+ sock.close()
+ return str(port)
+ except OSError:
+ continue
+ return str(start_port)
+
+ elif var_type == 'uuid':
+ import uuid
+ return str(uuid.uuid4())
+
+ elif var_type == 'random':
+ length = var_config.get('length', 16)
+ return secrets.token_hex(length // 2)
+
+ return str(default)
+
+ @classmethod
+ def substitute_variables(cls, content: str, variables: Dict) -> str:
+ """Substitute variables in content using ${VAR} syntax."""
+ def replace_var(match):
+ var_name = match.group(1)
+ return str(variables.get(var_name, match.group(0)))
+
+ # Replace ${VAR} patterns
+ pattern = r'\$\{([A-Z_][A-Z0-9_]*)\}'
+ return re.sub(pattern, replace_var, content)
+
+ @classmethod
+ def substitute_in_dict(cls, data: Any, variables: Dict) -> Any:
+ """Recursively substitute variables in a dictionary."""
+ if isinstance(data, str):
+ return cls.substitute_variables(data, variables)
+ elif isinstance(data, dict):
+ return {k: cls.substitute_in_dict(v, variables) for k, v in data.items()}
+ elif isinstance(data, list):
+ return [cls.substitute_in_dict(item, variables) for item in data]
+ return data
+
+ @classmethod
+ def generate_compose(cls, template: Dict, variables: Dict) -> str:
+ """Generate docker-compose.yml from template."""
+ compose = template.get('compose', {})
+
+ # Substitute variables
+ compose = cls.substitute_in_dict(compose, variables)
+
+ # Add version if not present
+ if 'version' not in compose:
+ compose = {'version': '3.8', **compose}
+
+ return yaml.dump(compose, default_flow_style=False, sort_keys=False)
+
+ @classmethod
+ def list_local_templates(cls) -> List[Dict]:
+ """List locally available templates."""
+ templates = []
+
+ if not os.path.exists(cls.TEMPLATES_DIR):
+ return templates
+
+ for filename in os.listdir(cls.TEMPLATES_DIR):
+ if filename.endswith('.yaml') or filename.endswith('.yml'):
+ filepath = os.path.join(cls.TEMPLATES_DIR, filename)
+ result = cls.parse_template(filepath)
+ if result.get('success'):
+ template = result['template']
+ templates.append({
+ 'id': filename.rsplit('.', 1)[0],
+ 'name': template.get('name'),
+ 'version': template.get('version'),
+ 'description': template.get('description'),
+ 'icon': template.get('icon'),
+ 'categories': template.get('categories', []),
+ 'source': 'local',
+ 'filepath': filepath
+ })
+
+ return templates
+
+ @classmethod
+ def fetch_remote_templates(cls, repo_url: str) -> List[Dict]:
+ """Fetch templates from a remote repository."""
+ templates = []
+
+ try:
+ # Fetch index.json from repo
+ index_url = f"{repo_url}/index.json"
+ response = requests.get(index_url, timeout=30)
+ response.raise_for_status()
+
+ index = response.json()
+ for template_info in index.get('templates', []):
+ template_info['source'] = 'remote'
+ template_info['repo_url'] = repo_url
+ templates.append(template_info)
+
+ except Exception as e:
+ print(f"Failed to fetch templates from {repo_url}: {e}")
+
+ return templates
+
+ @classmethod
+ def list_all_templates(cls, category: str = None, search: str = None) -> List[Dict]:
+ """List all available templates from all sources."""
+ templates = []
+
+ # Local templates
+ templates.extend(cls.list_local_templates())
+
+ # Remote templates
+ config = cls.get_config()
+ for repo in config.get('repos', []):
+ if repo.get('enabled', True):
+ templates.extend(cls.fetch_remote_templates(repo['url']))
+
+ # Filter by category
+ if category:
+ templates = [t for t in templates if category in t.get('categories', [])]
+
+ # Search filter
+ if search:
+ search_lower = search.lower()
+ templates = [
+ t for t in templates
+ if search_lower in t.get('name', '').lower()
+ or search_lower in t.get('description', '').lower()
+ ]
+
+ return templates
+
+ @classmethod
+ def get_template(cls, template_id: str) -> Dict:
+ """Get full template details."""
+ # Check local first
+ for ext in ['.yaml', '.yml']:
+ filepath = os.path.join(cls.TEMPLATES_DIR, f"{template_id}{ext}")
+ if os.path.exists(filepath):
+ result = cls.parse_template(filepath)
+ if result.get('success'):
+ template = result['template']
+ template['source'] = 'local'
+ template['filepath'] = filepath
+ return {'success': True, 'template': template}
+ return result
+
+ # Check remote repos
+ config = cls.get_config()
+ for repo in config.get('repos', []):
+ if not repo.get('enabled', True):
+ continue
+
+ try:
+ url = f"{repo['url']}/templates/{template_id}.yaml"
+ response = requests.get(url, timeout=30)
+ if response.status_code == 200:
+ template = yaml.safe_load(response.text)
+ validation = cls.validate_template(template)
+ if validation['valid']:
+ template['source'] = 'remote'
+ template['repo_url'] = repo['url']
+ return {'success': True, 'template': template}
+ except Exception:
+ continue
+
+ return {'success': False, 'error': 'Template not found'}
+
+ @classmethod
+ def install_template(cls, template_id: str, app_name: str,
+ user_variables: Dict = None, user_id: int = None) -> Dict:
+ """Install a template as a new application."""
+ from app.models import Application, db
+ from app.services.docker_service import DockerService
+
+ # Get template
+ result = cls.get_template(template_id)
+ if not result.get('success'):
+ return result
+
+ template = result['template']
+
+ # Prepare variables
+ variables = {}
+ template_vars = template.get('variables', {})
+
+ for var_name, var_config in template_vars.items():
+ if user_variables and var_name in user_variables:
+ variables[var_name] = user_variables[var_name]
+ elif var_config.get('required', False) and var_name not in (user_variables or {}):
+ return {'success': False, 'error': f"Required variable not provided: {var_name}"}
+ else:
+ variables[var_name] = cls.generate_value(var_config)
+
+ # Create app directory
+ app_path = os.path.join(cls.INSTALLED_DIR, app_name)
+ if os.path.exists(app_path):
+ return {'success': False, 'error': f"App directory already exists: {app_path}"}
+
+ try:
+ os.makedirs(app_path, exist_ok=True)
+
+ # Generate docker-compose.yml
+ compose_content = cls.generate_compose(template, variables)
+ compose_path = os.path.join(app_path, 'docker-compose.yml')
+ with open(compose_path, 'w') as f:
+ f.write(compose_content)
+
+ # Save installation info
+ install_info = {
+ 'template_id': template_id,
+ 'template_version': template.get('version'),
+ 'template_name': template.get('name'),
+ 'installed_at': datetime.now().isoformat(),
+ 'variables': variables,
+ 'user_id': user_id
+ }
+ info_path = os.path.join(app_path, '.serverkit-template.json')
+ with open(info_path, 'w') as f:
+ json.dump(install_info, f, indent=2)
+
+ # Save .env file with variables
+ env_path = os.path.join(app_path, '.env')
+ with open(env_path, 'w') as f:
+ for key, value in variables.items():
+ f.write(f"{key}={value}\n")
+
+ # Run pre-install script if exists
+ if 'scripts' in template and 'pre_install' in template['scripts']:
+ script_result = cls._run_script(
+ template['scripts']['pre_install'],
+ app_path,
+ variables
+ )
+ if not script_result.get('success'):
+ shutil.rmtree(app_path)
+ return script_result
+
+ # Start the app with docker compose
+ compose_result = DockerService.compose_up(app_path, detach=True, build=True)
+ if not compose_result.get('success'):
+ shutil.rmtree(app_path)
+ return compose_result
+
+ # Run post-install script if exists
+ if 'scripts' in template and 'post_install' in template['scripts']:
+ cls._run_script(
+ template['scripts']['post_install'],
+ app_path,
+ variables
+ )
+
+ # Create application record
+ app = Application(
+ name=app_name,
+ app_type='docker',
+ status='running',
+ root_path=app_path,
+ docker_image=template.get('name'),
+ user_id=user_id or 1,
+ port=int(variables.get('PORT', 0)) if 'PORT' in variables else None
+ )
+ db.session.add(app)
+ db.session.commit()
+
+ # Update installed config
+ config = cls.get_config()
+ config.setdefault('installed', {})[str(app.id)] = {
+ 'template_id': template_id,
+ 'template_version': template.get('version'),
+ 'app_id': app.id,
+ 'app_name': app_name,
+ 'installed_at': datetime.now().isoformat()
+ }
+ cls.save_config(config)
+
+ return {
+ 'success': True,
+ 'app_id': app.id,
+ 'app_name': app_name,
+ 'app_path': app_path,
+ 'variables': variables
+ }
+
+ except Exception as e:
+ if os.path.exists(app_path):
+ shutil.rmtree(app_path)
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _run_script(cls, script: str, cwd: str, variables: Dict) -> Dict:
+ """Run a script with variable substitution."""
+ try:
+ script = cls.substitute_variables(script, variables)
+
+ env = os.environ.copy()
+ env.update(variables)
+
+ result = subprocess.run(
+ script,
+ shell=True,
+ cwd=cwd,
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=300
+ )
+
+ if result.returncode != 0:
+ return {
+ 'success': False,
+ 'error': f"Script failed: {result.stderr}",
+ 'output': result.stdout
+ }
+
+ return {'success': True, 'output': result.stdout}
+
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Script timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def check_updates(cls, app_id: int) -> Dict:
+ """Check if an installed app has template updates available."""
+ config = cls.get_config()
+ installed = config.get('installed', {}).get(str(app_id))
+
+ if not installed:
+ return {'success': False, 'error': 'App not installed from template'}
+
+ template_id = installed['template_id']
+ installed_version = installed['template_version']
+
+ # Get latest template
+ result = cls.get_template(template_id)
+ if not result.get('success'):
+ return result
+
+ latest_version = result['template'].get('version')
+
+ return {
+ 'success': True,
+ 'installed_version': installed_version,
+ 'latest_version': latest_version,
+ 'update_available': latest_version != installed_version
+ }
+
+ @classmethod
+ def update_app(cls, app_id: int, user_id: int = None) -> Dict:
+ """Update an installed app to the latest template version."""
+ from app.models import Application, db
+ from app.services.docker_service import DockerService
+
+ config = cls.get_config()
+ installed = config.get('installed', {}).get(str(app_id))
+
+ if not installed:
+ return {'success': False, 'error': 'App not installed from template'}
+
+ app = Application.query.get(app_id)
+ if not app:
+ return {'success': False, 'error': 'Application not found'}
+
+ template_id = installed['template_id']
+ app_path = app.root_path
+
+ # Get latest template
+ result = cls.get_template(template_id)
+ if not result.get('success'):
+ return result
+
+ template = result['template']
+
+ # Load existing variables
+ info_path = os.path.join(app_path, '.serverkit-template.json')
+ try:
+ with open(info_path, 'r') as f:
+ install_info = json.load(f)
+ variables = install_info.get('variables', {})
+ except Exception:
+ variables = {}
+
+ # Add any new variables with defaults
+ for var_name, var_config in template.get('variables', {}).items():
+ if var_name not in variables:
+ variables[var_name] = cls.generate_value(var_config)
+
+ try:
+ # Backup current compose
+ compose_path = os.path.join(app_path, 'docker-compose.yml')
+ backup_path = os.path.join(app_path, 'docker-compose.yml.bak')
+ if os.path.exists(compose_path):
+ shutil.copy(compose_path, backup_path)
+
+ # Run pre-update script
+ if 'scripts' in template and 'pre_update' in template['scripts']:
+ script_result = cls._run_script(
+ template['scripts']['pre_update'],
+ app_path,
+ variables
+ )
+ if not script_result.get('success'):
+ return script_result
+
+ # Stop current containers
+ DockerService.compose_down(app_path)
+
+ # Generate new docker-compose.yml
+ compose_content = cls.generate_compose(template, variables)
+ with open(compose_path, 'w') as f:
+ f.write(compose_content)
+
+ # Update installation info
+ install_info['template_version'] = template.get('version')
+ install_info['updated_at'] = datetime.now().isoformat()
+ install_info['variables'] = variables
+ with open(info_path, 'w') as f:
+ json.dump(install_info, f, indent=2)
+
+ # Pull new images and start
+ DockerService.compose_pull(app_path)
+ compose_result = DockerService.compose_up(app_path, detach=True, build=True)
+
+ if not compose_result.get('success'):
+ # Rollback
+ if os.path.exists(backup_path):
+ shutil.copy(backup_path, compose_path)
+ DockerService.compose_up(app_path, detach=True)
+ return compose_result
+
+ # Run post-update script
+ if 'scripts' in template and 'post_update' in template['scripts']:
+ cls._run_script(
+ template['scripts']['post_update'],
+ app_path,
+ variables
+ )
+
+ # Update config
+ config['installed'][str(app_id)]['template_version'] = template.get('version')
+ config['installed'][str(app_id)]['updated_at'] = datetime.now().isoformat()
+ cls.save_config(config)
+
+ # Remove backup
+ if os.path.exists(backup_path):
+ os.remove(backup_path)
+
+ return {
+ 'success': True,
+ 'version': template.get('version'),
+ 'app_id': app_id
+ }
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_installed_info(cls, app_id: int) -> Optional[Dict]:
+ """Get template installation info for an app."""
+ config = cls.get_config()
+ return config.get('installed', {}).get(str(app_id))
+
+ @classmethod
+ def add_repository(cls, name: str, url: str) -> Dict:
+ """Add a template repository."""
+ config = cls.get_config()
+
+ # Check if already exists
+ for repo in config.get('repos', []):
+ if repo['url'] == url:
+ return {'success': False, 'error': 'Repository already exists'}
+
+ config.setdefault('repos', []).append({
+ 'name': name,
+ 'url': url.rstrip('/'),
+ 'enabled': True,
+ 'added_at': datetime.now().isoformat()
+ })
+
+ return cls.save_config(config)
+
+ @classmethod
+ def remove_repository(cls, url: str) -> Dict:
+ """Remove a template repository."""
+ config = cls.get_config()
+ config['repos'] = [r for r in config.get('repos', []) if r['url'] != url]
+ return cls.save_config(config)
+
+ @classmethod
+ def list_repositories(cls) -> List[Dict]:
+ """List configured template repositories."""
+ config = cls.get_config()
+ return config.get('repos', cls.DEFAULT_REPOS)
+
+ @classmethod
+ def sync_templates(cls) -> Dict:
+ """Sync templates from all repositories."""
+ os.makedirs(cls.TEMPLATES_DIR, exist_ok=True)
+
+ config = cls.get_config()
+ synced = 0
+ errors = []
+
+ for repo in config.get('repos', []):
+ if not repo.get('enabled', True):
+ continue
+
+ try:
+ # Fetch index
+ index_url = f"{repo['url']}/index.json"
+ response = requests.get(index_url, timeout=30)
+ response.raise_for_status()
+
+ index = response.json()
+
+ # Download each template
+ for template_info in index.get('templates', []):
+ template_id = template_info.get('id')
+ if not template_id:
+ continue
+
+ try:
+ template_url = f"{repo['url']}/templates/{template_id}.yaml"
+ response = requests.get(template_url, timeout=30)
+ response.raise_for_status()
+
+ # Save locally
+ filepath = os.path.join(cls.TEMPLATES_DIR, f"{template_id}.yaml")
+ with open(filepath, 'w') as f:
+ f.write(response.text)
+
+ synced += 1
+ except Exception as e:
+ errors.append(f"Failed to sync {template_id}: {e}")
+
+ except Exception as e:
+ errors.append(f"Failed to sync from {repo['name']}: {e}")
+
+ config['last_sync'] = datetime.now().isoformat()
+ cls.save_config(config)
+
+ return {
+ 'success': True,
+ 'synced': synced,
+ 'errors': errors if errors else None
+ }
+
+ @classmethod
+ def get_categories(cls) -> List[str]:
+ """Get all available template categories."""
+ templates = cls.list_all_templates()
+ categories = set()
+ for template in templates:
+ categories.update(template.get('categories', []))
+ return sorted(categories)
+
+ @classmethod
+ def create_local_template(cls, template_data: Dict) -> Dict:
+ """Create a local template."""
+ validation = cls.validate_template(template_data)
+ if not validation['valid']:
+ return {'success': False, 'errors': validation['errors']}
+
+ os.makedirs(cls.TEMPLATES_DIR, exist_ok=True)
+
+ template_id = template_data['name'].lower().replace(' ', '-')
+ filepath = os.path.join(cls.TEMPLATES_DIR, f"{template_id}.yaml")
+
+ if os.path.exists(filepath):
+ return {'success': False, 'error': 'Template with this name already exists'}
+
+ try:
+ with open(filepath, 'w') as f:
+ yaml.dump(template_data, f, default_flow_style=False, sort_keys=False)
+
+ return {'success': True, 'template_id': template_id, 'filepath': filepath}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def delete_local_template(cls, template_id: str) -> Dict:
+ """Delete a local template."""
+ for ext in ['.yaml', '.yml']:
+ filepath = os.path.join(cls.TEMPLATES_DIR, f"{template_id}{ext}")
+ if os.path.exists(filepath):
+ os.remove(filepath)
+ return {'success': True}
+
+ return {'success': False, 'error': 'Template not found'}
diff --git a/backend/templates/ghost.yaml b/backend/templates/ghost.yaml
new file mode 100644
index 00000000..66e156fb
--- /dev/null
+++ b/backend/templates/ghost.yaml
@@ -0,0 +1,70 @@
+name: ghost
+version: "5.75"
+description: Professional publishing platform for blogs and newsletters
+icon: /icons/ghost.png
+categories:
+ - cms
+ - blog
+ - publishing
+website: https://ghost.org
+documentation: https://ghost.org/docs
+
+variables:
+ PORT:
+ type: port
+ default: 2368
+ description: Port to expose Ghost
+ SITE_URL:
+ type: string
+ default: http://localhost:2368
+ description: Full URL where Ghost will be accessible
+ required: true
+ DB_PASSWORD:
+ type: password
+ length: 24
+ description: MySQL database password
+
+compose:
+ services:
+ ghost:
+ image: ghost:5-alpine
+ container_name: ghost
+ restart: unless-stopped
+ ports:
+ - "${PORT}:2368"
+ environment:
+ url: "${SITE_URL}"
+ database__client: mysql
+ database__connection__host: ghost-db
+ database__connection__user: ghost
+ database__connection__password: "${DB_PASSWORD}"
+ database__connection__database: ghost
+ volumes:
+ - ghost-content:/var/lib/ghost/content
+ depends_on:
+ - ghost-db
+
+ ghost-db:
+ image: mysql:8.0
+ container_name: ghost-db
+ restart: unless-stopped
+ environment:
+ MYSQL_ROOT_PASSWORD: "${DB_PASSWORD}"
+ MYSQL_USER: ghost
+ MYSQL_PASSWORD: "${DB_PASSWORD}"
+ MYSQL_DATABASE: ghost
+ volumes:
+ - ghost-db-data:/var/lib/mysql
+
+ volumes:
+ ghost-content:
+ ghost-db-data:
+
+ports:
+ - port: "${PORT}"
+ protocol: http
+ description: Ghost Blog
+
+requirements:
+ memory: 512MB
+ storage: 2GB
diff --git a/backend/templates/gitea.yaml b/backend/templates/gitea.yaml
new file mode 100644
index 00000000..56f1bf9d
--- /dev/null
+++ b/backend/templates/gitea.yaml
@@ -0,0 +1,80 @@
+name: gitea
+version: "1.21"
+description: Lightweight self-hosted Git service
+icon: /icons/gitea.png
+categories:
+ - devops
+ - git
+ - development
+website: https://gitea.io
+documentation: https://docs.gitea.io
+
+variables:
+ HTTP_PORT:
+ type: port
+ default: 3000
+ description: Port for web interface
+ SSH_PORT:
+ type: port
+ default: 2222
+ description: Port for SSH access
+ DB_PASSWORD:
+ type: password
+ length: 24
+ description: Database password
+ SECRET_KEY:
+ type: random
+ length: 32
+ description: Internal secret key
+
+compose:
+ services:
+ gitea:
+ image: gitea/gitea:1.21
+ container_name: gitea
+ restart: unless-stopped
+ ports:
+ - "${HTTP_PORT}:3000"
+ - "${SSH_PORT}:22"
+ environment:
+ USER_UID: 1000
+ USER_GID: 1000
+ GITEA__database__DB_TYPE: postgres
+ GITEA__database__HOST: gitea-db:5432
+ GITEA__database__NAME: gitea
+ GITEA__database__USER: gitea
+ GITEA__database__PASSWD: "${DB_PASSWORD}"
+ GITEA__security__SECRET_KEY: "${SECRET_KEY}"
+ volumes:
+ - gitea-data:/data
+ - /etc/timezone:/etc/timezone:ro
+ - /etc/localtime:/etc/localtime:ro
+ depends_on:
+ - gitea-db
+
+ gitea-db:
+ image: postgres:15-alpine
+ container_name: gitea-db
+ restart: unless-stopped
+ environment:
+ POSTGRES_USER: gitea
+ POSTGRES_PASSWORD: "${DB_PASSWORD}"
+ POSTGRES_DB: gitea
+ volumes:
+ - gitea-db-data:/var/lib/postgresql/data
+
+ volumes:
+ gitea-data:
+ gitea-db-data:
+
+ports:
+ - port: "${HTTP_PORT}"
+ protocol: http
+ description: Web Interface
+ - port: "${SSH_PORT}"
+ protocol: ssh
+ description: Git SSH
+
+requirements:
+ memory: 512MB
+ storage: 5GB
diff --git a/backend/templates/index.json b/backend/templates/index.json
new file mode 100644
index 00000000..27e0d376
--- /dev/null
+++ b/backend/templates/index.json
@@ -0,0 +1,54 @@
+{
+ "version": "1.0",
+ "updated_at": "2024-01-18",
+ "templates": [
+ {
+ "id": "uptime-kuma",
+ "name": "Uptime Kuma",
+ "version": "1.23",
+ "description": "A fancy self-hosted monitoring tool for websites and services",
+ "icon": "/icons/uptime-kuma.png",
+ "categories": ["monitoring", "devops"]
+ },
+ {
+ "id": "portainer",
+ "name": "Portainer",
+ "version": "2.19",
+ "description": "Lightweight Docker management UI",
+ "icon": "/icons/portainer.png",
+ "categories": ["devops", "docker", "management"]
+ },
+ {
+ "id": "ghost",
+ "name": "Ghost",
+ "version": "5.75",
+ "description": "Professional publishing platform for blogs and newsletters",
+ "icon": "/icons/ghost.png",
+ "categories": ["cms", "blog", "publishing"]
+ },
+ {
+ "id": "nextcloud",
+ "name": "Nextcloud",
+ "version": "28.0",
+ "description": "Self-hosted productivity platform with file sync and collaboration",
+ "icon": "/icons/nextcloud.png",
+ "categories": ["storage", "collaboration", "productivity"]
+ },
+ {
+ "id": "gitea",
+ "name": "Gitea",
+ "version": "1.21",
+ "description": "Lightweight self-hosted Git service",
+ "icon": "/icons/gitea.png",
+ "categories": ["devops", "git", "development"]
+ },
+ {
+ "id": "nginx-proxy-manager",
+ "name": "Nginx Proxy Manager",
+ "version": "2.10",
+ "description": "Easy-to-use reverse proxy with SSL management",
+ "icon": "/icons/nginx-proxy-manager.png",
+ "categories": ["networking", "proxy", "ssl"]
+ }
+ ]
+}
diff --git a/backend/templates/nextcloud.yaml b/backend/templates/nextcloud.yaml
new file mode 100644
index 00000000..53576c99
--- /dev/null
+++ b/backend/templates/nextcloud.yaml
@@ -0,0 +1,94 @@
+name: nextcloud
+version: "28.0"
+description: Self-hosted productivity platform with file sync and collaboration
+icon: /icons/nextcloud.png
+categories:
+ - storage
+ - collaboration
+ - productivity
+website: https://nextcloud.com
+documentation: https://docs.nextcloud.com
+
+variables:
+ PORT:
+ type: port
+ default: 8080
+ description: Port to expose Nextcloud
+ ADMIN_USER:
+ type: string
+ default: admin
+ description: Admin username
+ ADMIN_PASSWORD:
+ type: password
+ length: 16
+ description: Admin password
+ required: true
+ DB_PASSWORD:
+ type: password
+ length: 24
+ description: Database password
+ REDIS_PASSWORD:
+ type: password
+ length: 16
+ description: Redis password
+
+compose:
+ services:
+ nextcloud:
+ image: nextcloud:28-apache
+ container_name: nextcloud
+ restart: unless-stopped
+ ports:
+ - "${PORT}:80"
+ environment:
+ POSTGRES_HOST: nextcloud-db
+ POSTGRES_DB: nextcloud
+ POSTGRES_USER: nextcloud
+ POSTGRES_PASSWORD: "${DB_PASSWORD}"
+ NEXTCLOUD_ADMIN_USER: "${ADMIN_USER}"
+ NEXTCLOUD_ADMIN_PASSWORD: "${ADMIN_PASSWORD}"
+ REDIS_HOST: nextcloud-redis
+ REDIS_HOST_PASSWORD: "${REDIS_PASSWORD}"
+ volumes:
+ - nextcloud-data:/var/www/html
+ depends_on:
+ - nextcloud-db
+ - nextcloud-redis
+
+ nextcloud-db:
+ image: postgres:15-alpine
+ container_name: nextcloud-db
+ restart: unless-stopped
+ environment:
+ POSTGRES_USER: nextcloud
+ POSTGRES_PASSWORD: "${DB_PASSWORD}"
+ POSTGRES_DB: nextcloud
+ volumes:
+ - nextcloud-db-data:/var/lib/postgresql/data
+
+ nextcloud-redis:
+ image: redis:alpine
+ container_name: nextcloud-redis
+ restart: unless-stopped
+ command: redis-server --requirepass "${REDIS_PASSWORD}"
+ volumes:
+ - nextcloud-redis-data:/data
+
+ volumes:
+ nextcloud-data:
+ nextcloud-db-data:
+ nextcloud-redis-data:
+
+ports:
+ - port: "${PORT}"
+ protocol: http
+ description: Web Interface
+
+requirements:
+ memory: 1GB
+ storage: 10GB
+
+scripts:
+ post_install: |
+ echo "Nextcloud installed! Access it at http://localhost:${PORT}"
+ echo "Default admin: ${ADMIN_USER}"
diff --git a/backend/templates/nginx-proxy-manager.yaml b/backend/templates/nginx-proxy-manager.yaml
new file mode 100644
index 00000000..a1e74cde
--- /dev/null
+++ b/backend/templates/nginx-proxy-manager.yaml
@@ -0,0 +1,88 @@
+name: nginx-proxy-manager
+version: "2.10"
+description: Easy-to-use reverse proxy with SSL management
+icon: /icons/nginx-proxy-manager.png
+categories:
+ - networking
+ - proxy
+ - ssl
+website: https://nginxproxymanager.com
+documentation: https://nginxproxymanager.com/guide
+
+variables:
+ HTTP_PORT:
+ type: port
+ default: 80
+ description: HTTP port for proxied sites
+ HTTPS_PORT:
+ type: port
+ default: 443
+ description: HTTPS port for proxied sites
+ ADMIN_PORT:
+ type: port
+ default: 81
+ description: Admin panel port
+ DB_PASSWORD:
+ type: password
+ length: 24
+ description: MySQL database password
+
+compose:
+ services:
+ npm:
+ image: jc21/nginx-proxy-manager:latest
+ container_name: nginx-proxy-manager
+ restart: unless-stopped
+ ports:
+ - "${HTTP_PORT}:80"
+ - "${HTTPS_PORT}:443"
+ - "${ADMIN_PORT}:81"
+ environment:
+ DB_MYSQL_HOST: npm-db
+ DB_MYSQL_PORT: 3306
+ DB_MYSQL_USER: npm
+ DB_MYSQL_PASSWORD: "${DB_PASSWORD}"
+ DB_MYSQL_NAME: npm
+ volumes:
+ - npm-data:/data
+ - npm-letsencrypt:/etc/letsencrypt
+ depends_on:
+ - npm-db
+
+ npm-db:
+ image: jc21/mariadb-aria:latest
+ container_name: npm-db
+ restart: unless-stopped
+ environment:
+ MYSQL_ROOT_PASSWORD: "${DB_PASSWORD}"
+ MYSQL_DATABASE: npm
+ MYSQL_USER: npm
+ MYSQL_PASSWORD: "${DB_PASSWORD}"
+ volumes:
+ - npm-db-data:/var/lib/mysql
+
+ volumes:
+ npm-data:
+ npm-letsencrypt:
+ npm-db-data:
+
+ports:
+ - port: "${ADMIN_PORT}"
+ protocol: http
+ description: Admin Panel
+ - port: "${HTTP_PORT}"
+ protocol: http
+ description: HTTP Proxy
+ - port: "${HTTPS_PORT}"
+ protocol: https
+ description: HTTPS Proxy
+
+requirements:
+ memory: 256MB
+ storage: 1GB
+
+scripts:
+ post_install: |
+ echo "Nginx Proxy Manager installed!"
+ echo "Access admin panel at http://localhost:${ADMIN_PORT}"
+ echo "Default credentials: [email protected] / changeme"
diff --git a/backend/templates/portainer.yaml b/backend/templates/portainer.yaml
new file mode 100644
index 00000000..dbf6ee2a
--- /dev/null
+++ b/backend/templates/portainer.yaml
@@ -0,0 +1,50 @@
+name: portainer
+version: "2.19"
+description: Lightweight Docker management UI
+icon: /icons/portainer.png
+categories:
+ - devops
+ - docker
+ - management
+website: https://www.portainer.io
+documentation: https://docs.portainer.io
+
+variables:
+ PORT:
+ type: port
+ default: 9000
+ description: Port for web interface
+ HTTPS_PORT:
+ type: port
+ default: 9443
+ description: Port for HTTPS access
+
+compose:
+ services:
+ portainer:
+ image: portainer/portainer-ce:latest
+ container_name: portainer
+ restart: unless-stopped
+ ports:
+ - "${PORT}:9000"
+ - "${HTTPS_PORT}:9443"
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+ - portainer-data:/data
+ security_opt:
+ - no-new-privileges:true
+
+ volumes:
+ portainer-data:
+
+ports:
+ - port: "${PORT}"
+ protocol: http
+ description: Web Interface
+ - port: "${HTTPS_PORT}"
+ protocol: https
+ description: HTTPS Interface
+
+requirements:
+ memory: 128MB
+ storage: 500MB
diff --git a/backend/templates/uptime-kuma.yaml b/backend/templates/uptime-kuma.yaml
new file mode 100644
index 00000000..630382aa
--- /dev/null
+++ b/backend/templates/uptime-kuma.yaml
@@ -0,0 +1,45 @@
+name: uptime-kuma
+version: "1.23"
+description: A fancy self-hosted monitoring tool for websites and services
+icon: /icons/uptime-kuma.png
+categories:
+ - monitoring
+ - devops
+website: https://uptime.kuma.pet
+documentation: https://github.com/louislam/uptime-kuma/wiki
+
+variables:
+ PORT:
+ type: port
+ default: 3001
+ description: Port to expose the web interface
+ DATA_PATH:
+ type: string
+ default: ./data
+ description: Path to store data
+
+compose:
+ services:
+ uptime-kuma:
+ image: louislam/uptime-kuma:1
+ container_name: uptime-kuma
+ restart: unless-stopped
+ ports:
+ - "${PORT}:3001"
+ volumes:
+ - uptime-kuma-data:/app/data
+ dns:
+ - 1.1.1.1
+ - 8.8.8.8
+
+ volumes:
+ uptime-kuma-data:
+
+ports:
+ - port: "${PORT}"
+ protocol: http
+ description: Web Interface
+
+requirements:
+ memory: 256MB
+ storage: 1GB
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 781e8334..4c8d6090 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -22,6 +22,7 @@ import PHP from './pages/PHP';
import Firewall from './pages/Firewall';
import CronJobs from './pages/CronJobs';
import Security from './pages/Security';
+import Templates from './pages/Templates';
function PrivateRoute({ children }) {
const { isAuthenticated, loading } = useAuth();
@@ -64,6 +65,7 @@ function AppRoutes() {
<Route index element={<Dashboard />} />
<Route path="apps" element={<Applications />} />
<Route path="apps/:id" element={<ApplicationDetail />} />
+ <Route path="templates" element={<Templates />} />
<Route path="domains" element={<Domains />} />
<Route path="databases" element={<Databases />} />
<Route path="ssl" element={<div className="page">SSL Certificates</div>} />
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 6466460f..6d77eda1 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -47,6 +47,15 @@ const Sidebar = () => {
</svg>
Applications
</NavLink>
+ <NavLink to="/templates" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <rect x="3" y="3" width="7" height="9"/>
+ <rect x="14" y="3" width="7" height="5"/>
+ <rect x="14" y="12" width="7" height="9"/>
+ <rect x="3" y="16" width="7" height="5"/>
+ </svg>
+ Templates
+ </NavLink>
<NavLink to="/databases" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
<svg viewBox="0 0 24 24">
<ellipse cx="12" cy="5" rx="9" ry="3"/>
diff --git a/frontend/src/pages/Templates.jsx b/frontend/src/pages/Templates.jsx
new file mode 100644
index 00000000..ac43797b
--- /dev/null
+++ b/frontend/src/pages/Templates.jsx
@@ -0,0 +1,418 @@
+import { useState, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import api from '../services/api';
+import { useToast } from '../components/Toast';
+
+const Templates = () => {
+ const navigate = useNavigate();
+ const toast = useToast();
+ const [templates, setTemplates] = useState([]);
+ const [categories, setCategories] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedCategory, setSelectedCategory] = useState(null);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [selectedTemplate, setSelectedTemplate] = useState(null);
+ const [showInstallModal, setShowInstallModal] = useState(false);
+
+ useEffect(() => {
+ loadData();
+ }, []);
+
+ useEffect(() => {
+ loadTemplates();
+ }, [selectedCategory, searchQuery]);
+
+ async function loadData() {
+ try {
+ const [templatesRes, categoriesRes] = await Promise.all([
+ api.listTemplates(),
+ api.getTemplateCategories()
+ ]);
+ setTemplates(templatesRes.templates || []);
+ setCategories(categoriesRes.categories || []);
+ } catch (err) {
+ toast.error('Failed to load templates');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function loadTemplates() {
+ try {
+ const result = await api.listTemplates(selectedCategory, searchQuery || null);
+ setTemplates(result.templates || []);
+ } catch (err) {
+ console.error('Failed to load templates:', err);
+ }
+ }
+
+ function getCategoryIcon(category) {
+ const icons = {
+ monitoring: '📊',
+ devops: '⚙️',
+ docker: '🐳',
+ cms: '📝',
+ blog: '✍️',
+ storage: '💾',
+ collaboration: '👥',
+ git: '🔀',
+ development: '💻',
+ networking: '🌐',
+ proxy: '🔄',
+ ssl: '🔒',
+ productivity: '📋',
+ management: '📁',
+ publishing: '📰'
+ };
+ return icons[category] || '📦';
+ }
+
+ async function handleViewTemplate(template) {
+ try {
+ const result = await api.getTemplate(template.id);
+ if (result.template) {
+ setSelectedTemplate(result.template);
+ }
+ } catch (err) {
+ toast.error('Failed to load template details');
+ }
+ }
+
+ if (loading) {
+ return (
+ <div className="page">
+ <div className="loading">Loading templates...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="page templates-page">
+ <div className="page-header">
+ <h1>App Templates</h1>
+ <p className="page-description">One-click deployment for popular self-hosted applications</p>
+ </div>
+
+ {/* Search and Filters */}
+ <div className="templates-filters">
+ <div className="search-box">
+ <input
+ type="text"
+ placeholder="Search templates..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ </div>
+ <div className="category-filters">
+ <button
+ className={`category-btn ${!selectedCategory ? 'active' : ''}`}
+ onClick={() => setSelectedCategory(null)}
+ >
+ All
+ </button>
+ {categories.map(category => (
+ <button
+ key={category}
+ className={`category-btn ${selectedCategory === category ? 'active' : ''}`}
+ onClick={() => setSelectedCategory(category)}
+ >
+ {getCategoryIcon(category)} {category}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Templates Grid */}
+ <div className="templates-grid">
+ {templates.length === 0 ? (
+ <div className="empty-state">
+ <p>No templates found</p>
+ </div>
+ ) : (
+ templates.map(template => (
+ <div key={template.id} className="template-card" onClick={() => handleViewTemplate(template)}>
+ <div className="template-icon">
+ {template.icon ? (
+ <img src={template.icon} alt={template.name} />
+ ) : (
+ <span className="template-icon-placeholder">
+ {template.name?.charAt(0).toUpperCase()}
+ </span>
+ )}
+ </div>
+ <div className="template-info">
+ <h3>{template.name}</h3>
+ <p className="template-description">{template.description}</p>
+ <div className="template-meta">
+ <span className="template-version">v{template.version}</span>
+ <div className="template-categories">
+ {(template.categories || []).slice(0, 2).map(cat => (
+ <span key={cat} className="category-badge">
+ {getCategoryIcon(cat)} {cat}
+ </span>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+
+ {/* Template Detail Modal */}
+ {selectedTemplate && (
+ <div className="modal-overlay" onClick={() => setSelectedTemplate(null)}>
+ <div className="modal modal-lg" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <div className="template-detail-header">
+ <div className="template-icon-large">
+ {selectedTemplate.icon ? (
+ <img src={selectedTemplate.icon} alt={selectedTemplate.name} />
+ ) : (
+ <span className="template-icon-placeholder">
+ {selectedTemplate.name?.charAt(0).toUpperCase()}
+ </span>
+ )}
+ </div>
+ <div>
+ <h2>{selectedTemplate.name}</h2>
+ <span className="template-version">Version {selectedTemplate.version}</span>
+ </div>
+ </div>
+ <button className="modal-close" onClick={() => setSelectedTemplate(null)}>&times;</button>
+ </div>
+ <div className="modal-body">
+ <p className="template-full-description">{selectedTemplate.description}</p>
+
+ <div className="template-links">
+ {selectedTemplate.website && (
+ <a href={selectedTemplate.website} target="_blank" rel="noopener noreferrer" className="btn btn-secondary btn-sm">
+ Website
+ </a>
+ )}
+ {selectedTemplate.documentation && (
+ <a href={selectedTemplate.documentation} target="_blank" rel="noopener noreferrer" className="btn btn-secondary btn-sm">
+ Documentation
+ </a>
+ )}
+ </div>
+
+ <div className="template-details-grid">
+ <div className="detail-section">
+ <h4>Categories</h4>
+ <div className="template-categories">
+ {(selectedTemplate.categories || []).map(cat => (
+ <span key={cat} className="category-badge">
+ {getCategoryIcon(cat)} {cat}
+ </span>
+ ))}
+ </div>
+ </div>
+
+ {selectedTemplate.variables && selectedTemplate.variables.length > 0 && (
+ <div className="detail-section">
+ <h4>Configuration Variables</h4>
+ <div className="variables-list">
+ {selectedTemplate.variables.map(variable => (
+ <div key={variable.name} className="variable-item">
+ <span className="variable-name">{variable.name}</span>
+ <span className="variable-description">{variable.description}</span>
+ {variable.default && (
+ <span className="variable-default">Default: {variable.default}</span>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {selectedTemplate.ports && selectedTemplate.ports.length > 0 && (
+ <div className="detail-section">
+ <h4>Exposed Ports</h4>
+ <div className="ports-list">
+ {selectedTemplate.ports.map((port, index) => (
+ <div key={index} className="port-item">
+ <span className="port-number">{port.port}</span>
+ <span className="port-protocol">{port.protocol}</span>
+ <span className="port-description">{port.description}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setSelectedTemplate(null)}>
+ Close
+ </button>
+ <button
+ className="btn btn-primary"
+ onClick={() => {
+ setShowInstallModal(true);
+ }}
+ >
+ Install Template
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Install Modal */}
+ {showInstallModal && selectedTemplate && (
+ <InstallModal
+ template={selectedTemplate}
+ onClose={() => {
+ setShowInstallModal(false);
+ setSelectedTemplate(null);
+ }}
+ onSuccess={(appId) => {
+ setShowInstallModal(false);
+ setSelectedTemplate(null);
+ toast.success('Application installed successfully!');
+ navigate(`/apps/${appId}`);
+ }}
+ />
+ )}
+ </div>
+ );
+};
+
+const InstallModal = ({ template, onClose, onSuccess }) => {
+ const toast = useToast();
+ const [appName, setAppName] = useState(template.id.toLowerCase().replace(/[^a-z0-9-]/g, '-'));
+ const [variables, setVariables] = useState({});
+ const [installing, setInstalling] = useState(false);
+ const [errors, setErrors] = useState([]);
+
+ useEffect(() => {
+ // Initialize variables with defaults
+ const defaults = {};
+ (template.variables || []).forEach(v => {
+ if (v.default) {
+ defaults[v.name] = v.default;
+ }
+ });
+ setVariables(defaults);
+ }, [template]);
+
+ async function handleInstall(e) {
+ e.preventDefault();
+ setInstalling(true);
+ setErrors([]);
+
+ try {
+ // Validate first
+ const validation = await api.validateTemplateInstall(template.id, appName, variables);
+ if (!validation.valid) {
+ setErrors(validation.errors || ['Validation failed']);
+ setInstalling(false);
+ return;
+ }
+
+ // Install
+ const result = await api.installTemplate(template.id, appName, variables);
+ if (result.success) {
+ onSuccess(result.app_id);
+ } else {
+ setErrors([result.error || 'Installation failed']);
+ }
+ } catch (err) {
+ setErrors([err.message || 'Installation failed']);
+ } finally {
+ setInstalling(false);
+ }
+ }
+
+ return (
+ <div className="modal-overlay" onClick={onClose}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Install {template.name}</h2>
+ <button className="modal-close" onClick={onClose}>&times;</button>
+ </div>
+ <form onSubmit={handleInstall}>
+ <div className="modal-body">
+ {errors.length > 0 && (
+ <div className="alert alert-danger">
+ <ul>
+ {errors.map((error, i) => <li key={i}>{error}</li>)}
+ </ul>
+ </div>
+ )}
+
+ <div className="form-group">
+ <label>Application Name *</label>
+ <input
+ type="text"
+ value={appName}
+ onChange={(e) => setAppName(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '-'))}
+ placeholder="my-app"
+ pattern="[a-z0-9][a-z0-9-]*[a-z0-9]"
+ minLength={3}
+ required
+ />
+ <span className="form-help">Lowercase letters, numbers, and hyphens only</span>
+ </div>
+
+ {(template.variables || []).length > 0 && (
+ <>
+ <h4>Configuration</h4>
+ {template.variables.map(variable => (
+ <div key={variable.name} className="form-group">
+ <label>
+ {variable.name}
+ {variable.required && ' *'}
+ </label>
+ {variable.options ? (
+ <select
+ value={variables[variable.name] || ''}
+ onChange={(e) => setVariables({...variables, [variable.name]: e.target.value})}
+ required={variable.required}
+ >
+ <option value="">Select...</option>
+ {variable.options.map(opt => (
+ <option key={opt} value={opt}>{opt}</option>
+ ))}
+ </select>
+ ) : variable.type === 'password' ? (
+ <input
+ type="password"
+ value={variables[variable.name] || ''}
+ onChange={(e) => setVariables({...variables, [variable.name]: e.target.value})}
+ placeholder={variable.default ? '(auto-generated)' : ''}
+ required={variable.required && !variable.default}
+ />
+ ) : (
+ <input
+ type={variable.type === 'port' ? 'number' : 'text'}
+ value={variables[variable.name] || ''}
+ onChange={(e) => setVariables({...variables, [variable.name]: e.target.value})}
+ placeholder={variable.default || ''}
+ required={variable.required}
+ />
+ )}
+ {variable.description && (
+ <span className="form-help">{variable.description}</span>
+ )}
+ </div>
+ ))}
+ </>
+ )}
+ </div>
+ <div className="modal-footer">
+ <button type="button" className="btn btn-secondary" onClick={onClose} disabled={installing}>
+ Cancel
+ </button>
+ <button type="submit" className="btn btn-primary" disabled={installing}>
+ {installing ? 'Installing...' : 'Install'}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
+
+export default Templates;
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 14ac307b..975fe9f1 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -1297,6 +1297,73 @@ class ApiService {
return this.request(`/builds/apps/${appId}/current-deployment`);
}
+ // ========================================
+ // Template endpoints
+ // ========================================
+ async listTemplates(category = null, search = null) {
+ const params = new URLSearchParams();
+ if (category) params.append('category', category);
+ if (search) params.append('search', search);
+ const query = params.toString();
+ return this.request(`/templates/${query ? '?' + query : ''}`);
+ }
+
+ async getTemplateCategories() {
+ return this.request('/templates/categories');
+ }
+
+ async getTemplate(templateId) {
+ return this.request(`/templates/${templateId}`);
+ }
+
+ async installTemplate(templateId, appName, variables = {}) {
+ return this.request(`/templates/${templateId}/install`, {
+ method: 'POST',
+ body: { app_name: appName, variables }
+ });
+ }
+
+ async validateTemplateInstall(templateId, appName, variables = {}) {
+ return this.request('/templates/validate-install', {
+ method: 'POST',
+ body: { template_id: templateId, app_name: appName, variables }
+ });
+ }
+
+ async checkAppUpdate(appId) {
+ return this.request(`/templates/apps/${appId}/check-update`);
+ }
+
+ async updateAppFromTemplate(appId) {
+ return this.request(`/templates/apps/${appId}/update`, { method: 'POST' });
+ }
+
+ async getAppTemplateInfo(appId) {
+ return this.request(`/templates/apps/${appId}/template-info`);
+ }
+
+ async listTemplateRepos() {
+ return this.request('/templates/repos');
+ }
+
+ async addTemplateRepo(name, url) {
+ return this.request('/templates/repos', {
+ method: 'POST',
+ body: { name, url }
+ });
+ }
+
+ async removeTemplateRepo(url) {
+ return this.request('/templates/repos', {
+ method: 'DELETE',
+ body: { url }
+ });
+ }
+
+ async syncTemplates() {
+ return this.request('/templates/sync', { method: 'POST' });
+ }
+
// ========================================
// File Manager endpoints
// ========================================
diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.less
index 5848fdb1..abd58f9e 100644
--- a/frontend/src/styles/main.less
+++ b/frontend/src/styles/main.less
@@ -66,3 +66,4 @@
@import 'pages/_firewall';
@import 'pages/_cron';
@import 'pages/_security';
+@import 'pages/_templates';
diff --git a/frontend/src/styles/pages/_templates.less b/frontend/src/styles/pages/_templates.less
new file mode 100644
index 00000000..99be63b5
--- /dev/null
+++ b/frontend/src/styles/pages/_templates.less
@@ -0,0 +1,317 @@
+// ============================================
+// TEMPLATES PAGE STYLES
+// ============================================
+
+.templates-page {
+ .page-description {
+ color: @text-secondary;
+ margin-top: @space-2;
+ }
+}
+
+// Filters
+.templates-filters {
+ display: flex;
+ flex-direction: column;
+ gap: @space-4;
+ margin-bottom: @space-6;
+}
+
+.search-box {
+ input {
+ width: 100%;
+ max-width: 400px;
+ padding: @space-3 @space-4;
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-md;
+ color: @text-primary;
+ font-size: @font-size-base;
+
+ &:focus {
+ outline: none;
+ border-color: @accent-primary;
+ box-shadow: 0 0 0 3px @accent-glow;
+ }
+
+ &::placeholder {
+ color: @text-tertiary;
+ }
+ }
+}
+
+.category-filters {
+ display: flex;
+ flex-wrap: wrap;
+ gap: @space-2;
+}
+
+.category-btn {
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+ padding: @space-2 @space-3;
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-md;
+ color: @text-secondary;
+ font-size: @font-size-sm;
+ cursor: pointer;
+ transition: all @transition-fast;
+ text-transform: capitalize;
+
+ &:hover {
+ background: @bg-hover;
+ border-color: @border-default;
+ color: @text-primary;
+ }
+
+ &.active {
+ background: @accent-glow;
+ border-color: @accent-primary;
+ color: @accent-primary;
+ }
+}
+
+// Templates Grid
+.templates-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
+ gap: @space-6;
+}
+
+.template-card {
+ display: flex;
+ gap: @space-4;
+ padding: @space-5;
+ background: @bg-card;
+ border: 1px solid @border-subtle;
+ border-radius: @radius-lg;
+ cursor: pointer;
+ transition: all @transition-fast;
+
+ &:hover {
+ border-color: @accent-primary;
+ box-shadow: @shadow-md;
+ transform: translateY(-2px);
+ }
+}
+
+.template-icon {
+ width: 64px;
+ height: 64px;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: @bg-hover;
+ border-radius: @radius-md;
+ overflow: hidden;
+
+ img {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ }
+}
+
+.template-icon-placeholder {
+ font-size: @font-size-2xl;
+ font-weight: @font-weight-bold;
+ color: @accent-primary;
+}
+
+.template-icon-large {
+ width: 80px;
+ height: 80px;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: @bg-hover;
+ border-radius: @radius-lg;
+ overflow: hidden;
+
+ img {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ }
+
+ .template-icon-placeholder {
+ font-size: @font-size-3xl;
+ }
+}
+
+.template-info {
+ flex: 1;
+ min-width: 0;
+
+ h3 {
+ margin: 0 0 @space-2 0;
+ font-size: @font-size-lg;
+ font-weight: @font-weight-semibold;
+ }
+}
+
+.template-description {
+ margin: 0 0 @space-3 0;
+ color: @text-secondary;
+ font-size: @font-size-sm;
+ line-height: @line-height-relaxed;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+.template-full-description {
+ margin-bottom: @space-4;
+ color: @text-secondary;
+ line-height: @line-height-relaxed;
+}
+
+.template-meta {
+ display: flex;
+ align-items: center;
+ gap: @space-3;
+ flex-wrap: wrap;
+}
+
+.template-version {
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+ padding: @space-1 @space-2;
+ background: @bg-hover;
+ border-radius: @radius-sm;
+}
+
+.template-categories {
+ display: flex;
+ flex-wrap: wrap;
+ gap: @space-2;
+}
+
+.category-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: @space-1;
+ padding: @space-1 @space-2;
+ font-size: @font-size-xs;
+ color: @text-secondary;
+ background: @bg-hover;
+ border-radius: @radius-sm;
+ text-transform: capitalize;
+}
+
+// Template Detail Modal
+.template-detail-header {
+ display: flex;
+ align-items: center;
+ gap: @space-4;
+
+ h2 {
+ margin: 0;
+ }
+}
+
+.template-links {
+ display: flex;
+ gap: @space-2;
+ margin-bottom: @space-6;
+}
+
+.template-details-grid {
+ display: flex;
+ flex-direction: column;
+ gap: @space-6;
+}
+
+.detail-section {
+ h4 {
+ margin: 0 0 @space-3 0;
+ font-size: @font-size-sm;
+ font-weight: @font-weight-semibold;
+ color: @text-secondary;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+}
+
+.variables-list {
+ display: flex;
+ flex-direction: column;
+ gap: @space-3;
+}
+
+.variable-item {
+ display: flex;
+ flex-direction: column;
+ gap: @space-1;
+ padding: @space-3;
+ background: @bg-hover;
+ border-radius: @radius-md;
+}
+
+.variable-name {
+ font-family: @font-mono;
+ font-size: @font-size-sm;
+ font-weight: @font-weight-medium;
+ color: @accent-primary;
+}
+
+.variable-description {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+}
+
+.variable-default {
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+}
+
+.ports-list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: @space-2;
+}
+
+.port-item {
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+ padding: @space-2 @space-3;
+ background: @bg-hover;
+ border-radius: @radius-md;
+}
+
+.port-number {
+ font-family: @font-mono;
+ font-weight: @font-weight-medium;
+ color: @text-primary;
+}
+
+.port-protocol {
+ font-size: @font-size-xs;
+ padding: @space-1;
+ background: @bg-card;
+ border-radius: @radius-sm;
+ color: @text-secondary;
+ text-transform: uppercase;
+}
+
+.port-description {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+}
+
+// Install Modal
+.install-modal {
+ h4 {
+ margin: @space-4 0 @space-3 0;
+ font-size: @font-size-base;
+ font-weight: @font-weight-semibold;
+ padding-top: @space-4;
+ border-top: 1px solid @border-subtle;
+ }
+}