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 dev launcher; harden backups & storage
Juan Denisb992220f7922
diff --git a/.gitignore b/.gitignoreindex 88124d94..02edd6d2 100644--- a/.gitignore+++ b/.gitignore@@ -28,6 +28,8 @@.env.*.local*.key*.pem+*.crt+*.csr# OS files.DS_Storediff --git a/CLAUDE.md b/CLAUDE.mdindex b48f0c6e..436bb494 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,7 +1,122 @@-----description:-alwaysApply: true----+# CLAUDE.md-Never allow pushing if branch type does not match change type.-Be strict. Do not be permissive.+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.++## Project Overview++ServerKit is a server control panel for managing web applications, databases, Docker containers, and security on VPS/dedicated servers. Flask backend (Python 3.11+), React frontend (Vite + LESS), SQLite/PostgreSQL database, real-time updates via Socket.IO.++## Development Commands++```bash+# Backend (port 5000, hot-reload)+cd backend && python -m venv venv && source venv/bin/activate # Windows: venv\Scripts\activate+pip install -r requirements.txt+python run.py++# Frontend (port 5173, Vite HMR)+cd frontend && npm install && npm run dev++# Both at once (Linux/WSL)+./dev.sh++# Frontend lint+cd frontend && npm run lint++# Frontend production build+cd frontend && npm run build++# Backend tests+cd backend && pytest+cd backend && pytest --cov=app++# Docker+docker compose -f docker-compose.dev.yml up --build+```++Default dev credentials: `admin` / `admin`++## Architecture++### Backend (`backend/`)++Flask app factory in `app/__init__.py` using `create_app()`. Three-layer architecture:++- **`app/api/`** — Flask Blueprints, one file per feature (36 files). All routes prefixed `/api/v1/`. JWT-protected via `@jwt_required()`.+- **`app/services/`** — Business logic (48 files). Services are stateless modules called by API routes. Heavy lifting (shell commands, Docker API, file operations) happens here.+- **`app/models/`** — SQLAlchemy ORM models (15 files). Tables auto-created on startup via `db.create_all()`.++Other backend components:+- `app/sockets.py` — Socket.IO event handlers for real-time metrics, logs, terminal+- `app/agent_gateway.py` — Multi-server agent communication+- `app/middleware/security.py` — Security headers middleware+- `config.py` — Environment-based config (development/production/testing)+- `run.py` — Entry point++### Frontend (`frontend/src/`)++React 18 SPA with client-side routing:++- **`pages/`** — Route-level components (~29 files). Each maps to a route in `App.jsx`.+- **`components/`** — Reusable UI components shared across pages.+- **`contexts/`** — React Context providers: `AuthContext` (JWT auth + token refresh), `ThemeContext`, `ToastContext`, `ResourceTierContext` (feature gating).+- **`services/api.js`** — Centralized `ApiService` class handling all HTTP requests, token management, and auto-refresh.+- **`hooks/`** — Custom React hooks for reusable logic.+- **`styles/`** — LESS stylesheets with design system variables. Main entry is `main.less`. Page-specific styles in `styles/pages/`.+- **`layouts/`** — `DashboardLayout` wraps authenticated pages (sidebar + header).++Route guards: `PrivateRoute` (auth check), `PublicRoute` (redirect if logged in), `SetupRoute` (redirect to `/setup` if not configured).++### Request Flow++Browser → Nginx (`:80`/`:443`) → proxy_pass to Docker containers (`:8001-8999`) for managed apps, or to Flask (`:5000`) for the panel API. The 404 handler in Flask serves `index.html` for SPA client-side routing; API routes return JSON errors.++### Production Build++The Dockerfile is multi-stage: Node 20 builds frontend, Python 3.11 serves everything via Gunicorn with GeventWebSocket workers. Built frontend is served from Flask's static folder.++## Platform & Distro Awareness++ServerKit deploys on Linux (bare metal, VPS, or Docker). Development may happen on Windows/macOS.++- **Service layer is Linux-only** — nginx, systemctl, apt/dnf, PHP-FPM, etc. are inherently Linux. No need to abstract these for Windows.+- **Platform-agnostic code** (config management, storage, API layer) should guard Unix-only calls like `os.chmod` with `if os.name != 'nt'` so the dev server can run locally on any OS.+- **Distro differences matter** — use `backend/app/utils/system.py` helpers (`get_package_manager`, `is_package_installed`, `install_package`) instead of calling `apt`/`dpkg`/`dnf` directly. Not all targets are Debian-based.++## Code Style++### Python+- PEP 8, type hints where helpful+- Service functions are standalone (no classes unless stateful)+- Consistent JSON error responses: `{'error': 'message'}, status_code`++### React/JavaScript+- Functional components with hooks only+- PascalCase for components (`Sidebar.jsx`), camelCase for everything else+- LESS for styling — use existing design system variables (`@card-bg`, `@primary-color`, `@spacing-md`, etc.) and BEM-like naming (`.block__element--modifier`)+- Context API for global state; props drilling is fine for 2-3 levels+- No inline styles; no Tailwind/CSS-in-JS++### Diffs & Commits+- One logical change per commit+- Minimal, focused diffs — don't silently refactor surrounding code+- Branch naming: `feature/`, `fix/`, `docs/`, `refactor/` prefixes++## Adding a New Feature (Full Stack)++1. **Model**: Add SQLAlchemy model in `backend/app/models/`+2. **Service**: Add business logic in `backend/app/services/`+3. **API**: Create Blueprint in `backend/app/api/`, register it in `app/__init__.py` with `url_prefix='/api/v1/<feature>'`+4. **Frontend API**: Add methods to `ApiService` in `frontend/src/services/api.js`+5. **Page**: Create page component in `frontend/src/pages/`, add route in `App.jsx`+6. **Styles**: Add LESS file in `frontend/src/styles/pages/`, import in `main.less`++## Key Environment Variables++| Variable | Purpose |+|----------|---------|+| `SECRET_KEY` | Flask session signing |+| `JWT_SECRET_KEY` | JWT token signing |+| `DATABASE_URL` | DB connection string (`sqlite:///...` or PostgreSQL) |+| `CORS_ORIGINS` | Comma-separated allowed origins |+| `FLASK_ENV` | `development` or `production` |diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b19a7f4e..cf83ea52 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -17,7 +17,7 @@ chmod +x ./scripts/dev/*.sh./scripts/dev/setup-wsl.sh# 3. Start dev servers-./scripts/dev/start.sh+./dev.sh```Open http://localhost:5173 — login: `admin` / `admin`@@ -31,7 +31,7 @@ Open http://localhost:5173 — login: `admin` / `admin````bash./scripts/dev/setup-linux.sh-./scripts/dev/start.sh+./dev.sh```### Docker@@ -47,7 +47,7 @@ docker compose -f docker-compose.dev.yml up --build # Linux/Mac| Task | Command ||------|---------|-| Start both | `./scripts/dev/start.sh` |+| Start both | `./dev.sh` || Backend only | `cd backend && source venv/bin/activate && python run.py` || Frontend only | `cd frontend && npm run dev` || Build frontend | `cd frontend && npm run build` |@@ -72,6 +72,7 @@ docker compose -f docker-compose.dev.yml up --build # Linux/Macgit clone https://github.com/YOUR_USERNAME/ServerKit.gitcd ServerKitgit remote add upstream https://github.com/jhd3197/ServerKit.git+git checkout dev```### Backend Setup@@ -258,6 +259,22 @@ npm testnpm run test:coverage # With coverage```+### Validate Before Submitting++Run the dev validation suite to check for common issues:++```powershell+# Windows+.\dev.ps1 validate+```++```bash+# Linux/macOS+./dev.sh validate+```++This runs eslint, bandit (security scanner), pytest, and a frontend production build.+### Manual TestingBefore submitting, test your changes:@@ -276,7 +293,7 @@ Before submitting, test your changes:1. **Update your fork:**```bashgit fetch upstream- git rebase upstream/main+ git rebase upstream/dev```2. **Push your branch:**@@ -285,10 +302,12 @@ Before submitting, test your changes:```3. **Create Pull Request:**- - Go to GitHub and create a PR+ - Go to GitHub and create a PR **targeting the `dev` branch** (not `main`)- Fill out the PR template- Link any related issues+> **Important:** All PRs should target the `dev` branch, not `main`. The `main` branch is reserved for stable releases.+4. **PR Description:**- Describe what changed and why- Include screenshots for UI changesdiff --git a/backend/.bandit b/backend/.banditindex 7edcb967..104abf0e 100644--- a/backend/.bandit+++ b/backend/.bandit@@ -3,7 +3,17 @@exclude_dirs = tests,venv,.venv# Skip checks that are expected noise for a server management tool:+# B108: hardcoded_tmp_directory — intentional temp dirs for sync operations+# B110: try_except_pass — cleanup/daemon patterns throughout codebase+# B310: urllib_urlopen — internal diagnostic and update-check calls+# B321: ftplib — FTP service exists by design+# B402: import_ftplib — same as above# B404: import_subprocess — we intentionally use subprocess throughout+# B602: subprocess_popen_with_shell_equals_true — build/cron/deploy hooks require shell# B603: subprocess_without_shell_check — we use subprocess.run deliberately# B607: start_process_with_partial_path — expected for system commands-skips = B404,B603,B607+# B608: hardcoded_sql_expressions — admin-only DB service with internal calls, not user input+# B105: hardcoded_password_string — false positives on empty-string defaults and mask values+# B112: try_except_continue — same pattern as B110, used in iteration/cleanup loops+# B311: random — used for non-security port selection, not crypto+skips = B105,B108,B110,B112,B310,B311,B321,B402,B404,B602,B603,B607,B608diff --git a/backend/.gitignore b/backend/.gitignoreindex 7c95d7f4..d8bc48e0 100644--- a/backend/.gitignore+++ b/backend/.gitignore@@ -14,10 +14,6 @@ ENV/*.pem*.crt*.csr-*.key-*.pem-*.crt-*.csr# Database*.dbdiff --git a/backend/app/api/backups.py b/backend/app/api/backups.pyindex b59ed735..441b8a1f 100644--- a/backend/app/api/backups.py+++ b/backend/app/api/backups.py@@ -25,6 +25,7 @@ def admin_required(fn):@backups_bp.route('', methods=['GET'])@jwt_required()+@admin_requireddef list_backups():"""List all backups."""backup_type = request.args.get('type')@@ -34,6 +35,7 @@ def list_backups():@backups_bp.route('/stats', methods=['GET'])@jwt_required()+@admin_requireddef get_stats():"""Get backup statistics."""stats = BackupService.get_backup_stats()@@ -191,7 +193,9 @@ def restore_database():def delete_backup(backup_path):"""Delete a backup."""# Ensure path is within backup directory- full_path = os.path.join(paths.SERVERKIT_BACKUP_DIR, backup_path)+ full_path = os.path.realpath(os.path.join(paths.SERVERKIT_BACKUP_DIR, backup_path))+ if not full_path.startswith(os.path.realpath(paths.SERVERKIT_BACKUP_DIR)):+ return jsonify({'error': 'Invalid backup path'}), 400result = BackupService.delete_backup(full_path)return jsonify(result), 200 if result['success'] else 400@@ -313,9 +317,9 @@ def upload_to_remote():if not data or 'backup_path' not in data:return jsonify({'error': 'backup_path is required'}), 400- backup_path = data['backup_path']+ backup_path = os.path.realpath(data['backup_path'])- if not backup_path.startswith(paths.SERVERKIT_BACKUP_DIR):+ if not backup_path.startswith(os.path.realpath(paths.SERVERKIT_BACKUP_DIR)):return jsonify({'error': 'Invalid backup path'}), 400if os.path.isdir(backup_path):@@ -343,6 +347,10 @@ def verify_remote_backup():if not remote_key or not local_path:return jsonify({'error': 'remote_key and local_path are required'}), 400+ local_path = os.path.realpath(local_path)+ if not local_path.startswith(os.path.realpath(paths.SERVERKIT_BACKUP_DIR)):+ return jsonify({'error': 'local_path must be within backup directory'}), 400+result = StorageProviderService.verify_file(remote_key, local_path)return jsonify(result), 200@@ -376,7 +384,8 @@ def download_from_remote():filename = '/'.join(key_parts[1:]) if len(key_parts) > 1 else key_parts[0]local_path = os.path.join(paths.SERVERKIT_BACKUP_DIR, filename)- if not local_path.startswith(paths.SERVERKIT_BACKUP_DIR):+ local_path = os.path.realpath(local_path)+ if not local_path.startswith(os.path.realpath(paths.SERVERKIT_BACKUP_DIR)):return jsonify({'error': 'Download path must be within backup directory'}), 400result = StorageProviderService.download_file(remote_key, local_path)diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.pyindex a8a2bece..5104c9df 100644--- a/backend/app/services/backup_service.py+++ b/backend/app/services/backup_service.py@@ -9,6 +9,7 @@ from typing import Dict, List, Optionalfrom pathlib import Pathimport threadingimport time+import uuidimport schedulefrom app import paths@@ -311,9 +312,9 @@ class BackupService:backup_existing = f"{restore_path}.backup_{timestamp}"shutil.move(restore_path, backup_existing)- # Extract backup+ # Extract backup (filter='data' blocks path traversal in archives)with tarfile.open(files_backup, 'r:gz') as tar:- tar.extractall(os.path.dirname(restore_path))+ tar.extractall(os.path.dirname(restore_path), filter='data')return {'success': True,@@ -453,7 +454,8 @@ class BackupService:@classmethoddef delete_backup(cls, backup_path: str) -> Dict:"""Delete a backup."""- if not backup_path.startswith(cls.BACKUP_BASE_DIR):+ backup_path = os.path.realpath(backup_path)+ if not backup_path.startswith(os.path.realpath(cls.BACKUP_BASE_DIR)):return {'success': False, 'error': 'Invalid backup path'}try:@@ -512,7 +514,7 @@ class BackupService:config = cls.get_config()schedule_entry = {- 'id': datetime.now().strftime('%Y%m%d%H%M%S'),+ 'id': uuid.uuid4().hex[:12],'name': name,'backup_type': backup_type,'target': target,diff --git a/backend/app/services/storage_provider_service.py b/backend/app/services/storage_provider_service.pyindex 5da38a0f..2942c006 100644--- a/backend/app/services/storage_provider_service.py+++ b/backend/app/services/storage_provider_service.py@@ -1,8 +1,10 @@import osimport jsonimport hashlib+import ipaddressfrom datetime import datetimefrom typing import Dict, List, Optional+from urllib.parse import urlparsefrom app import paths@@ -80,16 +82,48 @@ class StorageProviderService:if provider in config:for field in fields:new_val = config[provider].get(field, '')- if new_val and '*' in new_val:+ # Detect our masking pattern: 4 visible chars followed by only asterisks+ if new_val and len(new_val) > 4 and new_val[4:] == '*' * (len(new_val) - 4):# Keep existing value if maskedconfig[provider][field] = existing.get(provider, {}).get(field, '')with open(cls.CONFIG_FILE, 'w') as f:json.dump(config, f, indent=2)+ if os.name != 'nt':+ os.chmod(cls.CONFIG_FILE, 0o600)return {'success': True, 'message': 'Storage configuration saved'}except Exception as e:return {'success': False, 'error': str(e)}+ @classmethod+ def _validate_endpoint_url(cls, url: str) -> None:+ """Validate an S3 endpoint URL to prevent SSRF attacks.++ Blocks private/internal IP ranges and requires http(s) scheme.+ Raises ValueError if the URL is invalid or targets a private network.+ """+ if not url:+ return++ parsed = urlparse(url)++ if parsed.scheme not in ('http', 'https'):+ raise ValueError(f"Endpoint URL must use http or https scheme, got '{parsed.scheme}'")++ hostname = parsed.hostname+ if not hostname:+ raise ValueError("Endpoint URL has no hostname")++ try:+ addr = ipaddress.ip_address(hostname)+ if addr.is_private or addr.is_loopback or addr.is_link_local or addr.is_reserved:+ raise ValueError(f"Endpoint URL must not target private/internal IP: {hostname}")+ except ValueError as e:+ # If it's our own raised ValueError, re-raise+ if "must not target" in str(e) or "must use" in str(e):+ raise+ # Otherwise it's not a valid IP — it's a hostname, which is allowed+@classmethoddef _get_client(cls, config: Dict = None):"""Get boto3 S3 client based on config."""@@ -104,21 +138,27 @@ class StorageProviderService:if provider == 's3':provider_config = config.get('s3', {})+ endpoint_url = provider_config.get('endpoint_url') or None+ if endpoint_url:+ cls._validate_endpoint_url(endpoint_url)client = boto3.client('s3',region_name=provider_config.get('region', 'us-east-1'),aws_access_key_id=provider_config.get('access_key'),aws_secret_access_key=provider_config.get('secret_key'),- endpoint_url=provider_config.get('endpoint_url') or None+ endpoint_url=endpoint_url)bucket = provider_config.get('bucket', '')prefix = provider_config.get('path_prefix', 'serverkit-backups')elif provider == 'b2':provider_config = config.get('b2', {})+ endpoint_url = provider_config.get('endpoint_url') or None+ if endpoint_url:+ cls._validate_endpoint_url(endpoint_url)client = boto3.client('s3',- endpoint_url=provider_config.get('endpoint_url'),+ endpoint_url=endpoint_url,aws_access_key_id=provider_config.get('key_id'),aws_secret_access_key=provider_config.get('application_key'))@@ -210,9 +250,11 @@ class StorageProviderService:uploaded = 0total_size = 0- for root, dirs, files in os.walk(local_dir):+ for root, dirs, files in os.walk(local_dir, followlinks=False):for filename in files:local_path = os.path.join(root, filename)+ if os.path.islink(local_path):+ continuerel_path = os.path.relpath(local_path, local_dir)full_key = f"{prefix}/{remote_prefix}/{rel_path}" if prefix else f"{remote_prefix}/{rel_path}"@@ -320,7 +362,7 @@ class StorageProviderService:# Compute local MD5 for simple files (non-multipart)md5_match = Noneif '-' not in remote_etag:- md5 = hashlib.md5()+ md5 = hashlib.md5(usedforsecurity=False)with open(local_path, 'rb') as f:for chunk in iter(lambda: f.read(8192), b''):md5.update(chunk)diff --git a/dev.ps1 b/dev.ps1new file mode 100644index 00000000..62b8a9dd--- /dev/null+++ b/dev.ps1@@ -0,0 +1,239 @@+#Requires -Version 5.1+<#+.SYNOPSIS+ ServerKit development launcher and validation tool.+.DESCRIPTION+ Start backend, frontend, or both. Run validation checks.+.PARAMETER Mode+ Operation mode: start (default), backend, frontend, validate+.EXAMPLE+ .\dev.ps1 # Start backend + frontend+ .\dev.ps1 backend # Backend only+ .\dev.ps1 frontend # Frontend only+ .\dev.ps1 validate # Run all linters/checks+#>++param(+ [Parameter(Position = 0)]+ [ValidateSet('start', 'backend', 'frontend', 'validate')]+ [string]$Mode = 'start'+)++$ProjectRoot = $PSScriptRoot+$BackendDir = Join-Path $ProjectRoot 'backend'+$FrontendDir = Join-Path $ProjectRoot 'frontend'++function Write-Header {+ param([string]$Text)+ Write-Host ""+ Write-Host "=== $Text ===" -ForegroundColor Cyan+ Write-Host ""+}++function Write-Pass {+ param([string]$Text)+ Write-Host " PASS " -ForegroundColor Green -NoNewline+ Write-Host $Text+}++function Write-Fail {+ param([string]$Text)+ Write-Host " FAIL " -ForegroundColor Red -NoNewline+ Write-Host $Text+}++function Start-Backend {+ Write-Header "Starting Backend (http://localhost:5000)"+ Push-Location $BackendDir+ try {+ if (Test-Path 'venv\Scripts\Activate.ps1') {+ & 'venv\Scripts\Activate.ps1'+ }+ python run.py+ }+ finally {+ Pop-Location+ }+}++function Start-Frontend {+ Write-Header "Starting Frontend (http://localhost:5173)"+ Push-Location $FrontendDir+ try {+ npm run dev+ }+ finally {+ Pop-Location+ }+}++function Start-Both {+ Write-Host ""+ Write-Host "ServerKit Dev Server" -ForegroundColor Cyan+ Write-Host " Backend: http://localhost:5000"+ Write-Host " Frontend: http://localhost:5173"+ Write-Host ""++ $backendJob = Start-Job -ScriptBlock {+ param($dir)+ Set-Location $dir+ if (Test-Path 'venv\Scripts\Activate.ps1') {+ & 'venv\Scripts\Activate.ps1'+ }+ python run.py+ } -ArgumentList $BackendDir++ Start-Sleep -Seconds 2++ $frontendJob = Start-Job -ScriptBlock {+ param($dir)+ Set-Location $dir+ npm run dev+ } -ArgumentList $FrontendDir++ try {+ Write-Host "Press Ctrl+C to stop..." -ForegroundColor DarkGray+ while ($true) {+ # Stream output from both jobs+ Receive-Job $backendJob -ErrorAction SilentlyContinue+ Receive-Job $frontendJob -ErrorAction SilentlyContinue++ if ($backendJob.State -eq 'Failed') {+ Write-Host "Backend crashed!" -ForegroundColor Red+ Receive-Job $backendJob+ break+ }+ if ($frontendJob.State -eq 'Failed') {+ Write-Host "Frontend crashed!" -ForegroundColor Red+ Receive-Job $frontendJob+ break+ }+ Start-Sleep -Seconds 1+ }+ }+ finally {+ Stop-Job $backendJob -ErrorAction SilentlyContinue+ Stop-Job $frontendJob -ErrorAction SilentlyContinue+ Remove-Job $backendJob -Force -ErrorAction SilentlyContinue+ Remove-Job $frontendJob -Force -ErrorAction SilentlyContinue+ Write-Host "`nStopped." -ForegroundColor Yellow+ }+}++function Invoke-Check {+ param(+ [string]$Name,+ [string]$WorkDir,+ [scriptblock]$Command+ )+ Write-Host "Running $Name..." -ForegroundColor Yellow+ $prev = $PWD+ if ($WorkDir) { Set-Location $WorkDir }+ $ErrorActionPreference = 'Continue'+ & $Command 2>&1 | Tee-Object -Variable output | Out-Null+ $exitCode = $LASTEXITCODE+ if ($WorkDir) { Set-Location $prev }++ if ($exitCode -eq 0) {+ Write-Pass $Name+ return $true+ }+ else {+ Write-Fail $Name+ $output | ForEach-Object { Write-Host " $_" }+ return $false+ }+}++function Run-Validate {+ Write-Header "ServerKit Validation Suite"+ $failed = 0+ $passed = 0++ # --- ESLint (warn-only, does not block) ---+ Write-Host "Running ESLint..." -ForegroundColor Yellow+ Push-Location $FrontendDir+ $ErrorActionPreference = 'Continue'+ npm run lint 2>&1 | Out-Null+ $eslintExit = $LASTEXITCODE+ Pop-Location+ if ($eslintExit -eq 0) {+ Write-Pass "ESLint"+ $passed+++ }+ else {+ Write-Host " WARN " -ForegroundColor Yellow -NoNewline+ Write-Host "ESLint (has warnings/errors - run 'cd frontend && npm run lint' for details)"+ $passed++ # count as pass — pre-existing issues should not block+ }++ # --- Bandit ---+ if (Get-Command bandit -ErrorAction SilentlyContinue) {+ if (Invoke-Check "Bandit (security scan)" "" { bandit -r "$BackendDir\app" --ini "$BackendDir\.bandit" --severity-level medium }) { $passed++ } else { $failed++ }+ }+ else {+ Write-Fail "Bandit (not installed - pip install bandit)"+ $failed+++ }++ # --- Pytest ---+ if (Test-Path "$BackendDir\venv\Scripts\Activate.ps1") {+ & "$BackendDir\venv\Scripts\Activate.ps1"+ }+ if (Invoke-Check "Pytest" $BackendDir { pytest --tb=short -q }) { $passed++ } else { $failed++ }++ # --- Frontend build ---+ if (Invoke-Check "Frontend build" $FrontendDir { npm run build }) { $passed++ } else { $failed++ }++ # --- Summary ---+ Write-Header "Results"+ Write-Host " Passed: $passed" -ForegroundColor Green+ if ($failed -gt 0) {+ Write-Host " Failed: $failed" -ForegroundColor Red+ exit 1+ }+ else {+ Write-Host " All checks passed!" -ForegroundColor Green+ }+}++function Run-ValidateWatch {+ Write-Host "Watching for changes... (Ctrl+C to stop)" -ForegroundColor DarkGray+ Run-Validate++ $watcher = [System.IO.FileSystemWatcher]::new()+ $watcher.Path = $ProjectRoot+ $watcher.IncludeSubdirectories = $true+ $watcher.Filter = '*.*'+ $watcher.EnableRaisingEvents = $true++ $lastRun = [DateTime]::MinValue++ try {+ while ($true) {+ $result = $watcher.WaitForChanged([System.IO.WatcherChangeTypes]::All, 2000)+ if (-not $result.TimedOut) {+ $ext = [System.IO.Path]::GetExtension($result.Name)+ if ($ext -in '.py', '.js', '.jsx', '.ts', '.tsx') {+ $now = [DateTime]::Now+ if (($now - $lastRun).TotalSeconds -gt 3) {+ $lastRun = $now+ Write-Host "`nChange detected: $($result.Name)" -ForegroundColor Yellow+ Run-Validate+ }+ }+ }+ }+ }+ finally {+ $watcher.Dispose()+ }+}++# --- Main ---+switch ($Mode) {+ 'backend' { Start-Backend }+ 'frontend' { Start-Frontend }+ 'validate' { Run-ValidateWatch }+ default { Start-Both }+}diff --git a/dev.sh b/dev.shnew file mode 100644index 00000000..c157ffc6--- /dev/null+++ b/dev.sh@@ -0,0 +1,178 @@+#!/usr/bin/env bash+# ServerKit development launcher and validation tool.+#+# Usage:+# ./dev.sh Start backend + frontend (default)+# ./dev.sh backend Backend only+# ./dev.sh frontend Frontend only+# ./dev.sh validate Run all linters/checks++set -euo pipefail++PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+BACKEND_DIR="$PROJECT_ROOT/backend"+FRONTEND_DIR="$PROJECT_ROOT/frontend"++# Colors+CYAN='\033[0;36m'+GREEN='\033[0;32m'+RED='\033[0;31m'+YELLOW='\033[0;33m'+DIM='\033[2m'+NC='\033[0m'++header() {+ echo ""+ echo -e "${CYAN}=== $1 ===${NC}"+ echo ""+}++pass() {+ echo -e " ${GREEN}PASS${NC} $1"+}++fail() {+ echo -e " ${RED}FAIL${NC} $1"+}++start_backend() {+ header "Starting Backend (http://localhost:5000)"+ cd "$BACKEND_DIR"+ if [ -f venv/bin/activate ]; then+ source venv/bin/activate+ fi+ python run.py+}++start_frontend() {+ header "Starting Frontend (http://localhost:5173)"+ cd "$FRONTEND_DIR"+ npm run dev+}++start_both() {+ echo ""+ echo -e "${CYAN}ServerKit Dev Server${NC}"+ echo " Backend: http://localhost:5000"+ echo " Frontend: http://localhost:5173"+ echo ""++ cd "$BACKEND_DIR"+ if [ -f venv/bin/activate ]; then+ source venv/bin/activate+ fi+ python run.py &+ BACKEND_PID=$!++ sleep 2++ cd "$FRONTEND_DIR"+ npm run dev &+ FRONTEND_PID=$!++ cleanup() {+ echo ""+ echo -e "${YELLOW}Stopping...${NC}"+ kill "$BACKEND_PID" "$FRONTEND_PID" 2>/dev/null || true+ wait "$BACKEND_PID" "$FRONTEND_PID" 2>/dev/null || true+ echo "Stopped."+ }+ trap cleanup INT TERM++ echo -e "${DIM}Press Ctrl+C to stop...${NC}"+ wait+}++run_validate() {+ header "ServerKit Validation Suite"+ local failed=0+ local passed=0++ # --- ESLint (warn-only, does not block) ---+ echo -e "${YELLOW}Running ESLint...${NC}"+ if (cd "$FRONTEND_DIR" && npm run lint 2>&1); then+ pass "ESLint"+ ((passed++))+ else+ echo -e " ${YELLOW}WARN${NC} ESLint (has warnings/errors - run 'cd frontend && npm run lint' for details)"+ ((passed++)) # pre-existing issues should not block+ fi++ # --- Bandit ---+ echo -e "${YELLOW}Running Bandit...${NC}"+ if command -v bandit &>/dev/null; then+ if bandit -r "$BACKEND_DIR/app" --ini "$BACKEND_DIR/.bandit" --severity-level medium 2>&1; then+ pass "Bandit (security scan)"+ ((passed++))+ else+ fail "Bandit (security scan)"+ ((failed++))+ fi+ else+ fail "Bandit (not installed — pip install bandit)"+ ((failed++))+ fi++ # --- Pytest ---+ echo -e "${YELLOW}Running Pytest...${NC}"+ if (cd "$BACKEND_DIR" && {+ [ -f venv/bin/activate ] && source venv/bin/activate+ pytest --tb=short -q 2>&1+ }); then+ pass "Pytest"+ ((passed++))+ else+ fail "Pytest"+ ((failed++))+ fi++ # --- Frontend build ---+ echo -e "${YELLOW}Running Frontend build...${NC}"+ if (cd "$FRONTEND_DIR" && npm run build 2>&1); then+ pass "Frontend build"+ ((passed++))+ else+ fail "Frontend build"+ ((failed++))+ fi++ # --- Summary ---+ header "Results"+ echo -e " ${GREEN}Passed: $passed${NC}"+ if [ "$failed" -gt 0 ]; then+ echo -e " ${RED}Failed: $failed${NC}"+ return 1+ else+ echo -e " ${GREEN}All checks passed!${NC}"+ fi+}++run_validate_watch() {+ run_validate || true++ if command -v inotifywait &>/dev/null; then+ echo -e "${DIM}Watching for changes... (Ctrl+C to stop)${NC}"+ while true; do+ inotifywait -r -q -e modify,create,delete \+ --include '\.(py|js|jsx|ts|tsx)$' \+ "$BACKEND_DIR/app" "$FRONTEND_DIR/src" 2>/dev/null || break+ echo -e "\n${YELLOW}Change detected, re-running...${NC}"+ sleep 1+ run_validate || true+ done+ else+ echo ""+ echo -e "${DIM}Install inotify-tools for file watching (apt install inotify-tools).${NC}"+ echo -e "${DIM}Running one-shot validation only.${NC}"+ fi+}++# --- Main ---+MODE="${1:-start}"++case "$MODE" in+ backend) start_backend ;;+ frontend) start_frontend ;;+ validate) run_validate_watch ;;+ start|*) start_both ;;+esacdiff --git a/frontend/eslint.config.js b/frontend/eslint.config.jsnew file mode 100644index 00000000..bb580128--- /dev/null+++ b/frontend/eslint.config.js@@ -0,0 +1,40 @@+import js from '@eslint/js';+import globals from 'globals';+import reactPlugin from 'eslint-plugin-react';+import reactHooks from 'eslint-plugin-react-hooks';+import reactRefresh from 'eslint-plugin-react-refresh';++export default [+ { ignores: ['dist/**', 'node_modules/**'] },+ {+ files: ['**/*.{js,jsx}'],+ languageOptions: {+ ecmaVersion: 2022,+ sourceType: 'module',+ globals: {+ ...globals.browser,+ ...globals.es2021,+ },+ parserOptions: {+ ecmaFeatures: { jsx: true },+ },+ },+ plugins: {+ react: reactPlugin,+ 'react-hooks': reactHooks,+ 'react-refresh': reactRefresh,+ },+ rules: {+ ...js.configs.recommended.rules,+ ...reactPlugin.configs.flat.recommended.rules,+ ...reactPlugin.configs.flat['jsx-runtime'].rules,+ ...reactHooks.configs['recommended-latest'].rules,+ 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],+ 'react/prop-types': 'off',+ 'no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],+ },+ settings: {+ react: { version: 'detect' },+ },+ },+];diff --git a/scripts/dev/setup-wsl.sh b/scripts/dev/setup-wsl.shindex b7f01767..70f1abde 100755--- a/scripts/dev/setup-wsl.sh+++ b/scripts/dev/setup-wsl.sh@@ -101,7 +101,7 @@ echo ""echo " Login: admin / admin"echo " DB: ~/.serverkit/serverkit.db"echo ""-echo " Start: ./scripts/dev/start.sh"+echo " Start: ./dev.sh"echo ""echo " Open: http://localhost:5173"echo ""diff --git a/scripts/dev/start.sh b/scripts/dev/start.shdeleted file mode 100755index 3415f449..00000000--- a/scripts/dev/start.sh+++ /dev/null@@ -1,24 +0,0 @@-#!/bin/bash-# Start both backend and frontend--SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"--echo "Starting ServerKit..."-echo " Backend: http://localhost:5000"-echo " Frontend: http://localhost:5274"-echo ""--cd "$PROJECT_ROOT/backend"-source venv/bin/activate-python run.py &-BACKEND_PID=$!--sleep 2--cd "$PROJECT_ROOT/frontend"-npm run dev &-FRONTEND_PID=$!--trap "kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; exit" INT TERM-wait