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 SSO/OAuth and DB migration framework
Juan Denis08d5c4badefd
diff --git a/ROADMAP.md b/ROADMAP.mdindex d71e4851..b4271464 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -166,17 +166,17 @@ This document outlines the development roadmap for ServerKit. Features are organ----## Phase 13: Email Server Management (Planned)+## Phase 13: Email Server Management (Completed)**Priority: Medium**-- [ ] Postfix mail server setup-- [ ] Dovecot IMAP/POP3 configuration-- [ ] Email account management-- [ ] Spam filtering (SpamAssassin)-- [ ] DKIM/SPF/DMARC configuration-- [ ] Webmail interface integration-- [ ] Email forwarding rules+- [x] Postfix mail server setup+- [x] Dovecot IMAP/POP3 configuration+- [x] Email account management+- [x] Spam filtering (SpamAssassin)+- [x] DKIM/SPF/DMARC configuration+- [x] Webmail interface integration+- [x] Email forwarding rules---@@ -267,20 +267,54 @@ This document outlines the development roadmap for ServerKit. Features are organ----## Phase 21: SSO & OAuth Login (Planned)+## Phase 21: SSO & OAuth Login (Completed)**Priority: High**-- [ ] Google OAuth 2.0 login-- [ ] GitHub OAuth login-- [ ] Generic OpenID Connect (OIDC) provider support-- [ ] SAML 2.0 support for enterprise environments-- [ ] Social login UI (provider buttons on login page)-- [ ] Account linking (connect OAuth identity to existing local account)-- [ ] Auto-provisioning of new users on first SSO login-- [ ] Configurable SSO settings (enable/disable providers, client ID/secret management)-- [ ] Enforce SSO-only login (disable password auth for team members)-- [ ] SSO session management and token refresh+- [x] Google OAuth 2.0 login+- [x] GitHub OAuth login+- [x] Generic OpenID Connect (OIDC) provider support+- [x] SAML 2.0 support for enterprise environments+- [x] Social login UI (provider buttons on login page)+- [x] Account linking (connect OAuth identity to existing local account)+- [x] Auto-provisioning of new users on first SSO login+- [x] Configurable SSO settings (enable/disable providers, client ID/secret management)+- [x] Enforce SSO-only login (disable password auth for team members)+- [x] SSO session management and token refresh++---++## Phase 22: Database Migrations & Schema Versioning (Planned)++**Priority: High**++Matomo-style update wizard — when the user logs in after an update and there are pending migrations, a popup/wizard guides them through the process visually.++### Backend — Migration Engine+- [ ] Integrate Flask-Migrate (Alembic) for versioned schema migrations+- [ ] Generate initial migration from current model state as baseline+- [ ] Replace `_auto_migrate_columns()` hack with proper Alembic migrations+- [ ] Store schema version in a `schema_version` table (current version, history)+- [ ] API endpoint to check migration status (`GET /api/v1/system/migrations`)+- [ ] API endpoint to run pending migrations (`POST /api/v1/system/migrations/apply`)+- [ ] API endpoint to rollback last migration (`POST /api/v1/system/migrations/rollback`)+- [ ] Auto-detect pending migrations on login and flag the session+- [ ] Pre-migration automatic DB backup before applying changes+- [ ] Migration scripts for all existing model changes (retroactive baseline)++### Frontend — Update Wizard UI+- [ ] Full-screen modal/wizard that appears when pending migrations are detected+- [ ] Step 1: "Update Available" — show current version vs new version, changelog summary+- [ ] Step 2: "Backup" — auto-backup the database, show progress, confirm success+- [ ] Step 3: "Apply Migrations" — run migrations with real-time progress/log output+- [ ] Step 4: "Done" — success confirmation with summary of changes applied+- [ ] Error handling: if a migration fails, show the error and offer rollback option+- [ ] Block access to the panel until migrations are applied (like Matomo does)+- [ ] Migration history page in Settings showing all past migrations and timestamps++### CLI Fallback+- [ ] CLI commands for headless/SSH scenarios (`flask db upgrade`, `flask db status`)+- [ ] CLI rollback support (`flask db downgrade`)---@@ -289,7 +323,7 @@ This document outlines the development roadmap for ServerKit. Features are organ| Version | Target Features | Status ||---------|-----------------|--------|| v0.9.0 | Core features, 2FA, Notifications, Security | Current |-| v1.0.0 | Production-ready stable release | Planned |+| v1.0.0 | Production-ready stable release, DB migrations | Planned || v1.1.0 | Multi-server, Git deployment | Planned || v1.2.0 | Backups, Advanced SSL, Advanced Security | Planned || v1.3.0 | Email server, API enhancements | Planned |diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 444c3112..329f138f 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -5,11 +5,13 @@ from flask_jwt_extended import JWTManagerfrom flask_cors import CORSfrom flask_limiter import Limiterfrom flask_limiter.util import get_remote_address+from flask_migrate import Migratefrom config import configdb = SQLAlchemy()jwt = JWTManager()+migrate = Migrate()limiter = Limiter(key_func=get_remote_address, default_limits=["100 per minute"])socketio = None@@ -33,6 +35,7 @@ def create_app(config_name=None):# Initialize extensionsdb.init_app(app)+ migrate.init_app(app, db)jwt.init_app(app)limiter.init_app(app)CORS(@@ -167,6 +170,14 @@ def create_app(config_name=None):from app.api.two_factor import two_factor_bpapp.register_blueprint(two_factor_bp, url_prefix='/api/v1/auth/2fa')+ # Register blueprints - SSO / OAuth+ from app.api.sso import sso_bp+ app.register_blueprint(sso_bp, url_prefix='/api/v1/sso')++ # Register blueprints - Database Migrations+ from app.api.migrations import migrations_bp+ app.register_blueprint(migrations_bp, url_prefix='/api/v1/migrations')+# Register blueprints - Admin (User Management, Settings, Audit Logs)from app.api.admin import admin_bpapp.register_blueprint(admin_bp, url_prefix='/api/v1/admin')@@ -183,12 +194,10 @@ def create_app(config_name=None):from app.api.servers import servers_bpapp.register_blueprint(servers_bp, url_prefix='/api/v1/servers')- # Create database tables+ # Handle database migrations (Alembic)with app.app_context():- db.create_all()-- # Auto-migrate missing columns on existing tables- _auto_migrate_columns(app)+ from app.services.migration_service import MigrationService+ MigrationService.check_and_prepare(app)# Initialize default settings and migrate legacy rolesfrom app.services.settings_service import SettingsService@@ -231,72 +240,6 @@ def get_socketio():return socketio-def _auto_migrate_columns(app):- """Add missing columns to existing tables (lightweight auto-migration)."""- import logging- from sqlalchemy import text, inspect as sa_inspect-- logger = logging.getLogger(__name__)-- # Define expected columns per table: (table, column, sql_type)- expected_columns = [- # wordpress_sites table- ('wordpress_sites', 'environment_type', "VARCHAR(20) DEFAULT 'standalone'"),- ('wordpress_sites', 'multidev_branch', 'VARCHAR(200)'),- ('wordpress_sites', 'is_locked', 'BOOLEAN DEFAULT 0'),- ('wordpress_sites', 'locked_by', 'VARCHAR(100)'),- ('wordpress_sites', 'locked_reason', 'VARCHAR(200)'),- ('wordpress_sites', 'lock_expires_at', 'DATETIME'),- ('wordpress_sites', 'compose_project_name', 'VARCHAR(100)'),- ('wordpress_sites', 'container_prefix', 'VARCHAR(100)'),- ('wordpress_sites', 'resource_limits', 'TEXT'),- ('wordpress_sites', 'basic_auth_enabled', 'BOOLEAN DEFAULT 0'),- ('wordpress_sites', 'basic_auth_user', 'VARCHAR(100)'),- ('wordpress_sites', 'basic_auth_password_hash', 'VARCHAR(200)'),- ('wordpress_sites', 'health_status', "VARCHAR(20) DEFAULT 'unknown'"),- ('wordpress_sites', 'last_health_check', 'DATETIME'),- ('wordpress_sites', 'disk_usage_bytes', 'BIGINT DEFAULT 0'),- ('wordpress_sites', 'disk_usage_updated_at', 'DATETIME'),- ('wordpress_sites', 'auto_sync_schedule', 'VARCHAR(100)'),- ('wordpress_sites', 'auto_sync_enabled', 'BOOLEAN DEFAULT 0'),- # applications table- ('applications', 'private_slug', 'VARCHAR(50)'),- ('applications', 'private_url_enabled', 'BOOLEAN DEFAULT 0'),- ('applications', 'environment_type', "VARCHAR(20) DEFAULT 'standalone'"),- ('applications', 'linked_app_id', 'INTEGER'),- ('applications', 'shared_config', 'TEXT'),- ]-- try:- inspector = sa_inspect(db.engine)- existing_tables = inspector.get_table_names()-- # Group by table for efficient inspection- tables_checked = {}- applied = 0-- for table, column, col_type in expected_columns:- if table not in existing_tables:- continue-- if table not in tables_checked:- tables_checked[table] = [col['name'] for col in inspector.get_columns(table)]-- if column not in tables_checked[table]:- try:- db.session.execute(text(f'ALTER TABLE {table} ADD COLUMN {column} {col_type}'))- applied += 1- logger.info(f'Auto-migrated: added {table}.{column}')- except Exception as e:- logger.warning(f'Auto-migrate failed for {table}.{column}: {e}')-- if applied > 0:- db.session.commit()- logger.info(f'Auto-migration: applied {applied} column(s)')- except Exception as e:- logger.warning(f'Auto-migration check failed: {e}')--_auto_sync_thread = Nonediff --git a/backend/app/api/auth.py b/backend/app/api/auth.pyindex 707c6b43..8c8e0efb 100644--- a/backend/app/api/auth.py+++ b/backend/app/api/auth.py@@ -21,9 +21,26 @@ def get_setup_status():needs_setup = SettingsService.needs_setup()registration_enabled = SettingsService.is_registration_enabled()+ # SSO info for login page+ from app.services import sso_service+ sso_providers = sso_service.get_enabled_providers()+ password_login_enabled = sso_service.is_password_login_allowed()++ # Migration status+ from app.services.migration_service import MigrationService+ migration_status = MigrationService.get_status()+return jsonify({'needs_setup': needs_setup,- 'registration_enabled': registration_enabled+ 'registration_enabled': registration_enabled,+ 'sso_providers': sso_providers,+ 'password_login_enabled': password_login_enabled,+ 'needs_migration': migration_status['needs_migration'],+ 'migration_info': {+ 'pending_count': migration_status['pending_count'],+ 'current_revision': migration_status['current_revision'],+ 'head_revision': migration_status['head_revision'],+ },}), 200@@ -123,6 +140,11 @@ def complete_onboarding():@auth_bp.route('/login', methods=['POST'])@limiter.limit("5 per minute")def login():+ # Check if password login is disabled (SSO-only mode)+ from app.services import sso_service+ if not sso_service.is_password_login_allowed():+ return jsonify({'error': 'Password login is disabled. Please use SSO.'}), 403+data = request.get_json()if not data:diff --git a/backend/app/api/migrations.py b/backend/app/api/migrations.pynew file mode 100644index 00000000..a5aea12c--- /dev/null+++ b/backend/app/api/migrations.py@@ -0,0 +1,54 @@+from flask import Blueprint, jsonify, current_app+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.models import User+from app.services.migration_service import MigrationService++migrations_bp = Blueprint('migrations', __name__)+++@migrations_bp.route('/status', methods=['GET'])+def get_migration_status():+ """Check if migrations are pending. No auth required (called before login)."""+ status = MigrationService.get_status()+ return jsonify(status), 200+++@migrations_bp.route('/backup', methods=['POST'])+@jwt_required()+def create_backup():+ """Create a database backup before applying migrations. Admin only."""+ user = User.query.get(get_jwt_identity())+ if not user or user.role != User.ROLE_ADMIN:+ return jsonify({'error': 'Admin access required'}), 403++ result = MigrationService.create_backup(current_app)+ if result['success']:+ return jsonify(result), 200+ return jsonify(result), 500+++@migrations_bp.route('/apply', methods=['POST'])+@jwt_required()+def apply_migrations():+ """Apply all pending migrations. Admin only."""+ user = User.query.get(get_jwt_identity())+ if not user or user.role != User.ROLE_ADMIN:+ return jsonify({'error': 'Admin access required'}), 403++ result = MigrationService.apply_migrations(current_app)+ if result['success']:+ return jsonify(result), 200+ return jsonify(result), 500+++@migrations_bp.route('/history', methods=['GET'])+@jwt_required()+def get_migration_history():+ """Return all migration revisions. Admin only."""+ user = User.query.get(get_jwt_identity())+ if not user or user.role != User.ROLE_ADMIN:+ return jsonify({'error': 'Admin access required'}), 403++ history = MigrationService.get_migration_history(current_app)+ return jsonify({'revisions': history}), 200diff --git a/backend/app/api/sso.py b/backend/app/api/sso.pynew file mode 100644index 00000000..2f584488--- /dev/null+++ b/backend/app/api/sso.py@@ -0,0 +1,328 @@+"""SSO / OAuth API blueprint."""+from datetime import datetime+from flask import Blueprint, request, jsonify, session+from flask_jwt_extended import (+ create_access_token, create_refresh_token, jwt_required, get_jwt_identity+)+from app import db+from app.models import User, AuditLog+from app.models.oauth_identity import OAuthIdentity+from app.services import sso_service+from app.services.settings_service import SettingsService+from app.services.audit_service import AuditService++sso_bp = Blueprint('sso', __name__)++VALID_PROVIDERS = ('google', 'github', 'oidc', 'saml')+++# ------------------------------------------------------------------+# Public endpoints (login flow)+# ------------------------------------------------------------------++@sso_bp.route('/providers', methods=['GET'])+def list_providers():+ """List enabled SSO providers + whether password login is available."""+ return jsonify({+ 'providers': sso_service.get_enabled_providers(),+ 'password_login_enabled': sso_service.is_password_login_allowed(),+ }), 200+++@sso_bp.route('/authorize/<provider>', methods=['GET'])+def authorize(provider):+ """Generate OAuth authorize URL (state + PKCE)."""+ if provider not in VALID_PROVIDERS or provider == 'saml':+ return jsonify({'error': f'Invalid OAuth provider: {provider}'}), 400++ redirect_uri = request.args.get('redirect_uri', '')+ if not redirect_uri:+ return jsonify({'error': 'redirect_uri is required'}), 400++ try:+ auth_url, state = sso_service.generate_auth_url(provider, redirect_uri)+ return jsonify({'auth_url': auth_url, 'state': state}), 200+ except Exception as e:+ return jsonify({'error': str(e)}), 400+++@sso_bp.route('/callback/<provider>', methods=['POST'])+def callback(provider):+ """Exchange authorization code for tokens, find/create user, return JWT."""+ if provider not in VALID_PROVIDERS or provider == 'saml':+ return jsonify({'error': f'Invalid OAuth provider: {provider}'}), 400++ data = request.get_json() or {}+ code = data.get('code', '')+ state = data.get('state', '')+ redirect_uri = data.get('redirect_uri', '')++ if not code or not state:+ return jsonify({'error': 'code and state are required'}), 400++ try:+ profile = sso_service.handle_oauth_callback(provider, code, state, redirect_uri)+ user, is_new = sso_service.find_or_create_user(provider, profile)+ except ValueError as e:+ AuditLog.log(+ action=AuditLog.ACTION_SSO_LOGIN_FAILED,+ details={'provider': provider, 'error': str(e)},+ ip_address=request.remote_addr,+ )+ db.session.commit()+ return jsonify({'error': str(e)}), 403+ except Exception as e:+ AuditLog.log(+ action=AuditLog.ACTION_SSO_LOGIN_FAILED,+ details={'provider': provider, 'error': str(e)},+ ip_address=request.remote_addr,+ )+ db.session.commit()+ return jsonify({'error': 'SSO authentication failed'}), 500++ return _complete_sso_login(user, provider, is_new)+++@sso_bp.route('/saml/callback', methods=['POST'])+def saml_callback():+ """SAML ACS endpoint (form POST from IdP)."""+ try:+ request_data = {+ 'https': request.scheme == 'https',+ 'http_host': request.host,+ 'script_name': request.path,+ 'acs_url': request.url,+ 'sp_entity_id': request.host_url.rstrip('/'),+ }+ profile = sso_service.handle_saml_callback(request.form, request_data)+ user, is_new = sso_service.find_or_create_user('saml', profile)+ except ValueError as e:+ return jsonify({'error': str(e)}), 403+ except Exception as e:+ return jsonify({'error': 'SAML authentication failed'}), 500++ return _complete_sso_login(user, 'saml', is_new)+++@sso_bp.route('/saml/metadata', methods=['GET'])+def saml_metadata():+ """Return SP metadata XML."""+ try:+ from onelogin.saml2.auth import OneLogin_Saml2_Auth+ cfg = sso_service.get_provider_config('saml')+ request_data = {+ 'https': request.scheme == 'https',+ 'http_host': request.host,+ 'script_name': request.path,+ 'acs_url': request.url_root.rstrip('/') + '/api/v1/sso/saml/callback',+ 'sp_entity_id': request.host_url.rstrip('/'),+ }+ settings = sso_service.get_saml_settings(cfg, request_data)+ saml_req = {+ 'https': 'on' if request_data.get('https') else 'off',+ 'http_host': request_data.get('http_host', ''),+ 'script_name': request_data.get('script_name', ''),+ }+ auth = OneLogin_Saml2_Auth(saml_req, settings)+ metadata = auth.get_settings().get_sp_metadata()+ from flask import Response+ return Response(metadata, mimetype='application/xml')+ except Exception as e:+ return jsonify({'error': str(e)}), 500+++# ------------------------------------------------------------------+# Authenticated endpoints (account linking)+# ------------------------------------------------------------------++@sso_bp.route('/identities', methods=['GET'])+@jwt_required()+def list_identities():+ """Current user's linked OAuth identities."""+ user_id = get_jwt_identity()+ identities = OAuthIdentity.query.filter_by(user_id=user_id).all()+ return jsonify({'identities': [i.to_dict() for i in identities]}), 200+++@sso_bp.route('/link/<provider>', methods=['POST'])+@jwt_required()+def link_provider(provider):+ """Link an OAuth identity to the current user."""+ if provider not in VALID_PROVIDERS:+ return jsonify({'error': f'Invalid provider: {provider}'}), 400++ user_id = get_jwt_identity()+ data = request.get_json() or {}+ code = data.get('code', '')+ state = data.get('state', '')+ redirect_uri = data.get('redirect_uri', '')++ if not code or not state:+ return jsonify({'error': 'code and state are required'}), 400++ try:+ profile = sso_service.handle_oauth_callback(provider, code, state, redirect_uri)+ except Exception as e:+ return jsonify({'error': str(e)}), 400++ # Check if this identity is already linked to another user+ existing = OAuthIdentity.query.filter_by(+ provider=provider,+ provider_user_id=profile['provider_user_id'],+ ).first()+ if existing:+ if existing.user_id == user_id:+ return jsonify({'error': 'This identity is already linked to your account'}), 409+ return jsonify({'error': 'This identity is already linked to another account'}), 409++ identity = sso_service.link_identity(user_id, provider, profile, profile.get('_tokens', {}))+ return jsonify({'identity': identity.to_dict()}), 201+++@sso_bp.route('/link/<provider>', methods=['DELETE'])+@jwt_required()+def unlink_provider(provider):+ """Unlink an OAuth identity."""+ if provider not in VALID_PROVIDERS:+ return jsonify({'error': f'Invalid provider: {provider}'}), 400++ user_id = get_jwt_identity()+ try:+ sso_service.unlink_identity(user_id, provider)+ return jsonify({'message': f'{provider} identity unlinked'}), 200+ except ValueError as e:+ return jsonify({'error': str(e)}), 400+++# ------------------------------------------------------------------+# Admin endpoints (SSO configuration)+# ------------------------------------------------------------------++@sso_bp.route('/admin/config', methods=['GET'])+@jwt_required()+def get_sso_config():+ """All SSO settings (secrets redacted)."""+ user = User.query.get(get_jwt_identity())+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ config = {}+ for key in SettingsService.DEFAULT_SETTINGS:+ if not key.startswith('sso_'):+ continue+ val = SettingsService.get(key, SettingsService.DEFAULT_SETTINGS[key]['value'])+ # Redact secrets+ if 'secret' in key or 'cert' in key:+ if val and isinstance(val, str) and len(val) > 4:+ val = '****' + val[-4:]+ config[key] = val+ return jsonify({'config': config}), 200+++@sso_bp.route('/admin/config/<provider>', methods=['PUT'])+@jwt_required()+def update_provider_config(provider):+ """Update a provider's SSO config."""+ user = User.query.get(get_jwt_identity())+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ if provider not in VALID_PROVIDERS:+ return jsonify({'error': f'Invalid provider: {provider}'}), 400++ data = request.get_json() or {}+ prefix = f'sso_{provider}_'+ updated = []++ for key, value in data.items():+ full_key = f'{prefix}{key}'+ if full_key not in SettingsService.DEFAULT_SETTINGS:+ continue+ # Skip unchanged redacted secrets+ if ('secret' in key or 'cert' in key) and isinstance(value, str) and value.startswith('****'):+ continue+ SettingsService.set(full_key, value, user_id=user.id)+ updated.append(key)++ AuditLog.log(+ action=AuditLog.ACTION_SETTINGS_UPDATE,+ user_id=user.id,+ details={'sso_provider': provider, 'updated_fields': updated},+ )+ db.session.commit()+ return jsonify({'message': f'{provider} SSO config updated', 'updated': updated}), 200+++@sso_bp.route('/admin/test/<provider>', methods=['POST'])+@jwt_required()+def test_provider(provider):+ """Test provider connectivity."""+ user = User.query.get(get_jwt_identity())+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ result = sso_service.test_provider_connectivity(provider)+ return jsonify(result), 200 if result['ok'] else 400+++@sso_bp.route('/admin/general', methods=['PUT'])+@jwt_required()+def update_general_settings():+ """Update general SSO settings (auto_provision, force_sso, etc.)."""+ user = User.query.get(get_jwt_identity())+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json() or {}+ general_keys = ['sso_auto_provision', 'sso_default_role', 'sso_force_sso', 'sso_allowed_domains']+ updated = []++ for key in general_keys:+ if key in data:+ SettingsService.set(key, data[key], user_id=user.id)+ updated.append(key)++ AuditLog.log(+ action=AuditLog.ACTION_SETTINGS_UPDATE,+ user_id=user.id,+ details={'sso_general': updated},+ )+ db.session.commit()+ return jsonify({'message': 'SSO general settings updated', 'updated': updated}), 200+++# ------------------------------------------------------------------+# Helper+# ------------------------------------------------------------------++def _complete_sso_login(user, provider, is_new):+ """Issue JWT or trigger 2FA for an SSO-authenticated user."""+ # Check 2FA+ if user.totp_enabled:+ temp_token = create_access_token(+ identity=user.id,+ additional_claims={'2fa_pending': True},+ expires_delta=False,+ )+ return jsonify({+ 'requires_2fa': True,+ 'temp_token': temp_token,+ 'message': 'Two-factor authentication required',+ }), 200++ user.last_login_at = datetime.utcnow()+ user.reset_failed_login()+ db.session.commit()++ AuditService.log_login(user.id, success=True, details={'provider': provider, 'is_new': is_new})+ db.session.commit()++ access_token = create_access_token(identity=user.id)+ refresh_token = create_refresh_token(identity=user.id)++ return jsonify({+ 'user': user.to_dict(),+ 'access_token': access_token,+ 'refresh_token': refresh_token,+ 'is_new_user': is_new,+ }), 200diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex c3985ad1..1458324a 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -16,6 +16,7 @@ from app.models.environment_activity import EnvironmentActivityfrom app.models.promotion_job import PromotionJobfrom app.models.sanitization_profile import SanitizationProfilefrom app.models.email_account import EmailAccount+from app.models.oauth_identity import OAuthIdentity__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',@@ -23,5 +24,6 @@ __all__ = ['MetricsHistory', 'Workflow', 'GitWebhook', 'WebhookLog', 'GitDeployment','Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'SecurityAlert','WordPressSite', 'DatabaseSnapshot', 'SyncJob',- 'EnvironmentActivity', 'PromotionJob', 'SanitizationProfile', 'EmailAccount'+ 'EnvironmentActivity', 'PromotionJob', 'SanitizationProfile', 'EmailAccount',+ 'OAuthIdentity']diff --git a/backend/app/models/audit_log.py b/backend/app/models/audit_log.pyindex b6dc0ab9..b5b65757 100644--- a/backend/app/models/audit_log.py+++ b/backend/app/models/audit_log.py@@ -39,6 +39,11 @@ class AuditLog(db.Model):ACTION_DEPLOY = 'app.deploy'ACTION_BACKUP_CREATE = 'backup.create'ACTION_BACKUP_RESTORE = 'backup.restore'+ ACTION_SSO_LOGIN = 'sso.login'+ ACTION_SSO_LOGIN_FAILED = 'sso.login_failed'+ ACTION_SSO_PROVISION = 'sso.provision'+ ACTION_SSO_LINK = 'sso.link'+ ACTION_SSO_UNLINK = 'sso.unlink'def get_details(self):"""Return parsed details JSON."""diff --git a/backend/app/models/oauth_identity.py b/backend/app/models/oauth_identity.pynew file mode 100644index 00000000..a27bbb7c--- /dev/null+++ b/backend/app/models/oauth_identity.py@@ -0,0 +1,38 @@+from datetime import datetime+from app import db+++class OAuthIdentity(db.Model):+ """Links an external OAuth/SAML identity to a local user."""+ __tablename__ = 'oauth_identities'+ __table_args__ = (+ db.UniqueConstraint('provider', 'provider_user_id', name='uq_provider_identity'),+ )++ id = db.Column(db.Integer, primary_key=True)+ user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, index=True)+ provider = db.Column(db.String(50), nullable=False) # google, github, oidc, saml+ provider_user_id = db.Column(db.String(256), nullable=False)+ provider_email = db.Column(db.String(256), nullable=True)+ provider_display_name = db.Column(db.String(256), nullable=True)+ access_token_encrypted = db.Column(db.Text, nullable=True)+ refresh_token_encrypted = db.Column(db.Text, nullable=True)+ token_expires_at = db.Column(db.DateTime, nullable=True)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)+ last_login_at = db.Column(db.DateTime, nullable=True)++ user = db.relationship('User', backref=db.backref('oauth_identities', lazy='dynamic'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'provider': self.provider,+ 'provider_email': self.provider_email,+ 'provider_display_name': self.provider_display_name,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'last_login_at': self.last_login_at.isoformat() if self.last_login_at else None,+ }++ def __repr__(self):+ return f'<OAuthIdentity {self.provider}:{self.provider_user_id}>'diff --git a/backend/app/models/user.py b/backend/app/models/user.pyindex e5762a94..1d598a9a 100644--- a/backend/app/models/user.py+++ b/backend/app/models/user.py@@ -16,7 +16,8 @@ class User(db.Model):id = db.Column(db.Integer, primary_key=True)email = db.Column(db.String(120), unique=True, nullable=False, index=True)username = db.Column(db.String(80), unique=True, nullable=False, index=True)- password_hash = db.Column(db.String(256), nullable=False)+ password_hash = db.Column(db.String(256), nullable=True)+ auth_provider = db.Column(db.String(50), default='local') # local, google, github, oidc, samlrole = db.Column(db.String(20), default='developer') # 'admin', 'developer', 'viewer'is_active = db.Column(db.Boolean, default=True)created_at = db.Column(db.DateTime, default=datetime.utcnow)@@ -69,6 +70,8 @@ class User(db.Model):self.password_hash = generate_password_hash(password)def check_password(self, password):+ if not self.password_hash:+ return Falsereturn check_password_hash(self.password_hash, password)@property@@ -90,6 +93,10 @@ class User(db.Model):"""Check if user has any of the specified roles."""return self.role in roles+ @property+ def has_password(self):+ return self.password_hash is not None+def to_dict(self):return {'id': self.id,@@ -98,6 +105,8 @@ class User(db.Model):'role': self.role,'is_active': self.is_active,'totp_enabled': self.totp_enabled,+ 'auth_provider': self.auth_provider or 'local',+ 'has_password': self.has_password,'created_at': self.created_at.isoformat(),'updated_at': self.updated_at.isoformat(),'last_login_at': self.last_login_at.isoformat() if self.last_login_at else None,diff --git a/backend/app/services/migration_service.py b/backend/app/services/migration_service.pynew file mode 100644index 00000000..1cbc94ad--- /dev/null+++ b/backend/app/services/migration_service.py@@ -0,0 +1,251 @@+"""Database migration service using Flask-Migrate (Alembic)."""++import os+import logging+import shutil+from datetime import datetime++from alembic import command+from alembic.config import Config as AlembicConfig+from alembic.script import ScriptDirectory+from alembic.migration import MigrationContext+from sqlalchemy import inspect as sa_inspect, text++logger = logging.getLogger(__name__)+++class MigrationService:+ """Handles database migration detection, backup, and execution."""++ _needs_migration = False+ _current_revision = None+ _head_revision = None+ _pending_migrations = []++ @classmethod+ def _get_alembic_config(cls, app):+ """Build an Alembic config pointing at the migrations directory."""+ migrations_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'migrations')+ cfg = AlembicConfig()+ cfg.set_main_option('script_location', migrations_dir)+ cfg.set_main_option('sqlalchemy.url', app.config['SQLALCHEMY_DATABASE_URI'])+ return cfg++ @classmethod+ def _fix_missing_columns(cls, db):+ """Add columns that may be missing from existing tables.++ Runs raw SQL before any ORM queries to prevent crashes when models+ reference columns that don't exist in the database yet.+ """+ inspector = sa_inspect(db.engine)+ existing_tables = inspector.get_table_names()++ if 'users' in existing_tables:+ cols = {c['name'] for c in inspector.get_columns('users')}+ if 'auth_provider' not in cols:+ logger.info('Adding missing column: users.auth_provider')+ with db.engine.begin() as conn:+ conn.execute(text(+ "ALTER TABLE users ADD COLUMN auth_provider VARCHAR(50) DEFAULT 'local'"+ ))++ @classmethod+ def check_and_prepare(cls, app):+ """Called on startup to detect migration state.++ Three scenarios:+ 1. Fresh install (no DB / no tables) -> upgrade head to create everything+ 2. Existing install (tables exist, no alembic_version) -> stamp baseline, then check+ 3. Normal state (alembic_version exists) -> compare current vs head+ """+ from app import db++ try:+ # Fix any missing columns before ORM queries can fail+ cls._fix_missing_columns(db)++ cfg = cls._get_alembic_config(app)+ script = ScriptDirectory.from_config(cfg)+ head = script.get_current_head()+ cls._head_revision = head++ inspector = sa_inspect(db.engine)+ existing_tables = inspector.get_table_names()+ has_alembic = 'alembic_version' in existing_tables++ # Count real application tables (exclude alembic_version)+ app_tables = [t for t in existing_tables if t != 'alembic_version']++ if not app_tables and not has_alembic:+ # Scenario 1: Fresh install — create everything via Alembic+ logger.info('Fresh install detected — running alembic upgrade head')+ with app.app_context():+ command.upgrade(cfg, 'head')+ cls._needs_migration = False+ cls._current_revision = head+ cls._pending_migrations = []+ return++ if app_tables and not has_alembic:+ # Scenario 2: Existing install upgrading to Alembic+ # Run upgrade so migrations can add missing columns to existing tables+ logger.info('Existing install detected — running alembic upgrade head')+ with app.app_context():+ command.upgrade(cfg, 'head')++ # Scenario 3 (or after stamping): Check current vs head+ with db.engine.connect() as conn:+ context = MigrationContext.configure(conn)+ current_heads = context.get_current_heads()+ cls._current_revision = current_heads[0] if current_heads else None++ if cls._current_revision != head:+ # Calculate pending migrations+ cls._pending_migrations = []+ for rev in script.walk_revisions():+ if cls._current_revision and rev.revision == cls._current_revision:+ break+ cls._pending_migrations.append({+ 'revision': rev.revision,+ 'description': rev.doc or '',+ 'down_revision': rev.down_revision,+ })+ cls._pending_migrations.reverse()+ cls._needs_migration = len(cls._pending_migrations) > 0+ if cls._needs_migration:+ logger.warning(+ f'Database migration needed: {len(cls._pending_migrations)} pending '+ f'(current={cls._current_revision}, head={head})'+ )+ else:+ cls._needs_migration = False+ cls._pending_migrations = []++ except Exception as e:+ logger.error(f'Migration check failed: {e}')+ # Don't block startup on migration check failure — fall back to no-migration state+ cls._needs_migration = False++ @classmethod+ def get_status(cls):+ """Return current migration status."""+ return {+ 'needs_migration': cls._needs_migration,+ 'current_revision': cls._current_revision,+ 'head_revision': cls._head_revision,+ 'pending_count': len(cls._pending_migrations),+ 'pending_migrations': cls._pending_migrations,+ }++ @classmethod+ def create_backup(cls, app):+ """Create a database backup before migration.++ SQLite: file copy. PostgreSQL: pg_dump.+ """+ db_url = app.config['SQLALCHEMY_DATABASE_URI']+ timestamp = datetime.utcnow().strftime('%Y%m%d_%H%M%S')++ try:+ if db_url.startswith('sqlite'):+ # Extract file path from sqlite:///path or sqlite:////path+ db_path = db_url.replace('sqlite:///', '')+ if not os.path.isabs(db_path):+ db_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), db_path)++ if not os.path.exists(db_path):+ return {'success': False, 'error': 'Database file not found'}++ backup_dir = os.path.join(os.path.dirname(db_path), 'backups')+ os.makedirs(backup_dir, exist_ok=True)+ backup_name = f'serverkit_pre_migration_{timestamp}.db'+ backup_path = os.path.join(backup_dir, backup_name)++ shutil.copy2(db_path, backup_path)+ logger.info(f'Database backup created: {backup_path}')+ return {'success': True, 'path': backup_path}++ elif 'postgresql' in db_url:+ import subprocess+ backup_dir = '/var/serverkit/backups/db'+ os.makedirs(backup_dir, exist_ok=True)+ backup_name = f'serverkit_pre_migration_{timestamp}.sql'+ backup_path = os.path.join(backup_dir, backup_name)++ result = subprocess.run(+ ['pg_dump', db_url, '-f', backup_path],+ capture_output=True, text=True, timeout=300+ )+ if result.returncode != 0:+ return {'success': False, 'error': result.stderr}++ logger.info(f'Database backup created: {backup_path}')+ return {'success': True, 'path': backup_path}++ else:+ return {'success': False, 'error': f'Unsupported database type'}++ except Exception as e:+ logger.error(f'Backup failed: {e}')+ return {'success': False, 'error': str(e)}++ @classmethod+ def apply_migrations(cls, app):+ """Run all pending Alembic migrations."""+ try:+ cfg = cls._get_alembic_config(app)++ with app.app_context():+ command.upgrade(cfg, 'head')++ # Update internal state+ from app import db+ with db.engine.connect() as conn:+ context = MigrationContext.configure(conn)+ current_heads = context.get_current_heads()+ cls._current_revision = current_heads[0] if current_heads else None++ cls._needs_migration = False+ cls._pending_migrations = []++ # Record in SystemSettings+ try:+ from app.models import SystemSettings+ from app import db as _db+ SystemSettings.set('schema_version', cls._current_revision)+ SystemSettings.set('last_migration_at', datetime.utcnow().isoformat())+ _db.session.commit()+ except Exception as e:+ logger.warning(f'Failed to record migration in settings: {e}')++ logger.info(f'Migrations applied successfully (now at {cls._current_revision})')+ return {'success': True, 'revision': cls._current_revision}++ except Exception as e:+ logger.error(f'Migration failed: {e}')+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_migration_history(cls, app):+ """Return list of all Alembic revisions with descriptions."""+ try:+ cfg = cls._get_alembic_config(app)+ script = ScriptDirectory.from_config(cfg)++ revisions = []+ for rev in script.walk_revisions():+ revisions.append({+ 'revision': rev.revision,+ 'down_revision': rev.down_revision,+ 'description': rev.doc or '',+ 'is_current': rev.revision == cls._current_revision,+ 'is_head': rev.revision == cls._head_revision,+ })++ revisions.reverse()+ return revisions++ except Exception as e:+ logger.error(f'Failed to get migration history: {e}')+ return []diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.pyindex 7810d783..69db1d70 100644--- a/backend/app/services/settings_service.py+++ b/backend/app/services/settings_service.py@@ -37,7 +37,28 @@ class SettingsService:'value': False,'type': 'boolean','description': 'Enable developer mode for debugging tools and icon reference'- }+ },+ # SSO / OAuth settings+ 'sso_google_enabled': {'value': False, 'type': 'boolean', 'description': 'Enable Google OAuth login'},+ 'sso_google_client_id': {'value': '', 'type': 'string', 'description': 'Google OAuth client ID'},+ 'sso_google_client_secret': {'value': '', 'type': 'string', 'description': 'Google OAuth client secret'},+ 'sso_github_enabled': {'value': False, 'type': 'boolean', 'description': 'Enable GitHub OAuth login'},+ 'sso_github_client_id': {'value': '', 'type': 'string', 'description': 'GitHub OAuth client ID'},+ 'sso_github_client_secret': {'value': '', 'type': 'string', 'description': 'GitHub OAuth client secret'},+ 'sso_oidc_enabled': {'value': False, 'type': 'boolean', 'description': 'Enable generic OIDC login'},+ 'sso_oidc_provider_name': {'value': '', 'type': 'string', 'description': 'OIDC provider display name'},+ 'sso_oidc_client_id': {'value': '', 'type': 'string', 'description': 'OIDC client ID'},+ 'sso_oidc_client_secret': {'value': '', 'type': 'string', 'description': 'OIDC client secret'},+ 'sso_oidc_discovery_url': {'value': '', 'type': 'string', 'description': 'OIDC discovery URL'},+ 'sso_saml_enabled': {'value': False, 'type': 'boolean', 'description': 'Enable SAML 2.0 login'},+ 'sso_saml_entity_id': {'value': '', 'type': 'string', 'description': 'SAML SP entity ID'},+ 'sso_saml_idp_metadata_url': {'value': '', 'type': 'string', 'description': 'SAML IdP metadata URL'},+ 'sso_saml_idp_sso_url': {'value': '', 'type': 'string', 'description': 'SAML IdP SSO URL'},+ 'sso_saml_idp_cert': {'value': '', 'type': 'string', 'description': 'SAML IdP certificate (PEM)'},+ 'sso_auto_provision': {'value': True, 'type': 'boolean', 'description': 'Auto-create users on first SSO login'},+ 'sso_default_role': {'value': 'developer', 'type': 'string', 'description': 'Default role for SSO-provisioned users'},+ 'sso_force_sso': {'value': False, 'type': 'boolean', 'description': 'Disable password login (SSO only)'},+ 'sso_allowed_domains': {'value': [], 'type': 'json', 'description': 'Restrict SSO to these email domains'},}@staticmethoddiff --git a/backend/app/services/sso_service.py b/backend/app/services/sso_service.pynew file mode 100644index 00000000..2022bc79--- /dev/null+++ b/backend/app/services/sso_service.py@@ -0,0 +1,503 @@+"""SSO / OAuth 2.0 / SAML service — handles external identity authentication."""+import hashlib+import logging+import secrets+from datetime import datetime++from authlib.integrations.requests_client import OAuth2Session+from cryptography.fernet import Fernet+from flask import current_app, session+import base64+import requests as http_requests++from app import db+from app.models import User, AuditLog+from app.models.oauth_identity import OAuthIdentity+from app.services.settings_service import SettingsService++logger = logging.getLogger(__name__)++# Built-in provider endpoint configs+PROVIDER_ENDPOINTS = {+ 'google': {+ 'authorize_url': 'https://accounts.google.com/o/oauth2/v2/auth',+ 'token_url': 'https://oauth2.googleapis.com/token',+ 'userinfo_url': 'https://openidconnect.googleapis.com/v1/userinfo',+ 'scopes': ['openid', 'email', 'profile'],+ },+ 'github': {+ 'authorize_url': 'https://github.com/login/oauth/authorize',+ 'token_url': 'https://github.com/login/oauth/access_token',+ 'userinfo_url': 'https://api.github.com/user',+ 'emails_url': 'https://api.github.com/user/emails',+ 'scopes': ['read:user', 'user:email'],+ },+}+++def _get_fernet():+ """Derive a Fernet key from SECRET_KEY."""+ key_bytes = current_app.config['SECRET_KEY'].encode('utf-8')+ digest = hashlib.sha256(key_bytes).digest()+ return Fernet(base64.urlsafe_b64encode(digest))+++def encrypt_token(token):+ if not token:+ return None+ return _get_fernet().encrypt(token.encode('utf-8')).decode('utf-8')+++def decrypt_token(encrypted):+ if not encrypted:+ return None+ try:+ return _get_fernet().decrypt(encrypted.encode('utf-8')).decode('utf-8')+ except Exception:+ return None+++def get_enabled_providers():+ """Return list of enabled SSO providers for the login page."""+ providers = []+ if SettingsService.get('sso_google_enabled', False):+ providers.append({'id': 'google', 'name': 'Google'})+ if SettingsService.get('sso_github_enabled', False):+ providers.append({'id': 'github', 'name': 'GitHub'})+ if SettingsService.get('sso_oidc_enabled', False):+ name = SettingsService.get('sso_oidc_provider_name', '') or 'OIDC'+ providers.append({'id': 'oidc', 'name': name})+ if SettingsService.get('sso_saml_enabled', False):+ providers.append({'id': 'saml', 'name': 'SAML'})+ return providers+++def is_password_login_allowed():+ return not SettingsService.get('sso_force_sso', False)+++def get_provider_config(provider):+ """Full config for a provider (internal use — includes secrets)."""+ prefix = f'sso_{provider}_'+ keys = [k for k in SettingsService.DEFAULT_SETTINGS if k.startswith(prefix)]+ cfg = {}+ for k in keys:+ short = k[len(prefix):]+ cfg[short] = SettingsService.get(k, SettingsService.DEFAULT_SETTINGS[k]['value'])+ return cfg+++# ------------------------------------------------------------------+# OAuth flow helpers+# ------------------------------------------------------------------++def generate_auth_url(provider, redirect_uri):+ """Build the OAuth authorize URL with PKCE, return (auth_url, state)."""+ cfg = get_provider_config(provider)++ if provider in ('google', 'github'):+ endpoints = PROVIDER_ENDPOINTS[provider]+ authorize_url = endpoints['authorize_url']+ scopes = endpoints['scopes']+ client_id = cfg.get('client_id', '')+ elif provider == 'oidc':+ discovery = _fetch_oidc_discovery(cfg.get('discovery_url', ''))+ authorize_url = discovery.get('authorization_endpoint', '')+ scopes = ['openid', 'email', 'profile']+ client_id = cfg.get('client_id', '')+ else:+ raise ValueError(f'OAuth authorize not supported for {provider}')++ state = secrets.token_urlsafe(32)+ code_verifier = secrets.token_urlsafe(64)+ code_challenge = base64.urlsafe_b64encode(+ hashlib.sha256(code_verifier.encode('ascii')).digest()+ ).rstrip(b'=').decode('ascii')++ # Store in server-side session+ session['sso_state'] = state+ session['sso_code_verifier'] = code_verifier+ session['sso_provider'] = provider++ params = {+ 'client_id': client_id,+ 'redirect_uri': redirect_uri,+ 'response_type': 'code',+ 'scope': ' '.join(scopes),+ 'state': state,+ 'code_challenge': code_challenge,+ 'code_challenge_method': 'S256',+ }++ if provider == 'google':+ params['access_type'] = 'offline'+ params['prompt'] = 'select_account'++ qs = '&'.join(f'{k}={v}' for k, v in params.items())+ return f'{authorize_url}?{qs}', state+++def handle_oauth_callback(provider, code, state, redirect_uri):+ """Exchange authorization code for tokens & fetch user profile."""+ # Validate state+ expected_state = session.pop('sso_state', None)+ code_verifier = session.pop('sso_code_verifier', None)+ if not expected_state or state != expected_state:+ raise ValueError('Invalid OAuth state — possible CSRF')++ cfg = get_provider_config(provider)++ if provider in ('google', 'github'):+ endpoints = PROVIDER_ENDPOINTS[provider]+ token_url = endpoints['token_url']+ userinfo_url = endpoints['userinfo_url']+ client_id = cfg.get('client_id', '')+ client_secret = cfg.get('client_secret', '')+ elif provider == 'oidc':+ discovery = _fetch_oidc_discovery(cfg.get('discovery_url', ''))+ token_url = discovery.get('token_endpoint', '')+ userinfo_url = discovery.get('userinfo_endpoint', '')+ client_id = cfg.get('client_id', '')+ client_secret = cfg.get('client_secret', '')+ else:+ raise ValueError(f'OAuth callback not supported for {provider}')++ # Exchange code for tokens+ oauth = OAuth2Session(+ client_id=client_id,+ client_secret=client_secret,+ code_challenge_method='S256',+ )+ token_resp = oauth.fetch_token(+ token_url,+ code=code,+ redirect_uri=redirect_uri,+ code_verifier=code_verifier,+ )++ access_token = token_resp.get('access_token', '')+ refresh_tok = token_resp.get('refresh_token')++ # Fetch user info+ headers = {'Authorization': f'Bearer {access_token}'}+ if provider == 'github':+ headers['Accept'] = 'application/vnd.github+json'++ resp = http_requests.get(userinfo_url, headers=headers, timeout=10)+ resp.raise_for_status()+ info = resp.json()++ profile = _normalize_profile(provider, info, headers)+ profile['_tokens'] = {+ 'access_token': access_token,+ 'refresh_token': refresh_tok,+ 'expires_at': token_resp.get('expires_at'),+ }+ return profile+++def _normalize_profile(provider, info, headers=None):+ """Convert provider-specific userinfo into a standard dict."""+ if provider == 'google':+ return {+ 'provider_user_id': info.get('sub', ''),+ 'email': info.get('email', ''),+ 'display_name': info.get('name', ''),+ }+ elif provider == 'github':+ email = info.get('email') or ''+ if not email and headers:+ # GitHub may not include email in profile; fetch from /user/emails+ try:+ emails_url = PROVIDER_ENDPOINTS['github']['emails_url']+ r = http_requests.get(emails_url, headers=headers, timeout=10)+ r.raise_for_status()+ for e in r.json():+ if e.get('primary') and e.get('verified'):+ email = e['email']+ break+ except Exception:+ pass+ return {+ 'provider_user_id': str(info.get('id', '')),+ 'email': email,+ 'display_name': info.get('name') or info.get('login', ''),+ }+ else:+ # Generic OIDC+ return {+ 'provider_user_id': info.get('sub', ''),+ 'email': info.get('email', ''),+ 'display_name': info.get('name', ''),+ }+++# ------------------------------------------------------------------+# SAML helpers+# ------------------------------------------------------------------++def get_saml_settings(provider_config, request_data):+ """Build python3-saml settings dict."""+ sp_entity_id = provider_config.get('entity_id', '') or request_data.get('sp_entity_id', '')+ acs_url = request_data.get('acs_url', '')++ return {+ 'strict': True,+ 'debug': False,+ 'sp': {+ 'entityId': sp_entity_id,+ 'assertionConsumerService': {+ 'url': acs_url,+ 'binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',+ },+ 'NameIDFormat': 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',+ },+ 'idp': {+ 'entityId': provider_config.get('entity_id', ''),+ 'singleSignOnService': {+ 'url': provider_config.get('idp_sso_url', ''),+ 'binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',+ },+ 'x509cert': provider_config.get('idp_cert', ''),+ },+ }+++def handle_saml_callback(saml_response_data, request_data):+ """Validate SAML response and extract user profile."""+ try:+ from onelogin.saml2.auth import OneLogin_Saml2_Auth+ except ImportError:+ raise RuntimeError('python3-saml is not installed')++ cfg = get_provider_config('saml')+ saml_settings = get_saml_settings(cfg, request_data)++ saml_req = {+ 'https': 'on' if request_data.get('https') else 'off',+ 'http_host': request_data.get('http_host', ''),+ 'script_name': request_data.get('script_name', ''),+ 'post_data': saml_response_data,+ }++ auth = OneLogin_Saml2_Auth(saml_req, saml_settings)+ auth.process_response()++ errors = auth.get_errors()+ if errors:+ raise ValueError(f'SAML validation failed: {", ".join(errors)}')++ if not auth.is_authenticated():+ raise ValueError('SAML authentication failed')++ attrs = auth.get_attributes()+ name_id = auth.get_nameid()++ return {+ 'provider_user_id': name_id,+ 'email': attrs.get('email', [name_id])[0] if attrs.get('email') else name_id,+ 'display_name': attrs.get('displayName', [''])[0] if attrs.get('displayName') else '',+ '_tokens': {},+ }+++# ------------------------------------------------------------------+# User linking / provisioning+# ------------------------------------------------------------------++def find_or_create_user(provider, profile):+ """+ 1. Check OAuthIdentity by (provider, provider_user_id) → return linked user+ 2. Check User by email → auto-link identity+ 3. Auto-provision if enabled+ Returns (user, is_new_user).+ """+ email = profile.get('email', '').lower().strip()++ # Enforce allowed domains+ allowed_domains = SettingsService.get('sso_allowed_domains', [])+ if allowed_domains and email:+ domain = email.split('@')[-1] if '@' in email else ''+ if domain not in allowed_domains:+ raise ValueError(f'Email domain @{domain} is not allowed for SSO login')++ # 1. Check existing identity link+ identity = OAuthIdentity.query.filter_by(+ provider=provider,+ provider_user_id=profile['provider_user_id'],+ ).first()++ if identity:+ user = identity.user+ if not user.is_active:+ raise ValueError('Account is deactivated')+ identity.last_login_at = datetime.utcnow()+ _update_identity_tokens(identity, profile.get('_tokens', {}))+ db.session.commit()+ return user, False++ # 2. Check existing user by email+ user = User.query.filter_by(email=email).first() if email else None+ if user:+ if not user.is_active:+ raise ValueError('Account is deactivated')+ link_identity(user.id, provider, profile, profile.get('_tokens', {}))+ return user, False++ # 3. Auto-provision+ if not SettingsService.get('sso_auto_provision', True):+ raise ValueError('No matching account found and auto-provisioning is disabled')++ if not email:+ raise ValueError('SSO provider did not return an email address')++ default_role = SettingsService.get('sso_default_role', 'developer')+ username = _generate_username(email, profile.get('display_name', ''))++ user = User(+ email=email,+ username=username,+ role=default_role,+ auth_provider=provider,+ )+ db.session.add(user)+ db.session.flush()++ link_identity(user.id, provider, profile, profile.get('_tokens', {}))++ AuditLog.log(+ action=AuditLog.ACTION_SSO_PROVISION,+ user_id=user.id,+ target_type='user',+ target_id=user.id,+ details={'provider': provider, 'email': email, 'role': default_role},+ )+ db.session.commit()+ return user, True+++def link_identity(user_id, provider, profile, tokens=None):+ """Create an OAuthIdentity record."""+ tokens = tokens or {}+ identity = OAuthIdentity(+ user_id=user_id,+ provider=provider,+ provider_user_id=profile['provider_user_id'],+ provider_email=profile.get('email'),+ provider_display_name=profile.get('display_name'),+ last_login_at=datetime.utcnow(),+ )+ _update_identity_tokens(identity, tokens)+ db.session.add(identity)++ AuditLog.log(+ action=AuditLog.ACTION_SSO_LINK,+ user_id=user_id,+ target_type='user',+ target_id=user_id,+ details={'provider': provider},+ )+ db.session.commit()+ return identity+++def unlink_identity(user_id, provider):+ """Remove an OAuth identity link (prevent if it's the only auth method)."""+ user = User.query.get(user_id)+ if not user:+ raise ValueError('User not found')++ identity = OAuthIdentity.query.filter_by(user_id=user_id, provider=provider).first()+ if not identity:+ raise ValueError(f'No {provider} identity linked')++ # Prevent unlinking if it's the only auth method+ identity_count = OAuthIdentity.query.filter_by(user_id=user_id).count()+ if not user.has_password and identity_count <= 1:+ raise ValueError('Cannot unlink the only authentication method. Set a password first.')++ db.session.delete(identity)+ AuditLog.log(+ action=AuditLog.ACTION_SSO_UNLINK,+ user_id=user_id,+ target_type='user',+ target_id=user_id,+ details={'provider': provider},+ )+ db.session.commit()+++# ------------------------------------------------------------------+# Internal helpers+# ------------------------------------------------------------------++def _update_identity_tokens(identity, tokens):+ if tokens.get('access_token'):+ identity.access_token_encrypted = encrypt_token(tokens['access_token'])+ if tokens.get('refresh_token'):+ identity.refresh_token_encrypted = encrypt_token(tokens['refresh_token'])+ if tokens.get('expires_at'):+ try:+ identity.token_expires_at = datetime.utcfromtimestamp(float(tokens['expires_at']))+ except (ValueError, TypeError):+ pass+++def _generate_username(email, display_name):+ """Generate a unique username from email or display name."""+ base = display_name.strip().lower().replace(' ', '_') if display_name else email.split('@')[0]+ # Remove non-alphanumeric except underscores+ base = ''.join(c for c in base if c.isalnum() or c == '_')[:60]+ if not base:+ base = 'user'++ username = base+ suffix = 1+ while User.query.filter_by(username=username).first():+ username = f'{base}_{suffix}'+ suffix += 1+ return username+++def _fetch_oidc_discovery(discovery_url):+ """Fetch and cache OIDC discovery document."""+ if not discovery_url:+ raise ValueError('OIDC discovery URL not configured')+ resp = http_requests.get(discovery_url, timeout=10)+ resp.raise_for_status()+ return resp.json()+++def test_provider_connectivity(provider):+ """Test that a provider's endpoints are reachable."""+ cfg = get_provider_config(provider)++ if provider == 'google':+ client_id = cfg.get('client_id', '')+ if not client_id:+ return {'ok': False, 'error': 'Client ID not configured'}+ # Google discovery is always available+ return {'ok': True, 'message': 'Google OAuth endpoints reachable'}+ elif provider == 'github':+ client_id = cfg.get('client_id', '')+ if not client_id:+ return {'ok': False, 'error': 'Client ID not configured'}+ return {'ok': True, 'message': 'GitHub OAuth endpoints reachable'}+ elif provider == 'oidc':+ try:+ discovery = _fetch_oidc_discovery(cfg.get('discovery_url', ''))+ if 'authorization_endpoint' in discovery:+ return {'ok': True, 'message': 'OIDC discovery successful'}+ return {'ok': False, 'error': 'Discovery document missing authorization_endpoint'}+ except Exception as e:+ return {'ok': False, 'error': str(e)}+ elif provider == 'saml':+ idp_sso_url = cfg.get('idp_sso_url', '')+ if not idp_sso_url:+ return {'ok': False, 'error': 'IdP SSO URL not configured'}+ idp_cert = cfg.get('idp_cert', '')+ if not idp_cert:+ return {'ok': False, 'error': 'IdP certificate not configured'}+ return {'ok': True, 'message': 'SAML configuration looks valid'}+ else:+ return {'ok': False, 'error': f'Unknown provider: {provider}'}diff --git a/backend/cli.py b/backend/cli.pyindex caa4a391..13deb2e2 100644--- a/backend/cli.py+++ b/backend/cli.py@@ -206,80 +206,102 @@ def generate_keys():@cli.command()def init_db():- """Initialize the database."""+ """Initialize the database using Alembic migrations."""app = create_app()with app.app_context():- db.create_all()- click.echo(click.style('Database initialized successfully!', fg='green'))+ from app.services.migration_service import MigrationService+ result = MigrationService.apply_migrations(app)+ if result['success']:+ click.echo(click.style(f'Database initialized successfully (revision: {result["revision"]})!', fg='green'))+ else:+ click.echo(click.style(f'Database initialization failed: {result["error"]}', fg='red'))+ sys.exit(1)@cli.command()-def migrate_db():- """Apply database migrations for missing columns."""+def db_status():+ """Show current database migration status."""app = create_app()with app.app_context():- from sqlalchemy import text, inspect-- inspector = inspect(db.engine)- existing_tables = inspector.get_table_names()-- # Define all expected columns per table- expected_columns = [- # applications table- ('applications', 'private_slug', 'VARCHAR(50)'),- ('applications', 'private_url_enabled', 'BOOLEAN DEFAULT 0'),- ('applications', 'environment_type', "VARCHAR(20) DEFAULT 'standalone'"),- ('applications', 'linked_app_id', 'INTEGER'),- ('applications', 'shared_config', 'TEXT'),- # wordpress_sites table- ('wordpress_sites', 'environment_type', "VARCHAR(20) DEFAULT 'standalone'"),- ('wordpress_sites', 'multidev_branch', 'VARCHAR(200)'),- ('wordpress_sites', 'is_locked', 'BOOLEAN DEFAULT 0'),- ('wordpress_sites', 'locked_by', 'VARCHAR(100)'),- ('wordpress_sites', 'locked_reason', 'VARCHAR(200)'),- ('wordpress_sites', 'lock_expires_at', 'DATETIME'),- ('wordpress_sites', 'compose_project_name', 'VARCHAR(100)'),- ('wordpress_sites', 'container_prefix', 'VARCHAR(100)'),- ('wordpress_sites', 'resource_limits', 'TEXT'),- ('wordpress_sites', 'basic_auth_enabled', 'BOOLEAN DEFAULT 0'),- ('wordpress_sites', 'basic_auth_user', 'VARCHAR(100)'),- ('wordpress_sites', 'basic_auth_password_hash', 'VARCHAR(200)'),- ('wordpress_sites', 'health_status', "VARCHAR(20) DEFAULT 'unknown'"),- ('wordpress_sites', 'last_health_check', 'DATETIME'),- ('wordpress_sites', 'disk_usage_bytes', 'BIGINT DEFAULT 0'),- ('wordpress_sites', 'disk_usage_updated_at', 'DATETIME'),- ('wordpress_sites', 'auto_sync_schedule', 'VARCHAR(100)'),- ('wordpress_sites', 'auto_sync_enabled', 'BOOLEAN DEFAULT 0'),- ]+ from app.services.migration_service import MigrationService+ status = MigrationService.get_status()++ click.echo(f"\nCurrent revision: {status['current_revision'] or 'none'}")+ click.echo(f"Head revision: {status['head_revision'] or 'none'}")+ click.echo(f"Pending: {status['pending_count']}")++ if status['pending_migrations']:+ click.echo(f"\nPending migrations:")+ for m in status['pending_migrations']:+ click.echo(f" - {m['revision']}: {m['description']}")+ else:+ click.echo(click.style('\nDatabase is up to date.', fg='green'))+ click.echo()- # Check which columns are missing- table_columns_cache = {}- migrations = []- for table, column, col_type in expected_columns:- if table not in existing_tables:- continue- if table not in table_columns_cache:- table_columns_cache[table] = [col['name'] for col in inspector.get_columns(table)]- if column not in table_columns_cache[table]:- migrations.append((table, column, col_type))[email protected]('--no-backup', is_flag=True, help='Skip creating a backup before migrating')+def db_migrate(no_backup):+ """Apply pending database migrations."""+ app = create_app()+ with app.app_context():+ from app.services.migration_service import MigrationService+ status = MigrationService.get_status()- if not migrations:+ if not status['needs_migration']:click.echo(click.style('Database is up to date. No migrations needed.', fg='green'))return- click.echo(f'Found {len(migrations)} migration(s) to apply...')+ click.echo(f'Found {status["pending_count"]} pending migration(s):')+ for m in status['pending_migrations']:+ click.echo(f' - {m["revision"]}: {m["description"]}')++ if not no_backup:+ click.echo('\nCreating backup...')+ backup = MigrationService.create_backup(app)+ if backup['success']:+ click.echo(click.style(f' Backup saved to: {backup["path"]}', fg='green'))+ else:+ click.echo(click.style(f' Backup failed: {backup["error"]}', fg='red'))+ if not click.confirm('Continue without backup?'):+ return++ click.echo('\nApplying migrations...')+ result = MigrationService.apply_migrations(app)+ if result['success']:+ click.echo(click.style(f'\nMigrations applied! Now at revision: {result["revision"]}', fg='green'))+ else:+ click.echo(click.style(f'\nMigration failed: {result["error"]}', fg='red'))+ sys.exit(1)- for table, column, col_type in migrations:- try:- sql = f'ALTER TABLE {table} ADD COLUMN {column} {col_type}'- db.session.execute(text(sql))- click.echo(click.style(f' ✓ Added column {table}.{column}', fg='green'))- except Exception as e:- click.echo(click.style(f' ✗ Failed to add {table}.{column}: {e}', fg='red'))- db.session.commit()- click.echo(click.style('\nMigrations completed!', fg='green'))+def db_history():+ """Show all database migration revisions."""+ app = create_app()+ with app.app_context():+ from app.services.migration_service import MigrationService+ history = MigrationService.get_migration_history(app)++ if not history:+ click.echo('No migration history found.')+ return++ click.echo(f"\n{'Revision':<20} {'Description':<50} {'Status'}")+ click.echo('-' * 80)++ for rev in history:+ status_parts = []+ if rev['is_current']:+ status_parts.append('CURRENT')+ if rev['is_head']:+ status_parts.append('HEAD')+ status = ', '.join(status_parts) if status_parts else ''++ desc = rev['description'][:48] if rev['description'] else ''+ click.echo(f"{rev['revision']:<20} {desc:<50} {status}")++ click.echo()@cli.command()@@ -542,11 +564,15 @@ def factory_reset():except Exception as e:click.echo(click.style(f'✗ Failed to clear template cache: {e}', fg='red'))- # 7. Drop and recreate database+ # 7. Drop and recreate database via Alembictry:db.drop_all()- db.create_all()- click.echo(click.style('✓ Reset database', fg='green'))+ from app.services.migration_service import MigrationService+ result = MigrationService.apply_migrations(app)+ if result['success']:+ click.echo(click.style('✓ Reset database', fg='green'))+ else:+ click.echo(click.style(f'✗ Migration after reset failed: {result["error"]}', fg='red'))except Exception as e:click.echo(click.style(f'✗ Failed to reset database: {e}', fg='red'))diff --git a/backend/migrations/alembic.ini b/backend/migrations/alembic.ininew file mode 100644index 00000000..5f8ee17e--- /dev/null+++ b/backend/migrations/alembic.ini@@ -0,0 +1,9 @@+# A generic, single database configuration.++[alembic]+# template used to generate migration files+# file_template = %%(rev)s_%%(slug)s++# set to 'true' to run the environment during+# the 'revision' command, regardless of autogenerate+# revision_environment = falsediff --git a/backend/migrations/env.py b/backend/migrations/env.pynew file mode 100644index 00000000..8390ac23--- /dev/null+++ b/backend/migrations/env.py@@ -0,0 +1,100 @@+import logging+from logging.config import fileConfig++from flask import current_app+from alembic import context++# Alembic Config object+config = context.config++# Set up loggers+if config.config_file_name is not None:+ fileConfig(config.config_file_name)+logger = logging.getLogger('alembic.env')+++def get_engine():+ try:+ # Flask-Migrate provides the engine via current_app+ return current_app.extensions['migrate'].db.get_engine()+ except (TypeError, AttributeError):+ # Fallback for CLI usage outside Flask context+ return current_app.extensions['migrate'].db.engine+++def get_engine_url():+ try:+ return get_engine().url.render_as_string(hide_password=False).replace('%', '%%')+ except AttributeError:+ return str(get_engine().url).replace('%', '%%')+++# Import all models so Alembic can detect them+def import_models():+ # noinspection PyUnresolvedReferences+ from app.models import ( # noqa: F401+ User, Application, Domain, EnvironmentVariable, EnvironmentVariableHistory,+ NotificationPreferences, Deployment, DeploymentDiff, SystemSettings, AuditLog,+ MetricsHistory, Workflow, GitWebhook, WebhookLog, GitDeployment,+ Server, ServerGroup, ServerMetrics, ServerCommand, AgentSession, SecurityAlert,+ WordPressSite, DatabaseSnapshot, SyncJob,+ EnvironmentActivity, PromotionJob, SanitizationProfile, EmailAccount,+ OAuthIdentity+ )+++config.set_main_option('sqlalchemy.url', get_engine_url())+target_db = current_app.extensions['migrate'].db+++def get_metadata():+ if hasattr(target_db, 'metadatas'):+ return target_db.metadatas[None]+ return target_db.metadata+++def run_migrations_offline():+ """Run migrations in 'offline' mode."""+ url = config.get_main_option("sqlalchemy.url")+ context.configure(+ url=url,+ target_metadata=get_metadata(),+ literal_binds=True,+ )++ import_models()++ with context.begin_transaction():+ context.run_migrations()+++def run_migrations_online():+ """Run migrations in 'online' mode."""++ def process_revision_directives(context, revision, directives):+ if getattr(config.cmd_opts, 'autogenerate', False):+ script = directives[0]+ if script.upgrade_ops.is_empty():+ directives[:] = []+ logger.info('No changes in schema detected.')++ connectable = get_engine()++ import_models()++ with connectable.connect() as connection:+ context.configure(+ connection=connection,+ target_metadata=get_metadata(),+ process_revision_directives=process_revision_directives,+ render_as_batch=True, # Required for SQLite ALTER TABLE support+ )++ with context.begin_transaction():+ context.run_migrations()+++if context.is_offline_mode():+ run_migrations_offline()+else:+ run_migrations_online()diff --git a/backend/migrations/script.py.mako b/backend/migrations/script.py.makonew file mode 100644index 00000000..2c015630--- /dev/null+++ b/backend/migrations/script.py.mako@@ -0,0 +1,24 @@+"""${message}++Revision ID: ${up_revision}+Revises: ${down_revision | comma,n}+Create Date: ${create_date}++"""+from alembic import op+import sqlalchemy as sa+${imports if imports else ""}++# revision identifiers, used by Alembic.+revision = ${repr(up_revision)}+down_revision = ${repr(down_revision)}+branch_labels = ${repr(branch_labels)}+depends_on = ${repr(depends_on)}+++def upgrade():+ ${upgrades if upgrades else "pass"}+++def downgrade():+ ${downgrades if downgrades else "pass"}diff --git a/backend/migrations/versions/001_baseline.py b/backend/migrations/versions/001_baseline.pynew file mode 100644index 00000000..b7516333--- /dev/null+++ b/backend/migrations/versions/001_baseline.py@@ -0,0 +1,601 @@+"""Baseline migration capturing full schema.++Revision ID: 001_baseline+Revises:+Create Date: 2026-03-04++For fresh installs: creates all tables from scratch.+For existing DBs: acts as a stamp point (tables already exist).+"""+from alembic import op+import sqlalchemy as sa++revision = '001_baseline'+down_revision = None+branch_labels = None+depends_on = None+++def upgrade():+ # Use batch mode and check if tables already exist to support both+ # fresh installs and existing databases being stamped.+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing_tables = inspector.get_table_names()++ if 'users' not in existing_tables:+ op.create_table('users',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('email', sa.String(120), unique=True, nullable=False, index=True),+ sa.Column('username', sa.String(80), unique=True, nullable=False, index=True),+ sa.Column('password_hash', sa.String(256), nullable=True),+ sa.Column('auth_provider', sa.String(50), server_default='local'),+ sa.Column('role', sa.String(20), server_default='developer'),+ sa.Column('is_active', sa.Boolean(), server_default=sa.text('1')),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('last_login_at', sa.DateTime(), nullable=True),+ sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),+ sa.Column('failed_login_count', sa.Integer(), server_default='0'),+ sa.Column('locked_until', sa.DateTime(), nullable=True),+ sa.Column('totp_secret', sa.String(32), nullable=True),+ sa.Column('totp_enabled', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('backup_codes', sa.Text(), nullable=True),+ sa.Column('totp_confirmed_at', sa.DateTime(), nullable=True),+ )+ else:+ # Add columns that may be missing in existing installs+ existing_cols = {c['name'] for c in inspector.get_columns('users')}+ if 'auth_provider' not in existing_cols:+ with op.batch_alter_table('users') as batch_op:+ batch_op.add_column(sa.Column('auth_provider', sa.String(50), server_default='local'))++ if 'applications' not in existing_tables:+ op.create_table('applications',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('name', sa.String(100), nullable=False),+ sa.Column('app_type', sa.String(50), nullable=False),+ sa.Column('status', sa.String(20), server_default='stopped'),+ sa.Column('php_version', sa.String(10), nullable=True),+ sa.Column('python_version', sa.String(10), nullable=True),+ sa.Column('port', sa.Integer(), nullable=True),+ sa.Column('root_path', sa.String(500), nullable=True),+ sa.Column('docker_image', sa.String(200), nullable=True),+ sa.Column('container_id', sa.String(100), nullable=True),+ sa.Column('private_slug', sa.String(50), unique=True, nullable=True, index=True),+ sa.Column('private_url_enabled', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('environment_type', sa.String(20), server_default='standalone'),+ sa.Column('linked_app_id', sa.Integer(), sa.ForeignKey('applications.id'), nullable=True),+ sa.Column('shared_config', sa.Text(), nullable=True),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('last_deployed_at', sa.DateTime(), nullable=True),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),+ )++ if 'domains' not in existing_tables:+ op.create_table('domains',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('name', sa.String(255), unique=True, nullable=False, index=True),+ sa.Column('is_primary', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('ssl_enabled', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('ssl_certificate_path', sa.String(500), nullable=True),+ sa.Column('ssl_key_path', sa.String(500), nullable=True),+ sa.Column('ssl_expires_at', sa.DateTime(), nullable=True),+ sa.Column('ssl_auto_renew', sa.Boolean(), server_default=sa.text('1')),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('application_id', sa.Integer(), sa.ForeignKey('applications.id'), nullable=False),+ )++ if 'environment_variables' not in existing_tables:+ op.create_table('environment_variables',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('application_id', sa.Integer(), sa.ForeignKey('applications.id'), nullable=False),+ sa.Column('key', sa.String(255), nullable=False),+ sa.Column('encrypted_value', sa.Text(), nullable=False),+ sa.Column('is_secret', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('description', sa.String(500), nullable=True),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),+ sa.UniqueConstraint('application_id', 'key', name='unique_app_env_key'),+ )++ if 'environment_variable_history' not in existing_tables:+ op.create_table('environment_variable_history',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('env_variable_id', sa.Integer(), nullable=False),+ sa.Column('application_id', sa.Integer(), sa.ForeignKey('applications.id'), nullable=False),+ sa.Column('key', sa.String(255), nullable=False),+ sa.Column('action', sa.String(20), nullable=False),+ sa.Column('old_value_hash', sa.String(64), nullable=True),+ sa.Column('new_value_hash', sa.String(64), nullable=True),+ sa.Column('changed_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),+ sa.Column('changed_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'notification_preferences' not in existing_tables:+ op.create_table('notification_preferences',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), unique=True, nullable=False),+ sa.Column('enabled', sa.Boolean(), server_default=sa.text('1')),+ sa.Column('channels', sa.Text(), server_default='["email"]'),+ sa.Column('severities', sa.Text(), server_default='["critical", "warning"]'),+ sa.Column('email', sa.String(255), nullable=True),+ sa.Column('discord_webhook', sa.String(512), nullable=True),+ sa.Column('telegram_chat_id', sa.String(64), nullable=True),+ sa.Column('categories', sa.Text(), server_default='{"system": true, "security": true, "backups": true, "apps": true}'),+ sa.Column('quiet_hours_enabled', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('quiet_hours_start', sa.String(5), server_default='22:00'),+ sa.Column('quiet_hours_end', sa.String(5), server_default='08:00'),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'deployments' not in existing_tables:+ op.create_table('deployments',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('app_id', sa.Integer(), sa.ForeignKey('applications.id'), nullable=False),+ sa.Column('version', sa.Integer(), nullable=False),+ sa.Column('version_tag', sa.String(100), nullable=True),+ sa.Column('status', sa.String(20), server_default='pending'),+ sa.Column('build_method', sa.String(20), nullable=True),+ sa.Column('image_tag', sa.String(255), nullable=True),+ sa.Column('commit_hash', sa.String(40), nullable=True),+ sa.Column('commit_message', sa.Text(), nullable=True),+ sa.Column('container_id', sa.String(100), nullable=True),+ sa.Column('deployed_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),+ sa.Column('deploy_trigger', sa.String(20), server_default='manual'),+ sa.Column('build_log_path', sa.String(500), nullable=True),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('build_started_at', sa.DateTime(), nullable=True),+ sa.Column('build_completed_at', sa.DateTime(), nullable=True),+ sa.Column('deploy_started_at', sa.DateTime(), nullable=True),+ sa.Column('deploy_completed_at', sa.DateTime(), nullable=True),+ sa.Column('error_message', sa.Text(), nullable=True),+ sa.Column('extra_data', sa.Text(), server_default='{}'),+ )++ if 'deployment_diffs' not in existing_tables:+ op.create_table('deployment_diffs',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('deployment_id', sa.Integer(), sa.ForeignKey('deployments.id'), nullable=False),+ sa.Column('previous_deployment_id', sa.Integer(), sa.ForeignKey('deployments.id'), nullable=True),+ sa.Column('files_added', sa.Text(), server_default='[]'),+ sa.Column('files_removed', sa.Text(), server_default='[]'),+ sa.Column('files_modified', sa.Text(), server_default='[]'),+ sa.Column('additions', sa.Integer(), server_default='0'),+ sa.Column('deletions', sa.Integer(), server_default='0'),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'system_settings' not in existing_tables:+ op.create_table('system_settings',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('key', sa.String(100), unique=True, nullable=False, index=True),+ sa.Column('value', sa.Text(), nullable=True),+ sa.Column('value_type', sa.String(20), server_default='string'),+ sa.Column('description', sa.String(500), nullable=True),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),+ )++ if 'audit_logs' not in existing_tables:+ op.create_table('audit_logs',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('action', sa.String(100), nullable=False, index=True),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),+ sa.Column('target_type', sa.String(50), nullable=True),+ sa.Column('target_id', sa.Integer(), nullable=True),+ sa.Column('details', sa.Text(), nullable=True),+ sa.Column('ip_address', sa.String(45), nullable=True),+ sa.Column('user_agent', sa.String(500), nullable=True),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now(), index=True),+ )++ if 'metrics_history' not in existing_tables:+ op.create_table('metrics_history',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('timestamp', sa.DateTime(), nullable=False, index=True),+ sa.Column('level', sa.String(10), nullable=False, server_default='minute', index=True),+ sa.Column('cpu_percent', sa.Float(), nullable=False),+ sa.Column('cpu_percent_min', sa.Float(), nullable=True),+ sa.Column('cpu_percent_max', sa.Float(), nullable=True),+ sa.Column('memory_percent', sa.Float(), nullable=False),+ sa.Column('memory_used_bytes', sa.BigInteger(), nullable=False),+ sa.Column('memory_total_bytes', sa.BigInteger(), nullable=False),+ sa.Column('disk_percent', sa.Float(), nullable=False),+ sa.Column('disk_used_bytes', sa.BigInteger(), nullable=False),+ sa.Column('disk_total_bytes', sa.BigInteger(), nullable=False),+ sa.Column('load_1m', sa.Float(), nullable=True),+ sa.Column('load_5m', sa.Float(), nullable=True),+ sa.Column('load_15m', sa.Float(), nullable=True),+ sa.Column('sample_count', sa.Integer(), server_default='1'),+ )+ op.create_index('idx_metrics_level_timestamp', 'metrics_history', ['level', 'timestamp'])++ if 'workflows' not in existing_tables:+ op.create_table('workflows',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('name', sa.String(100), nullable=False),+ sa.Column('description', sa.Text(), nullable=True),+ sa.Column('nodes', sa.Text(), nullable=True),+ sa.Column('edges', sa.Text(), nullable=True),+ sa.Column('viewport', sa.Text(), nullable=True),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),+ )++ if 'git_webhooks' not in existing_tables:+ op.create_table('git_webhooks',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('name', sa.String(100), nullable=False),+ sa.Column('source', sa.String(50), nullable=False),+ sa.Column('source_repo_url', sa.String(500), nullable=False),+ sa.Column('source_branch', sa.String(100), server_default='main'),+ sa.Column('local_repo_name', sa.String(200), nullable=True),+ sa.Column('secret', sa.String(100), nullable=False),+ sa.Column('webhook_token', sa.String(50), nullable=False, unique=True),+ sa.Column('sync_direction', sa.String(20), server_default='pull'),+ sa.Column('auto_sync', sa.Boolean(), server_default=sa.text('1')),+ sa.Column('app_id', sa.Integer(), sa.ForeignKey('applications.id'), nullable=True),+ sa.Column('deploy_on_push', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('pre_deploy_script', sa.Text(), nullable=True),+ sa.Column('post_deploy_script', sa.Text(), nullable=True),+ sa.Column('zero_downtime', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('is_active', sa.Boolean(), server_default=sa.text('1')),+ sa.Column('last_sync_at', sa.DateTime(), nullable=True),+ sa.Column('last_sync_status', sa.String(20), nullable=True),+ sa.Column('last_sync_message', sa.Text(), nullable=True),+ sa.Column('sync_count', sa.Integer(), server_default='0'),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'webhook_logs' not in existing_tables:+ op.create_table('webhook_logs',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('webhook_id', sa.Integer(), sa.ForeignKey('git_webhooks.id'), nullable=True),+ sa.Column('source', sa.String(50), nullable=False),+ sa.Column('event_type', sa.String(50), nullable=False),+ sa.Column('delivery_id', sa.String(100), nullable=True),+ sa.Column('ref', sa.String(200), nullable=True),+ sa.Column('commit_sha', sa.String(64), nullable=True),+ sa.Column('commit_message', sa.Text(), nullable=True),+ sa.Column('pusher', sa.String(100), nullable=True),+ sa.Column('status', sa.String(20), server_default='received'),+ sa.Column('status_message', sa.Text(), nullable=True),+ sa.Column('headers_json', sa.Text(), nullable=True),+ sa.Column('payload_preview', sa.Text(), nullable=True),+ sa.Column('received_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('processed_at', sa.DateTime(), nullable=True),+ )++ if 'git_deployments' not in existing_tables:+ op.create_table('git_deployments',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('app_id', sa.Integer(), sa.ForeignKey('applications.id'), nullable=False),+ sa.Column('webhook_id', sa.Integer(), sa.ForeignKey('git_webhooks.id'), nullable=True),+ sa.Column('version', sa.Integer(), nullable=False),+ sa.Column('commit_sha', sa.String(64), nullable=True),+ sa.Column('commit_message', sa.Text(), nullable=True),+ sa.Column('branch', sa.String(100), nullable=True),+ sa.Column('triggered_by', sa.String(100), nullable=True),+ sa.Column('status', sa.String(20), server_default='pending'),+ sa.Column('started_at', sa.DateTime(), nullable=True),+ sa.Column('completed_at', sa.DateTime(), nullable=True),+ sa.Column('duration_seconds', sa.Integer(), nullable=True),+ sa.Column('pre_script_output', sa.Text(), nullable=True),+ sa.Column('deploy_output', sa.Text(), nullable=True),+ sa.Column('post_script_output', sa.Text(), nullable=True),+ sa.Column('error_message', sa.Text(), nullable=True),+ sa.Column('is_rollback', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('rollback_from_version', sa.Integer(), nullable=True),+ sa.Column('rolled_back_at', sa.DateTime(), nullable=True),+ sa.Column('rolled_back_to_id', sa.Integer(), nullable=True),+ sa.Column('snapshot_data', sa.Text(), nullable=True),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'server_groups' not in existing_tables:+ op.create_table('server_groups',+ sa.Column('id', sa.String(36), primary_key=True),+ sa.Column('name', sa.String(100), nullable=False),+ sa.Column('description', sa.Text()),+ sa.Column('color', sa.String(7), server_default='#6366f1'),+ sa.Column('icon', sa.String(50), server_default='server'),+ sa.Column('parent_id', sa.String(36), sa.ForeignKey('server_groups.id'), nullable=True),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'servers' not in existing_tables:+ op.create_table('servers',+ sa.Column('id', sa.String(36), primary_key=True),+ sa.Column('name', sa.String(100), nullable=False),+ sa.Column('description', sa.Text()),+ sa.Column('hostname', sa.String(255)),+ sa.Column('ip_address', sa.String(45)),+ sa.Column('group_id', sa.String(36), sa.ForeignKey('server_groups.id'), nullable=True),+ sa.Column('tags', sa.JSON()),+ sa.Column('status', sa.String(20), server_default='pending'),+ sa.Column('last_seen', sa.DateTime()),+ sa.Column('last_error', sa.Text()),+ sa.Column('agent_version', sa.String(20)),+ sa.Column('agent_id', sa.String(36), unique=True, index=True),+ sa.Column('os_type', sa.String(20)),+ sa.Column('os_version', sa.String(100)),+ sa.Column('platform', sa.String(100)),+ sa.Column('architecture', sa.String(20)),+ sa.Column('cpu_cores', sa.Integer()),+ sa.Column('cpu_model', sa.String(200)),+ sa.Column('total_memory', sa.BigInteger()),+ sa.Column('total_disk', sa.BigInteger()),+ sa.Column('docker_version', sa.String(50)),+ sa.Column('api_key_hash', sa.String(256)),+ sa.Column('api_key_prefix', sa.String(12)),+ sa.Column('api_secret_encrypted', sa.Text()),+ sa.Column('permissions', sa.JSON()),+ sa.Column('allowed_ips', sa.JSON()),+ sa.Column('api_key_pending_hash', sa.String(256)),+ sa.Column('api_key_pending_prefix', sa.String(12)),+ sa.Column('api_secret_pending_encrypted', sa.Text()),+ sa.Column('api_key_rotation_expires', sa.DateTime()),+ sa.Column('api_key_rotation_id', sa.String(36)),+ sa.Column('api_key_last_rotated', sa.DateTime()),+ sa.Column('registration_token_hash', sa.String(256)),+ sa.Column('registration_token_expires', sa.DateTime()),+ sa.Column('registered_at', sa.DateTime()),+ sa.Column('registered_by', sa.Integer(), sa.ForeignKey('users.id')),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'server_metrics' not in existing_tables:+ op.create_table('server_metrics',+ sa.Column('id', sa.BigInteger(), primary_key=True, autoincrement=True),+ sa.Column('server_id', sa.String(36), sa.ForeignKey('servers.id'), nullable=False, index=True),+ sa.Column('timestamp', sa.DateTime(), server_default=sa.func.now(), index=True),+ sa.Column('cpu_percent', sa.Float()),+ sa.Column('memory_percent', sa.Float()),+ sa.Column('memory_used', sa.BigInteger()),+ sa.Column('disk_percent', sa.Float()),+ sa.Column('disk_used', sa.BigInteger()),+ sa.Column('network_rx', sa.BigInteger()),+ sa.Column('network_tx', sa.BigInteger()),+ sa.Column('network_rx_rate', sa.Float()),+ sa.Column('network_tx_rate', sa.Float()),+ sa.Column('container_count', sa.Integer()),+ sa.Column('container_running', sa.Integer()),+ sa.Column('extra', sa.JSON()),+ )+ op.create_index('ix_server_metrics_server_time', 'server_metrics', ['server_id', 'timestamp'])++ if 'server_commands' not in existing_tables:+ op.create_table('server_commands',+ sa.Column('id', sa.String(36), primary_key=True),+ sa.Column('server_id', sa.String(36), sa.ForeignKey('servers.id'), nullable=False, index=True),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id')),+ sa.Column('command_type', sa.String(50)),+ sa.Column('command_data', sa.JSON()),+ sa.Column('status', sa.String(20), server_default='pending'),+ sa.Column('started_at', sa.DateTime()),+ sa.Column('completed_at', sa.DateTime()),+ sa.Column('result', sa.JSON()),+ sa.Column('error', sa.Text()),+ sa.Column('exit_code', sa.Integer()),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'agent_sessions' not in existing_tables:+ op.create_table('agent_sessions',+ sa.Column('id', sa.String(36), primary_key=True),+ sa.Column('server_id', sa.String(36), sa.ForeignKey('servers.id'), nullable=False, index=True),+ sa.Column('session_token', sa.String(256)),+ sa.Column('socket_id', sa.String(100)),+ sa.Column('connected_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('last_heartbeat', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('ip_address', sa.String(45)),+ sa.Column('user_agent', sa.String(255)),+ sa.Column('is_active', sa.Boolean(), server_default=sa.text('1'), index=True),+ sa.Column('disconnected_at', sa.DateTime()),+ sa.Column('disconnect_reason', sa.String(100)),+ )++ if 'security_alerts' not in existing_tables:+ op.create_table('security_alerts',+ sa.Column('id', sa.String(36), primary_key=True),+ sa.Column('server_id', sa.String(36), sa.ForeignKey('servers.id'), nullable=True, index=True),+ sa.Column('alert_type', sa.String(50), nullable=False, index=True),+ sa.Column('severity', sa.String(20), nullable=False, server_default='info', index=True),+ sa.Column('source_ip', sa.String(45)),+ sa.Column('details', sa.JSON()),+ sa.Column('status', sa.String(20), server_default='open', index=True),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now(), index=True),+ sa.Column('acknowledged_at', sa.DateTime()),+ sa.Column('acknowledged_by', sa.Integer(), sa.ForeignKey('users.id')),+ sa.Column('resolved_at', sa.DateTime()),+ sa.Column('resolved_by', sa.Integer(), sa.ForeignKey('users.id')),+ )++ if 'wordpress_sites' not in existing_tables:+ op.create_table('wordpress_sites',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('application_id', sa.Integer(), sa.ForeignKey('applications.id'), unique=True, nullable=False),+ sa.Column('wp_version', sa.String(20)),+ sa.Column('multisite', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('admin_user', sa.String(100)),+ sa.Column('admin_email', sa.String(200)),+ sa.Column('db_name', sa.String(100)),+ sa.Column('db_user', sa.String(100)),+ sa.Column('db_host', sa.String(200), server_default='localhost'),+ sa.Column('db_prefix', sa.String(20), server_default='wp_'),+ sa.Column('git_repo_url', sa.String(500)),+ sa.Column('git_branch', sa.String(100), server_default='main'),+ sa.Column('git_paths', sa.Text()),+ sa.Column('auto_deploy', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('last_deploy_commit', sa.String(40)),+ sa.Column('last_deploy_at', sa.DateTime()),+ sa.Column('is_production', sa.Boolean(), server_default=sa.text('1')),+ sa.Column('production_site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=True),+ sa.Column('sync_config', sa.Text()),+ sa.Column('environment_type', sa.String(20), server_default='standalone'),+ sa.Column('multidev_branch', sa.String(200)),+ sa.Column('is_locked', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('locked_by', sa.String(100)),+ sa.Column('locked_reason', sa.String(200)),+ sa.Column('lock_expires_at', sa.DateTime()),+ sa.Column('compose_project_name', sa.String(100)),+ sa.Column('container_prefix', sa.String(100)),+ sa.Column('resource_limits', sa.Text()),+ sa.Column('basic_auth_enabled', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('basic_auth_user', sa.String(100)),+ sa.Column('basic_auth_password_hash', sa.String(200)),+ sa.Column('health_status', sa.String(20), server_default='unknown'),+ sa.Column('last_health_check', sa.DateTime()),+ sa.Column('disk_usage_bytes', sa.BigInteger(), server_default='0'),+ sa.Column('disk_usage_updated_at', sa.DateTime()),+ sa.Column('auto_sync_schedule', sa.String(100)),+ sa.Column('auto_sync_enabled', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'database_snapshots' not in existing_tables:+ op.create_table('database_snapshots',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=False),+ sa.Column('name', sa.String(200), nullable=False),+ sa.Column('description', sa.Text()),+ sa.Column('tag', sa.String(100)),+ sa.Column('file_path', sa.String(500), nullable=False),+ sa.Column('size_bytes', sa.BigInteger(), server_default='0'),+ sa.Column('compressed', sa.Boolean(), server_default=sa.text('1')),+ sa.Column('commit_sha', sa.String(40)),+ sa.Column('commit_message', sa.Text()),+ sa.Column('tables_included', sa.Text()),+ sa.Column('row_count', sa.Integer()),+ sa.Column('status', sa.String(20), server_default='completed'),+ sa.Column('error_message', sa.Text()),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('expires_at', sa.DateTime()),+ )++ if 'sync_jobs' not in existing_tables:+ op.create_table('sync_jobs',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('source_site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=False),+ sa.Column('target_site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=False),+ sa.Column('name', sa.String(200)),+ sa.Column('schedule', sa.String(100)),+ sa.Column('enabled', sa.Boolean(), server_default=sa.text('1')),+ sa.Column('config', sa.Text()),+ sa.Column('last_run', sa.DateTime()),+ sa.Column('last_run_status', sa.String(20)),+ sa.Column('last_run_duration', sa.Integer()),+ sa.Column('last_run_error', sa.Text()),+ sa.Column('next_run', sa.DateTime()),+ sa.Column('run_count', sa.Integer(), server_default='0'),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'environment_activities' not in existing_tables:+ op.create_table('environment_activities',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=False),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),+ sa.Column('action', sa.String(50), nullable=False),+ sa.Column('description', sa.Text()),+ sa.Column('metadata', sa.Text()),+ sa.Column('status', sa.String(20), server_default='completed'),+ sa.Column('error_message', sa.Text()),+ sa.Column('duration_seconds', sa.Float()),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'promotion_jobs' not in existing_tables:+ op.create_table('promotion_jobs',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('source_site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=False),+ sa.Column('target_site_id', sa.Integer(), sa.ForeignKey('wordpress_sites.id'), nullable=False),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),+ sa.Column('promotion_type', sa.String(20), nullable=False),+ sa.Column('config', sa.Text()),+ sa.Column('status', sa.String(20), server_default='pending'),+ sa.Column('pre_promotion_snapshot_id', sa.Integer(), sa.ForeignKey('database_snapshots.id'), nullable=True),+ sa.Column('error_message', sa.Text()),+ sa.Column('started_at', sa.DateTime()),+ sa.Column('completed_at', sa.DateTime()),+ sa.Column('duration_seconds', sa.Float()),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ )++ if 'sanitization_profiles' not in existing_tables:+ op.create_table('sanitization_profiles',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),+ sa.Column('name', sa.String(100), nullable=False),+ sa.Column('description', sa.Text()),+ sa.Column('config', sa.Text(), nullable=False),+ sa.Column('is_default', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('is_builtin', sa.Boolean(), server_default=sa.text('0')),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime()),+ )++ if 'email_accounts' not in existing_tables:+ op.create_table('email_accounts',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('email', sa.String(255), unique=True, nullable=False),+ sa.Column('domain', sa.String(255), nullable=False),+ sa.Column('username', sa.String(100), nullable=False),+ sa.Column('quota_mb', sa.Integer(), server_default='1024'),+ sa.Column('enabled', sa.Boolean(), server_default=sa.text('1')),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('forward_to', sa.Text(), nullable=True),+ sa.Column('forward_keep_copy', sa.Boolean(), server_default=sa.text('1')),+ )++ if 'oauth_identities' not in existing_tables:+ op.create_table('oauth_identities',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, index=True),+ sa.Column('provider', sa.String(50), nullable=False),+ sa.Column('provider_user_id', sa.String(256), nullable=False),+ sa.Column('provider_email', sa.String(256), nullable=True),+ sa.Column('provider_display_name', sa.String(256), nullable=True),+ sa.Column('access_token_encrypted', sa.Text(), nullable=True),+ sa.Column('refresh_token_encrypted', sa.Text(), nullable=True),+ sa.Column('token_expires_at', sa.DateTime(), nullable=True),+ sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),+ sa.Column('last_login_at', sa.DateTime(), nullable=True),+ sa.UniqueConstraint('provider', 'provider_user_id', name='uq_provider_identity'),+ )+++def downgrade():+ # Drop tables in reverse dependency order+ tables = [+ 'oauth_identities', 'email_accounts', 'sanitization_profiles',+ 'promotion_jobs', 'environment_activities', 'sync_jobs',+ 'database_snapshots', 'wordpress_sites', 'security_alerts',+ 'agent_sessions', 'server_commands', 'server_metrics', 'servers',+ 'server_groups', 'git_deployments', 'webhook_logs', 'git_webhooks',+ 'workflows', 'metrics_history', 'audit_logs', 'system_settings',+ 'deployment_diffs', 'deployments', 'notification_preferences',+ 'environment_variable_history', 'environment_variables', 'domains',+ 'applications', 'users',+ ]++ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing_tables = inspector.get_table_names()++ for table in tables:+ if table in existing_tables:+ op.drop_table(table)diff --git a/backend/requirements.txt b/backend/requirements.txtindex 6eba1fa5..fddada77 100644--- a/backend/requirements.txt+++ b/backend/requirements.txt@@ -5,6 +5,7 @@ Werkzeug==3.1.6# DatabaseFlask-SQLAlchemy==3.1.1SQLAlchemy==2.0.23+Flask-Migrate==4.0.7# AuthenticationFlask-JWT-Extended==4.6.0@@ -53,4 +54,8 @@ qrcode[pil]==7.4.2requests==2.32.5# S3-compatible storage (AWS S3, Backblaze B2, MinIO, Wasabi)-boto3==1.35.0\ No newline at end of file+boto3==1.35.0++# SSO / OAuth+Authlib==1.5.2+python3-saml==1.16.0\ No newline at end of filediff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex bbddce44..b11023f8 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -36,6 +36,8 @@ import WordPressProjects from './pages/WordPressProjects';import WordPressProject from './pages/WordPressProject';import SSLCertificates from './pages/SSLCertificates';import Email from './pages/Email';+import SSOCallback from './pages/SSOCallback';+import DatabaseMigration from './pages/DatabaseMigration';// Page title mappingconst PAGE_TITLES = {@@ -64,6 +66,7 @@ const PAGE_TITLES = {'/email': 'Email Server','/terminal': 'Terminal','/settings': 'Settings',+ '/migrate': 'Database Migration',};function PageTitleUpdater() {@@ -93,13 +96,17 @@ function PageTitleUpdater() {}function PrivateRoute({ children }) {- const { isAuthenticated, loading, needsSetup } = useAuth();+ const { isAuthenticated, loading, needsSetup, needsMigration } = useAuth();if (loading) {return <div className="loading">Loading...</div>;}- // If setup is needed, redirect to setup+ // Priority: migrations > setup > auth+ if (needsMigration) {+ return <Navigate to="/migrate" />;+ }+if (needsSetup) {return <Navigate to="/setup" />;}@@ -108,13 +115,17 @@ function PrivateRoute({ children }) {}function PublicRoute({ children }) {- const { isAuthenticated, loading, needsSetup } = useAuth();+ const { isAuthenticated, loading, needsSetup, needsMigration } = useAuth();if (loading) {return <div className="loading">Loading...</div>;}- // If setup is needed, redirect to setup+ // Priority: migrations > setup > auth+ if (needsMigration) {+ return <Navigate to="/migrate" />;+ }+if (needsSetup) {return <Navigate to="/setup" />;}@@ -142,6 +153,7 @@ function AppRoutes() {return (<Routes>+ <Route path="/migrate" element={<DatabaseMigration />} /><Route path="/setup" element={<SetupRoute><Setup />@@ -152,6 +164,11 @@ function AppRoutes() {<Login /></PublicRoute>} />+ <Route path="/login/callback/:provider" element={+ <PublicRoute>+ <SSOCallback />+ </PublicRoute>+ } />{registrationEnabled && (<Route path="/register" element={<PublicRoute>diff --git a/frontend/src/components/SSOProviderIcon.jsx b/frontend/src/components/SSOProviderIcon.jsxnew file mode 100644index 00000000..7054c958--- /dev/null+++ b/frontend/src/components/SSOProviderIcon.jsx@@ -0,0 +1,27 @@+import React from 'react';+import { Key } from 'lucide-react';++const GoogleIcon = () => (+ <svg viewBox="0 0 24 24" width="20" height="20">+ <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/>+ <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>+ <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>+ <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>+ </svg>+);++const GitHubIcon = () => (+ <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">+ <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/>+ </svg>+);++const SSOProviderIcon = ({ provider }) => {+ switch (provider) {+ case 'google': return <GoogleIcon />;+ case 'github': return <GitHubIcon />;+ default: return <Key size={20} />;+ }+};++export default SSOProviderIcon;diff --git a/frontend/src/components/ServerKitLogo.jsx b/frontend/src/components/ServerKitLogo.jsxnew file mode 100644index 00000000..f91dc0ec--- /dev/null+++ b/frontend/src/components/ServerKitLogo.jsx@@ -0,0 +1,27 @@+const ServerKitLogo = ({ width = 64, height = 64, className = '' }) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 2048 2048"+ width={width}+ height={height}+ className={className}+ role="img"+ aria-label="ServerKit Logo"+ >+ <defs>+ <linearGradient id="skBrandGradient" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" stopColor="var(--accent-primary, #6366f1)" />+ <stop offset="100%" stopColor="var(--accent-hover, #4f46e5)" />+ </linearGradient>+ </defs>+ <rect x="150" y="150" width="1748" height="1748" rx="150" fill="white" />+ <path fill="url(#skBrandGradient)" d="M169.61,1878.37c-58.74-56.76-93.82-135.58-99.4-217.52l.07-1284.1C80.47,209.28,209.08,77.66,377.92,70.27l1289.92-.07c173.25,6.73,300.76,139.7,309.9,311.19l.06,1279.44c-10.02,173.54-152.93,308.11-325.14,316.88l-1255.02.07c-87.51-5.09-165.43-38.95-228.02-99.43ZM1600.9,819.3v-69.2l1.69-1.47c59.31,8.75,119.93-21.99,131.77-83.73-.72-71.44,5.91-148.48,1.5-219.58-3.43-55.29-41.89-95.55-97.11-100.61-413.15,1.13-826.62-1.98-1239.58,1.56-51.76,10.06-83.97,47.53-87.04,100.22-3.95,67.93,2.93,139.76.2,208.09,4.42,37.49,26.63,70.13,61.53,85.02,23.73,10.12,47.78,10.56,73.24,9.92v68.04l-1.74,1.74h-40.71c-45.8,0-92.81,51.61-92.51,97.07,3.38,69-4.35,142.03.06,210.56,3.45,53.53,45.33,92.53,98.22,96.01,9.99.66,24.77-1.69,33.78-.05,1.3.24,2.18.59,2.91,1.74v68.04c-24.94.44-50.51-.87-73.69,9.47-33.62,15-57.82,47.15-61.08,84.31-5.99,68.38,4.22,144.71-.21,213.92,3.28,52.32,44.65,90.9,95.96,95.95h1229.5c51.94-2.48,94.76-42.48,98.27-94.8,4.66-69.44-3.58-144.06-.06-214.04-3.42-45.19-36.88-83.18-81.39-91.91-17.66-3.46-35.59-3-53.51-2.9v-69.79c25.25-.07,50.09,2.08,73.69-8.31,33.21-14.62,58.51-47.53,61.21-84.17,5.14-69.51-3.85-145.06.06-215.21.59-44-45.85-95.91-90.19-95.91h-44.78Z" />+ <path fill="url(#skBrandGradient)" d="M1645.86,904.61c3.93,3.68,5.98,9.92,6.26,15.26l-.03,202.43c-1.99,12.99-7.56,18.2-20.23,20.58-366.99.71-735.14,1.01-1102.74.1-34.1-.08-74.96,3.4-108.21.86-12.89-.98-23.01-8.16-24.86-21.66-3.47-25.29,2.96-56.74-.82-82.67,4.31-38.56-3.36-82.85.71-120.78,1.27-11.82,9.02-18.56,20.49-20.22l1209.55-.18c6.82.6,14.7,1.41,19.9,6.28ZM1209.84,975.47c-55.44,6.6-51.14,94.89,7.75,93.93,63.57-1.04,59.56-101.94-7.75-93.93ZM1365.67,975.45c-61.66,8.44-45.2,107.48,17.76,92.2,56.18-13.63,41.64-100.33-17.76-92.2ZM1496.63,1056.16c43.4,42.6,108.56-24.61,64.2-68.27-43.1-42.42-108.68,24.61-64.2,68.27Z" />+ <path fill="url(#skBrandGradient)" d="M415.4,1373.21l1215.01-.13c25.54,2.02,22.46,28.97,22.91,48.11,1.15,49.88,1.8,107.07-.04,157.09-.77,21.02-.79,36.94-26.17,38.94l-1211.71-.32c-7.31-1.22-17.24-9.74-19.19-16.87-2.27-69.63-2.66-140.15.23-209.73,2.3-9.69,9.95-14.4,18.96-17.1ZM1250.4,1462.9c-43.81-44.48-111.6,23.9-65.76,67.51,43.96,41.83,107.52-25.1,65.76-67.51ZM1528.49,1449.01c-62.25,2.08-59.67,94.67.89,93.82,62.28-.87,57.86-95.78-.89-93.82ZM1405.09,1529.54c43.25-43.24-20.92-110.55-65.3-67.04-43.23,42.39,21.83,110.51,65.3,67.04Z" />+ <path fill="url(#skBrandGradient)" d="M1645.85,661.88c-4.26,4.57-12.49,7.41-18.74,7.43l-1209.54-.18c-11-1.22-20.4-10.28-21.65-21.38-1.98-17.63-1.14-44.43-1.24-62.82-.16-30.33.12-61.22.39-91.85.13-14.24-.86-35.49.95-48.78,1.42-10.46,10.9-18.83,21.37-19.34l1215.38.15c9.9,1.79,17.37,9.17,19.32,19.06v201.29c-.4,5.39-2.54,12.44-6.25,16.42ZM1339.61,513.81c-22.99,22.96-15.41,64.43,15.44,76.2,40.12,15.3,76.94-24.03,59.6-63.09-13.09-29.5-52.45-35.68-75.05-13.11ZM1207.49,500.91c-44.94,6.5-51.92,79.05-2.34,91.29,71.33,17.61,80.68-102.62,2.34-91.29ZM1519.2,500.91c-48.7,7.04-50.02,89.18,6.69,92.72,66.96,4.19,64.61-103.04-6.69-92.72Z" />+ <polygon fill="url(#skBrandGradient)" points="1518.32 1222.89 1518.18 1293.71 1516.56 1293.93 531.45 1293.8 529.04 1292.74 528.53 1222.89 1518.32 1222.89" />+ <polygon fill="url(#skBrandGradient)" points="1518.32 749.51 1518.32 819.3 529.69 819.3 529.69 748.34 1518.32 749.51" />+ </svg>+);++export default ServerKitLogo;diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsxindex ce6ccef1..f56dd003 100644--- a/frontend/src/components/Sidebar.jsx+++ b/frontend/src/components/Sidebar.jsx@@ -2,13 +2,13 @@ import React, { useState, useEffect, useRef } from 'react';import { NavLink, useNavigate } from 'react-router-dom';import { useAuth } from '../contexts/AuthContext';import { useTheme } from '../contexts/ThemeContext';-import { Star, Settings, LogOut, Sun, Moon, Monitor, ChevronRight, ChevronUp } from 'lucide-react';+import { Star, Settings, LogOut, Sun, Moon, Monitor, ChevronRight, ChevronUp, Layers } from 'lucide-react';import { api } from '../services/api';-import ServerKitLogo from '../assets/ServerKitLogo.svg';+import ServerKitLogo from './ServerKitLogo';const Sidebar = () => {const { user, logout } = useAuth();- const { theme, resolvedTheme, setTheme } = useTheme();+ const { theme, resolvedTheme, setTheme, whiteLabel } = useTheme();const navigate = useNavigate();const [starAnimating, setStarAnimating] = useState(false);const [menuOpen, setMenuOpen] = useState(false);@@ -35,6 +35,8 @@ const Sidebar = () => {}, []);useEffect(() => {+ if (whiteLabel.enabled) return;+let playCount = 0;let timeoutId;@@ -68,32 +70,63 @@ const Sidebar = () => {clearTimeout(initialDelay);clearTimeout(timeoutId);};- }, []);+ }, [whiteLabel.enabled]);return (<aside className="sidebar">- <div className="brand-section">- <div className="brand-logo">- <img src={ServerKitLogo} alt="ServerKit" width="42" height="42" />+ {whiteLabel.enabled ? (+ <div className="brand-section brand-section--custom">+ {whiteLabel.mode === 'image_full' ? (+ <div className="brand-custom-banner">+ {whiteLabel.logoData ? (+ <img src={whiteLabel.logoData} alt={whiteLabel.brandName || 'Brand'} />+ ) : (+ <Layers size={32} />+ )}+ </div>+ ) : whiteLabel.mode === 'text_only' ? (+ <span className="brand-custom-text">+ {whiteLabel.brandName || 'Brand'}+ </span>+ ) : (+ <>+ <div className="brand-custom-logo">+ {whiteLabel.logoData ? (+ <img src={whiteLabel.logoData} alt={whiteLabel.brandName || 'Brand'} />+ ) : (+ <Layers size={20} />+ )}+ </div>+ <span className="brand-custom-text">+ {whiteLabel.brandName || 'Brand'}+ </span>+ </>+ )}</div>- <span className="brand-text">ServerKit</span>- <a- href="https://github.com/jhd3197/ServerKit"- target="_blank"- rel="noopener noreferrer"- className={`brand-star ${starAnimating ? 'animating' : ''}`}- title="Star on GitHub"- >- <Star size={14} />- <span className="star-particles">- <span></span><span></span><span></span><span></span><span></span><span></span>- </span>- <span className="star-ring"></span>- <span className="star-ring ring-2"></span>- <span className="star-ring ring-3"></span>- <span className="star-tooltip">Star us!</span>- </a>- </div>+ ) : (+ <div className="brand-section">+ <div className="brand-logo">+ <ServerKitLogo width={42} height={42} />+ </div>+ <span className="brand-text">ServerKit</span>+ <a+ href="https://github.com/jhd3197/ServerKit"+ target="_blank"+ rel="noopener noreferrer"+ className={`brand-star ${starAnimating ? 'animating' : ''}`}+ title="Star on GitHub"+ >+ <Star size={14} />+ <span className="star-particles">+ <span></span><span></span><span></span><span></span><span></span><span></span>+ </span>+ <span className="star-ring"></span>+ <span className="star-ring ring-2"></span>+ <span className="star-ring ring-3"></span>+ <span className="star-tooltip">Star us!</span>+ </a>+ </div>+ )}<div className="nav-scroll"><div className="nav-category">Overview</div>diff --git a/frontend/src/components/settings/MigrationHistoryTab.jsx b/frontend/src/components/settings/MigrationHistoryTab.jsxnew file mode 100644index 00000000..79a7a2af--- /dev/null+++ b/frontend/src/components/settings/MigrationHistoryTab.jsx@@ -0,0 +1,103 @@+import React, { useState, useEffect } from 'react';+import api from '../../services/api';+import { Database, Loader, CheckCircle, ArrowUpCircle } from 'lucide-react';++const MigrationHistoryTab = () => {+ const [revisions, setRevisions] = useState([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(null);++ useEffect(() => {+ loadHistory();+ }, []);++ async function loadHistory() {+ try {+ setLoading(true);+ const data = await api.getMigrationHistory();+ setRevisions(data.revisions || []);+ } catch (err) {+ setError(err.message || 'Failed to load migration history');+ } finally {+ setLoading(false);+ }+ }++ if (loading) {+ return (+ <div className="settings-section">+ <div className="loading-state">+ <Loader size={20} className="spin" />+ <span>Loading migration history...</span>+ </div>+ </div>+ );+ }++ if (error) {+ return (+ <div className="settings-section">+ <div className="empty-state">+ <p>{error}</p>+ </div>+ </div>+ );+ }++ return (+ <div className="settings-section">+ <div className="settings-section-header">+ <h2>Database Migrations</h2>+ <p className="settings-section-description">+ History of all database schema versions applied to this instance.+ </p>+ </div>++ {revisions.length === 0 ? (+ <div className="empty-state">+ <Database size={32} />+ <p>No migration history found.</p>+ </div>+ ) : (+ <div className="table-container">+ <table className="data-table">+ <thead>+ <tr>+ <th>Revision</th>+ <th>Description</th>+ <th>Status</th>+ </tr>+ </thead>+ <tbody>+ {revisions.map((rev, i) => (+ <tr key={i}>+ <td>+ <code>{rev.revision.substring(0, 16)}</code>+ </td>+ <td>{rev.description || 'Schema update'}</td>+ <td>+ {rev.is_current && (+ <span className="badge badge--success">+ <CheckCircle size={12} /> Current+ </span>+ )}+ {rev.is_head && !rev.is_current && (+ <span className="badge badge--warning">+ <ArrowUpCircle size={12} /> Pending+ </span>+ )}+ {!rev.is_current && !rev.is_head && (+ <span className="badge badge--neutral">Applied</span>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </div>+ );+};++export default MigrationHistoryTab;diff --git a/frontend/src/components/settings/SSOConfigTab.jsx b/frontend/src/components/settings/SSOConfigTab.jsxnew file mode 100644index 00000000..504b7017--- /dev/null+++ b/frontend/src/components/settings/SSOConfigTab.jsx@@ -0,0 +1,316 @@+import React, { useState, useEffect } from 'react';+import api from '../../services/api';+import SSOProviderIcon from '../SSOProviderIcon';+import {+ Save, RefreshCw, CheckCircle, XCircle, AlertTriangle, Shield, Globe,+ ChevronDown, ChevronUp+} from 'lucide-react';++const PROVIDERS = [+ { id: 'google', name: 'Google', fields: ['client_id', 'client_secret'] },+ { id: 'github', name: 'GitHub', fields: ['client_id', 'client_secret'] },+ {+ id: 'oidc', name: 'OIDC', fields: [+ 'provider_name', 'client_id', 'client_secret', 'discovery_url'+ ]+ },+ {+ id: 'saml', name: 'SAML 2.0', fields: [+ 'entity_id', 'idp_metadata_url', 'idp_sso_url', 'idp_cert'+ ]+ },+];++const FIELD_LABELS = {+ client_id: 'Client ID',+ client_secret: 'Client Secret',+ provider_name: 'Provider Name',+ discovery_url: 'Discovery URL',+ entity_id: 'SP Entity ID',+ idp_metadata_url: 'IdP Metadata URL',+ idp_sso_url: 'IdP SSO URL',+ idp_cert: 'IdP Certificate (PEM)',+};++const SSOConfigTab = () => {+ const [config, setConfig] = useState({});+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState({});+ const [testing, setTesting] = useState({});+ const [testResults, setTestResults] = useState({});+ const [generalSaving, setGeneralSaving] = useState(false);+ const [message, setMessage] = useState(null);+ const [expandedProvider, setExpandedProvider] = useState(null);++ // General settings local state+ const [autoProvision, setAutoProvision] = useState(true);+ const [defaultRole, setDefaultRole] = useState('developer');+ const [forceSso, setForceSso] = useState(false);+ const [allowedDomains, setAllowedDomains] = useState('');++ useEffect(() => {+ loadConfig();+ }, []);++ async function loadConfig() {+ try {+ const data = await api.getSSOConfig();+ setConfig(data.config || {});+ setAutoProvision(data.config?.sso_auto_provision ?? true);+ setDefaultRole(data.config?.sso_default_role || 'developer');+ setForceSso(data.config?.sso_force_sso ?? false);+ const domains = data.config?.sso_allowed_domains || [];+ setAllowedDomains(Array.isArray(domains) ? domains.join(', ') : '');+ } catch (err) {+ setMessage({ type: 'error', text: 'Failed to load SSO config' });+ } finally {+ setLoading(false);+ }+ }++ function getFieldValue(provider, field) {+ const key = `sso_${provider}_${field}`;+ return config[key] ?? '';+ }++ function setFieldValue(provider, field, value) {+ const key = `sso_${provider}_${field}`;+ setConfig(prev => ({ ...prev, [key]: value }));+ }++ async function handleSaveProvider(providerId) {+ setSaving(prev => ({ ...prev, [providerId]: true }));+ setMessage(null);+ try {+ const provider = PROVIDERS.find(p => p.id === providerId);+ const body = {};+ body.enabled = config[`sso_${providerId}_enabled`] ?? false;+ for (const field of provider.fields) {+ body[field] = getFieldValue(providerId, field);+ }+ await api.updateSSOProviderConfig(providerId, body);+ setMessage({ type: 'success', text: `${provider.name} config saved` });+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setSaving(prev => ({ ...prev, [providerId]: false }));+ }+ }++ async function handleTestProvider(providerId) {+ setTesting(prev => ({ ...prev, [providerId]: true }));+ setTestResults(prev => ({ ...prev, [providerId]: null }));+ try {+ const result = await api.testSSOProvider(providerId);+ setTestResults(prev => ({ ...prev, [providerId]: result }));+ } catch (err) {+ setTestResults(prev => ({+ ...prev,+ [providerId]: { ok: false, error: err.message }+ }));+ } finally {+ setTesting(prev => ({ ...prev, [providerId]: false }));+ }+ }++ async function handleSaveGeneral() {+ setGeneralSaving(true);+ setMessage(null);+ try {+ const domains = allowedDomains+ .split(',')+ .map(d => d.trim().toLowerCase())+ .filter(Boolean);+ await api.updateSSOGeneralSettings({+ sso_auto_provision: autoProvision,+ sso_default_role: defaultRole,+ sso_force_sso: forceSso,+ sso_allowed_domains: domains,+ });+ setMessage({ type: 'success', text: 'General SSO settings saved' });+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setGeneralSaving(false);+ }+ }++ if (loading) {+ return <div className="settings-section"><p>Loading SSO configuration...</p></div>;+ }++ return (+ <div className="sso-config">+ <div className="settings-section">+ <h2><Shield size={20} /> SSO / OAuth Configuration</h2>+ <p className="text-secondary">+ Configure external identity providers for single sign-on.+ </p>+ </div>++ {message && (+ <div className={`alert alert--${message.type}`}>+ {message.type === 'success' ? <CheckCircle size={16} /> : <XCircle size={16} />}+ {message.text}+ </div>+ )}++ {/* General Settings */}+ <div className="settings-card">+ <h3><Globe size={18} /> General Settings</h3>+ <div className="settings-form">+ <div className="form-group">+ <label className="toggle-label">+ <input+ type="checkbox"+ checked={autoProvision}+ onChange={e => setAutoProvision(e.target.checked)}+ />+ <span>Auto-provision users</span>+ </label>+ <p className="form-help">Automatically create accounts for new SSO users</p>+ </div>++ <div className="form-group">+ <label>Default role for new SSO users</label>+ <select value={defaultRole} onChange={e => setDefaultRole(e.target.value)}>+ <option value="viewer">Viewer</option>+ <option value="developer">Developer</option>+ <option value="admin">Admin</option>+ </select>+ </div>++ <div className="form-group">+ <label className="toggle-label">+ <input+ type="checkbox"+ checked={forceSso}+ onChange={e => setForceSso(e.target.checked)}+ />+ <span>SSO-only mode</span>+ </label>+ <p className="form-help">+ {forceSso && (+ <span className="text-warning">+ <AlertTriangle size={14} /> Password login will be disabled for all users.+ </span>+ )}+ {!forceSso && 'Disable password login and require SSO for all users'}+ </p>+ </div>++ <div className="form-group">+ <label>Allowed email domains</label>+ <input+ type="text"+ value={allowedDomains}+ onChange={e => setAllowedDomains(e.target.value)}+ placeholder="company.com, example.org"+ />+ <p className="form-help">Comma-separated. Leave empty to allow all domains.</p>+ </div>++ <button+ className="btn btn-primary"+ onClick={handleSaveGeneral}+ disabled={generalSaving}+ >+ <Save size={16} />+ {generalSaving ? 'Saving...' : 'Save General Settings'}+ </button>+ </div>+ </div>++ {/* Provider Cards */}+ {PROVIDERS.map(provider => {+ const enabled = config[`sso_${provider.id}_enabled`] ?? false;+ const isExpanded = expandedProvider === provider.id;+ const testResult = testResults[provider.id];++ return (+ <div key={provider.id} className={`settings-card sso-provider-config ${enabled ? 'sso-provider-config--enabled' : ''}`}>+ <div+ className="sso-provider-config__header"+ onClick={() => setExpandedProvider(isExpanded ? null : provider.id)}+ >+ <div className="sso-provider-config__title">+ <SSOProviderIcon provider={provider.id} />+ <h3>{provider.name}</h3>+ {enabled && (+ <span className="sso-provider-config__status sso-provider-config__status--active">+ Active+ </span>+ )}+ </div>+ {isExpanded ? <ChevronUp size={18} /> : <ChevronDown size={18} />}+ </div>++ {isExpanded && (+ <div className="sso-provider-config__body">+ <div className="form-group">+ <label className="toggle-label">+ <input+ type="checkbox"+ checked={enabled}+ onChange={e => setFieldValue(provider.id, 'enabled', e.target.checked)}+ />+ <span>Enable {provider.name}</span>+ </label>+ </div>++ {provider.fields.map(field => (+ <div key={field} className="form-group">+ <label>{FIELD_LABELS[field] || field}</label>+ {field === 'idp_cert' ? (+ <textarea+ rows={4}+ value={getFieldValue(provider.id, field)}+ onChange={e => setFieldValue(provider.id, field, e.target.value)}+ placeholder={`Enter ${FIELD_LABELS[field]}`}+ />+ ) : (+ <input+ type={field.includes('secret') ? 'password' : 'text'}+ value={getFieldValue(provider.id, field)}+ onChange={e => setFieldValue(provider.id, field, e.target.value)}+ placeholder={`Enter ${FIELD_LABELS[field]}`}+ />+ )}+ </div>+ ))}++ {testResult && (+ <div className={`alert alert--${testResult.ok ? 'success' : 'error'}`}>+ {testResult.ok ? <CheckCircle size={16} /> : <XCircle size={16} />}+ {testResult.ok ? testResult.message : testResult.error}+ </div>+ )}++ <div className="sso-provider-config__actions">+ <button+ className="btn btn-primary"+ onClick={() => handleSaveProvider(provider.id)}+ disabled={saving[provider.id]}+ >+ <Save size={16} />+ {saving[provider.id] ? 'Saving...' : 'Save'}+ </button>+ <button+ className="btn btn-secondary"+ onClick={() => handleTestProvider(provider.id)}+ disabled={testing[provider.id]}+ >+ <RefreshCw size={16} className={testing[provider.id] ? 'spinning' : ''} />+ {testing[provider.id] ? 'Testing...' : 'Test Connection'}+ </button>+ </div>+ </div>+ )}+ </div>+ );+ })}+ </div>+ );+};++export default SSOConfigTab;diff --git a/frontend/src/contexts/AuthContext.jsx b/frontend/src/contexts/AuthContext.jsxindex 6394d283..96ef9f92 100644--- a/frontend/src/contexts/AuthContext.jsx+++ b/frontend/src/contexts/AuthContext.jsx@@ -9,6 +9,10 @@ export function AuthProvider({ children }) {const [setupStatus, setSetupStatus] = useState({needsSetup: false,registrationEnabled: false,+ ssoProviders: [],+ passwordLoginEnabled: true,+ needsMigration: false,+ migrationInfo: null,checked: false});@@ -22,6 +26,10 @@ export function AuthProvider({ children }) {setSetupStatus({needsSetup: status.needs_setup,registrationEnabled: status.registration_enabled,+ ssoProviders: status.sso_providers || [],+ passwordLoginEnabled: status.password_login_enabled !== false,+ needsMigration: status.needs_migration || false,+ migrationInfo: status.migration_info || null,checked: true});@@ -54,6 +62,10 @@ export function AuthProvider({ children }) {setSetupStatus({needsSetup: status.needs_setup,registrationEnabled: status.registration_enabled,+ ssoProviders: status.sso_providers || [],+ passwordLoginEnabled: status.password_login_enabled !== false,+ needsMigration: status.needs_migration || false,+ migrationInfo: status.migration_info || null,checked: true});} catch (error) {@@ -75,11 +87,12 @@ export function AuthProvider({ children }) {async function completeOnboarding(useCases) {await api.completeOnboarding(useCases);- setSetupStatus({+ setSetupStatus(prev => ({+ ...prev,needsSetup: false,registrationEnabled: false,checked: true- });+ }));}function logout() {@@ -116,7 +129,11 @@ export function AuthProvider({ children }) {isViewer: !!user?.role,setupStatus,needsSetup: setupStatus.needsSetup,+ needsMigration: setupStatus.needsMigration,+ migrationInfo: setupStatus.migrationInfo,registrationEnabled: setupStatus.registrationEnabled,+ ssoProviders: setupStatus.ssoProviders,+ passwordLoginEnabled: setupStatus.passwordLoginEnabled,};return (diff --git a/frontend/src/contexts/ThemeContext.jsx b/frontend/src/contexts/ThemeContext.jsxindex 40461d2b..ba42f333 100644--- a/frontend/src/contexts/ThemeContext.jsx+++ b/frontend/src/contexts/ThemeContext.jsx@@ -4,6 +4,13 @@ const ThemeContext = createContext(null);const DEFAULT_ACCENT = '#6366f1';+const DEFAULT_WHITE_LABEL = {+ enabled: false,+ mode: 'image_text', // 'image_text' | 'image_full' | 'text_only'+ brandName: '',+ logoData: '', // base64 data URL+};+// Get the resolved theme based on current setting and OS preferencefunction getResolvedTheme(theme) {if (theme === 'system') {@@ -60,6 +67,15 @@ export function ThemeProvider({ children }) {return localStorage.getItem('accent_color') || DEFAULT_ACCENT;});+ const [whiteLabel, setWhiteLabelState] = useState(() => {+ try {+ const stored = localStorage.getItem('white_label');+ return stored ? { ...DEFAULT_WHITE_LABEL, ...JSON.parse(stored) } : DEFAULT_WHITE_LABEL;+ } catch {+ return DEFAULT_WHITE_LABEL;+ }+ });+// Update the DOM attribute and resolved themeconst applyTheme = useCallback((newTheme) => {document.documentElement.setAttribute('data-theme', newTheme);@@ -80,6 +96,15 @@ export function ThemeProvider({ children }) {applyAccentToDOM(hex);}, []);+ // Public setter for white label config (accepts partial updates)+ const setWhiteLabel = useCallback((partial) => {+ setWhiteLabelState(prev => {+ const next = { ...prev, ...partial };+ localStorage.setItem('white_label', JSON.stringify(next));+ return next;+ });+ }, []);+// Listen for OS theme changes when using 'system' themeuseEffect(() => {if (theme !== 'system') return;@@ -106,6 +131,8 @@ export function ThemeProvider({ children }) {setTheme, // Function to change themeaccentColor, // Current accent hex colorsetAccentColor, // Function to change accent color+ whiteLabel, // White label config object+ setWhiteLabel, // Function to update white label config};return (diff --git a/frontend/src/pages/DatabaseMigration.jsx b/frontend/src/pages/DatabaseMigration.jsxnew file mode 100644index 00000000..2712e353--- /dev/null+++ b/frontend/src/pages/DatabaseMigration.jsx@@ -0,0 +1,380 @@+import React, { useState, useEffect } from 'react';+import { useNavigate } from 'react-router-dom';+import { useAuth } from '../contexts/AuthContext';+import api from '../services/api';+import {+ Check, Database, AlertTriangle, ArrowRight, Download,+ Loader, CheckCircle, XCircle, RotateCcw, Shield+} from 'lucide-react';+import ServerKitLogo from '../components/ServerKitLogo';++const TOTAL_STEPS = 4;+const STEP_TITLES = ['Overview', 'Backup', 'Apply', 'Done'];++const DatabaseMigration = () => {+ const { isAuthenticated, isAdmin, needsMigration, migrationInfo, refreshSetupStatus, login } = useAuth();+ const navigate = useNavigate();++ const [currentStep, setCurrentStep] = useState(1);+ const [backupResult, setBackupResult] = useState(null);+ const [backupLoading, setBackupLoading] = useState(false);+ const [applyLoading, setApplyLoading] = useState(false);+ const [applyError, setApplyError] = useState(null);+ const [migrationStatus, setMigrationStatus] = useState(null);++ // Login form state (for unauthenticated users)+ const [loginEmail, setLoginEmail] = useState('');+ const [loginPassword, setLoginPassword] = useState('');+ const [loginError, setLoginError] = useState('');+ const [loginLoading, setLoginLoading] = useState(false);++ useEffect(() => {+ loadMigrationStatus();+ }, []);++ // Redirect away if no migration needed+ useEffect(() => {+ if (!needsMigration && migrationStatus && !migrationStatus.needs_migration) {+ navigate('/');+ }+ }, [needsMigration, migrationStatus]);++ async function loadMigrationStatus() {+ try {+ const status = await api.getMigrationStatus();+ setMigrationStatus(status);+ } catch (err) {+ console.error('Failed to load migration status:', err);+ }+ }++ async function handleLogin(e) {+ e.preventDefault();+ setLoginError('');+ setLoginLoading(true);+ try {+ await login(loginEmail, loginPassword);+ } catch (err) {+ setLoginError(err.message || 'Login failed');+ } finally {+ setLoginLoading(false);+ }+ }++ async function handleBackup() {+ setBackupLoading(true);+ try {+ const result = await api.createMigrationBackup();+ setBackupResult(result);+ } catch (err) {+ setBackupResult({ success: false, error: err.message });+ } finally {+ setBackupLoading(false);+ }+ }++ async function handleApply() {+ setApplyLoading(true);+ setApplyError(null);+ try {+ await api.applyMigrations();+ setCurrentStep(4);+ await loadMigrationStatus();+ } catch (err) {+ setApplyError(err.message || 'Migration failed');+ } finally {+ setApplyLoading(false);+ }+ }++ async function handleFinish() {+ await refreshSetupStatus();+ navigate('/');+ }++ function renderProgressBar() {+ const items = [];+ for (let i = 1; i <= TOTAL_STEPS; i++) {+ if (i > 1) {+ items.push(+ <div+ key={`line-${i}`}+ className={`wizard-progress-line${i <= currentStep ? ' active' : ''}`}+ />+ );+ }+ let stepClass = 'wizard-progress-step';+ if (i < currentStep) stepClass += ' completed';+ else if (i === currentStep) stepClass += ' active';++ items.push(+ <div key={`step-${i}`} className={stepClass} title={STEP_TITLES[i - 1]}>+ {i < currentStep ? <Check size={16} /> : i}+ </div>+ );+ }+ return <div className="wizard-progress">{items}</div>;+ }++ const status = migrationStatus || migrationInfo || {};+ const pendingCount = status.pending_count || 0;+ const pendingMigrations = status.pending_migrations || [];++ return (+ <div className="setup-wizard migration-wizard">+ <div className="wizard-card">+ <div className="wizard-header">+ <ServerKitLogo className="wizard-logo" />+ <h1>Database Update Required</h1>+ <p>ServerKit needs to update the database before continuing</p>+ </div>++ {renderProgressBar()}++ {/* Step 1: Overview */}+ {currentStep === 1 && (+ <div className="wizard-step">+ <div className="wizard-step-title">Update Overview</div>+ <div className="wizard-step-description">+ A new version of ServerKit requires database changes.+ The panel is paused until these are applied.+ </div>++ <div className="migration-status-panel">+ <div className="migration-status-row">+ <span className="migration-status-label">Current version</span>+ <code className="migration-status-value">+ {status.current_revision ? status.current_revision.substring(0, 12) : 'none'}+ </code>+ </div>+ <div className="migration-status-row">+ <span className="migration-status-label">Target version</span>+ <code className="migration-status-value">+ {status.head_revision ? status.head_revision.substring(0, 12) : 'unknown'}+ </code>+ </div>+ <div className="migration-status-row">+ <span className="migration-status-label">Pending updates</span>+ <span className="migration-status-value">{pendingCount}</span>+ </div>+ </div>++ {pendingMigrations.length > 0 && (+ <div className="migration-list">+ <div className="migration-list-title">Changes to apply:</div>+ {pendingMigrations.map((m, i) => (+ <div key={i} className="migration-list-item">+ <Database size={14} />+ <code>{m.revision.substring(0, 12)}</code>+ <span>{m.description || 'Schema update'}</span>+ </div>+ ))}+ </div>+ )}++ {!isAuthenticated && (+ <div className="migration-login-section">+ <div className="wizard-step-title">Admin Login Required</div>+ <p className="wizard-step-description">+ Sign in with an admin account to apply the update.+ </p>+ <form onSubmit={handleLogin} className="migration-login-form">+ {loginError && (+ <div className="migration-error-inline">{loginError}</div>+ )}+ <input+ type="text"+ placeholder="Email or username"+ value={loginEmail}+ onChange={e => setLoginEmail(e.target.value)}+ required+ />+ <input+ type="password"+ placeholder="Password"+ value={loginPassword}+ onChange={e => setLoginPassword(e.target.value)}+ required+ />+ <button type="submit" className="btn-wizard-next" disabled={loginLoading}>+ {loginLoading ? <Loader size={16} className="spin" /> : 'Sign In'}+ </button>+ </form>+ </div>+ )}++ {isAuthenticated && !isAdmin && (+ <div className="wizard-info-banner">+ <AlertTriangle size={20} className="wizard-info-icon" />+ <p>Only admin users can apply database updates. Please sign in with an admin account.</p>+ </div>+ )}++ <div className="wizard-nav">+ <div />+ <button+ className="btn-wizard-next"+ onClick={() => setCurrentStep(2)}+ disabled={!isAuthenticated || !isAdmin}+ >+ Continue <ArrowRight size={16} />+ </button>+ </div>+ </div>+ )}++ {/* Step 2: Backup */}+ {currentStep === 2 && (+ <div className="wizard-step">+ <div className="wizard-step-title">Create Backup</div>+ <div className="wizard-step-description">+ We recommend backing up your database before applying updates.+ </div>++ <div className="wizard-info-banner">+ <Shield size={20} className="wizard-info-icon" />+ <p>+ A backup allows you to restore your database if anything goes wrong+ during the update process.+ </p>+ </div>++ {!backupResult && (+ <div className="migration-backup-actions">+ <button+ className="btn-wizard-next"+ onClick={handleBackup}+ disabled={backupLoading}+ >+ {backupLoading ? (+ <><Loader size={16} className="spin" /> Creating Backup...</>+ ) : (+ <><Download size={16} /> Create Backup</>+ )}+ </button>+ </div>+ )}++ {backupResult && backupResult.success && (+ <div className="backup-status backup-status--success">+ <CheckCircle size={20} />+ <div>+ <strong>Backup created successfully</strong>+ <code>{backupResult.path}</code>+ </div>+ </div>+ )}++ {backupResult && !backupResult.success && (+ <div className="backup-status backup-status--error">+ <XCircle size={20} />+ <div>+ <strong>Backup failed</strong>+ <span>{backupResult.error}</span>+ </div>+ </div>+ )}++ <div className="wizard-nav">+ <button className="btn-wizard-prev" onClick={() => setCurrentStep(1)}>+ Back+ </button>+ <div className="migration-nav-right">+ {!backupResult?.success && (+ <button+ className="btn-text-link"+ onClick={() => setCurrentStep(3)}+ >+ Skip backup+ </button>+ )}+ <button+ className="btn-wizard-next"+ onClick={() => setCurrentStep(3)}+ disabled={!backupResult?.success}+ >+ Continue <ArrowRight size={16} />+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Step 3: Apply */}+ {currentStep === 3 && (+ <div className="wizard-step">+ <div className="wizard-step-title">Apply Updates</div>+ <div className="wizard-step-description">+ {applyLoading+ ? 'Applying database updates. Please do not close this page...'+ : `Ready to apply ${pendingCount} database update${pendingCount !== 1 ? 's' : ''}.`+ }+ </div>++ {!applyLoading && !applyError && (+ <div className="migration-apply-actions">+ <button className="btn-wizard-next" onClick={handleApply}>+ <Database size={16} /> Apply Updates+ </button>+ </div>+ )}++ {applyLoading && (+ <div className="migration-progress">+ <Loader size={32} className="spin" />+ <span>Updating database schema...</span>+ </div>+ )}++ {applyError && (+ <div className="migration-error">+ <XCircle size={20} />+ <div>+ <strong>Update failed</strong>+ <span>{applyError}</span>+ </div>+ <button className="btn-wizard-prev" onClick={handleApply}>+ <RotateCcw size={14} /> Retry+ </button>+ </div>+ )}++ {!applyLoading && (+ <div className="wizard-nav">+ <button className="btn-wizard-prev" onClick={() => setCurrentStep(2)}>+ Back+ </button>+ <div />+ </div>+ )}+ </div>+ )}++ {/* Step 4: Done */}+ {currentStep === 4 && (+ <div className="wizard-step">+ <div className="migration-success">+ <CheckCircle size={48} />+ <h2>Database Updated Successfully</h2>+ <p>+ All migrations have been applied.+ {migrationStatus?.current_revision && (+ <> Now at revision <code>{migrationStatus.current_revision.substring(0, 12)}</code>.</>+ )}+ </p>+ </div>++ <div className="wizard-nav">+ <div />+ <button className="btn-wizard-next" onClick={handleFinish}>+ Continue to ServerKit <ArrowRight size={16} />+ </button>+ </div>+ </div>+ )}+ </div>+ </div>+ );+};++export default DatabaseMigration;diff --git a/frontend/src/pages/Login.jsx b/frontend/src/pages/Login.jsxindex 58affc30..42e6d7f6 100644--- a/frontend/src/pages/Login.jsx+++ b/frontend/src/pages/Login.jsx@@ -1,8 +1,9 @@import React, { useState, useRef, useEffect } from 'react';-import { useNavigate, Link } from 'react-router-dom';+import { useNavigate, Link, useLocation } from 'react-router-dom';import { useAuth } from '../contexts/AuthContext';import api from '../services/api';-import ServerKitLogo from '../assets/ServerKitLogo.svg';+import SSOProviderIcon from '../components/SSOProviderIcon';+import ServerKitLogo from '../components/ServerKitLogo';const Login = () => {const [email, setEmail] = useState('');@@ -17,12 +18,35 @@ const Login = () => {const [useBackupCode, setUseBackupCode] = useState(false);const [backupCode, setBackupCode] = useState('');- const { login, setUser, setTokens, registrationEnabled } = useAuth();+ const { login, setUser, setTokens, registrationEnabled, ssoProviders, passwordLoginEnabled } = useAuth();const navigate = useNavigate();+ const location = useLocation();+ const [ssoLoading, setSsoLoading] = useState(null);// Refs for TOTP input fieldsconst inputRefs = useRef([]);+ // Handle incoming 2FA state from SSO callback+ useEffect(() => {+ if (location.state?.requires2FA) {+ setRequires2FA(true);+ setTempToken(location.state.tempToken);+ }+ }, [location.state]);++ async function handleSSOLogin(provider) {+ setSsoLoading(provider);+ setError('');+ try {+ const redirectUri = `${window.location.origin}/login/callback/${provider}`;+ const { auth_url } = await api.startSSOAuth(provider, redirectUri);+ window.location.href = auth_url;+ } catch (err) {+ setError(err.message || `Failed to start ${provider} login`);+ setSsoLoading(null);+ }+ }+async function handleSubmit(e) {e.preventDefault();setError('');@@ -223,7 +247,7 @@ const Login = () => {<div className="auth-card"><div className="auth-header"><div className="brand-logo">- <img src={ServerKitLogo} alt="ServerKit" width="40" height="40" />+ <ServerKitLogo width={40} height={40} /></div><h1>ServerKit</h1><p>Sign in to your account</p>@@ -231,40 +255,64 @@ const Login = () => {{error && <div className="error-message">{error}</div>}- <form onSubmit={handleSubmit}>- <div className="form-group">- <label htmlFor="email">Username or Email</label>- <input- type="text"- id="email"- value={email}- onChange={(e) => setEmail(e.target.value)}- placeholder="admin or [email protected]"- required- autoComplete="username"- />+ {ssoProviders && ssoProviders.length > 0 && (+ <div className="sso-providers">+ {ssoProviders.map(p => (+ <button+ key={p.id}+ className={`btn-sso btn-sso--${p.id}`}+ onClick={() => handleSSOLogin(p.id)}+ disabled={ssoLoading !== null}+ >+ <SSOProviderIcon provider={p.id} />+ {ssoLoading === p.id ? 'Redirecting...' : `Continue with ${p.name}`}+ </button>+ ))}</div>+ )}- <div className="form-group">- <label htmlFor="password">Password</label>- <input- type="password"- id="password"- value={password}- onChange={(e) => setPassword(e.target.value)}- placeholder="Enter your password"- required- />+ {ssoProviders && ssoProviders.length > 0 && passwordLoginEnabled && (+ <div className="sso-divider">+ <span>or</span></div>+ )}++ {passwordLoginEnabled && (+ <form onSubmit={handleSubmit}>+ <div className="form-group">+ <label htmlFor="email">Username or Email</label>+ <input+ type="text"+ id="email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ placeholder="admin or [email protected]"+ required+ autoComplete="username"+ />+ </div>++ <div className="form-group">+ <label htmlFor="password">Password</label>+ <input+ type="password"+ id="password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder="Enter your password"+ required+ />+ </div>- <button type="submit" className="btn btn-primary btn-full" disabled={loading}>- {loading ? 'Signing in...' : 'Sign In'}- </button>- </form>+ <button type="submit" className="btn btn-primary btn-full" disabled={loading}>+ {loading ? 'Signing in...' : 'Sign In'}+ </button>+ </form>+ )}- {registrationEnabled && (+ {registrationEnabled && passwordLoginEnabled && (<p className="auth-footer">- Don't have an account? <Link to="/register">Create one</Link>+ Don't have an account? <Link to="/register">Create one</Link></p>)}</div>diff --git a/frontend/src/pages/Register.jsx b/frontend/src/pages/Register.jsxindex 1eef052d..65ce77d7 100644--- a/frontend/src/pages/Register.jsx+++ b/frontend/src/pages/Register.jsx@@ -1,7 +1,7 @@import React, { useState } from 'react';import { useNavigate, Link } from 'react-router-dom';import { useAuth } from '../contexts/AuthContext';-import ServerKitLogo from '../assets/ServerKitLogo.svg';+import ServerKitLogo from '../components/ServerKitLogo';const Register = () => {const [email, setEmail] = useState('');@@ -44,7 +44,7 @@ const Register = () => {<div className="auth-card"><div className="auth-header"><div className="brand-logo">- <img src={ServerKitLogo} alt="ServerKit" width="40" height="40" />+ <ServerKitLogo width={40} height={40} /></div><h1>ServerKit</h1><p>Create your account</p>diff --git a/frontend/src/pages/SSOCallback.jsx b/frontend/src/pages/SSOCallback.jsxnew file mode 100644index 00000000..936592fa--- /dev/null+++ b/frontend/src/pages/SSOCallback.jsx@@ -0,0 +1,80 @@+import React, { useEffect, useState } from 'react';+import { useParams, useNavigate, useSearchParams, Link } from 'react-router-dom';+import { useAuth } from '../contexts/AuthContext';+import api from '../services/api';+import { Loader } from 'lucide-react';++const SSOCallback = () => {+ const { provider } = useParams();+ const [searchParams] = useSearchParams();+ const navigate = useNavigate();+ const { setUser } = useAuth();+ const [error, setError] = useState('');++ useEffect(() => {+ const code = searchParams.get('code');+ const state = searchParams.get('state');+ const redirectUri = `${window.location.origin}/login/callback/${provider}`;++ if (!code || !state) {+ setError('Missing authorization code or state parameter.');+ return;+ }++ completeAuth(code, state, redirectUri);+ }, []);++ async function completeAuth(code, state, redirectUri) {+ try {+ const response = await api.completeSSOAuth(provider, code, state, redirectUri);++ if (response.requires_2fa) {+ // Redirect to login page with 2FA state+ navigate('/login', {+ state: {+ requires2FA: true,+ tempToken: response.temp_token,+ }+ });+ return;+ }++ setUser(response.user);+ navigate('/');+ } catch (err) {+ setError(err.message || 'SSO authentication failed');+ }+ }++ if (error) {+ return (+ <div className="auth-container">+ <div className="auth-card">+ <div className="auth-header">+ <h1>Authentication Failed</h1>+ <p className="error-message">{error}</p>+ </div>+ <Link to="/login" className="btn btn-primary btn-full">+ Back to Login+ </Link>+ </div>+ </div>+ );+ }++ return (+ <div className="auth-container">+ <div className="auth-card">+ <div className="auth-header">+ <div className="sso-loading">+ <Loader size={32} className="spinning" />+ </div>+ <h1>Signing you in...</h1>+ <p>Completing authentication with {provider}</p>+ </div>+ </div>+ </div>+ );+};++export default SSOCallback;diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsxindex 614736c8..c3991049 100644--- a/frontend/src/pages/Settings.jsx+++ b/frontend/src/pages/Settings.jsx@@ -1,4 +1,4 @@-import React, { useState, useEffect } from 'react';+import React, { useState, useEffect, useRef } from 'react';import useTabParam from '../hooks/useTabParam';import { useAuth } from '../contexts/AuthContext';import { useTheme } from '../contexts/ThemeContext';@@ -6,6 +6,9 @@ import useDashboardLayout from '../hooks/useDashboardLayout';import api from '../services/api';import UsersTab from '../components/settings/UsersTab';import AuditLogTab from '../components/settings/AuditLogTab';+import SSOConfigTab from '../components/settings/SSOConfigTab';+import MigrationHistoryTab from '../components/settings/MigrationHistoryTab';+import SSOProviderIcon from '../components/SSOProviderIcon';import {Github, FileText, HelpCircle, MessageSquare, Bug, Check, Download, CheckCircle,RefreshCw, ExternalLink, Star, X, Code, Search, Container, Globe, BarChart3,@@ -16,11 +19,11 @@ import {Radio, Zap, MemoryStick, Monitor, Sun, Moon, ChevronRight, ChevronUp, LogOut,Loader, RotateCcw, FolderOpen, Layout, Palette, Camera, Newspaper, TrendingUp,Sparkles, ArrowUpCircle, AlertCircle, XCircle, GitCompare, GitCommit, Rocket,- Minus, Unlock, ArrowDownLeft, ArrowUpRight+ Minus, Unlock, ArrowDownLeft, ArrowUpRight, Upload, Type} from 'lucide-react';-import ServerKitLogo from '../assets/ServerKitLogo.svg';+import ServerKitLogo from '../components/ServerKitLogo';-const VALID_TABS = ['profile', 'security', 'appearance', 'notifications', 'system', 'users', 'audit', 'site', 'developer', 'about'];+const VALID_TABS = ['profile', 'security', 'appearance', 'notifications', 'system', 'users', 'audit', 'site', 'sso', 'migrations', 'developer', 'about'];const Settings = () => {const [activeTab, setActiveTab] = useTabParam('/settings', VALID_TABS);@@ -142,6 +145,24 @@ const Settings = () => {</svg>Site Settings</button>+ <button+ className={`settings-nav-item ${activeTab === 'sso' ? 'active' : ''}`}+ onClick={() => setActiveTab('sso')}+ >+ <svg viewBox="0 0 24 24" width="18" height="18">+ <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>+ <polyline points="10 17 15 12 10 7"/>+ <line x1="15" y1="12" x2="3" y2="12"/>+ </svg>+ SSO+ </button>+ <button+ className={`settings-nav-item ${activeTab === 'migrations' ? 'active' : ''}`}+ onClick={() => setActiveTab('migrations')}+ >+ <Database size={18} />+ Migrations+ </button></>)}{devMode && isAdmin && (@@ -178,6 +199,8 @@ const Settings = () => {{activeTab === 'users' && isAdmin && <UsersTab />}{activeTab === 'audit' && isAdmin && <AuditLogTab />}{activeTab === 'site' && isAdmin && <SiteSettings onDevModeChange={setDevMode} />}+ {activeTab === 'sso' && isAdmin && <SSOConfigTab />}+ {activeTab === 'migrations' && isAdmin && <MigrationHistoryTab />}{activeTab === 'developer' && devMode && isAdmin && <IconReference />}{activeTab === 'about' && <AboutSection />}</div>@@ -279,6 +302,112 @@ const ProfileSettings = () => {);};+const LinkedAccounts = () => {+ const { ssoProviders } = useAuth();+ const [identities, setIdentities] = useState([]);+ const [loading, setLoading] = useState(true);+ const [unlinking, setUnlinking] = useState(null);+ const [linkingProvider, setLinkingProvider] = useState(null);+ const [error, setError] = useState('');++ useEffect(() => {+ loadIdentities();+ }, []);++ async function loadIdentities() {+ try {+ const data = await api.getSSOIdentities();+ setIdentities(data.identities || []);+ } catch (err) {+ // SSO may not be configured; silently handle+ } finally {+ setLoading(false);+ }+ }++ async function handleUnlink(provider) {+ setUnlinking(provider);+ setError('');+ try {+ await api.unlinkSSOProvider(provider);+ await loadIdentities();+ } catch (err) {+ setError(err.message);+ } finally {+ setUnlinking(null);+ }+ }++ async function handleLink(provider) {+ setLinkingProvider(provider);+ setError('');+ try {+ const redirectUri = `${window.location.origin}/login/callback/${provider}`;+ const { auth_url } = await api.startSSOAuth(provider, redirectUri);+ window.location.href = auth_url;+ } catch (err) {+ setError(err.message);+ setLinkingProvider(null);+ }+ }++ // Only show if SSO is configured+ if (loading || (!ssoProviders?.length && !identities.length)) {+ return null;+ }++ const linkedProviderIds = identities.map(i => i.provider);+ const availableToLink = (ssoProviders || []).filter(p => !linkedProviderIds.includes(p.id));++ return (+ <div className="settings-card">+ <h3>Linked Accounts</h3>+ <p className="text-secondary">Connect external identity providers to your account</p>++ {error && <div className="alert alert-danger">{error}</div>}++ {identities.length > 0 && (+ <div className="linked-accounts-list">+ {identities.map(identity => (+ <div key={identity.id} className="linked-account">+ <div className="linked-account__info">+ <SSOProviderIcon provider={identity.provider} />+ <div>+ <span className="linked-account__provider">{identity.provider}</span>+ <span className="linked-account__email">{identity.provider_email}</span>+ </div>+ </div>+ <button+ className="btn btn-sm btn-danger"+ onClick={() => handleUnlink(identity.provider)}+ disabled={unlinking === identity.provider}+ >+ {unlinking === identity.provider ? 'Unlinking...' : 'Unlink'}+ </button>+ </div>+ ))}+ </div>+ )}++ {availableToLink.length > 0 && (+ <div className="linked-accounts-available">+ {availableToLink.map(p => (+ <button+ key={p.id}+ className="btn btn-secondary btn-sm"+ onClick={() => handleLink(p.id)}+ disabled={linkingProvider === p.id}+ >+ <SSOProviderIcon provider={p.id} />+ {linkingProvider === p.id ? 'Redirecting...' : `Link ${p.name}`}+ </button>+ ))}+ </div>+ )}+ </div>+ );+};+const SecuritySettings = () => {const { updateUser, user } = useAuth();const [formData, setFormData] = useState({@@ -591,6 +720,9 @@ Keep these codes in a safe place.`;</div></div>+ {/* Linked Accounts */}+ <LinkedAccounts />+{/* 2FA Setup Modal */}{showSetupModal && setupData && (<div className="modal-overlay" onClick={() => setShowSetupModal(false)}>@@ -796,9 +928,16 @@ const ACCENT_PRESETS = [{ label: 'Cyan', color: '#06b6d4' },];+const WHITELABEL_MODES = [+ { id: 'image_text', label: 'Logo + Text', icon: Layers, desc: 'Mini logo with brand name' },+ { id: 'image_full', label: 'Full-width Logo', icon: Image, desc: 'Banner image only' },+ { id: 'text_only', label: 'Text Only', icon: Type, desc: 'Just the brand name' },+];+const AppearanceSettings = () => {- const { theme, setTheme, accentColor, setAccentColor } = useTheme();+ const { theme, setTheme, accentColor, setAccentColor, whiteLabel, setWhiteLabel } = useTheme();const { widgets, toggleWidget, moveWidget, resetLayout } = useDashboardLayout();+ const logoInputRef = useRef(null);return (<div className="settings-section">@@ -925,6 +1064,158 @@ const AppearanceSettings = () => {Reset to defaults</button></div>++ <div className="settings-card">+ <h3>Custom Branding</h3>+ <p>Replace the default ServerKit branding in the sidebar with your own</p>++ <div className="settings-row">+ <div className="settings-label">+ <span>Enable custom branding</span>+ <span className="settings-hint">Replaces the sidebar logo, name, and GitHub star link</span>+ </div>+ <div className="settings-control">+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={whiteLabel.enabled}+ onChange={(e) => setWhiteLabel({ enabled: e.target.checked })}+ />+ <span className="toggle-slider"></span>+ </label>+ </div>+ </div>++ {whiteLabel.enabled && (+ <>+ <div className="whitelabel-modes">+ {WHITELABEL_MODES.map(({ id, label, icon: Icon, desc }) => (+ <button+ key={id}+ className={`whitelabel-mode${whiteLabel.mode === id ? ' active' : ''}`}+ onClick={() => setWhiteLabel({ mode: id })}+ >+ <Icon size={20} />+ <span className="whitelabel-mode__label">{label}</span>+ <span className="whitelabel-mode__desc">{desc}</span>+ </button>+ ))}+ </div>++ <div className="whitelabel-fields">+ {whiteLabel.mode !== 'image_full' && (+ <div className="form-group">+ <label>Brand Name</label>+ <input+ type="text"+ value={whiteLabel.brandName}+ onChange={(e) => setWhiteLabel({ brandName: e.target.value })}+ placeholder="My Brand"+ maxLength={30}+ />+ </div>+ )}++ {whiteLabel.mode !== 'text_only' && (+ <div className="form-group">+ <label>Logo Image</label>+ <div className="whitelabel-upload" onClick={() => logoInputRef.current?.click()}>+ {whiteLabel.logoData ? (+ <div className="whitelabel-logo-preview">+ <img src={whiteLabel.logoData} alt="Logo preview" />+ <button+ className="btn btn-secondary btn-sm"+ onClick={(e) => { e.stopPropagation(); setWhiteLabel({ logoData: '' }); }}+ >+ <X size={12} /> Remove+ </button>+ </div>+ ) : (+ <div className="whitelabel-upload__placeholder">+ <Upload size={20} />+ <span>Click to upload logo</span>+ <span className="whitelabel-upload__hint">PNG, JPG, SVG — max 200KB</span>+ </div>+ )}+ <input+ ref={logoInputRef}+ type="file"+ accept="image/png,image/jpeg,image/svg+xml,image/webp"+ style={{ display: 'none' }}+ onChange={(e) => {+ const file = e.target.files?.[0];+ if (!file) return;+ if (file.size > 200 * 1024) {+ alert('Image must be under 200KB');+ return;+ }+ const reader = new FileReader();+ reader.onload = (ev) => setWhiteLabel({ logoData: ev.target.result });+ reader.readAsDataURL(file);+ e.target.value = '';+ }}+ />+ </div>+ </div>+ )}+ </div>++ <div className="whitelabel-preview">+ <span className="whitelabel-preview__label">Preview</span>+ <div className="whitelabel-preview__box">+ {whiteLabel.mode === 'image_full' ? (+ <div className="brand-custom-banner">+ {whiteLabel.logoData ? (+ <img src={whiteLabel.logoData} alt="Preview" />+ ) : (+ <Layers size={24} />+ )}+ </div>+ ) : whiteLabel.mode === 'text_only' ? (+ <span className="brand-custom-text">+ {whiteLabel.brandName || 'Brand'}+ </span>+ ) : (+ <>+ <div className="brand-custom-logo">+ {whiteLabel.logoData ? (+ <img src={whiteLabel.logoData} alt="Preview" />+ ) : (+ <Layers size={16} />+ )}+ </div>+ <span className="brand-custom-text">+ {whiteLabel.brandName || 'Brand'}+ </span>+ </>+ )}+ </div>+ </div>++ <div className="whitelabel-star-prompt">+ <div className="star-icon">+ <Star size={22} />+ </div>+ <div className="star-content">+ <h4>Support ServerKit</h4>+ <p>+ By using custom branding, the GitHub star link is hidden from the sidebar.+ If ServerKit is useful to you, please consider starring the project — it helps the community grow!+ </p>+ <a+ href="https://github.com/jhd3197/ServerKit"+ target="_blank"+ rel="noopener noreferrer"+ className="btn btn-primary btn-sm"+ >+ <Star size={14} />+ Star on GitHub+ </a>+ </div>+ </div>+ </>+ )}+ </div></div>);};@@ -1893,7 +2184,7 @@ const AboutSection = () => {<div className="about-card"><div className="about-logo">- <img src={ServerKitLogo} alt="ServerKit Logo" width="64" height="64" />+ <ServerKitLogo width={64} height={64} /></div><h3>ServerKit</h3><p className="version">Version {version}</p>diff --git a/frontend/src/pages/Setup.jsx b/frontend/src/pages/Setup.jsxindex 1be6ae40..8a324953 100644--- a/frontend/src/pages/Setup.jsx+++ b/frontend/src/pages/Setup.jsx@@ -2,7 +2,7 @@ import React, { useState, useEffect } from 'react';import { useNavigate } from 'react-router-dom';import { useAuth } from '../contexts/AuthContext';import { Check, ArrowLeft } from 'lucide-react';-import ServerKitLogo from '../assets/ServerKitLogo.svg';+import ServerKitLogo from '../components/ServerKitLogo';import SetupStepAccount from '../components/setup/SetupStepAccount';import SetupStepIntent from '../components/setup/SetupStepIntent';import SetupStepTier from '../components/setup/SetupStepTier';@@ -116,13 +116,7 @@ const Setup = () => {<div className="setup-wizard"><div className="wizard-card"><div className="wizard-header">- <img- className="wizard-logo"- src={ServerKitLogo}- alt="ServerKit"- width="48"- height="48"- />+ <ServerKitLogo className="wizard-logo" width={48} height={48} /><h1>Welcome to ServerKit</h1><p>Let's get your server ready</p></div>diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 73147a17..75ccd0c9 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -3037,6 +3037,82 @@ class ApiService {async getMailLogs(lines = 100) {return this.request(`/email/logs?lines=${lines}`);}++ // ==================== SSO / OAuth ====================++ async getSSOProviders() {+ return this.request('/sso/providers');+ }++ async startSSOAuth(provider, redirectUri) {+ return this.request(`/sso/authorize/${provider}?redirect_uri=${encodeURIComponent(redirectUri)}`);+ }++ async completeSSOAuth(provider, code, state, redirectUri) {+ const data = await this.request(`/sso/callback/${provider}`, {+ method: 'POST',+ body: { code, state, redirect_uri: redirectUri },+ });+ if (data.access_token) {+ this.setTokens(data.access_token, data.refresh_token);+ }+ return data;+ }++ async getSSOIdentities() {+ return this.request('/sso/identities');+ }++ async linkSSOProvider(provider, code, state, redirectUri) {+ return this.request(`/sso/link/${provider}`, {+ method: 'POST',+ body: { code, state, redirect_uri: redirectUri },+ });+ }++ async unlinkSSOProvider(provider) {+ return this.request(`/sso/link/${provider}`, { method: 'DELETE' });+ }++ // SSO Admin+ async getSSOConfig() {+ return this.request('/sso/admin/config');+ }++ async updateSSOProviderConfig(provider, config) {+ return this.request(`/sso/admin/config/${provider}`, {+ method: 'PUT',+ body: config,+ });+ }++ async testSSOProvider(provider) {+ return this.request(`/sso/admin/test/${provider}`, { method: 'POST' });+ }++ async updateSSOGeneralSettings(settings) {+ return this.request('/sso/admin/general', {+ method: 'PUT',+ body: settings,+ });+ }++ // Database Migrations+ async getMigrationStatus() {+ return this.request('/migrations/status');+ }++ async createMigrationBackup() {+ return this.request('/migrations/backup', { method: 'POST' });+ }++ async applyMigrations() {+ return this.request('/migrations/apply', { method: 'POST' });+ }++ async getMigrationHistory() {+ return this.request('/migrations/history');+ }}export const api = new ApiService();diff --git a/frontend/src/styles/layout/_sidebar.less b/frontend/src/styles/layout/_sidebar.lessindex 60494c78..7d71bca2 100644--- a/frontend/src/styles/layout/_sidebar.less+++ b/frontend/src/styles/layout/_sidebar.less@@ -363,6 +363,58 @@}}+// Custom Brand (White Label)+.brand-section--custom {+ justify-content: flex-start;+}++.brand-custom-logo {+ width: 32px;+ height: 32px;+ border-radius: @radius-md;+ overflow: hidden;+ display: grid;+ place-items: center;+ flex-shrink: 0;+ color: @text-tertiary;+ background: @bg-secondary;++ img {+ width: 100%;+ height: 100%;+ object-fit: contain;+ }+}++.brand-custom-banner {+ width: 100%;+ max-height: 50px;+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ color: @text-tertiary;++ img {+ max-width: 100%;+ max-height: 50px;+ object-fit: contain;+ }+}++.brand-custom-text {+ font-size: 1.15rem;+ font-weight: @font-weight-bold;+ letter-spacing: -0.02em;+ background: linear-gradient(135deg, @text-primary 0%, #a5b4fc 100%);+ -webkit-background-clip: text;+ -webkit-text-fill-color: transparent;+ background-clip: text;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+// Scrollable Navigation Container.nav-scroll {flex: 1;diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.lessindex 7b5fbd8c..e99d1b2f 100644--- a/frontend/src/styles/main.less+++ b/frontend/src/styles/main.less@@ -80,3 +80,4 @@@import 'pages/_ssl';@import 'pages/_email';@import 'pages/_setup-wizard';+@import 'pages/_migration-wizard';diff --git a/frontend/src/styles/pages/_auth.less b/frontend/src/styles/pages/_auth.lessindex d0555353..03746039 100644--- a/frontend/src/styles/pages/_auth.less+++ b/frontend/src/styles/pages/_auth.less@@ -52,3 +52,73 @@}}}++// SSO login buttons+.sso-providers {+ display: flex;+ flex-direction: column;+ gap: @space-3;+}++.btn-sso {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: @space-3;+ width: 100%;+ padding: @space-3 @space-4;+ border: 1px solid @border-subtle;+ border-radius: @radius-lg;+ background: @bg-card;+ color: @text-primary;+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ cursor: pointer;+ transition: all @transition-fast;++ &:hover:not(:disabled) {+ border-color: @border-active;+ background: @bg-hover;+ }++ &:disabled {+ opacity: 0.6;+ cursor: not-allowed;+ }++ svg {+ flex-shrink: 0;+ }+}++.sso-divider {+ display: flex;+ align-items: center;+ gap: @space-4;+ margin: @space-6 0;+ color: @text-tertiary;+ font-size: @font-size-sm;++ &::before,+ &::after {+ content: '';+ flex: 1;+ height: 1px;+ background: @border-subtle;+ }+}++.sso-loading {+ display: flex;+ justify-content: center;+ margin-bottom: @space-4;++ .spinning {+ animation: spin 1s linear infinite;+ }+}++@keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+}diff --git a/frontend/src/styles/pages/_downloads.less b/frontend/src/styles/pages/_downloads.lessindex b3d979ba..9fea4bad 100644--- a/frontend/src/styles/pages/_downloads.less+++ b/frontend/src/styles/pages/_downloads.less@@ -74,7 +74,7 @@// Version Banner.version-banner {- background: linear-gradient(135deg, @accent-primary 0%, #4f46e5 100%);+ background: linear-gradient(135deg, var(--accent-primary) 0%, var(--accent-hover) 100%);border-radius: @radius-lg;padding: @space-6 @space-8;margin-bottom: @space-8;diff --git a/frontend/src/styles/pages/_migration-wizard.less b/frontend/src/styles/pages/_migration-wizard.lessnew file mode 100644index 00000000..62257e71--- /dev/null+++ b/frontend/src/styles/pages/_migration-wizard.less@@ -0,0 +1,315 @@+// ============================================+// MIGRATION WIZARD (Database Update)+// ============================================++.migration-wizard {+ // Extends .setup-wizard — same full-screen centered layout+}++// --------------------------------------------+// Status panel (version info)+// --------------------------------------------+.migration-status-panel {+ background: @bg-elevated;+ border: 1px solid @border-default;+ border-radius: @radius-xl;+ padding: @space-5;+ margin-bottom: @space-6;+}++.migration-status-row {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: @space-2 0;++ &:not(:last-child) {+ border-bottom: 1px solid @border-subtle;+ }+}++.migration-status-label {+ color: @text-secondary;+ font-size: @font-size-sm;+}++.migration-status-value {+ font-weight: @font-weight-semibold;+ font-size: @font-size-sm;++ code& {+ background: @bg-secondary;+ padding: 2px 8px;+ border-radius: @radius-md;+ font-family: @font-family-mono;+ }+}++// --------------------------------------------+// Migration list (pending changes)+// --------------------------------------------+.migration-list {+ margin-bottom: @space-6;+}++.migration-list-title {+ font-size: @font-size-sm;+ font-weight: @font-weight-semibold;+ color: @text-secondary;+ margin-bottom: @space-3;+}++.migration-list-item {+ display: flex;+ align-items: center;+ gap: @space-3;+ padding: @space-3 @space-4;+ background: @bg-elevated;+ border: 1px solid @border-subtle;+ border-radius: @radius-lg;+ font-size: @font-size-sm;++ &:not(:last-child) {+ margin-bottom: @space-2;+ }++ svg {+ flex-shrink: 0;+ color: @accent-primary;+ }++ code {+ font-family: @font-family-mono;+ color: @text-secondary;+ font-size: @font-size-xs;+ }++ span {+ color: @text-primary;+ }+}++// --------------------------------------------+// Login section (inline login for wizard)+// --------------------------------------------+.migration-login-section {+ margin-top: @space-6;+ padding-top: @space-6;+ border-top: 1px solid @border-default;+}++.migration-login-form {+ display: flex;+ flex-direction: column;+ gap: @space-3;+ max-width: 400px;++ input {+ width: 100%;+ padding: @space-3 @space-4;+ background: @bg-elevated;+ border: 1px solid @border-default;+ border-radius: @radius-lg;+ font-size: @font-size-base;+ color: @text-primary;+ .transition(border-color);++ &::placeholder {+ color: @text-tertiary;+ }++ &:focus {+ outline: none;+ border-color: @accent-primary;+ }+ }++ .btn-wizard-next {+ align-self: flex-start;+ }+}++.migration-error-inline {+ padding: @space-3;+ background: @danger-bg;+ border: 1px solid @danger-border;+ border-radius: @radius-lg;+ color: @danger;+ font-size: @font-size-sm;+}++// --------------------------------------------+// Backup status+// --------------------------------------------+.migration-backup-actions {+ margin-bottom: @space-6;+}++.backup-status {+ display: flex;+ align-items: flex-start;+ gap: @space-3;+ padding: @space-4;+ border-radius: @radius-lg;+ margin-bottom: @space-6;++ &--success {+ background: @success-bg;+ border: 1px solid @success-border;+ color: @success;+ }++ &--error {+ background: @danger-bg;+ border: 1px solid @danger-border;+ color: @danger;+ }++ svg {+ flex-shrink: 0;+ margin-top: 2px;+ }++ strong {+ display: block;+ margin-bottom: @space-1;+ }++ code {+ display: block;+ font-size: @font-size-xs;+ color: @text-secondary;+ word-break: break-all;+ font-family: @font-family-mono;+ }++ span {+ font-size: @font-size-sm;+ }+}++// --------------------------------------------+// Apply / progress+// --------------------------------------------+.migration-apply-actions {+ text-align: center;+ padding: @space-6 0;+}++.migration-progress {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: @space-4;+ padding: @space-8 0;+ color: @text-secondary;++ svg {+ color: @accent-primary;+ }++ span {+ font-size: @font-size-base;+ }+}++// --------------------------------------------+// Result states+// --------------------------------------------+.migration-success {+ text-align: center;+ padding: @space-8 0;++ svg {+ color: @success;+ margin-bottom: @space-4;+ }++ h2 {+ font-size: @font-size-xl;+ font-weight: @font-weight-bold;+ margin-bottom: @space-2;+ }++ p {+ color: @text-secondary;+ font-size: @font-size-base;+ }++ code {+ background: @bg-secondary;+ padding: 2px 8px;+ border-radius: @radius-md;+ font-family: @font-family-mono;+ font-size: @font-size-sm;+ }+}++.migration-error {+ display: flex;+ align-items: flex-start;+ gap: @space-3;+ padding: @space-4;+ background: @danger-bg;+ border: 1px solid @danger-border;+ border-radius: @radius-lg;+ margin-bottom: @space-6;++ > svg {+ flex-shrink: 0;+ color: @danger;+ margin-top: 2px;+ }++ strong {+ display: block;+ color: @danger;+ margin-bottom: @space-1;+ }++ span {+ display: block;+ font-size: @font-size-sm;+ color: @text-secondary;+ }++ .btn-wizard-prev {+ margin-left: auto;+ flex-shrink: 0;+ align-self: center;+ }+}++// --------------------------------------------+// Nav helpers+// --------------------------------------------+.migration-nav-right {+ display: flex;+ align-items: center;+ gap: @space-4;+}++.btn-text-link {+ background: none;+ border: none;+ color: @text-tertiary;+ font-size: @font-size-sm;+ cursor: pointer;+ padding: 0;+ text-decoration: underline;+ .transition(color);++ &:hover {+ color: @text-secondary;+ }+}++// Spin animation for loader+@keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+}++.spin {+ animation: spin 1s linear infinite;+}diff --git a/frontend/src/styles/pages/_settings.less b/frontend/src/styles/pages/_settings.lessindex 508dcc47..ef920641 100644--- a/frontend/src/styles/pages/_settings.less+++ b/frontend/src/styles/pages/_settings.less@@ -186,7 +186,7 @@margin-bottom: @space-2;}- input, select, textarea {+ input:not([type="checkbox"]):not([type="radio"]), select, textarea {width: 100%;padding: @space-3;background: @bg-hover;@@ -511,6 +511,28 @@}}+// Toggle Label (checkbox + text inline)+.toggle-label {+ display: flex !important;+ align-items: center;+ gap: @space-3;+ cursor: pointer;++ input[type="checkbox"] {+ width: 18px;+ height: 18px;+ accent-color: @accent-primary;+ cursor: pointer;+ flex-shrink: 0;+ }++ span {+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ color: @text-primary;+ }+}+// System Info Grid.system-info-grid {display: grid;@@ -1133,3 +1155,343 @@cursor: not-allowed;}}++// ============================================+// WHITE LABEL / CUSTOM BRANDING+// ============================================++.whitelabel-modes {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: @space-3;+ margin-top: @space-4;++ @media (max-width: @breakpoint-md) {+ grid-template-columns: 1fr;+ }+}++.whitelabel-mode {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: @space-2;+ padding: @space-4;+ background: transparent;+ border: 2px solid @border-subtle;+ border-radius: @radius-lg;+ cursor: pointer;+ transition: all @transition-fast;+ text-align: center;+ color: @text-secondary;++ svg {+ opacity: 0.7;+ }++ &:hover {+ border-color: @border-active;+ }++ &.active {+ border-color: @accent-primary;+ background: fade(@accent-primary-raw, 5%);+ color: @text-primary;++ svg {+ color: @accent-primary;+ opacity: 1;+ }+ }++ .whitelabel-mode__label {+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ color: @text-primary;+ }++ .whitelabel-mode__desc {+ font-size: @font-size-xs;+ color: @text-tertiary;+ }+}++.whitelabel-fields {+ margin-top: @space-4;+ display: flex;+ flex-direction: column;+ gap: @space-4;++ .form-group {+ label {+ display: block;+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ color: @text-secondary;+ margin-bottom: @space-2;+ }++ input[type="text"] {+ width: 100%;+ max-width: 320px;+ padding: @space-3;+ background: @bg-hover;+ border: 1px solid @border-subtle;+ border-radius: @radius-md;+ color: @text-primary;+ font-size: @font-size-sm;+ transition: border-color @transition-fast;++ &:focus {+ outline: none;+ border-color: @accent-primary;+ }+ }+ }+}++.whitelabel-upload {+ border: 2px dashed @border-subtle;+ border-radius: @radius-lg;+ padding: @space-5;+ cursor: pointer;+ transition: all @transition-fast;+ text-align: center;++ &:hover {+ border-color: @accent-primary;+ background: fade(@accent-primary-raw, 3%);+ }++ .whitelabel-upload__placeholder {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: @space-2;+ color: @text-tertiary;++ svg {+ opacity: 0.5;+ }++ span {+ font-size: @font-size-sm;+ }+ }++ .whitelabel-upload__hint {+ font-size: @font-size-xs !important;+ color: @text-tertiary;+ opacity: 0.7;+ }+}++.whitelabel-logo-preview {+ display: flex;+ align-items: center;+ gap: @space-4;+ justify-content: center;++ img {+ width: 48px;+ height: 48px;+ object-fit: contain;+ border-radius: @radius-md;+ border: 1px solid @border-subtle;+ background: @bg-hover;+ padding: @space-1;+ }+}++.whitelabel-preview {+ margin-top: @space-4;++ .whitelabel-preview__label {+ display: block;+ font-size: @font-size-xs;+ font-weight: @font-weight-semibold;+ color: @text-tertiary;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ margin-bottom: @space-2;+ }++ .whitelabel-preview__box {+ display: flex;+ align-items: center;+ gap: 10px;+ height: 70px;+ padding: 0 @space-4;+ background: @bg-body;+ border: 1px solid @border-subtle;+ border-radius: @radius-lg;+ }+}++.whitelabel-star-prompt {+ margin-top: @space-4;+ background: linear-gradient(135deg, @accent-glow 0%, fade(@accent-primary-raw, 8%) 100%);+ border: 1px solid fade(@accent-primary-raw, 30%);+ border-radius: @radius-lg;+ padding: @space-5;+ display: flex;+ align-items: flex-start;+ gap: @space-4;++ .star-icon {+ flex-shrink: 0;+ width: 44px;+ height: 44px;+ background: linear-gradient(135deg, @warning 0%, darken(@warning, 10%) 100%);+ border-radius: @radius-lg;+ display: flex;+ align-items: center;+ justify-content: center;+ color: white;+ }++ .star-content {+ flex: 1;++ h4 {+ margin: 0 0 @space-2;+ font-size: @font-size-md;+ font-weight: @font-weight-semibold;+ }++ p {+ margin: 0 0 @space-3;+ font-size: @font-size-sm;+ color: @text-secondary;+ line-height: @line-height-relaxed;+ }++ .btn {+ display: inline-flex;+ align-items: center;+ gap: @space-2;+ }+ }++ @media (max-width: @breakpoint-sm) {+ flex-direction: column;+ }+}++// ============================================+// SSO CONFIG & LINKED ACCOUNTS+// ============================================++.sso-config {+ display: flex;+ flex-direction: column;+ gap: @space-5;+}++.sso-provider-config {+ border: 1px solid @border-subtle;++ &--enabled {+ border-color: @accent-primary;+ }++ .sso-provider-config__header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ cursor: pointer;+ padding: @space-4;++ &:hover {+ background: @bg-hover;+ }+ }++ .sso-provider-config__title {+ display: flex;+ align-items: center;+ gap: @space-3;++ h3 {+ margin: 0;+ }+ }++ .sso-provider-config__status {+ font-size: @font-size-xs;+ padding: @space-1 @space-2;+ border-radius: @radius-full;+ font-weight: @font-weight-medium;++ &--active {+ background: fade(@color-success, 15%);+ color: @color-success;+ }+ }++ .sso-provider-config__body {+ padding: @space-1 @space-4 @space-4;+ border-top: 1px solid @border-subtle;+ display: flex;+ flex-direction: column;+ gap: @space-4;+ }++ .sso-provider-config__actions {+ display: flex;+ gap: @space-3;+ padding-top: @space-2;+ }+}++// Linked accounts (Security tab)+.linked-accounts-list {+ display: flex;+ flex-direction: column;+ gap: @space-3;+ margin: @space-4 0;+}++.linked-account {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: @space-3;+ background: @bg-secondary;+ border-radius: @radius-lg;+ border: 1px solid @border-subtle;++ .linked-account__info {+ display: flex;+ align-items: center;+ gap: @space-3;++ div {+ display: flex;+ flex-direction: column;+ }+ }++ .linked-account__provider {+ font-weight: @font-weight-medium;+ text-transform: capitalize;+ }++ .linked-account__email {+ font-size: @font-size-sm;+ color: @text-secondary;+ }+}++.linked-accounts-available {+ display: flex;+ gap: @space-3;+ margin-top: @space-3;+ flex-wrap: wrap;++ .btn {+ display: flex;+ align-items: center;+ gap: @space-2;+ }+}