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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add environment variable management feature
Juan Denise9455a716701
diff --git a/.claude/settings.local.json b/.claude/settings.local.jsondeleted file mode 100644index 1d8f3440..00000000--- a/.claude/settings.local.json+++ /dev/null@@ -1,8 +0,0 @@-{- "permissions": {- "allow": [- "Bash(npm install:*)",- "Bash(npm run build:*)"- ]- }-}diff --git a/.gitignore b/.gitignoreindex de41feea..b9f921eb 100644--- a/.gitignore+++ b/.gitignore@@ -1,2 +1,4 @@/frontend/node_modulesnul+/.claude+/.claude_diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex eaf9c0d7..62144120 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -125,6 +125,10 @@ def create_app(config_name=None):from app.api.uptime import uptime_bpapp.register_blueprint(uptime_bp, url_prefix='/api/v1/uptime')+ # Register blueprints - Environment Variables+ from app.api.env_vars import env_vars_bp+ app.register_blueprint(env_vars_bp, url_prefix='/api/v1/apps')+# Create database tableswith app.app_context():db.create_all()diff --git a/backend/app/api/env_vars.py b/backend/app/api/env_vars.pynew file mode 100644index 00000000..fd5df4b1--- /dev/null+++ b/backend/app/api/env_vars.py@@ -0,0 +1,287 @@+"""+Environment Variables API++Provides endpoints for managing application environment variables.+All values are encrypted at rest.+"""++from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity+from app.models import Application, User+from app.services.env_service import EnvService++env_vars_bp = Blueprint('env_vars', __name__)+++def check_app_access(app_id, user_id):+ """Check if user has access to the application."""+ user = User.query.get(user_id)+ app = Application.query.get(app_id)++ if not app:+ return None, None, jsonify({'error': 'Application not found'}), 404++ if user.role != 'admin' and app.user_id != user_id:+ return None, None, jsonify({'error': 'Access denied'}), 403++ return user, app, None, None+++@env_vars_bp.route('/<int:app_id>/env', methods=['GET'])+@jwt_required()+def get_env_vars(app_id):+ """Get all environment variables for an application."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ # Check if secrets should be masked+ mask_secrets = request.args.get('mask', 'false').lower() == 'true'++ env_vars = EnvService.get_env_vars(app_id, mask_secrets=mask_secrets)++ return jsonify({+ 'env_vars': env_vars,+ 'count': len(env_vars)+ }), 200+++@env_vars_bp.route('/<int:app_id>/env', methods=['POST'])+@jwt_required()+def create_env_var(app_id):+ """Create a new environment variable."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ key = data.get('key')+ value = data.get('value', '')+ is_secret = data.get('is_secret', False)+ description = data.get('description')++ if not key:+ return jsonify({'error': 'Key is required'}), 400++ env_var, created, err = EnvService.set_env_var(+ app_id, key, value, is_secret, description, current_user_id+ )++ if err:+ return jsonify({'error': err}), 400++ return jsonify({+ 'message': 'Environment variable created' if created else 'Environment variable updated',+ 'env_var': env_var.to_dict(),+ 'created': created+ }), 201 if created else 200+++@env_vars_bp.route('/<int:app_id>/env/<string:key>', methods=['GET'])+@jwt_required()+def get_env_var(app_id, key):+ """Get a single environment variable by key."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ env_var = EnvService.get_env_var(app_id, key)++ if not env_var:+ return jsonify({'error': 'Environment variable not found'}), 404++ return jsonify({+ 'env_var': env_var.to_dict()+ }), 200+++@env_vars_bp.route('/<int:app_id>/env/<string:key>', methods=['PUT'])+@jwt_required()+def update_env_var(app_id, key):+ """Update an existing environment variable."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ value = data.get('value')+ is_secret = data.get('is_secret')+ description = data.get('description')++ # Get existing+ existing = EnvService.get_env_var(app_id, key)+ if not existing:+ return jsonify({'error': 'Environment variable not found'}), 404++ # Update only provided fields+ if value is not None:+ old_value = existing.value+ existing.value = value+ from app.models import EnvironmentVariableHistory+ from app import db+ EnvironmentVariableHistory.record_change(+ existing, 'updated', old_value=old_value, new_value=value, user_id=current_user_id+ )++ if is_secret is not None:+ existing.is_secret = is_secret++ if description is not None:+ existing.description = description++ from app import db+ db.session.commit()++ return jsonify({+ 'message': 'Environment variable updated',+ 'env_var': existing.to_dict()+ }), 200+++@env_vars_bp.route('/<int:app_id>/env/<string:key>', methods=['DELETE'])+@jwt_required()+def delete_env_var(app_id, key):+ """Delete an environment variable."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ success, err = EnvService.delete_env_var(app_id, key, current_user_id)++ if not success:+ return jsonify({'error': err}), 404++ return jsonify({+ 'message': 'Environment variable deleted',+ 'key': key+ }), 200+++@env_vars_bp.route('/<int:app_id>/env/bulk', methods=['POST'])+@jwt_required()+def bulk_set_env_vars(app_id):+ """Set multiple environment variables at once."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ data = request.get_json()+ if not data or 'env_vars' not in data:+ return jsonify({'error': 'env_vars object is required'}), 400++ count, errors = EnvService.bulk_set_env_vars(+ app_id, data['env_vars'], current_user_id+ )++ return jsonify({+ 'message': f'{count} environment variables set',+ 'count': count,+ 'errors': errors if errors else None+ }), 200 if not errors else 207 # 207 Multi-Status if partial success+++@env_vars_bp.route('/<int:app_id>/env/import', methods=['POST'])+@jwt_required()+def import_env_file(app_id):+ """Import environment variables from .env file content."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ data = request.get_json()+ if not data or 'content' not in data:+ return jsonify({'error': 'content is required'}), 400++ # Parse the .env content+ env_vars, parse_errors = EnvService.parse_env_file(data['content'])++ if not env_vars and parse_errors:+ return jsonify({+ 'error': 'Failed to parse .env content',+ 'parse_errors': parse_errors+ }), 400++ # Whether to overwrite existing+ overwrite = data.get('overwrite', True)++ if not overwrite:+ # Filter out existing keys+ existing_keys = {ev.key for ev in EnvService.get_env_vars(app_id)}+ env_vars = {k: v for k, v in env_vars.items() if k not in existing_keys}++ # Import the variables+ count, errors = EnvService.bulk_set_env_vars(app_id, env_vars, current_user_id)++ return jsonify({+ 'message': f'{count} environment variables imported',+ 'count': count,+ 'parse_errors': parse_errors if parse_errors else None,+ 'import_errors': errors if errors else None+ }), 200+++@env_vars_bp.route('/<int:app_id>/env/export', methods=['GET'])+@jwt_required()+def export_env_file(app_id):+ """Export environment variables as .env file content."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ include_secrets = request.args.get('include_secrets', 'true').lower() == 'true'++ content = EnvService.export_to_env_format(app_id, include_secrets=include_secrets)++ return jsonify({+ 'content': content,+ 'filename': f'{app.name}.env'+ }), 200+++@env_vars_bp.route('/<int:app_id>/env/history', methods=['GET'])+@jwt_required()+def get_env_history(app_id):+ """Get change history for environment variables."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ limit = request.args.get('limit', 50, type=int)+ history = EnvService.get_history(app_id, limit=limit)++ return jsonify({+ 'history': history,+ 'count': len(history)+ }), 200+++@env_vars_bp.route('/<int:app_id>/env/clear', methods=['DELETE'])+@jwt_required()+def clear_all_env_vars(app_id):+ """Delete all environment variables for an application."""+ current_user_id = get_jwt_identity()+ user, app, error, status = check_app_access(app_id, current_user_id)+ if error:+ return error, status++ count = EnvService.clear_all(app_id, current_user_id)++ return jsonify({+ 'message': f'{count} environment variables deleted',+ 'count': count+ }), 200diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 9f20fce3..7f8794a1 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -1,5 +1,6 @@from app.models.user import Userfrom app.models.application import Applicationfrom app.models.domain import Domain+from app.models.env_variable import EnvironmentVariable, EnvironmentVariableHistory-__all__ = ['User', 'Application', 'Domain']+__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory']diff --git a/backend/app/models/env_variable.py b/backend/app/models/env_variable.pynew file mode 100644index 00000000..1827c315--- /dev/null+++ b/backend/app/models/env_variable.py@@ -0,0 +1,146 @@+from datetime import datetime+from app import db+from cryptography.fernet import Fernet+import os+import base64+import hashlib+++class EnvironmentVariable(db.Model):+ """+ Stores environment variables for applications with encrypted values.+ Supports versioning for history tracking.+ """+ __tablename__ = 'environment_variables'++ id = db.Column(db.Integer, primary_key=True)+ application_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False)+ key = db.Column(db.String(255), nullable=False)+ encrypted_value = db.Column(db.Text, nullable=False)+ is_secret = db.Column(db.Boolean, default=False) # Mark sensitive values+ description = db.Column(db.String(500), nullable=True) # Optional description++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)+ created_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)++ # Unique constraint: one key per application+ __table_args__ = (+ db.UniqueConstraint('application_id', 'key', name='unique_app_env_key'),+ )++ # Class-level encryption key (generated from SECRET_KEY)+ _fernet = None++ @classmethod+ def _get_fernet(cls):+ """Get or create the Fernet encryption instance."""+ if cls._fernet is None:+ # Derive a 32-byte key from SECRET_KEY using SHA256+ secret_key = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production')+ key = hashlib.sha256(secret_key.encode()).digest()+ fernet_key = base64.urlsafe_b64encode(key)+ cls._fernet = Fernet(fernet_key)+ return cls._fernet++ @classmethod+ def encrypt_value(cls, value):+ """Encrypt a value for storage."""+ if value is None:+ value = ''+ fernet = cls._get_fernet()+ return fernet.encrypt(value.encode()).decode()++ @classmethod+ def decrypt_value(cls, encrypted_value):+ """Decrypt a stored value."""+ if not encrypted_value:+ return ''+ fernet = cls._get_fernet()+ try:+ return fernet.decrypt(encrypted_value.encode()).decode()+ except Exception:+ return '[DECRYPTION_ERROR]'++ @property+ def value(self):+ """Get the decrypted value."""+ return self.decrypt_value(self.encrypted_value)++ @value.setter+ def value(self, plaintext):+ """Set the value (encrypts automatically)."""+ self.encrypted_value = self.encrypt_value(plaintext)++ def to_dict(self, include_value=True, mask_secrets=False):+ """Convert to dictionary, optionally masking secret values."""+ result = {+ 'id': self.id,+ 'application_id': self.application_id,+ 'key': self.key,+ 'is_secret': self.is_secret,+ 'description': self.description,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }++ if include_value:+ if mask_secrets and self.is_secret:+ result['value'] = '••••••••'+ else:+ result['value'] = self.value++ return result++ def __repr__(self):+ return f'<EnvironmentVariable {self.key}>'+++class EnvironmentVariableHistory(db.Model):+ """+ Tracks history of environment variable changes for auditing.+ """+ __tablename__ = 'environment_variable_history'++ id = db.Column(db.Integer, primary_key=True)+ env_variable_id = db.Column(db.Integer, nullable=False) # Not FK to allow deleted vars+ application_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False)+ key = db.Column(db.String(255), nullable=False)+ action = db.Column(db.String(20), nullable=False) # 'created', 'updated', 'deleted'+ old_value_hash = db.Column(db.String(64), nullable=True) # SHA256 hash (not the actual value)+ new_value_hash = db.Column(db.String(64), nullable=True)+ changed_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)+ changed_at = db.Column(db.DateTime, default=datetime.utcnow)++ @classmethod+ def hash_value(cls, value):+ """Create a hash of the value for comparison (not for storage of actual value)."""+ if value is None:+ return None+ return hashlib.sha256(value.encode()).hexdigest()++ @classmethod+ def record_change(cls, env_var, action, old_value=None, new_value=None, user_id=None):+ """Record a change to an environment variable."""+ history = cls(+ env_variable_id=env_var.id if env_var.id else 0,+ application_id=env_var.application_id,+ key=env_var.key,+ action=action,+ old_value_hash=cls.hash_value(old_value) if old_value else None,+ new_value_hash=cls.hash_value(new_value) if new_value else None,+ changed_by=user_id+ )+ db.session.add(history)+ return history++ def to_dict(self):+ return {+ 'id': self.id,+ 'env_variable_id': self.env_variable_id,+ 'application_id': self.application_id,+ 'key': self.key,+ 'action': self.action,+ 'changed_by': self.changed_by,+ 'changed_at': self.changed_at.isoformat() if self.changed_at else None,+ }diff --git a/backend/app/services/env_service.py b/backend/app/services/env_service.pynew file mode 100644index 00000000..46f9a41a--- /dev/null+++ b/backend/app/services/env_service.py@@ -0,0 +1,316 @@+"""+Environment Variable Management Service++Handles CRUD operations for application environment variables,+including encryption, history tracking, and .env file operations.+"""++import re+from app import db+from app.models import Application, EnvironmentVariable, EnvironmentVariableHistory+++class EnvService:+ """Service for managing application environment variables."""++ # Valid environment variable key pattern+ KEY_PATTERN = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')++ @staticmethod+ def validate_key(key):+ """Validate environment variable key format."""+ if not key:+ return False, "Key cannot be empty"+ if len(key) > 255:+ return False, "Key cannot exceed 255 characters"+ if not EnvService.KEY_PATTERN.match(key):+ return False, "Key must start with a letter or underscore and contain only letters, numbers, and underscores"+ return True, None++ @staticmethod+ def get_env_vars(application_id, mask_secrets=False):+ """Get all environment variables for an application."""+ env_vars = EnvironmentVariable.query.filter_by(+ application_id=application_id+ ).order_by(EnvironmentVariable.key).all()++ return [ev.to_dict(include_value=True, mask_secrets=mask_secrets) for ev in env_vars]++ @staticmethod+ def get_env_var(application_id, key):+ """Get a single environment variable by key."""+ return EnvironmentVariable.query.filter_by(+ application_id=application_id,+ key=key+ ).first()++ @staticmethod+ def get_env_var_by_id(env_var_id):+ """Get a single environment variable by ID."""+ return EnvironmentVariable.query.get(env_var_id)++ @staticmethod+ def set_env_var(application_id, key, value, is_secret=False, description=None, user_id=None):+ """+ Set an environment variable (create or update).+ Returns (env_var, created, error)+ """+ # Validate key+ valid, error = EnvService.validate_key(key)+ if not valid:+ return None, False, error++ # Check if application exists+ app = Application.query.get(application_id)+ if not app:+ return None, False, "Application not found"++ # Check if key already exists+ existing = EnvService.get_env_var(application_id, key)++ if existing:+ # Update existing+ old_value = existing.value+ existing.value = value+ existing.is_secret = is_secret+ if description is not None:+ existing.description = description++ # Record history+ EnvironmentVariableHistory.record_change(+ existing, 'updated', old_value=old_value, new_value=value, user_id=user_id+ )++ db.session.commit()+ return existing, False, None+ else:+ # Create new+ env_var = EnvironmentVariable(+ application_id=application_id,+ key=key,+ is_secret=is_secret,+ description=description,+ created_by=user_id+ )+ env_var.value = value++ db.session.add(env_var)+ db.session.flush() # Get ID before commit++ # Record history+ EnvironmentVariableHistory.record_change(+ env_var, 'created', new_value=value, user_id=user_id+ )++ db.session.commit()+ return env_var, True, None++ @staticmethod+ def delete_env_var(application_id, key, user_id=None):+ """Delete an environment variable. Returns (success, error)."""+ env_var = EnvService.get_env_var(application_id, key)++ if not env_var:+ return False, "Environment variable not found"++ old_value = env_var.value++ # Record history before deletion+ EnvironmentVariableHistory.record_change(+ env_var, 'deleted', old_value=old_value, user_id=user_id+ )++ db.session.delete(env_var)+ db.session.commit()++ return True, None++ @staticmethod+ def delete_env_var_by_id(env_var_id, user_id=None):+ """Delete an environment variable by ID. Returns (success, error)."""+ env_var = EnvironmentVariable.query.get(env_var_id)++ if not env_var:+ return False, "Environment variable not found"++ old_value = env_var.value++ # Record history before deletion+ EnvironmentVariableHistory.record_change(+ env_var, 'deleted', old_value=old_value, user_id=user_id+ )++ db.session.delete(env_var)+ db.session.commit()++ return True, None++ @staticmethod+ def bulk_set_env_vars(application_id, env_vars_dict, user_id=None):+ """+ Set multiple environment variables at once.+ env_vars_dict: {key: value} or {key: {value, is_secret, description}}+ Returns (count, errors)+ """+ count = 0+ errors = []++ for key, val in env_vars_dict.items():+ if isinstance(val, dict):+ value = val.get('value', '')+ is_secret = val.get('is_secret', False)+ description = val.get('description')+ else:+ value = val+ is_secret = False+ description = None++ env_var, created, error = EnvService.set_env_var(+ application_id, key, value, is_secret, description, user_id+ )++ if error:+ errors.append(f"{key}: {error}")+ else:+ count += 1++ return count, errors++ @staticmethod+ def parse_env_file(content):+ """+ Parse .env file content into a dictionary.+ Handles comments, quotes, and multiline values.+ Returns (dict, errors)+ """+ env_vars = {}+ errors = []+ lines = content.split('\n')+ current_key = None+ current_value = None+ in_multiline = False++ for line_num, line in enumerate(lines, 1):+ # Skip empty lines and comments (unless in multiline)+ if not in_multiline:+ stripped = line.strip()+ if not stripped or stripped.startswith('#'):+ continue++ # Check for key=value+ if '=' not in line:+ errors.append(f"Line {line_num}: Invalid format (missing '=')")+ continue++ # Split on first =+ key, value = line.split('=', 1)+ key = key.strip()+ value = value.strip()++ # Validate key+ valid, error = EnvService.validate_key(key)+ if not valid:+ errors.append(f"Line {line_num}: {error}")+ continue++ # Check for quoted values+ if value.startswith('"') and not value.endswith('"'):+ # Start of multiline+ in_multiline = True+ current_key = key+ current_value = value[1:] # Remove opening quote+ elif value.startswith('"') and value.endswith('"') and len(value) > 1:+ # Quoted value (single line)+ env_vars[key] = value[1:-1]+ elif value.startswith("'") and value.endswith("'") and len(value) > 1:+ # Single-quoted value+ env_vars[key] = value[1:-1]+ else:+ # Unquoted value+ env_vars[key] = value+ else:+ # Continue multiline value+ if line.rstrip().endswith('"'):+ # End of multiline+ current_value += '\n' + line.rstrip()[:-1]+ env_vars[current_key] = current_value+ in_multiline = False+ current_key = None+ current_value = None+ else:+ current_value += '\n' + line++ if in_multiline:+ errors.append("Unterminated quoted value")++ return env_vars, errors++ @staticmethod+ def export_to_env_format(application_id, include_secrets=True):+ """+ Export environment variables to .env file format.+ Returns string content.+ """+ env_vars = EnvironmentVariable.query.filter_by(+ application_id=application_id+ ).order_by(EnvironmentVariable.key).all()++ lines = []+ lines.append("# Environment variables")+ lines.append(f"# Exported from ServerKit")+ lines.append("")++ for ev in env_vars:+ if ev.is_secret and not include_secrets:+ lines.append(f"# {ev.key}=<secret>")+ else:+ value = ev.value+ # Quote values that contain special characters+ if any(c in value for c in [' ', '"', "'", '\n', '#', '$']):+ # Escape existing quotes and wrap in quotes+ value = value.replace('\\', '\\\\').replace('"', '\\"')+ lines.append(f'{ev.key}="{value}"')+ else:+ lines.append(f"{ev.key}={value}")++ # Add description as comment if present+ if ev.description:+ lines[-1] = f"# {ev.description}\n" + lines[-1]++ return '\n'.join(lines)++ @staticmethod+ def get_history(application_id, limit=50):+ """Get change history for an application's environment variables."""+ history = EnvironmentVariableHistory.query.filter_by(+ application_id=application_id+ ).order_by(EnvironmentVariableHistory.changed_at.desc()).limit(limit).all()++ return [h.to_dict() for h in history]++ @staticmethod+ def get_env_dict(application_id):+ """Get environment variables as a simple key:value dictionary."""+ env_vars = EnvironmentVariable.query.filter_by(+ application_id=application_id+ ).all()++ return {ev.key: ev.value for ev in env_vars}++ @staticmethod+ def clear_all(application_id, user_id=None):+ """Delete all environment variables for an application."""+ env_vars = EnvironmentVariable.query.filter_by(+ application_id=application_id+ ).all()++ count = 0+ for ev in env_vars:+ EnvironmentVariableHistory.record_change(+ ev, 'deleted', old_value=ev.value, user_id=user_id+ )+ db.session.delete(ev)+ count += 1++ db.session.commit()+ return countdiff --git a/backend/requirements.txt b/backend/requirements.txtindex 1736130c..7fdda93b 100644--- a/backend/requirements.txt+++ b/backend/requirements.txt@@ -40,4 +40,7 @@ click==8.1.7schedulepasslib-bcrypt\ No newline at end of file+bcrypt++# Encryption for env vars+cryptography==42.0.0\ No newline at end of filediff --git a/docs/COMPETITIVE_ANALYSIS.md b/docs/COMPETITIVE_ANALYSIS.mdnew file mode 100644index 00000000..1a99a2ed--- /dev/null+++ b/docs/COMPETITIVE_ANALYSIS.md@@ -0,0 +1,314 @@+# ServerKit Competitive Analysis++*Last Updated: January 2026*++This document analyzes ServerKit's competitive landscape, identifying key players, their strengths, weaknesses, and opportunities for differentiation.++---++## Market Overview++The self-hosted server management space has evolved significantly, with solutions ranging from traditional hosting control panels to modern PaaS alternatives. The market can be segmented into:++1. **Traditional Hosting Panels** - cPanel-like interfaces for web hosting+2. **PaaS Alternatives** - Heroku/Vercel-like deployment platforms+3. **Container Management** - Docker/Kubernetes focused tools+4. **Server Monitoring** - Infrastructure observability tools++ServerKit aims to bridge categories 1, 2, and 3 - offering a modern, unified experience.++---++## Primary Competitors++### 1. Coolify++**Website:** [coolify.io](https://coolify.io)++**What it is:** Open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify.++**Strengths:**+- 280+ one-click deployable services+- Git-based auto-deployment (push to deploy)+- Built-in database management (PostgreSQL, MySQL, MongoDB, Redis)+- Automatic SSL via Let's Encrypt + Traefik+- Multi-server support (manage multiple VMs from one dashboard)+- S3-compatible backup with one-click restore+- Active development with strong community+- Notifications via Discord, Telegram, email+- No vendor lock-in (configs saved on server)++**Weaknesses:**+- Docker-centric (not ideal for traditional PHP hosting)+- Steeper learning curve for non-Docker users+- Resource intensive for small VPS (needs 2GB+ RAM)+- Limited traditional hosting features (no email, DNS)++**Pricing:** Free & open-source (Cloud version available)++---++### 2. CloudPanel++**Website:** [cloudpanel.io](https://www.cloudpanel.io)++**What it is:** Lightweight, free control panel optimized for PHP/Node.js applications.++**Strengths:**+- Ultra-lightweight (runs on 1GB RAM VPS)+- Nginx-only stack (excellent performance)+- PHP 7.4 to 8.3 support+- Node.js and Python support+- Modern, clean UI with real-time metrics+- Free Let's Encrypt SSL+- Two-factor authentication+- UFW firewall integration++**Weaknesses:**+- Debian-exclusive (no Ubuntu/CentOS)+- No built-in email/DNS server+- Single admin role (no multi-user/reseller)+- Limited Docker support+- No Git deployment integration++**Pricing:** 100% Free++---++### 3. HestiaCP++**Website:** [hestiacp.com](https://hestiacp.com)++**What it is:** Fork of VestaCP, traditional web hosting control panel.++**Strengths:**+- Full hosting stack (Web + Email + DNS)+- Apache-Nginx hybrid for flexibility+- Multi-user with reseller support+- Built-in Roundcube webmail+- SpamAssassin integration+- DNSSEC support+- Runs on 1GB RAM VPS+- Large community and documentation++**Weaknesses:**+- Dated UI compared to modern tools+- No container management+- No Git deployment+- Complex initial configuration+- Higher resource usage with all services enabled++**Pricing:** 100% Free++---++### 4. CapRover++**Website:** [caprover.com](https://caprover.com)++**What it is:** Automated Docker + Nginx PaaS (called "Heroku on Steroids").++**Strengths:**+- One-click app marketplace+- Push-to-deploy with CLI tool+- Automatic SSL with Let's Encrypt+- Horizontal scaling support+- Docker Compose/Stack support+- GitHub Actions integration+- WebSocket terminal for containers+- 100M+ Docker Hub downloads++**Weaknesses:**+- Docker-only (no traditional PHP hosting)+- Limited UI compared to newer alternatives+- No built-in monitoring dashboard+- Manual database backup setup+- Single-server focus (limited multi-server)++**Pricing:** 100% Free++---++### 5. Dokploy++**Website:** [dokploy.com](https://dokploy.com)++**What it is:** Lightweight self-hosted PaaS for Docker applications.++**Strengths:**+- Clean, modern UI+- Git repository deployment (GitHub, GitLab)+- Docker + Docker Compose support+- Traefik for automatic HTTPS+- Environment variable management+- Swagger API documentation+- Lightweight resource usage+- JWT-secured API with rate limiting++**Weaknesses:**+- Newer project (less mature)+- Limited one-click apps compared to Coolify+- No traditional PHP hosting+- Limited monitoring features+- Smaller community++**Pricing:** 100% Free++---++### 6. Portainer++**Website:** [portainer.io](https://www.portainer.io)++**What it is:** Universal container management platform for Docker, Kubernetes, and Podman.++**Strengths:**+- Enterprise-grade container management+- Kubernetes support+- RBAC with team management+- Container templates/app catalog+- Edge computing support+- LTS versions for stability+- Wide enterprise adoption++**Weaknesses:**+- Container management only (not app deployment)+- No Git deployment+- No web hosting features+- Community Edition limitations+- Business Edition requires license++**Pricing:** Community Edition free, Business Edition paid++---++### 7. Webmin/Virtualmin++**Website:** [webmin.com](https://webmin.com) / [virtualmin.com](https://virtualmin.com)++**What it is:** Veteran Linux server administration panel (25+ years).++**Strengths:**+- Comprehensive Linux administration+- Virtualmin adds full hosting features+- Extensive plugin ecosystem+- Multi-server management+- Low resource usage+- Massive documentation++**Weaknesses:**+- Dated interface+- Steep learning curve+- No modern PaaS features+- No container management+- Configuration can be overwhelming++**Pricing:** Free (GPL versions), Pro versions available++---++### 8. Cockpit++**Website:** [cockpit-project.org](https://cockpit-project.org)++**What it is:** Lightweight, modern Linux server admin interface.++**Strengths:**+- Red Hat backed (enterprise quality)+- Very lightweight+- Beautiful modern UI+- Native container management (Podman)+- Multi-server support+- Excellent for system administration++**Weaknesses:**+- Not designed for web hosting+- No domain/SSL management+- No app deployment features+- Limited for developers++**Pricing:** 100% Free++---++## Competitive Matrix++| Feature | ServerKit | Coolify | CloudPanel | HestiaCP | CapRover | Dokploy |+|---------|:---------:|:-------:|:----------:|:--------:|:--------:|:-------:|+| **Modern UI** | Yes | Yes | Yes | Partial | Partial | Yes |+| **PHP/WordPress** | Yes | Limited | Yes | Yes | No | No |+| **Python Apps** | Yes | Yes | Yes | Limited | Yes | Yes |+| **Docker Support** | Yes | Yes | No | No | Yes | Yes |+| **Git Deployment** | Planned | Yes | No | No | Yes | Yes |+| **One-Click Apps** | Planned | 280+ | No | No | 100+ | Limited |+| **SSL (Let's Encrypt)** | Yes | Yes | Yes | Yes | Yes | Yes |+| **Real-time Metrics** | Yes | Yes | Yes | Limited | No | Limited |+| **Multi-Server** | No | Yes | No | No | Limited | No |+| **Email Server** | No | No | No | Yes | No | No |+| **DNS Management** | No | No | No | Yes | No | No |+| **File Manager** | Yes | No | Yes | Yes | No | No |+| **Web Terminal** | Yes | Yes | No | No | Yes | Limited |+| **Firewall UI** | Yes | Limited | Yes | Yes | No | No |+| **Cron Jobs** | Yes | No | Yes | Yes | No | No |+| **Backup to S3** | Planned | Yes | No | Yes | No | No |+| **2FA** | Planned | Yes | Yes | Yes | No | No |+| **Free & Open Source** | Yes | Yes | Yes | Yes | Yes | Yes |++---++## Key Insights++### Where ServerKit Excels (Currently)+1. **Unified approach** - Combines traditional hosting with modern container support+2. **Real-time metrics** - WebSocket-based live monitoring+3. **File Manager + Terminal** - Complete server access from browser+4. **Firewall management** - UFW/firewalld abstraction+5. **Cron job management** - Visual scheduler++### Critical Gaps to Address+1. **Git deployment** - All modern competitors have this+2. **One-click apps marketplace** - Coolify leads with 280++3. **Multi-server management** - Expected for scale+4. **S3 backup integration** - Industry standard+5. **Two-factor authentication** - Security baseline++### Opportunity Areas+1. **Best of both worlds** - Traditional hosting simplicity + PaaS power+2. **WordPress-first experience** - Better WP toolkit than PaaS tools+3. **Lightweight option** - Target 1GB VPS (compete with CloudPanel)+4. **Developer experience** - Git deploy + container logs + real-time metrics++---++## Strategic Recommendations++### Short-term (Next 3 Months)+1. Implement Git webhook deployment+2. Add one-click app marketplace (start with top 20)+3. Complete 2FA implementation+4. Add S3/MinIO backup support++### Medium-term (3-6 Months)+1. Multi-server agent architecture+2. Expand one-click apps to 100++3. Add CI/CD pipeline visualization+4. Implement rollback functionality++### Long-term (6-12 Months)+1. Kubernetes support (optional)+2. Team/organization management+3. API marketplace for integrations+4. Mobile app for monitoring++---++## Sources++- [Coolify GitHub](https://github.com/coollabsio/coolify)+- [Coolify Documentation](https://coolify.io/docs/)+- [CloudPanel vs HestiaCP Comparison](https://www.cloudpanel.io/blog/cloudpanel-vs-hestiacp-hosting/)+- [CapRover GitHub](https://github.com/caprover/caprover)+- [Best VPS Control Panels 2026](https://www.hostinger.com/tutorials/best-vps-control-panels)+- [Comparing Self-Hostable PaaS Solutions](https://kloudshift.net/blog/comparing-self-hostable-paas-solutions-caprover-coolify-dokploy-reviewed/)+- [Top Free Web Hosting Control Panels 2025](https://underhost.com/blog/top-free-web-hosting-control-panels-2025/)+- [Best Container Management Software](https://www.portainer.io/blog/best-container-management-software)diff --git a/docs/FEATURE_GAPS.md b/docs/FEATURE_GAPS.mdnew file mode 100644index 00000000..ff43aa64--- /dev/null+++ b/docs/FEATURE_GAPS.md@@ -0,0 +1,474 @@+# ServerKit Feature Gap Analysis++*Last Updated: January 2026*++This document identifies features that ServerKit currently lacks compared to leading competitors, prioritized by impact and implementation complexity.++---++## Gap Severity Legend++| Icon | Severity | Description |+|:----:|----------|-------------|+| P0 | **Critical** | Must-have for competitive parity |+| P1 | **High** | Expected by users, significant differentiator |+| P2 | **Medium** | Nice-to-have, improves UX |+| P3 | **Low** | Future consideration |++---++## Critical Gaps (P0)++### 1. Git-Based Deployment+**Found in:** Coolify, CapRover, Dokploy++**What's missing:**+- GitHub/GitLab/Bitbucket repository connection+- Webhook-triggered auto-deployment on push+- Branch-based deployment (deploy `main` to production, `dev` to staging)+- Build command configuration+- Deploy previews for pull requests++**Why it matters:**+This is the #1 expected feature in 2025+. Developers expect push-to-deploy workflows. Without this, ServerKit feels dated compared to Coolify/Dokploy.++**Implementation scope:** Medium-High+```+Components needed:+- Git service integration (OAuth apps)+- Webhook receiver endpoint+- Build pipeline execution+- Deployment history tracking+- Rollback mechanism+```++---++### 2. One-Click App Marketplace+**Found in:** Coolify (280+), CapRover (100+), Portainer++**What's missing:**+- Pre-configured application templates+- One-click deployment for popular services+- Auto-configured databases, volumes, networking++**Top 20 apps to prioritize:**+1. WordPress+2. Ghost (blog platform)+3. Nextcloud (file storage)+4. GitLab/Gitea (code hosting)+5. n8n (workflow automation)+6. Uptime Kuma (monitoring)+7. Plausible Analytics+8. Minio (S3-compatible storage)+9. PostgreSQL+10. MySQL/MariaDB+11. Redis+12. MongoDB+13. Nginx Proxy Manager+14. Traefik+15. Portainer+16. Directus (headless CMS)+17. Strapi (headless CMS)+18. Supabase (Firebase alternative)+19. Appwrite (BaaS)+20. Mailcow (email server)++**Implementation scope:** Medium+```+Components needed:+- App template schema (docker-compose based)+- Template repository/registry+- Variable substitution engine+- Post-install hooks+- Update mechanism+```++---++### 3. Two-Factor Authentication (2FA)+**Found in:** CloudPanel, HestiaCP, Coolify++**What's missing:**+- TOTP-based 2FA (Google Authenticator, Authy)+- Backup/recovery codes+- Per-user 2FA enforcement+- Remember device option++**Why it matters:**+Security baseline. Server management panels are high-value targets. No 2FA = deal breaker for security-conscious users.++**Implementation scope:** Low+```+Components needed:+- pyotp library integration+- QR code generation for setup+- Backup codes storage (encrypted)+- 2FA challenge during login flow+- Admin enforcement settings+```++---++### 4. S3-Compatible Backup Storage+**Found in:** Coolify, HestiaCP, Cloudron++**What's missing:**+- Backup to AWS S3+- Backup to MinIO (self-hosted)+- Backup to Backblaze B2+- Backup to any S3-compatible storage+- Encrypted backups+- Scheduled backup jobs+- One-click restore++**Why it matters:**+Local backups on the same server aren't real backups. Off-site backup is expected for production use.++**Implementation scope:** Medium+```+Components needed:+- boto3 integration for S3 API+- Backup job scheduler+- Encryption at rest (AES-256)+- Restore workflow+- Retention policy management+```++---++## High Priority Gaps (P1)++### 5. Multi-Server Management+**Found in:** Coolify, Webmin, Cockpit++**What's missing:**+- Connect and manage multiple VPS from single dashboard+- Server grouping/tagging+- Cross-server application deployment+- Centralized monitoring across servers+- Server provisioning automation++**Why it matters:**+Users scaling beyond one server expect unified management. Currently, they'd need separate ServerKit instances.++**Implementation scope:** High+```+Components needed:+- Server agent protocol (authenticated WebSocket)+- Server registration flow+- Multi-tenant data model+- Aggregated metrics dashboard+- Server selector in all operations+```++---++### 6. Database GUI/Web Interface+**Found in:** CloudPanel, HestiaCP++**What's missing:**+- phpMyAdmin integration for MySQL+- pgAdmin or similar for PostgreSQL+- In-app SQL query runner+- Visual schema browser+- Export/import tools++**Why it matters:**+Database management without a GUI is painful. Competitors bundle this.++**Implementation scope:** Low-Medium+```+Options:+A) Embed phpMyAdmin/Adminer (quick)+B) Build custom query interface (more work, better UX)+C) One-click deploy phpMyAdmin as app (hybrid)+```++---++### 7. Deployment Rollback+**Found in:** Coolify, CapRover, Dokploy++**What's missing:**+- Version history of deployments+- One-click rollback to previous version+- Deployment comparison (diff view)+- Automatic rollback on health check failure++**Why it matters:**+Deployments can break things. Easy rollback = confidence to deploy frequently.++**Implementation scope:** Medium+```+Components needed:+- Deployment versioning (keep previous N images/states)+- Rollback API endpoint+- Health check integration+- Deployment history UI+```++---++### 8. Environment Variable Management+**Found in:** Coolify, Dokploy, CapRover++**What's missing:**+- Centralized .env management per app+- Secret masking in UI+- Environment inheritance (global > app > service)+- Import/export .env files+- Variable versioning++**Why it matters:**+Modern apps are configured via environment variables. Managing these well is essential.++**Implementation scope:** Low+```+Components needed:+- Encrypted storage for secrets+- UI for key-value management+- Injection into app containers/processes+- History/audit log+```++---++### 9. Build Pipeline / CI Integration+**Found in:** Coolify, Dokploy++**What's missing:**+- Build logs streaming+- Build status indicators+- Custom build commands+- Dockerfile auto-detection+- Buildpack support (like Heroku)+- GitHub Actions integration++**Why it matters:**+"Deploy" isn't just "run container" - it's build, test, then run. Users need visibility.++**Implementation scope:** High+```+Components needed:+- Build queue system+- Log streaming via WebSocket+- Build configuration per app+- Dockerfile/nixpacks/buildpacks support+- Build cache management+```++---++### 10. Notification System+**Found in:** Coolify (Discord, Telegram, Email)++**What's missing:**+- Multi-channel notifications+- Slack integration+- Discord webhook+- Telegram bot+- PagerDuty/Opsgenie integration+- Customizable alert rules++**Current:** Email only (basic)++**Why it matters:**+Admins need to know when things break - in channels they already use.++**Implementation scope:** Low-Medium+```+Components needed:+- Notification provider abstraction+- Webhook sender for Discord/Slack+- Telegram bot integration+- User notification preferences+```++---++## Medium Priority Gaps (P2)++### 11. Team/Organization Management+**Found in:** Portainer, Cloudron++**What's missing:**+- Multiple users per organization+- Role-based access (Admin, Developer, Viewer)+- Per-app access control+- Audit logging of user actions+- SSO/LDAP integration++**Implementation scope:** High++---++### 12. Resource Quotas/Limits+**Found in:** cPanel, Virtualmin++**What's missing:**+- CPU/RAM limits per app+- Disk quota per user+- Bandwidth limits+- Container resource constraints++**Implementation scope:** Medium++---++### 13. Staging/Preview Environments+**Found in:** Coolify++**What's missing:**+- One-click staging clone+- PR preview deployments+- Environment promotion (staging -> production)+- Isolated databases for staging++**Implementation scope:** High++---++### 14. Custom Domain Management+**Found in:** Coolify, CloudPanel++**What's missing:**+- Wildcard SSL certificates+- Subdomain auto-provisioning+- DNS record management (if DNS hosted)+- Domain verification flow++**Implementation scope:** Medium++---++### 15. Log Aggregation & Search+**Found in:** Portainer, Coolify++**What's missing:**+- Centralized log storage+- Full-text log search+- Log retention policies+- Log export to external systems (Loki, ELK)+- Log-based alerting++**Implementation scope:** Medium-High++---++### 16. API Rate Limiting Dashboard+**Found in:** Various++**What's missing:**+- Visual rate limit configuration+- Per-endpoint limits+- Rate limit monitoring+- IP whitelist for rate limiting++**Implementation scope:** Low++---++### 17. CLI Tool+**Found in:** CapRover, Coolify++**What's missing:**+- `serverkit deploy` command+- `serverkit logs <app>`+- `serverkit ssh <app>`+- API token authentication+- Shell completions++**Implementation scope:** Medium++---++## Low Priority Gaps (P3)++### 18. Kubernetes Support+**Found in:** Portainer++Consider for future if targeting enterprise users.++---++### 19. Mobile App+**Found in:** None of the direct competitors++Opportunity to differentiate with mobile monitoring.++---++### 20. Plugin/Extension System+**Found in:** Webmin++Allow community to extend functionality.++---++### 21. White-Label Support+**Found in:** HestiaCP++For agencies reselling hosting.++---++### 22. Integrated CDN+**Found in:** None++Could partner with Cloudflare/BunnyCDN for one-click setup.++---++## Implementation Priority Matrix++| Gap | Impact | Effort | Priority Score |+|-----|:------:|:------:|:--------------:|+| Git Deployment | 10 | 7 | **P0** |+| One-Click Apps | 9 | 6 | **P0** |+| 2FA | 8 | 2 | **P0** |+| S3 Backups | 8 | 5 | **P0** |+| Multi-Server | 7 | 9 | P1 |+| Database GUI | 7 | 3 | **P1** |+| Rollback | 7 | 5 | P1 |+| Env Variables | 8 | 3 | **P1** |+| Build Pipeline | 8 | 8 | P1 |+| Notifications | 6 | 4 | P1 |+| Team Mgmt | 6 | 8 | P2 |+| Resource Quotas | 5 | 5 | P2 |+| Staging Env | 6 | 7 | P2 |+| CLI Tool | 5 | 5 | P2 |++*Impact: 1-10 (user value), Effort: 1-10 (dev time)*++---++## Quick Wins (High Impact, Low Effort)++1. **2FA** - 2-3 days, massive security improvement+2. **Environment Variables UI** - 2-3 days, developer essential+3. **Database GUI** (embed Adminer) - 1 day+4. **Notification webhooks** - 2-3 days+5. **Basic Git webhook receiver** - 3-5 days++---++## Recommendations++### Immediate Focus (This Month)+1. 2FA implementation+2. Environment variable management+3. Embed Adminer for database GUI+4. Basic Discord/Slack notifications++### Next Quarter+1. Full Git deployment pipeline+2. One-click app marketplace (start with 20)+3. S3 backup integration+4. Deployment rollback++### This Year+1. Multi-server architecture+2. Team/organization support+3. CLI tool+4. 100+ one-click appsdiff --git a/docs/MARKET_POSITIONING.md b/docs/MARKET_POSITIONING.mdnew file mode 100644index 00000000..076af817--- /dev/null+++ b/docs/MARKET_POSITIONING.md@@ -0,0 +1,346 @@+# ServerKit Market Positioning++*Last Updated: January 2026*++This document defines ServerKit's market positioning, target audiences, unique value propositions, and differentiation strategy.++---++## Market Landscape++### The Problem Space++**Traditional Hosting Panels (cPanel, Plesk, HestiaCP)**+- Great for: Web hosting, email, multiple domains+- Limited: No modern deployment workflows, no containers+- Users feel: "Stuck in 2010"++**Modern PaaS (Coolify, CapRover, Dokploy)**+- Great for: Git deployment, containers, modern apps+- Limited: No traditional PHP hosting, steeper learning curve+- Users feel: "Overkill for a WordPress site"++**Container Managers (Portainer)**+- Great for: Docker/Kubernetes management+- Limited: Not application-focused, no hosting features+- Users feel: "I just want to deploy my app"++### The Gap++There's no solution that gives you:+- Simple WordPress/PHP hosting like cPanel+- Modern Git-based deployment like Heroku+- Container management when you need it+- All in one unified, beautiful interface++**ServerKit fills this gap.**++---++## Target Audiences++### Primary: Solo Developers & Small Teams++**Profile:**+- Freelance developers, indie hackers, small agencies+- 1-10 person teams+- Managing 1-5 servers+- Mix of WordPress sites and custom applications++**Pain Points:**+- cPanel is expensive ($15-45/month per server)+- Coolify is overkill for simple sites+- Managing multiple tools is exhausting+- Limited DevOps expertise++**What They Want:**+- Free, open-source solution+- Easy WordPress deployments+- Git push-to-deploy for custom apps+- Simple container management+- One dashboard for everything++### Secondary: Self-Hosters & Homelab Enthusiasts++**Profile:**+- Privacy-conscious individuals+- Running services at home or on VPS+- Technical but time-constrained++**Pain Points:**+- Docker Compose gets tedious+- No central management interface+- Scattered across Portainer, CLI, etc.++**What They Want:**+- One-click apps (Nextcloud, Plex, etc.)+- Beautiful dashboard+- Easy SSL/domain setup+- Low resource usage++### Tertiary: Small Hosting Providers++**Profile:**+- Small web hosting businesses+- Reselling VPS/hosting+- 10-100 client sites++**Pain Points:**+- cPanel licensing costs eating profits+- HestiaCP UI feels dated+- Clients expect modern experience++**What They Want:**+- Modern UI for clients+- Multi-tenant support+- White-label options+- Reliable and secure++---++## Unique Value Proposition++### Primary Message++> **"The modern server panel for developers who want simplicity without sacrificing power."**++### Supporting Messages++1. **"From WordPress to Docker in one panel"**+ - Deploy a WordPress site in 2 clicks+ - Deploy a Docker container in 3 clicks+ - Same interface, same experience++2. **"Push to deploy, without the complexity"**+ - Git integration that just works+ - No Kubernetes required+ - Heroku experience on your own server++3. **"Self-hosted, open-source, forever free"**+ - No licensing fees ever+ - Your data stays on your server+ - MIT licensed, fork friendly++4. **"Beautiful by default"**+ - Modern dark-themed UI+ - Real-time metrics that look good+ - Mobile-responsive dashboard++---++## Positioning Statement++**For** developers and small teams **who** manage their own servers,++**ServerKit** is a **modern server management panel**++**that** provides a unified interface for traditional hosting and cloud-native deployment,++**unlike** cPanel (expensive, dated), Coolify (container-only), or Portainer (not app-focused),++**ServerKit** delivers the simplicity of traditional hosting with the power of modern PaaS.++---++## Competitive Differentiation++### vs Coolify++| Aspect | Coolify | ServerKit |+|--------|---------|-----------|+| Focus | PaaS, containers | Unified hosting + PaaS |+| PHP/WordPress | Basic | First-class support |+| Learning curve | Steeper | Gentler |+| Resource usage | Higher | Optimized for 1GB VPS |+| Traditional features | Limited | File manager, cron, FTP |++**When to recommend Coolify:** Pure container workloads, microservices+**When to recommend ServerKit:** Mix of WordPress + custom apps, simpler needs++### vs CloudPanel++| Aspect | CloudPanel | ServerKit |+|--------|------------|-----------|+| Focus | PHP/Node hosting | Universal |+| Containers | None | Full Docker support |+| Git deployment | No | Yes |+| One-click apps | No | Marketplace |+| OS support | Debian only | Ubuntu + Debian |++**When to recommend CloudPanel:** PHP-only workloads, minimal VPS+**When to recommend ServerKit:** Need containers + hosting, want flexibility++### vs HestiaCP++| Aspect | HestiaCP | ServerKit |+|--------|----------|-----------|+| Focus | Traditional hosting | Modern + traditional |+| UI | Dated | Modern dark theme |+| Email/DNS | Built-in | Via one-click apps |+| Containers | None | Full support |+| Reseller | Yes | Planned |++**When to recommend HestiaCP:** Need built-in email/DNS, reseller business+**When to recommend ServerKit:** Developer-focused, modern workflow++### vs CapRover++| Aspect | CapRover | ServerKit |+|--------|----------|-----------|+| Focus | Container PaaS | Universal |+| Traditional hosting | No | Yes |+| UI | Functional | Modern |+| File manager | No | Yes |+| Web terminal | Container only | Full server |++**When to recommend CapRover:** Container-only, CLI-comfortable+**When to recommend ServerKit:** Mix of workloads, prefer GUI++---++## Brand Personality++### Voice & Tone+- **Approachable:** Not intimidating, welcoming to beginners+- **Confident:** We know what we're doing+- **Practical:** No hype, real solutions+- **Developer-friendly:** Speak their language++### Design Principles+- **Dark theme by default:** Developer preference+- **Information density:** Show what matters, hide the rest+- **Speed:** Instant feedback, real-time updates+- **Consistency:** Same patterns everywhere++### Key Phrases to Use+- "Simple but powerful"+- "Deploy in seconds"+- "Your server, your way"+- "Open source, forever free"+- "Modern hosting, without the complexity"++### Key Phrases to Avoid+- "Enterprise-grade" (intimidating)+- "Cloud-native" (buzzwordy)+- "Revolutionary" (overpromising)+- "AI-powered" (not relevant)++---++## Go-to-Market Strategy++### Phase 1: Community Building (Now - v0.7)++**Goals:**+- Build awareness in developer communities+- Get early adopters and feedback+- Establish presence on GitHub++**Tactics:**+- Post on r/selfhosted, r/homelab, r/webdev+- Hacker News "Show HN" post at v0.6+- YouTube demo videos+- Blog posts on Dev.to, Hashnode+- Twitter/X presence++**Metrics:**+- GitHub stars (target: 500 by v0.7)+- Discord community members+- Installation count (telemetry opt-in)++### Phase 2: Content & SEO (v0.7 - v1.0)++**Goals:**+- Capture search traffic+- Establish thought leadership+- Drive organic installs++**Tactics:**+- "Best cPanel alternatives" content+- "How to deploy X on your VPS" tutorials+- Comparison pages (ServerKit vs Coolify, etc.)+- Documentation site with SEO++**Metrics:**+- Organic search traffic+- Tutorial engagement+- Documentation visits++### Phase 3: Ecosystem (v1.0+)++**Goals:**+- Enable community contributions+- Create integration partnerships+- Consider sustainable revenue++**Tactics:**+- Plugin/extension system+- Partner with VPS providers+- One-click deployments on DigitalOcean/Vultr/Linode+- Optional cloud-hosted version (freemium)++---++## Messaging by Channel++### GitHub README+> ServerKit is a modern, self-hosted server management panel. Deploy WordPress, Flask, Django, and Docker containers from one beautiful dashboard. Push to deploy. Open source. Free forever.++### Twitter/X Bio+> Open-source server panel for developers. WordPress to Docker in one interface. Push-to-deploy without Kubernetes. Free forever.++### Hacker News Post+> Show HN: ServerKit - Modern server panel (cPanel simplicity + Heroku deployment)+>+> Hey HN, I built an open-source server panel that combines traditional hosting features with modern deployment workflows. Think cPanel meets Coolify, but lighter and more approachable.++### Reddit Post+> I built an open-source alternative to ServerPilot/CyberPanel with a focus on developer experience. Dark mode, real-time metrics, Git deployment, one-click apps. Looking for feedback from the self-hosted community.++---++## Success Indicators++### Short-term (6 months)+- [ ] 500+ GitHub stars+- [ ] 100+ active installations+- [ ] Featured on awesome-selfhosted+- [ ] 5+ community contributors++### Medium-term (1 year)+- [ ] 2,000+ GitHub stars+- [ ] 500+ active installations+- [ ] Listed on VPS provider marketplaces+- [ ] 50+ one-click apps in marketplace++### Long-term (2 years)+- [ ] 10,000+ GitHub stars+- [ ] 5,000+ active installations+- [ ] Recognized as top 3 open-source panel+- [ ] Sustainable development model++---++## Appendix: Competitor Taglines++| Product | Tagline |+|---------|---------|+| Coolify | "An open-source & self-hostable Heroku / Netlify / Vercel alternative" |+| CloudPanel | "The Modern PHP Control Panel" |+| HestiaCP | "Open Source Hosting Control Panel" |+| CapRover | "Scalable, Free and Self-hosted PaaS" |+| Portainer | "Making Docker and Kubernetes management easy" |++### ServerKit Tagline Options++1. **"Modern. Self-hosted. Effortless."**+2. **"The server panel developers actually want to use"**+3. **"From WordPress to containers, beautifully simple"**+4. **"Your server, your way"**+5. **"Deploy anything. Manage everything."**++**Recommended:** "The server panel developers actually want to use"++---++*This positioning should guide all marketing, documentation, and communication efforts.*diff --git a/docs/STRATEGIC_ROADMAP.md b/docs/STRATEGIC_ROADMAP.mdnew file mode 100644index 00000000..2decd85b--- /dev/null+++ b/docs/STRATEGIC_ROADMAP.md@@ -0,0 +1,424 @@+# ServerKit Strategic Roadmap++*Last Updated: January 2026*++This roadmap outlines the strategic development path for ServerKit to achieve competitive parity and differentiation in the self-hosted server management market.++---++## Vision Statement++**ServerKit: The modern server panel that bridges traditional hosting and cloud-native deployment.**++ServerKit will be the go-to choice for developers and small teams who want:+- The simplicity of traditional hosting panels (like cPanel)+- The power of modern PaaS platforms (like Coolify/Heroku)+- Without the complexity of Kubernetes+- Without vendor lock-in++---++## Current State Assessment++### What We Have (January 2026)++| Category | Features |+|----------|----------|+| **Authentication** | JWT auth, role-based access, account lockout |+| **Applications** | PHP, WordPress, Flask, Django, Docker support |+| **Infrastructure** | Nginx config, SSL/Let's Encrypt, firewall (ufw/firewalld) |+| **Monitoring** | Real-time metrics, uptime tracking, alerts |+| **Operations** | File manager, web terminal, cron jobs, FTP |+| **UI** | Modern React dashboard with dark theme |++### What's Missing for Competitive Parity+1. Git-based deployment+2. One-click app marketplace+3. Two-factor authentication+4. S3 backup integration+5. Multi-server support++---++## Phased Roadmap++## Phase 1: Security & Developer Essentials+**Timeline: Q1 2026 (Jan-Mar)**+**Theme: "Trust & Productivity"**++### 1.1 Two-Factor Authentication [P0]+- [ ] TOTP implementation (Google Authenticator compatible)+- [ ] QR code setup flow+- [ ] Backup codes generation+- [ ] Recovery flow for lost 2FA+- [ ] Admin enforcement option++**Deliverable:** Users can secure accounts with 2FA++### 1.2 Environment Variable Management [P1]+- [ ] Per-application .env storage+- [ ] Secret masking in UI (show/hide toggle)+- [ ] Import from .env file+- [ ] Export to .env file+- [ ] Variable history/versioning+- [ ] Encrypted storage in database++**Deliverable:** Developers can manage app config without SSH++### 1.3 Database Web Interface [P1]+- [ ] Embed Adminer (single PHP file, lightweight)+- [ ] Single sign-on from ServerKit dashboard+- [ ] Support MySQL, PostgreSQL, SQLite+- [ ] Alternative: custom query runner for simple tasks++**Deliverable:** Database management without external tools++### 1.4 Notification System [P1]+- [ ] Discord webhook integration+- [ ] Slack webhook integration+- [ ] Telegram bot notifications+- [ ] Email improvements (templates, reliability)+- [ ] Notification preferences per user+- [ ] Test notification button++**Deliverable:** Get alerted on your preferred channel++---++## Phase 2: Git Deployment Pipeline+**Timeline: Q2 2026 (Apr-Jun)**+**Theme: "Push to Deploy"**++### 2.1 Git Repository Integration [P0]+- [ ] GitHub OAuth app connection+- [ ] GitLab integration+- [ ] Bitbucket integration+- [ ] Generic Git URL support (any repo)+- [ ] Repository browser in UI+- [ ] Branch selection++**Deliverable:** Connect any Git repository++### 2.2 Webhook Deployment [P0]+- [ ] Auto-generated webhook URLs per app+- [ ] Signature verification (GitHub, GitLab)+- [ ] Branch-specific triggers+- [ ] Deploy on push to `main`+- [ ] Webhook logs and debugging++**Deliverable:** Auto-deploy when you push code++### 2.3 Build System [P0]+- [ ] Dockerfile detection and building+- [ ] Nixpacks support (Heroku-style detection)+- [ ] Custom build commands+- [ ] Build log streaming (WebSocket)+- [ ] Build caching for speed+- [ ] Build timeout handling++**Deliverable:** Build and deploy any language/framework++### 2.4 Deployment Management [P1]+- [ ] Deployment history per app+- [ ] Deployment status (building, deploying, live, failed)+- [ ] One-click rollback to previous version+- [ ] Keep last N deployments (configurable)+- [ ] Deployment diff view++**Deliverable:** Safe deployments with easy rollback++---++## Phase 3: One-Click App Marketplace+**Timeline: Q3 2026 (Jul-Sep)**+**Theme: "Deploy Anything in Seconds"**++### 3.1 Template System [P0]+- [ ] App template schema (YAML-based)+- [ ] Docker Compose compatibility+- [ ] Variable substitution (ports, passwords, etc.)+- [ ] Post-install scripts+- [ ] Update mechanism for apps++**Template schema example:**+```yaml+name: uptime-kuma+version: "1.21"+description: Self-hosted monitoring tool+icon: /icons/uptime-kuma.png+categories: [monitoring, devops]+compose:+ services:+ uptime-kuma:+ image: louislam/uptime-kuma:1+ ports:+ - "${PORT}:3001"+ volumes:+ - data:/app/data+variables:+ PORT:+ default: 3001+ description: "Port to expose"+```++### 3.2 Initial App Catalog (50 Apps) [P0]++**Development & DevOps:**+- [ ] Gitea / GitLab+- [ ] Drone CI / Woodpecker CI+- [ ] SonarQube+- [ ] Vault (secrets)+- [ ] Uptime Kuma++**Databases:**+- [ ] PostgreSQL+- [ ] MySQL / MariaDB+- [ ] MongoDB+- [ ] Redis+- [ ] InfluxDB++**CMS & Content:**+- [ ] WordPress+- [ ] Ghost+- [ ] Strapi+- [ ] Directus+- [ ] Payload CMS++**Productivity:**+- [ ] Nextcloud+- [ ] Minio (S3)+- [ ] Vaultwarden (passwords)+- [ ] n8n (automation)+- [ ] Appwrite++**Communication:**+- [ ] Mattermost+- [ ] Rocket.Chat+- [ ] Mailcow (email)+- [ ] Listmonk (newsletters)++**Analytics & Monitoring:**+- [ ] Plausible Analytics+- [ ] Umami+- [ ] Grafana+- [ ] Prometheus++### 3.3 App Marketplace UI [P1]+- [ ] Browse by category+- [ ] Search functionality+- [ ] App detail pages with screenshots+- [ ] One-click deploy button+- [ ] Configuration wizard+- [ ] Installed apps management++**Deliverable:** 50+ apps deployable in one click++---++## Phase 4: Backup & Recovery+**Timeline: Q4 2026 (Oct-Dec)**+**Theme: "Never Lose Data"**++### 4.1 S3-Compatible Backup [P0]+- [ ] AWS S3 support+- [ ] MinIO support (self-hosted)+- [ ] Backblaze B2 support+- [ ] DigitalOcean Spaces+- [ ] Any S3-compatible endpoint++### 4.2 Backup Features [P0]+- [ ] Scheduled backups (cron-based)+- [ ] On-demand backups+- [ ] Backup encryption (AES-256)+- [ ] Compression (gzip/zstd)+- [ ] Backup verification+- [ ] Retention policies (keep last N)++### 4.3 Restore Capabilities [P1]+- [ ] One-click restore from backup+- [ ] Selective restore (files/database)+- [ ] Point-in-time recovery+- [ ] Download backup locally+- [ ] Restore to different server++### 4.4 What Gets Backed Up+- [ ] Application files+- [ ] Database dumps+- [ ] SSL certificates+- [ ] Nginx configurations+- [ ] Environment variables+- [ ] Cron jobs++**Deliverable:** Complete disaster recovery solution++---++## Phase 5: Multi-Server Architecture+**Timeline: Q1 2027**+**Theme: "Scale Without Limits"**++### 5.1 Server Agent [P0]+- [ ] Standalone agent binary (Python/Go)+- [ ] Authenticated connection to control panel+- [ ] Auto-registration flow+- [ ] Health reporting+- [ ] Secure communication (TLS + JWT)++### 5.2 Multi-Server Management [P0]+- [ ] Add/remove servers from dashboard+- [ ] Server grouping and tagging+- [ ] Per-server resource monitoring+- [ ] Server status overview++### 5.3 Cross-Server Features [P1]+- [ ] Deploy app to any connected server+- [ ] Centralized logging+- [ ] Aggregated metrics dashboard+- [ ] Server-to-server migration++**Deliverable:** Manage entire infrastructure from one panel++---++## Phase 6: Team & Enterprise Features+**Timeline: Q2 2027**+**Theme: "Collaborate Securely"**++### 6.1 Team Management [P1]+- [ ] Create organizations+- [ ] Invite team members+- [ ] Role-based access (Admin, Developer, Viewer)+- [ ] Per-app permissions+- [ ] Audit logging++### 6.2 Advanced Security [P1]+- [ ] SSO/SAML integration+- [ ] LDAP/Active Directory+- [ ] IP whitelist for dashboard+- [ ] Session management+- [ ] Security event alerts++### 6.3 Developer Experience [P2]+- [ ] CLI tool (`serverkit` command)+- [ ] API tokens for CI/CD+- [ ] Terraform provider+- [ ] Public API documentation++**Deliverable:** Enterprise-ready team features++---++## Phase 7: Advanced Features+**Timeline: Q3-Q4 2027**+**Theme: "Power User Tools"**++### 7.1 Staging & Previews+- [ ] Create staging environments+- [ ] PR preview deployments+- [ ] Environment promotion workflow+- [ ] Isolated staging databases++### 7.2 Advanced Monitoring+- [ ] Custom metrics collection+- [ ] Log search and filtering+- [ ] Performance profiling+- [ ] Error tracking integration (Sentry)++### 7.3 Networking+- [ ] Internal networking between apps+- [ ] Load balancer configuration+- [ ] TCP/UDP proxy support+- [ ] WebSocket support improvements++---++## Milestone Summary++| Version | Milestone | Target | Key Features |+|---------|-----------|--------|--------------|+| **v0.5** | Security Ready | Mar 2026 | 2FA, env vars, notifications |+| **v0.6** | Git Deploy | Jun 2026 | Push-to-deploy, rollback |+| **v0.7** | App Store | Sep 2026 | 50+ one-click apps |+| **v0.8** | Backup Pro | Dec 2026 | S3 backups, restore |+| **v0.9** | Multi-Server | Mar 2027 | Server agents, fleet management |+| **v1.0** | Production Ready | Jun 2027 | Teams, enterprise features |++---++## Success Metrics++### User Adoption+- 1,000 GitHub stars by v1.0+- 500 active installations+- 10+ community contributors++### Feature Parity+- Match Coolify core features by v0.8+- Exceed CloudPanel features by v0.6+- Complete WordPress toolkit by v0.7++### Performance+- Dashboard load < 1 second+- Deploy completion < 2 minutes+- Support 100 apps per server++### Reliability+- 99.9% panel uptime+- Zero data loss in backups+- Automated disaster recovery++---++## Competitive Positioning by Version++| Version | vs Coolify | vs CloudPanel | vs HestiaCP |+|---------|------------|---------------|-------------|+| v0.5 | -80% | -20% | +10% |+| v0.6 | -50% | +30% | +40% |+| v0.7 | -20% | +60% | +60% |+| v0.8 | Match | +70% | +70% |+| v1.0 | +10% | +100% | +80% |++*Percentage represents feature coverage comparison*++---++## Resource Allocation++### Recommended Team+- 1-2 Backend developers (Flask, system integration)+- 1 Frontend developer (React)+- 0.5 DevOps (testing, CI/CD)+- Community contributors++### Technical Priorities+1. Backend stability and security+2. API completeness+3. Frontend polish+4. Documentation+5. Testing coverage++---++## Risk Mitigation++| Risk | Mitigation |+|------|------------|+| Scope creep | Strict phase boundaries, MVP first |+| Security vulnerabilities | Security audit before v1.0 |+| Performance at scale | Load testing each phase |+| Community adoption | Open roadmap, contributor docs |+| Maintenance burden | Automated testing, CI/CD |++---++## Next Steps++1. **This Week:** Begin 2FA implementation+2. **This Month:** Complete Phase 1.1 and 1.2+3. **This Quarter:** Ship v0.5 with all Phase 1 features+4. **Review:** Quarterly roadmap review and adjustment++---++*This roadmap is a living document. Review and update quarterly based on user feedback and market changes.*diff --git a/frontend/src/components/EnvironmentVariables.jsx b/frontend/src/components/EnvironmentVariables.jsxnew file mode 100644index 00000000..2c40d6a3--- /dev/null+++ b/frontend/src/components/EnvironmentVariables.jsx@@ -0,0 +1,535 @@+import React, { useState, useEffect, useRef } from 'react';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';++const EnvironmentVariables = ({ appId }) => {+ const toast = useToast();+ const [envVars, setEnvVars] = useState([]);+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);++ // Form state+ const [newKey, setNewKey] = useState('');+ const [newValue, setNewValue] = useState('');+ const [newIsSecret, setNewIsSecret] = useState(false);+ const [newDescription, setNewDescription] = useState('');++ // UI state+ const [showValues, setShowValues] = useState({});+ const [editingId, setEditingId] = useState(null);+ const [editValue, setEditValue] = useState('');+ const [showImportModal, setShowImportModal] = useState(false);+ const [showHistoryModal, setShowHistoryModal] = useState(false);+ const [importContent, setImportContent] = useState('');+ const [importOverwrite, setImportOverwrite] = useState(true);+ const [history, setHistory] = useState([]);+ const [filter, setFilter] = useState('');++ const fileInputRef = useRef(null);++ useEffect(() => {+ loadEnvVars();+ }, [appId]);++ async function loadEnvVars() {+ try {+ setLoading(true);+ const data = await api.getEnvVars(appId);+ setEnvVars(data.env_vars || []);+ } catch (err) {+ toast.error('Failed to load environment variables');+ console.error('Failed to load env vars:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleAdd(e) {+ e.preventDefault();+ if (!newKey.trim()) {+ toast.error('Key is required');+ return;+ }++ setSaving(true);+ try {+ await api.createEnvVar(appId, newKey.trim(), newValue, newIsSecret, newDescription || null);+ toast.success('Environment variable added');+ setNewKey('');+ setNewValue('');+ setNewIsSecret(false);+ setNewDescription('');+ loadEnvVars();+ } catch (err) {+ toast.error(err.message || 'Failed to add environment variable');+ } finally {+ setSaving(false);+ }+ }++ async function handleUpdate(key) {+ if (editingId === null) return;++ setSaving(true);+ try {+ await api.updateEnvVar(appId, key, { value: editValue });+ toast.success('Environment variable updated');+ setEditingId(null);+ setEditValue('');+ loadEnvVars();+ } catch (err) {+ toast.error(err.message || 'Failed to update environment variable');+ } finally {+ setSaving(false);+ }+ }++ async function handleDelete(key) {+ if (!confirm(`Delete environment variable "${key}"?`)) return;++ try {+ await api.deleteEnvVar(appId, key);+ toast.success('Environment variable deleted');+ loadEnvVars();+ } catch (err) {+ toast.error(err.message || 'Failed to delete environment variable');+ }+ }++ async function handleToggleSecret(envVar) {+ try {+ await api.updateEnvVar(appId, envVar.key, { is_secret: !envVar.is_secret });+ loadEnvVars();+ } catch (err) {+ toast.error('Failed to update');+ }+ }++ function toggleShowValue(id) {+ setShowValues(prev => ({ ...prev, [id]: !prev[id] }));+ }++ function startEditing(envVar) {+ setEditingId(envVar.id);+ setEditValue(envVar.value);+ }++ function cancelEditing() {+ setEditingId(null);+ setEditValue('');+ }++ async function handleExport(includeSecrets = true) {+ try {+ const data = await api.exportEnvFile(appId, includeSecrets);+ // Download as file+ const blob = new Blob([data.content], { type: 'text/plain' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = data.filename || 'app.env';+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);+ toast.success('Environment file exported');+ } catch (err) {+ toast.error('Failed to export');+ }+ }++ async function handleImport() {+ if (!importContent.trim()) {+ toast.error('Please paste .env content');+ return;+ }++ setSaving(true);+ try {+ const result = await api.importEnvFile(appId, importContent, importOverwrite);+ toast.success(`${result.count} variables imported`);+ setShowImportModal(false);+ setImportContent('');+ loadEnvVars();+ } catch (err) {+ toast.error(err.message || 'Failed to import');+ } finally {+ setSaving(false);+ }+ }++ function handleFileUpload(e) {+ const file = e.target.files[0];+ if (!file) return;++ const reader = new FileReader();+ reader.onload = (event) => {+ setImportContent(event.target.result);+ };+ reader.readAsText(file);+ }++ async function handleShowHistory() {+ try {+ const data = await api.getEnvVarHistory(appId);+ setHistory(data.history || []);+ setShowHistoryModal(true);+ } catch (err) {+ toast.error('Failed to load history');+ }+ }++ async function handleClearAll() {+ if (!confirm('Delete ALL environment variables? This cannot be undone.')) return;+ if (!confirm('Are you absolutely sure?')) return;++ try {+ await api.clearEnvVars(appId);+ toast.success('All environment variables cleared');+ loadEnvVars();+ } catch (err) {+ toast.error('Failed to clear');+ }+ }++ function copyToClipboard(value) {+ navigator.clipboard.writeText(value);+ toast.success('Copied to clipboard');+ }++ // Filter env vars+ const filteredEnvVars = filter+ ? envVars.filter(ev =>+ ev.key.toLowerCase().includes(filter.toLowerCase()) ||+ (ev.description && ev.description.toLowerCase().includes(filter.toLowerCase()))+ )+ : envVars;++ if (loading) {+ return <div className="loading">Loading environment variables...</div>;+ }++ return (+ <div className="env-vars-container">+ <div className="section-header">+ <h3>Environment Variables</h3>+ <div className="header-actions">+ <button className="btn btn-secondary btn-sm" onClick={() => setShowImportModal(true)}>+ <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/>+ </svg>+ Import+ </button>+ <button className="btn btn-secondary btn-sm" onClick={() => handleExport(true)}>+ <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/>+ </svg>+ Export+ </button>+ <button className="btn btn-secondary btn-sm" onClick={handleShowHistory}>+ <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/>+ <polyline points="12 6 12 12 16 14"/>+ </svg>+ History+ </button>+ </div>+ </div>++ <p className="hint">+ Environment variables are encrypted at rest. Changes require app restart to take effect.+ </p>++ {/* Add new variable form */}+ <form className="env-add-form" onSubmit={handleAdd}>+ <div className="env-form-row">+ <input+ type="text"+ value={newKey}+ onChange={(e) => setNewKey(e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, ''))}+ placeholder="KEY_NAME"+ className="env-key-input"+ />+ <input+ type={newIsSecret ? 'password' : 'text'}+ value={newValue}+ onChange={(e) => setNewValue(e.target.value)}+ placeholder="value"+ className="env-value-input"+ />+ <label className="env-secret-toggle" title="Mark as secret">+ <input+ type="checkbox"+ checked={newIsSecret}+ onChange={(e) => setNewIsSecret(e.target.checked)}+ />+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>+ <path d="M7 11V7a5 5 0 0 1 10 0v4"/>+ </svg>+ </label>+ <button type="submit" className="btn btn-primary" disabled={saving}>+ Add+ </button>+ </div>+ <input+ type="text"+ value={newDescription}+ onChange={(e) => setNewDescription(e.target.value)}+ placeholder="Optional description..."+ className="env-description-input"+ />+ </form>++ {/* Filter */}+ {envVars.length > 5 && (+ <div className="env-filter">+ <input+ type="text"+ value={filter}+ onChange={(e) => setFilter(e.target.value)}+ placeholder="Filter variables..."+ />+ {filter && (+ <button className="filter-clear" onClick={() => setFilter('')}>×</button>+ )}+ </div>+ )}++ {/* Variables list */}+ {filteredEnvVars.length === 0 ? (+ <div className="env-empty">+ {filter ? 'No matching variables' : 'No environment variables defined yet'}+ </div>+ ) : (+ <div className="env-list">+ {filteredEnvVars.map(envVar => (+ <div key={envVar.id} className={`env-item ${envVar.is_secret ? 'is-secret' : ''}`}>+ <div className="env-item-header">+ <span className="env-key">+ {envVar.key}+ {envVar.is_secret && (+ <span className="secret-badge" title="Secret value">+ <svg viewBox="0 0 24 24" width="12" height="12" stroke="currentColor" fill="none" strokeWidth="2">+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>+ <path d="M7 11V7a5 5 0 0 1 10 0v4"/>+ </svg>+ </span>+ )}+ </span>+ <div className="env-item-actions">+ <button+ className="btn-icon"+ onClick={() => toggleShowValue(envVar.id)}+ title={showValues[envVar.id] ? 'Hide value' : 'Show value'}+ >+ {showValues[envVar.id] ? (+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/>+ <line x1="1" y1="1" x2="23" y2="23"/>+ </svg>+ ) : (+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>+ <circle cx="12" cy="12" r="3"/>+ </svg>+ )}+ </button>+ <button+ className="btn-icon"+ onClick={() => copyToClipboard(envVar.value)}+ title="Copy value"+ >+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>+ </svg>+ </button>+ <button+ className="btn-icon"+ onClick={() => startEditing(envVar)}+ title="Edit"+ >+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>+ </svg>+ </button>+ <button+ className="btn-icon"+ onClick={() => handleToggleSecret(envVar)}+ title={envVar.is_secret ? 'Mark as non-secret' : 'Mark as secret'}+ >+ {envVar.is_secret ? (+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>+ <path d="M7 11V7a5 5 0 0 1 9.9-1"/>+ </svg>+ ) : (+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>+ <path d="M7 11V7a5 5 0 0 1 10 0v4"/>+ </svg>+ )}+ </button>+ <button+ className="btn-icon btn-danger"+ onClick={() => handleDelete(envVar.key)}+ title="Delete"+ >+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <polyline points="3 6 5 6 21 6"/>+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>+ </svg>+ </button>+ </div>+ </div>++ {editingId === envVar.id ? (+ <div className="env-edit-row">+ <input+ type="text"+ value={editValue}+ onChange={(e) => setEditValue(e.target.value)}+ autoFocus+ onKeyDown={(e) => {+ if (e.key === 'Enter') handleUpdate(envVar.key);+ if (e.key === 'Escape') cancelEditing();+ }}+ />+ <button className="btn btn-primary btn-sm" onClick={() => handleUpdate(envVar.key)}>+ Save+ </button>+ <button className="btn btn-secondary btn-sm" onClick={cancelEditing}>+ Cancel+ </button>+ </div>+ ) : (+ <div className="env-value">+ {showValues[envVar.id] ? envVar.value : '••••••••••••'}+ </div>+ )}++ {envVar.description && (+ <div className="env-description">{envVar.description}</div>+ )}+ </div>+ ))}+ </div>+ )}++ {/* Footer actions */}+ {envVars.length > 0 && (+ <div className="env-footer">+ <span className="env-count">{envVars.length} variable{envVars.length !== 1 ? 's' : ''}</span>+ <button className="btn btn-danger btn-sm" onClick={handleClearAll}>+ Clear All+ </button>+ </div>+ )}++ {/* Import Modal */}+ {showImportModal && (+ <div className="modal-overlay" onClick={() => setShowImportModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Import Environment Variables</h2>+ <button className="modal-close" onClick={() => setShowImportModal(false)}>×</button>+ </div>+ <div className="modal-body">+ <p className="hint">Paste your .env file content below or upload a file.</p>++ <div className="import-file-upload">+ <input+ type="file"+ ref={fileInputRef}+ accept=".env,.txt"+ onChange={handleFileUpload}+ style={{ display: 'none' }}+ />+ <button+ className="btn btn-secondary"+ onClick={() => fileInputRef.current?.click()}+ >+ Choose File+ </button>+ </div>++ <textarea+ value={importContent}+ onChange={(e) => setImportContent(e.target.value)}+ placeholder="DATABASE_URL=postgres://... API_KEY=your-api-key DEBUG=false"+ rows={10}+ className="import-textarea"+ />++ <label className="checkbox-label">+ <input+ type="checkbox"+ checked={importOverwrite}+ onChange={(e) => setImportOverwrite(e.target.checked)}+ />+ <span>Overwrite existing variables with same keys</span>+ </label>+ </div>+ <div className="modal-footer">+ <button className="btn btn-secondary" onClick={() => setShowImportModal(false)}>+ Cancel+ </button>+ <button className="btn btn-primary" onClick={handleImport} disabled={saving}>+ {saving ? 'Importing...' : 'Import'}+ </button>+ </div>+ </div>+ </div>+ )}++ {/* History Modal */}+ {showHistoryModal && (+ <div className="modal-overlay" onClick={() => setShowHistoryModal(false)}>+ <div className="modal modal-lg" onClick={e => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Change History</h2>+ <button className="modal-close" onClick={() => setShowHistoryModal(false)}>×</button>+ </div>+ <div className="modal-body">+ {history.length === 0 ? (+ <p className="hint">No changes recorded yet.</p>+ ) : (+ <table className="table">+ <thead>+ <tr>+ <th>Key</th>+ <th>Action</th>+ <th>Changed At</th>+ </tr>+ </thead>+ <tbody>+ {history.map((h, idx) => (+ <tr key={idx}>+ <td className="mono">{h.key}</td>+ <td>+ <span className={`badge badge-${h.action === 'created' ? 'success' : h.action === 'deleted' ? 'danger' : 'warning'}`}>+ {h.action}+ </span>+ </td>+ <td>{new Date(h.changed_at).toLocaleString()}</td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ <div className="modal-footer">+ <button className="btn btn-secondary" onClick={() => setShowHistoryModal(false)}>+ Close+ </button>+ </div>+ </div>+ </div>+ )}+ </div>+ );+};++export default EnvironmentVariables;diff --git a/frontend/src/pages/ApplicationDetail.jsx b/frontend/src/pages/ApplicationDetail.jsxindex bf058152..3eedf494 100644--- a/frontend/src/pages/ApplicationDetail.jsx+++ b/frontend/src/pages/ApplicationDetail.jsx@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';import { useParams, useNavigate } from 'react-router-dom';import api from '../services/api';import { useToast } from '../contexts/ToastContext';+import EnvironmentVariables from '../components/EnvironmentVariables';const ApplicationDetail = () => {const { id } = useParams();@@ -134,6 +135,12 @@ const ApplicationDetail = () => {>Overview</button>+ <button+ className={`tab ${activeTab === 'environment' ? 'active' : ''}`}+ onClick={() => setActiveTab('environment')}+ >+ Environment+ </button>{isPythonApp && (<><button@@ -142,12 +149,6 @@ const ApplicationDetail = () => {>Packages</button>- <button- className={`tab ${activeTab === 'environment' ? 'active' : ''}`}- onClick={() => setActiveTab('environment')}- >- Environment- </button><buttonclassName={`tab ${activeTab === 'gunicorn' ? 'active' : ''}`}onClick={() => setActiveTab('gunicorn')}@@ -206,8 +207,8 @@ const ApplicationDetail = () => {<div className="tab-content">{activeTab === 'overview' && <OverviewTab app={app} />}+ {activeTab === 'environment' && <EnvironmentVariables appId={app.id} />}{activeTab === 'packages' && isPythonApp && <PackagesTab appId={app.id} />}- {activeTab === 'environment' && isPythonApp && <EnvironmentTab appId={app.id} />}{activeTab === 'gunicorn' && isPythonApp && <GunicornTab appId={app.id} />}{activeTab === 'commands' && isPythonApp && <CommandsTab appId={app.id} appType={app.app_type} />}{activeTab === 'plugins' && isWordPressApp && <PluginsTab appId={app.id} />}diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex cdb4daad..5eb55214 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -1524,6 +1524,67 @@ class ApiService {async getUptimeTrackingStatus() {return this.request('/uptime/tracking/status');}++ // ========================================+ // Environment Variables endpoints+ // ========================================+ async getEnvVars(appId, maskSecrets = false) {+ const params = maskSecrets ? '?mask=true' : '';+ return this.request(`/apps/${appId}/env${params}`);+ }++ async getEnvVar(appId, key) {+ return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`);+ }++ async createEnvVar(appId, key, value, isSecret = false, description = null) {+ return this.request(`/apps/${appId}/env`, {+ method: 'POST',+ body: { key, value, is_secret: isSecret, description }+ });+ }++ async updateEnvVar(appId, key, data) {+ return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`, {+ method: 'PUT',+ body: data+ });+ }++ async deleteEnvVar(appId, key) {+ return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`, {+ method: 'DELETE'+ });+ }++ async bulkSetEnvVars(appId, envVars) {+ return this.request(`/apps/${appId}/env/bulk`, {+ method: 'POST',+ body: { env_vars: envVars }+ });+ }++ async importEnvFile(appId, content, overwrite = true) {+ return this.request(`/apps/${appId}/env/import`, {+ method: 'POST',+ body: { content, overwrite }+ });+ }++ async exportEnvFile(appId, includeSecrets = true) {+ const params = includeSecrets ? '' : '?include_secrets=false';+ return this.request(`/apps/${appId}/env/export${params}`);+ }++ async getEnvVarHistory(appId, limit = 50) {+ return this.request(`/apps/${appId}/env/history?limit=${limit}`);+ }++ async clearEnvVars(appId) {+ return this.request(`/apps/${appId}/env/clear`, {+ method: 'DELETE'+ });+ }}export const api = new ApiService();diff --git a/frontend/src/styles/components/_env-vars.less b/frontend/src/styles/components/_env-vars.lessnew file mode 100644index 00000000..a9b56a4e--- /dev/null+++ b/frontend/src/styles/components/_env-vars.less@@ -0,0 +1,271 @@+// ============================================+// ENVIRONMENT VARIABLES COMPONENT+// ============================================++.env-vars-container {+ .section-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @spacing-md;++ h3 {+ margin: 0;+ }++ .header-actions {+ display: flex;+ gap: @spacing-sm;+ }+ }++ .hint {+ color: @text-tertiary;+ font-size: @font-size-sm;+ margin-bottom: @spacing-lg;+ }+}++// Add new variable form+.env-add-form {+ background: @surface-secondary;+ border: 1px solid @border-color;+ border-radius: @radius-md;+ padding: @spacing-md;+ margin-bottom: @spacing-lg;++ .env-form-row {+ display: flex;+ gap: @spacing-sm;+ margin-bottom: @spacing-sm;+ }++ .env-key-input {+ width: 200px;+ flex-shrink: 0;+ font-family: @font-mono;+ text-transform: uppercase;+ }++ .env-value-input {+ flex: 1;+ }++ .env-secret-toggle {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 40px;+ height: 40px;+ background: @surface-tertiary;+ border: 1px solid @border-color;+ border-radius: @radius-sm;+ cursor: pointer;+ color: @text-tertiary;+ transition: all 0.2s;++ input {+ display: none;+ }++ &:hover {+ border-color: @primary;+ color: @primary;+ }++ &:has(input:checked) {+ background: fade(@primary, 20%);+ border-color: @primary;+ color: @primary;+ }+ }++ .env-description-input {+ width: 100%;+ font-size: @font-size-sm;+ color: @text-secondary;+ }+}++// Filter+.env-filter {+ position: relative;+ margin-bottom: @spacing-md;++ input {+ width: 100%;+ padding-right: 36px;+ }++ .filter-clear {+ position: absolute;+ right: 8px;+ top: 50%;+ transform: translateY(-50%);+ background: none;+ border: none;+ color: @text-tertiary;+ cursor: pointer;+ font-size: 18px;+ padding: 4px 8px;++ &:hover {+ color: @text-primary;+ }+ }+}++// Variables list+.env-list {+ display: flex;+ flex-direction: column;+ gap: @spacing-sm;+}++.env-item {+ background: @surface-secondary;+ border: 1px solid @border-color;+ border-radius: @radius-md;+ padding: @spacing-md;+ transition: border-color 0.2s;++ &:hover {+ border-color: @border-light;+ }++ &.is-secret {+ border-left: 3px solid @warning;+ }++ .env-item-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @spacing-xs;+ }++ .env-key {+ font-family: @font-mono;+ font-weight: 600;+ color: @text-primary;+ display: flex;+ align-items: center;+ gap: @spacing-xs;++ .secret-badge {+ color: @warning;+ }+ }++ .env-item-actions {+ display: flex;+ gap: @spacing-xs;+ opacity: 0;+ transition: opacity 0.2s;+ }++ &:hover .env-item-actions {+ opacity: 1;+ }++ .env-value {+ font-family: @font-mono;+ font-size: @font-size-sm;+ color: @text-secondary;+ word-break: break-all;+ padding: @spacing-xs 0;+ }++ .env-description {+ font-size: @font-size-xs;+ color: @text-tertiary;+ margin-top: @spacing-xs;+ font-style: italic;+ }++ .env-edit-row {+ display: flex;+ gap: @spacing-sm;+ margin-top: @spacing-sm;++ input {+ flex: 1;+ font-family: @font-mono;+ }+ }+}++.btn-icon {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ background: transparent;+ border: none;+ border-radius: @radius-sm;+ color: @text-tertiary;+ cursor: pointer;+ transition: all 0.2s;++ &:hover {+ background: @surface-tertiary;+ color: @text-primary;+ }++ &.btn-danger:hover {+ background: fade(@danger, 20%);+ color: @danger;+ }+}++// Empty state+.env-empty {+ text-align: center;+ padding: @spacing-xl;+ color: @text-tertiary;+ background: @surface-secondary;+ border: 1px dashed @border-color;+ border-radius: @radius-md;+}++// Footer+.env-footer {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-top: @spacing-lg;+ padding-top: @spacing-md;+ border-top: 1px solid @border-color;++ .env-count {+ color: @text-tertiary;+ font-size: @font-size-sm;+ }+}++// Import modal specific+.import-file-upload {+ margin-bottom: @spacing-md;+}++.import-textarea {+ width: 100%;+ font-family: @font-mono;+ font-size: @font-size-sm;+ background: @surface-primary;+ border: 1px solid @border-color;+ border-radius: @radius-sm;+ padding: @spacing-md;+ resize: vertical;+ min-height: 200px;++ &::placeholder {+ color: @text-tertiary;+ }+}++// Modal large variant+.modal-lg {+ max-width: 700px;+}diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.lessindex d1eb7969..d24b3203 100644--- a/frontend/src/styles/main.less+++ b/frontend/src/styles/main.less@@ -40,6 +40,7 @@@import 'components/_toasts';@import 'components/_spinner';@import 'components/_uptime';+@import 'components/_env-vars';// --------------------------------------------// 5. PAGE-SPECIFIC STYLES