ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add agent plugin system with full lifecycle management
Juan Denis3cc94d1e0395
diff --git a/ROADMAP.md b/ROADMAP.mdindex d7f9e076..ec57c2f0 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 (Planned)--**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-- [ ] Plugin specification — standard interface (init, healthcheck, metrics, commands)-- [ ] Plugin manifest format (YAML/JSON) — name, version, dependencies, capabilities, permissions-- [ ] Plugin lifecycle management — install, enable, disable, uninstall, upgrade-- [ ] Plugin isolation — each plugin runs in its own process/sandbox with resource limits-- [ ] Plugin communication — standardized IPC between plugin and agent core--### Plugin Capabilities-- [ ] Custom metrics reporters — plugins can push arbitrary metrics to the panel-- [ ] Custom health checks — plugins define checks that feed into the status system-- [ ] Custom commands — plugins register new command types the panel can invoke-- [ ] Scheduled tasks — plugins can register periodic jobs (cron-like)-- [ ] Event hooks — plugins can react to agent events (connect, disconnect, command, alert)-------## Phase 29: Server Templates & Config Sync (Planned)--**Priority: Medium**--Define what a server should look like, apply it, and detect when it drifts.--- [ ] Server template builder — define expected state (packages, services, firewall rules, users, files)-- [ ] Template library — save and reuse templates (e.g., "Web Server", "Database Server", "Mail Server")-- [ ] Apply template to server — install packages, configure services, set firewall rules via agent-- [ ] Config drift detection — periodic comparison of actual vs. expected state-- [ ] Drift report UI — visual diff showing what changed and when-- [ ] Auto-remediation option — automatically fix drift back to template (with approval toggle)-- [ ] Template versioning — track changes to templates over time-- [ ] Template inheritance — base template + role-specific overrides-- [ ] Bulk apply — roll out template changes across server groups-- [ ] Compliance dashboard — percentage of fleet in compliance per template-------## Phase 30: Multi-Tenancy & Workspaces (Planned)--**Priority: Medium**--Isolate servers by team, client, or project. Essential for agencies, MSPs, and larger teams.--- [ ] Workspace model — isolated container for servers, users, and settings-- [ ] Workspace CRUD — create, rename, archive workspaces-- [ ] Server assignment — each server belongs to exactly one workspace-- [ ] User workspace membership — users can belong to multiple workspaces with different roles-- [ ] Workspace switching — quick-switch dropdown in the header-- [ ] Per-workspace settings — notification preferences, default templates, branding-- [ ] Workspace-scoped API keys — API keys restricted to a single workspace-- [ ] Cross-workspace admin view — super-admin can see all workspaces and usage-- [ ] Workspace usage quotas — limit servers, users, or API calls per workspace-- [ ] Workspace billing integration — track resource usage per workspace for invoicing-------## Phase 31: Advanced SSL Features (Planned)--**Priority: Medium**--- [x] Certificate expiry monitoring-- [ ] Wildcard SSL certificates via DNS-01 challenge-- [ ] Multi-domain certificates (SAN)-- [ ] Custom certificate upload (key + cert + chain)-- [ ] Certificate expiry notifications (email/webhook alerts before expiration)-- [ ] SSL configuration templates (modern, intermediate, legacy compatibility)-- [ ] SSL health check dashboard (grade, cipher suites, protocol versions)-------## Phase 32: DNS Zone Management (Planned)--**Priority: Medium**--Full DNS record management with provider API integration.--- [ ] DNS zone editor UI (A, AAAA, CNAME, MX, TXT, SRV, CAA records)-- [ ] Cloudflare API integration (list/create/update/delete records)-- [ ] Route53 API integration-- [ ] DigitalOcean DNS integration-- [ ] DNS propagation checker (query multiple nameservers)-- [ ] Auto-generate recommended records for hosted services (SPF, DKIM, DMARC, MX)-- [ ] DNS template presets (e.g., "standard web hosting", "email hosting")-- [ ] Bulk record import/export (BIND zone file format)-------## Phase 33: Nginx Advanced Configuration (Planned)--**Priority: Medium**--Go beyond basic virtual hosts — full reverse proxy and performance configuration.--- [ ] Visual reverse proxy rule builder (upstream servers, load balancing methods)-- [ ] Load balancing configuration (round-robin, least connections, IP hash)-- [ ] Caching rules editor (proxy cache zones, TTLs, cache bypass rules)-- [ ] Rate limiting at proxy level (per-IP, per-route)-- [ ] Custom location block editor with syntax validation-- [ ] Header manipulation (add/remove/modify request/response headers)-- [ ] Nginx config syntax check before applying changes-- [ ] Config diff preview before saving-- [ ] Access/error log viewer per virtual host-------## Phase 34: Status Page & Health Checks (Planned)--**Priority: Medium**--Public-facing status page and automated health monitoring.--- [ ] Automated health checks (HTTP, TCP, DNS, SMTP) with configurable intervals-- [ ] Public status page (standalone URL, no auth required)-- [ ] Status page customization (logo, colors, custom domain)-- [ ] Service grouping on status page (e.g., "Web Services", "Email", "APIs")-- [ ] Incident management — create, update, resolve incidents with timeline-- [ ] Uptime percentage display (24h, 7d, 30d, 90d)-- [ ] Scheduled maintenance windows with advance notifications-- [ ] Status page subscribers (email/webhook notifications on incidents)-- [ ] Historical uptime graphs-- [ ] Status badge embeds (SVG/PNG for README files)-------## Phase 35: Server Provisioning APIs (Planned)--**Priority: Medium**--Spin up and manage cloud servers directly from the panel.--- [ ] DigitalOcean API integration (create/destroy/resize droplets)-- [ ] Hetzner Cloud API integration-- [ ] Vultr API integration-- [ ] Linode/Akamai API integration-- [ ] Server creation wizard (region, size, OS, SSH keys)-- [ ] Auto-install ServerKit agent on provisioned servers-- [ ] Server cost tracking and billing overview-- [ ] Snapshot management (create/restore/delete)-- [ ] One-click server cloning-- [ ] Destroy server with confirmation safeguards-------## Phase 36: Performance Optimization (Planned)--**Priority: Low**--- [ ] Redis caching for frequently accessed data (metrics, server status)-- [ ] Database query optimization and slow query logging-- [ ] Background job queue (Celery or RQ) for long-running tasks-- [ ] Lazy loading for large datasets (paginated API responses)-- [ ] WebSocket connection pooling and reconnection improvements-- [ ] Frontend bundle optimization and code splitting-------## Phase 37: Mobile App (Future)--**Priority: Low — v3.0+**--- [ ] React Native or PWA mobile application-- [ ] Push notifications for alerts and incidents-- [ ] Quick actions (restart services, view stats, acknowledge alerts)-- [ ] Biometric authentication (fingerprint/Face ID)-- [ ] Offline mode with cached server status-------## Phase 38: Marketplace & Extensions (Future)--**Priority: Low — v3.0+**--- [ ] Plugin/extension system with API hooks-- [ ] Community marketplace for plugins-- [ ] Custom dashboard widgets-- [ ] Theme customization (colors, layout, branding)-- [ ] 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 | In Progress |-| v1.8.0 | Server templates, multi-tenancy | Planned |-| v1.9.0 | Advanced SSL, DNS management, Nginx config | Planned |-| v2.0.0 | Status pages, server provisioning, performance | Planned |-| v3.0.0 | Mobile app, Marketplace | Future |-------## 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 (Planned)++**Priority: Medium**++Define what a server should look like, apply it, and detect when it drifts.++- [ ] Server template builder — define expected state (packages, services, firewall rules, users, files)+- [ ] Template library — save and reuse templates (e.g., "Web Server", "Database Server", "Mail Server")+- [ ] Apply template to server — install packages, configure services, set firewall rules via agent+- [ ] Config drift detection — periodic comparison of actual vs. expected state+- [ ] Drift report UI — visual diff showing what changed and when+- [ ] Auto-remediation option — automatically fix drift back to template (with approval toggle)+- [ ] Template versioning — track changes to templates over time+- [ ] Template inheritance — base template + role-specific overrides+- [ ] Bulk apply — roll out template changes across server groups+- [ ] Compliance dashboard — percentage of fleet in compliance per template++---++## Phase 30: Multi-Tenancy & Workspaces (Planned)++**Priority: Medium**++Isolate servers by team, client, or project. Essential for agencies, MSPs, and larger teams.++- [ ] Workspace model — isolated container for servers, users, and settings+- [ ] Workspace CRUD — create, rename, archive workspaces+- [ ] Server assignment — each server belongs to exactly one workspace+- [ ] User workspace membership — users can belong to multiple workspaces with different roles+- [ ] Workspace switching — quick-switch dropdown in the header+- [ ] Per-workspace settings — notification preferences, default templates, branding+- [ ] Workspace-scoped API keys — API keys restricted to a single workspace+- [ ] Cross-workspace admin view — super-admin can see all workspaces and usage+- [ ] Workspace usage quotas — limit servers, users, or API calls per workspace+- [ ] Workspace billing integration — track resource usage per workspace for invoicing++---++## Phase 31: Advanced SSL Features (Planned)++**Priority: Medium**++- [x] Certificate expiry monitoring+- [ ] Wildcard SSL certificates via DNS-01 challenge+- [ ] Multi-domain certificates (SAN)+- [ ] Custom certificate upload (key + cert + chain)+- [ ] Certificate expiry notifications (email/webhook alerts before expiration)+- [ ] SSL configuration templates (modern, intermediate, legacy compatibility)+- [ ] SSL health check dashboard (grade, cipher suites, protocol versions)++---++## Phase 32: DNS Zone Management (Planned)++**Priority: Medium**++Full DNS record management with provider API integration.++- [ ] DNS zone editor UI (A, AAAA, CNAME, MX, TXT, SRV, CAA records)+- [ ] Cloudflare API integration (list/create/update/delete records)+- [ ] Route53 API integration+- [ ] DigitalOcean DNS integration+- [ ] DNS propagation checker (query multiple nameservers)+- [ ] Auto-generate recommended records for hosted services (SPF, DKIM, DMARC, MX)+- [ ] DNS template presets (e.g., "standard web hosting", "email hosting")+- [ ] Bulk record import/export (BIND zone file format)++---++## Phase 33: Nginx Advanced Configuration (Planned)++**Priority: Medium**++Go beyond basic virtual hosts — full reverse proxy and performance configuration.++- [ ] Visual reverse proxy rule builder (upstream servers, load balancing methods)+- [ ] Load balancing configuration (round-robin, least connections, IP hash)+- [ ] Caching rules editor (proxy cache zones, TTLs, cache bypass rules)+- [ ] Rate limiting at proxy level (per-IP, per-route)+- [ ] Custom location block editor with syntax validation+- [ ] Header manipulation (add/remove/modify request/response headers)+- [ ] Nginx config syntax check before applying changes+- [ ] Config diff preview before saving+- [ ] Access/error log viewer per virtual host++---++## Phase 34: Status Page & Health Checks (Planned)++**Priority: Medium**++Public-facing status page and automated health monitoring.++- [ ] Automated health checks (HTTP, TCP, DNS, SMTP) with configurable intervals+- [ ] Public status page (standalone URL, no auth required)+- [ ] Status page customization (logo, colors, custom domain)+- [ ] Service grouping on status page (e.g., "Web Services", "Email", "APIs")+- [ ] Incident management — create, update, resolve incidents with timeline+- [ ] Uptime percentage display (24h, 7d, 30d, 90d)+- [ ] Scheduled maintenance windows with advance notifications+- [ ] Status page subscribers (email/webhook notifications on incidents)+- [ ] Historical uptime graphs+- [ ] Status badge embeds (SVG/PNG for README files)++---++## Phase 35: Server Provisioning APIs (Planned)++**Priority: Medium**++Spin up and manage cloud servers directly from the panel.++- [ ] DigitalOcean API integration (create/destroy/resize droplets)+- [ ] Hetzner Cloud API integration+- [ ] Vultr API integration+- [ ] Linode/Akamai API integration+- [ ] Server creation wizard (region, size, OS, SSH keys)+- [ ] Auto-install ServerKit agent on provisioned servers+- [ ] Server cost tracking and billing overview+- [ ] Snapshot management (create/restore/delete)+- [ ] One-click server cloning+- [ ] Destroy server with confirmation safeguards++---++## Phase 36: Performance Optimization (Planned)++**Priority: Low**++- [ ] Redis caching for frequently accessed data (metrics, server status)+- [ ] Database query optimization and slow query logging+- [ ] Background job queue (Celery or RQ) for long-running tasks+- [ ] Lazy loading for large datasets (paginated API responses)+- [ ] WebSocket connection pooling and reconnection improvements+- [ ] Frontend bundle optimization and code splitting++---++## Phase 37: Mobile App (Future)++**Priority: Low — v3.0+**++- [ ] React Native or PWA mobile application+- [ ] Push notifications for alerts and incidents+- [ ] Quick actions (restart services, view stats, acknowledge alerts)+- [ ] Biometric authentication (fingerprint/Face ID)+- [ ] Offline mode with cached server status++---++## Phase 38: Marketplace & Extensions (Future)++**Priority: Low — v3.0+**++- [ ] Plugin/extension system with API hooks+- [ ] Community marketplace for plugins+- [ ] Custom dashboard widgets+- [ ] Theme customization (colors, layout, branding)+- [ ] 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 | In Progress |+| v1.8.0 | Server templates, multi-tenancy | Planned |+| v1.9.0 | Advanced SSL, DNS management, Nginx config | Planned |+| v2.0.0 | Status pages, server provisioning, performance | Planned |+| v3.0.0 | Mobile app, Marketplace | Future |++---++## 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 10e4aa17..2b37298e 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -1,499 +1,503 @@-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()-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)-- # 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')-- # 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- app.register_blueprint(builds_bp, url_prefix='/api/v1/builds')-- # Register blueprints - Templates- from app.api.templates import templates_bp- app.register_blueprint(templates_bp, url_prefix='/api/v1/templates')-- # Register blueprints - File Manager- from app.api.files import files_bp- app.register_blueprint(files_bp, url_prefix='/api/v1/files')-- # 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 - 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')-- # Handle database migrations (Alembic)- 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()-- # 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)-- # 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_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()+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)++ # 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')++ # 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+ app.register_blueprint(builds_bp, url_prefix='/api/v1/builds')++ # Register blueprints - Templates+ from app.api.templates import templates_bp+ app.register_blueprint(templates_bp, url_prefix='/api/v1/templates')++ # Register blueprints - File Manager+ from app.api.files import files_bp+ app.register_blueprint(files_bp, url_prefix='/api/v1/files')++ # 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 - 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 - Agent Plugins+ from app.api.agent_plugins import agent_plugins_bp+ app.register_blueprint(agent_plugins_bp, url_prefix='/api/v1/agent-plugins')++ # Handle database migrations (Alembic)+ 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()++ # 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)++ # 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_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/api/agent_plugins.py b/backend/app/api/agent_plugins.pynew file mode 100644index 00000000..aee04f72--- /dev/null+++ b/backend/app/api/agent_plugins.py@@ -0,0 +1,240 @@+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required+from app.services.agent_plugin_service import AgentPluginService+from app.services.audit_service import AuditService+from app.models.audit_log import AuditLog++agent_plugins_bp = Blueprint('agent_plugins', __name__)+++def get_current_user():+ from flask_jwt_extended import get_jwt_identity+ from app.models.user import User+ return User.query.get(get_jwt_identity())+++@agent_plugins_bp.route('/', methods=['GET'])+@jwt_required()+def list_plugins():+ status = request.args.get('status')+ plugins = AgentPluginService.list_plugins(status=status)+ return jsonify({'plugins': [p.to_dict() for p in plugins]})+++@agent_plugins_bp.route('/<int:plugin_id>', methods=['GET'])+@jwt_required()+def get_plugin(plugin_id):+ plugin = AgentPluginService.get_plugin(plugin_id)+ if not plugin:+ return jsonify({'error': 'Plugin not found'}), 404+ return jsonify(plugin.to_dict())+++@agent_plugins_bp.route('/', methods=['POST'])+@jwt_required()+def create_plugin():+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json()+ if not data:+ return jsonify({'error': 'Request body required'}), 400++ # Validate manifest+ errors = AgentPluginService.validate_manifest(data)+ if errors:+ return jsonify({'error': 'Invalid manifest', 'details': errors}), 400++ try:+ plugin = AgentPluginService.create_plugin(data)+ AuditService.log(+ action=AuditLog.ACTION_RESOURCE_CREATE,+ user_id=user.id,+ target_type='agent_plugin',+ target_id=plugin.id,+ details={'name': plugin.name, 'version': plugin.version}+ )+ return jsonify(plugin.to_dict()), 201+ except ValueError as e:+ return jsonify({'error': str(e)}), 400+++@agent_plugins_bp.route('/<int:plugin_id>', methods=['PUT'])+@jwt_required()+def update_plugin(plugin_id):+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json()+ plugin = AgentPluginService.update_plugin(plugin_id, data)+ if not plugin:+ return jsonify({'error': 'Plugin not found'}), 404++ return jsonify(plugin.to_dict())+++@agent_plugins_bp.route('/<int:plugin_id>', methods=['DELETE'])+@jwt_required()+def delete_plugin(plugin_id):+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ try:+ result = AgentPluginService.delete_plugin(plugin_id)+ if not result:+ return jsonify({'error': 'Plugin not found'}), 404+ AuditService.log(+ action=AuditLog.ACTION_RESOURCE_DELETE,+ user_id=user.id,+ target_type='agent_plugin',+ target_id=plugin_id,+ details={}+ )+ return jsonify({'message': 'Plugin deleted'})+ except ValueError as e:+ return jsonify({'error': str(e)}), 400+++@agent_plugins_bp.route('/validate', methods=['POST'])+@jwt_required()+def validate_manifest():+ data = request.get_json()+ if not data:+ return jsonify({'error': 'Manifest data required'}), 400+ errors = AgentPluginService.validate_manifest(data)+ return jsonify({'valid': len(errors) == 0, 'errors': errors})+++# --- Installation endpoints ---++@agent_plugins_bp.route('/<int:plugin_id>/install', methods=['POST'])+@jwt_required()+def install_plugin(plugin_id):+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json() or {}+ server_id = data.get('server_id')+ if not server_id:+ return jsonify({'error': 'server_id required'}), 400++ try:+ install = AgentPluginService.install_plugin(+ plugin_id, server_id, config=data.get('config')+ )+ AuditService.log(+ action=AuditLog.ACTION_RESOURCE_CREATE,+ user_id=user.id,+ target_type='agent_plugin_install',+ target_id=install.id,+ details={'plugin_id': plugin_id, 'server_id': server_id}+ )+ return jsonify(install.to_dict()), 201+ except ValueError as e:+ return jsonify({'error': str(e)}), 400+++@agent_plugins_bp.route('/<int:plugin_id>/bulk-install', methods=['POST'])+@jwt_required()+def bulk_install_plugin(plugin_id):+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json() or {}+ server_ids = data.get('server_ids', [])+ if not server_ids:+ return jsonify({'error': 'server_ids required'}), 400++ results = AgentPluginService.bulk_install(plugin_id, server_ids, config=data.get('config'))+ return jsonify({'results': results})+++@agent_plugins_bp.route('/<int:plugin_id>/installations', methods=['GET'])+@jwt_required()+def get_plugin_installations(plugin_id):+ installs = AgentPluginService.get_plugin_installations(plugin_id)+ return jsonify({'installations': [i.to_dict() for i in installs]})+++@agent_plugins_bp.route('/installs/<int:install_id>', methods=['GET'])+@jwt_required()+def get_install(install_id):+ install = AgentPluginService.get_install(install_id)+ if not install:+ return jsonify({'error': 'Installation not found'}), 404+ return jsonify(install.to_dict())+++@agent_plugins_bp.route('/installs/<int:install_id>/enable', methods=['POST'])+@jwt_required()+def enable_install(install_id):+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ install = AgentPluginService.enable_plugin(install_id)+ if not install:+ return jsonify({'error': 'Installation not found'}), 404+ return jsonify(install.to_dict())+++@agent_plugins_bp.route('/installs/<int:install_id>/disable', methods=['POST'])+@jwt_required()+def disable_install(install_id):+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ install = AgentPluginService.disable_plugin(install_id)+ if not install:+ return jsonify({'error': 'Installation not found'}), 404+ return jsonify(install.to_dict())+++@agent_plugins_bp.route('/installs/<int:install_id>', methods=['DELETE'])+@jwt_required()+def uninstall_plugin(install_id):+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ result = AgentPluginService.uninstall_plugin(install_id)+ if not result:+ return jsonify({'error': 'Installation not found'}), 404+ return jsonify({'message': 'Plugin uninstall initiated'})+++@agent_plugins_bp.route('/installs/<int:install_id>/config', methods=['PUT'])+@jwt_required()+def update_install_config(install_id):+ user = get_current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json()+ if not data or 'config' not in data:+ return jsonify({'error': 'config required'}), 400++ install = AgentPluginService.update_install_config(install_id, data['config'])+ if not install:+ return jsonify({'error': 'Installation not found'}), 404+ return jsonify(install.to_dict())+++@agent_plugins_bp.route('/server/<int:server_id>', methods=['GET'])+@jwt_required()+def get_server_plugins(server_id):+ installs = AgentPluginService.get_server_plugins(server_id)+ return jsonify({'plugins': [i.to_dict() for i in installs]})+++@agent_plugins_bp.route('/spec', methods=['GET'])+@jwt_required()+def get_plugin_spec():+ """Return the plugin specification interface."""+ return jsonify(AgentPluginService.PLUGIN_SPEC)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 8cc20a6a..ed66c87b 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -1,37 +1,39 @@-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.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.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--__all__ = [- 'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',- 'NotificationPreferences', 'Deployment', 'DeploymentDiff', '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', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',- 'EventSubscription', 'EventDelivery', 'Invitation',- 'ServerAlertThreshold', 'MetricAlert'-]+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.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.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++__all__ = [+ 'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',+ 'NotificationPreferences', 'Deployment', 'DeploymentDiff', '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', 'ApiKey', 'ApiUsageLog', 'ApiUsageSummary',+ 'EventSubscription', 'EventDelivery', 'Invitation',+ 'ServerAlertThreshold', 'MetricAlert',+ 'AgentPlugin', 'AgentPluginInstall'+]diff --git a/backend/app/models/agent_plugin.py b/backend/app/models/agent_plugin.pynew file mode 100644index 00000000..8ad55656--- /dev/null+++ b/backend/app/models/agent_plugin.py@@ -0,0 +1,163 @@+from datetime import datetime+from app import db+import json+++class AgentPlugin(db.Model):+ """Represents a plugin that can be installed on agents."""+ __tablename__ = 'agent_plugins'++ id = db.Column(db.Integer, primary_key=True)+ name = db.Column(db.String(128), nullable=False, unique=True)+ display_name = db.Column(db.String(256), nullable=False)+ version = db.Column(db.String(32), nullable=False)+ description = db.Column(db.Text)+ author = db.Column(db.String(128))+ homepage = db.Column(db.String(512))++ # Plugin manifest+ manifest_json = db.Column(db.Text)++ # Capabilities+ capabilities_json = db.Column(db.Text) # metrics, health_checks, commands, scheduled_tasks, event_hooks++ # Dependencies+ dependencies_json = db.Column(db.Text) # other plugins required++ # Permissions+ permissions_json = db.Column(db.Text) # filesystem, network, docker, etc.++ # Resource limits+ max_memory_mb = db.Column(db.Integer, default=128)+ max_cpu_percent = db.Column(db.Integer, default=10)++ # Status+ STATUS_AVAILABLE = 'available'+ STATUS_DEPRECATED = 'deprecated'+ status = db.Column(db.String(32), default=STATUS_AVAILABLE)++ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ # Relationships+ installations = db.relationship('AgentPluginInstall', backref='plugin', lazy='dynamic')++ @property+ def manifest(self):+ return json.loads(self.manifest_json) if self.manifest_json else {}++ @manifest.setter+ def manifest(self, value):+ self.manifest_json = json.dumps(value)++ @property+ def capabilities(self):+ return json.loads(self.capabilities_json) if self.capabilities_json else []++ @capabilities.setter+ def capabilities(self, value):+ self.capabilities_json = json.dumps(value)++ @property+ def dependencies(self):+ return json.loads(self.dependencies_json) if self.dependencies_json else []++ @dependencies.setter+ def dependencies(self, value):+ self.dependencies_json = json.dumps(value)++ @property+ def permissions(self):+ return json.loads(self.permissions_json) if self.permissions_json else []++ @permissions.setter+ def permissions(self, value):+ self.permissions_json = json.dumps(value)++ def to_dict(self):+ return {+ 'id': self.id,+ 'name': self.name,+ 'display_name': self.display_name,+ 'version': self.version,+ 'description': self.description,+ 'author': self.author,+ 'homepage': self.homepage,+ 'manifest': self.manifest,+ 'capabilities': self.capabilities,+ 'dependencies': self.dependencies,+ 'permissions': self.permissions,+ 'max_memory_mb': self.max_memory_mb,+ 'max_cpu_percent': self.max_cpu_percent,+ 'status': self.status,+ 'install_count': self.installations.count(),+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }++ def __repr__(self):+ return f'<AgentPlugin {self.name}@{self.version}>'+++class AgentPluginInstall(db.Model):+ """Tracks plugin installations on specific agents/servers."""+ __tablename__ = 'agent_plugin_installs'++ id = db.Column(db.Integer, primary_key=True)+ plugin_id = db.Column(db.Integer, db.ForeignKey('agent_plugins.id'), nullable=False)+ server_id = db.Column(db.Integer, db.ForeignKey('servers.id'), nullable=False)++ # Installation state+ STATUS_INSTALLING = 'installing'+ STATUS_ENABLED = 'enabled'+ STATUS_DISABLED = 'disabled'+ STATUS_ERROR = 'error'+ STATUS_UNINSTALLING = 'uninstalling'+ status = db.Column(db.String(32), default=STATUS_INSTALLING)++ installed_version = db.Column(db.String(32))+ config_json = db.Column(db.Text)+ error_message = db.Column(db.Text)++ installed_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ # Plugin runtime data+ last_health_check = db.Column(db.DateTime)+ health_status = db.Column(db.String(32), default='unknown') # healthy, degraded, unhealthy, unknown+ metrics_json = db.Column(db.Text)++ server = db.relationship('Server', backref=db.backref('plugin_installs', lazy='dynamic'))++ @property+ def config(self):+ return json.loads(self.config_json) if self.config_json else {}++ @config.setter+ def config(self, value):+ self.config_json = json.dumps(value)++ @property+ def metrics(self):+ return json.loads(self.metrics_json) if self.metrics_json else {}++ def to_dict(self):+ return {+ 'id': self.id,+ 'plugin_id': self.plugin_id,+ 'plugin': self.plugin.to_dict() if self.plugin else None,+ 'server_id': self.server_id,+ 'server_name': self.server.name if self.server else None,+ 'status': self.status,+ 'installed_version': self.installed_version,+ 'config': self.config,+ 'error_message': self.error_message,+ 'installed_at': self.installed_at.isoformat() if self.installed_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ 'last_health_check': self.last_health_check.isoformat() if self.last_health_check else None,+ 'health_status': self.health_status,+ 'metrics': self.metrics,+ }++ def __repr__(self):+ return f'<AgentPluginInstall plugin={self.plugin_id} server={self.server_id}>'diff --git a/backend/app/services/agent_plugin_service.py b/backend/app/services/agent_plugin_service.pynew file mode 100644index 00000000..6bd44d6c--- /dev/null+++ b/backend/app/services/agent_plugin_service.py@@ -0,0 +1,306 @@+import json+import logging+from datetime import datetime+from app import db+from app.models.agent_plugin import AgentPlugin, AgentPluginInstall+from app.models.server import Server++logger = logging.getLogger(__name__)+++class AgentPluginService:+ """Service for managing agent plugins."""++ # Plugin specification interface+ PLUGIN_SPEC = {+ 'required_fields': ['name', 'display_name', 'version'],+ 'capability_types': ['metrics', 'health_checks', 'commands', 'scheduled_tasks', 'event_hooks'],+ 'permission_types': ['filesystem', 'network', 'docker', 'process', 'system'],+ }++ @staticmethod+ def list_plugins(status=None):+ query = AgentPlugin.query+ if status:+ query = query.filter_by(status=status)+ return query.order_by(AgentPlugin.display_name).all()++ @staticmethod+ def get_plugin(plugin_id):+ return AgentPlugin.query.get(plugin_id)++ @staticmethod+ def get_plugin_by_name(name):+ return AgentPlugin.query.filter_by(name=name).first()++ @staticmethod+ def create_plugin(data):+ """Register a new plugin from manifest data."""+ if AgentPlugin.query.filter_by(name=data['name']).first():+ raise ValueError(f"Plugin '{data['name']}' already exists")++ plugin = AgentPlugin(+ name=data['name'],+ display_name=data.get('display_name', data['name']),+ version=data['version'],+ description=data.get('description', ''),+ author=data.get('author', ''),+ homepage=data.get('homepage', ''),+ max_memory_mb=data.get('max_memory_mb', 128),+ max_cpu_percent=data.get('max_cpu_percent', 10),+ )+ plugin.manifest = data.get('manifest', data)+ plugin.capabilities = data.get('capabilities', [])+ plugin.dependencies = data.get('dependencies', [])+ plugin.permissions = data.get('permissions', [])++ db.session.add(plugin)+ db.session.commit()+ return plugin++ @staticmethod+ def update_plugin(plugin_id, data):+ plugin = AgentPlugin.query.get(plugin_id)+ if not plugin:+ return None++ for field in ['display_name', 'version', 'description', 'author', 'homepage',+ 'max_memory_mb', 'max_cpu_percent', 'status']:+ if field in data:+ setattr(plugin, field, data[field])++ if 'capabilities' in data:+ plugin.capabilities = data['capabilities']+ if 'dependencies' in data:+ plugin.dependencies = data['dependencies']+ if 'permissions' in data:+ plugin.permissions = data['permissions']+ if 'manifest' in data:+ plugin.manifest = data['manifest']++ db.session.commit()+ return plugin++ @staticmethod+ def delete_plugin(plugin_id):+ plugin = AgentPlugin.query.get(plugin_id)+ if not plugin:+ return False++ # Check for active installations+ active = plugin.installations.filter(+ AgentPluginInstall.status.in_([+ AgentPluginInstall.STATUS_ENABLED,+ AgentPluginInstall.STATUS_INSTALLING+ ])+ ).count()+ if active > 0:+ raise ValueError(f'Cannot delete plugin with {active} active installations')++ # Remove all installation records+ AgentPluginInstall.query.filter_by(plugin_id=plugin_id).delete()+ db.session.delete(plugin)+ db.session.commit()+ return True++ # --- Installation Management ---++ @staticmethod+ def install_plugin(plugin_id, server_id, config=None):+ """Install a plugin on a server."""+ plugin = AgentPlugin.query.get(plugin_id)+ if not plugin:+ raise ValueError('Plugin not found')++ server = Server.query.get(server_id)+ if not server:+ raise ValueError('Server not found')++ # Check if already installed+ existing = AgentPluginInstall.query.filter_by(+ plugin_id=plugin_id, server_id=server_id+ ).first()+ if existing and existing.status in ['enabled', 'installing']:+ raise ValueError('Plugin already installed on this server')++ # Check dependencies+ for dep_name in plugin.dependencies:+ dep_plugin = AgentPlugin.query.filter_by(name=dep_name).first()+ if not dep_plugin:+ raise ValueError(f"Required dependency '{dep_name}' not available")+ dep_install = AgentPluginInstall.query.filter_by(+ plugin_id=dep_plugin.id, server_id=server_id, status='enabled'+ ).first()+ if not dep_install:+ raise ValueError(f"Dependency '{dep_name}' not installed on server")++ if existing:+ existing.status = AgentPluginInstall.STATUS_INSTALLING+ existing.installed_version = plugin.version+ existing.error_message = None+ if config:+ existing.config = config+ install = existing+ else:+ install = AgentPluginInstall(+ plugin_id=plugin_id,+ server_id=server_id,+ installed_version=plugin.version,+ status=AgentPluginInstall.STATUS_INSTALLING,+ )+ if config:+ install.config = config+ db.session.add(install)++ db.session.commit()++ # Send install command to agent+ try:+ from app.agent_gateway import get_agent_gateway+ gw = get_agent_gateway()+ if gw:+ gw.send_command(server.agent_id, 'plugin_install', {+ 'plugin_name': plugin.name,+ 'version': plugin.version,+ 'manifest': plugin.manifest,+ 'config': install.config,+ 'permissions': plugin.permissions,+ 'resource_limits': {+ 'max_memory_mb': plugin.max_memory_mb,+ 'max_cpu_percent': plugin.max_cpu_percent,+ }+ })+ except Exception as e:+ logger.warning(f'Could not send plugin install command: {e}')++ return install++ @staticmethod+ def uninstall_plugin(install_id):+ install = AgentPluginInstall.query.get(install_id)+ if not install:+ return False++ install.status = AgentPluginInstall.STATUS_UNINSTALLING+ db.session.commit()++ # Send uninstall command to agent+ try:+ from app.agent_gateway import get_agent_gateway+ gw = get_agent_gateway()+ if gw and install.server:+ gw.send_command(install.server.agent_id, 'plugin_uninstall', {+ 'plugin_name': install.plugin.name,+ })+ except Exception as e:+ logger.warning(f'Could not send plugin uninstall command: {e}')++ return True++ @staticmethod+ def enable_plugin(install_id):+ install = AgentPluginInstall.query.get(install_id)+ if not install:+ return None+ install.status = AgentPluginInstall.STATUS_ENABLED+ db.session.commit()+ return install++ @staticmethod+ def disable_plugin(install_id):+ install = AgentPluginInstall.query.get(install_id)+ if not install:+ return None+ install.status = AgentPluginInstall.STATUS_DISABLED+ db.session.commit()++ try:+ from app.agent_gateway import get_agent_gateway+ gw = get_agent_gateway()+ if gw and install.server:+ gw.send_command(install.server.agent_id, 'plugin_disable', {+ 'plugin_name': install.plugin.name,+ })+ except Exception as e:+ logger.warning(f'Could not send plugin disable command: {e}')++ return install++ @staticmethod+ def update_install_status(install_id, status, error=None, health=None, metrics=None):+ install = AgentPluginInstall.query.get(install_id)+ if not install:+ return None+ install.status = status+ if error is not None:+ install.error_message = error+ if health is not None:+ install.health_status = health+ install.last_health_check = datetime.utcnow()+ if metrics is not None:+ install.metrics_json = json.dumps(metrics)+ db.session.commit()+ return install++ @staticmethod+ def update_install_config(install_id, config):+ install = AgentPluginInstall.query.get(install_id)+ if not install:+ return None+ install.config = config+ db.session.commit()++ try:+ from app.agent_gateway import get_agent_gateway+ gw = get_agent_gateway()+ if gw and install.server:+ gw.send_command(install.server.agent_id, 'plugin_configure', {+ 'plugin_name': install.plugin.name,+ 'config': config,+ })+ except Exception as e:+ logger.warning(f'Could not send plugin config update: {e}')++ return install++ @staticmethod+ def get_server_plugins(server_id):+ return AgentPluginInstall.query.filter_by(server_id=server_id).all()++ @staticmethod+ def get_plugin_installations(plugin_id):+ return AgentPluginInstall.query.filter_by(plugin_id=plugin_id).all()++ @staticmethod+ def get_install(install_id):+ return AgentPluginInstall.query.get(install_id)++ @staticmethod+ def bulk_install(plugin_id, server_ids, config=None):+ """Install plugin on multiple servers."""+ results = []+ for sid in server_ids:+ try:+ install = AgentPluginService.install_plugin(plugin_id, sid, config)+ results.append({'server_id': sid, 'status': 'installing', 'install_id': install.id})+ except ValueError as e:+ results.append({'server_id': sid, 'status': 'error', 'error': str(e)})+ return results++ @staticmethod+ def validate_manifest(manifest):+ """Validate a plugin manifest against the spec."""+ errors = []+ for field in AgentPluginService.PLUGIN_SPEC['required_fields']:+ if field not in manifest:+ errors.append(f"Missing required field: {field}")++ for cap in manifest.get('capabilities', []):+ if cap not in AgentPluginService.PLUGIN_SPEC['capability_types']:+ errors.append(f"Unknown capability: {cap}")++ for perm in manifest.get('permissions', []):+ if perm not in AgentPluginService.PLUGIN_SPEC['permission_types']:+ errors.append(f"Unknown permission: {perm}")++ return errorsdiff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex b62d4aef..f26a2a56 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -1,256 +1,259 @@-import React, { useEffect } from 'react';-import { BrowserRouter as Router, Routes, Route, Navigate, useLocation } 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 { ToastContainer } from './components/Toast';-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 Applications from './pages/Applications';-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 page-import Git from './pages/Git';-import CronJobs from './pages/CronJobs';-import Security from './pages/Security';-import Services from './pages/Services';-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 DatabaseMigration from './pages/DatabaseMigration';--// Page title mapping-const PAGE_TITLES = {- '/': 'Dashboard',- '/login': 'Login',- '/register': 'Register',- '/setup': 'Setup',- '/services': 'Services',- '/apps': 'Applications',- '/wordpress': 'WordPress Sites',- '/wordpress/projects': 'WordPress Projects',- '/templates': 'Templates',- '/workflow': 'Workflow Builder',- '/domains': 'Domains',- '/databases': 'Databases',- '/ssl': 'SSL Certificates',- '/docker': 'Docker',- '/servers': 'Servers',- '/downloads': 'Downloads',- '/git': 'Git Repositories',- '/files': 'File Manager',- '/ftp': 'FTP Server',- '/monitoring': 'Monitoring',- '/backups': 'Backups',- '/cron': 'Cron Jobs',- '/security': 'Security',- '/email': 'Email Server',- '/terminal': 'Terminal',- '/settings': 'Settings',- '/migrate': 'Database Migration',- '/fleet': 'Agent Fleet',- '/fleet-monitor': 'Fleet Monitor',-};--function PageTitleUpdater() {- const location = useLocation();-- useEffect(() => {- const path = location.pathname;- let title = PAGE_TITLES[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 (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]);-- 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;-}--function AppRoutes() {- 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="/" element={- <PrivateRoute>- <DashboardLayout />- </PrivateRoute>- }>- <Route index element={<Dashboard />} />- <Route path="services" element={<Services />} />- <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="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="downloads" element={<Downloads />} />- <Route path="firewall" element={<Navigate to="/security/firewall" replace />} />- <Route path="git" element={<Git />} />- <Route path="git/:tab" element={<Git />} />- <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 />} />- </Route>- </Routes>- );-}--function App() {- return (- <Router>- <PageTitleUpdater />- <ThemeProvider>- <AuthProvider>- <ResourceTierProvider>- <ToastProvider>- <AppRoutes />- <ToastContainer />- </ToastProvider>- </ResourceTierProvider>- </AuthProvider>- </ThemeProvider>- </Router>- );-}--export default App;+import React, { useEffect } from 'react';+import { BrowserRouter as Router, Routes, Route, Navigate, useLocation } 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 { ToastContainer } from './components/Toast';+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 Applications from './pages/Applications';+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 page+import Git from './pages/Git';+import CronJobs from './pages/CronJobs';+import Security from './pages/Security';+import Services from './pages/Services';+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 DatabaseMigration from './pages/DatabaseMigration';+import AgentPlugins from './pages/AgentPlugins';++// Page title mapping+const PAGE_TITLES = {+ '/': 'Dashboard',+ '/login': 'Login',+ '/register': 'Register',+ '/setup': 'Setup',+ '/services': 'Services',+ '/apps': 'Applications',+ '/wordpress': 'WordPress Sites',+ '/wordpress/projects': 'WordPress Projects',+ '/templates': 'Templates',+ '/workflow': 'Workflow Builder',+ '/domains': 'Domains',+ '/databases': 'Databases',+ '/ssl': 'SSL Certificates',+ '/docker': 'Docker',+ '/servers': 'Servers',+ '/downloads': 'Downloads',+ '/git': 'Git Repositories',+ '/files': 'File Manager',+ '/ftp': 'FTP Server',+ '/monitoring': 'Monitoring',+ '/backups': 'Backups',+ '/cron': 'Cron Jobs',+ '/security': 'Security',+ '/email': 'Email Server',+ '/terminal': 'Terminal',+ '/settings': 'Settings',+ '/migrate': 'Database Migration',+ '/fleet': 'Agent Fleet',+ '/fleet-monitor': 'Fleet Monitor',+ '/agent-plugins': 'Agent Plugins',+};++function PageTitleUpdater() {+ const location = useLocation();++ useEffect(() => {+ const path = location.pathname;+ let title = PAGE_TITLES[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 (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]);++ 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;+}++function AppRoutes() {+ 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="/" element={+ <PrivateRoute>+ <DashboardLayout />+ </PrivateRoute>+ }>+ <Route index element={<Dashboard />} />+ <Route path="services" element={<Services />} />+ <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="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={<AgentPlugins />} />+ <Route path="downloads" element={<Downloads />} />+ <Route path="firewall" element={<Navigate to="/security/firewall" replace />} />+ <Route path="git" element={<Git />} />+ <Route path="git/:tab" element={<Git />} />+ <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 />} />+ </Route>+ </Routes>+ );+}++function App() {+ return (+ <Router>+ <PageTitleUpdater />+ <ThemeProvider>+ <AuthProvider>+ <ResourceTierProvider>+ <ToastProvider>+ <AppRoutes />+ <ToastContainer />+ </ToastProvider>+ </ResourceTierProvider>+ </AuthProvider>+ </ThemeProvider>+ </Router>+ );+}++export default App;diff --git a/frontend/src/components/sidebarItems.js b/frontend/src/components/sidebarItems.jsindex 2372b451..fd95cb20 100644--- a/frontend/src/components/sidebarItems.js+++ b/frontend/src/components/sidebarItems.js@@ -42,6 +42,13 @@ export const SIDEBAR_ITEMS = [category: 'infrastructure',icon: '<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>'},+ {+ id: 'agent-plugins',+ label: 'Agent Plugins',+ route: '/agent-plugins',+ category: 'infrastructure',+ icon: '<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>'+ },{id: 'domains',label: 'Domains & Sites',diff --git a/frontend/src/pages/AgentPlugins.jsx b/frontend/src/pages/AgentPlugins.jsxnew file mode 100644index 00000000..26127b87--- /dev/null+++ b/frontend/src/pages/AgentPlugins.jsx@@ -0,0 +1,294 @@+import React, { useState, useEffect, useCallback } from 'react';+import { useNavigate } from 'react-router-dom';+import api from '../services/api';+import { useToast } from '../contexts/ToastContext';+import { useAuth } from '../contexts/AuthContext';+import Spinner from '../components/Spinner';+import ConfirmDialog from '../components/ConfirmDialog';++const AgentPlugins = () => {+ const navigate = useNavigate();+ const toast = useToast();+ const { user } = useAuth();+ const [plugins, setPlugins] = useState([]);+ const [loading, setLoading] = useState(true);+ const [showCreateModal, setShowCreateModal] = useState(false);+ const [showInstallModal, setShowInstallModal] = useState(false);+ const [selectedPlugin, setSelectedPlugin] = useState(null);+ const [deleteConfirm, setDeleteConfirm] = useState(null);+ const [servers, setServers] = useState([]);+ const [filter, setFilter] = useState('all');++ const [newPlugin, setNewPlugin] = useState({+ name: '', display_name: '', version: '1.0.0', description: '',+ author: '', capabilities: [], permissions: [],+ max_memory_mb: 128, max_cpu_percent: 10+ });++ const loadPlugins = useCallback(async () => {+ try {+ const data = await api.getAgentPlugins();+ setPlugins(data.plugins || []);+ } catch (err) {+ toast.error('Failed to load plugins');+ } finally {+ setLoading(false);+ }+ }, [toast]);++ useEffect(() => {+ loadPlugins();+ api.getServers().then(data => setServers(data.servers || [])).catch(() => {});+ }, [loadPlugins]);++ const handleCreate = async () => {+ try {+ await api.createAgentPlugin(newPlugin);+ toast.success('Plugin registered');+ setShowCreateModal(false);+ setNewPlugin({ name: '', display_name: '', version: '1.0.0', description: '', author: '', capabilities: [], permissions: [], max_memory_mb: 128, max_cpu_percent: 10 });+ loadPlugins();+ } catch (err) {+ toast.error(err.message);+ }+ };++ const handleDelete = async (id) => {+ try {+ await api.deleteAgentPlugin(id);+ toast.success('Plugin deleted');+ setDeleteConfirm(null);+ loadPlugins();+ } catch (err) {+ toast.error(err.message);+ }+ };++ const handleInstall = async (pluginId, serverId) => {+ try {+ await api.installAgentPlugin(pluginId, serverId);+ toast.success('Plugin installation initiated');+ setShowInstallModal(false);+ loadPlugins();+ } catch (err) {+ toast.error(err.message);+ }+ };++ const toggleCapability = (cap) => {+ setNewPlugin(prev => ({+ ...prev,+ capabilities: prev.capabilities.includes(cap)+ ? prev.capabilities.filter(c => c !== cap)+ : [...prev.capabilities, cap]+ }));+ };++ const togglePermission = (perm) => {+ setNewPlugin(prev => ({+ ...prev,+ permissions: prev.permissions.includes(perm)+ ? prev.permissions.filter(p => p !== perm)+ : [...prev.permissions, perm]+ }));+ };++ const filteredPlugins = filter === 'all' ? plugins+ : plugins.filter(p => p.status === filter);++ const capabilityLabels = {+ metrics: 'Custom Metrics',+ health_checks: 'Health Checks',+ commands: 'Custom Commands',+ scheduled_tasks: 'Scheduled Tasks',+ event_hooks: 'Event Hooks'+ };++ const permissionLabels = {+ filesystem: 'Filesystem',+ network: 'Network',+ docker: 'Docker',+ process: 'Process',+ system: 'System'+ };++ if (loading) return <Spinner />;++ return (+ <div className="agent-plugins-page">+ <header className="top-bar">+ <div className="top-bar__title">+ <h1>Agent Plugins</h1>+ <span className="top-bar__subtitle">{plugins.length} plugin{plugins.length !== 1 ? 's' : ''} registered</span>+ </div>+ <div className="top-bar__actions">+ <select value={filter} onChange={e => setFilter(e.target.value)} className="form-select">+ <option value="all">All Plugins</option>+ <option value="available">Available</option>+ <option value="deprecated">Deprecated</option>+ </select>+ {user?.is_admin && (+ <button className="btn btn--primary" onClick={() => setShowCreateModal(true)}>+ Register Plugin+ </button>+ )}+ </div>+ </header>++ <div className="plugins-grid">+ {filteredPlugins.map(plugin => (+ <div key={plugin.id} className="plugin-card card">+ <div className="plugin-card__header">+ <div className="plugin-card__info">+ <h3>{plugin.display_name}</h3>+ <span className="plugin-card__version">v{plugin.version}</span>+ </div>+ <span className={`badge badge--${plugin.status === 'available' ? 'success' : 'warning'}`}>+ {plugin.status}+ </span>+ </div>+ {plugin.description && (+ <p className="plugin-card__desc">{plugin.description}</p>+ )}+ <div className="plugin-card__meta">+ {plugin.author && <span>By {plugin.author}</span>}+ <span>{plugin.install_count} installation{plugin.install_count !== 1 ? 's' : ''}</span>+ </div>+ <div className="plugin-card__capabilities">+ {(plugin.capabilities || []).map(cap => (+ <span key={cap} className="badge badge--outline">{capabilityLabels[cap] || cap}</span>+ ))}+ </div>+ <div className="plugin-card__permissions">+ {(plugin.permissions || []).map(perm => (+ <span key={perm} className="badge badge--subtle">{permissionLabels[perm] || perm}</span>+ ))}+ </div>+ <div className="plugin-card__actions">+ <button className="btn btn--sm btn--primary" onClick={() => { setSelectedPlugin(plugin); setShowInstallModal(true); }}>+ Install+ </button>+ {user?.is_admin && (+ <button className="btn btn--sm btn--danger" onClick={() => setDeleteConfirm(plugin)}>+ Delete+ </button>+ )}+ </div>+ </div>+ ))}+ {filteredPlugins.length === 0 && (+ <div className="empty-state">+ <p>No plugins found. Register a plugin to extend agent capabilities.</p>+ </div>+ )}+ </div>++ {/* Create Plugin Modal */}+ {showCreateModal && (+ <div className="modal-overlay" onClick={() => setShowCreateModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal__header">+ <h2>Register Plugin</h2>+ <button className="modal__close" onClick={() => setShowCreateModal(false)}>×</button>+ </div>+ <div className="modal__body">+ <div className="form-group">+ <label>Plugin Name (identifier)</label>+ <input className="form-input" value={newPlugin.name} onChange={e => setNewPlugin({...newPlugin, name: e.target.value})} placeholder="my-plugin" />+ </div>+ <div className="form-group">+ <label>Display Name</label>+ <input className="form-input" value={newPlugin.display_name} onChange={e => setNewPlugin({...newPlugin, display_name: e.target.value})} placeholder="My Plugin" />+ </div>+ <div className="form-group">+ <label>Version</label>+ <input className="form-input" value={newPlugin.version} onChange={e => setNewPlugin({...newPlugin, version: e.target.value})} />+ </div>+ <div className="form-group">+ <label>Description</label>+ <textarea className="form-input" value={newPlugin.description} onChange={e => setNewPlugin({...newPlugin, description: e.target.value})} rows={3} />+ </div>+ <div className="form-group">+ <label>Author</label>+ <input className="form-input" value={newPlugin.author} onChange={e => setNewPlugin({...newPlugin, author: e.target.value})} />+ </div>+ <div className="form-group">+ <label>Capabilities</label>+ <div className="checkbox-group">+ {Object.entries(capabilityLabels).map(([key, label]) => (+ <label key={key} className="checkbox-label">+ <input type="checkbox" checked={newPlugin.capabilities.includes(key)} onChange={() => toggleCapability(key)} />+ {label}+ </label>+ ))}+ </div>+ </div>+ <div className="form-group">+ <label>Permissions</label>+ <div className="checkbox-group">+ {Object.entries(permissionLabels).map(([key, label]) => (+ <label key={key} className="checkbox-label">+ <input type="checkbox" checked={newPlugin.permissions.includes(key)} onChange={() => togglePermission(key)} />+ {label}+ </label>+ ))}+ </div>+ </div>+ <div className="form-row">+ <div className="form-group">+ <label>Max Memory (MB)</label>+ <input className="form-input" type="number" value={newPlugin.max_memory_mb} onChange={e => setNewPlugin({...newPlugin, max_memory_mb: parseInt(e.target.value) || 128})} />+ </div>+ <div className="form-group">+ <label>Max CPU (%)</label>+ <input className="form-input" type="number" value={newPlugin.max_cpu_percent} onChange={e => setNewPlugin({...newPlugin, max_cpu_percent: parseInt(e.target.value) || 10})} />+ </div>+ </div>+ </div>+ <div className="modal__footer">+ <button className="btn" onClick={() => setShowCreateModal(false)}>Cancel</button>+ <button className="btn btn--primary" onClick={handleCreate} disabled={!newPlugin.name || !newPlugin.display_name}>Register</button>+ </div>+ </div>+ </div>+ )}++ {/* Install Plugin Modal */}+ {showInstallModal && selectedPlugin && (+ <div className="modal-overlay" onClick={() => setShowInstallModal(false)}>+ <div className="modal" onClick={e => e.stopPropagation()}>+ <div className="modal__header">+ <h2>Install {selectedPlugin.display_name}</h2>+ <button className="modal__close" onClick={() => setShowInstallModal(false)}>×</button>+ </div>+ <div className="modal__body">+ <p>Select a server to install this plugin on:</p>+ <div className="server-select-list">+ {servers.map(server => (+ <div key={server.id} className="server-select-item" onClick={() => handleInstall(selectedPlugin.id, server.id)}>+ <span className={`status-dot status-dot--${server.status === 'online' ? 'success' : 'danger'}`} />+ <span>{server.name}</span>+ <span className="text-muted">{server.hostname}</span>+ </div>+ ))}+ {servers.length === 0 && <p className="text-muted">No servers available</p>}+ </div>+ </div>+ </div>+ </div>+ )}++ {deleteConfirm && (+ <ConfirmDialog+ title="Delete Plugin"+ message={`Delete "${deleteConfirm.display_name}"? This cannot be undone.`}+ onConfirm={() => handleDelete(deleteConfirm.id)}+ onCancel={() => setDeleteConfirm(null)}+ variant="danger"+ />+ )}+ </div>+ );+};++export default AgentPlugins;diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex d8b7542f..57bc819a 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -1,3378 +1,3443 @@-// Use relative URL in production (served from Flask), absolute in development-const API_BASE_URL = import.meta.env.VITE_API_URL ||- (import.meta.env.PROD ? '/api/v1' : 'http://localhost:5000/api/v1');--class ApiService {- constructor() {- this.baseUrl = API_BASE_URL;- }-- getToken() {- return localStorage.getItem('access_token');- }-- setTokens(accessToken, refreshToken) {- localStorage.setItem('access_token', accessToken);- localStorage.setItem('refresh_token', refreshToken);- }-- clearTokens() {- localStorage.removeItem('access_token');- localStorage.removeItem('refresh_token');- }-- async request(endpoint, options = {}) {- const url = `${this.baseUrl}${endpoint}`;- const token = this.getToken();-- const config = {- headers: {- 'Content-Type': 'application/json',- ...(token && { Authorization: `Bearer ${token}` }),- ...options.headers,- },- ...options,- };-- if (options.body && typeof options.body === 'object') {- config.body = JSON.stringify(options.body);- }-- try {- const response = await fetch(url, config);-- if (response.status === 401) {- const refreshed = await this.refreshToken();- if (refreshed) {- config.headers.Authorization = `Bearer ${this.getToken()}`;- const retryResponse = await fetch(url, config);- return this.handleResponse(retryResponse);- }- this.clearTokens();- window.location.href = '/login';- throw new Error('Session expired');- }-- return this.handleResponse(response);- } catch (error) {- console.error('API Error:', error);- throw error;- }- }-- async handleResponse(response) {- const data = await response.json();- if (!response.ok) {- throw new Error(data.error || 'Request failed');- }- return data;- }-- async refreshToken() {- const refreshToken = localStorage.getItem('refresh_token');- if (!refreshToken) return false;-- try {- const response = await fetch(`${this.baseUrl}/auth/refresh`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- Authorization: `Bearer ${refreshToken}`,- },- });-- if (response.ok) {- const data = await response.json();- localStorage.setItem('access_token', data.access_token);- return true;- }- return false;- } catch {- return false;- }- }-- // Auth endpoints- async getSetupStatus() {- return this.request('/auth/setup-status');- }-- async login(email, password) {- const data = await this.request('/auth/login', {- method: 'POST',- body: { email, password },- });- this.setTokens(data.access_token, data.refresh_token);- return data;- }-- async register(email, username, password, inviteToken) {- const body = { email, username, password };- if (inviteToken) body.invite_token = inviteToken;- const data = await this.request('/auth/register', {- method: 'POST',- body,- });- this.setTokens(data.access_token, data.refresh_token);- return data;- }-- async completeOnboarding(useCases) {- return this.request('/auth/complete-onboarding', {- method: 'POST',- body: { use_cases: useCases },- });- }-- async logout() {- this.clearTokens();- }-- async getCurrentUser() {- return this.request('/auth/me');- }-- async updateCurrentUser(data) {- return this.request('/auth/me', {- method: 'PUT',- body: data- });- }-- // ========================================- // Admin - User Management endpoints- // ========================================- async getUsers() {- return this.request('/admin/users');- }-- async getUser(userId) {- return this.request(`/admin/users/${userId}`);- }-- async createUser(userData) {- return this.request('/admin/users', {- method: 'POST',- body: userData- });- }-- async updateUser(userId, userData) {- return this.request(`/admin/users/${userId}`, {- method: 'PUT',- body: userData- });- }-- async deleteUser(userId) {- return this.request(`/admin/users/${userId}`, {- method: 'DELETE'- });- }-- // ========================================- // Admin - Audit Log endpoints- // ========================================- async getAuditLogs(params = {}) {- const searchParams = new URLSearchParams();- if (params.page) searchParams.append('page', params.page);- if (params.per_page) searchParams.append('per_page', params.per_page);- if (params.action) searchParams.append('action', params.action);- if (params.user_id) searchParams.append('user_id', params.user_id);- if (params.target_type) searchParams.append('target_type', params.target_type);- const query = searchParams.toString();- return this.request(`/admin/audit-logs${query ? '?' + query : ''}`);- }-- async getAuditLogActions() {- return this.request('/admin/audit-logs/actions');- }-- // ========================================- // Admin - System Settings endpoints- // ========================================- async getSystemSettings() {- const data = await this.request('/admin/settings');- const result = {};- if (data.settings && Array.isArray(data.settings)) {- for (const setting of data.settings) {- result[setting.key] = setting.value;- }- }- return result;- }-- async updateSystemSettings(settings) {- return this.request('/admin/settings', {- method: 'PUT',- body: settings- });- }-- async getSystemSetting(key) {- return this.request(`/admin/settings/${key}`);- }-- async updateSystemSetting(key, value) {- return this.request(`/admin/settings/${key}`, {- method: 'PUT',- body: { value }- });- }-- async getAdminStats() {- return this.request('/admin/stats');- }-- // Apps endpoints- async getApps() {- return this.request('/apps');- }-- async getApp(id) {- return this.request(`/apps/${id}`);- }-- async createApp(appData) {- return this.request('/apps', {- method: 'POST',- body: appData,- });- }-- async updateApp(id, appData) {- return this.request(`/apps/${id}`, {- method: 'PUT',- body: appData,- });- }-- async deleteApp(id) {- return this.request(`/apps/${id}`, {- method: 'DELETE',- });- }-- async startApp(id) {- return this.request(`/apps/${id}/start`, { method: 'POST' });- }-- async stopApp(id) {- return this.request(`/apps/${id}/stop`, { method: 'POST' });- }-- async restartApp(id) {- return this.request(`/apps/${id}/restart`, { method: 'POST' });- }-- // App linking endpoints- async linkApp(appId, targetAppId, asEnvironment, options = {}) {- return this.request(`/apps/${appId}/link`, {- method: 'POST',- body: {- target_app_id: targetAppId,- as_environment: asEnvironment,- propagate_credentials: options.propagateCredentials !== false,- table_prefix: options.tablePrefix- }- });- }-- async getLinkedApps(appId) {- return this.request(`/apps/${appId}/linked`);- }-- async unlinkApp(appId) {- return this.request(`/apps/${appId}/link`, {- method: 'DELETE'- });- }-- async updateAppEnvironment(appId, environmentType) {- return this.request(`/apps/${appId}/environment`, {- method: 'PUT',- body: { environment_type: environmentType }- });- }-- // Domains endpoints- async getDomains() {- return this.request('/domains');- }-- async getDomain(id) {- return this.request(`/domains/${id}`);- }-- async createDomain(domainData) {- return this.request('/domains', {- method: 'POST',- body: domainData,- });- }-- async updateDomain(id, domainData) {- return this.request(`/domains/${id}`, {- method: 'PUT',- body: domainData,- });- }-- async deleteDomain(id) {- return this.request(`/domains/${id}`, {- method: 'DELETE',- });- }-- async enableSsl(domainId, email) {- return this.request(`/domains/${domainId}/ssl/enable`, {- method: 'POST',- body: { email }- });- }-- async disableSsl(domainId) {- return this.request(`/domains/${domainId}/ssl/disable`, { method: 'POST' });- }-- async renewDomainSsl(domainId) {- return this.request(`/domains/${domainId}/ssl/renew`, { method: 'POST' });- }-- async verifyDomain(domainId) {- return this.request(`/domains/${domainId}/verify`);- }-- async getDomainsNginxSites() {- return this.request('/domains/nginx/sites');- }-- async getDomainsSslStatus() {- return this.request('/domains/ssl/status');- }-- // System endpoints- async getSystemMetrics() {- return this.request('/system/metrics');- }-- async getSystemInfo() {- return this.request('/system/info');- }-- async getServerTime() {- return this.request('/system/time');- }-- async getTimezones() {- return this.request('/system/timezones');- }-- async setTimezone(timezone) {- return this.request('/system/timezone', {- method: 'PUT',- body: { timezone }- });- }-- async getVersion() {- return this.request('/system/version');- }-- async checkUpdate() {- return this.request('/system/check-update');- }-- async getProcesses() {- return this.request('/system/processes');- }-- async getServices() {- return this.request('/system/services');- }-- async healthCheck() {- return this.request('/system/health');- }-- // Process endpoints- async getProcesses(limit = 50, sortBy = 'cpu') {- return this.request(`/processes?limit=${limit}&sort=${sortBy}`);- }-- async getProcess(pid) {- return this.request(`/processes/${pid}`);- }-- async killProcess(pid, force = false) {- return this.request(`/processes/${pid}?force=${force}`, { method: 'DELETE' });- }-- async getServicesStatus() {- return this.request('/processes/services');- }-- async controlService(serviceName, action) {- return this.request(`/processes/services/${serviceName}`, {- method: 'POST',- body: { action }- });- }-- // Nginx endpoints- async getNginxStatus() {- return this.request('/nginx/status');- }-- async testNginxConfig() {- return this.request('/nginx/test', { method: 'POST' });- }-- async reloadNginx() {- return this.request('/nginx/reload', { method: 'POST' });- }-- async getNginxSites() {- return this.request('/nginx/sites');- }-- async createNginxSite(siteData) {- return this.request('/nginx/sites', {- method: 'POST',- body: siteData- });- }-- async enableNginxSite(name) {- return this.request(`/nginx/sites/${name}/enable`, { method: 'POST' });- }-- async disableNginxSite(name) {- return this.request(`/nginx/sites/${name}/disable`, { method: 'POST' });- }-- async deleteNginxSite(name) {- return this.request(`/nginx/sites/${name}`, { method: 'DELETE' });- }-- // SSL endpoints- async getSSLStatus() {- return this.request('/ssl/status');- }-- async getCertificates() {- return this.request('/ssl/certificates');- }-- async obtainCertificate(data) {- return this.request('/ssl/certificates', {- method: 'POST',- body: data- });- }-- async renewCertificate(domain) {- return this.request(`/ssl/certificates/${domain}/renew`, { method: 'POST' });- }-- async renewAllCertificates() {- return this.request('/ssl/certificates/renew-all', { method: 'POST' });- }-- async revokeCertificate(domain) {- return this.request(`/ssl/certificates/${domain}`, { method: 'DELETE' });- }-- async setupAutoRenewal() {- return this.request('/ssl/auto-renewal', { method: 'POST' });- }-- async installCertbot() {- return this.request('/ssl/install-certbot', { method: 'POST' });- }-- // Log endpoints- async getLogFiles() {- return this.request('/logs');- }-- async readLog(filepath, lines = 100) {- return this.request(`/logs/read?path=${encodeURIComponent(filepath)}&lines=${lines}`);- }-- async searchLog(filepath, pattern, lines = 100) {- return this.request(`/logs/search?path=${encodeURIComponent(filepath)}&pattern=${encodeURIComponent(pattern)}&lines=${lines}`);- }-- async getAppLogs(appName, type = 'access', lines = 100) {- return this.request(`/logs/app/${appName}?type=${type}&lines=${lines}`);- }-- async getJournalLogs(unit, lines = 100) {- const params = new URLSearchParams({ lines });- if (unit) params.append('unit', unit);- return this.request(`/logs/journal?${params}`);- }-- async clearLog(filepath) {- return this.request('/logs/clear', {- method: 'POST',- body: { path: filepath }- });- }-- // PHP endpoints- async getPHPVersions() {- return this.request('/php/versions');- }-- async installPHPVersion(version) {- return this.request(`/php/versions/${version}/install`, { method: 'POST' });- }-- async setDefaultPHPVersion(version) {- return this.request('/php/versions/default', {- method: 'POST',- body: { version }- });- }-- async getPHPExtensions(version) {- return this.request(`/php/versions/${version}/extensions`);- }-- async installPHPExtension(version, extension) {- return this.request(`/php/versions/${version}/extensions`, {- method: 'POST',- body: { extension }- });- }-- async getPHPPools(version) {- return this.request(`/php/versions/${version}/pools`);- }-- async createPHPPool(version, poolData) {- return this.request(`/php/versions/${version}/pools`, {- method: 'POST',- body: poolData- });- }-- async deletePHPPool(version, poolName) {- return this.request(`/php/versions/${version}/pools/${poolName}`, { method: 'DELETE' });- }-- async restartPHPFPM(version) {- return this.request(`/php/versions/${version}/fpm/restart`, { method: 'POST' });- }-- async getPHPFPMStatus(version) {- return this.request(`/php/versions/${version}/fpm/status`);- }-- // WordPress: Use dedicated wordpress.js service instead-- // Python endpoints- async getPythonVersions() {- return this.request('/python/versions');- }-- async createFlaskApp(data) {- return this.request('/python/apps/flask', {- method: 'POST',- body: data- });- }-- async createDjangoApp(data) {- return this.request('/python/apps/django', {- method: 'POST',- body: data- });- }-- async createPythonVenv(appId) {- return this.request(`/python/apps/${appId}/venv`, { method: 'POST' });- }-- async getPythonPackages(appId) {- return this.request(`/python/apps/${appId}/packages`);- }-- async installPythonPackages(appId, packages) {- return this.request(`/python/apps/${appId}/packages`, {- method: 'POST',- body: { packages }- });- }-- async freezePythonRequirements(appId) {- return this.request(`/python/apps/${appId}/requirements`, { method: 'POST' });- }-- async getPythonEnvVars(appId) {- return this.request(`/python/apps/${appId}/env`);- }-- async setPythonEnvVars(appId, envVars) {- return this.request(`/python/apps/${appId}/env`, {- method: 'PUT',- body: { env_vars: envVars }- });- }-- async deletePythonEnvVar(appId, key) {- return this.request(`/python/apps/${appId}/env/${key}`, { method: 'DELETE' });- }-- async startPythonApp(appId) {- return this.request(`/python/apps/${appId}/start`, { method: 'POST' });- }-- async stopPythonApp(appId) {- return this.request(`/python/apps/${appId}/stop`, { method: 'POST' });- }-- async restartPythonApp(appId) {- return this.request(`/python/apps/${appId}/restart`, { method: 'POST' });- }-- async getPythonAppStatus(appId) {- return this.request(`/python/apps/${appId}/status`);- }-- async getGunicornConfig(appId) {- return this.request(`/python/apps/${appId}/gunicorn`);- }-- async updateGunicornConfig(appId, content) {- return this.request(`/python/apps/${appId}/gunicorn`, {- method: 'PUT',- body: { content }- });- }-- async runPythonMigrations(appId) {- return this.request(`/python/apps/${appId}/migrate`, { method: 'POST' });- }-- async collectPythonStatic(appId) {- return this.request(`/python/apps/${appId}/collectstatic`, { method: 'POST' });- }-- async runPythonCommand(appId, command) {- return this.request(`/python/apps/${appId}/run`, {- method: 'POST',- body: { command }- });- }-- async deletePythonApp(appId, removeFiles = false) {- return this.request(`/python/apps/${appId}`, {- method: 'DELETE',- body: { remove_files: removeFiles }- });- }-- // Docker endpoints- async getDockerStatus() {- return this.request('/docker/status');- }-- async getDockerInfo() {- return this.request('/docker/info');- }-- async getDockerDiskUsage() {- return this.request('/docker/disk-usage');- }-- // Containers- async getContainers(all = true) {- return this.request(`/docker/containers?all=${all}`);- }-- async getContainer(containerId) {- return this.request(`/docker/containers/${containerId}`);- }-- async createContainer(data) {- return this.request('/docker/containers', {- method: 'POST',- body: data- });- }-- async runContainer(data) {- return this.request('/docker/containers/run', {- method: 'POST',- body: data- });- }-- async startContainer(containerId) {- return this.request(`/docker/containers/${containerId}/start`, { method: 'POST' });- }-- async stopContainer(containerId, timeout = 10) {- return this.request(`/docker/containers/${containerId}/stop`, {- method: 'POST',- body: { timeout }- });- }-- async restartContainer(containerId, timeout = 10) {- return this.request(`/docker/containers/${containerId}/restart`, {- method: 'POST',- body: { timeout }- });- }-- async removeContainer(containerId, force = false, volumes = false) {- return this.request(`/docker/containers/${containerId}`, {- method: 'DELETE',- body: { force, volumes }- });- }-- async getContainerLogs(containerId, tail = 100, since = null) {- const params = new URLSearchParams({ tail });- if (since) params.append('since', since);- return this.request(`/docker/containers/${containerId}/logs?${params}`);- }-- async getContainerStats(containerId) {- return this.request(`/docker/containers/${containerId}/stats`);- }-- async execContainer(containerId, command) {- return this.request(`/docker/containers/${containerId}/exec`, {- method: 'POST',- body: { command }- });- }-- // Images- async getImages() {- return this.request('/docker/images');- }-- async pullImage(image, tag = 'latest') {- return this.request('/docker/images/pull', {- method: 'POST',- body: { image, tag }- });- }-- async removeImage(imageId, force = false) {- return this.request(`/docker/images/${imageId}`, {- method: 'DELETE',- body: { force }- });- }-- async buildImage(path, tag, dockerfile = 'Dockerfile', noCache = false) {- return this.request('/docker/images/build', {- method: 'POST',- body: { path, tag, dockerfile, no_cache: noCache }- });- }-- // Networks- async getNetworks() {- return this.request('/docker/networks');- }-- async createNetwork(name, driver = 'bridge') {- return this.request('/docker/networks', {- method: 'POST',- body: { name, driver }- });- }-- async removeNetwork(networkId) {- return this.request(`/docker/networks/${networkId}`, { method: 'DELETE' });- }-- // Volumes- async getVolumes() {- return this.request('/docker/volumes');- }-- async createVolume(name, driver = 'local') {- return this.request('/docker/volumes', {- method: 'POST',- body: { name, driver }- });- }-- async removeVolume(volumeName, force = false) {- return this.request(`/docker/volumes/${volumeName}`, {- method: 'DELETE',- body: { force }- });- }-- // Docker Compose- async composeUp(path, detach = true, build = false) {- return this.request('/docker/compose/up', {- method: 'POST',- body: { path, detach, build }- });- }-- async composeDown(path, volumes = false, removeOrphans = true) {- return this.request('/docker/compose/down', {- method: 'POST',- body: { path, volumes, remove_orphans: removeOrphans }- });- }-- async composePs(path) {- return this.request('/docker/compose/ps', {- method: 'POST',- body: { path }- });- }-- async composeLogs(path, service = null, tail = 100) {- return this.request('/docker/compose/logs', {- method: 'POST',- body: { path, service, tail }- });- }-- async composeRestart(path, service = null) {- return this.request('/docker/compose/restart', {- method: 'POST',- body: { path, service }- });- }-- async composePull(path, service = null) {- return this.request('/docker/compose/pull', {- method: 'POST',- body: { path, service }- });- }-- // Docker App- async createDockerApp(data) {- return this.request('/docker/apps', {- method: 'POST',- body: data- });- }-- async pruneDocker(all = false, volumes = false) {- return this.request('/docker/prune', {- method: 'POST',- body: { all, volumes }- });- }-- async dockerCleanup(includeVolumes = false) {- return this.request('/docker/cleanup', {- method: 'POST',- body: { volumes: includeVolumes }- });- }-- async cleanupAllApps() {- return this.request('/docker/cleanup/apps', {- method: 'POST'- });- }-- // Database endpoints- async getDatabaseStatus() {- return this.request('/databases/status');- }-- // MySQL- async getMySQLDatabases(rootPassword = null) {- const params = rootPassword ? `?root_password=${encodeURIComponent(rootPassword)}` : '';- return this.request(`/databases/mysql${params}`);- }-- async createMySQLDatabase(data) {- return this.request('/databases/mysql', {- method: 'POST',- body: data- });- }-- async dropMySQLDatabase(name, rootPassword = null) {- return this.request(`/databases/mysql/${name}`, {- method: 'DELETE',- body: { root_password: rootPassword }- });- }-- async getMySQLTables(database, rootPassword = null) {- const params = rootPassword ? `?root_password=${encodeURIComponent(rootPassword)}` : '';- return this.request(`/databases/mysql/${database}/tables${params}`);- }-- async backupMySQLDatabase(database, rootPassword = null) {- return this.request(`/databases/mysql/${database}/backup`, {- method: 'POST',- body: { root_password: rootPassword }- });- }-- async restoreMySQLDatabase(database, backupPath, rootPassword = null) {- return this.request(`/databases/mysql/${database}/restore`, {- method: 'POST',- body: { backup_path: backupPath, root_password: rootPassword }- });- }-- async getMySQLUsers(rootPassword = null) {- const params = rootPassword ? `?root_password=${encodeURIComponent(rootPassword)}` : '';- return this.request(`/databases/mysql/users${params}`);- }-- async createMySQLUser(data) {- return this.request('/databases/mysql/users', {- method: 'POST',- body: data- });- }-- async dropMySQLUser(username, host = 'localhost', rootPassword = null) {- return this.request(`/databases/mysql/users/${username}`, {- method: 'DELETE',- body: { host, root_password: rootPassword }- });- }-- async grantMySQLPrivileges(username, database, privileges = 'ALL', host = 'localhost', rootPassword = null) {- return this.request(`/databases/mysql/users/${username}/grant`, {- method: 'POST',- body: { database, privileges, host, root_password: rootPassword }- });- }-- // PostgreSQL- async getPostgreSQLDatabases() {- return this.request('/databases/postgresql');- }-- async createPostgreSQLDatabase(data) {- return this.request('/databases/postgresql', {- method: 'POST',- body: data- });- }-- async dropPostgreSQLDatabase(name) {- return this.request(`/databases/postgresql/${name}`, { method: 'DELETE' });- }-- async getPostgreSQLTables(database) {- return this.request(`/databases/postgresql/${database}/tables`);- }-- async backupPostgreSQLDatabase(database) {- return this.request(`/databases/postgresql/${database}/backup`, { method: 'POST' });- }-- async restorePostgreSQLDatabase(database, backupPath) {- return this.request(`/databases/postgresql/${database}/restore`, {- method: 'POST',- body: { backup_path: backupPath }- });- }-- async getPostgreSQLUsers() {- return this.request('/databases/postgresql/users');- }-- async createPostgreSQLUser(data) {- return this.request('/databases/postgresql/users', {- method: 'POST',- body: data- });- }-- async dropPostgreSQLUser(username) {- return this.request(`/databases/postgresql/users/${username}`, { method: 'DELETE' });- }-- async grantPostgreSQLPrivileges(username, database, privileges = 'ALL') {- return this.request(`/databases/postgresql/users/${username}/grant`, {- method: 'POST',- body: { database, privileges }- });- }-- // Backups- async getDatabaseBackups(type = null) {- const params = type ? `?type=${type}` : '';- return this.request(`/databases/backups${params}`);- }-- async deleteDatabaseBackup(filename) {- return this.request(`/databases/backups/${filename}`, { method: 'DELETE' });- }-- async generateDatabasePassword(length = 16) {- return this.request(`/databases/generate-password?length=${length}`);- }-- // Query Execution- async executeMySQLQuery(database, query, readonly = true) {- return this.request(`/databases/mysql/${database}/query`, {- method: 'POST',- body: { query, readonly }- });- }-- async executePostgreSQLQuery(database, query, readonly = true) {- return this.request(`/databases/postgresql/${database}/query`, {- method: 'POST',- body: { query, readonly }- });- }-- async executeSQLiteQuery(path, query, readonly = true) {- return this.request('/databases/sqlite/query', {- method: 'POST',- body: { path, query, readonly }- });- }-- async getMySQLTableStructure(database, table) {- return this.request(`/databases/mysql/${database}/tables/${table}/structure`);- }-- async getPostgreSQLTableStructure(database, table) {- return this.request(`/databases/postgresql/${database}/tables/${table}/structure`);- }-- async getSQLiteTableStructure(path, table) {- return this.request(`/databases/sqlite/tables/${table}/structure?path=${encodeURIComponent(path)}`);- }-- async getSQLiteDatabases() {- return this.request('/databases/sqlite');- }-- async getSQLiteTables(path) {- return this.request(`/databases/sqlite/tables?path=${encodeURIComponent(path)}`);- }-- // Docker Container Databases- async getDockerDatabases() {- return this.request('/databases/docker');- }-- async getAppDatabases(appId) {- return this.request(`/databases/docker/app/${appId}`);- }-- async getDockerContainerDatabases(container, password = null) {- const headers = password ? { 'X-DB-Password': password } : {};- return this.request(`/databases/docker/${container}/databases`, { headers });- }-- async getDockerDatabaseTables(container, database, password = null) {- const headers = password ? { 'X-DB-Password': password } : {};- return this.request(`/databases/docker/${container}/${database}/tables`, { headers });- }-- async executeDockerQuery(container, database, query, password = null, readonly = true) {- const headers = password ? { 'X-DB-Password': password } : {};- return this.request(`/databases/docker/${container}/${database}/query`, {- method: 'POST',- body: { query, readonly, password },- headers- });- }-- // Docker App Logs and Status- async getDockerAppLogs(appId, lines = 100) {- return this.request(`/apps/${appId}/logs?lines=${lines}`);- }-- async getDockerAppStatus(appId) {- return this.request(`/apps/${appId}/status`);- }-- // ========================================- // Monitoring & Alerts endpoints- // ========================================- async getMonitoringStatus() {- return this.request('/monitoring/status');- }-- async getMonitoringMetrics() {- return this.request('/monitoring/metrics');- }-- async checkAlerts() {- return this.request('/monitoring/alerts/check');- }-- async getAlertHistory(limit = 100) {- return this.request(`/monitoring/alerts/history?limit=${limit}`);- }-- async getMonitoringConfig() {- return this.request('/monitoring/config');- }-- async updateMonitoringConfig(config) {- return this.request('/monitoring/config', {- method: 'PUT',- body: config- });- }-- async getMonitoringThresholds() {- return this.request('/monitoring/thresholds');- }-- async updateMonitoringThresholds(thresholds) {- return this.request('/monitoring/thresholds', {- method: 'PUT',- body: thresholds- });- }-- async startMonitoring() {- return this.request('/monitoring/start', { method: 'POST' });- }-- async stopMonitoring() {- return this.request('/monitoring/stop', { method: 'POST' });- }-- async testEmailAlert(email) {- return this.request('/monitoring/test/email', {- method: 'POST',- body: { email }- });- }-- async testWebhookAlert(webhookUrl) {- return this.request('/monitoring/test/webhook', {- method: 'POST',- body: { webhook_url: webhookUrl }- });- }-- // ========================================- // Backup System endpoints- // ========================================- async getBackups(type = null) {- const params = type ? `?type=${type}` : '';- return this.request(`/backups${params}`);- }-- async getBackupStats() {- return this.request('/backups/stats');- }-- async getBackupConfig() {- return this.request('/backups/config');- }-- async updateBackupConfig(config) {- return this.request('/backups/config', {- method: 'PUT',- body: config- });- }-- async backupApplication(applicationId, includeDb = false, dbConfig = null) {- return this.request('/backups/application', {- method: 'POST',- body: {- application_id: applicationId,- include_db: includeDb,- db_config: dbConfig- }- });- }-- async backupDatabase(dbType, dbName, user = null, password = null, host = 'localhost') {- return this.request('/backups/database', {- method: 'POST',- body: { db_type: dbType, db_name: dbName, user, password, host }- });- }-- async restoreApplication(backupPath, restorePath = null) {- return this.request('/backups/restore/application', {- method: 'POST',- body: { backup_path: backupPath, restore_path: restorePath }- });- }-- async restoreDatabase(backupPath, dbType, dbName, user = null, password = null, host = 'localhost') {- return this.request('/backups/restore/database', {- method: 'POST',- body: { backup_path: backupPath, db_type: dbType, db_name: dbName, user, password, host }- });- }-- async deleteBackup(backupPath) {- return this.request(`/backups/${encodeURIComponent(backupPath)}`, { method: 'DELETE' });- }-- async cleanupBackups(retentionDays = null) {- return this.request('/backups/cleanup', {- method: 'POST',- body: retentionDays ? { retention_days: retentionDays } : {}- });- }-- async getBackupSchedules() {- return this.request('/backups/schedules');- }-- async addBackupSchedule(name, backupType, target, scheduleTime, days = null, uploadRemote = false) {- return this.request('/backups/schedules', {- method: 'POST',- body: { name, backup_type: backupType, target, schedule_time: scheduleTime, days, upload_remote: uploadRemote }- });- }-- async updateBackupSchedule(scheduleId, updates) {- return this.request(`/backups/schedules/${scheduleId}`, {- method: 'PUT',- body: updates- });- }-- async removeBackupSchedule(scheduleId) {- return this.request(`/backups/schedules/${scheduleId}`, { method: 'DELETE' });- }-- async backupFiles(filePaths, name = null) {- return this.request('/backups/files', {- method: 'POST',- body: { paths: filePaths, name }- });- }-- // Remote Storage- async getStorageConfig() {- return this.request('/backups/storage');- }-- async updateStorageConfig(config) {- return this.request('/backups/storage', {- method: 'PUT',- body: config- });- }-- async testStorageConnection(config = null) {- return this.request('/backups/storage/test', {- method: 'POST',- body: config || {}- });- }-- async uploadBackupToRemote(backupPath) {- return this.request('/backups/upload', {- method: 'POST',- body: { backup_path: backupPath }- });- }-- async verifyRemoteBackup(remoteKey, localPath) {- return this.request('/backups/verify', {- method: 'POST',- body: { remote_key: remoteKey, local_path: localPath }- });- }-- async listRemoteBackups(prefix = null) {- const params = prefix ? `?prefix=${encodeURIComponent(prefix)}` : '';- return this.request(`/backups/remote${params}`);- }-- async downloadRemoteBackup(remoteKey, localPath = null) {- return this.request('/backups/remote/download', {- method: 'POST',- body: { remote_key: remoteKey, local_path: localPath }- });- }-- // ========================================- // Git Deployment endpoints- // ========================================- async getDeployConfig(appId) {- return this.request(`/deploy/apps/${appId}/config`);- }-- async configureDeployment(appId, repoUrl, branch = 'main', autoDeploy = true, preDeployScript = null, postDeployScript = null) {- return this.request(`/deploy/apps/${appId}/config`, {- method: 'POST',- body: {- repo_url: repoUrl,- branch,- auto_deploy: autoDeploy,- pre_deploy_script: preDeployScript,- post_deploy_script: postDeployScript- }- });- }-- async removeDeployment(appId) {- return this.request(`/deploy/apps/${appId}/config`, { method: 'DELETE' });- }-- async triggerDeploy(appId, force = false) {- return this.request(`/deploy/apps/${appId}/deploy`, {- method: 'POST',- body: { force }- });- }-- async pullChanges(appId, branch = null) {- return this.request(`/deploy/apps/${appId}/pull`, {- method: 'POST',- body: branch ? { branch } : {}- });- }-- async getGitStatus(appId) {- return this.request(`/deploy/apps/${appId}/git-status`);- }-- async getCommitInfo(appId) {- return this.request(`/deploy/apps/${appId}/commit`);- }-- async getDeploymentHistory(appId = null, limit = 50) {- const params = new URLSearchParams({ limit });- if (appId) params.append('app_id', appId);- return this.request(`/deploy/history?${params}`);- }-- async cloneRepository(appPath, repoUrl, branch = 'main') {- return this.request('/deploy/clone', {- method: 'POST',- body: { app_path: appPath, repo_url: repoUrl, branch }- });- }-- async getAppBranches(appId) {- return this.request(`/deploy/apps/${appId}/branches`);- }-- async getBranchesFromUrl(repoUrl) {- return this.request('/deploy/branches', {- method: 'POST',- body: { repo_url: repoUrl }- });- }-- async getWebhookLogs(appId = null, limit = 50) {- const params = new URLSearchParams({ limit });- if (appId) params.append('app_id', appId);- return this.request(`/deploy/webhook-logs?${params}`);- }-- // ========================================- // Build & Deployment endpoints- // ========================================- async getBuildConfig(appId) {- return this.request(`/builds/apps/${appId}/build-config`);- }-- async configureBuild(appId, config) {- return this.request(`/builds/apps/${appId}/build-config`, {- method: 'POST',- body: config- });- }-- async removeBuildConfig(appId) {- return this.request(`/builds/apps/${appId}/build-config`, { method: 'DELETE' });- }-- async detectBuildMethod(appId) {- return this.request(`/builds/apps/${appId}/detect`);- }-- async getNixpacksPlan(appId) {- return this.request(`/builds/apps/${appId}/nixpacks-plan`);- }-- async triggerBuild(appId, noCache = false) {- return this.request(`/builds/apps/${appId}/build`, {- method: 'POST',- body: { no_cache: noCache }- });- }-- async getBuildLogs(appId, limit = 20) {- return this.request(`/builds/apps/${appId}/build-logs?limit=${limit}`);- }-- async getBuildLogDetail(appId, timestamp) {- return this.request(`/builds/apps/${appId}/build-logs/${timestamp}`);- }-- async clearBuildCache(appId) {- return this.request(`/builds/apps/${appId}/clear-cache`, { method: 'POST' });- }-- async deployApp(appId, options = {}) {- return this.request(`/builds/apps/${appId}/deploy`, {- method: 'POST',- body: options- });- }-- async getDeployments(appId, limit = 20, offset = 0) {- return this.request(`/builds/apps/${appId}/deployments?limit=${limit}&offset=${offset}`);- }-- async getDeploymentDetail(deploymentId, includeLogs = false) {- return this.request(`/builds/deployments/${deploymentId}?include_logs=${includeLogs}`);- }-- async getDeploymentDiff(deploymentId) {- return this.request(`/builds/deployments/${deploymentId}/diff`);- }-- async rollback(appId, targetVersion = null) {- return this.request(`/builds/apps/${appId}/rollback`, {- method: 'POST',- body: targetVersion ? { version: targetVersion } : {}- });- }-- async getCurrentDeployment(appId) {- return this.request(`/builds/apps/${appId}/current-deployment`);- }-- // ========================================- // Template endpoints- // ========================================- async listTemplates(category = null, search = null) {- const params = new URLSearchParams();- if (category) params.append('category', category);- if (search) params.append('search', search);- const query = params.toString();- return this.request(`/templates/${query ? '?' + query : ''}`);- }-- async getTemplateCategories() {- return this.request('/templates/categories');- }-- async getTemplate(templateId) {- return this.request(`/templates/${templateId}`);- }-- async installTemplate(templateId, appName, variables = {}) {- return this.request(`/templates/${templateId}/install`, {- method: 'POST',- body: { app_name: appName, variables }- });- }-- async validateTemplateInstall(templateId, appName, variables = {}) {- return this.request('/templates/validate-install', {- method: 'POST',- body: { template_id: templateId, app_name: appName, variables }- });- }-- async testDatabaseConnection(config) {- return this.request('/templates/test-db-connection', {- method: 'POST',- body: config- });- }-- async checkAppUpdate(appId) {- return this.request(`/templates/apps/${appId}/check-update`);- }-- async updateAppFromTemplate(appId) {- return this.request(`/templates/apps/${appId}/update`, { method: 'POST' });- }-- async getAppTemplateInfo(appId) {- return this.request(`/templates/apps/${appId}/template-info`);- }-- async listTemplateRepos() {- return this.request('/templates/repos');- }-- async addTemplateRepo(name, url) {- return this.request('/templates/repos', {- method: 'POST',- body: { name, url }- });- }-- async removeTemplateRepo(url) {- return this.request('/templates/repos', {- method: 'DELETE',- body: { url }- });- }-- async syncTemplates() {- return this.request('/templates/sync', { method: 'POST' });- }-- // ========================================- // File Manager endpoints- // ========================================- async browseFiles(path = '/home', showHidden = false) {- const params = new URLSearchParams({ path, show_hidden: showHidden });- return this.request(`/files/browse?${params}`);- }-- async getFileInfo(path) {- return this.request(`/files/info?path=${encodeURIComponent(path)}`);- }-- async readFile(path) {- return this.request(`/files/read?path=${encodeURIComponent(path)}`);- }-- async writeFile(path, content, createBackup = true) {- return this.request('/files/write', {- method: 'POST',- body: { path, content, create_backup: createBackup }- });- }-- async createFile(path, content = '') {- return this.request('/files/create', {- method: 'POST',- body: { path, content }- });- }-- async createDirectory(path) {- return this.request('/files/mkdir', {- method: 'POST',- body: { path }- });- }-- async deleteFile(path) {- return this.request(`/files/delete?path=${encodeURIComponent(path)}`, {- method: 'DELETE'- });- }-- async renameFile(path, newName) {- return this.request('/files/rename', {- method: 'POST',- body: { path, new_name: newName }- });- }-- async copyFile(src, dest) {- return this.request('/files/copy', {- method: 'POST',- body: { src, dest }- });- }-- async moveFile(src, dest) {- return this.request('/files/move', {- method: 'POST',- body: { src, dest }- });- }-- async changeFilePermissions(path, mode) {- return this.request('/files/chmod', {- method: 'POST',- body: { path, mode }- });- }-- async searchFiles(directory, pattern, maxResults = 100) {- const params = new URLSearchParams({ directory, pattern, max_results: maxResults });- return this.request(`/files/search?${params}`);- }-- async getDiskUsage(path = '/') {- return this.request(`/files/disk-usage?path=${encodeURIComponent(path)}`);- }-- async getAllDiskMounts() {- return this.request('/files/disk-mounts');- }-- async analyzeDirectory(path = '/home', depth = 2, limit = 20) {- const params = new URLSearchParams({ path, depth, limit });- return this.request(`/files/analyze?${params}`);- }-- async getFileTypeBreakdown(path = '/home', maxDepth = 3) {- const params = new URLSearchParams({ path, max_depth: maxDepth });- return this.request(`/files/type-breakdown?${params}`);- }-- async downloadFile(path) {- const token = this.getToken();- const url = `${this.baseUrl}/files/download?path=${encodeURIComponent(path)}`;- window.open(`${url}&token=${token}`, '_blank');- }-- async uploadFile(destination, file, onProgress = null) {- const token = this.getToken();- const formData = new FormData();- formData.append('file', file);- formData.append('destination', destination);-- return new Promise((resolve, reject) => {- const xhr = new XMLHttpRequest();- xhr.open('POST', `${this.baseUrl}/files/upload`);- xhr.setRequestHeader('Authorization', `Bearer ${token}`);-- if (onProgress) {- xhr.upload.onprogress = (e) => {- if (e.lengthComputable) {- onProgress((e.loaded / e.total) * 100);- }- };- }-- xhr.onload = () => {- if (xhr.status >= 200 && xhr.status < 300) {- resolve(JSON.parse(xhr.responseText));- } else {- reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));- }- };-- xhr.onerror = () => reject(new Error('Upload failed'));- xhr.send(formData);- });- }-- // ========================================- // FTP Server endpoints- // ========================================- async getFTPStatus() {- return this.request('/ftp/status');- }-- async controlFTPService(action, service = null) {- return this.request(`/ftp/service/${action}`, {- method: 'POST',- body: service ? { service } : {}- });- }-- async getFTPConfig(service = null) {- const params = service ? `?service=${service}` : '';- return this.request(`/ftp/config${params}`);- }-- async updateFTPConfig(config, service = null) {- return this.request('/ftp/config', {- method: 'POST',- body: { config, service }- });- }-- async getFTPUsers() {- return this.request('/ftp/users');- }-- async createFTPUser(username, password = null, homeDir = null) {- return this.request('/ftp/users', {- method: 'POST',- body: { username, password, home_dir: homeDir }- });- }-- async deleteFTPUser(username, deleteHome = false) {- const params = deleteHome ? '?delete_home=true' : '';- return this.request(`/ftp/users/${username}${params}`, {- method: 'DELETE'- });- }-- async changeFTPPassword(username, password = null) {- return this.request(`/ftp/users/${username}/password`, {- method: 'POST',- body: password ? { password } : {}- });- }-- async toggleFTPUser(username, enabled) {- return this.request(`/ftp/users/${username}/toggle`, {- method: 'POST',- body: { enabled }- });- }-- async getFTPConnections() {- return this.request('/ftp/connections');- }-- async disconnectFTPSession(pid) {- return this.request(`/ftp/connections/${pid}`, {- method: 'DELETE'- });- }-- async getFTPLogs(lines = 100) {- return this.request(`/ftp/logs?lines=${lines}`);- }-- async installFTPServer(service = 'vsftpd') {- return this.request('/ftp/install', {- method: 'POST',- body: { service }- });- }-- async testFTPConnection(host = 'localhost', port = 21, username = null, password = null) {- return this.request('/ftp/test', {- method: 'POST',- body: { host, port, username, password }- });- }-- // ========================================- // Firewall endpoints- // ========================================- async getFirewallStatus() {- return this.request('/firewall/status');- }-- async enableFirewall(firewall = null) {- return this.request('/firewall/enable', {- method: 'POST',- body: firewall ? { firewall } : {}- });- }-- async disableFirewall(firewall = null) {- return this.request('/firewall/disable', {- method: 'POST',- body: firewall ? { firewall } : {}- });- }-- async getFirewallRules(firewall = null) {- const params = firewall ? `?firewall=${firewall}` : '';- return this.request(`/firewall/rules${params}`);- }-- async addFirewallRule(ruleData) {- return this.request('/firewall/rules', {- method: 'POST',- body: ruleData- });- }-- async removeFirewallRule(ruleData) {- return this.request('/firewall/rules', {- method: 'DELETE',- body: ruleData- });- }-- async blockIP(ip, permanent = true) {- return this.request('/firewall/block-ip', {- method: 'POST',- body: { ip, permanent }- });- }-- async unblockIP(ip, permanent = true) {- return this.request('/firewall/unblock-ip', {- method: 'POST',- body: { ip, permanent }- });- }-- async getBlockedIPs() {- return this.request('/firewall/blocked-ips');- }-- async allowPort(port, protocol = 'tcp', permanent = true) {- return this.request('/firewall/allow-port', {- method: 'POST',- body: { port, protocol, permanent }- });- }-- async denyPort(port, protocol = 'tcp', permanent = true) {- return this.request('/firewall/deny-port', {- method: 'POST',- body: { port, protocol, permanent }- });- }-- async getFirewallZones() {- return this.request('/firewall/zones');- }-- async setDefaultZone(zone) {- return this.request('/firewall/zones/default', {- method: 'POST',- body: { zone }- });- }-- async installFirewall(firewall = 'ufw') {- return this.request('/firewall/install', {- method: 'POST',- body: { firewall }- });- }-- // ========================================- // Git Server endpoints- // ========================================- async getGitStatus() {- return this.request('/git/status');- }-- async getGitRequirements() {- return this.request('/git/requirements');- }-- async installGit(data) {- return this.request('/git/install', {- method: 'POST',- body: data- });- }-- async uninstallGit(removeData = false) {- return this.request('/git/uninstall', {- method: 'POST',- body: { removeData }- });- }-- async startGit() {- return this.request('/git/start', { method: 'POST' });- }-- async stopGit() {- return this.request('/git/stop', { method: 'POST' });- }-- async restartGit() {- return this.request('/git/restart', { method: 'POST' });- }-- // ========================================- // WordPress Standalone endpoints- // ========================================- async getWordPressStatus() {- return this.request('/wordpress/standalone/status');- }-- async getWordPressRequirements() {- return this.request('/wordpress/standalone/requirements');- }-- async installWordPress(data) {- return this.request('/wordpress/standalone/install', {- method: 'POST',- body: data- });- }-- async uninstallWordPress(removeData = false) {- return this.request('/wordpress/standalone/uninstall', {- method: 'POST',- body: { removeData }- });- }-- async startWordPress() {- return this.request('/wordpress/standalone/start', { method: 'POST' });- }-- async stopWordPress() {- return this.request('/wordpress/standalone/stop', { method: 'POST' });- }-- async restartWordPress() {- return this.request('/wordpress/standalone/restart', { method: 'POST' });- }-- // Git Webhooks- async getWebhooks() {- return this.request('/git/webhooks');- }-- async getWebhook(webhookId) {- return this.request(`/git/webhooks/${webhookId}`);- }-- async createWebhook(data) {- return this.request('/git/webhooks', {- method: 'POST',- body: data- });- }-- async updateWebhook(webhookId, data) {- return this.request(`/git/webhooks/${webhookId}`, {- method: 'PUT',- body: data- });- }-- async deleteWebhook(webhookId) {- return this.request(`/git/webhooks/${webhookId}`, { method: 'DELETE' });- }-- async toggleWebhook(webhookId) {- return this.request(`/git/webhooks/${webhookId}/toggle`, { method: 'POST' });- }-- async getWebhookLogs(webhookId, limit = 50) {- return this.request(`/git/webhooks/${webhookId}/logs?limit=${limit}`);- }-- async testWebhook(webhookId) {- return this.request(`/git/webhooks/${webhookId}/test`, { method: 'POST' });- }-- // Git Repositories- async getRepositories(limit = 50) {- return this.request(`/git/repos?limit=${limit}`);- }-- async getRepository(owner, repo) {- return this.request(`/git/repos/${owner}/${repo}`);- }-- async getRepoStats(owner, repo) {- return this.request(`/git/repos/${owner}/${repo}/stats`);- }-- async getBranches(owner, repo) {- return this.request(`/git/repos/${owner}/${repo}/branches`);- }-- async getBranch(owner, repo, branch) {- return this.request(`/git/repos/${owner}/${repo}/branches/${branch}`);- }-- async getCommits(owner, repo, branch = null, page = 1, limit = 30) {- let url = `/git/repos/${owner}/${repo}/commits?page=${page}&limit=${limit}`;- if (branch) url += `&branch=${branch}`;- return this.request(url);- }-- async getCommit(owner, repo, sha) {- return this.request(`/git/repos/${owner}/${repo}/commits/${sha}`);- }-- async getRepoFiles(owner, repo, ref = 'main', path = '') {- let url = `/git/repos/${owner}/${repo}/contents?ref=${ref}`;- if (path) url += `&path=${path}`;- return this.request(url);- }-- async getFileContent(owner, repo, filepath, ref = 'main') {- return this.request(`/git/repos/${owner}/${repo}/contents/${filepath}?ref=${ref}`);- }-- async getRepoReadme(owner, repo, ref = null) {- let url = `/git/repos/${owner}/${repo}/readme`;- if (ref) url += `?ref=${ref}`;- return this.request(url);- }-- async getGiteaVersion() {- return this.request('/git/version');- }-- // Git Deployments- async getAppDeployments(appId, limit = 20) {- return this.request(`/git/deployments/app/${appId}?limit=${limit}`);- }-- async getDeployment(deploymentId, includeLogs = false) {- return this.request(`/git/deployments/${deploymentId}?logs=${includeLogs}`);- }-- async triggerDeploy(appId, branch = null) {- return this.request(`/git/deployments/app/${appId}/deploy`, {- method: 'POST',- body: branch ? { branch } : {}- });- }-- async rollbackDeployment(appId, targetVersion = null) {- return this.request(`/git/deployments/app/${appId}/rollback`, {- method: 'POST',- body: targetVersion ? { targetVersion } : {}- });- }-- async getWebhookDeployments(webhookId, limit = 20) {- return this.request(`/git/deployments/webhook/${webhookId}?limit=${limit}`);- }-- // ========================================- // Cron Job endpoints- // ========================================- async getCronStatus() {- return this.request('/cron/status');- }-- async getCronJobs() {- return this.request('/cron/jobs');- }-- async createCronJob(data) {- return this.request('/cron/jobs', {- method: 'POST',- body: data- });- }-- async updateCronJob(jobId, data) {- return this.request(`/cron/jobs/${jobId}`, {- method: 'PUT',- body: data- });- }-- async deleteCronJob(jobId) {- return this.request(`/cron/jobs/${jobId}`, { method: 'DELETE' });- }-- async toggleCronJob(jobId, enabled) {- return this.request(`/cron/jobs/${jobId}/toggle`, {- method: 'POST',- body: { enabled }- });- }-- async runCronJob(jobId) {- return this.request(`/cron/jobs/${jobId}/run`, { method: 'POST' });- }-- async getCronPresets() {- return this.request('/cron/presets');- }-- // ========================================- // Uptime Tracking endpoints- // ========================================- async getCurrentUptime() {- return this.request('/uptime/current');- }-- async getUptimeStats() {- return this.request('/uptime/stats');- }-- async getUptimeGraph(period = '24h') {- return this.request(`/uptime/graph?period=${period}`);- }-- async getUptimeHistory(hours = 24) {- return this.request(`/uptime/history?hours=${hours}`);- }-- async startUptimeTracking() {- return this.request('/uptime/tracking/start', { method: 'POST' });- }-- async stopUptimeTracking() {- return this.request('/uptime/tracking/stop', { method: 'POST' });- }-- async getUptimeTrackingStatus() {- return this.request('/uptime/tracking/status');- }-- // ========================================- // Metrics History endpoints- // ========================================- async getMetricsHistory(period = '1h') {- return this.request(`/metrics/history?period=${period}`);- }-- async getMetricsStats() {- return this.request('/metrics/stats');- }-- async startMetricsCollection() {- return this.request('/metrics/collection/start', { method: 'POST' });- }-- async stopMetricsCollection() {- return this.request('/metrics/collection/stop', { method: 'POST' });- }-- async triggerMetricsAggregation() {- return this.request('/metrics/aggregate', { method: 'POST' });- }-- // ========================================- // Private URL endpoints- // ========================================- async enablePrivateUrl(appId, slug = null) {- return this.request(`/apps/${appId}/private-url`, {- method: 'POST',- body: slug ? { slug } : {}- });- }-- async getPrivateUrl(appId) {- return this.request(`/apps/${appId}/private-url`);- }-- async updatePrivateUrl(appId, slug) {- return this.request(`/apps/${appId}/private-url`, {- method: 'PUT',- body: { slug }- });- }-- async disablePrivateUrl(appId) {- return this.request(`/apps/${appId}/private-url`, {- method: 'DELETE'- });- }-- async regeneratePrivateUrl(appId) {- return this.request(`/apps/${appId}/private-url/regenerate`, {- method: 'POST'- });- }-- // ========================================- // Environment Variables endpoints- // ========================================- async getEnvVars(appId, maskSecrets = false) {- const params = maskSecrets ? '?mask=true' : '';- return this.request(`/apps/${appId}/env${params}`);- }-- async getEnvVar(appId, key) {- return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`);- }-- async createEnvVar(appId, key, value, isSecret = false, description = null) {- return this.request(`/apps/${appId}/env`, {- method: 'POST',- body: { key, value, is_secret: isSecret, description }- });- }-- async updateEnvVar(appId, key, data) {- return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`, {- method: 'PUT',- body: data- });- }-- async deleteEnvVar(appId, key) {- return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`, {- method: 'DELETE'- });- }-- async bulkSetEnvVars(appId, envVars) {- return this.request(`/apps/${appId}/env/bulk`, {- method: 'POST',- body: { env_vars: envVars }- });- }-- async importEnvFile(appId, content, overwrite = true) {- return this.request(`/apps/${appId}/env/import`, {- method: 'POST',- body: { content, overwrite }- });- }-- async exportEnvFile(appId, includeSecrets = true) {- const params = includeSecrets ? '' : '?include_secrets=false';- return this.request(`/apps/${appId}/env/export${params}`);- }-- async getEnvVarHistory(appId, limit = 50) {- return this.request(`/apps/${appId}/env/history?limit=${limit}`);- }-- async clearEnvVars(appId) {- return this.request(`/apps/${appId}/env/clear`, {- method: 'DELETE'- });- }-- // ========================================- // Two-Factor Authentication endpoints- // ========================================- async get2FAStatus() {- return this.request('/auth/2fa/status');- }-- async initiate2FASetup() {- return this.request('/auth/2fa/setup', { method: 'POST' });- }-- async confirm2FASetup(code) {- return this.request('/auth/2fa/setup/confirm', {- method: 'POST',- body: { code }- });- }-- async disable2FA(code) {- return this.request('/auth/2fa/disable', {- method: 'POST',- body: { code }- });- }-- async regenerateBackupCodes(code) {- return this.request('/auth/2fa/backup-codes/regenerate', {- method: 'POST',- body: { code }- });- }-- async verify2FA(tempToken, code) {- return this.request('/auth/2fa/verify', {- method: 'POST',- body: { temp_token: tempToken, code }- });- }-- // ========================================- // Notification Webhooks endpoints- // ========================================- async getNotificationsStatus() {- return this.request('/notifications/status');- }-- async getNotificationsConfig() {- return this.request('/notifications/config');- }-- async updateNotificationChannel(channel, settings) {- return this.request(`/notifications/config/${channel}`, {- method: 'PUT',- body: settings- });- }-- async testNotificationChannel(channel) {- return this.request(`/notifications/test/${channel}`, {- method: 'POST'- });- }-- async testAllNotifications() {- return this.request('/notifications/test', {- method: 'POST'- });- }-- // User notification preferences- async getUserNotificationPreferences() {- return this.request('/notifications/preferences');- }-- async updateUserNotificationPreferences(preferences) {- return this.request('/notifications/preferences', {- method: 'PUT',- body: preferences- });- }-- async testUserNotification() {- return this.request('/notifications/preferences/test', {- method: 'POST'- });- }-- // ========================================- // Security (ClamAV, File Integrity) endpoints- // ========================================- async getSecurityStatus() {- return this.request('/security/status');- }-- async getSecurityConfig() {- return this.request('/security/config');- }-- async updateSecurityConfig(config) {- return this.request('/security/config', {- method: 'PUT',- body: config- });- }-- async getClamAVStatus() {- return this.request('/security/clamav/status');- }-- async installClamAV() {- return this.request('/security/clamav/install', { method: 'POST' });- }-- async updateVirusDefinitions() {- return this.request('/security/clamav/update', { method: 'POST' });- }-- async scanFile(path) {- return this.request('/security/scan/file', {- method: 'POST',- body: { path }- });- }-- async scanDirectory(path, recursive = true) {- return this.request('/security/scan/directory', {- method: 'POST',- body: { path, recursive }- });- }-- async getScanStatus() {- return this.request('/security/scan/status');- }-- async cancelScan() {- return this.request('/security/scan/cancel', { method: 'POST' });- }-- async getScanHistory(limit = 50) {- return this.request(`/security/scan/history?limit=${limit}`);- }-- async runQuickScan() {- return this.request('/security/scan/quick', { method: 'POST' });- }-- async runFullScan() {- return this.request('/security/scan/full', { method: 'POST' });- }-- async getQuarantinedFiles() {- return this.request('/security/quarantine');- }-- async quarantineFile(path) {- return this.request('/security/quarantine', {- method: 'POST',- body: { path }- });- }-- async deleteQuarantinedFile(filename) {- return this.request(`/security/quarantine/${encodeURIComponent(filename)}`, {- method: 'DELETE'- });- }-- async initializeIntegrityDatabase(paths = null) {- return this.request('/security/integrity/initialize', {- method: 'POST',- body: paths ? { paths } : {}- });- }-- async checkFileIntegrity() {- return this.request('/security/integrity/check');- }-- async getFailedLogins(hours = 24) {- return this.request(`/security/failed-logins?hours=${hours}`);- }-- async getSecurityEvents(limit = 100) {- return this.request(`/security/events?limit=${limit}`);- }-- // ========================================- // Fail2ban endpoints- // ========================================- async getFail2banStatus() {- return this.request('/security/fail2ban/status');- }-- async installFail2ban() {- return this.request('/security/fail2ban/install', { method: 'POST' });- }-- async getFail2banJailStatus(jail) {- return this.request(`/security/fail2ban/jails/${jail}`);- }-- async getAllFail2banBans() {- return this.request('/security/fail2ban/bans');- }-- async fail2banUnban(ip, jail = null) {- return this.request('/security/fail2ban/unban', {- method: 'POST',- body: { ip, jail }- });- }-- async fail2banBan(ip, jail = 'sshd') {- return this.request('/security/fail2ban/ban', {- method: 'POST',- body: { ip, jail }- });- }-- // ========================================- // SSH Key endpoints- // ========================================- async getSSHKeys(user = 'root') {- return this.request(`/security/ssh-keys?user=${user}`);- }-- async addSSHKey(key, user = 'root') {- return this.request('/security/ssh-keys', {- method: 'POST',- body: { key, user }- });- }-- async removeSSHKey(keyId, user = 'root') {- return this.request(`/security/ssh-keys/${keyId}?user=${user}`, {- method: 'DELETE'- });- }-- // ========================================- // IP Lists endpoints- // ========================================- async getIPLists() {- return this.request('/security/ip-lists');- }-- async addToIPList(ip, listType, comment = '') {- return this.request(`/security/ip-lists/${listType}`, {- method: 'POST',- body: { ip, comment }- });- }-- async removeFromIPList(ip, listType) {- return this.request(`/security/ip-lists/${listType}/${encodeURIComponent(ip)}`, {- method: 'DELETE'- });- }-- // ========================================- // Security Audit endpoints- // ========================================- async generateSecurityAudit() {- return this.request('/security/audit');- }-- // ========================================- // Lynis (Vulnerability Scanning) endpoints- // ========================================- async getLynisStatus() {- return this.request('/security/lynis/status');- }-- async installLynis() {- return this.request('/security/lynis/install', { method: 'POST' });- }-- async runLynisScan() {- return this.request('/security/lynis/scan', { method: 'POST' });- }-- async getLynisScanStatus() {- return this.request('/security/lynis/scan/status');- }-- // ========================================- // Auto Updates endpoints- // ========================================- async getAutoUpdatesStatus() {- return this.request('/security/auto-updates/status');- }-- async installAutoUpdates() {- return this.request('/security/auto-updates/install', { method: 'POST' });- }-- async enableAutoUpdates() {- return this.request('/security/auto-updates/enable', { method: 'POST' });- }-- async disableAutoUpdates() {- return this.request('/security/auto-updates/disable', { method: 'POST' });- }-- // ========================================- // Workflow endpoints- // ========================================- async getWorkflows() {- return this.request('/workflows');- }-- async getWorkflow(id) {- return this.request(`/workflows/${id}`);- }-- async createWorkflow(data) {- return this.request('/workflows', {- method: 'POST',- body: data- });- }-- async updateWorkflow(id, data) {- return this.request(`/workflows/${id}`, {- method: 'PUT',- body: data- });- }-- async deleteWorkflow(id) {- return this.request(`/workflows/${id}`, {- method: 'DELETE'- });- }-- async deployWorkflow(id) {- return this.request(`/workflows/${id}/deploy`, {- method: 'POST'- });- }-- async executeWorkflow(id, context = {}) {- return this.request(`/workflows/${id}/execute`, {- method: 'POST',- body: { context }- });- }-- async getWorkflowExecutions(id) {- return this.request(`/workflows/${id}/executions`);- }-- async getWorkflowExecutionDetails(executionId) {- return this.request(`/workflows/executions/${executionId}`);- }-- async getWorkflowExecutionLogs(executionId) {- return this.request(`/workflows/executions/${executionId}/logs`);- }-- async validateWorkflow(data) {- return this.request('/workflows/validate', {- method: 'POST',- body: JSON.stringify(data)- });- }-- // ========================================- // Servers (Multi-Server Management) endpoints- // ========================================- async getServers() {- return this.request('/servers');- }-- async getServer(id) {- return this.request(`/servers/${id}`);- }-- async createServer(data) {- return this.request('/servers', {- method: 'POST',- body: data- });- }-- async updateServer(id, data) {- return this.request(`/servers/${id}`, {- method: 'PUT',- body: data- });- }-- async deleteServer(id) {- return this.request(`/servers/${id}`, {- method: 'DELETE'- });- }-- async getServerStatus(id) {- return this.request(`/servers/${id}/status`);- }-- async getServerMetrics(id) {- return this.request(`/servers/${id}/metrics`);- }-- async pingServer(id) {- return this.request(`/servers/${id}/ping`, {- method: 'POST'- });- }-- // Server Registration- async generateRegistrationToken(serverId) {- return this.request(`/servers/${serverId}/regenerate-token`, {- method: 'POST'- });- }-- async registerServer(registrationData) {- return this.request('/servers/register', {- method: 'POST',- body: registrationData- });- }-- // Server Groups- async getServerGroups() {- return this.request('/servers/groups');- }-- async createServerGroup(data) {- return this.request('/servers/groups', {- method: 'POST',- body: data- });- }-- async updateServerGroup(id, data) {- return this.request(`/servers/groups/${id}`, {- method: 'PUT',- body: data- });- }-- async deleteServerGroup(id) {- return this.request(`/servers/groups/${id}`, {- method: 'DELETE'- });- }-- // Remote Docker Operations (via agent)- async getRemoteContainers(serverId, all = false) {- return this.request(`/servers/${serverId}/docker/containers?all=${all}`);- }-- async getRemoteContainer(serverId, containerId) {- return this.request(`/servers/${serverId}/docker/containers/${containerId}`);- }-- async startRemoteContainer(serverId, containerId) {- return this.request(`/servers/${serverId}/docker/containers/${containerId}/start`, {- method: 'POST'- });- }-- async stopRemoteContainer(serverId, containerId) {- return this.request(`/servers/${serverId}/docker/containers/${containerId}/stop`, {- method: 'POST'- });- }-- async restartRemoteContainer(serverId, containerId) {- return this.request(`/servers/${serverId}/docker/containers/${containerId}/restart`, {- method: 'POST'- });- }-- async removeRemoteContainer(serverId, containerId, force = false) {- return this.request(`/servers/${serverId}/docker/containers/${containerId}?force=${force}`, {- method: 'DELETE'- });- }-- async getRemoteContainerStats(serverId, containerId) {- return this.request(`/servers/${serverId}/docker/containers/${containerId}/stats`);- }-- async getRemoteContainerLogs(serverId, containerId, tail = 100, since = null) {- const params = new URLSearchParams({ tail });- if (since) params.append('since', since);- return this.request(`/servers/${serverId}/docker/containers/${containerId}/logs?${params}`);- }-- async getRemoteImages(serverId) {- return this.request(`/servers/${serverId}/docker/images`);- }-- async pullRemoteImage(serverId, image) {- return this.request(`/servers/${serverId}/docker/images/pull`, {- method: 'POST',- body: { image }- });- }-- async removeRemoteImage(serverId, imageId, force = false) {- return this.request(`/servers/${serverId}/docker/images/${imageId}?force=${force}`, {- method: 'DELETE'- });- }-- async getRemoteVolumes(serverId) {- return this.request(`/servers/${serverId}/docker/volumes`);- }-- async getRemoteNetworks(serverId) {- return this.request(`/servers/${serverId}/docker/networks`);- }-- async getRemoteSystemMetrics(serverId) {- return this.request(`/servers/${serverId}/system/metrics`);- }-- async getRemoteSystemInfo(serverId) {- return this.request(`/servers/${serverId}/system/info`);- }-- // Get available servers for Docker operations- async getAvailableServers() {- return this.request('/servers/available');- }-- // Remote Docker Compose Operations- async getRemoteComposeProjects(serverId) {- return this.request(`/servers/${serverId}/docker/compose/projects`);- }-- async getRemoteComposePs(serverId, projectPath) {- return this.request(`/servers/${serverId}/docker/compose/ps`, {- method: 'POST',- body: { project_path: projectPath }- });- }-- async remoteComposeUp(serverId, projectPath, options = {}) {- return this.request(`/servers/${serverId}/docker/compose/up`, {- method: 'POST',- body: {- project_path: projectPath,- detach: options.detach !== false,- build: options.build || false- }- });- }-- async remoteComposeDown(serverId, projectPath, options = {}) {- return this.request(`/servers/${serverId}/docker/compose/down`, {- method: 'POST',- body: {- project_path: projectPath,- volumes: options.volumes || false,- remove_orphans: options.removeOrphans !== false- }- });- }-- async remoteComposeLogs(serverId, projectPath, service = null, tail = 100) {- return this.request(`/servers/${serverId}/docker/compose/logs`, {- method: 'POST',- body: {- project_path: projectPath,- service: service,- tail: tail- }- });- }-- async remoteComposeRestart(serverId, projectPath, service = null) {- return this.request(`/servers/${serverId}/docker/compose/restart`, {- method: 'POST',- body: {- project_path: projectPath,- service: service- }- });- }-- async remoteComposePull(serverId, projectPath, service = null) {- return this.request(`/servers/${serverId}/docker/compose/pull`, {- method: 'POST',- body: {- project_path: projectPath,- service: service- }- });- }-- // Server Historical Metrics- async getServerMetricsHistory(serverId, period = '24h') {- return this.request(`/servers/${serverId}/metrics/history?period=${period}`);- }-- async getServerMetricsAggregated(serverId, period = '24h', aggregation = 'hourly') {- return this.request(`/servers/${serverId}/metrics/aggregated?period=${period}&aggregation=${aggregation}`);- }-- async compareServerMetrics(serverIds, metric = 'cpu', period = '24h') {- const ids = Array.isArray(serverIds) ? serverIds.join(',') : serverIds;- return this.request(`/servers/metrics/compare?ids=${ids}&metric=${metric}&period=${period}`);- }-- async getMetricsRetentionStats() {- return this.request('/servers/metrics/retention');- }-- async triggerMetricsCleanup() {- return this.request('/servers/metrics/cleanup', { method: 'POST' });- }-- // Remote Terminal- async createTerminalSession(serverId, cols = 80, rows = 24) {- return this.request(`/servers/${serverId}/terminal`, {- method: 'POST',- body: { cols, rows }- });- }-- async sendTerminalInput(sessionId, data) {- return this.request(`/servers/terminal/${sessionId}/input`, {- method: 'POST',- body: { data }- });- }-- async resizeTerminal(sessionId, cols, rows) {- return this.request(`/servers/terminal/${sessionId}/resize`, {- method: 'POST',- body: { cols, rows }- });- }-- async closeTerminalSession(sessionId) {- return this.request(`/servers/terminal/${sessionId}`, {- method: 'DELETE'- });- }-- async listTerminalSessions() {- return this.request('/servers/terminal/sessions');- }-- // Security Features- async getAllowedIPs(serverId) {- return this.request(`/servers/${serverId}/allowed-ips`);- }-- async updateAllowedIPs(serverId, allowedIPs) {- return this.request(`/servers/${serverId}/allowed-ips`, {- method: 'PUT',- body: { allowed_ips: allowedIPs }- });- }-- async getConnectionInfo(serverId) {- return this.request(`/servers/${serverId}/connection-info`);- }-- async rotateAPIKey(serverId) {- return this.request(`/servers/${serverId}/rotate-api-key`, {- method: 'POST'- });- }-- async getServerSecurityAlerts(serverId, options = {}) {- const params = new URLSearchParams();- if (options.status) params.append('status', options.status);- if (options.severity) params.append('severity', options.severity);- if (options.limit) params.append('limit', options.limit);- const query = params.toString() ? `?${params.toString()}` : '';- return this.request(`/servers/${serverId}/security/alerts${query}`);- }-- async getAllSecurityAlerts(options = {}) {- const params = new URLSearchParams();- if (options.status) params.append('status', options.status);- if (options.severity) params.append('severity', options.severity);- if (options.type) params.append('type', options.type);- if (options.limit) params.append('limit', options.limit);- const query = params.toString() ? `?${params.toString()}` : '';- return this.request(`/servers/security/alerts${query}`);- }-- async getSecurityAlertCounts(serverId = null) {- const query = serverId ? `?server_id=${serverId}` : '';- return this.request(`/servers/security/alerts/counts${query}`);- }-- async acknowledgeAlert(alertId) {- return this.request(`/servers/security/alerts/${alertId}/acknowledge`, {- method: 'POST'- });- }-- async resolveAlert(alertId) {- return this.request(`/servers/security/alerts/${alertId}/resolve`, {- method: 'POST'- });- }-- // Agent Downloads- async getAgentVersion() {- return this.request('/servers/agent/version');- }-- async getAgentDownloadUrl(os, arch) {- // Returns the download URL, caller should redirect or fetch- const baseUrl = this.baseUrl.replace('/api/v1', '');- return `${baseUrl}/api/servers/agent/download/${os}/${arch}`;- }-- // ========================================- // Agent Fleet Management endpoints- // ========================================- async getFleetHealth() {- return this.request('/servers/fleet/health');- }-- async getAgentVersions() {- return this.request('/servers/fleet/versions');- }-- async addAgentVersion(data) {- return this.request('/servers/fleet/versions', {- method: 'POST',- body: data- });- }-- async upgradeFleet(serverIds, versionId) {- return this.request('/servers/fleet/upgrade', {- method: 'POST',- body: { server_ids: serverIds, version_id: versionId }- });- }-- async startRollout(data) {- return this.request('/servers/fleet/rollout', {- method: 'POST',- body: data- });- }-- async getRollouts(status) {- const query = status ? `?status=${status}` : '';- return this.request(`/servers/fleet/rollouts${query}`);- }-- async getRollout(rolloutId) {- return this.request(`/servers/fleet/rollouts/${rolloutId}`);- }-- async cancelRollout(rolloutId) {- return this.request(`/servers/fleet/rollouts/${rolloutId}/cancel`, {- method: 'POST'- });- }-- async startDiscovery(duration = 10) {- return this.request(`/servers/fleet/discovery?duration=${duration}`, {- method: 'POST'- });- }-- async getDiscoveredAgents() {- return this.request('/servers/fleet/discovery');- }-- async approveRegistration(serverId) {- return this.request(`/servers/fleet/approve/${serverId}`, {- method: 'POST'- });- }-- async rejectRegistration(serverId) {- return this.request(`/servers/fleet/reject/${serverId}`, {- method: 'POST'- });- }-- async getQueuedCommands(serverId) {- const query = serverId ? `?server_id=${serverId}` : '';- return this.request(`/servers/fleet/commands/queued${query}`);- }-- async retryCommand(commandId) {- return this.request(`/servers/fleet/commands/${commandId}/retry`, {- method: 'POST'- });- }-- async getServerDiagnostics(serverId) {- return this.request(`/servers/fleet/diagnostics/${serverId}`);- }-- // ========================================- // Fleet Monitor (Cross-Server Monitoring) endpoints- // ========================================- async getFleetHeatmap(groupId) {- const query = groupId ? `?group_id=${groupId}` : '';- return this.request(`/fleet-monitor/heatmap${query}`);- }-- async getFleetComparison(serverIds, metric, period) {- const ids = serverIds.join(',');- return this.request(`/fleet-monitor/comparison?ids=${ids}&metric=${metric}&period=${period}`);- }-- async getFleetAlerts(params = {}) {- const searchParams = new URLSearchParams();- if (params.status) searchParams.append('status', params.status);- if (params.severity) searchParams.append('severity', params.severity);- if (params.server_id) searchParams.append('server_id', params.server_id);- if (params.limit) searchParams.append('limit', params.limit);- const query = searchParams.toString();- return this.request(`/fleet-monitor/alerts${query ? '?' + query : ''}`);- }-- async acknowledgeFleetAlert(alertId) {- return this.request(`/fleet-monitor/alerts/${alertId}/acknowledge`, { method: 'POST' });- }-- async resolveFleetAlert(alertId) {- return this.request(`/fleet-monitor/alerts/${alertId}/resolve`, { method: 'POST' });- }-- async getFleetThresholds(serverId) {- const query = serverId ? `?server_id=${serverId}` : '';- return this.request(`/fleet-monitor/thresholds${query}`);- }-- async createFleetThreshold(data) {- return this.request('/fleet-monitor/thresholds', { method: 'POST', body: data });- }-- async deleteFleetThreshold(thresholdId) {- return this.request(`/fleet-monitor/thresholds/${thresholdId}`, { method: 'DELETE' });- }-- async getFleetAnomalies(serverId) {- const query = serverId ? `?server_id=${serverId}` : '';- return this.request(`/fleet-monitor/anomalies${query}`);- }-- async getCapacityForecast(serverId, metric = 'disk') {- return this.request(`/fleet-monitor/forecast/${serverId}?metric=${metric}`);- }-- async searchFleet(query, type = 'any') {- return this.request(`/fleet-monitor/search?q=${encodeURIComponent(query)}&type=${type}`);- }-- async exportFleetCsv(serverIds, metric, period) {- const ids = serverIds.join(',');- const url = `${this.baseUrl}/fleet-monitor/export/csv?ids=${ids}&metric=${metric}&period=${period}`;- const token = this.getToken();- const response = await fetch(url, {- headers: token ? { Authorization: `Bearer ${token}` } : {}- });- return response.blob();- }-- // ── Email Server ──- async getEmailStatus() { return this.request('/email/status'); }- async installEmailServer(data = {}) { return this.request('/email/install', { method: 'POST', body: JSON.stringify(data) }); }- async controlEmailService(component, action) { return this.request(`/email/service/${component}/${action}`, { method: 'POST' }); }- // Email Domains- async getEmailDomains() { return this.request('/email/domains'); }- async addEmailDomain(data) { return this.request('/email/domains', { method: 'POST', body: JSON.stringify(data) }); }- async getEmailDomain(domainId) { return this.request(`/email/domains/${domainId}`); }- async deleteEmailDomain(domainId) { return this.request(`/email/domains/${domainId}`, { method: 'DELETE' }); }- async verifyEmailDNS(domainId) { return this.request(`/email/domains/${domainId}/verify-dns`, { method: 'POST' }); }- async deployEmailDNS(domainId) { return this.request(`/email/domains/${domainId}/deploy-dns`, { method: 'POST' }); }- // Email Accounts- async getEmailAccounts(domainId) { return this.request(`/email/domains/${domainId}/accounts`); }- async createEmailAccount(domainId, data) { return this.request(`/email/domains/${domainId}/accounts`, { method: 'POST', body: JSON.stringify(data) }); }- async getEmailAccount(accountId) { return this.request(`/email/accounts/${accountId}`); }- async updateEmailAccount(accountId, data) { return this.request(`/email/accounts/${accountId}`, { method: 'PUT', body: JSON.stringify(data) }); }- async deleteEmailAccount(accountId) { return this.request(`/email/accounts/${accountId}`, { method: 'DELETE' }); }- async changeEmailPassword(accountId, password) { return this.request(`/email/accounts/${accountId}/password`, { method: 'POST', body: JSON.stringify({ password }) }); }- // Email Aliases- async getEmailAliases(domainId) { return this.request(`/email/domains/${domainId}/aliases`); }- async createEmailAlias(domainId, data) { return this.request(`/email/domains/${domainId}/aliases`, { method: 'POST', body: JSON.stringify(data) }); }- async deleteEmailAlias(aliasId) { return this.request(`/email/aliases/${aliasId}`, { method: 'DELETE' }); }- // Email Forwarding- async getEmailForwarding(accountId) { return this.request(`/email/accounts/${accountId}/forwarding`); }- async createEmailForwarding(accountId, data) { return this.request(`/email/accounts/${accountId}/forwarding`, { method: 'POST', body: JSON.stringify(data) }); }- async updateEmailForwarding(ruleId, data) { return this.request(`/email/forwarding/${ruleId}`, { method: 'PUT', body: JSON.stringify(data) }); }- async deleteEmailForwarding(ruleId) { return this.request(`/email/forwarding/${ruleId}`, { method: 'DELETE' }); }- // DNS Providers- async getEmailDNSProviders() { return this.request('/email/dns-providers'); }- async addEmailDNSProvider(data) { return this.request('/email/dns-providers', { method: 'POST', body: JSON.stringify(data) }); }- async deleteEmailDNSProvider(providerId) { return this.request(`/email/dns-providers/${providerId}`, { method: 'DELETE' }); }- async testEmailDNSProvider(providerId) { return this.request(`/email/dns-providers/${providerId}/test`, { method: 'POST' }); }- async getEmailDNSZones(providerId) { return this.request(`/email/dns-providers/${providerId}/zones`); }- // SpamAssassin- async getSpamConfig() { return this.request('/email/spam/config'); }- async updateSpamConfig(data) { return this.request('/email/spam/config', { method: 'PUT', body: JSON.stringify(data) }); }- async updateSpamRules() { return this.request('/email/spam/update-rules', { method: 'POST' }); }- // Roundcube Webmail- async getWebmailStatus() { return this.request('/email/webmail/status'); }- async installWebmail(data = {}) { return this.request('/email/webmail/install', { method: 'POST', body: JSON.stringify(data) }); }- async controlWebmail(action) { return this.request(`/email/webmail/service/${action}`, { method: 'POST' }); }- async configureWebmailProxy(domain) { return this.request('/email/webmail/configure-proxy', { method: 'POST', body: JSON.stringify({ domain }) }); }- // Mail Queue & Logs- async getMailQueue() { return this.request('/email/queue'); }- async flushMailQueue() { return this.request('/email/queue/flush', { method: 'POST' }); }- async deleteMailQueueItem(queueId) { return this.request(`/email/queue/${queueId}`, { method: 'DELETE' }); }- async getMailLogs(lines = 100) { return this.request(`/email/logs?lines=${lines}`); }-- // ==================== SSO / OAuth ====================-- async getSSOProviders() {- return this.request('/sso/providers');- }-- async startSSOAuth(provider, redirectUri) {- return this.request(`/sso/authorize/${provider}?redirect_uri=${encodeURIComponent(redirectUri)}`);- }-- async completeSSOAuth(provider, code, state, redirectUri) {- const data = await this.request(`/sso/callback/${provider}`, {- method: 'POST',- body: { code, state, redirect_uri: redirectUri },- });- if (data.access_token) {- this.setTokens(data.access_token, data.refresh_token);- }- return data;- }-- async getSSOIdentities() {- return this.request('/sso/identities');- }-- async linkSSOProvider(provider, code, state, redirectUri) {- return this.request(`/sso/link/${provider}`, {- method: 'POST',- body: { code, state, redirect_uri: redirectUri },- });- }-- async unlinkSSOProvider(provider) {- return this.request(`/sso/link/${provider}`, { method: 'DELETE' });- }-- // SSO Admin- async getSSOConfig() {- return this.request('/sso/admin/config');- }-- async updateSSOProviderConfig(provider, config) {- return this.request(`/sso/admin/config/${provider}`, {- method: 'PUT',- body: config,- });- }-- async testSSOProvider(provider) {- return this.request(`/sso/admin/test/${provider}`, { method: 'POST' });- }-- async updateSSOGeneralSettings(settings) {- return this.request('/sso/admin/general', {- method: 'PUT',- body: settings,- });- }-- // Database Migrations- async getMigrationStatus() {- return this.request('/migrations/status');- }-- async createMigrationBackup() {- return this.request('/migrations/backup', { method: 'POST' });- }-- async applyMigrations() {- return this.request('/migrations/apply', { method: 'POST' });- }-- async getMigrationHistory() {- return this.request('/migrations/history');- }-- // API Keys- async getApiKeys() {- return this.request('/api-keys/');- }-- async createApiKey(data) {- return this.request('/api-keys/', { method: 'POST', body: data });- }-- async getApiKey(id) {- return this.request(`/api-keys/${id}`);- }-- async updateApiKey(id, data) {- return this.request(`/api-keys/${id}`, { method: 'PUT', body: data });- }-- async revokeApiKey(id) {- return this.request(`/api-keys/${id}`, { method: 'DELETE' });- }-- async rotateApiKey(id) {- return this.request(`/api-keys/${id}/rotate`, { method: 'POST' });- }-- // Event Subscriptions (Webhooks)- async getEventSubscriptions() {- return this.request('/event-subscriptions/');- }-- async createEventSubscription(data) {- return this.request('/event-subscriptions/', { method: 'POST', body: data });- }-- async getAvailableEvents() {- return this.request('/event-subscriptions/events');- }-- async getEventSubscription(id) {- return this.request(`/event-subscriptions/${id}`);- }-- async updateEventSubscription(id, data) {- return this.request(`/event-subscriptions/${id}`, { method: 'PUT', body: data });- }-- async deleteEventSubscription(id) {- return this.request(`/event-subscriptions/${id}`, { method: 'DELETE' });- }-- async testEventSubscription(id) {- return this.request(`/event-subscriptions/${id}/test`, { method: 'POST' });- }-- async getEventDeliveries(id, page = 1) {- return this.request(`/event-subscriptions/${id}/deliveries?page=${page}`);- }-- async retryEventDelivery(subId, deliveryId) {- return this.request(`/event-subscriptions/${subId}/deliveries/${deliveryId}/retry`, { method: 'POST' });- }-- // API Analytics- async getApiAnalyticsOverview(period = '24h') {- return this.request(`/api-analytics/overview?period=${period}`);- }-- async getApiAnalyticsEndpoints(period = '24h', limit = 20) {- return this.request(`/api-analytics/endpoints?period=${period}&limit=${limit}`);- }-- async getApiAnalyticsErrors(period = '24h') {- return this.request(`/api-analytics/errors?period=${period}`);- }-- async getApiAnalyticsTimeseries(period = '24h', interval = 'hour') {- return this.request(`/api-analytics/timeseries?period=${period}&interval=${interval}`);- }-- async getApiKeyUsage(keyId, period = '24h') {- return this.request(`/api-analytics/keys/${keyId}/usage?period=${period}`);- }-- // ========================================- // Admin - Permissions endpoints- // ========================================- async getUserPermissions(userId) {- return this.request(`/admin/users/${userId}/permissions`);- }-- async updateUserPermissions(userId, permissions) {- return this.request(`/admin/users/${userId}/permissions`, {- method: 'PUT',- body: { permissions }- });- }-- async resetUserPermissions(userId) {- return this.request(`/admin/users/${userId}/permissions/reset`, {- method: 'POST'- });- }-- async getPermissionTemplates() {- return this.request('/admin/permissions/templates');- }-- // ========================================- // Admin - Invitations endpoints- // ========================================- async getInvitations(status) {- const query = status ? `?status=${status}` : '';- return this.request(`/admin/invitations/${query}`);- }-- async createInvitation(data) {- return this.request('/admin/invitations/', {- method: 'POST',- body: data- });- }-- async revokeInvitation(id) {- return this.request(`/admin/invitations/${id}`, {- method: 'DELETE'- });- }-- async resendInvitation(id) {- return this.request(`/admin/invitations/resend/${id}`, {- method: 'POST'- });- }-- async validateInvitation(token) {- return this.request(`/admin/invitations/validate/${token}`);- }-- // ========================================- // Admin - Activity endpoints- // ========================================- async getActivitySummary() {- return this.request('/admin/activity/summary');- }-- async getActivityFeed(params = {}) {- const searchParams = new URLSearchParams();- if (params.page) searchParams.append('page', params.page);- if (params.per_page) searchParams.append('per_page', params.per_page);- if (params.user_id) searchParams.append('user_id', params.user_id);- if (params.action) searchParams.append('action', params.action);- if (params.start_date) searchParams.append('start_date', params.start_date);- if (params.end_date) searchParams.append('end_date', params.end_date);- const query = searchParams.toString();- return this.request(`/admin/activity/feed${query ? '?' + query : ''}`);- }-}--export const api = new ApiService();-export default api;+// Use relative URL in production (served from Flask), absolute in development+const API_BASE_URL = import.meta.env.VITE_API_URL ||+ (import.meta.env.PROD ? '/api/v1' : 'http://localhost:5000/api/v1');++class ApiService {+ constructor() {+ this.baseUrl = API_BASE_URL;+ }++ getToken() {+ return localStorage.getItem('access_token');+ }++ setTokens(accessToken, refreshToken) {+ localStorage.setItem('access_token', accessToken);+ localStorage.setItem('refresh_token', refreshToken);+ }++ clearTokens() {+ localStorage.removeItem('access_token');+ localStorage.removeItem('refresh_token');+ }++ async request(endpoint, options = {}) {+ const url = `${this.baseUrl}${endpoint}`;+ const token = this.getToken();++ const config = {+ headers: {+ 'Content-Type': 'application/json',+ ...(token && { Authorization: `Bearer ${token}` }),+ ...options.headers,+ },+ ...options,+ };++ if (options.body && typeof options.body === 'object') {+ config.body = JSON.stringify(options.body);+ }++ try {+ const response = await fetch(url, config);++ if (response.status === 401) {+ const refreshed = await this.refreshToken();+ if (refreshed) {+ config.headers.Authorization = `Bearer ${this.getToken()}`;+ const retryResponse = await fetch(url, config);+ return this.handleResponse(retryResponse);+ }+ this.clearTokens();+ window.location.href = '/login';+ throw new Error('Session expired');+ }++ return this.handleResponse(response);+ } catch (error) {+ console.error('API Error:', error);+ throw error;+ }+ }++ async handleResponse(response) {+ const data = await response.json();+ if (!response.ok) {+ throw new Error(data.error || 'Request failed');+ }+ return data;+ }++ async refreshToken() {+ const refreshToken = localStorage.getItem('refresh_token');+ if (!refreshToken) return false;++ try {+ const response = await fetch(`${this.baseUrl}/auth/refresh`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${refreshToken}`,+ },+ });++ if (response.ok) {+ const data = await response.json();+ localStorage.setItem('access_token', data.access_token);+ return true;+ }+ return false;+ } catch {+ return false;+ }+ }++ // Auth endpoints+ async getSetupStatus() {+ return this.request('/auth/setup-status');+ }++ async login(email, password) {+ const data = await this.request('/auth/login', {+ method: 'POST',+ body: { email, password },+ });+ this.setTokens(data.access_token, data.refresh_token);+ return data;+ }++ async register(email, username, password, inviteToken) {+ const body = { email, username, password };+ if (inviteToken) body.invite_token = inviteToken;+ const data = await this.request('/auth/register', {+ method: 'POST',+ body,+ });+ this.setTokens(data.access_token, data.refresh_token);+ return data;+ }++ async completeOnboarding(useCases) {+ return this.request('/auth/complete-onboarding', {+ method: 'POST',+ body: { use_cases: useCases },+ });+ }++ async logout() {+ this.clearTokens();+ }++ async getCurrentUser() {+ return this.request('/auth/me');+ }++ async updateCurrentUser(data) {+ return this.request('/auth/me', {+ method: 'PUT',+ body: data+ });+ }++ // ========================================+ // Admin - User Management endpoints+ // ========================================+ async getUsers() {+ return this.request('/admin/users');+ }++ async getUser(userId) {+ return this.request(`/admin/users/${userId}`);+ }++ async createUser(userData) {+ return this.request('/admin/users', {+ method: 'POST',+ body: userData+ });+ }++ async updateUser(userId, userData) {+ return this.request(`/admin/users/${userId}`, {+ method: 'PUT',+ body: userData+ });+ }++ async deleteUser(userId) {+ return this.request(`/admin/users/${userId}`, {+ method: 'DELETE'+ });+ }++ // ========================================+ // Admin - Audit Log endpoints+ // ========================================+ async getAuditLogs(params = {}) {+ const searchParams = new URLSearchParams();+ if (params.page) searchParams.append('page', params.page);+ if (params.per_page) searchParams.append('per_page', params.per_page);+ if (params.action) searchParams.append('action', params.action);+ if (params.user_id) searchParams.append('user_id', params.user_id);+ if (params.target_type) searchParams.append('target_type', params.target_type);+ const query = searchParams.toString();+ return this.request(`/admin/audit-logs${query ? '?' + query : ''}`);+ }++ async getAuditLogActions() {+ return this.request('/admin/audit-logs/actions');+ }++ // ========================================+ // Admin - System Settings endpoints+ // ========================================+ async getSystemSettings() {+ const data = await this.request('/admin/settings');+ const result = {};+ if (data.settings && Array.isArray(data.settings)) {+ for (const setting of data.settings) {+ result[setting.key] = setting.value;+ }+ }+ return result;+ }++ async updateSystemSettings(settings) {+ return this.request('/admin/settings', {+ method: 'PUT',+ body: settings+ });+ }++ async getSystemSetting(key) {+ return this.request(`/admin/settings/${key}`);+ }++ async updateSystemSetting(key, value) {+ return this.request(`/admin/settings/${key}`, {+ method: 'PUT',+ body: { value }+ });+ }++ async getAdminStats() {+ return this.request('/admin/stats');+ }++ // Apps endpoints+ async getApps() {+ return this.request('/apps');+ }++ async getApp(id) {+ return this.request(`/apps/${id}`);+ }++ async createApp(appData) {+ return this.request('/apps', {+ method: 'POST',+ body: appData,+ });+ }++ async updateApp(id, appData) {+ return this.request(`/apps/${id}`, {+ method: 'PUT',+ body: appData,+ });+ }++ async deleteApp(id) {+ return this.request(`/apps/${id}`, {+ method: 'DELETE',+ });+ }++ async startApp(id) {+ return this.request(`/apps/${id}/start`, { method: 'POST' });+ }++ async stopApp(id) {+ return this.request(`/apps/${id}/stop`, { method: 'POST' });+ }++ async restartApp(id) {+ return this.request(`/apps/${id}/restart`, { method: 'POST' });+ }++ // App linking endpoints+ async linkApp(appId, targetAppId, asEnvironment, options = {}) {+ return this.request(`/apps/${appId}/link`, {+ method: 'POST',+ body: {+ target_app_id: targetAppId,+ as_environment: asEnvironment,+ propagate_credentials: options.propagateCredentials !== false,+ table_prefix: options.tablePrefix+ }+ });+ }++ async getLinkedApps(appId) {+ return this.request(`/apps/${appId}/linked`);+ }++ async unlinkApp(appId) {+ return this.request(`/apps/${appId}/link`, {+ method: 'DELETE'+ });+ }++ async updateAppEnvironment(appId, environmentType) {+ return this.request(`/apps/${appId}/environment`, {+ method: 'PUT',+ body: { environment_type: environmentType }+ });+ }++ // Domains endpoints+ async getDomains() {+ return this.request('/domains');+ }++ async getDomain(id) {+ return this.request(`/domains/${id}`);+ }++ async createDomain(domainData) {+ return this.request('/domains', {+ method: 'POST',+ body: domainData,+ });+ }++ async updateDomain(id, domainData) {+ return this.request(`/domains/${id}`, {+ method: 'PUT',+ body: domainData,+ });+ }++ async deleteDomain(id) {+ return this.request(`/domains/${id}`, {+ method: 'DELETE',+ });+ }++ async enableSsl(domainId, email) {+ return this.request(`/domains/${domainId}/ssl/enable`, {+ method: 'POST',+ body: { email }+ });+ }++ async disableSsl(domainId) {+ return this.request(`/domains/${domainId}/ssl/disable`, { method: 'POST' });+ }++ async renewDomainSsl(domainId) {+ return this.request(`/domains/${domainId}/ssl/renew`, { method: 'POST' });+ }++ async verifyDomain(domainId) {+ return this.request(`/domains/${domainId}/verify`);+ }++ async getDomainsNginxSites() {+ return this.request('/domains/nginx/sites');+ }++ async getDomainsSslStatus() {+ return this.request('/domains/ssl/status');+ }++ // System endpoints+ async getSystemMetrics() {+ return this.request('/system/metrics');+ }++ async getSystemInfo() {+ return this.request('/system/info');+ }++ async getServerTime() {+ return this.request('/system/time');+ }++ async getTimezones() {+ return this.request('/system/timezones');+ }++ async setTimezone(timezone) {+ return this.request('/system/timezone', {+ method: 'PUT',+ body: { timezone }+ });+ }++ async getVersion() {+ return this.request('/system/version');+ }++ async checkUpdate() {+ return this.request('/system/check-update');+ }++ async getProcesses() {+ return this.request('/system/processes');+ }++ async getServices() {+ return this.request('/system/services');+ }++ async healthCheck() {+ return this.request('/system/health');+ }++ // Process endpoints+ async getProcesses(limit = 50, sortBy = 'cpu') {+ return this.request(`/processes?limit=${limit}&sort=${sortBy}`);+ }++ async getProcess(pid) {+ return this.request(`/processes/${pid}`);+ }++ async killProcess(pid, force = false) {+ return this.request(`/processes/${pid}?force=${force}`, { method: 'DELETE' });+ }++ async getServicesStatus() {+ return this.request('/processes/services');+ }++ async controlService(serviceName, action) {+ return this.request(`/processes/services/${serviceName}`, {+ method: 'POST',+ body: { action }+ });+ }++ // Nginx endpoints+ async getNginxStatus() {+ return this.request('/nginx/status');+ }++ async testNginxConfig() {+ return this.request('/nginx/test', { method: 'POST' });+ }++ async reloadNginx() {+ return this.request('/nginx/reload', { method: 'POST' });+ }++ async getNginxSites() {+ return this.request('/nginx/sites');+ }++ async createNginxSite(siteData) {+ return this.request('/nginx/sites', {+ method: 'POST',+ body: siteData+ });+ }++ async enableNginxSite(name) {+ return this.request(`/nginx/sites/${name}/enable`, { method: 'POST' });+ }++ async disableNginxSite(name) {+ return this.request(`/nginx/sites/${name}/disable`, { method: 'POST' });+ }++ async deleteNginxSite(name) {+ return this.request(`/nginx/sites/${name}`, { method: 'DELETE' });+ }++ // SSL endpoints+ async getSSLStatus() {+ return this.request('/ssl/status');+ }++ async getCertificates() {+ return this.request('/ssl/certificates');+ }++ async obtainCertificate(data) {+ return this.request('/ssl/certificates', {+ method: 'POST',+ body: data+ });+ }++ async renewCertificate(domain) {+ return this.request(`/ssl/certificates/${domain}/renew`, { method: 'POST' });+ }++ async renewAllCertificates() {+ return this.request('/ssl/certificates/renew-all', { method: 'POST' });+ }++ async revokeCertificate(domain) {+ return this.request(`/ssl/certificates/${domain}`, { method: 'DELETE' });+ }++ async setupAutoRenewal() {+ return this.request('/ssl/auto-renewal', { method: 'POST' });+ }++ async installCertbot() {+ return this.request('/ssl/install-certbot', { method: 'POST' });+ }++ // Log endpoints+ async getLogFiles() {+ return this.request('/logs');+ }++ async readLog(filepath, lines = 100) {+ return this.request(`/logs/read?path=${encodeURIComponent(filepath)}&lines=${lines}`);+ }++ async searchLog(filepath, pattern, lines = 100) {+ return this.request(`/logs/search?path=${encodeURIComponent(filepath)}&pattern=${encodeURIComponent(pattern)}&lines=${lines}`);+ }++ async getAppLogs(appName, type = 'access', lines = 100) {+ return this.request(`/logs/app/${appName}?type=${type}&lines=${lines}`);+ }++ async getJournalLogs(unit, lines = 100) {+ const params = new URLSearchParams({ lines });+ if (unit) params.append('unit', unit);+ return this.request(`/logs/journal?${params}`);+ }++ async clearLog(filepath) {+ return this.request('/logs/clear', {+ method: 'POST',+ body: { path: filepath }+ });+ }++ // PHP endpoints+ async getPHPVersions() {+ return this.request('/php/versions');+ }++ async installPHPVersion(version) {+ return this.request(`/php/versions/${version}/install`, { method: 'POST' });+ }++ async setDefaultPHPVersion(version) {+ return this.request('/php/versions/default', {+ method: 'POST',+ body: { version }+ });+ }++ async getPHPExtensions(version) {+ return this.request(`/php/versions/${version}/extensions`);+ }++ async installPHPExtension(version, extension) {+ return this.request(`/php/versions/${version}/extensions`, {+ method: 'POST',+ body: { extension }+ });+ }++ async getPHPPools(version) {+ return this.request(`/php/versions/${version}/pools`);+ }++ async createPHPPool(version, poolData) {+ return this.request(`/php/versions/${version}/pools`, {+ method: 'POST',+ body: poolData+ });+ }++ async deletePHPPool(version, poolName) {+ return this.request(`/php/versions/${version}/pools/${poolName}`, { method: 'DELETE' });+ }++ async restartPHPFPM(version) {+ return this.request(`/php/versions/${version}/fpm/restart`, { method: 'POST' });+ }++ async getPHPFPMStatus(version) {+ return this.request(`/php/versions/${version}/fpm/status`);+ }++ // WordPress: Use dedicated wordpress.js service instead++ // Python endpoints+ async getPythonVersions() {+ return this.request('/python/versions');+ }++ async createFlaskApp(data) {+ return this.request('/python/apps/flask', {+ method: 'POST',+ body: data+ });+ }++ async createDjangoApp(data) {+ return this.request('/python/apps/django', {+ method: 'POST',+ body: data+ });+ }++ async createPythonVenv(appId) {+ return this.request(`/python/apps/${appId}/venv`, { method: 'POST' });+ }++ async getPythonPackages(appId) {+ return this.request(`/python/apps/${appId}/packages`);+ }++ async installPythonPackages(appId, packages) {+ return this.request(`/python/apps/${appId}/packages`, {+ method: 'POST',+ body: { packages }+ });+ }++ async freezePythonRequirements(appId) {+ return this.request(`/python/apps/${appId}/requirements`, { method: 'POST' });+ }++ async getPythonEnvVars(appId) {+ return this.request(`/python/apps/${appId}/env`);+ }++ async setPythonEnvVars(appId, envVars) {+ return this.request(`/python/apps/${appId}/env`, {+ method: 'PUT',+ body: { env_vars: envVars }+ });+ }++ async deletePythonEnvVar(appId, key) {+ return this.request(`/python/apps/${appId}/env/${key}`, { method: 'DELETE' });+ }++ async startPythonApp(appId) {+ return this.request(`/python/apps/${appId}/start`, { method: 'POST' });+ }++ async stopPythonApp(appId) {+ return this.request(`/python/apps/${appId}/stop`, { method: 'POST' });+ }++ async restartPythonApp(appId) {+ return this.request(`/python/apps/${appId}/restart`, { method: 'POST' });+ }++ async getPythonAppStatus(appId) {+ return this.request(`/python/apps/${appId}/status`);+ }++ async getGunicornConfig(appId) {+ return this.request(`/python/apps/${appId}/gunicorn`);+ }++ async updateGunicornConfig(appId, content) {+ return this.request(`/python/apps/${appId}/gunicorn`, {+ method: 'PUT',+ body: { content }+ });+ }++ async runPythonMigrations(appId) {+ return this.request(`/python/apps/${appId}/migrate`, { method: 'POST' });+ }++ async collectPythonStatic(appId) {+ return this.request(`/python/apps/${appId}/collectstatic`, { method: 'POST' });+ }++ async runPythonCommand(appId, command) {+ return this.request(`/python/apps/${appId}/run`, {+ method: 'POST',+ body: { command }+ });+ }++ async deletePythonApp(appId, removeFiles = false) {+ return this.request(`/python/apps/${appId}`, {+ method: 'DELETE',+ body: { remove_files: removeFiles }+ });+ }++ // Docker endpoints+ async getDockerStatus() {+ return this.request('/docker/status');+ }++ async getDockerInfo() {+ return this.request('/docker/info');+ }++ async getDockerDiskUsage() {+ return this.request('/docker/disk-usage');+ }++ // Containers+ async getContainers(all = true) {+ return this.request(`/docker/containers?all=${all}`);+ }++ async getContainer(containerId) {+ return this.request(`/docker/containers/${containerId}`);+ }++ async createContainer(data) {+ return this.request('/docker/containers', {+ method: 'POST',+ body: data+ });+ }++ async runContainer(data) {+ return this.request('/docker/containers/run', {+ method: 'POST',+ body: data+ });+ }++ async startContainer(containerId) {+ return this.request(`/docker/containers/${containerId}/start`, { method: 'POST' });+ }++ async stopContainer(containerId, timeout = 10) {+ return this.request(`/docker/containers/${containerId}/stop`, {+ method: 'POST',+ body: { timeout }+ });+ }++ async restartContainer(containerId, timeout = 10) {+ return this.request(`/docker/containers/${containerId}/restart`, {+ method: 'POST',+ body: { timeout }+ });+ }++ async removeContainer(containerId, force = false, volumes = false) {+ return this.request(`/docker/containers/${containerId}`, {+ method: 'DELETE',+ body: { force, volumes }+ });+ }++ async getContainerLogs(containerId, tail = 100, since = null) {+ const params = new URLSearchParams({ tail });+ if (since) params.append('since', since);+ return this.request(`/docker/containers/${containerId}/logs?${params}`);+ }++ async getContainerStats(containerId) {+ return this.request(`/docker/containers/${containerId}/stats`);+ }++ async execContainer(containerId, command) {+ return this.request(`/docker/containers/${containerId}/exec`, {+ method: 'POST',+ body: { command }+ });+ }++ // Images+ async getImages() {+ return this.request('/docker/images');+ }++ async pullImage(image, tag = 'latest') {+ return this.request('/docker/images/pull', {+ method: 'POST',+ body: { image, tag }+ });+ }++ async removeImage(imageId, force = false) {+ return this.request(`/docker/images/${imageId}`, {+ method: 'DELETE',+ body: { force }+ });+ }++ async buildImage(path, tag, dockerfile = 'Dockerfile', noCache = false) {+ return this.request('/docker/images/build', {+ method: 'POST',+ body: { path, tag, dockerfile, no_cache: noCache }+ });+ }++ // Networks+ async getNetworks() {+ return this.request('/docker/networks');+ }++ async createNetwork(name, driver = 'bridge') {+ return this.request('/docker/networks', {+ method: 'POST',+ body: { name, driver }+ });+ }++ async removeNetwork(networkId) {+ return this.request(`/docker/networks/${networkId}`, { method: 'DELETE' });+ }++ // Volumes+ async getVolumes() {+ return this.request('/docker/volumes');+ }++ async createVolume(name, driver = 'local') {+ return this.request('/docker/volumes', {+ method: 'POST',+ body: { name, driver }+ });+ }++ async removeVolume(volumeName, force = false) {+ return this.request(`/docker/volumes/${volumeName}`, {+ method: 'DELETE',+ body: { force }+ });+ }++ // Docker Compose+ async composeUp(path, detach = true, build = false) {+ return this.request('/docker/compose/up', {+ method: 'POST',+ body: { path, detach, build }+ });+ }++ async composeDown(path, volumes = false, removeOrphans = true) {+ return this.request('/docker/compose/down', {+ method: 'POST',+ body: { path, volumes, remove_orphans: removeOrphans }+ });+ }++ async composePs(path) {+ return this.request('/docker/compose/ps', {+ method: 'POST',+ body: { path }+ });+ }++ async composeLogs(path, service = null, tail = 100) {+ return this.request('/docker/compose/logs', {+ method: 'POST',+ body: { path, service, tail }+ });+ }++ async composeRestart(path, service = null) {+ return this.request('/docker/compose/restart', {+ method: 'POST',+ body: { path, service }+ });+ }++ async composePull(path, service = null) {+ return this.request('/docker/compose/pull', {+ method: 'POST',+ body: { path, service }+ });+ }++ // Docker App+ async createDockerApp(data) {+ return this.request('/docker/apps', {+ method: 'POST',+ body: data+ });+ }++ async pruneDocker(all = false, volumes = false) {+ return this.request('/docker/prune', {+ method: 'POST',+ body: { all, volumes }+ });+ }++ async dockerCleanup(includeVolumes = false) {+ return this.request('/docker/cleanup', {+ method: 'POST',+ body: { volumes: includeVolumes }+ });+ }++ async cleanupAllApps() {+ return this.request('/docker/cleanup/apps', {+ method: 'POST'+ });+ }++ // Database endpoints+ async getDatabaseStatus() {+ return this.request('/databases/status');+ }++ // MySQL+ async getMySQLDatabases(rootPassword = null) {+ const params = rootPassword ? `?root_password=${encodeURIComponent(rootPassword)}` : '';+ return this.request(`/databases/mysql${params}`);+ }++ async createMySQLDatabase(data) {+ return this.request('/databases/mysql', {+ method: 'POST',+ body: data+ });+ }++ async dropMySQLDatabase(name, rootPassword = null) {+ return this.request(`/databases/mysql/${name}`, {+ method: 'DELETE',+ body: { root_password: rootPassword }+ });+ }++ async getMySQLTables(database, rootPassword = null) {+ const params = rootPassword ? `?root_password=${encodeURIComponent(rootPassword)}` : '';+ return this.request(`/databases/mysql/${database}/tables${params}`);+ }++ async backupMySQLDatabase(database, rootPassword = null) {+ return this.request(`/databases/mysql/${database}/backup`, {+ method: 'POST',+ body: { root_password: rootPassword }+ });+ }++ async restoreMySQLDatabase(database, backupPath, rootPassword = null) {+ return this.request(`/databases/mysql/${database}/restore`, {+ method: 'POST',+ body: { backup_path: backupPath, root_password: rootPassword }+ });+ }++ async getMySQLUsers(rootPassword = null) {+ const params = rootPassword ? `?root_password=${encodeURIComponent(rootPassword)}` : '';+ return this.request(`/databases/mysql/users${params}`);+ }++ async createMySQLUser(data) {+ return this.request('/databases/mysql/users', {+ method: 'POST',+ body: data+ });+ }++ async dropMySQLUser(username, host = 'localhost', rootPassword = null) {+ return this.request(`/databases/mysql/users/${username}`, {+ method: 'DELETE',+ body: { host, root_password: rootPassword }+ });+ }++ async grantMySQLPrivileges(username, database, privileges = 'ALL', host = 'localhost', rootPassword = null) {+ return this.request(`/databases/mysql/users/${username}/grant`, {+ method: 'POST',+ body: { database, privileges, host, root_password: rootPassword }+ });+ }++ // PostgreSQL+ async getPostgreSQLDatabases() {+ return this.request('/databases/postgresql');+ }++ async createPostgreSQLDatabase(data) {+ return this.request('/databases/postgresql', {+ method: 'POST',+ body: data+ });+ }++ async dropPostgreSQLDatabase(name) {+ return this.request(`/databases/postgresql/${name}`, { method: 'DELETE' });+ }++ async getPostgreSQLTables(database) {+ return this.request(`/databases/postgresql/${database}/tables`);+ }++ async backupPostgreSQLDatabase(database) {+ return this.request(`/databases/postgresql/${database}/backup`, { method: 'POST' });+ }++ async restorePostgreSQLDatabase(database, backupPath) {+ return this.request(`/databases/postgresql/${database}/restore`, {+ method: 'POST',+ body: { backup_path: backupPath }+ });+ }++ async getPostgreSQLUsers() {+ return this.request('/databases/postgresql/users');+ }++ async createPostgreSQLUser(data) {+ return this.request('/databases/postgresql/users', {+ method: 'POST',+ body: data+ });+ }++ async dropPostgreSQLUser(username) {+ return this.request(`/databases/postgresql/users/${username}`, { method: 'DELETE' });+ }++ async grantPostgreSQLPrivileges(username, database, privileges = 'ALL') {+ return this.request(`/databases/postgresql/users/${username}/grant`, {+ method: 'POST',+ body: { database, privileges }+ });+ }++ // Backups+ async getDatabaseBackups(type = null) {+ const params = type ? `?type=${type}` : '';+ return this.request(`/databases/backups${params}`);+ }++ async deleteDatabaseBackup(filename) {+ return this.request(`/databases/backups/${filename}`, { method: 'DELETE' });+ }++ async generateDatabasePassword(length = 16) {+ return this.request(`/databases/generate-password?length=${length}`);+ }++ // Query Execution+ async executeMySQLQuery(database, query, readonly = true) {+ return this.request(`/databases/mysql/${database}/query`, {+ method: 'POST',+ body: { query, readonly }+ });+ }++ async executePostgreSQLQuery(database, query, readonly = true) {+ return this.request(`/databases/postgresql/${database}/query`, {+ method: 'POST',+ body: { query, readonly }+ });+ }++ async executeSQLiteQuery(path, query, readonly = true) {+ return this.request('/databases/sqlite/query', {+ method: 'POST',+ body: { path, query, readonly }+ });+ }++ async getMySQLTableStructure(database, table) {+ return this.request(`/databases/mysql/${database}/tables/${table}/structure`);+ }++ async getPostgreSQLTableStructure(database, table) {+ return this.request(`/databases/postgresql/${database}/tables/${table}/structure`);+ }++ async getSQLiteTableStructure(path, table) {+ return this.request(`/databases/sqlite/tables/${table}/structure?path=${encodeURIComponent(path)}`);+ }++ async getSQLiteDatabases() {+ return this.request('/databases/sqlite');+ }++ async getSQLiteTables(path) {+ return this.request(`/databases/sqlite/tables?path=${encodeURIComponent(path)}`);+ }++ // Docker Container Databases+ async getDockerDatabases() {+ return this.request('/databases/docker');+ }++ async getAppDatabases(appId) {+ return this.request(`/databases/docker/app/${appId}`);+ }++ async getDockerContainerDatabases(container, password = null) {+ const headers = password ? { 'X-DB-Password': password } : {};+ return this.request(`/databases/docker/${container}/databases`, { headers });+ }++ async getDockerDatabaseTables(container, database, password = null) {+ const headers = password ? { 'X-DB-Password': password } : {};+ return this.request(`/databases/docker/${container}/${database}/tables`, { headers });+ }++ async executeDockerQuery(container, database, query, password = null, readonly = true) {+ const headers = password ? { 'X-DB-Password': password } : {};+ return this.request(`/databases/docker/${container}/${database}/query`, {+ method: 'POST',+ body: { query, readonly, password },+ headers+ });+ }++ // Docker App Logs and Status+ async getDockerAppLogs(appId, lines = 100) {+ return this.request(`/apps/${appId}/logs?lines=${lines}`);+ }++ async getDockerAppStatus(appId) {+ return this.request(`/apps/${appId}/status`);+ }++ // ========================================+ // Monitoring & Alerts endpoints+ // ========================================+ async getMonitoringStatus() {+ return this.request('/monitoring/status');+ }++ async getMonitoringMetrics() {+ return this.request('/monitoring/metrics');+ }++ async checkAlerts() {+ return this.request('/monitoring/alerts/check');+ }++ async getAlertHistory(limit = 100) {+ return this.request(`/monitoring/alerts/history?limit=${limit}`);+ }++ async getMonitoringConfig() {+ return this.request('/monitoring/config');+ }++ async updateMonitoringConfig(config) {+ return this.request('/monitoring/config', {+ method: 'PUT',+ body: config+ });+ }++ async getMonitoringThresholds() {+ return this.request('/monitoring/thresholds');+ }++ async updateMonitoringThresholds(thresholds) {+ return this.request('/monitoring/thresholds', {+ method: 'PUT',+ body: thresholds+ });+ }++ async startMonitoring() {+ return this.request('/monitoring/start', { method: 'POST' });+ }++ async stopMonitoring() {+ return this.request('/monitoring/stop', { method: 'POST' });+ }++ async testEmailAlert(email) {+ return this.request('/monitoring/test/email', {+ method: 'POST',+ body: { email }+ });+ }++ async testWebhookAlert(webhookUrl) {+ return this.request('/monitoring/test/webhook', {+ method: 'POST',+ body: { webhook_url: webhookUrl }+ });+ }++ // ========================================+ // Backup System endpoints+ // ========================================+ async getBackups(type = null) {+ const params = type ? `?type=${type}` : '';+ return this.request(`/backups${params}`);+ }++ async getBackupStats() {+ return this.request('/backups/stats');+ }++ async getBackupConfig() {+ return this.request('/backups/config');+ }++ async updateBackupConfig(config) {+ return this.request('/backups/config', {+ method: 'PUT',+ body: config+ });+ }++ async backupApplication(applicationId, includeDb = false, dbConfig = null) {+ return this.request('/backups/application', {+ method: 'POST',+ body: {+ application_id: applicationId,+ include_db: includeDb,+ db_config: dbConfig+ }+ });+ }++ async backupDatabase(dbType, dbName, user = null, password = null, host = 'localhost') {+ return this.request('/backups/database', {+ method: 'POST',+ body: { db_type: dbType, db_name: dbName, user, password, host }+ });+ }++ async restoreApplication(backupPath, restorePath = null) {+ return this.request('/backups/restore/application', {+ method: 'POST',+ body: { backup_path: backupPath, restore_path: restorePath }+ });+ }++ async restoreDatabase(backupPath, dbType, dbName, user = null, password = null, host = 'localhost') {+ return this.request('/backups/restore/database', {+ method: 'POST',+ body: { backup_path: backupPath, db_type: dbType, db_name: dbName, user, password, host }+ });+ }++ async deleteBackup(backupPath) {+ return this.request(`/backups/${encodeURIComponent(backupPath)}`, { method: 'DELETE' });+ }++ async cleanupBackups(retentionDays = null) {+ return this.request('/backups/cleanup', {+ method: 'POST',+ body: retentionDays ? { retention_days: retentionDays } : {}+ });+ }++ async getBackupSchedules() {+ return this.request('/backups/schedules');+ }++ async addBackupSchedule(name, backupType, target, scheduleTime, days = null, uploadRemote = false) {+ return this.request('/backups/schedules', {+ method: 'POST',+ body: { name, backup_type: backupType, target, schedule_time: scheduleTime, days, upload_remote: uploadRemote }+ });+ }++ async updateBackupSchedule(scheduleId, updates) {+ return this.request(`/backups/schedules/${scheduleId}`, {+ method: 'PUT',+ body: updates+ });+ }++ async removeBackupSchedule(scheduleId) {+ return this.request(`/backups/schedules/${scheduleId}`, { method: 'DELETE' });+ }++ async backupFiles(filePaths, name = null) {+ return this.request('/backups/files', {+ method: 'POST',+ body: { paths: filePaths, name }+ });+ }++ // Remote Storage+ async getStorageConfig() {+ return this.request('/backups/storage');+ }++ async updateStorageConfig(config) {+ return this.request('/backups/storage', {+ method: 'PUT',+ body: config+ });+ }++ async testStorageConnection(config = null) {+ return this.request('/backups/storage/test', {+ method: 'POST',+ body: config || {}+ });+ }++ async uploadBackupToRemote(backupPath) {+ return this.request('/backups/upload', {+ method: 'POST',+ body: { backup_path: backupPath }+ });+ }++ async verifyRemoteBackup(remoteKey, localPath) {+ return this.request('/backups/verify', {+ method: 'POST',+ body: { remote_key: remoteKey, local_path: localPath }+ });+ }++ async listRemoteBackups(prefix = null) {+ const params = prefix ? `?prefix=${encodeURIComponent(prefix)}` : '';+ return this.request(`/backups/remote${params}`);+ }++ async downloadRemoteBackup(remoteKey, localPath = null) {+ return this.request('/backups/remote/download', {+ method: 'POST',+ body: { remote_key: remoteKey, local_path: localPath }+ });+ }++ // ========================================+ // Git Deployment endpoints+ // ========================================+ async getDeployConfig(appId) {+ return this.request(`/deploy/apps/${appId}/config`);+ }++ async configureDeployment(appId, repoUrl, branch = 'main', autoDeploy = true, preDeployScript = null, postDeployScript = null) {+ return this.request(`/deploy/apps/${appId}/config`, {+ method: 'POST',+ body: {+ repo_url: repoUrl,+ branch,+ auto_deploy: autoDeploy,+ pre_deploy_script: preDeployScript,+ post_deploy_script: postDeployScript+ }+ });+ }++ async removeDeployment(appId) {+ return this.request(`/deploy/apps/${appId}/config`, { method: 'DELETE' });+ }++ async triggerDeploy(appId, force = false) {+ return this.request(`/deploy/apps/${appId}/deploy`, {+ method: 'POST',+ body: { force }+ });+ }++ async pullChanges(appId, branch = null) {+ return this.request(`/deploy/apps/${appId}/pull`, {+ method: 'POST',+ body: branch ? { branch } : {}+ });+ }++ async getGitStatus(appId) {+ return this.request(`/deploy/apps/${appId}/git-status`);+ }++ async getCommitInfo(appId) {+ return this.request(`/deploy/apps/${appId}/commit`);+ }++ async getDeploymentHistory(appId = null, limit = 50) {+ const params = new URLSearchParams({ limit });+ if (appId) params.append('app_id', appId);+ return this.request(`/deploy/history?${params}`);+ }++ async cloneRepository(appPath, repoUrl, branch = 'main') {+ return this.request('/deploy/clone', {+ method: 'POST',+ body: { app_path: appPath, repo_url: repoUrl, branch }+ });+ }++ async getAppBranches(appId) {+ return this.request(`/deploy/apps/${appId}/branches`);+ }++ async getBranchesFromUrl(repoUrl) {+ return this.request('/deploy/branches', {+ method: 'POST',+ body: { repo_url: repoUrl }+ });+ }++ async getWebhookLogs(appId = null, limit = 50) {+ const params = new URLSearchParams({ limit });+ if (appId) params.append('app_id', appId);+ return this.request(`/deploy/webhook-logs?${params}`);+ }++ // ========================================+ // Build & Deployment endpoints+ // ========================================+ async getBuildConfig(appId) {+ return this.request(`/builds/apps/${appId}/build-config`);+ }++ async configureBuild(appId, config) {+ return this.request(`/builds/apps/${appId}/build-config`, {+ method: 'POST',+ body: config+ });+ }++ async removeBuildConfig(appId) {+ return this.request(`/builds/apps/${appId}/build-config`, { method: 'DELETE' });+ }++ async detectBuildMethod(appId) {+ return this.request(`/builds/apps/${appId}/detect`);+ }++ async getNixpacksPlan(appId) {+ return this.request(`/builds/apps/${appId}/nixpacks-plan`);+ }++ async triggerBuild(appId, noCache = false) {+ return this.request(`/builds/apps/${appId}/build`, {+ method: 'POST',+ body: { no_cache: noCache }+ });+ }++ async getBuildLogs(appId, limit = 20) {+ return this.request(`/builds/apps/${appId}/build-logs?limit=${limit}`);+ }++ async getBuildLogDetail(appId, timestamp) {+ return this.request(`/builds/apps/${appId}/build-logs/${timestamp}`);+ }++ async clearBuildCache(appId) {+ return this.request(`/builds/apps/${appId}/clear-cache`, { method: 'POST' });+ }++ async deployApp(appId, options = {}) {+ return this.request(`/builds/apps/${appId}/deploy`, {+ method: 'POST',+ body: options+ });+ }++ async getDeployments(appId, limit = 20, offset = 0) {+ return this.request(`/builds/apps/${appId}/deployments?limit=${limit}&offset=${offset}`);+ }++ async getDeploymentDetail(deploymentId, includeLogs = false) {+ return this.request(`/builds/deployments/${deploymentId}?include_logs=${includeLogs}`);+ }++ async getDeploymentDiff(deploymentId) {+ return this.request(`/builds/deployments/${deploymentId}/diff`);+ }++ async rollback(appId, targetVersion = null) {+ return this.request(`/builds/apps/${appId}/rollback`, {+ method: 'POST',+ body: targetVersion ? { version: targetVersion } : {}+ });+ }++ async getCurrentDeployment(appId) {+ return this.request(`/builds/apps/${appId}/current-deployment`);+ }++ // ========================================+ // Template endpoints+ // ========================================+ async listTemplates(category = null, search = null) {+ const params = new URLSearchParams();+ if (category) params.append('category', category);+ if (search) params.append('search', search);+ const query = params.toString();+ return this.request(`/templates/${query ? '?' + query : ''}`);+ }++ async getTemplateCategories() {+ return this.request('/templates/categories');+ }++ async getTemplate(templateId) {+ return this.request(`/templates/${templateId}`);+ }++ async installTemplate(templateId, appName, variables = {}) {+ return this.request(`/templates/${templateId}/install`, {+ method: 'POST',+ body: { app_name: appName, variables }+ });+ }++ async validateTemplateInstall(templateId, appName, variables = {}) {+ return this.request('/templates/validate-install', {+ method: 'POST',+ body: { template_id: templateId, app_name: appName, variables }+ });+ }++ async testDatabaseConnection(config) {+ return this.request('/templates/test-db-connection', {+ method: 'POST',+ body: config+ });+ }++ async checkAppUpdate(appId) {+ return this.request(`/templates/apps/${appId}/check-update`);+ }++ async updateAppFromTemplate(appId) {+ return this.request(`/templates/apps/${appId}/update`, { method: 'POST' });+ }++ async getAppTemplateInfo(appId) {+ return this.request(`/templates/apps/${appId}/template-info`);+ }++ async listTemplateRepos() {+ return this.request('/templates/repos');+ }++ async addTemplateRepo(name, url) {+ return this.request('/templates/repos', {+ method: 'POST',+ body: { name, url }+ });+ }++ async removeTemplateRepo(url) {+ return this.request('/templates/repos', {+ method: 'DELETE',+ body: { url }+ });+ }++ async syncTemplates() {+ return this.request('/templates/sync', { method: 'POST' });+ }++ // ========================================+ // File Manager endpoints+ // ========================================+ async browseFiles(path = '/home', showHidden = false) {+ const params = new URLSearchParams({ path, show_hidden: showHidden });+ return this.request(`/files/browse?${params}`);+ }++ async getFileInfo(path) {+ return this.request(`/files/info?path=${encodeURIComponent(path)}`);+ }++ async readFile(path) {+ return this.request(`/files/read?path=${encodeURIComponent(path)}`);+ }++ async writeFile(path, content, createBackup = true) {+ return this.request('/files/write', {+ method: 'POST',+ body: { path, content, create_backup: createBackup }+ });+ }++ async createFile(path, content = '') {+ return this.request('/files/create', {+ method: 'POST',+ body: { path, content }+ });+ }++ async createDirectory(path) {+ return this.request('/files/mkdir', {+ method: 'POST',+ body: { path }+ });+ }++ async deleteFile(path) {+ return this.request(`/files/delete?path=${encodeURIComponent(path)}`, {+ method: 'DELETE'+ });+ }++ async renameFile(path, newName) {+ return this.request('/files/rename', {+ method: 'POST',+ body: { path, new_name: newName }+ });+ }++ async copyFile(src, dest) {+ return this.request('/files/copy', {+ method: 'POST',+ body: { src, dest }+ });+ }++ async moveFile(src, dest) {+ return this.request('/files/move', {+ method: 'POST',+ body: { src, dest }+ });+ }++ async changeFilePermissions(path, mode) {+ return this.request('/files/chmod', {+ method: 'POST',+ body: { path, mode }+ });+ }++ async searchFiles(directory, pattern, maxResults = 100) {+ const params = new URLSearchParams({ directory, pattern, max_results: maxResults });+ return this.request(`/files/search?${params}`);+ }++ async getDiskUsage(path = '/') {+ return this.request(`/files/disk-usage?path=${encodeURIComponent(path)}`);+ }++ async getAllDiskMounts() {+ return this.request('/files/disk-mounts');+ }++ async analyzeDirectory(path = '/home', depth = 2, limit = 20) {+ const params = new URLSearchParams({ path, depth, limit });+ return this.request(`/files/analyze?${params}`);+ }++ async getFileTypeBreakdown(path = '/home', maxDepth = 3) {+ const params = new URLSearchParams({ path, max_depth: maxDepth });+ return this.request(`/files/type-breakdown?${params}`);+ }++ async downloadFile(path) {+ const token = this.getToken();+ const url = `${this.baseUrl}/files/download?path=${encodeURIComponent(path)}`;+ window.open(`${url}&token=${token}`, '_blank');+ }++ async uploadFile(destination, file, onProgress = null) {+ const token = this.getToken();+ const formData = new FormData();+ formData.append('file', file);+ formData.append('destination', destination);++ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open('POST', `${this.baseUrl}/files/upload`);+ xhr.setRequestHeader('Authorization', `Bearer ${token}`);++ if (onProgress) {+ xhr.upload.onprogress = (e) => {+ if (e.lengthComputable) {+ onProgress((e.loaded / e.total) * 100);+ }+ };+ }++ xhr.onload = () => {+ if (xhr.status >= 200 && xhr.status < 300) {+ resolve(JSON.parse(xhr.responseText));+ } else {+ reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));+ }+ };++ xhr.onerror = () => reject(new Error('Upload failed'));+ xhr.send(formData);+ });+ }++ // ========================================+ // FTP Server endpoints+ // ========================================+ async getFTPStatus() {+ return this.request('/ftp/status');+ }++ async controlFTPService(action, service = null) {+ return this.request(`/ftp/service/${action}`, {+ method: 'POST',+ body: service ? { service } : {}+ });+ }++ async getFTPConfig(service = null) {+ const params = service ? `?service=${service}` : '';+ return this.request(`/ftp/config${params}`);+ }++ async updateFTPConfig(config, service = null) {+ return this.request('/ftp/config', {+ method: 'POST',+ body: { config, service }+ });+ }++ async getFTPUsers() {+ return this.request('/ftp/users');+ }++ async createFTPUser(username, password = null, homeDir = null) {+ return this.request('/ftp/users', {+ method: 'POST',+ body: { username, password, home_dir: homeDir }+ });+ }++ async deleteFTPUser(username, deleteHome = false) {+ const params = deleteHome ? '?delete_home=true' : '';+ return this.request(`/ftp/users/${username}${params}`, {+ method: 'DELETE'+ });+ }++ async changeFTPPassword(username, password = null) {+ return this.request(`/ftp/users/${username}/password`, {+ method: 'POST',+ body: password ? { password } : {}+ });+ }++ async toggleFTPUser(username, enabled) {+ return this.request(`/ftp/users/${username}/toggle`, {+ method: 'POST',+ body: { enabled }+ });+ }++ async getFTPConnections() {+ return this.request('/ftp/connections');+ }++ async disconnectFTPSession(pid) {+ return this.request(`/ftp/connections/${pid}`, {+ method: 'DELETE'+ });+ }++ async getFTPLogs(lines = 100) {+ return this.request(`/ftp/logs?lines=${lines}`);+ }++ async installFTPServer(service = 'vsftpd') {+ return this.request('/ftp/install', {+ method: 'POST',+ body: { service }+ });+ }++ async testFTPConnection(host = 'localhost', port = 21, username = null, password = null) {+ return this.request('/ftp/test', {+ method: 'POST',+ body: { host, port, username, password }+ });+ }++ // ========================================+ // Firewall endpoints+ // ========================================+ async getFirewallStatus() {+ return this.request('/firewall/status');+ }++ async enableFirewall(firewall = null) {+ return this.request('/firewall/enable', {+ method: 'POST',+ body: firewall ? { firewall } : {}+ });+ }++ async disableFirewall(firewall = null) {+ return this.request('/firewall/disable', {+ method: 'POST',+ body: firewall ? { firewall } : {}+ });+ }++ async getFirewallRules(firewall = null) {+ const params = firewall ? `?firewall=${firewall}` : '';+ return this.request(`/firewall/rules${params}`);+ }++ async addFirewallRule(ruleData) {+ return this.request('/firewall/rules', {+ method: 'POST',+ body: ruleData+ });+ }++ async removeFirewallRule(ruleData) {+ return this.request('/firewall/rules', {+ method: 'DELETE',+ body: ruleData+ });+ }++ async blockIP(ip, permanent = true) {+ return this.request('/firewall/block-ip', {+ method: 'POST',+ body: { ip, permanent }+ });+ }++ async unblockIP(ip, permanent = true) {+ return this.request('/firewall/unblock-ip', {+ method: 'POST',+ body: { ip, permanent }+ });+ }++ async getBlockedIPs() {+ return this.request('/firewall/blocked-ips');+ }++ async allowPort(port, protocol = 'tcp', permanent = true) {+ return this.request('/firewall/allow-port', {+ method: 'POST',+ body: { port, protocol, permanent }+ });+ }++ async denyPort(port, protocol = 'tcp', permanent = true) {+ return this.request('/firewall/deny-port', {+ method: 'POST',+ body: { port, protocol, permanent }+ });+ }++ async getFirewallZones() {+ return this.request('/firewall/zones');+ }++ async setDefaultZone(zone) {+ return this.request('/firewall/zones/default', {+ method: 'POST',+ body: { zone }+ });+ }++ async installFirewall(firewall = 'ufw') {+ return this.request('/firewall/install', {+ method: 'POST',+ body: { firewall }+ });+ }++ // ========================================+ // Git Server endpoints+ // ========================================+ async getGitStatus() {+ return this.request('/git/status');+ }++ async getGitRequirements() {+ return this.request('/git/requirements');+ }++ async installGit(data) {+ return this.request('/git/install', {+ method: 'POST',+ body: data+ });+ }++ async uninstallGit(removeData = false) {+ return this.request('/git/uninstall', {+ method: 'POST',+ body: { removeData }+ });+ }++ async startGit() {+ return this.request('/git/start', { method: 'POST' });+ }++ async stopGit() {+ return this.request('/git/stop', { method: 'POST' });+ }++ async restartGit() {+ return this.request('/git/restart', { method: 'POST' });+ }++ // ========================================+ // WordPress Standalone endpoints+ // ========================================+ async getWordPressStatus() {+ return this.request('/wordpress/standalone/status');+ }++ async getWordPressRequirements() {+ return this.request('/wordpress/standalone/requirements');+ }++ async installWordPress(data) {+ return this.request('/wordpress/standalone/install', {+ method: 'POST',+ body: data+ });+ }++ async uninstallWordPress(removeData = false) {+ return this.request('/wordpress/standalone/uninstall', {+ method: 'POST',+ body: { removeData }+ });+ }++ async startWordPress() {+ return this.request('/wordpress/standalone/start', { method: 'POST' });+ }++ async stopWordPress() {+ return this.request('/wordpress/standalone/stop', { method: 'POST' });+ }++ async restartWordPress() {+ return this.request('/wordpress/standalone/restart', { method: 'POST' });+ }++ // Git Webhooks+ async getWebhooks() {+ return this.request('/git/webhooks');+ }++ async getWebhook(webhookId) {+ return this.request(`/git/webhooks/${webhookId}`);+ }++ async createWebhook(data) {+ return this.request('/git/webhooks', {+ method: 'POST',+ body: data+ });+ }++ async updateWebhook(webhookId, data) {+ return this.request(`/git/webhooks/${webhookId}`, {+ method: 'PUT',+ body: data+ });+ }++ async deleteWebhook(webhookId) {+ return this.request(`/git/webhooks/${webhookId}`, { method: 'DELETE' });+ }++ async toggleWebhook(webhookId) {+ return this.request(`/git/webhooks/${webhookId}/toggle`, { method: 'POST' });+ }++ async getWebhookLogs(webhookId, limit = 50) {+ return this.request(`/git/webhooks/${webhookId}/logs?limit=${limit}`);+ }++ async testWebhook(webhookId) {+ return this.request(`/git/webhooks/${webhookId}/test`, { method: 'POST' });+ }++ // Git Repositories+ async getRepositories(limit = 50) {+ return this.request(`/git/repos?limit=${limit}`);+ }++ async getRepository(owner, repo) {+ return this.request(`/git/repos/${owner}/${repo}`);+ }++ async getRepoStats(owner, repo) {+ return this.request(`/git/repos/${owner}/${repo}/stats`);+ }++ async getBranches(owner, repo) {+ return this.request(`/git/repos/${owner}/${repo}/branches`);+ }++ async getBranch(owner, repo, branch) {+ return this.request(`/git/repos/${owner}/${repo}/branches/${branch}`);+ }++ async getCommits(owner, repo, branch = null, page = 1, limit = 30) {+ let url = `/git/repos/${owner}/${repo}/commits?page=${page}&limit=${limit}`;+ if (branch) url += `&branch=${branch}`;+ return this.request(url);+ }++ async getCommit(owner, repo, sha) {+ return this.request(`/git/repos/${owner}/${repo}/commits/${sha}`);+ }++ async getRepoFiles(owner, repo, ref = 'main', path = '') {+ let url = `/git/repos/${owner}/${repo}/contents?ref=${ref}`;+ if (path) url += `&path=${path}`;+ return this.request(url);+ }++ async getFileContent(owner, repo, filepath, ref = 'main') {+ return this.request(`/git/repos/${owner}/${repo}/contents/${filepath}?ref=${ref}`);+ }++ async getRepoReadme(owner, repo, ref = null) {+ let url = `/git/repos/${owner}/${repo}/readme`;+ if (ref) url += `?ref=${ref}`;+ return this.request(url);+ }++ async getGiteaVersion() {+ return this.request('/git/version');+ }++ // Git Deployments+ async getAppDeployments(appId, limit = 20) {+ return this.request(`/git/deployments/app/${appId}?limit=${limit}`);+ }++ async getDeployment(deploymentId, includeLogs = false) {+ return this.request(`/git/deployments/${deploymentId}?logs=${includeLogs}`);+ }++ async triggerDeploy(appId, branch = null) {+ return this.request(`/git/deployments/app/${appId}/deploy`, {+ method: 'POST',+ body: branch ? { branch } : {}+ });+ }++ async rollbackDeployment(appId, targetVersion = null) {+ return this.request(`/git/deployments/app/${appId}/rollback`, {+ method: 'POST',+ body: targetVersion ? { targetVersion } : {}+ });+ }++ async getWebhookDeployments(webhookId, limit = 20) {+ return this.request(`/git/deployments/webhook/${webhookId}?limit=${limit}`);+ }++ // ========================================+ // Cron Job endpoints+ // ========================================+ async getCronStatus() {+ return this.request('/cron/status');+ }++ async getCronJobs() {+ return this.request('/cron/jobs');+ }++ async createCronJob(data) {+ return this.request('/cron/jobs', {+ method: 'POST',+ body: data+ });+ }++ async updateCronJob(jobId, data) {+ return this.request(`/cron/jobs/${jobId}`, {+ method: 'PUT',+ body: data+ });+ }++ async deleteCronJob(jobId) {+ return this.request(`/cron/jobs/${jobId}`, { method: 'DELETE' });+ }++ async toggleCronJob(jobId, enabled) {+ return this.request(`/cron/jobs/${jobId}/toggle`, {+ method: 'POST',+ body: { enabled }+ });+ }++ async runCronJob(jobId) {+ return this.request(`/cron/jobs/${jobId}/run`, { method: 'POST' });+ }++ async getCronPresets() {+ return this.request('/cron/presets');+ }++ // ========================================+ // Uptime Tracking endpoints+ // ========================================+ async getCurrentUptime() {+ return this.request('/uptime/current');+ }++ async getUptimeStats() {+ return this.request('/uptime/stats');+ }++ async getUptimeGraph(period = '24h') {+ return this.request(`/uptime/graph?period=${period}`);+ }++ async getUptimeHistory(hours = 24) {+ return this.request(`/uptime/history?hours=${hours}`);+ }++ async startUptimeTracking() {+ return this.request('/uptime/tracking/start', { method: 'POST' });+ }++ async stopUptimeTracking() {+ return this.request('/uptime/tracking/stop', { method: 'POST' });+ }++ async getUptimeTrackingStatus() {+ return this.request('/uptime/tracking/status');+ }++ // ========================================+ // Metrics History endpoints+ // ========================================+ async getMetricsHistory(period = '1h') {+ return this.request(`/metrics/history?period=${period}`);+ }++ async getMetricsStats() {+ return this.request('/metrics/stats');+ }++ async startMetricsCollection() {+ return this.request('/metrics/collection/start', { method: 'POST' });+ }++ async stopMetricsCollection() {+ return this.request('/metrics/collection/stop', { method: 'POST' });+ }++ async triggerMetricsAggregation() {+ return this.request('/metrics/aggregate', { method: 'POST' });+ }++ // ========================================+ // Private URL endpoints+ // ========================================+ async enablePrivateUrl(appId, slug = null) {+ return this.request(`/apps/${appId}/private-url`, {+ method: 'POST',+ body: slug ? { slug } : {}+ });+ }++ async getPrivateUrl(appId) {+ return this.request(`/apps/${appId}/private-url`);+ }++ async updatePrivateUrl(appId, slug) {+ return this.request(`/apps/${appId}/private-url`, {+ method: 'PUT',+ body: { slug }+ });+ }++ async disablePrivateUrl(appId) {+ return this.request(`/apps/${appId}/private-url`, {+ method: 'DELETE'+ });+ }++ async regeneratePrivateUrl(appId) {+ return this.request(`/apps/${appId}/private-url/regenerate`, {+ method: 'POST'+ });+ }++ // ========================================+ // Environment Variables endpoints+ // ========================================+ async getEnvVars(appId, maskSecrets = false) {+ const params = maskSecrets ? '?mask=true' : '';+ return this.request(`/apps/${appId}/env${params}`);+ }++ async getEnvVar(appId, key) {+ return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`);+ }++ async createEnvVar(appId, key, value, isSecret = false, description = null) {+ return this.request(`/apps/${appId}/env`, {+ method: 'POST',+ body: { key, value, is_secret: isSecret, description }+ });+ }++ async updateEnvVar(appId, key, data) {+ return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`, {+ method: 'PUT',+ body: data+ });+ }++ async deleteEnvVar(appId, key) {+ return this.request(`/apps/${appId}/env/${encodeURIComponent(key)}`, {+ method: 'DELETE'+ });+ }++ async bulkSetEnvVars(appId, envVars) {+ return this.request(`/apps/${appId}/env/bulk`, {+ method: 'POST',+ body: { env_vars: envVars }+ });+ }++ async importEnvFile(appId, content, overwrite = true) {+ return this.request(`/apps/${appId}/env/import`, {+ method: 'POST',+ body: { content, overwrite }+ });+ }++ async exportEnvFile(appId, includeSecrets = true) {+ const params = includeSecrets ? '' : '?include_secrets=false';+ return this.request(`/apps/${appId}/env/export${params}`);+ }++ async getEnvVarHistory(appId, limit = 50) {+ return this.request(`/apps/${appId}/env/history?limit=${limit}`);+ }++ async clearEnvVars(appId) {+ return this.request(`/apps/${appId}/env/clear`, {+ method: 'DELETE'+ });+ }++ // ========================================+ // Two-Factor Authentication endpoints+ // ========================================+ async get2FAStatus() {+ return this.request('/auth/2fa/status');+ }++ async initiate2FASetup() {+ return this.request('/auth/2fa/setup', { method: 'POST' });+ }++ async confirm2FASetup(code) {+ return this.request('/auth/2fa/setup/confirm', {+ method: 'POST',+ body: { code }+ });+ }++ async disable2FA(code) {+ return this.request('/auth/2fa/disable', {+ method: 'POST',+ body: { code }+ });+ }++ async regenerateBackupCodes(code) {+ return this.request('/auth/2fa/backup-codes/regenerate', {+ method: 'POST',+ body: { code }+ });+ }++ async verify2FA(tempToken, code) {+ return this.request('/auth/2fa/verify', {+ method: 'POST',+ body: { temp_token: tempToken, code }+ });+ }++ // ========================================+ // Notification Webhooks endpoints+ // ========================================+ async getNotificationsStatus() {+ return this.request('/notifications/status');+ }++ async getNotificationsConfig() {+ return this.request('/notifications/config');+ }++ async updateNotificationChannel(channel, settings) {+ return this.request(`/notifications/config/${channel}`, {+ method: 'PUT',+ body: settings+ });+ }++ async testNotificationChannel(channel) {+ return this.request(`/notifications/test/${channel}`, {+ method: 'POST'+ });+ }++ async testAllNotifications() {+ return this.request('/notifications/test', {+ method: 'POST'+ });+ }++ // User notification preferences+ async getUserNotificationPreferences() {+ return this.request('/notifications/preferences');+ }++ async updateUserNotificationPreferences(preferences) {+ return this.request('/notifications/preferences', {+ method: 'PUT',+ body: preferences+ });+ }++ async testUserNotification() {+ return this.request('/notifications/preferences/test', {+ method: 'POST'+ });+ }++ // ========================================+ // Security (ClamAV, File Integrity) endpoints+ // ========================================+ async getSecurityStatus() {+ return this.request('/security/status');+ }++ async getSecurityConfig() {+ return this.request('/security/config');+ }++ async updateSecurityConfig(config) {+ return this.request('/security/config', {+ method: 'PUT',+ body: config+ });+ }++ async getClamAVStatus() {+ return this.request('/security/clamav/status');+ }++ async installClamAV() {+ return this.request('/security/clamav/install', { method: 'POST' });+ }++ async updateVirusDefinitions() {+ return this.request('/security/clamav/update', { method: 'POST' });+ }++ async scanFile(path) {+ return this.request('/security/scan/file', {+ method: 'POST',+ body: { path }+ });+ }++ async scanDirectory(path, recursive = true) {+ return this.request('/security/scan/directory', {+ method: 'POST',+ body: { path, recursive }+ });+ }++ async getScanStatus() {+ return this.request('/security/scan/status');+ }++ async cancelScan() {+ return this.request('/security/scan/cancel', { method: 'POST' });+ }++ async getScanHistory(limit = 50) {+ return this.request(`/security/scan/history?limit=${limit}`);+ }++ async runQuickScan() {+ return this.request('/security/scan/quick', { method: 'POST' });+ }++ async runFullScan() {+ return this.request('/security/scan/full', { method: 'POST' });+ }++ async getQuarantinedFiles() {+ return this.request('/security/quarantine');+ }++ async quarantineFile(path) {+ return this.request('/security/quarantine', {+ method: 'POST',+ body: { path }+ });+ }++ async deleteQuarantinedFile(filename) {+ return this.request(`/security/quarantine/${encodeURIComponent(filename)}`, {+ method: 'DELETE'+ });+ }++ async initializeIntegrityDatabase(paths = null) {+ return this.request('/security/integrity/initialize', {+ method: 'POST',+ body: paths ? { paths } : {}+ });+ }++ async checkFileIntegrity() {+ return this.request('/security/integrity/check');+ }++ async getFailedLogins(hours = 24) {+ return this.request(`/security/failed-logins?hours=${hours}`);+ }++ async getSecurityEvents(limit = 100) {+ return this.request(`/security/events?limit=${limit}`);+ }++ // ========================================+ // Fail2ban endpoints+ // ========================================+ async getFail2banStatus() {+ return this.request('/security/fail2ban/status');+ }++ async installFail2ban() {+ return this.request('/security/fail2ban/install', { method: 'POST' });+ }++ async getFail2banJailStatus(jail) {+ return this.request(`/security/fail2ban/jails/${jail}`);+ }++ async getAllFail2banBans() {+ return this.request('/security/fail2ban/bans');+ }++ async fail2banUnban(ip, jail = null) {+ return this.request('/security/fail2ban/unban', {+ method: 'POST',+ body: { ip, jail }+ });+ }++ async fail2banBan(ip, jail = 'sshd') {+ return this.request('/security/fail2ban/ban', {+ method: 'POST',+ body: { ip, jail }+ });+ }++ // ========================================+ // SSH Key endpoints+ // ========================================+ async getSSHKeys(user = 'root') {+ return this.request(`/security/ssh-keys?user=${user}`);+ }++ async addSSHKey(key, user = 'root') {+ return this.request('/security/ssh-keys', {+ method: 'POST',+ body: { key, user }+ });+ }++ async removeSSHKey(keyId, user = 'root') {+ return this.request(`/security/ssh-keys/${keyId}?user=${user}`, {+ method: 'DELETE'+ });+ }++ // ========================================+ // IP Lists endpoints+ // ========================================+ async getIPLists() {+ return this.request('/security/ip-lists');+ }++ async addToIPList(ip, listType, comment = '') {+ return this.request(`/security/ip-lists/${listType}`, {+ method: 'POST',+ body: { ip, comment }+ });+ }++ async removeFromIPList(ip, listType) {+ return this.request(`/security/ip-lists/${listType}/${encodeURIComponent(ip)}`, {+ method: 'DELETE'+ });+ }++ // ========================================+ // Security Audit endpoints+ // ========================================+ async generateSecurityAudit() {+ return this.request('/security/audit');+ }++ // ========================================+ // Lynis (Vulnerability Scanning) endpoints+ // ========================================+ async getLynisStatus() {+ return this.request('/security/lynis/status');+ }++ async installLynis() {+ return this.request('/security/lynis/install', { method: 'POST' });+ }++ async runLynisScan() {+ return this.request('/security/lynis/scan', { method: 'POST' });+ }++ async getLynisScanStatus() {+ return this.request('/security/lynis/scan/status');+ }++ // ========================================+ // Auto Updates endpoints+ // ========================================+ async getAutoUpdatesStatus() {+ return this.request('/security/auto-updates/status');+ }++ async installAutoUpdates() {+ return this.request('/security/auto-updates/install', { method: 'POST' });+ }++ async enableAutoUpdates() {+ return this.request('/security/auto-updates/enable', { method: 'POST' });+ }++ async disableAutoUpdates() {+ return this.request('/security/auto-updates/disable', { method: 'POST' });+ }++ // ========================================+ // Workflow endpoints+ // ========================================+ async getWorkflows() {+ return this.request('/workflows');+ }++ async getWorkflow(id) {+ return this.request(`/workflows/${id}`);+ }++ async createWorkflow(data) {+ return this.request('/workflows', {+ method: 'POST',+ body: data+ });+ }++ async updateWorkflow(id, data) {+ return this.request(`/workflows/${id}`, {+ method: 'PUT',+ body: data+ });+ }++ async deleteWorkflow(id) {+ return this.request(`/workflows/${id}`, {+ method: 'DELETE'+ });+ }++ async deployWorkflow(id) {+ return this.request(`/workflows/${id}/deploy`, {+ method: 'POST'+ });+ }++ async executeWorkflow(id, context = {}) {+ return this.request(`/workflows/${id}/execute`, {+ method: 'POST',+ body: { context }+ });+ }++ async getWorkflowExecutions(id) {+ return this.request(`/workflows/${id}/executions`);+ }++ async getWorkflowExecutionDetails(executionId) {+ return this.request(`/workflows/executions/${executionId}`);+ }++ async getWorkflowExecutionLogs(executionId) {+ return this.request(`/workflows/executions/${executionId}/logs`);+ }++ async validateWorkflow(data) {+ return this.request('/workflows/validate', {+ method: 'POST',+ body: JSON.stringify(data)+ });+ }++ // ========================================+ // Servers (Multi-Server Management) endpoints+ // ========================================+ async getServers() {+ return this.request('/servers');+ }++ async getServer(id) {+ return this.request(`/servers/${id}`);+ }++ async createServer(data) {+ return this.request('/servers', {+ method: 'POST',+ body: data+ });+ }++ async updateServer(id, data) {+ return this.request(`/servers/${id}`, {+ method: 'PUT',+ body: data+ });+ }++ async deleteServer(id) {+ return this.request(`/servers/${id}`, {+ method: 'DELETE'+ });+ }++ async getServerStatus(id) {+ return this.request(`/servers/${id}/status`);+ }++ async getServerMetrics(id) {+ return this.request(`/servers/${id}/metrics`);+ }++ async pingServer(id) {+ return this.request(`/servers/${id}/ping`, {+ method: 'POST'+ });+ }++ // Server Registration+ async generateRegistrationToken(serverId) {+ return this.request(`/servers/${serverId}/regenerate-token`, {+ method: 'POST'+ });+ }++ async registerServer(registrationData) {+ return this.request('/servers/register', {+ method: 'POST',+ body: registrationData+ });+ }++ // Server Groups+ async getServerGroups() {+ return this.request('/servers/groups');+ }++ async createServerGroup(data) {+ return this.request('/servers/groups', {+ method: 'POST',+ body: data+ });+ }++ async updateServerGroup(id, data) {+ return this.request(`/servers/groups/${id}`, {+ method: 'PUT',+ body: data+ });+ }++ async deleteServerGroup(id) {+ return this.request(`/servers/groups/${id}`, {+ method: 'DELETE'+ });+ }++ // Remote Docker Operations (via agent)+ async getRemoteContainers(serverId, all = false) {+ return this.request(`/servers/${serverId}/docker/containers?all=${all}`);+ }++ async getRemoteContainer(serverId, containerId) {+ return this.request(`/servers/${serverId}/docker/containers/${containerId}`);+ }++ async startRemoteContainer(serverId, containerId) {+ return this.request(`/servers/${serverId}/docker/containers/${containerId}/start`, {+ method: 'POST'+ });+ }++ async stopRemoteContainer(serverId, containerId) {+ return this.request(`/servers/${serverId}/docker/containers/${containerId}/stop`, {+ method: 'POST'+ });+ }++ async restartRemoteContainer(serverId, containerId) {+ return this.request(`/servers/${serverId}/docker/containers/${containerId}/restart`, {+ method: 'POST'+ });+ }++ async removeRemoteContainer(serverId, containerId, force = false) {+ return this.request(`/servers/${serverId}/docker/containers/${containerId}?force=${force}`, {+ method: 'DELETE'+ });+ }++ async getRemoteContainerStats(serverId, containerId) {+ return this.request(`/servers/${serverId}/docker/containers/${containerId}/stats`);+ }++ async getRemoteContainerLogs(serverId, containerId, tail = 100, since = null) {+ const params = new URLSearchParams({ tail });+ if (since) params.append('since', since);+ return this.request(`/servers/${serverId}/docker/containers/${containerId}/logs?${params}`);+ }++ async getRemoteImages(serverId) {+ return this.request(`/servers/${serverId}/docker/images`);+ }++ async pullRemoteImage(serverId, image) {+ return this.request(`/servers/${serverId}/docker/images/pull`, {+ method: 'POST',+ body: { image }+ });+ }++ async removeRemoteImage(serverId, imageId, force = false) {+ return this.request(`/servers/${serverId}/docker/images/${imageId}?force=${force}`, {+ method: 'DELETE'+ });+ }++ async getRemoteVolumes(serverId) {+ return this.request(`/servers/${serverId}/docker/volumes`);+ }++ async getRemoteNetworks(serverId) {+ return this.request(`/servers/${serverId}/docker/networks`);+ }++ async getRemoteSystemMetrics(serverId) {+ return this.request(`/servers/${serverId}/system/metrics`);+ }++ async getRemoteSystemInfo(serverId) {+ return this.request(`/servers/${serverId}/system/info`);+ }++ // Get available servers for Docker operations+ async getAvailableServers() {+ return this.request('/servers/available');+ }++ // Remote Docker Compose Operations+ async getRemoteComposeProjects(serverId) {+ return this.request(`/servers/${serverId}/docker/compose/projects`);+ }++ async getRemoteComposePs(serverId, projectPath) {+ return this.request(`/servers/${serverId}/docker/compose/ps`, {+ method: 'POST',+ body: { project_path: projectPath }+ });+ }++ async remoteComposeUp(serverId, projectPath, options = {}) {+ return this.request(`/servers/${serverId}/docker/compose/up`, {+ method: 'POST',+ body: {+ project_path: projectPath,+ detach: options.detach !== false,+ build: options.build || false+ }+ });+ }++ async remoteComposeDown(serverId, projectPath, options = {}) {+ return this.request(`/servers/${serverId}/docker/compose/down`, {+ method: 'POST',+ body: {+ project_path: projectPath,+ volumes: options.volumes || false,+ remove_orphans: options.removeOrphans !== false+ }+ });+ }++ async remoteComposeLogs(serverId, projectPath, service = null, tail = 100) {+ return this.request(`/servers/${serverId}/docker/compose/logs`, {+ method: 'POST',+ body: {+ project_path: projectPath,+ service: service,+ tail: tail+ }+ });+ }++ async remoteComposeRestart(serverId, projectPath, service = null) {+ return this.request(`/servers/${serverId}/docker/compose/restart`, {+ method: 'POST',+ body: {+ project_path: projectPath,+ service: service+ }+ });+ }++ async remoteComposePull(serverId, projectPath, service = null) {+ return this.request(`/servers/${serverId}/docker/compose/pull`, {+ method: 'POST',+ body: {+ project_path: projectPath,+ service: service+ }+ });+ }++ // Server Historical Metrics+ async getServerMetricsHistory(serverId, period = '24h') {+ return this.request(`/servers/${serverId}/metrics/history?period=${period}`);+ }++ async getServerMetricsAggregated(serverId, period = '24h', aggregation = 'hourly') {+ return this.request(`/servers/${serverId}/metrics/aggregated?period=${period}&aggregation=${aggregation}`);+ }++ async compareServerMetrics(serverIds, metric = 'cpu', period = '24h') {+ const ids = Array.isArray(serverIds) ? serverIds.join(',') : serverIds;+ return this.request(`/servers/metrics/compare?ids=${ids}&metric=${metric}&period=${period}`);+ }++ async getMetricsRetentionStats() {+ return this.request('/servers/metrics/retention');+ }++ async triggerMetricsCleanup() {+ return this.request('/servers/metrics/cleanup', { method: 'POST' });+ }++ // Remote Terminal+ async createTerminalSession(serverId, cols = 80, rows = 24) {+ return this.request(`/servers/${serverId}/terminal`, {+ method: 'POST',+ body: { cols, rows }+ });+ }++ async sendTerminalInput(sessionId, data) {+ return this.request(`/servers/terminal/${sessionId}/input`, {+ method: 'POST',+ body: { data }+ });+ }++ async resizeTerminal(sessionId, cols, rows) {+ return this.request(`/servers/terminal/${sessionId}/resize`, {+ method: 'POST',+ body: { cols, rows }+ });+ }++ async closeTerminalSession(sessionId) {+ return this.request(`/servers/terminal/${sessionId}`, {+ method: 'DELETE'+ });+ }++ async listTerminalSessions() {+ return this.request('/servers/terminal/sessions');+ }++ // Security Features+ async getAllowedIPs(serverId) {+ return this.request(`/servers/${serverId}/allowed-ips`);+ }++ async updateAllowedIPs(serverId, allowedIPs) {+ return this.request(`/servers/${serverId}/allowed-ips`, {+ method: 'PUT',+ body: { allowed_ips: allowedIPs }+ });+ }++ async getConnectionInfo(serverId) {+ return this.request(`/servers/${serverId}/connection-info`);+ }++ async rotateAPIKey(serverId) {+ return this.request(`/servers/${serverId}/rotate-api-key`, {+ method: 'POST'+ });+ }++ async getServerSecurityAlerts(serverId, options = {}) {+ const params = new URLSearchParams();+ if (options.status) params.append('status', options.status);+ if (options.severity) params.append('severity', options.severity);+ if (options.limit) params.append('limit', options.limit);+ const query = params.toString() ? `?${params.toString()}` : '';+ return this.request(`/servers/${serverId}/security/alerts${query}`);+ }++ async getAllSecurityAlerts(options = {}) {+ const params = new URLSearchParams();+ if (options.status) params.append('status', options.status);+ if (options.severity) params.append('severity', options.severity);+ if (options.type) params.append('type', options.type);+ if (options.limit) params.append('limit', options.limit);+ const query = params.toString() ? `?${params.toString()}` : '';+ return this.request(`/servers/security/alerts${query}`);+ }++ async getSecurityAlertCounts(serverId = null) {+ const query = serverId ? `?server_id=${serverId}` : '';+ return this.request(`/servers/security/alerts/counts${query}`);+ }++ async acknowledgeAlert(alertId) {+ return this.request(`/servers/security/alerts/${alertId}/acknowledge`, {+ method: 'POST'+ });+ }++ async resolveAlert(alertId) {+ return this.request(`/servers/security/alerts/${alertId}/resolve`, {+ method: 'POST'+ });+ }++ // Agent Downloads+ async getAgentVersion() {+ return this.request('/servers/agent/version');+ }++ async getAgentDownloadUrl(os, arch) {+ // Returns the download URL, caller should redirect or fetch+ const baseUrl = this.baseUrl.replace('/api/v1', '');+ return `${baseUrl}/api/servers/agent/download/${os}/${arch}`;+ }++ // ========================================+ // Agent Fleet Management endpoints+ // ========================================+ async getFleetHealth() {+ return this.request('/servers/fleet/health');+ }++ async getAgentVersions() {+ return this.request('/servers/fleet/versions');+ }++ async addAgentVersion(data) {+ return this.request('/servers/fleet/versions', {+ method: 'POST',+ body: data+ });+ }++ async upgradeFleet(serverIds, versionId) {+ return this.request('/servers/fleet/upgrade', {+ method: 'POST',+ body: { server_ids: serverIds, version_id: versionId }+ });+ }++ async startRollout(data) {+ return this.request('/servers/fleet/rollout', {+ method: 'POST',+ body: data+ });+ }++ async getRollouts(status) {+ const query = status ? `?status=${status}` : '';+ return this.request(`/servers/fleet/rollouts${query}`);+ }++ async getRollout(rolloutId) {+ return this.request(`/servers/fleet/rollouts/${rolloutId}`);+ }++ async cancelRollout(rolloutId) {+ return this.request(`/servers/fleet/rollouts/${rolloutId}/cancel`, {+ method: 'POST'+ });+ }++ async startDiscovery(duration = 10) {+ return this.request(`/servers/fleet/discovery?duration=${duration}`, {+ method: 'POST'+ });+ }++ async getDiscoveredAgents() {+ return this.request('/servers/fleet/discovery');+ }++ async approveRegistration(serverId) {+ return this.request(`/servers/fleet/approve/${serverId}`, {+ method: 'POST'+ });+ }++ async rejectRegistration(serverId) {+ return this.request(`/servers/fleet/reject/${serverId}`, {+ method: 'POST'+ });+ }++ async getQueuedCommands(serverId) {+ const query = serverId ? `?server_id=${serverId}` : '';+ return this.request(`/servers/fleet/commands/queued${query}`);+ }++ async retryCommand(commandId) {+ return this.request(`/servers/fleet/commands/${commandId}/retry`, {+ method: 'POST'+ });+ }++ async getServerDiagnostics(serverId) {+ return this.request(`/servers/fleet/diagnostics/${serverId}`);+ }++ // ========================================+ // Fleet Monitor (Cross-Server Monitoring) endpoints+ // ========================================+ async getFleetHeatmap(groupId) {+ const query = groupId ? `?group_id=${groupId}` : '';+ return this.request(`/fleet-monitor/heatmap${query}`);+ }++ async getFleetComparison(serverIds, metric, period) {+ const ids = serverIds.join(',');+ return this.request(`/fleet-monitor/comparison?ids=${ids}&metric=${metric}&period=${period}`);+ }++ async getFleetAlerts(params = {}) {+ const searchParams = new URLSearchParams();+ if (params.status) searchParams.append('status', params.status);+ if (params.severity) searchParams.append('severity', params.severity);+ if (params.server_id) searchParams.append('server_id', params.server_id);+ if (params.limit) searchParams.append('limit', params.limit);+ const query = searchParams.toString();+ return this.request(`/fleet-monitor/alerts${query ? '?' + query : ''}`);+ }++ async acknowledgeFleetAlert(alertId) {+ return this.request(`/fleet-monitor/alerts/${alertId}/acknowledge`, { method: 'POST' });+ }++ async resolveFleetAlert(alertId) {+ return this.request(`/fleet-monitor/alerts/${alertId}/resolve`, { method: 'POST' });+ }++ async getFleetThresholds(serverId) {+ const query = serverId ? `?server_id=${serverId}` : '';+ return this.request(`/fleet-monitor/thresholds${query}`);+ }++ async createFleetThreshold(data) {+ return this.request('/fleet-monitor/thresholds', { method: 'POST', body: data });+ }++ async deleteFleetThreshold(thresholdId) {+ return this.request(`/fleet-monitor/thresholds/${thresholdId}`, { method: 'DELETE' });+ }++ async getFleetAnomalies(serverId) {+ const query = serverId ? `?server_id=${serverId}` : '';+ return this.request(`/fleet-monitor/anomalies${query}`);+ }++ async getCapacityForecast(serverId, metric = 'disk') {+ return this.request(`/fleet-monitor/forecast/${serverId}?metric=${metric}`);+ }++ async searchFleet(query, type = 'any') {+ return this.request(`/fleet-monitor/search?q=${encodeURIComponent(query)}&type=${type}`);+ }++ async exportFleetCsv(serverIds, metric, period) {+ const ids = serverIds.join(',');+ const url = `${this.baseUrl}/fleet-monitor/export/csv?ids=${ids}&metric=${metric}&period=${period}`;+ const token = this.getToken();+ const response = await fetch(url, {+ headers: token ? { Authorization: `Bearer ${token}` } : {}+ });+ return response.blob();+ }++ // ── Email Server ──+ async getEmailStatus() { return this.request('/email/status'); }+ async installEmailServer(data = {}) { return this.request('/email/install', { method: 'POST', body: JSON.stringify(data) }); }+ async controlEmailService(component, action) { return this.request(`/email/service/${component}/${action}`, { method: 'POST' }); }+ // Email Domains+ async getEmailDomains() { return this.request('/email/domains'); }+ async addEmailDomain(data) { return this.request('/email/domains', { method: 'POST', body: JSON.stringify(data) }); }+ async getEmailDomain(domainId) { return this.request(`/email/domains/${domainId}`); }+ async deleteEmailDomain(domainId) { return this.request(`/email/domains/${domainId}`, { method: 'DELETE' }); }+ async verifyEmailDNS(domainId) { return this.request(`/email/domains/${domainId}/verify-dns`, { method: 'POST' }); }+ async deployEmailDNS(domainId) { return this.request(`/email/domains/${domainId}/deploy-dns`, { method: 'POST' }); }+ // Email Accounts+ async getEmailAccounts(domainId) { return this.request(`/email/domains/${domainId}/accounts`); }+ async createEmailAccount(domainId, data) { return this.request(`/email/domains/${domainId}/accounts`, { method: 'POST', body: JSON.stringify(data) }); }+ async getEmailAccount(accountId) { return this.request(`/email/accounts/${accountId}`); }+ async updateEmailAccount(accountId, data) { return this.request(`/email/accounts/${accountId}`, { method: 'PUT', body: JSON.stringify(data) }); }+ async deleteEmailAccount(accountId) { return this.request(`/email/accounts/${accountId}`, { method: 'DELETE' }); }+ async changeEmailPassword(accountId, password) { return this.request(`/email/accounts/${accountId}/password`, { method: 'POST', body: JSON.stringify({ password }) }); }+ // Email Aliases+ async getEmailAliases(domainId) { return this.request(`/email/domains/${domainId}/aliases`); }+ async createEmailAlias(domainId, data) { return this.request(`/email/domains/${domainId}/aliases`, { method: 'POST', body: JSON.stringify(data) }); }+ async deleteEmailAlias(aliasId) { return this.request(`/email/aliases/${aliasId}`, { method: 'DELETE' }); }+ // Email Forwarding+ async getEmailForwarding(accountId) { return this.request(`/email/accounts/${accountId}/forwarding`); }+ async createEmailForwarding(accountId, data) { return this.request(`/email/accounts/${accountId}/forwarding`, { method: 'POST', body: JSON.stringify(data) }); }+ async updateEmailForwarding(ruleId, data) { return this.request(`/email/forwarding/${ruleId}`, { method: 'PUT', body: JSON.stringify(data) }); }+ async deleteEmailForwarding(ruleId) { return this.request(`/email/forwarding/${ruleId}`, { method: 'DELETE' }); }+ // DNS Providers+ async getEmailDNSProviders() { return this.request('/email/dns-providers'); }+ async addEmailDNSProvider(data) { return this.request('/email/dns-providers', { method: 'POST', body: JSON.stringify(data) }); }+ async deleteEmailDNSProvider(providerId) { return this.request(`/email/dns-providers/${providerId}`, { method: 'DELETE' }); }+ async testEmailDNSProvider(providerId) { return this.request(`/email/dns-providers/${providerId}/test`, { method: 'POST' }); }+ async getEmailDNSZones(providerId) { return this.request(`/email/dns-providers/${providerId}/zones`); }+ // SpamAssassin+ async getSpamConfig() { return this.request('/email/spam/config'); }+ async updateSpamConfig(data) { return this.request('/email/spam/config', { method: 'PUT', body: JSON.stringify(data) }); }+ async updateSpamRules() { return this.request('/email/spam/update-rules', { method: 'POST' }); }+ // Roundcube Webmail+ async getWebmailStatus() { return this.request('/email/webmail/status'); }+ async installWebmail(data = {}) { return this.request('/email/webmail/install', { method: 'POST', body: JSON.stringify(data) }); }+ async controlWebmail(action) { return this.request(`/email/webmail/service/${action}`, { method: 'POST' }); }+ async configureWebmailProxy(domain) { return this.request('/email/webmail/configure-proxy', { method: 'POST', body: JSON.stringify({ domain }) }); }+ // Mail Queue & Logs+ async getMailQueue() { return this.request('/email/queue'); }+ async flushMailQueue() { return this.request('/email/queue/flush', { method: 'POST' }); }+ async deleteMailQueueItem(queueId) { return this.request(`/email/queue/${queueId}`, { method: 'DELETE' }); }+ async getMailLogs(lines = 100) { return this.request(`/email/logs?lines=${lines}`); }++ // ==================== SSO / OAuth ====================++ async getSSOProviders() {+ return this.request('/sso/providers');+ }++ async startSSOAuth(provider, redirectUri) {+ return this.request(`/sso/authorize/${provider}?redirect_uri=${encodeURIComponent(redirectUri)}`);+ }++ async completeSSOAuth(provider, code, state, redirectUri) {+ const data = await this.request(`/sso/callback/${provider}`, {+ method: 'POST',+ body: { code, state, redirect_uri: redirectUri },+ });+ if (data.access_token) {+ this.setTokens(data.access_token, data.refresh_token);+ }+ return data;+ }++ async getSSOIdentities() {+ return this.request('/sso/identities');+ }++ async linkSSOProvider(provider, code, state, redirectUri) {+ return this.request(`/sso/link/${provider}`, {+ method: 'POST',+ body: { code, state, redirect_uri: redirectUri },+ });+ }++ async unlinkSSOProvider(provider) {+ return this.request(`/sso/link/${provider}`, { method: 'DELETE' });+ }++ // SSO Admin+ async getSSOConfig() {+ return this.request('/sso/admin/config');+ }++ async updateSSOProviderConfig(provider, config) {+ return this.request(`/sso/admin/config/${provider}`, {+ method: 'PUT',+ body: config,+ });+ }++ async testSSOProvider(provider) {+ return this.request(`/sso/admin/test/${provider}`, { method: 'POST' });+ }++ async updateSSOGeneralSettings(settings) {+ return this.request('/sso/admin/general', {+ method: 'PUT',+ body: settings,+ });+ }++ // Database Migrations+ async getMigrationStatus() {+ return this.request('/migrations/status');+ }++ async createMigrationBackup() {+ return this.request('/migrations/backup', { method: 'POST' });+ }++ async applyMigrations() {+ return this.request('/migrations/apply', { method: 'POST' });+ }++ async getMigrationHistory() {+ return this.request('/migrations/history');+ }++ // API Keys+ async getApiKeys() {+ return this.request('/api-keys/');+ }++ async createApiKey(data) {+ return this.request('/api-keys/', { method: 'POST', body: data });+ }++ async getApiKey(id) {+ return this.request(`/api-keys/${id}`);+ }++ async updateApiKey(id, data) {+ return this.request(`/api-keys/${id}`, { method: 'PUT', body: data });+ }++ async revokeApiKey(id) {+ return this.request(`/api-keys/${id}`, { method: 'DELETE' });+ }++ async rotateApiKey(id) {+ return this.request(`/api-keys/${id}/rotate`, { method: 'POST' });+ }++ // Event Subscriptions (Webhooks)+ async getEventSubscriptions() {+ return this.request('/event-subscriptions/');+ }++ async createEventSubscription(data) {+ return this.request('/event-subscriptions/', { method: 'POST', body: data });+ }++ async getAvailableEvents() {+ return this.request('/event-subscriptions/events');+ }++ async getEventSubscription(id) {+ return this.request(`/event-subscriptions/${id}`);+ }++ async updateEventSubscription(id, data) {+ return this.request(`/event-subscriptions/${id}`, { method: 'PUT', body: data });+ }++ async deleteEventSubscription(id) {+ return this.request(`/event-subscriptions/${id}`, { method: 'DELETE' });+ }++ async testEventSubscription(id) {+ return this.request(`/event-subscriptions/${id}/test`, { method: 'POST' });+ }++ async getEventDeliveries(id, page = 1) {+ return this.request(`/event-subscriptions/${id}/deliveries?page=${page}`);+ }++ async retryEventDelivery(subId, deliveryId) {+ return this.request(`/event-subscriptions/${subId}/deliveries/${deliveryId}/retry`, { method: 'POST' });+ }++ // API Analytics+ async getApiAnalyticsOverview(period = '24h') {+ return this.request(`/api-analytics/overview?period=${period}`);+ }++ async getApiAnalyticsEndpoints(period = '24h', limit = 20) {+ return this.request(`/api-analytics/endpoints?period=${period}&limit=${limit}`);+ }++ async getApiAnalyticsErrors(period = '24h') {+ return this.request(`/api-analytics/errors?period=${period}`);+ }++ async getApiAnalyticsTimeseries(period = '24h', interval = 'hour') {+ return this.request(`/api-analytics/timeseries?period=${period}&interval=${interval}`);+ }++ async getApiKeyUsage(keyId, period = '24h') {+ return this.request(`/api-analytics/keys/${keyId}/usage?period=${period}`);+ }++ // ========================================+ // Admin - Permissions endpoints+ // ========================================+ async getUserPermissions(userId) {+ return this.request(`/admin/users/${userId}/permissions`);+ }++ async updateUserPermissions(userId, permissions) {+ return this.request(`/admin/users/${userId}/permissions`, {+ method: 'PUT',+ body: { permissions }+ });+ }++ async resetUserPermissions(userId) {+ return this.request(`/admin/users/${userId}/permissions/reset`, {+ method: 'POST'+ });+ }++ async getPermissionTemplates() {+ return this.request('/admin/permissions/templates');+ }++ // ========================================+ // Admin - Invitations endpoints+ // ========================================+ async getInvitations(status) {+ const query = status ? `?status=${status}` : '';+ return this.request(`/admin/invitations/${query}`);+ }++ async createInvitation(data) {+ return this.request('/admin/invitations/', {+ method: 'POST',+ body: data+ });+ }++ async revokeInvitation(id) {+ return this.request(`/admin/invitations/${id}`, {+ method: 'DELETE'+ });+ }++ async resendInvitation(id) {+ return this.request(`/admin/invitations/resend/${id}`, {+ method: 'POST'+ });+ }++ async validateInvitation(token) {+ return this.request(`/admin/invitations/validate/${token}`);+ }++ // ========================================+ // Admin - Activity endpoints+ // ========================================+ async getActivitySummary() {+ return this.request('/admin/activity/summary');+ }++ async getActivityFeed(params = {}) {+ const searchParams = new URLSearchParams();+ if (params.page) searchParams.append('page', params.page);+ if (params.per_page) searchParams.append('per_page', params.per_page);+ if (params.user_id) searchParams.append('user_id', params.user_id);+ if (params.action) searchParams.append('action', params.action);+ if (params.start_date) searchParams.append('start_date', params.start_date);+ if (params.end_date) searchParams.append('end_date', params.end_date);+ const query = searchParams.toString();+ return this.request(`/admin/activity/feed${query ? '?' + query : ''}`);+ }+ // ========================================+ // Agent Plugins endpoints+ // ========================================+ async getAgentPlugins(status) {+ const query = status ? `?status=${status}` : '';+ return this.request(`/agent-plugins/${query}`);+ }++ async getAgentPlugin(id) {+ return this.request(`/agent-plugins/${id}`);+ }++ async createAgentPlugin(data) {+ return this.request('/agent-plugins/', { method: 'POST', body: data });+ }++ async updateAgentPlugin(id, data) {+ return this.request(`/agent-plugins/${id}`, { method: 'PUT', body: data });+ }++ async deleteAgentPlugin(id) {+ return this.request(`/agent-plugins/${id}`, { method: 'DELETE' });+ }++ async installAgentPlugin(pluginId, serverId, config) {+ return this.request(`/agent-plugins/${pluginId}/install`, {+ method: 'POST', body: { server_id: serverId, config }+ });+ }++ async bulkInstallAgentPlugin(pluginId, serverIds, config) {+ return this.request(`/agent-plugins/${pluginId}/bulk-install`, {+ method: 'POST', body: { server_ids: serverIds, config }+ });+ }++ async getPluginInstallations(pluginId) {+ return this.request(`/agent-plugins/${pluginId}/installations`);+ }++ async getServerPlugins(serverId) {+ return this.request(`/agent-plugins/server/${serverId}`);+ }++ async enablePluginInstall(installId) {+ return this.request(`/agent-plugins/installs/${installId}/enable`, { method: 'POST' });+ }++ async disablePluginInstall(installId) {+ return this.request(`/agent-plugins/installs/${installId}/disable`, { method: 'POST' });+ }++ async uninstallPlugin(installId) {+ return this.request(`/agent-plugins/installs/${installId}`, { method: 'DELETE' });+ }++ async updatePluginInstallConfig(installId, config) {+ return this.request(`/agent-plugins/installs/${installId}/config`, {+ method: 'PUT', body: { config }+ });+ }++ async getPluginSpec() {+ return this.request('/agent-plugins/spec');+ }+}++export const api = new ApiService();+export default api;diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.lessindex fd421217..2b6473cc 100644--- a/frontend/src/styles/main.less+++ b/frontend/src/styles/main.less@@ -1,87 +1,88 @@-// ============================================-// SERVERKIT - MAIN STYLESHEET-// ============================================-// This file imports all LESS partials in the correct order.-// Import this file in your main React entry point.-// ============================================--// ---------------------------------------------// 1. DESIGN TOKENS-// ---------------------------------------------@import '_theme-variables'; // CSS custom properties for runtime theming (must be first)-@import '_variables';-@import '_mixins';--// ---------------------------------------------// 2. BASE STYLES-// ---------------------------------------------@import 'base/_reset';-@import 'base/_typography';--// ---------------------------------------------// 3. LAYOUT-// ---------------------------------------------@import 'layout/_sidebar';-@import 'layout/_main-content';-@import 'layout/_grid';--// ---------------------------------------------// 4. COMPONENTS-// ---------------------------------------------@import 'components/_buttons';-@import 'components/_cards';-@import 'components/_modals';-@import 'components/_forms';-@import 'components/_badges';-@import 'components/_tabs';-@import 'components/_lists';-@import 'components/_services';-@import 'components/_logs';-@import 'components/_credentials';-@import 'components/_toasts';-@import 'components/_spinner';-@import 'components/_uptime';-@import 'components/_metrics-graph';-@import 'components/_env-vars';-@import 'components/_private-url';-@import 'components/_two-factor';-@import 'components/_notifications';-@import 'components/_query-runner';-@import 'components/_deploy';-@import 'components/_build';-@import 'components/_users';-@import 'components/_linked-apps';-@import 'components/_api-settings';--// ---------------------------------------------// 5. PAGE-SPECIFIC STYLES-// ---------------------------------------------@import 'pages/_auth';-@import 'pages/_dashboard';-@import 'pages/_applications';-@import 'pages/_docker';-@import 'pages/_databases';-@import 'pages/_domains';-@import 'pages/_monitoring';-@import 'pages/_backups';-@import 'pages/_terminal';-@import 'pages/_settings';-@import 'pages/_file-manager';-@import 'pages/_ftp-server';-@import 'pages/_firewall';-@import 'pages/_cron';-@import 'pages/_security';-@import 'pages/_templates';-@import 'pages/_workflow';-@import 'pages/_git';-@import 'pages/_servers';-@import 'pages/_downloads';-@import 'pages/_wordpress';-@import 'pages/_wordpress-pipeline';-@import 'pages/_ssl';-@import 'pages/_email';-@import 'pages/_setup-wizard';-@import 'pages/_migration-wizard';-@import 'pages/_services';-@import 'pages/_service-detail';-@import 'pages/_fleet-monitor';+// ============================================+// SERVERKIT - MAIN STYLESHEET+// ============================================+// This file imports all LESS partials in the correct order.+// Import this file in your main React entry point.+// ============================================++// --------------------------------------------+// 1. DESIGN TOKENS+// --------------------------------------------+@import '_theme-variables'; // CSS custom properties for runtime theming (must be first)+@import '_variables';+@import '_mixins';++// --------------------------------------------+// 2. BASE STYLES+// --------------------------------------------+@import 'base/_reset';+@import 'base/_typography';++// --------------------------------------------+// 3. LAYOUT+// --------------------------------------------+@import 'layout/_sidebar';+@import 'layout/_main-content';+@import 'layout/_grid';++// --------------------------------------------+// 4. COMPONENTS+// --------------------------------------------+@import 'components/_buttons';+@import 'components/_cards';+@import 'components/_modals';+@import 'components/_forms';+@import 'components/_badges';+@import 'components/_tabs';+@import 'components/_lists';+@import 'components/_services';+@import 'components/_logs';+@import 'components/_credentials';+@import 'components/_toasts';+@import 'components/_spinner';+@import 'components/_uptime';+@import 'components/_metrics-graph';+@import 'components/_env-vars';+@import 'components/_private-url';+@import 'components/_two-factor';+@import 'components/_notifications';+@import 'components/_query-runner';+@import 'components/_deploy';+@import 'components/_build';+@import 'components/_users';+@import 'components/_linked-apps';+@import 'components/_api-settings';++// --------------------------------------------+// 5. PAGE-SPECIFIC STYLES+// --------------------------------------------+@import 'pages/_auth';+@import 'pages/_dashboard';+@import 'pages/_applications';+@import 'pages/_docker';+@import 'pages/_databases';+@import 'pages/_domains';+@import 'pages/_monitoring';+@import 'pages/_backups';+@import 'pages/_terminal';+@import 'pages/_settings';+@import 'pages/_file-manager';+@import 'pages/_ftp-server';+@import 'pages/_firewall';+@import 'pages/_cron';+@import 'pages/_security';+@import 'pages/_templates';+@import 'pages/_workflow';+@import 'pages/_git';+@import 'pages/_servers';+@import 'pages/_downloads';+@import 'pages/_wordpress';+@import 'pages/_wordpress-pipeline';+@import 'pages/_ssl';+@import 'pages/_email';+@import 'pages/_setup-wizard';+@import 'pages/_migration-wizard';+@import 'pages/_services';+@import 'pages/_service-detail';+@import 'pages/_fleet-monitor';+@import 'pages/_agent-plugins';diff --git a/frontend/src/styles/pages/_agent-plugins.less b/frontend/src/styles/pages/_agent-plugins.lessnew file mode 100644index 00000000..4e8227a0--- /dev/null+++ b/frontend/src/styles/pages/_agent-plugins.less@@ -0,0 +1,111 @@+// Agent Plugins page styles++.agent-plugins-page {+ .plugins-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));+ gap: @spacing-lg;+ margin-top: @spacing-lg;+ }++ .plugin-card {+ padding: @spacing-lg;+ display: flex;+ flex-direction: column;+ gap: @spacing-sm;++ &__header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ }++ &__info {+ display: flex;+ align-items: baseline;+ gap: @spacing-sm;++ h3 {+ margin: 0;+ font-size: 1.1rem;+ }+ }++ &__version {+ color: @text-muted;+ font-size: 0.85rem;+ font-family: @font-mono;+ }++ &__desc {+ color: @text-secondary;+ font-size: 0.9rem;+ margin: 0;+ line-height: 1.5;+ }++ &__meta {+ display: flex;+ gap: @spacing-md;+ font-size: 0.85rem;+ color: @text-muted;+ }++ &__capabilities,+ &__permissions {+ display: flex;+ flex-wrap: wrap;+ gap: @spacing-xs;+ }++ &__actions {+ display: flex;+ gap: @spacing-sm;+ margin-top: @spacing-sm;+ padding-top: @spacing-sm;+ border-top: 1px solid @border-color;+ }+ }++ .server-select-list {+ display: flex;+ flex-direction: column;+ gap: @spacing-xs;+ max-height: 300px;+ overflow-y: auto;+ }++ .server-select-item {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ padding: @spacing-sm @spacing-md;+ border-radius: @radius-md;+ cursor: pointer;+ transition: background-color 0.15s;++ &:hover {+ background: @hover-bg;+ }+ }++ .checkbox-group {+ display: flex;+ flex-wrap: wrap;+ gap: @spacing-sm;+ }++ .checkbox-label {+ display: flex;+ align-items: center;+ gap: @spacing-xs;+ font-size: 0.9rem;+ cursor: pointer;+ }++ .form-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: @spacing-md;+ }+}