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
chore: normalize line endings to LF per .gitattributes
Juan Denis8aa760bf0207
diff --git a/ROADMAP.md b/ROADMAP.mdindex 8983bf31..62757f5a 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -1,621 +1,621 @@-# ServerKit Roadmap--This document outlines the development roadmap for ServerKit. Features are organized by phases and priority.-------## Current Version: v1.6.0 (In Development)--### Recently Completed (v1.5.0)--- **New UI & Services Page** - Integrated full Services page with detail views, metrics, logs, and shell.-- **Environment Pipeline** - Multi-environment management for WordPress (Prod/Staging/Dev) with promotion/sync.-- **Visual Infrastructure Designer** - Node-based visual canvas for stack deployment and server overview.-- **Advanced Monitoring UI** - Real-time log streaming and terminal integration in the dashboard.-- **Template Library Expansion** - Over 60+ one-click deployment templates (Immich, Authelia, Ghost, etc.).-- **Team & Permissions** - RBAC with admin/developer/viewer roles, invitations, audit logging-- **SSO & OAuth Login** - Google, GitHub, OIDC, SAML with account linking-------## Phase 1: Core Infrastructure (Completed)--- [x] Flask backend with SQLAlchemy ORM-- [x] React frontend with Vite-- [x] JWT-based authentication-- [x] Real-time WebSocket updates-- [x] System metrics (CPU, RAM, disk, network)-- [x] Docker and Docker Compose support-- [x] SQLite/PostgreSQL database support-------## Phase 2: Application Management (Completed)--- [x] PHP/WordPress application deployment-- [x] Python (Flask/Django) application support-- [x] Node.js application management with PM2-- [x] Docker container management-- [x] Environment variable management-- [x] Application start/stop/restart controls-- [x] Log viewing per application-------## Phase 3: Domain & SSL Management (Completed)--- [x] Nginx virtual host management-- [x] Domain configuration interface-- [x] Let's Encrypt SSL integration-- [x] SSL certificate auto-renewal-- [x] Redirect management (HTTP → HTTPS)-------## Phase 4: Database Management (Completed)--- [x] MySQL/MariaDB database support-- [x] PostgreSQL database support-- [x] Database creation/deletion-- [x] User management per database-- [x] Basic query interface-------## Phase 5: File & FTP Management (Completed)--- [x] Web-based file manager-- [x] File upload/download-- [x] File editing with syntax highlighting-- [x] vsftpd FTP server integration-- [x] FTP user management-------## Phase 6: Monitoring & Alerts (Completed)--- [x] Real-time system metrics-- [x] Server uptime tracking-- [x] Customizable alert thresholds-- [x] Discord webhook notifications-- [x] Slack webhook notifications-- [x] Telegram bot notifications-- [x] Generic webhook support-- [x] Alert history and logging-------## Phase 7: Security Features (Completed)--- [x] Two-factor authentication (TOTP)-- [x] Backup codes for 2FA recovery-- [x] ClamAV malware scanning-- [x] Quick scan / Full scan options-- [x] File quarantine management-- [x] File integrity monitoring-- [x] Failed login detection-- [x] Security event logging-------## Phase 8: Scheduled Tasks (Completed)--- [x] Cron job management-- [x] Visual cron expression builder-- [x] Job execution history-- [x] Enable/disable jobs-------## Phase 9: Firewall Management (Completed - Merged into Security)--- [x] UFW firewall integration-- [x] Visual rule management-- [x] Common port presets-- [x] Rule enable/disable-- [x] Consolidated into Security page for unified security management-------## Phase 10: Multi-Server Management (Completed)--**Priority: High**--- [x] Agent-based remote server monitoring (Go agent)-- [x] Centralized dashboard for multiple servers-- [x] Server grouping and tagging-- [x] Cross-server metrics comparison-- [x] Remote Docker management via agents-- [x] Server health overview-- [x] Agent WebSocket gateway-- [x] HMAC-SHA256 authentication-- [x] GitHub Actions for agent releases (Linux/Windows)-- [x] Installation scripts endpoint-- [x] Agent auto-update mechanism-- [x] Agent download page in UI-- [x] Container logs streaming for remote servers-------## Phase 11: Git Deployment (Completed)--**Priority: High**--- [x] GitHub/GitLab webhook integration-- [x] Automatic deployment on push-- [x] Branch selection for deployment-- [x] Rollback to previous deployments-- [x] Deployment history and logs-- [x] Pre/post deployment scripts-- [x] Zero-downtime deployments-------## Phase 12: Backup & Restore (Completed)--**Priority: High**--- [x] Automated database backups-- [x] File/directory backups-- [x] S3-compatible storage support-- [x] Backblaze B2 integration-- [x] Backup scheduling-- [x] One-click restore-- [x] Backup retention policies-- [x] Offsite backup verification-------## Phase 13: Email Server Management (Completed)--**Priority: Medium**--- [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-------## Phase 14: Visual Infrastructure Designer (Completed)--**Priority: High**--The visual canvas for designing and deploying entire infrastructure stacks.--- [x] Node-based Visual Canvas (`WorkflowBuilder.jsx`) using React Flow-- [x] Infrastructure component nodes (Docker, Database, Domain, Service)-- [x] Smart connection rules (link apps to DBs, domains to apps)-- [x] One-click stack deployment from the canvas-- [x] Template-based stack generation-- [x] Server overview mode (visualize existing infrastructure)-------## Phase 15: Team & Permissions (Completed)--**Priority: Medium**--- [x] Multi-user support-- [x] Role-based access control (RBAC)-- [x] Custom permission sets-- [x] Audit logging per user-- [x] Team invitations-- [x] Activity dashboard-------## Phase 16: API Enhancements (Completed)--**Priority: Medium**--- [x] API key management-- [x] Rate limiting-- [x] Webhook event subscriptions-- [x] OpenAPI/Swagger documentation-- [x] API usage analytics-------## Phase 17: Advanced Security (Completed)--**Priority: High**--- [x] Unified Security page with all security features-- [x] Firewall tab with UFW/firewalld management-- [x] Fail2ban integration-- [x] SSH key management-- [x] IP allowlist/blocklist-- [x] Brute force protection-- [x] Security audit reports-- [x] Vulnerability scanning (Lynis)-- [x] Automatic security updates (unattended-upgrades/dnf-automatic)-------## Phase 18: SSO & OAuth Login (Completed)--**Priority: High**--- [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 19: Database Migrations & Schema Versioning (Completed)--**Priority: High**--- [x] Flask-Migrate (Alembic) integration-- [x] Migration wizard UI (Completed)-- [x] CLI fallback support-------## Phase 20: New UI & Services Page (Completed)--**Priority: Critical**--Integrated full Services page with detail views, metrics, logs, shell, settings, and package management.--- [x] Services list page with status indicators and quick actions-- [x] Service detail page with tabbed interface (Metrics, Logs, Shell, Settings, Commands, Events, Packages)-- [x] Git connect modal for linking services to repositories-- [x] Gunicorn management tab for Python services-- [x] Service type detection and type-specific UI (Node, Python, PHP, Docker, etc.)-------## Phase 21: Environment Pipeline (Completed)--**Priority: High**--- [x] WordPress multi-environment pipeline (Prod/Staging/Dev)-- [x] Code and Database promotion between environments-- [x] Production syncing and environment locking-------## Phase 22: Container Logs & Monitoring UI (Completed)--**Priority: High**--- [x] Real-time log streaming via WebSocket with ANSI color support-- [x] Web-based terminal (`Terminal.jsx`) with shell access-- [x] Per-app resource usage charts (CPU, RAM)-- [x] Log search and filtering-------# Upcoming Development--The phases below are ordered by priority. Higher phases ship first.-------## Phase 23: Workflow & Automation Engine — Core (Completed)--**Priority: Critical**--Moving beyond static design to dynamic, event-driven automation. This turns ServerKit into a powerful automation hub.--- [x] **Visual Workflow Builder:** Node-based canvas with drag-and-drop nodes, connection validation, and config panels-- [x] **Cron Integration:** Schedule workflows to run on recurring intervals (e.g., "Every Sunday at 2 AM, backup all DBs and rotate logs")-- [x] **Manual Execution:** Trigger workflows on demand with optional context data-- [x] **Execution History:** Track workflow execution status, per-node results, and timestamped logs-- [x] **Script Nodes:** Custom Shell script execution nodes with output capture-- [x] **Notification Nodes:** Send alerts via configured notification channels-- [x] **One-Click Stack Deployment:** Deploy full infrastructure (databases, apps, domains) from a workflow diagram-------## Phase 24: Customizable Sidebar & Dashboard Views (Completed)--**Priority: High**--Let users personalize what they see. Not everyone runs email servers or manages Docker — the sidebar should adapt to each user's needs.--- [x] Sidebar configuration page in Settings-- [x] Preset view profiles (Full, Web Hosting, Email Admin, Docker/DevOps, Minimal)-- [x] Custom view builder — toggle individual sidebar items on/off-- [x] Per-user preference storage (saved to user profile)-------## Phase 25: Workflow Engine — Triggers & Completion (Completed)--**Priority: High**--Complete the workflow engine with proper execution logic, missing triggers, and production-grade reliability.--- [x] **DAG Execution:** Full directed acyclic graph traversal with parallel branch support (replace current linear BFS)-- [x] **Logic Node Evaluation:** If/Else condition evaluation with true/false branching-- [x] **Variable Interpolation:** Pass data between steps using `${node_id.field}` and `{{placeholder}}` syntax in node configs-- [x] **Webhook Triggers:** Register `/hooks/<webhook_id>` endpoint to fire workflows on incoming HTTP requests-- [x] **Event Triggers:** Run workflows on system events (health check failure, high CPU/memory, git push, app stopped)-- [x] **Notification Templating:** Message placeholder substitution (`${node_id.stdout}`, `{{workflow_name}}`) in notification nodes-- [x] **Execution Timeouts:** Configurable timeout per node (1–3600s) to prevent hung workflows-- [x] **Retry on Failure:** Configurable retry count (0–5) and delay per node-- [x] **Circular Dependency Detection:** Kahn's algorithm validates graph on save and before execution-- [x] **Script Sandboxing:** Timeout enforcement, output size limits, explicit `bash -c`/`python3 -c` execution-------## Phase 26: Agent Fleet Management (Completed)--**Priority: High**--Level up agent management from "connect and monitor" to full fleet control.--- [x] Agent version tracking and compatibility matrix (panel version ↔ agent version)-- [x] Push agent upgrades from the panel (single server or fleet-wide rollout)-- [x] Staged rollout support — upgrade agents in batches with health checks between waves-- [x] Agent health dashboard — connection uptime, heartbeat latency, command success rate per agent-- [x] Auto-discovery of new servers on the local network (mDNS/broadcast scan)-- [x] Agent registration approval workflow (admin must approve before agent joins fleet)-- [x] Bulk agent operations — restart, upgrade, rotate keys across selected servers-- [x] Agent changelog and release notes visible in UI-- [x] Offline agent command queue — persist commands and deliver when agent reconnects-- [x] Command retry with configurable backoff for failed/timed-out operations-- [x] Agent connection diagnostics — test connectivity, latency, firewall check from panel-------## Phase 27: Cross-Server Monitoring Dashboard (Completed)--**Priority: High**--Fleet-wide visibility — see everything at a glance and catch problems early.--- [x] Fleet overview dashboard — heatmap of all servers by CPU/memory/disk usage-- [x] Server comparison charts — overlay metrics from multiple servers on one graph-- [x] Per-server alert thresholds (CPU > 80% for 5 min → warning, > 95% → critical)-- [x] Anomaly detection — automatic baseline learning, alert on deviations-- [x] Custom metric dashboards — drag-and-drop widgets, save layouts per user-- [x] Metric correlation view — spot relationships between metrics across servers-- [x] Capacity forecasting — trend-based predictions (disk full in X days, memory growth rate)-- [x] Metrics export — Prometheus endpoint (`/metrics`), CSV download, JSON API-- [x] Grafana integration guide and pre-built dashboard templates-- [x] Fleet-wide search — find which server is running a specific container, service, or port-------## Phase 28: Agent Plugin System (Completed)--**Priority: High**--Make the agent extensible — let users add custom capabilities without modifying agent core. This is the foundation for future integrations (Android device farms, IoT fleets, custom hardware monitoring, etc.).--### Plugin Architecture-- [x] Plugin specification — standard interface (init, healthcheck, metrics, commands)-- [x] Plugin manifest format (YAML/JSON) — name, version, dependencies, capabilities, permissions-- [x] Plugin lifecycle management — install, enable, disable, uninstall, upgrade-- [x] Plugin isolation — each plugin runs in its own process/sandbox with resource limits-- [x] Plugin communication — standardized IPC between plugin and agent core--### Plugin Capabilities-- [x] Custom metrics reporters — plugins can push arbitrary metrics to the panel-- [x] Custom health checks — plugins define checks that feed into the status system-- [x] Custom commands — plugins register new command types the panel can invoke-- [x] Scheduled tasks — plugins can register periodic jobs (cron-like)-- [x] Event hooks — plugins can react to agent events (connect, disconnect, command, alert)-------## Phase 29: Server Templates & Config Sync (Completed)--**Priority: Medium**--Define what a server should look like, apply it, and detect when it drifts.--- [x] Server template builder — define expected state (packages, services, firewall rules, users, files)-- [x] Template library — save and reuse templates (e.g., "Web Server", "Database Server", "Mail Server")-- [x] Apply template to server — install packages, configure services, set firewall rules via agent-- [x] Config drift detection — periodic comparison of actual vs. expected state-- [x] Drift report UI — visual diff showing what changed and when-- [x] Auto-remediation option — automatically fix drift back to template (with approval toggle)-- [x] Template versioning — track changes to templates over time-- [x] Template inheritance — base template + role-specific overrides-- [x] Bulk apply — roll out template changes across server groups-- [x] Compliance dashboard — percentage of fleet in compliance per template-------## Phase 30: Multi-Tenancy & Workspaces (Completed)--**Priority: Medium**--Isolate servers by team, client, or project. Essential for agencies, MSPs, and larger teams.--- [x] Workspace model — isolated container for servers, users, and settings-- [x] Workspace CRUD — create, rename, archive workspaces-- [x] Server assignment — each server belongs to exactly one workspace-- [x] User workspace membership — users can belong to multiple workspaces with different roles-- [x] Workspace switching — quick-switch dropdown in the header-- [x] Per-workspace settings — notification preferences, default templates, branding-- [x] Workspace-scoped API keys — API keys restricted to a single workspace-- [x] Cross-workspace admin view — super-admin can see all workspaces and usage-- [x] Workspace usage quotas — limit servers, users, or API calls per workspace-- [x] Workspace billing integration — track resource usage per workspace for invoicing-------## Phase 31: Advanced SSL Features (Completed)--**Priority: Medium**--- [x] Certificate expiry monitoring-- [x] Wildcard SSL certificates via DNS-01 challenge-- [x] Multi-domain certificates (SAN)-- [x] Custom certificate upload (key + cert + chain)-- [x] Certificate expiry notifications (email/webhook alerts before expiration)-- [x] SSL configuration templates (modern, intermediate, legacy compatibility)-- [x] SSL health check dashboard (grade, cipher suites, protocol versions)-------## Phase 32: DNS Zone Management (Completed)--**Priority: Medium**--Full DNS record management with provider API integration.--- [x] DNS zone editor UI (A, AAAA, CNAME, MX, TXT, SRV, CAA records)-- [x] Cloudflare API integration (list/create/update/delete records)-- [x] Route53 API integration-- [x] DigitalOcean DNS integration-- [x] DNS propagation checker (query multiple nameservers)-- [x] Auto-generate recommended records for hosted services (SPF, DKIM, DMARC, MX)-- [x] DNS template presets (e.g., "standard web hosting", "email hosting")-- [x] Bulk record import/export (BIND zone file format)-------## Phase 33: Nginx Advanced Configuration (Completed)--**Priority: Medium**--Go beyond basic virtual hosts — full reverse proxy and performance configuration.--- [x] Visual reverse proxy rule builder (upstream servers, load balancing methods)-- [x] Load balancing configuration (round-robin, least connections, IP hash)-- [x] Caching rules editor (proxy cache zones, TTLs, cache bypass rules)-- [x] Rate limiting at proxy level (per-IP, per-route)-- [x] Custom location block editor with syntax validation-- [x] Header manipulation (add/remove/modify request/response headers)-- [x] Nginx config syntax check before applying changes-- [x] Config diff preview before saving-- [x] Access/error log viewer per virtual host-------## Phase 34: Status Page & Health Checks (Completed)--**Priority: Medium**--Public-facing status page and automated health monitoring.--- [x] Automated health checks (HTTP, TCP, DNS, SMTP) with configurable intervals-- [x] Public status page (standalone URL, no auth required)-- [x] Status page customization (logo, colors, custom domain)-- [x] Service grouping on status page (e.g., "Web Services", "Email", "APIs")-- [x] Incident management — create, update, resolve incidents with timeline-- [x] Uptime percentage display (24h, 7d, 30d, 90d)-- [x] Scheduled maintenance windows with advance notifications-- [x] Status page subscribers (email/webhook notifications on incidents)-- [x] Historical uptime graphs-- [x] Status badge embeds (SVG/PNG for README files)-------## Phase 35: Server Provisioning APIs (Completed)--**Priority: Medium**--Spin up and manage cloud servers directly from the panel.--- [x] DigitalOcean API integration (create/destroy/resize droplets)-- [x] Hetzner Cloud API integration-- [x] Vultr API integration-- [x] Linode/Akamai API integration-- [x] Server creation wizard (region, size, OS, SSH keys)-- [x] Auto-install ServerKit agent on provisioned servers-- [x] Server cost tracking and billing overview-- [x] Snapshot management (create/restore/delete)-- [x] One-click server cloning-- [x] Destroy server with confirmation safeguards-------## Phase 36: Performance Optimization (Completed)--**Priority: Low**--- [x] Redis caching for frequently accessed data (metrics, server status)-- [x] Database query optimization and slow query logging-- [x] Background job queue (Celery or RQ) for long-running tasks-- [x] Lazy loading for large datasets (paginated API responses)-- [x] WebSocket connection pooling and reconnection improvements-- [x] Frontend bundle optimization and code splitting-------## Phase 37: Mobile App (Completed)--**Priority: Low — v3.0+**--- [x] React Native or PWA mobile application-- [x] Push notifications for alerts and incidents-- [x] Quick actions (restart services, view stats, acknowledge alerts)-- [x] Biometric authentication (fingerprint/Face ID)-- [x] Offline mode with cached server status-------## Phase 38: Marketplace & Extensions (Completed)--**Priority: Low — v3.0+**--- [x] Plugin/extension system with API hooks-- [x] Community marketplace for plugins-- [x] Custom dashboard widgets-- [x] Theme customization (colors, layout, branding)-- [x] Extension SDK and developer documentation-------## Version Milestones--| Version | Target Features | Status |-|---------|-----------------|--------|-| v0.9.0 | Core features, 2FA, Notifications, Security | Completed |-| v1.0.0 | Production-ready stable release, DB migrations | Completed |-| v1.1.0 | Multi-server, Git deployment | Completed |-| v1.2.0 | Backups, Advanced SSL, Advanced Security | Completed |-| v1.3.0 | Email server, API enhancements | Completed |-| v1.4.0 | Team & permissions, SSO & OAuth login | Completed |-| v1.5.0 | New UI, Visual Designer, Services Page | Completed |-| v1.6.0 | Workflow triggers & completion, fleet management | Current |-| v1.7.0 | Cross-server monitoring, agent plugin system | Completed |-| v1.8.0 | Server templates, multi-tenancy | Completed |-| v1.9.0 | Advanced SSL, DNS management, Nginx config | Completed |-| v2.0.0 | Status pages, server provisioning, performance | Completed |-| v3.0.0 | Mobile app, Marketplace | Completed |-------## Contributing--Want to help? See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.--**Priority areas for contributions:**-- Agent plugin SDK and example plugins-- Fleet management and monitoring dashboard-- DNS provider integrations (Cloudflare, Route53)-- Status page and health check system-- UI/UX improvements-- Documentation-------## Feature Requests--Have a feature idea? Open an issue on GitHub with the `enhancement` label.-------<p align="center">- <strong>ServerKit Roadmap</strong><br>- Last updated: March 2026-</p>+# ServerKit Roadmap++This document outlines the development roadmap for ServerKit. Features are organized by phases and priority.++---++## Current Version: v1.6.0 (In Development)++### Recently Completed (v1.5.0)++- **New UI & Services Page** - Integrated full Services page with detail views, metrics, logs, and shell.+- **Environment Pipeline** - Multi-environment management for WordPress (Prod/Staging/Dev) with promotion/sync.+- **Visual Infrastructure Designer** - Node-based visual canvas for stack deployment and server overview.+- **Advanced Monitoring UI** - Real-time log streaming and terminal integration in the dashboard.+- **Template Library Expansion** - Over 60+ one-click deployment templates (Immich, Authelia, Ghost, etc.).+- **Team & Permissions** - RBAC with admin/developer/viewer roles, invitations, audit logging+- **SSO & OAuth Login** - Google, GitHub, OIDC, SAML with account linking++---++## Phase 1: Core Infrastructure (Completed)++- [x] Flask backend with SQLAlchemy ORM+- [x] React frontend with Vite+- [x] JWT-based authentication+- [x] Real-time WebSocket updates+- [x] System metrics (CPU, RAM, disk, network)+- [x] Docker and Docker Compose support+- [x] SQLite/PostgreSQL database support++---++## Phase 2: Application Management (Completed)++- [x] PHP/WordPress application deployment+- [x] Python (Flask/Django) application support+- [x] Node.js application management with PM2+- [x] Docker container management+- [x] Environment variable management+- [x] Application start/stop/restart controls+- [x] Log viewing per application++---++## Phase 3: Domain & SSL Management (Completed)++- [x] Nginx virtual host management+- [x] Domain configuration interface+- [x] Let's Encrypt SSL integration+- [x] SSL certificate auto-renewal+- [x] Redirect management (HTTP → HTTPS)++---++## Phase 4: Database Management (Completed)++- [x] MySQL/MariaDB database support+- [x] PostgreSQL database support+- [x] Database creation/deletion+- [x] User management per database+- [x] Basic query interface++---++## Phase 5: File & FTP Management (Completed)++- [x] Web-based file manager+- [x] File upload/download+- [x] File editing with syntax highlighting+- [x] vsftpd FTP server integration+- [x] FTP user management++---++## Phase 6: Monitoring & Alerts (Completed)++- [x] Real-time system metrics+- [x] Server uptime tracking+- [x] Customizable alert thresholds+- [x] Discord webhook notifications+- [x] Slack webhook notifications+- [x] Telegram bot notifications+- [x] Generic webhook support+- [x] Alert history and logging++---++## Phase 7: Security Features (Completed)++- [x] Two-factor authentication (TOTP)+- [x] Backup codes for 2FA recovery+- [x] ClamAV malware scanning+- [x] Quick scan / Full scan options+- [x] File quarantine management+- [x] File integrity monitoring+- [x] Failed login detection+- [x] Security event logging++---++## Phase 8: Scheduled Tasks (Completed)++- [x] Cron job management+- [x] Visual cron expression builder+- [x] Job execution history+- [x] Enable/disable jobs++---++## Phase 9: Firewall Management (Completed - Merged into Security)++- [x] UFW firewall integration+- [x] Visual rule management+- [x] Common port presets+- [x] Rule enable/disable+- [x] Consolidated into Security page for unified security management++---++## Phase 10: Multi-Server Management (Completed)++**Priority: High**++- [x] Agent-based remote server monitoring (Go agent)+- [x] Centralized dashboard for multiple servers+- [x] Server grouping and tagging+- [x] Cross-server metrics comparison+- [x] Remote Docker management via agents+- [x] Server health overview+- [x] Agent WebSocket gateway+- [x] HMAC-SHA256 authentication+- [x] GitHub Actions for agent releases (Linux/Windows)+- [x] Installation scripts endpoint+- [x] Agent auto-update mechanism+- [x] Agent download page in UI+- [x] Container logs streaming for remote servers++---++## Phase 11: Git Deployment (Completed)++**Priority: High**++- [x] GitHub/GitLab webhook integration+- [x] Automatic deployment on push+- [x] Branch selection for deployment+- [x] Rollback to previous deployments+- [x] Deployment history and logs+- [x] Pre/post deployment scripts+- [x] Zero-downtime deployments++---++## Phase 12: Backup & Restore (Completed)++**Priority: High**++- [x] Automated database backups+- [x] File/directory backups+- [x] S3-compatible storage support+- [x] Backblaze B2 integration+- [x] Backup scheduling+- [x] One-click restore+- [x] Backup retention policies+- [x] Offsite backup verification++---++## Phase 13: Email Server Management (Completed)++**Priority: Medium**++- [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++---++## Phase 14: Visual Infrastructure Designer (Completed)++**Priority: High**++The visual canvas for designing and deploying entire infrastructure stacks.++- [x] Node-based Visual Canvas (`WorkflowBuilder.jsx`) using React Flow+- [x] Infrastructure component nodes (Docker, Database, Domain, Service)+- [x] Smart connection rules (link apps to DBs, domains to apps)+- [x] One-click stack deployment from the canvas+- [x] Template-based stack generation+- [x] Server overview mode (visualize existing infrastructure)++---++## Phase 15: Team & Permissions (Completed)++**Priority: Medium**++- [x] Multi-user support+- [x] Role-based access control (RBAC)+- [x] Custom permission sets+- [x] Audit logging per user+- [x] Team invitations+- [x] Activity dashboard++---++## Phase 16: API Enhancements (Completed)++**Priority: Medium**++- [x] API key management+- [x] Rate limiting+- [x] Webhook event subscriptions+- [x] OpenAPI/Swagger documentation+- [x] API usage analytics++---++## Phase 17: Advanced Security (Completed)++**Priority: High**++- [x] Unified Security page with all security features+- [x] Firewall tab with UFW/firewalld management+- [x] Fail2ban integration+- [x] SSH key management+- [x] IP allowlist/blocklist+- [x] Brute force protection+- [x] Security audit reports+- [x] Vulnerability scanning (Lynis)+- [x] Automatic security updates (unattended-upgrades/dnf-automatic)++---++## Phase 18: SSO & OAuth Login (Completed)++**Priority: High**++- [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 19: Database Migrations & Schema Versioning (Completed)++**Priority: High**++- [x] Flask-Migrate (Alembic) integration+- [x] Migration wizard UI (Completed)+- [x] CLI fallback support++---++## Phase 20: New UI & Services Page (Completed)++**Priority: Critical**++Integrated full Services page with detail views, metrics, logs, shell, settings, and package management.++- [x] Services list page with status indicators and quick actions+- [x] Service detail page with tabbed interface (Metrics, Logs, Shell, Settings, Commands, Events, Packages)+- [x] Git connect modal for linking services to repositories+- [x] Gunicorn management tab for Python services+- [x] Service type detection and type-specific UI (Node, Python, PHP, Docker, etc.)++---++## Phase 21: Environment Pipeline (Completed)++**Priority: High**++- [x] WordPress multi-environment pipeline (Prod/Staging/Dev)+- [x] Code and Database promotion between environments+- [x] Production syncing and environment locking++---++## Phase 22: Container Logs & Monitoring UI (Completed)++**Priority: High**++- [x] Real-time log streaming via WebSocket with ANSI color support+- [x] Web-based terminal (`Terminal.jsx`) with shell access+- [x] Per-app resource usage charts (CPU, RAM)+- [x] Log search and filtering++---++# Upcoming Development++The phases below are ordered by priority. Higher phases ship first.++---++## Phase 23: Workflow & Automation Engine — Core (Completed)++**Priority: Critical**++Moving beyond static design to dynamic, event-driven automation. This turns ServerKit into a powerful automation hub.++- [x] **Visual Workflow Builder:** Node-based canvas with drag-and-drop nodes, connection validation, and config panels+- [x] **Cron Integration:** Schedule workflows to run on recurring intervals (e.g., "Every Sunday at 2 AM, backup all DBs and rotate logs")+- [x] **Manual Execution:** Trigger workflows on demand with optional context data+- [x] **Execution History:** Track workflow execution status, per-node results, and timestamped logs+- [x] **Script Nodes:** Custom Shell script execution nodes with output capture+- [x] **Notification Nodes:** Send alerts via configured notification channels+- [x] **One-Click Stack Deployment:** Deploy full infrastructure (databases, apps, domains) from a workflow diagram++---++## Phase 24: Customizable Sidebar & Dashboard Views (Completed)++**Priority: High**++Let users personalize what they see. Not everyone runs email servers or manages Docker — the sidebar should adapt to each user's needs.++- [x] Sidebar configuration page in Settings+- [x] Preset view profiles (Full, Web Hosting, Email Admin, Docker/DevOps, Minimal)+- [x] Custom view builder — toggle individual sidebar items on/off+- [x] Per-user preference storage (saved to user profile)++---++## Phase 25: Workflow Engine — Triggers & Completion (Completed)++**Priority: High**++Complete the workflow engine with proper execution logic, missing triggers, and production-grade reliability.++- [x] **DAG Execution:** Full directed acyclic graph traversal with parallel branch support (replace current linear BFS)+- [x] **Logic Node Evaluation:** If/Else condition evaluation with true/false branching+- [x] **Variable Interpolation:** Pass data between steps using `${node_id.field}` and `{{placeholder}}` syntax in node configs+- [x] **Webhook Triggers:** Register `/hooks/<webhook_id>` endpoint to fire workflows on incoming HTTP requests+- [x] **Event Triggers:** Run workflows on system events (health check failure, high CPU/memory, git push, app stopped)+- [x] **Notification Templating:** Message placeholder substitution (`${node_id.stdout}`, `{{workflow_name}}`) in notification nodes+- [x] **Execution Timeouts:** Configurable timeout per node (1–3600s) to prevent hung workflows+- [x] **Retry on Failure:** Configurable retry count (0–5) and delay per node+- [x] **Circular Dependency Detection:** Kahn's algorithm validates graph on save and before execution+- [x] **Script Sandboxing:** Timeout enforcement, output size limits, explicit `bash -c`/`python3 -c` execution++---++## Phase 26: Agent Fleet Management (Completed)++**Priority: High**++Level up agent management from "connect and monitor" to full fleet control.++- [x] Agent version tracking and compatibility matrix (panel version ↔ agent version)+- [x] Push agent upgrades from the panel (single server or fleet-wide rollout)+- [x] Staged rollout support — upgrade agents in batches with health checks between waves+- [x] Agent health dashboard — connection uptime, heartbeat latency, command success rate per agent+- [x] Auto-discovery of new servers on the local network (mDNS/broadcast scan)+- [x] Agent registration approval workflow (admin must approve before agent joins fleet)+- [x] Bulk agent operations — restart, upgrade, rotate keys across selected servers+- [x] Agent changelog and release notes visible in UI+- [x] Offline agent command queue — persist commands and deliver when agent reconnects+- [x] Command retry with configurable backoff for failed/timed-out operations+- [x] Agent connection diagnostics — test connectivity, latency, firewall check from panel++---++## Phase 27: Cross-Server Monitoring Dashboard (Completed)++**Priority: High**++Fleet-wide visibility — see everything at a glance and catch problems early.++- [x] Fleet overview dashboard — heatmap of all servers by CPU/memory/disk usage+- [x] Server comparison charts — overlay metrics from multiple servers on one graph+- [x] Per-server alert thresholds (CPU > 80% for 5 min → warning, > 95% → critical)+- [x] Anomaly detection — automatic baseline learning, alert on deviations+- [x] Custom metric dashboards — drag-and-drop widgets, save layouts per user+- [x] Metric correlation view — spot relationships between metrics across servers+- [x] Capacity forecasting — trend-based predictions (disk full in X days, memory growth rate)+- [x] Metrics export — Prometheus endpoint (`/metrics`), CSV download, JSON API+- [x] Grafana integration guide and pre-built dashboard templates+- [x] Fleet-wide search — find which server is running a specific container, service, or port++---++## Phase 28: Agent Plugin System (Completed)++**Priority: High**++Make the agent extensible — let users add custom capabilities without modifying agent core. This is the foundation for future integrations (Android device farms, IoT fleets, custom hardware monitoring, etc.).++### Plugin Architecture+- [x] Plugin specification — standard interface (init, healthcheck, metrics, commands)+- [x] Plugin manifest format (YAML/JSON) — name, version, dependencies, capabilities, permissions+- [x] Plugin lifecycle management — install, enable, disable, uninstall, upgrade+- [x] Plugin isolation — each plugin runs in its own process/sandbox with resource limits+- [x] Plugin communication — standardized IPC between plugin and agent core++### Plugin Capabilities+- [x] Custom metrics reporters — plugins can push arbitrary metrics to the panel+- [x] Custom health checks — plugins define checks that feed into the status system+- [x] Custom commands — plugins register new command types the panel can invoke+- [x] Scheduled tasks — plugins can register periodic jobs (cron-like)+- [x] Event hooks — plugins can react to agent events (connect, disconnect, command, alert)++---++## Phase 29: Server Templates & Config Sync (Completed)++**Priority: Medium**++Define what a server should look like, apply it, and detect when it drifts.++- [x] Server template builder — define expected state (packages, services, firewall rules, users, files)+- [x] Template library — save and reuse templates (e.g., "Web Server", "Database Server", "Mail Server")+- [x] Apply template to server — install packages, configure services, set firewall rules via agent+- [x] Config drift detection — periodic comparison of actual vs. expected state+- [x] Drift report UI — visual diff showing what changed and when+- [x] Auto-remediation option — automatically fix drift back to template (with approval toggle)+- [x] Template versioning — track changes to templates over time+- [x] Template inheritance — base template + role-specific overrides+- [x] Bulk apply — roll out template changes across server groups+- [x] Compliance dashboard — percentage of fleet in compliance per template++---++## Phase 30: Multi-Tenancy & Workspaces (Completed)++**Priority: Medium**++Isolate servers by team, client, or project. Essential for agencies, MSPs, and larger teams.++- [x] Workspace model — isolated container for servers, users, and settings+- [x] Workspace CRUD — create, rename, archive workspaces+- [x] Server assignment — each server belongs to exactly one workspace+- [x] User workspace membership — users can belong to multiple workspaces with different roles+- [x] Workspace switching — quick-switch dropdown in the header+- [x] Per-workspace settings — notification preferences, default templates, branding+- [x] Workspace-scoped API keys — API keys restricted to a single workspace+- [x] Cross-workspace admin view — super-admin can see all workspaces and usage+- [x] Workspace usage quotas — limit servers, users, or API calls per workspace+- [x] Workspace billing integration — track resource usage per workspace for invoicing++---++## Phase 31: Advanced SSL Features (Completed)++**Priority: Medium**++- [x] Certificate expiry monitoring+- [x] Wildcard SSL certificates via DNS-01 challenge+- [x] Multi-domain certificates (SAN)+- [x] Custom certificate upload (key + cert + chain)+- [x] Certificate expiry notifications (email/webhook alerts before expiration)+- [x] SSL configuration templates (modern, intermediate, legacy compatibility)+- [x] SSL health check dashboard (grade, cipher suites, protocol versions)++---++## Phase 32: DNS Zone Management (Completed)++**Priority: Medium**++Full DNS record management with provider API integration.++- [x] DNS zone editor UI (A, AAAA, CNAME, MX, TXT, SRV, CAA records)+- [x] Cloudflare API integration (list/create/update/delete records)+- [x] Route53 API integration+- [x] DigitalOcean DNS integration+- [x] DNS propagation checker (query multiple nameservers)+- [x] Auto-generate recommended records for hosted services (SPF, DKIM, DMARC, MX)+- [x] DNS template presets (e.g., "standard web hosting", "email hosting")+- [x] Bulk record import/export (BIND zone file format)++---++## Phase 33: Nginx Advanced Configuration (Completed)++**Priority: Medium**++Go beyond basic virtual hosts — full reverse proxy and performance configuration.++- [x] Visual reverse proxy rule builder (upstream servers, load balancing methods)+- [x] Load balancing configuration (round-robin, least connections, IP hash)+- [x] Caching rules editor (proxy cache zones, TTLs, cache bypass rules)+- [x] Rate limiting at proxy level (per-IP, per-route)+- [x] Custom location block editor with syntax validation+- [x] Header manipulation (add/remove/modify request/response headers)+- [x] Nginx config syntax check before applying changes+- [x] Config diff preview before saving+- [x] Access/error log viewer per virtual host++---++## Phase 34: Status Page & Health Checks (Completed)++**Priority: Medium**++Public-facing status page and automated health monitoring.++- [x] Automated health checks (HTTP, TCP, DNS, SMTP) with configurable intervals+- [x] Public status page (standalone URL, no auth required)+- [x] Status page customization (logo, colors, custom domain)+- [x] Service grouping on status page (e.g., "Web Services", "Email", "APIs")+- [x] Incident management — create, update, resolve incidents with timeline+- [x] Uptime percentage display (24h, 7d, 30d, 90d)+- [x] Scheduled maintenance windows with advance notifications+- [x] Status page subscribers (email/webhook notifications on incidents)+- [x] Historical uptime graphs+- [x] Status badge embeds (SVG/PNG for README files)++---++## Phase 35: Server Provisioning APIs (Completed)++**Priority: Medium**++Spin up and manage cloud servers directly from the panel.++- [x] DigitalOcean API integration (create/destroy/resize droplets)+- [x] Hetzner Cloud API integration+- [x] Vultr API integration+- [x] Linode/Akamai API integration+- [x] Server creation wizard (region, size, OS, SSH keys)+- [x] Auto-install ServerKit agent on provisioned servers+- [x] Server cost tracking and billing overview+- [x] Snapshot management (create/restore/delete)+- [x] One-click server cloning+- [x] Destroy server with confirmation safeguards++---++## Phase 36: Performance Optimization (Completed)++**Priority: Low**++- [x] Redis caching for frequently accessed data (metrics, server status)+- [x] Database query optimization and slow query logging+- [x] Background job queue (Celery or RQ) for long-running tasks+- [x] Lazy loading for large datasets (paginated API responses)+- [x] WebSocket connection pooling and reconnection improvements+- [x] Frontend bundle optimization and code splitting++---++## Phase 37: Mobile App (Completed)++**Priority: Low — v3.0+**++- [x] React Native or PWA mobile application+- [x] Push notifications for alerts and incidents+- [x] Quick actions (restart services, view stats, acknowledge alerts)+- [x] Biometric authentication (fingerprint/Face ID)+- [x] Offline mode with cached server status++---++## Phase 38: Marketplace & Extensions (Completed)++**Priority: Low — v3.0+**++- [x] Plugin/extension system with API hooks+- [x] Community marketplace for plugins+- [x] Custom dashboard widgets+- [x] Theme customization (colors, layout, branding)+- [x] Extension SDK and developer documentation++---++## Version Milestones++| Version | Target Features | Status |+|---------|-----------------|--------|+| v0.9.0 | Core features, 2FA, Notifications, Security | Completed |+| v1.0.0 | Production-ready stable release, DB migrations | Completed |+| v1.1.0 | Multi-server, Git deployment | Completed |+| v1.2.0 | Backups, Advanced SSL, Advanced Security | Completed |+| v1.3.0 | Email server, API enhancements | Completed |+| v1.4.0 | Team & permissions, SSO & OAuth login | Completed |+| v1.5.0 | New UI, Visual Designer, Services Page | Completed |+| v1.6.0 | Workflow triggers & completion, fleet management | Current |+| v1.7.0 | Cross-server monitoring, agent plugin system | Completed |+| v1.8.0 | Server templates, multi-tenancy | Completed |+| v1.9.0 | Advanced SSL, DNS management, Nginx config | Completed |+| v2.0.0 | Status pages, server provisioning, performance | Completed |+| v3.0.0 | Mobile app, Marketplace | Completed |++---++## Contributing++Want to help? See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.++**Priority areas for contributions:**+- Agent plugin SDK and example plugins+- Fleet management and monitoring dashboard+- DNS provider integrations (Cloudflare, Route53)+- Status page and health check system+- UI/UX improvements+- Documentation++---++## Feature Requests++Have a feature idea? Open an issue on GitHub with the `enhancement` label.++---++<p align="center">+ <strong>ServerKit Roadmap</strong><br>+ Last updated: March 2026+</p>diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex f987bc85..0c0d6660 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -1,624 +1,624 @@-import os-from flask import Flask, send_from_directory, request, jsonify-from flask_sqlalchemy import SQLAlchemy-from flask_jwt_extended import JWTManager-from flask_cors import CORS-from flask_limiter import Limiter-from flask_limiter.util import get_remote_address-from flask_migrate import Migrate--from config import config--db = SQLAlchemy()-jwt = JWTManager()-migrate = Migrate()--# PyJWT 2.10+ enforces that 'sub' must be a string.-# Stringify the identity so integer user IDs work transparently.[email protected]_identity_loader-def _user_identity(user_id):- return str(user_id)-limiter = Limiter(key_func=get_remote_address, default_limits=["100 per minute"])-# Note: key_func is updated to get_rate_limit_key after app init-socketio = None--# Path to frontend dist folder (relative to backend folder)-FRONTEND_DIST = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'frontend', 'dist')---def create_app(config_name=None):- global socketio-- if config_name is None:- config_name = os.environ.get('FLASK_ENV', 'development')-- # Configure Flask to serve static files from frontend dist- app = Flask(- __name__,- static_folder=FRONTEND_DIST,- static_url_path=''- )- app.config.from_object(config[config_name])-- # Initialize extensions- db.init_app(app)- migrate.init_app(app, db)- jwt.init_app(app)- limiter.init_app(app)- CORS(- app,- origins=app.config['CORS_ORIGINS'],- supports_credentials=True,- allow_headers=['Content-Type', 'Authorization', 'X-Requested-With', 'X-API-Key'],- methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH']- )-- # Register security headers middleware- from app.middleware.security import register_security_headers- register_security_headers(app)-- # Register API key authentication middleware- from app.middleware.api_key_auth import register_api_key_auth- register_api_key_auth(app)-- # Register API analytics middleware- from app.middleware.api_analytics import register_api_analytics- register_api_analytics(app)-- # Register fallback audit logging for authenticated mutating API requests- from app.middleware.audit import register_audit_fallback- register_audit_fallback(app)-- # Update rate limiter with custom key function- from app.middleware.rate_limit import get_rate_limit_key, register_rate_limit_headers- limiter._key_func = get_rate_limit_key- register_rate_limit_headers(app)-- # Initialize SocketIO- from app.sockets import init_socketio- socketio = init_socketio(app)-- # Initialize Agent Gateway- from app.agent_gateway import init_agent_gateway- init_agent_gateway(socketio)-- # Register blueprints - Auth- from app.api.auth import auth_bp- app.register_blueprint(auth_bp, url_prefix='/api/v1/auth')-- # Agent polling fallback transport (REST equivalent of the WS gateway,- # used when tunnels mangle WebSocket frames).- from app.api.agent_poll import agent_poll_bp- app.register_blueprint(agent_poll_bp, url_prefix='/api/v1/agent')-- # Register blueprints - Core- from app.api.apps import apps_bp- from app.api.domains import domains_bp- from app.api.private_urls import private_urls_bp- app.register_blueprint(apps_bp, url_prefix='/api/v1/apps')- app.register_blueprint(domains_bp, url_prefix='/api/v1/domains')- app.register_blueprint(private_urls_bp, url_prefix='/api/v1/apps')-- # Register blueprints - System- from app.api.system import system_bp- from app.api.processes import processes_bp- from app.api.logs import logs_bp- app.register_blueprint(system_bp, url_prefix='/api/v1/system')- app.register_blueprint(processes_bp, url_prefix='/api/v1/processes')- app.register_blueprint(logs_bp, url_prefix='/api/v1/logs')-- # Register blueprints - Infrastructure- from app.api.nginx import nginx_bp- from app.api.ssl import ssl_bp- app.register_blueprint(nginx_bp, url_prefix='/api/v1/nginx')- app.register_blueprint(ssl_bp, url_prefix='/api/v1/ssl')-- # Register blueprints - PHP & WordPress- from app.api.php import php_bp- from app.api.wordpress import wordpress_bp- from app.api.wordpress_sites import wordpress_sites_bp- from app.api.environment_pipeline import environment_pipeline_bp- app.register_blueprint(php_bp, url_prefix='/api/v1/php')- app.register_blueprint(wordpress_bp, url_prefix='/api/v1/wordpress')- app.register_blueprint(wordpress_sites_bp, url_prefix='/api/v1/wordpress')- app.register_blueprint(environment_pipeline_bp, url_prefix='/api/v1/wordpress/projects')-- # Register blueprints - Python- from app.api.python import python_bp- app.register_blueprint(python_bp, url_prefix='/api/v1/python')-- # Register blueprints - Docker- from app.api.docker import docker_bp- app.register_blueprint(docker_bp, url_prefix='/api/v1/docker')-- # Register blueprints - Databases- from app.api.databases import databases_bp- app.register_blueprint(databases_bp, url_prefix='/api/v1/databases')-- # Register blueprints - Monitoring & Alerts- from app.api.monitoring import monitoring_bp- app.register_blueprint(monitoring_bp, url_prefix='/api/v1/monitoring')-- # Register blueprints - Notifications- from app.api.notifications import notifications_bp- app.register_blueprint(notifications_bp, url_prefix='/api/v1/notifications')-- # Register blueprints - Backups- from app.api.backups import backups_bp- app.register_blueprint(backups_bp, url_prefix='/api/v1/backups')-- # Register blueprints - Git Deployment- from app.api.deploy import deploy_bp- app.register_blueprint(deploy_bp, url_prefix='/api/v1/deploy')-- # Register blueprints - Builds & Deployments- from app.api.builds import builds_bp- from app.api.deployment_jobs import deployment_jobs_bp- app.register_blueprint(builds_bp, url_prefix='/api/v1/builds')- app.register_blueprint(deployment_jobs_bp, url_prefix='/api/v1/deployment-jobs')-- # Register blueprints - Templates- from app.api.templates import templates_bp- app.register_blueprint(templates_bp, url_prefix='/api/v1/templates')-- # Register blueprints - File Manager- from app.api.files import files_bp- app.register_blueprint(files_bp, url_prefix='/api/v1/files')-- # Register blueprints - FTP Server- from app.api.ftp import ftp_bp- app.register_blueprint(ftp_bp, url_prefix='/api/v1/ftp')-- # Register blueprints - Firewall- from app.api.firewall import firewall_bp- app.register_blueprint(firewall_bp, url_prefix='/api/v1/firewall')-- # Register blueprints - Git Server- from app.api.git import git_bp- app.register_blueprint(git_bp, url_prefix='/api/v1/git')-- # Register blueprints - Security (ClamAV, File Integrity, etc.)- from app.api.security import security_bp- app.register_blueprint(security_bp, url_prefix='/api/v1/security')-- # Register blueprints - Cron Jobs- from app.api.cron import cron_bp- app.register_blueprint(cron_bp, url_prefix='/api/v1/cron')-- # Register blueprints - Email Server- from app.api.email import email_bp- app.register_blueprint(email_bp, url_prefix='/api/v1/email')-- # Register blueprints - Uptime Tracking- from app.api.uptime import uptime_bp- app.register_blueprint(uptime_bp, url_prefix='/api/v1/uptime')-- # Register blueprints - Environment Variables- from app.api.env_vars import env_vars_bp- app.register_blueprint(env_vars_bp, url_prefix='/api/v1/apps')-- # Register blueprints - Two-Factor Authentication- from app.api.two_factor import two_factor_bp- app.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 - Source provider connections- from app.api.source_connections import source_connections_bp- app.register_blueprint(source_connections_bp, url_prefix='/api/v1/source-connections')-- # Register blueprints - Database Migrations- from app.api.migrations import migrations_bp- app.register_blueprint(migrations_bp, url_prefix='/api/v1/migrations')-- # Register blueprints - API Enhancements- from app.api.api_keys import api_keys_bp- from app.api.api_analytics import api_analytics_bp- from app.api.event_subscriptions import event_subscriptions_bp- from app.api.docs import docs_bp- app.register_blueprint(api_keys_bp, url_prefix='/api/v1/api-keys')- app.register_blueprint(api_analytics_bp, url_prefix='/api/v1/api-analytics')- app.register_blueprint(event_subscriptions_bp, url_prefix='/api/v1/event-subscriptions')- app.register_blueprint(docs_bp, url_prefix='/api/v1/docs')-- # Register blueprints - Admin (User Management, Settings, Audit Logs)- from app.api.admin import admin_bp- app.register_blueprint(admin_bp, url_prefix='/api/v1/admin')-- # Register blueprints - Invitations- from app.api.invitations import invitations_bp- app.register_blueprint(invitations_bp, url_prefix='/api/v1/admin/invitations')-- # Register blueprints - Historical Metrics- from app.api.metrics import metrics_bp- app.register_blueprint(metrics_bp, url_prefix='/api/v1/metrics')-- # Register blueprints - Workflows- from app.api.workflows import workflows_bp- app.register_blueprint(workflows_bp, url_prefix='/api/v1/workflows')-- # Register blueprints - Servers (Multi-server management)- from app.api.servers import servers_bp- app.register_blueprint(servers_bp, url_prefix='/api/v1/servers')-- # Register blueprints - Fleet Monitor (Cross-server monitoring)- from app.api.fleet_monitor import fleet_monitor_bp- app.register_blueprint(fleet_monitor_bp, url_prefix='/api/v1/fleet-monitor')-- # Register blueprints - Fleet (target picker, capability discovery)- from app.api.fleet import fleet_bp- app.register_blueprint(fleet_bp, url_prefix='/api/v1/fleet')-- # Register blueprints - Agent Plugins- from app.api.agent_plugins import agent_plugins_bp- app.register_blueprint(agent_plugins_bp, url_prefix='/api/v1/agent-plugins')-- # Register blueprints - Server Templates- from app.api.server_templates import server_templates_bp- app.register_blueprint(server_templates_bp, url_prefix='/api/v1/server-templates')-- # Register blueprints - Workspaces- from app.api.workspaces import workspaces_bp- app.register_blueprint(workspaces_bp, url_prefix='/api/v1/workspaces')-- # Register blueprints - Advanced SSL- from app.api.advanced_ssl import advanced_ssl_bp- app.register_blueprint(advanced_ssl_bp, url_prefix='/api/v1/ssl/advanced')-- # Register blueprints - DNS Zones- from app.api.dns_zones import dns_zones_bp- app.register_blueprint(dns_zones_bp, url_prefix='/api/v1/dns')-- # Register blueprints - Nginx Advanced- from app.api.nginx_advanced import nginx_advanced_bp- app.register_blueprint(nginx_advanced_bp, url_prefix='/api/v1/nginx/advanced')-- # Register blueprints - Status Pages- from app.api.status_pages import status_pages_bp- app.register_blueprint(status_pages_bp, url_prefix='/api/v1/status')-- # Register blueprints - Cloud Provisioning- from app.api.cloud_provisioning import cloud_provisioning_bp- app.register_blueprint(cloud_provisioning_bp, url_prefix='/api/v1/cloud')-- # Register blueprints - Performance- from app.api.performance import performance_bp- app.register_blueprint(performance_bp, url_prefix='/api/v1/performance')-- # Register blueprints - Mobile- from app.api.mobile import mobile_bp- app.register_blueprint(mobile_bp, url_prefix='/api/v1/mobile')-- # Register blueprints - Marketplace- from app.api.marketplace import marketplace_bp- app.register_blueprint(marketplace_bp, url_prefix='/api/v1/marketplace')-- # Register blueprints - Plugins- from app.api.plugins import plugins_bp- app.register_blueprint(plugins_bp, url_prefix='/api/v1/plugins')-- # Register blueprints - Agent Pairing (RustDesk-style short-code flow)- from app.api.pairing import pairing_bp- app.register_blueprint(pairing_bp, url_prefix='/api/v1/pairing')-- # Handle database migrations (Alembic) — must run before plugin loader- # since the loader queries the installed_plugins table.- with app.app_context():- from app.services.migration_service import MigrationService- MigrationService.check_and_prepare(app)-- # Initialize default settings and migrate legacy roles- from app.services.settings_service import SettingsService- SettingsService.initialize_defaults()- SettingsService.migrate_legacy_roles()-- # Load installed plugins (dynamic blueprints) AFTER migrations,- # so the installed_plugins table exists.- try:- from app.services.plugin_service import load_all_plugins- load_all_plugins(app)- except Exception as e:- import logging- logging.getLogger(__name__).warning(f'Plugin loader: {e}')-- # Start metrics history collection in background- from app.services.metrics_history_service import MetricsHistoryService- if not MetricsHistoryService.is_running():- MetricsHistoryService.start_collection(app)-- # Start auto-sync scheduler for WordPress environments- _start_auto_sync_scheduler(app)-- # Start workflow scheduler- _start_workflow_scheduler(app)-- # Start API analytics flush thread- from app.middleware.api_analytics import start_analytics_flush_thread- start_analytics_flush_thread(app)-- # Start hourly analytics aggregation and event retry threads- _start_api_background_threads(app)-- # Start hourly pruner for expired pending agent pairings- _start_pairing_pruner(app)-- # Request body size limit- app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB limit-- # Reject 2FA pending tokens on non-2FA endpoints- @app.before_request- def check_2fa_pending():- """Reject 2FA pending tokens on non-2FA endpoints."""- from flask_jwt_extended import verify_jwt_in_request, get_jwt- if request.endpoint and request.path.startswith('/api/'):- # Allow 2FA verification endpoints- if '/two-factor/verify' in request.path or '/two-factor/verify-backup' in request.path:- return- # Allow auth endpoints (login, refresh)- if '/auth/login' in request.path or '/auth/refresh' in request.path:- return- try:- verify_jwt_in_request()- claims = get_jwt()- if claims.get('2fa_pending'):- return jsonify({'error': '2FA verification required'}), 403- except Exception:- pass # Let @jwt_required handle actual auth errors-- # Serve frontend for root path- @app.route('/')- def serve_index():- index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None- if index and os.path.isfile(index):- return send_from_directory(app.static_folder, 'index.html')- return {'message': 'ServerKit API is running', 'docs': '/api/v1/'}, 200-- # Catch-all route for SPA - must be after all other routes- @app.errorhandler(404)- def not_found(e):- from flask import request- if request.path.startswith('/api/'):- return {'error': 'Not found'}, 404- # Serve SPA index.html if it exists, otherwise JSON 404- index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None- if index and os.path.isfile(index):- return send_from_directory(app.static_folder, 'index.html')- return {'error': 'Not found'}, 404-- return app---def get_socketio():- """Get the SocketIO instance."""- return socketio---_auto_sync_thread = None---def _start_auto_sync_scheduler(app):- """Start a background thread that checks for auto-sync schedules."""- global _auto_sync_thread- if _auto_sync_thread is not None:- return-- import threading- import time- import logging-- logger = logging.getLogger(__name__)-- def auto_sync_loop():- while True:- try:- time.sleep(60) # Check every 60 seconds- with app.app_context():- _check_auto_sync_schedules(logger)- except Exception as e:- logger.error(f'Auto-sync scheduler error: {e}')-- _auto_sync_thread = threading.Thread(- target=auto_sync_loop,- daemon=True,- name='auto-sync-scheduler'- )- _auto_sync_thread.start()---def _check_auto_sync_schedules(logger):- """Check all auto-sync enabled sites and run syncs that are due."""- from app.models.wordpress_site import WordPressSite- from datetime import datetime-- sites = WordPressSite.query.filter_by(auto_sync_enabled=True).all()- if not sites:- return-- try:- from croniter import croniter- except ImportError:- logger.debug('croniter not installed, skipping auto-sync check')- return-- now = datetime.utcnow()-- for site in sites:- if not site.auto_sync_schedule:- continue-- try:- if not croniter.is_valid(site.auto_sync_schedule):- continue-- cron = croniter(site.auto_sync_schedule, now)- prev_run = cron.get_prev(datetime)-- # Check if a run was due in the last 90 seconds (to account for check interval)- seconds_since_due = (now - prev_run).total_seconds()- if seconds_since_due <= 90:- logger.info(f'Auto-sync triggered for site {site.id} ({site.name})')- from app.services.environment_pipeline_service import EnvironmentPipelineService- EnvironmentPipelineService.sync_from_production(- env_site_id=site.id,- sync_type='full',- user_id=None- )- except Exception as e:- logger.error(f'Auto-sync check failed for site {site.id}: {e}')---_api_bg_thread = None---def _start_pairing_pruner(app):- """Start a background thread that prunes expired PendingAgent rows hourly."""- global _pairing_prune_thread- if _pairing_prune_thread is not None:- return-- import threading- import time- import logging-- logger = logging.getLogger(__name__)-- def prune_loop():- # Wait a bit before first run so app is fully initialized.- time.sleep(60)- while True:- try:- with app.app_context():- from app.services import pairing_service- pairing_service.prune_expired()- except Exception as e:- logger.error(f'Pairing pruner error: {e}')- time.sleep(3600)-- _pairing_prune_thread = threading.Thread(- target=prune_loop,- daemon=True,- name='pairing-pruner'- )- _pairing_prune_thread.start()---_pairing_prune_thread = None---def _start_api_background_threads(app):- """Start background threads for API analytics aggregation and event delivery retry."""- global _api_bg_thread- if _api_bg_thread is not None:- return-- import threading- import time- import logging-- logger = logging.getLogger(__name__)-- def api_bg_loop():- while True:- try:- time.sleep(3600) # Run hourly- with app.app_context():- from app.services.api_analytics_service import ApiAnalyticsService- ApiAnalyticsService.aggregate_hourly()-- from app.services.event_service import EventService- EventService.retry_failed()- except Exception as e:- logger.error(f'API background thread error: {e}')-- _api_bg_thread = threading.Thread(- target=api_bg_loop,- daemon=True,- name='api-background'- )- _api_bg_thread.start()---_workflow_thread = None---def _start_workflow_scheduler(app):- """Start a background thread that checks for scheduled workflows."""- global _workflow_thread- if _workflow_thread is not None:- return-- import threading- import time- import logging-- logger = logging.getLogger(__name__)-- def workflow_loop():- while True:- try:- time.sleep(60) # Check every 60 seconds- with app.app_context():- _check_workflow_schedules(logger)- except Exception as e:- logger.error(f'Workflow scheduler error: {e}')-- _workflow_thread = threading.Thread(- target=workflow_loop,- daemon=True,- name='workflow-scheduler'- )- _workflow_thread.start()---def _check_workflow_schedules(logger):- """Check all active workflows with cron triggers and run those that are due."""- from app.models.workflow import Workflow- from app.services.workflow_engine import WorkflowEngine- from datetime import datetime- import json-- try:- from croniter import croniter- except ImportError:- logger.debug('croniter not installed, skipping workflow schedule check')- return-- # Find active workflows with cron triggers- workflows = Workflow.query.filter_by(is_active=True, trigger_type='cron').all()- if not workflows:- return-- now = datetime.utcnow()-- for workflow in workflows:- try:- config = json.loads(workflow.trigger_config) if workflow.trigger_config else {}- cron_expr = config.get('cron')-- if not cron_expr or not croniter.is_valid(cron_expr):- continue-- cron = croniter(cron_expr, now)- prev_run = cron.get_prev(datetime)-- # Check if a run was due in the last 90 seconds- seconds_since_due = (now - prev_run).total_seconds()-- # Also ensure we don't run it multiple times for the same slot- if 0 < seconds_since_due <= 90:- # Check if it already ran in the last 2 minutes- if workflow.last_run_at:- seconds_since_last_run = (now - workflow.last_run_at).total_seconds()- if seconds_since_last_run < 110:- continue-- logger.info(f'Scheduled workflow triggered: {workflow.name} (ID: {workflow.id})')- WorkflowEngine.execute_workflow(- workflow_id=workflow.id,- trigger_type='cron',- context={'scheduled_at': prev_run.isoformat()}- )- except Exception as e:- logger.error(f'Workflow schedule check failed for workflow {workflow.id}: {e}')+import os+from flask import Flask, send_from_directory, request, jsonify+from flask_sqlalchemy import SQLAlchemy+from flask_jwt_extended import JWTManager+from flask_cors import CORS+from flask_limiter import Limiter+from flask_limiter.util import get_remote_address+from flask_migrate import Migrate++from config import config++db = SQLAlchemy()+jwt = JWTManager()+migrate = Migrate()++# PyJWT 2.10+ enforces that 'sub' must be a string.+# Stringify the identity so integer user IDs work transparently.[email protected]_identity_loader+def _user_identity(user_id):+ return str(user_id)+limiter = Limiter(key_func=get_remote_address, default_limits=["100 per minute"])+# Note: key_func is updated to get_rate_limit_key after app init+socketio = None++# Path to frontend dist folder (relative to backend folder)+FRONTEND_DIST = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'frontend', 'dist')+++def create_app(config_name=None):+ global socketio++ if config_name is None:+ config_name = os.environ.get('FLASK_ENV', 'development')++ # Configure Flask to serve static files from frontend dist+ app = Flask(+ __name__,+ static_folder=FRONTEND_DIST,+ static_url_path=''+ )+ app.config.from_object(config[config_name])++ # Initialize extensions+ db.init_app(app)+ migrate.init_app(app, db)+ jwt.init_app(app)+ limiter.init_app(app)+ CORS(+ app,+ origins=app.config['CORS_ORIGINS'],+ supports_credentials=True,+ allow_headers=['Content-Type', 'Authorization', 'X-Requested-With', 'X-API-Key'],+ methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH']+ )++ # Register security headers middleware+ from app.middleware.security import register_security_headers+ register_security_headers(app)++ # Register API key authentication middleware+ from app.middleware.api_key_auth import register_api_key_auth+ register_api_key_auth(app)++ # Register API analytics middleware+ from app.middleware.api_analytics import register_api_analytics+ register_api_analytics(app)++ # Register fallback audit logging for authenticated mutating API requests+ from app.middleware.audit import register_audit_fallback+ register_audit_fallback(app)++ # Update rate limiter with custom key function+ from app.middleware.rate_limit import get_rate_limit_key, register_rate_limit_headers+ limiter._key_func = get_rate_limit_key+ register_rate_limit_headers(app)++ # Initialize SocketIO+ from app.sockets import init_socketio+ socketio = init_socketio(app)++ # Initialize Agent Gateway+ from app.agent_gateway import init_agent_gateway+ init_agent_gateway(socketio)++ # Register blueprints - Auth+ from app.api.auth import auth_bp+ app.register_blueprint(auth_bp, url_prefix='/api/v1/auth')++ # Agent polling fallback transport (REST equivalent of the WS gateway,+ # used when tunnels mangle WebSocket frames).+ from app.api.agent_poll import agent_poll_bp+ app.register_blueprint(agent_poll_bp, url_prefix='/api/v1/agent')++ # Register blueprints - Core+ from app.api.apps import apps_bp+ from app.api.domains import domains_bp+ from app.api.private_urls import private_urls_bp+ app.register_blueprint(apps_bp, url_prefix='/api/v1/apps')+ app.register_blueprint(domains_bp, url_prefix='/api/v1/domains')+ app.register_blueprint(private_urls_bp, url_prefix='/api/v1/apps')++ # Register blueprints - System+ from app.api.system import system_bp+ from app.api.processes import processes_bp+ from app.api.logs import logs_bp+ app.register_blueprint(system_bp, url_prefix='/api/v1/system')+ app.register_blueprint(processes_bp, url_prefix='/api/v1/processes')+ app.register_blueprint(logs_bp, url_prefix='/api/v1/logs')++ # Register blueprints - Infrastructure+ from app.api.nginx import nginx_bp+ from app.api.ssl import ssl_bp+ app.register_blueprint(nginx_bp, url_prefix='/api/v1/nginx')+ app.register_blueprint(ssl_bp, url_prefix='/api/v1/ssl')++ # Register blueprints - PHP & WordPress+ from app.api.php import php_bp+ from app.api.wordpress import wordpress_bp+ from app.api.wordpress_sites import wordpress_sites_bp+ from app.api.environment_pipeline import environment_pipeline_bp+ app.register_blueprint(php_bp, url_prefix='/api/v1/php')+ app.register_blueprint(wordpress_bp, url_prefix='/api/v1/wordpress')+ app.register_blueprint(wordpress_sites_bp, url_prefix='/api/v1/wordpress')+ app.register_blueprint(environment_pipeline_bp, url_prefix='/api/v1/wordpress/projects')++ # Register blueprints - Python+ from app.api.python import python_bp+ app.register_blueprint(python_bp, url_prefix='/api/v1/python')++ # Register blueprints - Docker+ from app.api.docker import docker_bp+ app.register_blueprint(docker_bp, url_prefix='/api/v1/docker')++ # Register blueprints - Databases+ from app.api.databases import databases_bp+ app.register_blueprint(databases_bp, url_prefix='/api/v1/databases')++ # Register blueprints - Monitoring & Alerts+ from app.api.monitoring import monitoring_bp+ app.register_blueprint(monitoring_bp, url_prefix='/api/v1/monitoring')++ # Register blueprints - Notifications+ from app.api.notifications import notifications_bp+ app.register_blueprint(notifications_bp, url_prefix='/api/v1/notifications')++ # Register blueprints - Backups+ from app.api.backups import backups_bp+ app.register_blueprint(backups_bp, url_prefix='/api/v1/backups')++ # Register blueprints - Git Deployment+ from app.api.deploy import deploy_bp+ app.register_blueprint(deploy_bp, url_prefix='/api/v1/deploy')++ # Register blueprints - Builds & Deployments+ from app.api.builds import builds_bp+ from app.api.deployment_jobs import deployment_jobs_bp+ app.register_blueprint(builds_bp, url_prefix='/api/v1/builds')+ app.register_blueprint(deployment_jobs_bp, url_prefix='/api/v1/deployment-jobs')++ # Register blueprints - Templates+ from app.api.templates import templates_bp+ app.register_blueprint(templates_bp, url_prefix='/api/v1/templates')++ # Register blueprints - File Manager+ from app.api.files import files_bp+ app.register_blueprint(files_bp, url_prefix='/api/v1/files')++ # Register blueprints - FTP Server+ from app.api.ftp import ftp_bp+ app.register_blueprint(ftp_bp, url_prefix='/api/v1/ftp')++ # Register blueprints - Firewall+ from app.api.firewall import firewall_bp+ app.register_blueprint(firewall_bp, url_prefix='/api/v1/firewall')++ # Register blueprints - Git Server+ from app.api.git import git_bp+ app.register_blueprint(git_bp, url_prefix='/api/v1/git')++ # Register blueprints - Security (ClamAV, File Integrity, etc.)+ from app.api.security import security_bp+ app.register_blueprint(security_bp, url_prefix='/api/v1/security')++ # Register blueprints - Cron Jobs+ from app.api.cron import cron_bp+ app.register_blueprint(cron_bp, url_prefix='/api/v1/cron')++ # Register blueprints - Email Server+ from app.api.email import email_bp+ app.register_blueprint(email_bp, url_prefix='/api/v1/email')++ # Register blueprints - Uptime Tracking+ from app.api.uptime import uptime_bp+ app.register_blueprint(uptime_bp, url_prefix='/api/v1/uptime')++ # Register blueprints - Environment Variables+ from app.api.env_vars import env_vars_bp+ app.register_blueprint(env_vars_bp, url_prefix='/api/v1/apps')++ # Register blueprints - Two-Factor Authentication+ from app.api.two_factor import two_factor_bp+ app.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 - Source provider connections+ from app.api.source_connections import source_connections_bp+ app.register_blueprint(source_connections_bp, url_prefix='/api/v1/source-connections')++ # Register blueprints - Database Migrations+ from app.api.migrations import migrations_bp+ app.register_blueprint(migrations_bp, url_prefix='/api/v1/migrations')++ # Register blueprints - API Enhancements+ from app.api.api_keys import api_keys_bp+ from app.api.api_analytics import api_analytics_bp+ from app.api.event_subscriptions import event_subscriptions_bp+ from app.api.docs import docs_bp+ app.register_blueprint(api_keys_bp, url_prefix='/api/v1/api-keys')+ app.register_blueprint(api_analytics_bp, url_prefix='/api/v1/api-analytics')+ app.register_blueprint(event_subscriptions_bp, url_prefix='/api/v1/event-subscriptions')+ app.register_blueprint(docs_bp, url_prefix='/api/v1/docs')++ # Register blueprints - Admin (User Management, Settings, Audit Logs)+ from app.api.admin import admin_bp+ app.register_blueprint(admin_bp, url_prefix='/api/v1/admin')++ # Register blueprints - Invitations+ from app.api.invitations import invitations_bp+ app.register_blueprint(invitations_bp, url_prefix='/api/v1/admin/invitations')++ # Register blueprints - Historical Metrics+ from app.api.metrics import metrics_bp+ app.register_blueprint(metrics_bp, url_prefix='/api/v1/metrics')++ # Register blueprints - Workflows+ from app.api.workflows import workflows_bp+ app.register_blueprint(workflows_bp, url_prefix='/api/v1/workflows')++ # Register blueprints - Servers (Multi-server management)+ from app.api.servers import servers_bp+ app.register_blueprint(servers_bp, url_prefix='/api/v1/servers')++ # Register blueprints - Fleet Monitor (Cross-server monitoring)+ from app.api.fleet_monitor import fleet_monitor_bp+ app.register_blueprint(fleet_monitor_bp, url_prefix='/api/v1/fleet-monitor')++ # Register blueprints - Fleet (target picker, capability discovery)+ from app.api.fleet import fleet_bp+ app.register_blueprint(fleet_bp, url_prefix='/api/v1/fleet')++ # Register blueprints - Agent Plugins+ from app.api.agent_plugins import agent_plugins_bp+ app.register_blueprint(agent_plugins_bp, url_prefix='/api/v1/agent-plugins')++ # Register blueprints - Server Templates+ from app.api.server_templates import server_templates_bp+ app.register_blueprint(server_templates_bp, url_prefix='/api/v1/server-templates')++ # Register blueprints - Workspaces+ from app.api.workspaces import workspaces_bp+ app.register_blueprint(workspaces_bp, url_prefix='/api/v1/workspaces')++ # Register blueprints - Advanced SSL+ from app.api.advanced_ssl import advanced_ssl_bp+ app.register_blueprint(advanced_ssl_bp, url_prefix='/api/v1/ssl/advanced')++ # Register blueprints - DNS Zones+ from app.api.dns_zones import dns_zones_bp+ app.register_blueprint(dns_zones_bp, url_prefix='/api/v1/dns')++ # Register blueprints - Nginx Advanced+ from app.api.nginx_advanced import nginx_advanced_bp+ app.register_blueprint(nginx_advanced_bp, url_prefix='/api/v1/nginx/advanced')++ # Register blueprints - Status Pages+ from app.api.status_pages import status_pages_bp+ app.register_blueprint(status_pages_bp, url_prefix='/api/v1/status')++ # Register blueprints - Cloud Provisioning+ from app.api.cloud_provisioning import cloud_provisioning_bp+ app.register_blueprint(cloud_provisioning_bp, url_prefix='/api/v1/cloud')++ # Register blueprints - Performance+ from app.api.performance import performance_bp+ app.register_blueprint(performance_bp, url_prefix='/api/v1/performance')++ # Register blueprints - Mobile+ from app.api.mobile import mobile_bp+ app.register_blueprint(mobile_bp, url_prefix='/api/v1/mobile')++ # Register blueprints - Marketplace+ from app.api.marketplace import marketplace_bp+ app.register_blueprint(marketplace_bp, url_prefix='/api/v1/marketplace')++ # Register blueprints - Plugins+ from app.api.plugins import plugins_bp+ app.register_blueprint(plugins_bp, url_prefix='/api/v1/plugins')++ # Register blueprints - Agent Pairing (RustDesk-style short-code flow)+ from app.api.pairing import pairing_bp+ app.register_blueprint(pairing_bp, url_prefix='/api/v1/pairing')++ # Handle database migrations (Alembic) — must run before plugin loader+ # since the loader queries the installed_plugins table.+ with app.app_context():+ from app.services.migration_service import MigrationService+ MigrationService.check_and_prepare(app)++ # Initialize default settings and migrate legacy roles+ from app.services.settings_service import SettingsService+ SettingsService.initialize_defaults()+ SettingsService.migrate_legacy_roles()++ # Load installed plugins (dynamic blueprints) AFTER migrations,+ # so the installed_plugins table exists.+ try:+ from app.services.plugin_service import load_all_plugins+ load_all_plugins(app)+ except Exception as e:+ import logging+ logging.getLogger(__name__).warning(f'Plugin loader: {e}')++ # Start metrics history collection in background+ from app.services.metrics_history_service import MetricsHistoryService+ if not MetricsHistoryService.is_running():+ MetricsHistoryService.start_collection(app)++ # Start auto-sync scheduler for WordPress environments+ _start_auto_sync_scheduler(app)++ # Start workflow scheduler+ _start_workflow_scheduler(app)++ # Start API analytics flush thread+ from app.middleware.api_analytics import start_analytics_flush_thread+ start_analytics_flush_thread(app)++ # Start hourly analytics aggregation and event retry threads+ _start_api_background_threads(app)++ # Start hourly pruner for expired pending agent pairings+ _start_pairing_pruner(app)++ # Request body size limit+ app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB limit++ # Reject 2FA pending tokens on non-2FA endpoints+ @app.before_request+ def check_2fa_pending():+ """Reject 2FA pending tokens on non-2FA endpoints."""+ from flask_jwt_extended import verify_jwt_in_request, get_jwt+ if request.endpoint and request.path.startswith('/api/'):+ # Allow 2FA verification endpoints+ if '/two-factor/verify' in request.path or '/two-factor/verify-backup' in request.path:+ return+ # Allow auth endpoints (login, refresh)+ if '/auth/login' in request.path or '/auth/refresh' in request.path:+ return+ try:+ verify_jwt_in_request()+ claims = get_jwt()+ if claims.get('2fa_pending'):+ return jsonify({'error': '2FA verification required'}), 403+ except Exception:+ pass # Let @jwt_required handle actual auth errors++ # Serve frontend for root path+ @app.route('/')+ def serve_index():+ index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None+ if index and os.path.isfile(index):+ return send_from_directory(app.static_folder, 'index.html')+ return {'message': 'ServerKit API is running', 'docs': '/api/v1/'}, 200++ # Catch-all route for SPA - must be after all other routes+ @app.errorhandler(404)+ def not_found(e):+ from flask import request+ if request.path.startswith('/api/'):+ return {'error': 'Not found'}, 404+ # Serve SPA index.html if it exists, otherwise JSON 404+ index = os.path.join(app.static_folder, 'index.html') if app.static_folder else None+ if index and os.path.isfile(index):+ return send_from_directory(app.static_folder, 'index.html')+ return {'error': 'Not found'}, 404++ return app+++def get_socketio():+ """Get the SocketIO instance."""+ return socketio+++_auto_sync_thread = None+++def _start_auto_sync_scheduler(app):+ """Start a background thread that checks for auto-sync schedules."""+ global _auto_sync_thread+ if _auto_sync_thread is not None:+ return++ import threading+ import time+ import logging++ logger = logging.getLogger(__name__)++ def auto_sync_loop():+ while True:+ try:+ time.sleep(60) # Check every 60 seconds+ with app.app_context():+ _check_auto_sync_schedules(logger)+ except Exception as e:+ logger.error(f'Auto-sync scheduler error: {e}')++ _auto_sync_thread = threading.Thread(+ target=auto_sync_loop,+ daemon=True,+ name='auto-sync-scheduler'+ )+ _auto_sync_thread.start()+++def _check_auto_sync_schedules(logger):+ """Check all auto-sync enabled sites and run syncs that are due."""+ from app.models.wordpress_site import WordPressSite+ from datetime import datetime++ sites = WordPressSite.query.filter_by(auto_sync_enabled=True).all()+ if not sites:+ return++ try:+ from croniter import croniter+ except ImportError:+ logger.debug('croniter not installed, skipping auto-sync check')+ return++ now = datetime.utcnow()++ for site in sites:+ if not site.auto_sync_schedule:+ continue++ try:+ if not croniter.is_valid(site.auto_sync_schedule):+ continue++ cron = croniter(site.auto_sync_schedule, now)+ prev_run = cron.get_prev(datetime)++ # Check if a run was due in the last 90 seconds (to account for check interval)+ seconds_since_due = (now - prev_run).total_seconds()+ if seconds_since_due <= 90:+ logger.info(f'Auto-sync triggered for site {site.id} ({site.name})')+ from app.services.environment_pipeline_service import EnvironmentPipelineService+ EnvironmentPipelineService.sync_from_production(+ env_site_id=site.id,+ sync_type='full',+ user_id=None+ )+ except Exception as e:+ logger.error(f'Auto-sync check failed for site {site.id}: {e}')+++_api_bg_thread = None+++def _start_pairing_pruner(app):+ """Start a background thread that prunes expired PendingAgent rows hourly."""+ global _pairing_prune_thread+ if _pairing_prune_thread is not None:+ return++ import threading+ import time+ import logging++ logger = logging.getLogger(__name__)++ def prune_loop():+ # Wait a bit before first run so app is fully initialized.+ time.sleep(60)+ while True:+ try:+ with app.app_context():+ from app.services import pairing_service+ pairing_service.prune_expired()+ except Exception as e:+ logger.error(f'Pairing pruner error: {e}')+ time.sleep(3600)++ _pairing_prune_thread = threading.Thread(+ target=prune_loop,+ daemon=True,+ name='pairing-pruner'+ )+ _pairing_prune_thread.start()+++_pairing_prune_thread = None+++def _start_api_background_threads(app):+ """Start background threads for API analytics aggregation and event delivery retry."""+ global _api_bg_thread+ if _api_bg_thread is not None:+ return++ import threading+ import time+ import logging++ logger = logging.getLogger(__name__)++ def api_bg_loop():+ while True:+ try:+ time.sleep(3600) # Run hourly+ with app.app_context():+ from app.services.api_analytics_service import ApiAnalyticsService+ ApiAnalyticsService.aggregate_hourly()++ from app.services.event_service import EventService+ EventService.retry_failed()+ except Exception as e:+ logger.error(f'API background thread error: {e}')++ _api_bg_thread = threading.Thread(+ target=api_bg_loop,+ daemon=True,+ name='api-background'+ )+ _api_bg_thread.start()+++_workflow_thread = None+++def _start_workflow_scheduler(app):+ """Start a background thread that checks for scheduled workflows."""+ global _workflow_thread+ if _workflow_thread is not None:+ return++ import threading+ import time+ import logging++ logger = logging.getLogger(__name__)++ def workflow_loop():+ while True:+ try:+ time.sleep(60) # Check every 60 seconds+ with app.app_context():+ _check_workflow_schedules(logger)+ except Exception as e:+ logger.error(f'Workflow scheduler error: {e}')++ _workflow_thread = threading.Thread(+ target=workflow_loop,+ daemon=True,+ name='workflow-scheduler'+ )+ _workflow_thread.start()+++def _check_workflow_schedules(logger):+ """Check all active workflows with cron triggers and run those that are due."""+ from app.models.workflow import Workflow+ from app.services.workflow_engine import WorkflowEngine+ from datetime import datetime+ import json++ try:+ from croniter import croniter+ except ImportError:+ logger.debug('croniter not installed, skipping workflow schedule check')+ return++ # Find active workflows with cron triggers+ workflows = Workflow.query.filter_by(is_active=True, trigger_type='cron').all()+ if not workflows:+ return++ now = datetime.utcnow()++ for workflow in workflows:+ try:+ config = json.loads(workflow.trigger_config) if workflow.trigger_config else {}+ cron_expr = config.get('cron')++ if not cron_expr or not croniter.is_valid(cron_expr):+ continue++ cron = croniter(cron_expr, now)+ prev_run = cron.get_prev(datetime)++ # Check if a run was due in the last 90 seconds+ seconds_since_due = (now - prev_run).total_seconds()++ # Also ensure we don't run it multiple times for the same slot+ if 0 < seconds_since_due <= 90:+ # Check if it already ran in the last 2 minutes+ if workflow.last_run_at:+ seconds_since_last_run = (now - workflow.last_run_at).total_seconds()+ if seconds_since_last_run < 110:+ continue++ logger.info(f'Scheduled workflow triggered: {workflow.name} (ID: {workflow.id})')+ WorkflowEngine.execute_workflow(+ workflow_id=workflow.id,+ trigger_type='cron',+ context={'scheduled_at': prev_run.isoformat()}+ )+ except Exception as e:+ logger.error(f'Workflow schedule check failed for workflow {workflow.id}: {e}')diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 2dfbe74c..76410709 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -1,57 +1,57 @@-from app.models.user import User-from app.models.application import Application-from app.models.domain import Domain-from app.models.env_variable import EnvironmentVariable, EnvironmentVariableHistory-from app.models.notification_preferences import NotificationPreferences-from app.models.deployment import Deployment, DeploymentDiff-from app.models.deployment_job import DeploymentJob, DeploymentJobLog-from app.models.system_settings import SystemSettings-from app.models.audit_log import AuditLog-from app.models.metrics_history import MetricsHistory-from app.models.workflow import Workflow, WorkflowExecution, WorkflowLog-from app.models.webhook import GitWebhook, WebhookLog, GitDeployment-from app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand, AgentSession, AgentVersion, AgentRollout-from app.models.security_alert import SecurityAlert-from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob-from app.models.environment_activity import EnvironmentActivity-from app.models.promotion_job import PromotionJob-from app.models.sanitization_profile import SanitizationProfile-from app.models.email import EmailDomain, EmailAccount, EmailAlias, EmailForwardingRule, DNSProviderConfig-from app.models.oauth_identity import OAuthIdentity-from app.models.source_connection import SourceConnection-from app.models.api_key import ApiKey-from app.models.api_usage import ApiUsageLog, ApiUsageSummary-from app.models.event_subscription import EventSubscription, EventDelivery-from app.models.invitation import Invitation-from app.models.metric_alert import ServerAlertThreshold, MetricAlert-from app.models.agent_plugin import AgentPlugin, AgentPluginInstall-from app.models.server_template import ServerTemplate, ServerTemplateAssignment-from app.models.workspace import Workspace, WorkspaceMember, WorkspaceApiKey-from app.models.dns_zone import DNSZone, DNSRecord-from app.models.status_page import StatusPage, StatusComponent, HealthCheck, StatusIncident, StatusIncidentUpdate-from app.models.cloud_server import CloudProvider, CloudServer, CloudSnapshot-from app.models.marketplace import Extension, ExtensionInstall-from app.models.pending_agent import PendingAgent-from app.models.plugin import InstalledPlugin--__all__ = [- 'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',- 'NotificationPreferences', 'Deployment', 'DeploymentDiff', 'DeploymentJob', 'DeploymentJobLog', 'SystemSettings', 'AuditLog',- 'MetricsHistory', 'Workflow', 'WorkflowExecution', 'WorkflowLog', 'GitWebhook', 'WebhookLog', 'GitDeployment',- 'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'AgentVersion', 'AgentRollout', 'SecurityAlert',- 'WordPressSite', 'DatabaseSnapshot', 'SyncJob',- 'EnvironmentActivity', 'PromotionJob', 'SanitizationProfile',- 'EmailDomain', 'EmailAccount', 'EmailAlias', 'EmailForwardingRule', 'DNSProviderConfig',- 'OAuthIdentity', 'SourceConnection', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',- 'EventSubscription', 'EventDelivery', 'Invitation',- 'ServerAlertThreshold', 'MetricAlert',- 'AgentPlugin', 'AgentPluginInstall',- 'ServerTemplate', 'ServerTemplateAssignment',- 'Workspace', 'WorkspaceMember', 'WorkspaceApiKey',- 'DNSZone', 'DNSRecord',- 'StatusPage', 'StatusComponent', 'HealthCheck', 'StatusIncident', 'StatusIncidentUpdate',- 'CloudProvider', 'CloudServer', 'CloudSnapshot',- 'Extension', 'ExtensionInstall',- 'PendingAgent',- 'InstalledPlugin',-]+from app.models.user import User+from app.models.application import Application+from app.models.domain import Domain+from app.models.env_variable import EnvironmentVariable, EnvironmentVariableHistory+from app.models.notification_preferences import NotificationPreferences+from app.models.deployment import Deployment, DeploymentDiff+from app.models.deployment_job import DeploymentJob, DeploymentJobLog+from app.models.system_settings import SystemSettings+from app.models.audit_log import AuditLog+from app.models.metrics_history import MetricsHistory+from app.models.workflow import Workflow, WorkflowExecution, WorkflowLog+from app.models.webhook import GitWebhook, WebhookLog, GitDeployment+from app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand, AgentSession, AgentVersion, AgentRollout+from app.models.security_alert import SecurityAlert+from app.models.wordpress_site import WordPressSite, DatabaseSnapshot, SyncJob+from app.models.environment_activity import EnvironmentActivity+from app.models.promotion_job import PromotionJob+from app.models.sanitization_profile import SanitizationProfile+from app.models.email import EmailDomain, EmailAccount, EmailAlias, EmailForwardingRule, DNSProviderConfig+from app.models.oauth_identity import OAuthIdentity+from app.models.source_connection import SourceConnection+from app.models.api_key import ApiKey+from app.models.api_usage import ApiUsageLog, ApiUsageSummary+from app.models.event_subscription import EventSubscription, EventDelivery+from app.models.invitation import Invitation+from app.models.metric_alert import ServerAlertThreshold, MetricAlert+from app.models.agent_plugin import AgentPlugin, AgentPluginInstall+from app.models.server_template import ServerTemplate, ServerTemplateAssignment+from app.models.workspace import Workspace, WorkspaceMember, WorkspaceApiKey+from app.models.dns_zone import DNSZone, DNSRecord+from app.models.status_page import StatusPage, StatusComponent, HealthCheck, StatusIncident, StatusIncidentUpdate+from app.models.cloud_server import CloudProvider, CloudServer, CloudSnapshot+from app.models.marketplace import Extension, ExtensionInstall+from app.models.pending_agent import PendingAgent+from app.models.plugin import InstalledPlugin++__all__ = [+ 'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',+ 'NotificationPreferences', 'Deployment', 'DeploymentDiff', 'DeploymentJob', 'DeploymentJobLog', 'SystemSettings', 'AuditLog',+ 'MetricsHistory', 'Workflow', 'WorkflowExecution', 'WorkflowLog', 'GitWebhook', 'WebhookLog', 'GitDeployment',+ 'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'AgentVersion', 'AgentRollout', 'SecurityAlert',+ 'WordPressSite', 'DatabaseSnapshot', 'SyncJob',+ 'EnvironmentActivity', 'PromotionJob', 'SanitizationProfile',+ 'EmailDomain', 'EmailAccount', 'EmailAlias', 'EmailForwardingRule', 'DNSProviderConfig',+ 'OAuthIdentity', 'SourceConnection', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',+ 'EventSubscription', 'EventDelivery', 'Invitation',+ 'ServerAlertThreshold', 'MetricAlert',+ 'AgentPlugin', 'AgentPluginInstall',+ 'ServerTemplate', 'ServerTemplateAssignment',+ 'Workspace', 'WorkspaceMember', 'WorkspaceApiKey',+ 'DNSZone', 'DNSRecord',+ 'StatusPage', 'StatusComponent', 'HealthCheck', 'StatusIncident', 'StatusIncidentUpdate',+ 'CloudProvider', 'CloudServer', 'CloudSnapshot',+ 'Extension', 'ExtensionInstall',+ 'PendingAgent',+ 'InstalledPlugin',+]diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 79b004d9..d6bdb086 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -1,187 +1,187 @@-import { useEffect } from 'react';+import { useEffect } from 'react';import { BrowserRouter as Router, Routes, Route, Navigate, useLocation, useParams } from 'react-router-dom';-import { AuthProvider, useAuth } from './contexts/AuthContext';-import { ToastProvider } from './contexts/ToastContext';-import { ThemeProvider } from './contexts/ThemeContext';-import { ResourceTierProvider } from './contexts/ResourceTierContext';-import { Toaster } from './components/ui/sonner';-import DashboardLayout from './layouts/DashboardLayout';-import Dashboard from './pages/Dashboard';-import Login from './pages/Login';-import Register from './pages/Register';-import Setup from './pages/Setup';-import ApplicationDetail from './pages/ApplicationDetail';-import Docker from './pages/Docker';-import Databases from './pages/Databases';-import Domains from './pages/Domains';-import Monitoring from './pages/Monitoring';-import Backups from './pages/Backups';-import Terminal from './pages/Terminal';-import Settings from './pages/Settings';-import FileManager from './pages/FileManager';-import FTPServer from './pages/FTPServer';+import { AuthProvider, useAuth } from './contexts/AuthContext';+import { ToastProvider } from './contexts/ToastContext';+import { ThemeProvider } from './contexts/ThemeContext';+import { ResourceTierProvider } from './contexts/ResourceTierContext';+import { Toaster } from './components/ui/sonner';+import DashboardLayout from './layouts/DashboardLayout';+import Dashboard from './pages/Dashboard';+import Login from './pages/Login';+import Register from './pages/Register';+import Setup from './pages/Setup';+import ApplicationDetail from './pages/ApplicationDetail';+import Docker from './pages/Docker';+import Databases from './pages/Databases';+import Domains from './pages/Domains';+import Monitoring from './pages/Monitoring';+import Backups from './pages/Backups';+import Terminal from './pages/Terminal';+import Settings from './pages/Settings';+import FileManager from './pages/FileManager';+import FTPServer from './pages/FTPServer';// Firewall is now part of Security pageimport CronJobs from './pages/CronJobs';-import Security from './pages/Security';-import Services from './pages/Services';-import NewService from './pages/NewService';-import ServiceDetail from './pages/ServiceDetail';-import Templates from './pages/Templates';-import WorkflowBuilder from './pages/WorkflowBuilder';-import Servers from './pages/Servers';-import ServerDetail from './pages/ServerDetail';-import AgentFleet from './pages/AgentFleet';-import FleetMonitor from './pages/FleetMonitor';-import Downloads from './pages/Downloads';-import WordPress from './pages/WordPress';-import WordPressDetail from './pages/WordPressDetail';-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 SourceConnectionCallback from './pages/SourceConnectionCallback';-import DatabaseMigration from './pages/DatabaseMigration';-import ServerTemplates from './pages/ServerTemplates';-import Workspaces from './pages/Workspaces';+import Security from './pages/Security';+import Services from './pages/Services';+import NewService from './pages/NewService';+import ServiceDetail from './pages/ServiceDetail';+import Templates from './pages/Templates';+import WorkflowBuilder from './pages/WorkflowBuilder';+import Servers from './pages/Servers';+import ServerDetail from './pages/ServerDetail';+import AgentFleet from './pages/AgentFleet';+import FleetMonitor from './pages/FleetMonitor';+import Downloads from './pages/Downloads';+import WordPress from './pages/WordPress';+import WordPressDetail from './pages/WordPressDetail';+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 SourceConnectionCallback from './pages/SourceConnectionCallback';+import DatabaseMigration from './pages/DatabaseMigration';+import ServerTemplates from './pages/ServerTemplates';+import Workspaces from './pages/Workspaces';import DNSZones from './pages/DNSZones';import StatusPages from './pages/StatusPages';import PublicStatusPage from './pages/PublicStatusPage';import CloudProvision from './pages/CloudProvision';-import Marketplace from './pages/Marketplace';-import StyleGuide from './pages/StyleGuide';-import AppMap from './pages/AppMap';-import Documentation from './pages/Documentation';-import Deployments from './pages/Deployments';-import useExtensionRoutes from './plugins/ExtensionRoutes';-import { useContributions } from './plugins/contributions';--// Page title mapping-const PAGE_TITLES = {- '/': 'Dashboard',- '/login': 'Login',- '/register': 'Register',- '/setup': 'Setup',- '/services': 'Services',- '/services/new': 'New Service',- '/apps': 'Applications',- '/wordpress': 'WordPress Sites',- '/wordpress/projects': 'WordPress Projects',- '/templates': 'Templates',- '/deployments': 'Deployment Activity',- '/workflow': 'Workflow Builder',- '/domains': 'Domains',- '/databases': 'Databases',- '/ssl': 'SSL Certificates',- '/docker': 'Docker',- '/servers': 'Servers',- '/downloads': 'Downloads',- '/files': 'File Manager',- '/ftp': 'FTP Server',- '/monitoring': 'Monitoring',- '/backups': 'Backups',- '/cron': 'Cron Jobs',- '/security': 'Security',- '/email': 'Email Server',- '/terminal': 'Terminal',- '/settings': 'Settings',- '/connections/callback/github': 'GitHub Connection',- '/migrate': 'Database Migration',- '/fleet': 'Agent Fleet',- '/fleet-monitor': 'Fleet Monitor',- '/agent-plugins': 'Marketplace',- '/server-templates': 'Server Templates',- '/workspaces': 'Workspaces',- '/dns': 'DNS Zones',- '/status-pages': 'Status Pages',- '/cloud': 'Cloud Provisioning',- '/marketplace': 'Marketplace',- '/style-guide': 'Style Guide',- '/app-map': 'App Map',- '/documentation': 'Documentation',-};--function PageTitleUpdater() {- const location = useLocation();- const { page_titles: pluginTitles } = useContributions();-- useEffect(() => {- const path = location.pathname;- let title = PAGE_TITLES[path] || (pluginTitles && pluginTitles[path]);-- // Handle dynamic routes and tab sub-routes- if (!title) {- // Check if it's a base page with a tab suffix (e.g., /security/firewall)- const basePath = '/' + path.split('/')[1];- if (PAGE_TITLES[basePath]) {- title = PAGE_TITLES[basePath];- } else if (pluginTitles && pluginTitles[basePath]) {- title = pluginTitles[basePath];- } else if (path.startsWith('/services/')) title = 'Service Details';- else if (path.startsWith('/apps/')) title = 'Application Details';- else if (path.startsWith('/servers/')) title = 'Server Details';- else if (path.startsWith('/wordpress/projects/')) title = 'WordPress Pipeline';- else if (path.startsWith('/wordpress/')) title = 'WordPress Site';- else title = 'ServerKit';- }-- document.title = title ? `${title} | ServerKit` : 'ServerKit';- }, [location, pluginTitles]);-- return null;-}--function PrivateRoute({ children }) {- const { isAuthenticated, loading, needsSetup, needsMigration } = useAuth();-- if (loading) {- return <div className="loading">Loading...</div>;- }-- // Priority: migrations > setup > auth- if (needsMigration) {- return <Navigate to="/migrate" />;- }-- if (needsSetup) {- return <Navigate to="/setup" />;- }-- return isAuthenticated ? children : <Navigate to="/login" />;-}--function PublicRoute({ children }) {- const { isAuthenticated, loading, needsSetup, needsMigration } = useAuth();-- if (loading) {- return <div className="loading">Loading...</div>;- }-- // Priority: migrations > setup > auth- if (needsMigration) {- return <Navigate to="/migrate" />;- }-- if (needsSetup) {- return <Navigate to="/setup" />;- }-- return isAuthenticated ? <Navigate to="/" /> : children;-}-+import Marketplace from './pages/Marketplace';+import StyleGuide from './pages/StyleGuide';+import AppMap from './pages/AppMap';+import Documentation from './pages/Documentation';+import Deployments from './pages/Deployments';+import useExtensionRoutes from './plugins/ExtensionRoutes';+import { useContributions } from './plugins/contributions';++// Page title mapping+const PAGE_TITLES = {+ '/': 'Dashboard',+ '/login': 'Login',+ '/register': 'Register',+ '/setup': 'Setup',+ '/services': 'Services',+ '/services/new': 'New Service',+ '/apps': 'Applications',+ '/wordpress': 'WordPress Sites',+ '/wordpress/projects': 'WordPress Projects',+ '/templates': 'Templates',+ '/deployments': 'Deployment Activity',+ '/workflow': 'Workflow Builder',+ '/domains': 'Domains',+ '/databases': 'Databases',+ '/ssl': 'SSL Certificates',+ '/docker': 'Docker',+ '/servers': 'Servers',+ '/downloads': 'Downloads',+ '/files': 'File Manager',+ '/ftp': 'FTP Server',+ '/monitoring': 'Monitoring',+ '/backups': 'Backups',+ '/cron': 'Cron Jobs',+ '/security': 'Security',+ '/email': 'Email Server',+ '/terminal': 'Terminal',+ '/settings': 'Settings',+ '/connections/callback/github': 'GitHub Connection',+ '/migrate': 'Database Migration',+ '/fleet': 'Agent Fleet',+ '/fleet-monitor': 'Fleet Monitor',+ '/agent-plugins': 'Marketplace',+ '/server-templates': 'Server Templates',+ '/workspaces': 'Workspaces',+ '/dns': 'DNS Zones',+ '/status-pages': 'Status Pages',+ '/cloud': 'Cloud Provisioning',+ '/marketplace': 'Marketplace',+ '/style-guide': 'Style Guide',+ '/app-map': 'App Map',+ '/documentation': 'Documentation',+};++function PageTitleUpdater() {+ const location = useLocation();+ const { page_titles: pluginTitles } = useContributions();++ useEffect(() => {+ const path = location.pathname;+ let title = PAGE_TITLES[path] || (pluginTitles && pluginTitles[path]);++ // Handle dynamic routes and tab sub-routes+ if (!title) {+ // Check if it's a base page with a tab suffix (e.g., /security/firewall)+ const basePath = '/' + path.split('/')[1];+ if (PAGE_TITLES[basePath]) {+ title = PAGE_TITLES[basePath];+ } else if (pluginTitles && pluginTitles[basePath]) {+ title = pluginTitles[basePath];+ } else if (path.startsWith('/services/')) title = 'Service Details';+ else if (path.startsWith('/apps/')) title = 'Application Details';+ else if (path.startsWith('/servers/')) title = 'Server Details';+ else if (path.startsWith('/wordpress/projects/')) title = 'WordPress Pipeline';+ else if (path.startsWith('/wordpress/')) title = 'WordPress Site';+ else title = 'ServerKit';+ }++ document.title = title ? `${title} | ServerKit` : 'ServerKit';+ }, [location, pluginTitles]);++ return null;+}++function PrivateRoute({ children }) {+ const { isAuthenticated, loading, needsSetup, needsMigration } = useAuth();++ if (loading) {+ return <div className="loading">Loading...</div>;+ }++ // Priority: migrations > setup > auth+ if (needsMigration) {+ return <Navigate to="/migrate" />;+ }++ if (needsSetup) {+ return <Navigate to="/setup" />;+ }++ return isAuthenticated ? children : <Navigate to="/login" />;+}++function PublicRoute({ children }) {+ const { isAuthenticated, loading, needsSetup, needsMigration } = useAuth();++ if (loading) {+ return <div className="loading">Loading...</div>;+ }++ // Priority: migrations > setup > auth+ if (needsMigration) {+ return <Navigate to="/migrate" />;+ }++ if (needsSetup) {+ return <Navigate to="/setup" />;+ }++ return isAuthenticated ? <Navigate to="/" /> : children;+}+function SetupRoute({ children }) {- const { loading, needsSetup, isAuthenticated } = useAuth();-- if (loading) {- return <div className="loading">Loading...</div>;- }-- // If setup is not needed, redirect appropriately- if (!needsSetup) {- return isAuthenticated ? <Navigate to="/" /> : <Navigate to="/login" />;- }-- return children;+ const { loading, needsSetup, isAuthenticated } = useAuth();++ if (loading) {+ return <div className="loading">Loading...</div>;+ }++ // If setup is not needed, redirect appropriately+ if (!needsSetup) {+ return isAuthenticated ? <Navigate to="/" /> : <Navigate to="/login" />;+ }++ return children;}function LegacyGitExtRedirect() {@@ -190,30 +190,30 @@ function LegacyGitExtRedirect() {}function AppRoutes() {- const { dashboardRoutes, standaloneGroups } = useExtensionRoutes();- return (- <Routes>- <Route path="/migrate" element={<DatabaseMigration />} />- <Route path="/setup" element={- <SetupRoute>- <Setup />- </SetupRoute>- } />- <Route path="/login" element={- <PublicRoute>- <Login />- </PublicRoute>- } />- <Route path="/login/callback/:provider" element={- <PublicRoute>- <SSOCallback />- </PublicRoute>- } />- <Route path="/register" element={- <PublicRoute>- <Register />- </PublicRoute>- } />+ const { dashboardRoutes, standaloneGroups } = useExtensionRoutes();+ return (+ <Routes>+ <Route path="/migrate" element={<DatabaseMigration />} />+ <Route path="/setup" element={+ <SetupRoute>+ <Setup />+ </SetupRoute>+ } />+ <Route path="/login" element={+ <PublicRoute>+ <Login />+ </PublicRoute>+ } />+ <Route path="/login/callback/:provider" element={+ <PublicRoute>+ <SSOCallback />+ </PublicRoute>+ } />+ <Route path="/register" element={+ <PublicRoute>+ <Register />+ </PublicRoute>+ } /><Route path="/connections/callback/:provider" element={<PrivateRoute><SourceConnectionCallback />@@ -222,105 +222,105 @@ function AppRoutes() {<Route path="/status/:slug" element={<PublicStatusPage />} />{/* Standalone plugin layouts — bare or custom. Each group isa sibling top-level Route under PrivateRoute, so the- plugin owns the chrome (no DashboardLayout sidebar). */}- {standaloneGroups.map((group) => {- const Layout = group.LayoutComponent;- return (- <Route- key={`standalone:${group.layoutId}`}- element={<PrivateRoute><Layout /></PrivateRoute>}- >- {group.routes}- </Route>- );- })}- <Route path="/" element={- <PrivateRoute>- <DashboardLayout />- </PrivateRoute>- }>- <Route index element={<Dashboard />} />- <Route path="services" element={<Services />} />- <Route path="services/new" element={<NewService />} />- <Route path="services/:id" element={<ServiceDetail />} />- <Route path="apps" element={<Navigate to="/services" replace />} />- <Route path="apps/:id" element={<ApplicationDetail />} />- <Route path="apps/:id/:tab" element={<ApplicationDetail />} />- <Route path="wordpress" element={<WordPress />} />- <Route path="wordpress/projects" element={<WordPressProjects />} />- <Route path="wordpress/projects/:id" element={<WordPressProject />} />- <Route path="wordpress/projects/:id/:tab" element={<WordPressProject />} />- <Route path="wordpress/:id" element={<WordPressDetail />} />- <Route path="wordpress/:id/:tab" element={<WordPressDetail />} />- <Route path="templates" element={<Templates />} />- <Route path="deployments" element={<Deployments />} />- <Route path="deployments/:jobId" element={<Deployments />} />- <Route path="workflow" element={<WorkflowBuilder />} />- <Route path="domains" element={<Domains />} />- <Route path="databases" element={<Databases />} />- <Route path="databases/:tab" element={<Databases />} />- <Route path="ssl" element={<SSLCertificates />} />- <Route path="docker" element={<Docker />} />- <Route path="docker/:tab" element={<Docker />} />- <Route path="servers" element={<Servers />} />- <Route path="servers/:id" element={<ServerDetail />} />- <Route path="servers/:id/:tab" element={<ServerDetail />} />- <Route path="fleet" element={<AgentFleet />} />- <Route path="fleet-monitor" element={<FleetMonitor />} />- <Route path="agent-plugins" element={<Navigate to="/marketplace" replace />} />- <Route path="server-templates" element={<ServerTemplates />} />- <Route path="workspaces" element={<Workspaces />} />- <Route path="dns" element={<DNSZones />} />- <Route path="status-pages" element={<StatusPages />} />- <Route path="cloud" element={<CloudProvision />} />- <Route path="marketplace" element={<Marketplace />} />- <Route path="style-guide" element={<StyleGuide />} />- <Route path="style-guide/:tab" element={<StyleGuide />} />- <Route path="app-map" element={<AppMap />} />- <Route path="app-map/:tab" element={<AppMap />} />+ plugin owns the chrome (no DashboardLayout sidebar). */}+ {standaloneGroups.map((group) => {+ const Layout = group.LayoutComponent;+ return (+ <Route+ key={`standalone:${group.layoutId}`}+ element={<PrivateRoute><Layout /></PrivateRoute>}+ >+ {group.routes}+ </Route>+ );+ })}+ <Route path="/" element={+ <PrivateRoute>+ <DashboardLayout />+ </PrivateRoute>+ }>+ <Route index element={<Dashboard />} />+ <Route path="services" element={<Services />} />+ <Route path="services/new" element={<NewService />} />+ <Route path="services/:id" element={<ServiceDetail />} />+ <Route path="apps" element={<Navigate to="/services" replace />} />+ <Route path="apps/:id" element={<ApplicationDetail />} />+ <Route path="apps/:id/:tab" element={<ApplicationDetail />} />+ <Route path="wordpress" element={<WordPress />} />+ <Route path="wordpress/projects" element={<WordPressProjects />} />+ <Route path="wordpress/projects/:id" element={<WordPressProject />} />+ <Route path="wordpress/projects/:id/:tab" element={<WordPressProject />} />+ <Route path="wordpress/:id" element={<WordPressDetail />} />+ <Route path="wordpress/:id/:tab" element={<WordPressDetail />} />+ <Route path="templates" element={<Templates />} />+ <Route path="deployments" element={<Deployments />} />+ <Route path="deployments/:jobId" element={<Deployments />} />+ <Route path="workflow" element={<WorkflowBuilder />} />+ <Route path="domains" element={<Domains />} />+ <Route path="databases" element={<Databases />} />+ <Route path="databases/:tab" element={<Databases />} />+ <Route path="ssl" element={<SSLCertificates />} />+ <Route path="docker" element={<Docker />} />+ <Route path="docker/:tab" element={<Docker />} />+ <Route path="servers" element={<Servers />} />+ <Route path="servers/:id" element={<ServerDetail />} />+ <Route path="servers/:id/:tab" element={<ServerDetail />} />+ <Route path="fleet" element={<AgentFleet />} />+ <Route path="fleet-monitor" element={<FleetMonitor />} />+ <Route path="agent-plugins" element={<Navigate to="/marketplace" replace />} />+ <Route path="server-templates" element={<ServerTemplates />} />+ <Route path="workspaces" element={<Workspaces />} />+ <Route path="dns" element={<DNSZones />} />+ <Route path="status-pages" element={<StatusPages />} />+ <Route path="cloud" element={<CloudProvision />} />+ <Route path="marketplace" element={<Marketplace />} />+ <Route path="style-guide" element={<StyleGuide />} />+ <Route path="style-guide/:tab" element={<StyleGuide />} />+ <Route path="app-map" element={<AppMap />} />+ <Route path="app-map/:tab" element={<AppMap />} /><Route path="documentation" element={<Documentation />} /><Route path="downloads" element={<Downloads />} /><Route path="firewall" element={<Navigate to="/security/firewall" replace />} /><Route path="git-ext" element={<LegacyGitExtRedirect />} /><Route path="git-ext/:tab" element={<LegacyGitExtRedirect />} /><Route path="files" element={<FileManager />} />- <Route path="ftp" element={<FTPServer />} />- <Route path="ftp/:tab" element={<FTPServer />} />- <Route path="monitoring" element={<Monitoring />} />- <Route path="monitoring/:tab" element={<Monitoring />} />- <Route path="backups" element={<Backups />} />- <Route path="backups/:tab" element={<Backups />} />- <Route path="cron" element={<CronJobs />} />- <Route path="security" element={<Security />} />- <Route path="security/:tab" element={<Security />} />- <Route path="email" element={<Email />} />- <Route path="email/:tab" element={<Email />} />- <Route path="terminal" element={<Terminal />} />- <Route path="terminal/:tab" element={<Terminal />} />- <Route path="settings" element={<Settings />} />- <Route path="settings/:tab" element={<Settings />} />- {dashboardRoutes}- </Route>- </Routes>- );-}--function App() {- return (- <Router>- <PageTitleUpdater />- <ThemeProvider>- <AuthProvider>- <ResourceTierProvider>- <ToastProvider>- <AppRoutes />- <Toaster />- </ToastProvider>- </ResourceTierProvider>- </AuthProvider>- </ThemeProvider>- </Router>- );-}--export default App;+ <Route path="ftp" element={<FTPServer />} />+ <Route path="ftp/:tab" element={<FTPServer />} />+ <Route path="monitoring" element={<Monitoring />} />+ <Route path="monitoring/:tab" element={<Monitoring />} />+ <Route path="backups" element={<Backups />} />+ <Route path="backups/:tab" element={<Backups />} />+ <Route path="cron" element={<CronJobs />} />+ <Route path="security" element={<Security />} />+ <Route path="security/:tab" element={<Security />} />+ <Route path="email" element={<Email />} />+ <Route path="email/:tab" element={<Email />} />+ <Route path="terminal" element={<Terminal />} />+ <Route path="terminal/:tab" element={<Terminal />} />+ <Route path="settings" element={<Settings />} />+ <Route path="settings/:tab" element={<Settings />} />+ {dashboardRoutes}+ </Route>+ </Routes>+ );+}++function App() {+ return (+ <Router>+ <PageTitleUpdater />+ <ThemeProvider>+ <AuthProvider>+ <ResourceTierProvider>+ <ToastProvider>+ <AppRoutes />+ <Toaster />+ </ToastProvider>+ </ResourceTierProvider>+ </AuthProvider>+ </ThemeProvider>+ </Router>+ );+}++export default App;