diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
deleted file mode 100644
index e85f936..0000000
--- a/ARCHITECTURE.md
+++ /dev/null
@@ -1,291 +0,0 @@
-# Архитектура системы управления серверами
-
-## Общая схема
-
-```
-┌─────────────────────────────────────────────────────────────┐
-│ FRONTEND │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ ServerPanel Component │ │
-│ │ ┌─────────┬─────────┬─────────┬──────────────┐ │ │
-│ │ │ Обзор │ Консоль │ Статис- │ Управление │ │ │
-│ │ │ │ │ тика │ │ │ │
-│ │ └─────────┴─────────┴─────────┴──────────────┘ │ │
-│ │ ┌─────────┬─────────┬─────────┐ │ │
-│ │ │ Снэп- │ Конфигу-│ Безопас-│ │ │
-│ │ │ шоты │ рация │ ность │ │ │
-│ │ └─────────┴─────────┴─────────┘ │ │
-│ │ │ │
-│ │ Components: │ │
-│ │ • ConsoleSection (noVNC) │ │
-│ │ • ResizeModal (CPU/RAM/Disk) │ │
-│ │ • SnapshotsSection (Create/Restore/Delete) │ │
-│ │ • Stats Charts (Recharts LineChart) │ │
-│ └─────────────────────────────────────────────────────┘ │
-│ │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ WebSocket Hook (useSocket) │ │
-│ │ • Real-time stats updates │ │
-│ │ • Alert notifications │ │
-│ │ • Connection status │ │
-│ └─────────────────────────────────────────────────────┘ │
-└──────────────────────┬──────────────────────────────────────┘
- │ HTTP REST API + WebSocket
- │
-┌──────────────────────┴──────────────────────────────────────┐
-│ BACKEND SERVER │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ Express.js + Socket.IO Server │ │
-│ │ • CORS: localhost:3000, localhost:5173 │ │
-│ │ • Port: 5000 │ │
-│ └─────────────────────────────────────────────────────┘ │
-│ │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ API Routes (/api/server) │ │
-│ │ • GET / - List servers │ │
-│ │ • GET /:id - Get server │ │
-│ │ • GET /:id/status - Get stats │ │
-│ │ • POST /create - Create server │ │
-│ │ • POST /:id/start - Start │ │
-│ │ • POST /:id/stop - Stop │ │
-│ │ • POST /:id/restart - Restart │ │
-│ │ • DELETE /:id - Delete │ │
-│ │ • POST /:id/password - Change password │ │
-│ │ • PUT /:id/resize - Resize config │ │
-│ │ • POST /:id/snapshots - Create snapshot │ │
-│ │ • GET /:id/snapshots - List snapshots │ │
-│ │ • POST /:id/snapshots/rollback - Restore │ │
-│ │ • DELETE /:id/snapshots - Delete snapshot │ │
-│ │ • POST /console - Get console URL │ │
-│ └─────────────────────────────────────────────────────┘ │
-│ │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ MonitoringService (WebSocket) │ │
-│ │ • Interval: 30 seconds │ │
-│ │ • Check all active servers │ │
-│ │ • Update database metrics │ │
-│ │ • Broadcast to subscribed clients │ │
-│ │ • Check resource limits (>90%) │ │
-│ │ • Send alerts via WebSocket │ │
-│ │ • Send email notifications │ │
-│ └─────────────────────────────────────────────────────┘ │
-│ │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ Email Service (Nodemailer) │ │
-│ │ • SMTP configuration │ │
-│ │ • Resource alerts │ │
-│ │ • Server created notifications │ │
-│ │ • Payment reminders │ │
-│ └─────────────────────────────────────────────────────┘ │
-│ │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ Proxmox API Integration │ │
-│ │ • createLXContainer() │ │
-│ │ • controlContainer() - start/stop/restart │ │
-│ │ • getContainerStats() - CPU/RAM/Disk/Network │ │
-│ │ • getContainerIP() │ │
-│ │ • resizeContainer() - CPU/RAM/Disk │ │
-│ │ • createSnapshot() │ │
-│ │ • listSnapshots() │ │
-│ │ • rollbackSnapshot() │ │
-│ │ • deleteSnapshot() │ │
-│ │ • changeRootPassword() │ │
-│ │ • getConsoleURL() │ │
-│ │ • deleteContainer() │ │
-│ └─────────────────────────────────────────────────────┘ │
-└──────────────────────┬──────────────────────────────────────┘
- │ Proxmox API
- │ Token: PROXMOX_TOKEN_ID + SECRET
-┌──────────────────────┴──────────────────────────────────────┐
-│ PROXMOX VE SERVER │
-│ • LXC Containers │
-│ • VNC Console Access │
-│ • Resource Management │
-│ • Snapshot Management │
-└──────────────────────┬──────────────────────────────────────┘
- │
-┌──────────────────────┴──────────────────────────────────────┐
-│ MYSQL/MARIADB DATABASE │
-│ ┌─────────────────────────────────────────────────────┐ │
-│ │ Prisma Schema │ │
-│ │ • User (auth, balance) │ │
-│ │ • Server (status, metrics, proxmoxId) │ │
-│ │ • Tariff (price, resources) │ │
-│ │ • OperatingSystem (template, type) │ │
-│ │ • Ticket (support system) │ │
-│ │ • Check (payment verification) │ │
-│ │ • Notification (user alerts) │ │
-│ └─────────────────────────────────────────────────────┘ │
-└──────────────────────────────────────────────────────────────┘
-```
-
-## Поток данных Real-Time мониторинга
-
-```
-┌──────────────┐ 30s interval ┌──────────────┐
-│ Monitoring │ ───────────────────────>│ Proxmox │
-│ Service │<───────────────────────│ VE API │
-└──────┬───────┘ getContainerStats() └──────────────┘
- │
- │ Update metrics
- │
- ▼
-┌──────────────┐
-│ Database │
-│ (Server │
-│ metrics) │
-└──────┬───────┘
- │
- │ Broadcast via WebSocket
- │
- ▼
-┌──────────────┐ socket.emit() ┌──────────────┐
-│ Socket.IO │ ───────────────────────>│ Frontend │
-│ Server │ 'server-stats' │ Clients │
-│ │ 'server-alerts' │ │
-└──────────────┘ └──────────────┘
-```
-
-## Структура компонентов Frontend
-
-```
-ServerPanel (Main Component)
-├── State Management
-│ ├── server: Server | null
-│ ├── stats: ServerStats | null
-│ ├── activeTab: string
-│ ├── showResizeModal: boolean
-│ └── WebSocket hook: useServerStats(serverId)
-│ ├── stats (real-time)
-│ ├── alerts (real-time)
-│ └── connected (status)
-│
-├── Tabs Navigation
-│ ├── overview
-│ ├── console
-│ ├── stats
-│ ├── manage
-│ ├── snapshots
-│ ├── resize
-│ └── security
-│
-└── Tab Content
- ├── Overview Tab
- │ └── Server info (status, tariff, OS, IP, dates)
- │
- ├── Console Tab
- │ └── ConsoleSection
- │ ├── Open console button
- │ └── Embedded iframe (noVNC)
- │
- ├── Stats Tab
- │ ├── WebSocket connection indicator
- │ ├── Alerts display (if any)
- │ ├── Stats cards (CPU, RAM, Disk)
- │ ├── LineChart (history)
- │ └── Detailed stats grid
- │
- ├── Manage Tab
- │ └── Action buttons (start, restart, stop)
- │
- ├── Snapshots Tab
- │ └── SnapshotsSection
- │ ├── Create snapshot form
- │ └── Snapshots list
- │ ├── Restore button
- │ └── Delete button
- │
- ├── Resize Tab
- │ └── Open modal button
- │ └── ResizeModal (CPU, RAM, Disk inputs)
- │
- └── Security Tab
- ├── Generate password button
- └── New password display
-```
-
-## Технологический стек
-
-### Backend Dependencies
-```
-express: ^4.21.2 - HTTP сервер
-socket.io: ^4.8.1 - WebSocket
-@prisma/client: ^6.16.2 - ORM
-axios: ^1.12.2 - HTTP клиент
-nodemailer: ^6.9.16 - Email
-bcrypt: ^6.0.0 - Хеширование
-jsonwebtoken: ^9.0.2 - JWT
-multer: ^2.0.2 - Загрузка файлов
-cors: ^2.8.5 - CORS
-dotenv: ^16.4.5 - Env vars
-```
-
-### Frontend Dependencies
-```
-react: ^19.1.1 - UI библиотека
-socket.io-client: ^4.8.1 - WebSocket клиент
-recharts: ^2.15.0 - Графики
-axios: ^1.12.2 - HTTP клиент
-react-router-dom: ^7.9.1 - Роутинг
-tailwindcss: ^3.3.3 - CSS фреймворк
-vite: ^7.1.2 - Build tool
-typescript: ^5.8.3 - Type safety
-```
-
-## Конфигурация окружения (.env)
-
-```env
-# Database
-DATABASE_URL="mysql://user:pass@localhost:3306/ospabhost"
-
-# Proxmox
-PROXMOX_API_URL="https://proxmox.example.com:8006/api2/json"
-PROXMOX_TOKEN_ID="user@pam!token-id"
-PROXMOX_TOKEN_SECRET="secret"
-PROXMOX_NODE="proxmox"
-PROXMOX_WEB_URL="https://proxmox.example.com:8006"
-
-# Server
-PORT=5000
-JWT_SECRET="secret-key"
-
-# Email (optional)
-SMTP_HOST="smtp.gmail.com"
-SMTP_PORT=587
-SMTP_USER="email@gmail.com"
-SMTP_PASS="app-password"
-```
-
-## Основные метрики производительности
-
-- **Мониторинг интервал**: 30 секунд
-- **WebSocket latency**: < 100ms
-- **API response time**: < 500ms
-- **Database queries**: Optimized with Prisma
-- **Concurrent connections**: Поддержка множества клиентов
-
-## Безопасность
-
-1. **Аутентификация**: JWT tokens
-2. **API доступ**: Bearer tokens
-3. **Proxmox**: API tokens (не пароли)
-4. **Пароли**: Bcrypt хеширование
-5. **CORS**: Ограниченные origins
-6. **WebSocket**: Authenticated connections
-7. **SQL injection**: Prisma ORM защита
-
-## Масштабируемость
-
-- **Горизонтальное**: Можно запустить несколько инстансов backend
-- **Database**: MySQL поддерживает репликацию
-- **WebSocket**: Socket.IO поддерживает Redis adapter
-- **Кэширование**: Можно добавить Redis для кэша
-- **Load balancing**: Nginx/HAProxy совместимы
-
-## Мониторинг и логирование
-
-- Console.log для всех критических событий
-- Error tracking для ошибок Proxmox API
-- Database логи метрик каждые 30 секунд
-- Email алерты для критических событий
-- WebSocket connection/disconnection логи
diff --git a/PROJECT_COMPLETION_SUMMARY.md b/PROJECT_COMPLETION_SUMMARY.md
deleted file mode 100644
index e998881..0000000
--- a/PROJECT_COMPLETION_SUMMARY.md
+++ /dev/null
@@ -1,393 +0,0 @@
-# Project Completion Summary
-
-## Task: Реализация полноценного управления серверами клиентами
-
-**Status**: ✅ **COMPLETED WITH ENHANCED SECURITY**
-
-**Date**: October 2024
-**Branch**: `copilot/expand-proxmox-api-functions`
-**Commits**: 8 commits
-**Lines Changed**: +3,343 lines added, -25 lines removed
-
----
-
-## Executive Summary
-
-Successfully implemented comprehensive server management functionality for the Ospabhost 8.1 platform, enabling clients to fully manage their LXC containers through a web interface with real-time monitoring, alerts, and snapshot management. Added security validation to prevent SSRF and other attacks.
-
----
-
-## Deliverables
-
-### 1. Backend Enhancements (8 files)
-
-#### New Features
-- **11 Proxmox API functions**: resize, snapshots (create/list/rollback/delete), list containers
-- **6 new controllers**: resize, create/get/rollback/delete snapshots
-- **5 new API routes**: resize, snapshot management
-- **WebSocket server**: Socket.IO integration for real-time updates
-- **Monitoring service**: 30-second interval server checks
-- **Email service**: nodemailer integration for alerts
-- **Input validation**: SSRF and injection prevention
-
-#### Files Modified/Created
-1. `proxmoxApi.ts` - +182 lines (11 functions, 2 validators)
-2. `server.controller.ts` - +92 lines (6 controllers)
-3. `server.routes.ts` - +14 lines (5 routes)
-4. `monitoring.service.ts` - NEW (191 lines)
-5. `email.service.ts` - NEW (133 lines)
-6. `index.ts` - +21 lines (Socket.IO integration)
-7. `package.json` - +5 dependencies (socket.io, nodemailer)
-
-### 2. Frontend Enhancements (4 files)
-
-#### New Features
-- **Complete ServerPanel redesign**: 7 tabs instead of 5
-- **Real-time monitoring**: WebSocket integration with useServerStats hook
-- **Interactive charts**: Recharts LineChart for resource history
-- **Snapshot management**: Create, restore, delete with UI
-- **Configuration modal**: ResizeModal for CPU/RAM/Disk changes
-- **Visual alerts**: Real-time display of resource warnings
-
-#### Files Modified/Created
-1. `serverpanel.tsx` - +415 lines (complete redesign)
-2. `useSocket.ts` - NEW (76 lines, WebSocket hooks)
-3. `package.json` - +4 dependencies (socket.io-client, recharts)
-4. `main.tsx`, `settings.tsx` - 2 lines (import fixes)
-
-### 3. Documentation (4 files, 1,510 lines)
-
-#### Created Documentation
-1. **README.md** (366 lines)
- - Installation instructions
- - Configuration guide
- - Project structure
- - Usage examples
- - Troubleshooting
-
-2. **API_DOCUMENTATION.md** (534 lines)
- - 15+ endpoint documentation
- - Request/response examples
- - WebSocket events
- - Error codes
- - Best practices
-
-3. **ARCHITECTURE.md** (291 lines)
- - System architecture diagrams
- - Data flow charts
- - Component structure
- - Technology stack
- - Performance metrics
-
-4. **SECURITY.md** (319 lines)
- - Security measures
- - Input validation details
- - CodeQL scan results
- - Best practices
- - Production recommendations
-
----
-
-## Technical Implementation
-
-### Architecture
-
-```
-Frontend (React + Socket.IO Client)
- ↓
-Backend API (Express + Socket.IO Server)
- ↓
-Proxmox VE API (LXC Management)
-```
-
-### Key Technologies
-
-**Backend:**
-- Express.js 4.21.2
-- Socket.IO 4.8.1 (WebSocket)
-- Prisma 6.16.2 (ORM)
-- Nodemailer 6.9.16 (Email)
-- TypeScript 5.4.5
-
-**Frontend:**
-- React 19.1.1
-- Socket.IO Client 4.8.1
-- Recharts 2.15.0 (Charts)
-- TailwindCSS 3.3.3
-- TypeScript 5.8.3
-
-### Database Schema
-No schema changes required - existing Server model supports all features via `cpuUsage`, `memoryUsage`, `diskUsage`, `networkIn`, `networkOut` fields.
-
----
-
-## Features Implemented
-
-### ✅ Server Management (100%)
-- [x] Create LXC containers
-- [x] Start/Stop/Restart servers
-- [x] Change configuration (CPU, RAM, Disk)
-- [x] Delete servers
-- [x] Change root password
-
-### ✅ Snapshot System (100%)
-- [x] Create snapshots with description
-- [x] List all snapshots
-- [x] Restore from snapshot
-- [x] Delete snapshots
-
-### ✅ Real-time Monitoring (100%)
-- [x] WebSocket connection
-- [x] 30-second interval checks
-- [x] Live statistics (CPU, RAM, Disk, Network)
-- [x] Connection status indicator
-- [x] Auto subscribe/unsubscribe
-
-### ✅ Alert System (100%)
-- [x] Visual alerts in UI (>90% usage)
-- [x] Email notifications
-- [x] CPU/Memory/Disk alerts
-- [x] Real-time broadcasting
-
-### ✅ Data Visualization (100%)
-- [x] Interactive charts (Recharts)
-- [x] Resource usage graphs
-- [x] History tracking (1 hour)
-- [x] Detailed statistics cards
-
-### ✅ Console Access (100%)
-- [x] noVNC integration
-- [x] Embedded console
-- [x] Secure token access
-
-### ✅ Security (100%)
-- [x] Input validation
-- [x] SSRF prevention
-- [x] SQL injection protection (Prisma)
-- [x] XSS protection (React)
-- [x] CSRF protection (CORS)
-- [x] Secure password generation
-
-### ✅ Documentation (100%)
-- [x] Installation guide
-- [x] API documentation
-- [x] Architecture diagrams
-- [x] Security documentation
-
----
-
-## API Endpoints Added
-
-1. `PUT /api/server/:id/resize` - Change CPU/RAM/Disk
-2. `POST /api/server/:id/snapshots` - Create snapshot
-3. `GET /api/server/:id/snapshots` - List snapshots
-4. `POST /api/server/:id/snapshots/rollback` - Restore snapshot
-5. `DELETE /api/server/:id/snapshots` - Delete snapshot
-
-**Total API endpoints**: 15+ (5 new, 10 existing)
-
----
-
-## Security Enhancements
-
-### Input Validation Functions
-
-1. **validateSnapshotName()**
- - Sanitizes snapshot names
- - Allows only: a-z, A-Z, 0-9, _, -
- - Max length: 64 characters
- - Prevents: SSRF, path traversal, injection
-
-2. **validateContainerConfig()**
- - Validates CPU cores: 1-32
- - Validates memory: 512-65536 MB
- - Validates disk: 10-1000 GB
- - Prevents: resource exhaustion, DoS
-
-### CodeQL Security Scan
-- **Alerts**: 2 (false positives)
-- **Critical Issues**: 0
-- **Status**: Production-ready
-
----
-
-## Quality Assurance
-
-### Build Status
-✅ Backend: Compiles successfully (TypeScript)
-✅ Frontend: Compiles successfully (TypeScript + Vite)
-✅ No compilation errors
-✅ No linting errors
-
-### Code Review
-✅ Code review completed
-✅ Security scan performed
-✅ Input validation verified
-✅ Documentation reviewed
-
-### Testing Status
-- Manual testing: ✅ Completed
-- Integration testing: ⚠️ Recommended for production
-- Load testing: ⚠️ Recommended for production
-- Penetration testing: ⚠️ Recommended for production
-
----
-
-## Performance Metrics
-
-- **Monitoring Interval**: 30 seconds (optimized)
-- **WebSocket Latency**: <100ms
-- **API Response Time**: <500ms
-- **Database Queries**: Optimized with Prisma
-- **Bundle Size**:
- - Backend: ~2,700 lines
- - Frontend: ~782 KB (gzipped: ~230 KB)
-
----
-
-## Git Statistics
-
-```
-Repository: Ospab/ospabhost8.1
-Branch: copilot/expand-proxmox-api-functions
-Base Commit: 07f3eab
-Head Commit: 1b76dc9
-
-Commits: 8
-Files Changed: 18
-Lines Added: 3,343
-Lines Removed: 25
-Net Change: +3,318 lines
-
-Backend Changes: +1,457 lines
-Frontend Changes: +969 lines
-Documentation: +1,510 lines
-```
-
-### Commit History
-1. Fix frontend build errors with imports
-2. Add Proxmox API extensions, WebSocket monitoring, and email notifications
-3. Add frontend real-time monitoring, snapshots, and configuration management
-4. Add comprehensive API documentation and README
-5. Update API documentation date format
-6. Add comprehensive architecture documentation
-7. Add input validation for security (SSRF prevention)
-8. Add comprehensive security documentation
-
----
-
-## Production Readiness Checklist
-
-### ✅ Completed
-- [x] All features implemented
-- [x] Code compiles without errors
-- [x] Security validation added
-- [x] Documentation complete
-- [x] Code review performed
-- [x] Security scan completed
-
-### ⚠️ Required for Production
-- [ ] Configure HTTPS/TLS
-- [ ] Update CORS origins to production domains
-- [ ] Configure SMTP for emails
-- [ ] Set up environment variables (.env)
-- [ ] Configure Proxmox API tokens
-- [ ] Create and migrate database
-- [ ] Set up reverse proxy (Nginx/Apache)
-- [ ] Configure firewall rules
-
-### 📋 Recommended for Production
-- [ ] Implement rate limiting
-- [ ] Add security headers (Helmet.js)
-- [ ] Set up monitoring (PM2/Docker)
-- [ ] Configure database backups
-- [ ] Perform load testing
-- [ ] Conduct penetration testing
-- [ ] Set up CI/CD pipeline
-
----
-
-## User Benefits
-
-### For Clients
-✅ **Complete Control**: Full server management through web interface
-✅ **Real-time Insights**: Live monitoring with graphs and alerts
-✅ **Peace of Mind**: Automatic alerts for issues
-✅ **Data Safety**: Snapshot management for backups
-✅ **Flexibility**: Easy resource scaling
-✅ **Convenience**: Console access without SSH
-
-### For Administrators
-✅ **Automation**: Automatic monitoring and alerts
-✅ **Scalability**: WebSocket for efficient real-time updates
-✅ **Maintainability**: Well-documented codebase
-✅ **Security**: Multiple layers of protection
-✅ **Observability**: Comprehensive logging
-
----
-
-## Known Limitations
-
-1. **WebSocket Scalability**: Single-server deployment
- - *Solution*: Use Socket.IO Redis adapter for multi-server
-
-2. **Email Delivery**: Depends on SMTP configuration
- - *Solution*: Configure SMTP or use service like SendGrid
-
-3. **Console Access**: Requires Proxmox noVNC support
- - *Solution*: Ensure Proxmox VE properly configured
-
-4. **Database Performance**: No query caching implemented
- - *Solution*: Add Redis caching layer if needed
-
----
-
-## Future Enhancement Opportunities
-
-1. **Multi-server Support**: Manage multiple Proxmox nodes
-2. **Advanced Monitoring**: Prometheus/Grafana integration
-3. **Backup Automation**: Scheduled snapshot creation
-4. **Resource Quotas**: User-level resource limits
-5. **Billing Integration**: Automatic billing based on usage
-6. **Template Management**: Custom OS templates
-7. **Network Configuration**: Advanced networking options
-8. **API Keys**: User-generated API keys for automation
-
----
-
-## Conclusion
-
-The project has been successfully completed with all requirements met and exceeded. The implementation provides clients with a comprehensive server management platform featuring:
-
-- **Full Server Control**: Complete lifecycle management
-- **Real-time Monitoring**: Live statistics and alerts
-- **Snapshot Management**: Backup and restore capabilities
-- **Resource Scaling**: Dynamic configuration changes
-- **Console Access**: Browser-based terminal
-- **Email Notifications**: Proactive alerting
-- **Enhanced Security**: Input validation and protection
-
-The codebase is production-ready, well-documented, and follows security best practices. All builds are successful, and security scans have been performed.
-
-**Status**: ✅ **READY FOR DEPLOYMENT**
-
----
-
-## Project Team
-
-**Implementation**: GitHub Copilot Coding Agent
-**Repository**: github.com/Ospab/ospabhost8.1
-**Branch**: copilot/expand-proxmox-api-functions
-**Completion Date**: October 2024
-
----
-
-## Support & Maintenance
-
-For questions, issues, or feature requests:
-1. Create an issue in the GitHub repository
-2. Refer to documentation in README.md, API_DOCUMENTATION.md, ARCHITECTURE.md
-3. Security issues: Follow disclosure process in SECURITY.md
-
-**Documentation Last Updated**: October 2024
-**Next Review Recommended**: October 2025
diff --git a/README.md b/README.md
index d8b048b..d0ca3d0 100644
--- a/README.md
+++ b/README.md
@@ -1,366 +1,34 @@
-# Ospabhost 8.1 - Server Management Platform
+# Ospabhost 8.1
-Полнофункциональная платформа управления серверами на базе Proxmox VE с поддержкой LXC контейнеров.
+VPS hosting platform with Proxmox VE integration.
-## Возможности
+## 📁 Project Structure
-### Управление серверами
-- ✅ Создание LXC контейнеров
-- ✅ Управление состоянием (запуск, остановка, перезагрузка)
-- ✅ Изменение конфигурации (CPU, RAM, диск)
-- ✅ Управление снэпшотами (создание, восстановление, удаление)
-- ✅ Доступ к консоли через noVNC
-- ✅ Смена root-пароля
+This is a monorepo containing:
-### Мониторинг
-- ✅ Real-time статистика серверов через WebSocket
-- ✅ Графики использования ресурсов (CPU, RAM, диск, сеть)
-- ✅ Автоматические алерты при превышении лимитов (>90%)
-- ✅ Email уведомления о проблемах
-- ✅ Периодическая проверка состояния (каждые 30 секунд)
+- **`ospabhost/`** - Main application (backend + frontend)
+- **`Manuals/`** - Additional documentation and guides
-### Пользовательский интерфейс
-- ✅ Панель управления серверами
-- ✅ Real-time обновления статуса
-- ✅ Интерактивные графики
-- ✅ Модальные окна для настроек
-- ✅ Управление снэпшотами
-- ✅ Встроенная консоль
+## 📖 Documentation
-## Технологический стек
+**All documentation is located in the `ospabhost/` directory:**
-### Backend
-- TypeScript
-- Express.js
-- Prisma ORM
-- Socket.IO (WebSocket)
-- Nodemailer (Email)
-- Axios (Proxmox API)
-- MySQL/MariaDB
+- **[Main README](./ospabhost/README.md)** - Complete project documentation
+- **[Contributing Guide](./ospabhost/CONTRIBUTIONS.md)** - How to contribute
-### Frontend
-- React 19
-- TypeScript
-- Vite
-- TailwindCSS
-- Socket.IO Client
-- Recharts (графики)
-- React Router DOM
+## 🚀 Quick Start
-## Установка и настройка
-
-### Требования
-- Node.js 18+
-- MySQL/MariaDB
-- Proxmox VE 7+ с настроенными API токенами
-- SMTP сервер (опционально, для email уведомлений)
-
-### Backend
-
-1. Перейдите в директорию backend:
```bash
-cd ospabhost/backend
+cd ospabhost
```
-2. Установите зависимости:
-```bash
-npm install
-```
+Then follow the instructions in [ospabhost/README.md](./ospabhost/README.md).
-3. Создайте файл `.env` с конфигурацией:
-```env
-# Database
-DATABASE_URL="mysql://user:password@localhost:3306/ospabhost"
+## 📞 Support
-# Proxmox Configuration
-PROXMOX_API_URL="https://your-proxmox.example.com:8006/api2/json"
-PROXMOX_TOKEN_ID="user@pam!token-id"
-PROXMOX_TOKEN_SECRET="your-secret-token"
-PROXMOX_NODE="proxmox"
-PROXMOX_WEB_URL="https://your-proxmox.example.com:8006"
+- **Email:** support@ospab.host
+- **Telegram:** @ospab_support
-# Server Configuration
-PORT=5000
+---
-# JWT Secret
-JWT_SECRET="your-jwt-secret-key-change-this"
-
-# SMTP Configuration (optional)
-SMTP_HOST="smtp.gmail.com"
-SMTP_PORT=587
-SMTP_USER="your-email@gmail.com"
-SMTP_PASS="your-app-password"
-```
-
-4. Создайте базу данных и примените миграции:
-```bash
-npx prisma migrate dev
-npx prisma db seed
-```
-
-5. Соберите проект:
-```bash
-npm run build
-```
-
-6. Запустите сервер:
-```bash
-# Development режим с hot-reload
-npm run dev
-
-# Production режим
-npm start
-```
-
-### Frontend
-
-1. Перейдите в директорию frontend:
-```bash
-cd ospabhost/frontend
-```
-
-2. Установите зависимости:
-```bash
-npm install
-```
-
-3. Запустите dev-сервер:
-```bash
-npm run dev
-```
-
-4. Или соберите для production:
-```bash
-npm run build
-npm run preview
-```
-
-## Структура проекта
-
-```
-ospabhost/
-├── backend/
-│ ├── src/
-│ │ ├── modules/
-│ │ │ ├── auth/ # Авторизация и аутентификация
-│ │ │ ├── server/ # Управление серверами
-│ │ │ │ ├── proxmoxApi.ts # Интеграция с Proxmox
-│ │ │ │ ├── server.controller.ts
-│ │ │ │ ├── server.routes.ts
-│ │ │ │ └── monitoring.service.ts # WebSocket мониторинг
-│ │ │ ├── notification/ # Email уведомления
-│ │ │ ├── tariff/ # Тарифные планы
-│ │ │ ├── os/ # Операционные системы
-│ │ │ ├── ticket/ # Система тикетов
-│ │ │ └── check/ # Проверка платежей
-│ │ ├── index.ts # Точка входа, Socket.IO сервер
-│ │ └── prisma/
-│ │ ├── schema.prisma # Схема БД
-│ │ └── seed.ts # Начальные данные
-│ ├── API_DOCUMENTATION.md # Документация API
-│ └── package.json
-└── frontend/
- ├── src/
- │ ├── pages/
- │ │ └── dashboard/
- │ │ └── serverpanel.tsx # Главная панель управления
- │ ├── hooks/
- │ │ └── useSocket.ts # WebSocket хуки
- │ ├── components/ # Переиспользуемые компоненты
- │ └── context/ # React контексты
- └── package.json
-```
-
-## API Endpoints
-
-Полная документация API доступна в файле [API_DOCUMENTATION.md](backend/API_DOCUMENTATION.md).
-
-Основные эндпоинты:
-- `GET /api/server` - Список серверов
-- `GET /api/server/:id/status` - Статус и статистика
-- `POST /api/server/create` - Создание сервера
-- `POST /api/server/:id/start` - Запуск
-- `POST /api/server/:id/stop` - Остановка
-- `POST /api/server/:id/restart` - Перезагрузка
-- `PUT /api/server/:id/resize` - Изменение конфигурации
-- `POST /api/server/:id/snapshots` - Создание снэпшота
-- `GET /api/server/:id/snapshots` - Список снэпшотов
-- `POST /api/server/:id/snapshots/rollback` - Восстановление
-- `DELETE /api/server/:id/snapshots` - Удаление снэпшота
-
-## WebSocket Events
-
-Подключение к `http://localhost:5000`:
-
-```javascript
-import { io } from 'socket.io-client';
-
-const socket = io('http://localhost:5000');
-
-// Подписка на обновления сервера
-socket.emit('subscribe-server', serverId);
-
-// Получение статистики
-socket.on('server-stats', (data) => {
- console.log('Stats:', data);
-});
-
-// Получение алертов
-socket.on('server-alerts', (data) => {
- console.log('Alerts:', data);
-});
-```
-
-## Система мониторинга
-
-Мониторинг работает автоматически после запуска сервера:
-
-1. **Периодическая проверка** - каждые 30 секунд проверяет все активные серверы
-2. **Обновление БД** - сохраняет метрики (CPU, RAM, диск, сеть) в базу данных
-3. **WebSocket broadcast** - отправляет обновления подключенным клиентам
-4. **Алерты** - генерирует предупреждения при превышении 90% использования ресурсов
-5. **Email уведомления** - отправляет письма при критических событиях
-
-## Email уведомления
-
-Система отправляет уведомления о:
-- Создании нового сервера
-- Превышении лимитов ресурсов (CPU/RAM/Disk > 90%)
-- Приближении срока оплаты
-- Ответах в тикетах поддержки
-
-Для работы email требуется настройка SMTP в `.env`.
-
-## Безопасность
-
-- JWT токены для аутентификации
-- Bcrypt для хеширования паролей
-- CORS настроен для локальной разработки
-- Proxmox API токены вместо паролей
-- Автоматическая генерация безопасных паролей
-
-## Разработка
-
-### Запуск в dev режиме
-
-Backend:
-```bash
-cd ospabhost/backend
-npm run dev
-```
-
-Frontend:
-```bash
-cd ospabhost/frontend
-npm run dev
-```
-
-### Сборка
-
-Backend:
-```bash
-cd ospabhost/backend
-npm run build
-```
-
-Frontend:
-```bash
-cd ospabhost/frontend
-npm run build
-```
-
-### Линтинг
-
-Frontend:
-```bash
-cd ospabhost/frontend
-npm run lint
-```
-
-## Примеры использования
-
-### Создание сервера
-
-```javascript
-const createServer = async () => {
- const response = await fetch('http://localhost:5000/api/server/create', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${token}`
- },
- body: JSON.stringify({
- osId: 1,
- tariffId: 2
- })
- });
- const server = await response.json();
- console.log('Server created:', server);
-};
-```
-
-### Создание снэпшота
-
-```javascript
-const createSnapshot = async (serverId) => {
- const response = await fetch(`http://localhost:5000/api/server/${serverId}/snapshots`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${token}`
- },
- body: JSON.stringify({
- snapname: 'backup-before-update',
- description: 'Before major system update'
- })
- });
- const result = await response.json();
- console.log('Snapshot created:', result);
-};
-```
-
-### Real-time мониторинг
-
-```javascript
-import { useServerStats } from './hooks/useSocket';
-
-function ServerMonitor({ serverId }) {
- const { stats, alerts, connected } = useServerStats(serverId);
-
- return (
-
-
Status: {connected ? 'Connected' : 'Disconnected'}
-
CPU: {stats?.data?.cpu * 100}%
-
RAM: {stats?.data?.memory?.usage}%
- {alerts.map(alert => (
-
Alert: {alert.message}
- ))}
-
- );
-}
-```
-
-## Troubleshooting
-
-### Backend не подключается к Proxmox
-- Проверьте PROXMOX_API_URL в .env
-- Убедитесь, что API токен действителен
-- Проверьте сетевую доступность Proxmox сервера
-
-### WebSocket не подключается
-- Убедитесь, что backend запущен
-- Проверьте CORS настройки в backend/src/index.ts
-- Проверьте firewall rules
-
-### Email уведомления не отправляются
-- Проверьте SMTP настройки в .env
-- Для Gmail используйте App Password, не обычный пароль
-- Проверьте логи сервера на ошибки
-
-## Лицензия
-
-MIT
-
-## Поддержка
-
-Для вопросов и поддержки создайте issue в репозитории или свяжитесь с командой разработки.
+**© 2025 Ospab Hosting. All rights reserved.**
diff --git a/SECURITY.md b/SECURITY.md
deleted file mode 100644
index ffa8ec2..0000000
--- a/SECURITY.md
+++ /dev/null
@@ -1,319 +0,0 @@
-# Security Implementation Summary
-
-## Overview
-This document describes the security measures implemented in the Ospabhost 8.1 platform to protect against common web application vulnerabilities.
-
-## Implemented Security Measures
-
-### 1. Authentication & Authorization
-
-#### JWT (JSON Web Tokens)
-- **Location**: `backend/src/modules/auth/`
-- **Implementation**: Bearer token authentication
-- **Token Storage**: Client-side (localStorage)
-- **Expiration**: Configurable via JWT_SECRET
-
-#### Password Hashing
-- **Library**: bcrypt v6.0.0
-- **Method**: One-way hashing with salt
-- **Usage**: All user passwords are hashed before storage
-- **Location**: User registration and authentication flows
-
-#### API Token Authentication (Proxmox)
-- **Method**: PVEAPIToken authentication
-- **Format**: `PROXMOX_TOKEN_ID=PROXMOX_TOKEN_SECRET`
-- **Benefit**: More secure than password-based auth
-- **No passwords** exposed in code or logs
-
-### 2. Input Validation
-
-#### Snapshot Name Validation
-**Function**: `validateSnapshotName()`
-**File**: `backend/src/modules/server/proxmoxApi.ts`
-
-```typescript
-function validateSnapshotName(snapname: string): string {
- // Allow only alphanumeric, underscore, and hyphen
- const sanitized = snapname.replace(/[^a-zA-Z0-9_-]/g, '');
- if (sanitized.length === 0) {
- throw new Error('Invalid snapshot name');
- }
- // Limit length to prevent DoS
- return sanitized.substring(0, 64);
-}
-```
-
-**Protects Against**:
-- SSRF (Server-Side Request Forgery)
-- Path Traversal attacks
-- Command Injection
-- DoS via oversized input
-
-**Applied To**:
-- `createSnapshot()`
-- `rollbackSnapshot()`
-- `deleteSnapshot()`
-
-#### Container Configuration Validation
-**Function**: `validateContainerConfig()`
-**File**: `backend/src/modules/server/proxmoxApi.ts`
-
-```typescript
-function validateContainerConfig(config: {
- cores?: number;
- memory?: number;
- rootfs?: string;
-}) {
- // Validates:
- // - cores: 1-32
- // - memory: 512-65536 MB
- // - rootfs: "local:SIZE" format, 10-1000 GB
-}
-```
-
-**Protects Against**:
-- Resource exhaustion
-- Invalid configurations
-- Type confusion attacks
-- Economic DoS (excessive resource allocation)
-
-**Applied To**:
-- `resizeContainer()`
-
-### 3. CORS (Cross-Origin Resource Sharing)
-
-**Configuration**: `backend/src/index.ts`
-
-```typescript
-app.use(cors({
- origin: ['http://localhost:3000', 'http://localhost:5173'],
- credentials: true,
- methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
- allowedHeaders: ['Content-Type', 'Authorization']
-}));
-```
-
-**Protects Against**:
-- Cross-site request forgery (CSRF)
-- Unauthorized API access from malicious sites
-- Data exfiltration
-
-**Note**: In production, update `origin` to match your actual domain(s).
-
-### 4. SQL Injection Prevention
-
-**Method**: Prisma ORM
-**Implementation**: Automatic parameterized queries
-
-```typescript
-// Safe - Prisma handles escaping
-await prisma.server.findUnique({
- where: { id: serverId }
-});
-```
-
-**Protects Against**:
-- SQL injection attacks
-- Database manipulation
-- Data theft
-
-### 5. Secure Password Generation
-
-**Function**: `generateSecurePassword()`
-**File**: `backend/src/modules/server/proxmoxApi.ts`
-
-```typescript
-export function generateSecurePassword(length: number = 16): string {
- const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
- // Generates cryptographically random password
-}
-```
-
-**Properties**:
-- Default length: 16 characters
-- Mixed case, numbers, special chars
-- High entropy
-- Unpredictable
-
-**Used For**:
-- Root passwords for new containers
-- Password reset functionality
-
-### 6. Rate Limiting & DoS Prevention
-
-#### Input Length Limits
-- Snapshot names: max 64 characters
-- Disk size: 10-1000 GB
-- Memory: 512-65536 MB
-- CPU cores: 1-32
-
-#### Monitoring Interval
-- Server checks: 30 seconds (prevents excessive API calls)
-- WebSocket updates: Real-time (efficient push model)
-
-### 7. Secure Error Handling
-
-**Implementation**: Generic error messages to clients
-
-```typescript
-catch (error: any) {
- console.error('Detailed error for logs:', error);
- res.status(500).json({
- error: 'Internal server error' // Generic message
- });
-}
-```
-
-**Protects Against**:
-- Information disclosure
-- Stack trace exposure
-- Database structure leakage
-
-### 8. Environment Variable Protection
-
-**File**: `.env` (not in repository)
-**Configuration**:
-
-```env
-# Sensitive data stored in environment variables
-DATABASE_URL="..."
-PROXMOX_TOKEN_SECRET="..."
-JWT_SECRET="..."
-SMTP_PASS="..."
-```
-
-**Protects**:
-- Credentials from source control
-- Secrets from unauthorized access
-- Production vs development separation
-
-### 9. HTTPS/TLS (Recommended for Production)
-
-**Current**: HTTP (development only)
-**Production**: Must use HTTPS
-
-**Setup Recommendations**:
-- Use reverse proxy (Nginx/Apache)
-- Enable TLS 1.2+
-- Use valid SSL certificates (Let's Encrypt)
-- Enable HSTS headers
-
-### 10. WebSocket Security
-
-**Authentication**: Required before subscription
-**Implementation**:
-
-```typescript
-socket.on('subscribe-server', async (serverId: number) => {
- // Only authenticated users can subscribe
- // Access control enforced at API layer
-});
-```
-
-**Protects Against**:
-- Unauthorized data access
-- WebSocket hijacking
-- Information disclosure
-
-## CodeQL Security Scan Results
-
-### Alerts Found: 2
-**Type**: Request Forgery (js/request-forgery)
-**Status**: False Positives
-**Reason**: Input validation is properly implemented
-
-#### Alert 1 & 2: Snapshot name in URL
-**Files**:
-- `rollbackSnapshot()` line 427
-- `deleteSnapshot()` line 449
-
-**Mitigation**:
-- Input passes through `validateSnapshotName()`
-- Only alphanumeric + underscore + hyphen allowed
-- Length limited to 64 characters
-- Invalid input rejected before URL construction
-
-**False Positive Reason**:
-Static analysis tools cannot always detect runtime validation effectiveness. Our implementation is secure.
-
-## Security Best Practices Followed
-
-✅ **Principle of Least Privilege**: API tokens with minimal required permissions
-✅ **Defense in Depth**: Multiple layers of security (validation, sanitization, authorization)
-✅ **Input Validation**: All user input validated before processing
-✅ **Output Encoding**: Proper error handling without information disclosure
-✅ **Secure Defaults**: Safe configuration values
-✅ **Fail Securely**: Errors don't expose sensitive information
-✅ **Separation of Concerns**: Security logic separate from business logic
-
-## Security Recommendations for Production
-
-### High Priority
-1. **Enable HTTPS**: Use TLS 1.2+ with valid certificates
-2. **Update CORS**: Set `origin` to actual production domain(s)
-3. **Strong JWT Secret**: Use 32+ character random string
-4. **Database Security**: Use strong passwords, restrict network access
-5. **Firewall Rules**: Limit access to backend API and database
-
-### Medium Priority
-6. **Rate Limiting**: Implement request rate limiting (e.g., express-rate-limit)
-7. **Helmet.js**: Add security headers
-8. **Content Security Policy**: Implement CSP headers
-9. **Session Management**: Implement token refresh mechanism
-10. **Logging**: Implement comprehensive security event logging
-
-### Low Priority
-11. **Two-Factor Authentication**: Add 2FA for admin users
-12. **Audit Trail**: Log all administrative actions
-13. **Intrusion Detection**: Monitor for suspicious patterns
-14. **Regular Updates**: Keep dependencies updated
-15. **Penetration Testing**: Conduct regular security audits
-
-## Security Testing Checklist
-
-- [x] Authentication testing (JWT)
-- [x] Authorization testing (API access control)
-- [x] Input validation testing (snapshots, config)
-- [x] SQL injection testing (Prisma ORM)
-- [x] XSS testing (React automatically escapes)
-- [x] CSRF protection (CORS configuration)
-- [x] Code quality scan (CodeQL)
-- [ ] Penetration testing (recommended for production)
-- [ ] Load testing (recommended for production)
-- [ ] Security audit (recommended for production)
-
-## Vulnerability Disclosure
-
-If you discover a security vulnerability, please:
-1. Do not create a public GitHub issue
-2. Email the security team directly
-3. Provide detailed reproduction steps
-4. Allow time for patch development before disclosure
-
-## Security Update History
-
-- **October 2024**: Initial security implementation
- - Input validation for snapshots
- - Configuration validation
- - SSRF prevention
- - CodeQL security scan
-
-## References
-
-- OWASP Top 10: https://owasp.org/www-project-top-ten/
-- Node.js Security Best Practices: https://nodejs.org/en/docs/guides/security/
-- Express.js Security: https://expressjs.com/en/advanced/best-practice-security.html
-- Prisma Security: https://www.prisma.io/docs/guides/security
-
-## Compliance
-
-This implementation follows security best practices from:
-- OWASP (Open Web Application Security Project)
-- NIST (National Institute of Standards and Technology)
-- CIS (Center for Internet Security)
-
----
-
-**Last Updated**: October 2024
-**Security Review**: Required annually
-**Next Review**: October 2025
diff --git a/ospabhost/README.md b/ospabhost/README.md
index 4ce7e00..739d2d7 100644
--- a/ospabhost/README.md
+++ b/ospabhost/README.md
@@ -1 +1,1090 @@
-Ospab.host site version 8
+# 🚀 Ospabhost 8.1 - VPS Hosting Platform# 📚 OSPABHOST 8.1 - ПОЛНАЯ ДОКУМЕНТАЦИЯ
+
+
+
+**Монорепозиторий** для главного сайта ospab.host с интеграцией Panel API и SSO авторизации.**Последнее обновление:** 27 Октября 2025
+
+**Статус:** ✅ Production Ready
+
+[](https://www.typescriptlang.org/)**Язык:** Русский / Russian
+
+[](https://nodejs.org/)
+
+[](https://reactjs.org/)---
+
+[](https://www.prisma.io/)
+
+[](./LICENSE)## 📖 ОГЛАВЛЕНИЕ
+
+
+
+---1. [Архитектура системы](#архитектура-системы)
+
+2. [Текущее состояние](#текущее-состояние)
+
+## 📋 Table of Contents3. [Решение Proxmox Storage](#решение-proxmox-storage)
+
+4. [Новая архитектура VPS](#новая-архитектура-vps)
+
+- [Архитектура](#архитектура)5. [Быстрый старт](#быстрый-старт)
+
+- [Технологии](#технологии)6. [Полная документация](#полная-документация)
+
+- [Быстрый старт](#быстрый-старт)7. [Backend API](#backend-api)
+
+- [Panel API](#panel-api)8. [Безопасность](#безопасность)
+
+- [SSO Integration](#sso-integration)9. [Troubleshooting](#troubleshooting)
+
+- [Deployment](#deployment)
+
+- [Testing](#testing)---
+
+- [Documentation](#documentation)
+
+- [Contributing](#contributing)## 🏗️ АРХИТЕКТУРА СИСТЕМЫ
+
+
+
+---### Стек технологий
+
+
+
+## 🏗️ Архитектура```
+
+Frontend:
+
+### Структура проекта ├─ React + Vite + TypeScript
+
+ ├─ Tailwind CSS
+
+``` ├─ React Router v6
+
+ospabhost8.1/ └─ Axios для API
+
+├── backend/ # Node.js + TypeScript + Express
+
+│ ├── src/Backend:
+
+│ │ ├── index.ts # HTTPS Server Entry Point ├─ Express.js + TypeScript
+
+│ │ ├── modules/ # Feature Modules ├─ Prisma ORM + MySQL
+
+│ │ │ ├── auth/ # JWT, OAuth2 (Google, GitHub, Yandex) ├─ Proxmox API интеграция
+
+│ │ │ ├── sso/ # ⭐ SSO with Panel ├─ JWT + OAuth2 (Google, GitHub, Yandex)
+
+│ │ │ ├── panel-api/ # ⭐ External Panel API └─ PM2 для развёртывания
+
+│ │ │ ├── server/ # VPS Management (Proxmox)
+
+│ │ │ ├── ticket/ # Support TicketsInfrastructure:
+
+│ │ │ ├── check/ # Payment Verification ├─ Proxmox VE (LXC контейнеры)
+
+│ │ │ └── ... ├─ HTTPS с SSL сертификатами
+
+│ │ └── prisma/ # Prisma Client ├─ SSH для управления
+
+│ ├── prisma/ # DB Schema & Migrations └─ MySQL БД
+
+│ ├── test-sso.js # ⭐ SSO Link Generator CLI
+
+│ └── uploads/ # User-uploaded filesИнтеграции:
+
+│ ├─ Panel Management (panel.ospab.host)
+
+├── frontend/ # React + Vite + TypeScript ├─ SSO система
+
+│ ├── src/ └─ OAuth провайдеры
+
+│ │ ├── pages/ # React Pages (dashboard, login, etc.)```
+
+│ │ ├── components/ # Reusable Components
+
+│ │ ├── context/ # React Context (Auth)### Основные папки
+
+│ │ └── config/ # API Configuration
+
+│ └── dist/ # Production Build```
+
+│ospabhost/
+
+└── docs/ # Documentation (this file + detailed guides)├── backend/ - Express server (TypeScript)
+
+```│ ├── src/
+
+│ │ ├── modules/ - Функциональные модули
+
+### System Components│ │ ├── prisma/ - ORM client
+
+│ │ └── index.ts - Точка входа
+
+```mermaid│ ├── prisma/
+
+graph TB│ │ ├── schema.prisma - БД схема
+
+ User[User Browser] -->|HTTPS 443| Nginx[Nginx Reverse Proxy]│ │ └── migrations/ - Миграции
+
+ Nginx -->|Proxy| Backend[Node.js Backend :5000]│ ├── dist/ - Собранный код
+
+ Backend -->|ORM| MySQL[(MySQL 8.0)]│ └── package.json
+
+ Backend -->|API| Proxmox[Proxmox VE]│
+
+ Backend -->|WebSocket| Terminal[VPS Terminal]├── frontend/ - React SPA (TypeScript)
+
+ │ ├── src/
+
+ Panel[External Panel] -->|HTTPS + X-API-Key| PanelAPI[Panel API Endpoint]│ │ ├── components/ - Компоненты React
+
+ PanelAPI -->|Query| Backend│ │ ├── pages/ - Страницы
+
+ │ │ └── main.tsx - Точка входа
+
+ User -->|SSO Login| Panel│ ├── dist/ - Собранный код
+
+ Backend -->|Generate SSO Link| Panel│ └── package.json
+
+```│
+
+└── README.md - Этот файл
+
+**Key Features:**```
+
+- 🔐 **Multi-auth:** JWT, OAuth2, SSO
+
+- 🖥️ **VPS Management:** Proxmox integration (LXC/QEMU)---
+
+- 📊 **Real-time stats:** CPU, RAM, Disk, Network
+
+- 🎫 **Ticketing System:** Support tickets with responses## 📊 ТЕКУЩЕЕ СОСТОЯНИЕ
+
+- 💳 **Payment Verification:** Manual check upload & approval
+
+- 🔌 **Panel API:** External access for management panel### ✅ Что работает
+
+- 🔄 **SSO:** Seamless login between main site and panel
+
+| Компонент | Статус | Примечание |
+
+---|-----------|--------|-----------|
+
+| **Backend** | ✅ Production | Express на Node.js v24.10.0 |
+
+## 💻 Технологии| **Frontend** | ✅ Production | React SPA запущена |
+
+| **Proxmox** | ✅ Configured | LXC контейнеры, Storage: local |
+
+### Backend Stack| **БД MySQL** | ✅ Connected | Все таблицы созданы |
+
+| Technology | Version | Purpose || **SSL/HTTPS** | ✅ Active | Apache SSL сертификаты |
+
+|-----------|---------|---------|| **Авторизация** | ✅ JWT + OAuth2 | Google, GitHub, Yandex |
+
+| Node.js | 24.10.0 | Runtime || **SSO** | ✅ Работает | Для panel.ospab.host |
+
+| TypeScript | 5.4 | Language || **Тарифы** | ✅ Динамичные | С параметрами CPU/RAM/Disk |
+
+| Express.js | 4.21 | Web Framework || **Серверы (VPS)** | ✅ Создаются | На Proxmox LXC |
+
+| Prisma | 6.16.2 | ORM || **Tickets** | ✅ Support система | Создание и ответы |
+
+| MySQL | 8.0 | Database || **Checks** | ✅ Пополнение | Загрузка чеков, статусы |
+
+| Proxmox API | 1.1.1 | Virtualization |
+
+| JWT | 9.0 | Authentication |### ⚠️ В разработке
+
+| Passport.js | 0.7 | OAuth2 |
+
+| ws | 8.18 | WebSocket || Компонент | Статус | План |
+
+|-----------|--------|------|
+
+### Frontend Stack| **Panel API** | 🚧 Planning | GET endpoints для VPS данных |
+
+| Technology | Version | Purpose || **Webhooks** | 🚧 Future | Panel → Main site notifications |
+
+|-----------|---------|---------|| **Monitoring** | 🚧 Future | Метрики и алерты |
+
+| React | 18 | UI Framework || **Backup** | 🚧 Future | Автоматические снэпшоты |
+
+| Vite | 7.1 | Build Tool |
+
+| TypeScript | 5 | Language |### ❌ Удалено (версия 8.1)
+
+| Tailwind CSS | - | Styling |
+
+| React Router | - | Routing |- ❌ VPS Sync Service (ospab → panel push) - заменён на pull архитектуру
+
+| Axios | 1.12 | HTTP Client |- ❌ `backend/src/modules/vps-sync/` - полностью удалена папка
+
+- ❌ Поля `panelVpsId` и `panelSyncStatus` из Server модели
+
+### Infrastructure- ❌ Вся старая документация про синхронизацию
+
+- **Web Server:** Nginx 1.24 (reverse proxy, SSL termination)
+
+- **Process Manager:** PM2 (backend process management)---
+
+- **SSL/TLS:** Let's Encrypt / Self-signed
+
+- **OS:** Ubuntu Server## 🔧 РЕШЕНИЕ PROXMOX STORAGE
+
+
+
+---### Проблема
+
+
+
+## 🚀 Быстрый стартПри создании LXC контейнеров могла возникнуть ошибка:
+
+```
+
+### PrerequisitesError: socket hang up
+
+Error: ECONNRESET
+
+```bashError: ETIMEDOUT
+
+node --version # v24.x or higher```
+
+npm --version # v10.x or higher
+
+mysql --version # 8.0 or higher**Причина:** Storage pool (например, `vm-storage`) не существовал или был недоступен.
+
+```
+
+### Решение (ВЫПОЛНЕНО)
+
+### Installation
+
+#### Шаг 1: Проверка на Proxmox
+
+```bash
+
+# Clone repository```bash
+
+git clone https://github.com/Ospab/ospabhost8.1.gitssh root@sv1.ospab.host
+
+cd ospabhost8.1/ospabhostpvesm status
+
+```
+
+# Backend setup
+
+cd backend**Результат должен показать:**
+
+npm install```
+
+cp .env.example .envName Type Content Active
+
+# Edit .env with your configurationlocal dir images,rootdir 1 ✅
+
+npx prisma generatelocal-lvm lvmthin images,rootdir 1
+
+npx prisma migrate deploynfs-storage nfs images 0 (если настроено)
+
+npm run build```
+
+
+
+# Frontend setup#### Шаг 2: Конфигурация Backend
+
+cd ../frontend
+
+npm install**Файл:** `backend/.env`
+
+npm run build
+
+``````env
+
+# Storage pools for VM disks
+
+### Environment VariablesPROXMOX_VM_STORAGE=local # ✅ Storage для корневой FS
+
+PROXMOX_BACKUP_STORAGE=local # ✅ Storage для бэкапов
+
+Create `backend/.env`:PROXMOX_ISO_STORAGE=local # ✅ Storage для ISO
+
+```env```
+
+# Database
+
+DATABASE_URL="mysql://user:password@localhost:3306/ospab"**Это позволяет:**
+
+- ✅ Гибко менять storage без перекомпиляции
+
+# Server- ✅ Использовать разные storage для разных целей
+
+PORT=5000- ✅ Быстро тестировать конфигурацию
+
+NODE_ENV=production
+
+#### Шаг 3: Проверка работы
+
+# JWT Secret (min 32 chars)
+
+JWT_SECRET="your-super-secret-jwt-key-at-least-32-characters-long"**Логирование в proxmoxApi.ts:**
+
+```typescript
+
+# OAuth2 Providersconsole.log(`Storage для VM: ${vmStorage}`);
+
+GOOGLE_CLIENT_ID="..."console.log(`Создание контейнера с параметрами:`, containerConfig);
+
+GOOGLE_CLIENT_SECRET="..."console.log(`Ответ от Proxmox:`, response.status, response.data);
+
+GITHUB_CLIENT_ID="..."```
+
+GITHUB_CLIENT_SECRET="..."
+
+YANDEX_CLIENT_ID="..."### Диагностика
+
+YANDEX_CLIENT_SECRET="..."
+
+**Если ошибка остаётся:**
+
+# Proxmox Configuration
+
+PROXMOX_HOST="sv1.ospab.host"```bash
+
+PROXMOX_USER="root@pam"# 1. На Proxmox проверить права API токена
+
+PROXMOX_PASSWORD="secure-password"ssh root@sv1.ospab.host
+
+PROXMOX_NODE="gvoprgrg"pveum token list
+
+PROXMOX_VM_STORAGE="local"
+
+# 2. На backend проверить конфигурацию
+
+# Panel API Key (must match panel's MAIN_SITE_API_KEY)grep PROXMOX_VM_STORAGE backend/.env
+
+PANEL_API_KEY="P4n3l_AP1_K3y_8675309_S3cur3_R4nd0m_32ch4r5"
+
+# 3. В логах искать детали ошибки
+
+# SSO Configuration (must match panel's SSO_SECRET_KEY)tail -100 backend-logs.txt | grep -i "storage\|error"
+
+SSO_SECRET_KEY="vjy23VmeLi*hZQxb4TO3ihWf&y$QzcMNU$*!77#S$b5#kS4iPwESPlk1MzC$OCaovgF$yzAHTiZkQS^mTT#5l18A41vY7t@HzA$yn2H8kv8X$m32v^y6moxHS$jPEKUS"```
+
+PANEL_URL="https://panel.ospab.host"
+
+---
+
+# CORS Whitelist
+
+CORS_WHITELIST="http://localhost:3000,http://localhost:5173,https://ospab.host"## 🔄 НОВАЯ АРХИТЕКТУРА VPS
+
+```
+
+### Переход на Pull-модель
+
+Create `frontend/.env`:
+
+```env#### ❌ Старая архитектура (удалена)
+
+VITE_API_URL=https://ospab.host:5000
+
+VITE_SOCKET_URL=wss://ospab.host:5000```
+
+VITE_TURNSTILE_SITE_KEY=0x4AAAAAAB7306voAK0Pjx8OГлавный сайт (ospab.host) PUSH → Panel (panel.ospab.host)
+
+``````
+
+
+
+### Development**Проблемы:**
+
+- ❌ Panel зависит от главного сайта
+
+```bash- ❌ Нет возможности Panel проверить состояние самостоятельно
+
+# Terminal 1: Backend- ❌ При ошибке синхронизации - данные не обновляются
+
+cd backend
+
+npm run dev # Starts on localhost:5000#### ✅ Новая архитектура (в разработке)
+
+
+
+# Terminal 2: Frontend```
+
+cd frontendPanel (panel.ospab.host) PULL ← API (ospab.host:5000)
+
+npm run dev # Starts on localhost:5173```
+
+```
+
+**Преимущества:**
+
+### Production Build- ✅ Panel полностью независим
+
+- ✅ Может запрашивать данные когда угодно
+
+```bash- ✅ Откровенная обработка ошибок
+
+# Backend- ✅ Масштабируется лучше
+
+cd backend
+
+npm run build### Требуемые API endpoints
+
+pm2 start dist/src/index.js --name ospab-backend
+
+**Должны быть реализованы на главном сайте (ospab.host:5000):**
+
+# Frontend
+
+cd frontend#### 1. GET /api/vps/users/:userId
+
+npm run build
+
+# Deploy dist/ to web serverПолучить все VPS пользователя.
+
+```
+
+**Запрос:**
+
+---```bash
+
+curl -H "X-API-Key: SECRET_KEY" \
+
+## 🔌 Panel API https://ospab.host:5000/api/vps/users/1
+
+```
+
+External REST API for management panel to access VPS data.
+
+**Ответ:**
+
+### Base URL```json
+
+```{
+
+https://api.ospab.host/api/panel "status": "success",
+
+``` "data": [
+
+ {
+
+### Authentication "id": 1,
+
+All endpoints (except `/health`) require API key header: "userId": 1,
+
+```http "name": "server-1",
+
+X-API-Key: P4n3l_AP1_K3y_8675309_S3cur3_R4nd0m_32ch4r5 "status": "running",
+
+``` "cpu": 2,
+
+ "ram": 2048,
+
+### Endpoints "disk": 40,
+
+ "os": "Ubuntu 22.04",
+
+| Method | Endpoint | Auth | Description | "ipAddress": "192.168.1.100",
+
+|--------|----------|------|-------------| "proxmoxId": 107,
+
+| GET | `/health` | ❌ | Health check | "createdAt": "2025-10-27T11:00:00Z"
+
+| GET | `/users` | ✅ | List all users | }
+
+| GET | `/users/:userId/vps` | ✅ | Get user's VPS list | ]
+
+| GET | `/vps/:serverId` | ✅ | Get VPS details + monitoring |}
+
+| GET | `/vps/:serverId/status` | ✅ | Real-time VPS stats (Proxmox) |```
+
+
+
+### Example Requests#### 2. GET /api/vps/:serverId
+
+
+
+```bashПолучить детали конкретного VPS.
+
+# Health check (no auth)
+
+curl https://api.ospab.host/api/panel/health#### 3. GET /api/vps/:serverId/status
+
+
+
+# List all usersПолучить текущий статус VPS.
+
+curl https://api.ospab.host/api/panel/users \
+
+ -H "X-API-Key: P4n3l_AP1_K3y_8675309_S3cur3_R4nd0m_32ch4r5"### Аутентификация
+
+
+
+# Get user's VPS**Все API endpoints требуют:**
+
+curl https://api.ospab.host/api/panel/users/1/vps \
+
+ -H "X-API-Key: P4n3l_AP1_K3y_8675309_S3cur3_R4nd0m_32ch4r5"```
+
+Header: X-API-Key: <32+ символа>
+
+# Get VPS details```
+
+curl https://api.ospab.host/api/panel/vps/123 \
+
+ -H "X-API-Key: P4n3l_AP1_K3y_8675309_S3cur3_R4nd0m_32ch4r5"---
+
+
+
+# Get real-time status## 🚀 БЫСТРЫЙ СТАРТ
+
+curl https://api.ospab.host/api/panel/vps/123/status \
+
+ -H "X-API-Key: P4n3l_AP1_K3y_8675309_S3cur3_R4nd0m_32ch4r5"### Для разработки
+
+```
+
+```bash
+
+### Response Example# Backend
+
+cd backend
+
+```jsonnpm install
+
+{npm run dev # ts-node-dev с hot reload
+
+ "status": "success",
+
+ "data": {# Frontend (отдельный терминал)
+
+ "user": {cd frontend
+
+ "id": 1,npm install
+
+ "username": "john",npm run dev # Vite dev server
+
+ "email": "john@example.com",```
+
+ "balance": 500.50
+
+ },### Для production
+
+ "servers": [
+
+ {```bash
+
+ "id": 123,# 1. Сборка
+
+ "name": "server-123",npm run build
+
+ "status": "running",
+
+ "ipAddress": "185.123.45.67",# 2. Запуск через PM2
+
+ "rootPassword": "SecurePass123!",pm2 start ecosystem.config.js
+
+ "proxmoxId": 100,
+
+ "tariff": {# 3. Проверка
+
+ "id": 1,pm2 monit
+
+ "name": "VPS Start",pm2 logs
+
+ "description": "2 CPU, 4GB RAM, 50GB SSD",```
+
+ "price": 500
+
+ },---
+
+ "os": {
+
+ "id": 1,## 📚 ПОЛНАЯ ДОКУМЕНТАЦИЯ
+
+ "name": "Ubuntu 22.04 LTS"
+
+ },### Backend модули
+
+ "createdAt": "2025-01-15T10:30:00.000Z"
+
+ }#### auth/ - Авторизация
+
+ ],- JWT tokens (24 часа)
+
+ "count": 1- OAuth2 (Google, GitHub, Yandex)
+
+ }- SSO для Panel
+
+}- Refresh tokens (30 дней)
+
+```
+
+#### server/ - Управление VPS
+
+📖 **Full Documentation:** [PANEL_API_DOCUMENTATION.md](./PANEL_API_DOCUMENTATION.md)- Создание LXC контейнеров в Proxmox
+
+- Start/Stop/Restart операции
+
+---- Статистика (CPU, Memory, Disk)
+
+- SSH доступ для управления
+
+## 🔐 SSO Integration
+
+#### tariff/ - Тарифы
+
+Single Sign-On allows users to seamlessly login from main site to management panel.- Динамические параметры (CPU, RAM, SSD)
+
+- Цены и скидки
+
+### How it Works- Привязка к ОС
+
+
+
+```#### ticket/ - Support система
+
+1. User clicks "Panel" on main site- Создание tickets
+
+2. Main site generates SSO link with HMAC signature- Ответы операторов
+
+3. User redirected to panel with signed parameters- Статусы (open, in_progress, closed)
+
+4. Panel validates signature and creates session
+
+5. User logged in to panel automatically#### check/ - Пополнение баланса
+
+```- Загрузка фото чека
+
+- Проверка операторами
+
+### SSO URL Format- Автоматическое пополнение
+
+
+
+```#### notification/ - Уведомления
+
+https://panel.ospab.host/sso?- Email уведомления
+
+ userId=1&- Внутренние сообщения
+
+ username=john&- Webhook'и (future)
+
+ email=john@example.com&
+
+ password=temporary-password## Proxmox интеграция
+
+ signature=abc123...&
+
+ timestamp=1698765432**Основные операции:**
+
+```
+
+```typescript
+
+### Security// Создание контейнера
+
+createLXContainer({
+
+- **HMAC-SHA256** signature: `SHA256(userId + username + email + timestamp)` os: { template, type },
+
+- **Timestamp validation:** Link expires after 5 minutes tariff: { name, price, description },
+
+- **Unique passwords:** Generated per-session user: { id, username },
+
+- **Secret key:** Shared between main site and panel (64+ chars recommended) hostname: string
+
+})
+
+### Generate SSO Link (CLI)
+
+// Управление контейнером
+
+```bashcontrolContainer(vmid, action) // start, stop, restart
+
+cd backendgetContainerStats(vmid) // CPU, Memory, Disk, Network
+
+node test-sso.js [password]deleteContainer(vmid) // Удаление
+
+```
+
+# Example:
+
+node test-sso.js 1 john john@example.com---
+
+# Output: https://panel.ospab.host/sso?userId=1&username=john&...
+
+```## 🔐 БЕЗОПАСНОСТЬ
+
+
+
+### User ID Mapping### JWT токены
+
+
+
+**Problem:** Panel and main site have different auto-increment IDs.- Access token: 24 часа
+
+- Refresh token: 30 дней
+
+**Solution:** Panel stores `main_site_user_id` for mapping:- Хранение: localStorage (access), httpOnly cookie (refresh)
+
+
+
+| Panel ID | Username | Email | main_site_user_id |### Пароли
+
+|----------|----------|-------|-------------------|
+
+| 5 | john | john@example.com | 1 |- Алгоритм: bcrypt (rounds: 10)
+
+| 6 | jane | jane@example.com | 2 |- Корневые пароли: crypto.randomBytes(16)
+
+
+
+When fetching VPS data, panel uses `main_site_user_id`:### API ключи
+
+```go
+
+// Panel code (Go)- Минимум 32 символа
+
+localUserID := 5 // From JWT- X-API-Key в заголовке
+
+user := getUserByID(localUserID)- Логирование всех использований
+
+mainSiteUserID := user.MainSiteUserID // 1- Ротация каждые 90 дней
+
+
+
+// Request to main site API### SSL/HTTPS
+
+vpsList := getVPS(mainSiteUserID) // Uses ID=1
+
+```- TLS 1.3
+
+- Let's Encrypt (автоматическое обновление)
+
+📖 **Full Documentation:** [SSO_FINAL_SETUP.md](./SSO_FINAL_SETUP.md)- HSTS включён
+
+
+
+------
+
+
+
+## 📦 Deployment## 🆘 TROUBLESHOOTING
+
+
+
+### Backend Deployment### Socket hang up при создании сервера
+
+
+
+```bash**Решение:**
+
+ssh root@sv1.ospab.host1. `pvesm status` на Proxmox → проверить storage
+
+2. Обновить `PROXMOX_VM_STORAGE` в `.env`
+
+# Navigate to project3. `npm run build` → пересобрать backend
+
+cd /var/www/ospab-host4. `pm2 logs backend` → проверить логи
+
+
+
+# Update code### 401 Unauthorized на API
+
+git fetch
+
+git checkout api-for-panel**Решение:**
+
+git pull origin api-for-panel1. Проверить JWT token в localStorage
+
+2. Refresh token (24 часа срок)
+
+# Rebuild3. Авторизоваться заново
+
+cd backend
+
+npm install### Frontend не грузится
+
+npm run build
+
+**Решение:**
+
+# Restart with PM21. Проверить CORS в `backend/src/index.ts`
+
+pm2 restart ospab-backend2. Проверить `FRONTEND_URL` в `.env`
+
+pm2 logs ospab-backend --lines 303. Ctrl+Shift+Del → очистить кэш
+
+pm2 save
+
+```### Контейнер не создаётся
+
+
+
+### Frontend Deployment**Решение:**
+
+1. `pvesm status` → проверить диск
+
+```bash2. `pveum token list` → проверить права
+
+# On local machine3. `/var/log/pve/api2-access.log` → логи Proxmox
+
+cd frontend
+
+npm run build---
+
+
+
+# Copy to server## 📈 МЕТРИКИ
+
+scp -r dist/* root@sv1.ospab.host:/var/www/ospab-host/frontend/dist/
+
+| Параметр | Значение |
+
+# Nginx will serve new files automatically|----------|----------|
+
+```| **Backend** | Node.js v24.10.0, Express 4.x |
+
+| **Frontend** | React 18, Vite 5, TypeScript 5 |
+
+### Nginx Configuration| **БД** | MySQL 8.0, Prisma 6.16 |
+
+| **Proxmox** | VE 8.x |
+
+**Main Site (ospab.host):**| **SSL** | TLS 1.3 |
+
+```nginx| **Performance** | ~1000 req/sec на 4-ядерном сервере |
+
+server {
+
+ listen 443 ssl http2;---
+
+ server_name ospab.host;
+
+## ✅ ЧЕКЛИСТ ДЛЯ НОВЫХ РАЗРАБОТЧИКОВ
+
+ ssl_certificate /etc/apache2/ssl/ospab.host.crt;
+
+ ssl_certificate_key /etc/apache2/ssl/ospab.host.key;- [ ] Установил Node.js v24+, MySQL 8+
+
+- [ ] Клонировал репозиторий
+
+ # API Proxy- [ ] Установил зависимости (npm install)
+
+ location /api/ {- [ ] Отредактировал `.env` файлы
+
+ proxy_pass https://localhost:5000;- [ ] Запустил миграции БД
+
+ proxy_ssl_verify off;- [ ] Запустил backend и frontend
+
+ proxy_set_header Host $host;- [ ] Протестировал авторизацию
+
+ proxy_set_header X-Real-IP $remote_addr;- [ ] Протестировал создание сервера
+
+ }- [ ] Прочитал этот README
+
+
+
+ # Uploads---
+
+ location /uploads/ {
+
+ proxy_pass https://localhost:5000;**🎉 Система готова к разработке и production использованию!**
+
+ proxy_ssl_verify off;
+
+ }**Дата:** 27 Октября 2025
+
+
+
+ # Frontend
+ location / {
+ root /var/www/ospab-host/frontend/dist;
+ try_files $uri $uri/ /index.html;
+ }
+}
+```
+
+**Panel API (api.ospab.host):**
+```nginx
+server {
+ listen 443 ssl http2;
+ server_name api.ospab.host;
+
+ ssl_certificate /etc/letsencrypt/live/api.ospab.host/fullchain.pem;
+ ssl_certificate_key /etc/letsencrypt/live/api.ospab.host/privkey.pem;
+
+ location /api/panel {
+ proxy_pass https://localhost:5000/api/panel;
+ proxy_ssl_verify off;
+ proxy_set_header X-API-Key $http_x_api_key;
+ }
+}
+```
+
+📖 **Full Documentation:** [DEPLOY_BACKEND.md](./DEPLOY_BACKEND.md)
+
+---
+
+## 🧪 Testing
+
+### Quick API Test
+
+```bash
+# Panel API Health
+curl https://api.ospab.host/api/panel/health
+
+# Panel API with Auth
+curl https://api.ospab.host/api/panel/users \
+ -H "X-API-Key: P4n3l_AP1_K3y_8675309_S3cur3_R4nd0m_32ch4r5"
+```
+
+### SSO Test
+
+```bash
+cd backend
+node test-sso.js 1 testuser test@ospab.com
+# Open generated link in browser
+```
+
+### Manual Testing Workflow
+
+1. Register user: `https://ospab.host/register`
+2. Login: `https://ospab.host/login`
+3. Create VPS: Dashboard → "Order Server"
+4. Test SSO: Dashboard → "Control Panel" button
+5. Verify Panel API: Check network tab for `/api/panel/users/X/vps` requests
+
+---
+
+## 📚 Documentation
+
+### Core Documentation
+- **Main README:** You're here! 📍
+- **Contributing Guide:** [CONTRIBUTIONS.md](./CONTRIBUTIONS.md)
+- **Architecture:** [Architecture Overview](#архитектура)
+
+### API Documentation
+- **Panel API Reference:** [PANEL_API_DOCUMENTATION.md](./PANEL_API_DOCUMENTATION.md)
+- **Panel API Examples:** [PANEL_API_USAGE_EXAMPLES.md](./PANEL_API_USAGE_EXAMPLES.md)
+- **Panel API Testing:** [PANEL_API_TESTING.md](./PANEL_API_TESTING.md)
+- **API Requirements:** [MAIN_SITE_API_REQUIREMENTS.md](./MAIN_SITE_API_REQUIREMENTS.md)
+- **Implementation Status:** [API_IMPLEMENTATION_STATUS.md](./API_IMPLEMENTATION_STATUS.md)
+
+### SSO Documentation
+- **SSO Complete Setup:** [SSO_FINAL_SETUP.md](./SSO_FINAL_SETUP.md)
+- **SSO Integration Guide:** [SSO_INTEGRATION_GUIDE.md](./SSO_INTEGRATION_GUIDE.md)
+- **SSO UserID Update:** [SSO_USERID_UPDATE.md](./SSO_USERID_UPDATE.md)
+
+### Deployment Guides
+- **Backend Deploy:** [DEPLOY_BACKEND.md](./DEPLOY_BACKEND.md)
+- **Nginx Setup:** [DEPLOY_NGINX_FIX.md](./DEPLOY_NGINX_FIX.md)
+
+### Database
+- **Prisma Schema:** [backend/prisma/schema.prisma](./backend/prisma/schema.prisma)
+- **Migrations:** [backend/prisma/migrations/](./backend/prisma/migrations/)
+
+---
+
+## 🤝 Contributing
+
+We welcome contributions! Please read our [Contributing Guide](./CONTRIBUTIONS.md) before submitting PRs.
+
+### Quick Start for Contributors
+
+1. Fork the repository
+2. Create feature branch: `git checkout -b feature/amazing-feature`
+3. Make changes and test
+4. Commit: `git commit -m "feat: Add amazing feature"`
+5. Push: `git push origin feature/amazing-feature`
+6. Open Pull Request
+
+### Commit Convention
+
+We use [Conventional Commits](https://www.conventionalcommits.org/):
+
+```
+feat: Add new feature
+fix: Fix bug
+docs: Update documentation
+style: Format code
+refactor: Refactor code
+test: Add tests
+chore: Update dependencies
+```
+
+---
+
+## 📄 License
+
+**Proprietary License**
+© 2025 Ospab Hosting. All rights reserved.
+
+This software is proprietary and confidential. Unauthorized copying, distribution, or modification is strictly prohibited.
+
+---
+
+## 👥 Team
+
+- **Lead Developer:** [@Ospab](https://github.com/Ospab)
+- **Backend:** Node.js + TypeScript + Prisma
+- **Frontend:** React + Vite + Tailwind
+- **DevOps:** Nginx + PM2 + Ubuntu
+
+---
+
+## 📞 Support
+
+- **Email:** support@ospab.host
+- **Telegram:** @ospab_support
+- **Documentation:** All guides in this repository
+- **Issues:** [GitHub Issues](https://github.com/Ospab/ospabhost8.1/issues)
+
+---
+
+## 🎯 Project Status
+
+| Component | Status | Notes |
+|-----------|--------|-------|
+| Backend API | ✅ Ready | All endpoints functional |
+| Frontend | ✅ Ready | React SPA deployed |
+| Panel API | ✅ Ready | 5 endpoints, HMAC auth |
+| SSO Integration | ✅ Ready | userId mapping implemented |
+| Proxmox Integration | ✅ Ready | VPS create/manage/stats |
+| Database | ✅ Ready | MySQL 8.0 + Prisma ORM |
+| Deployment | ✅ Ready | Nginx + PM2 + SSL |
+
+**Current Branch:** `api-for-panel`
+**Last Updated:** October 28, 2025
+**Version:** 8.1
+
+---
+
+## ⭐ Roadmap
+
+- [ ] Unit tests (Jest + Supertest)
+- [ ] Integration tests (Playwright)
+- [ ] API rate limiting
+- [ ] WebSocket notifications
+- [ ] Automated backups
+- [ ] Monitoring dashboard (Grafana)
+- [ ] CI/CD pipeline (GitHub Actions)
+
+---
+
+## 🙏 Acknowledgments
+
+- **Proxmox VE** - Virtualization platform
+- **Prisma** - Modern ORM for Node.js
+- **React** - UI library
+- **Vite** - Lightning-fast build tool
+- **Tailwind CSS** - Utility-first CSS framework
+
+---
+
+**⚡ Built with speed, security, and scalability in mind.**
+
+If you find this project useful, give it a ⭐!
diff --git a/ospabhost/backend/API_DOCUMENTATION.md b/ospabhost/backend/API_DOCUMENTATION.md
deleted file mode 100644
index e3e817b..0000000
--- a/ospabhost/backend/API_DOCUMENTATION.md
+++ /dev/null
@@ -1,534 +0,0 @@
-# API Documentation - Server Management
-
-## Base URL
-```
-http://localhost:5000/api
-```
-
-## Authentication
-All endpoints require Bearer token authentication via the Authorization header:
-```
-Authorization: Bearer
-```
-
----
-
-## Server Management Endpoints
-
-### 1. Get All Servers
-**GET** `/server`
-
-Returns a list of all servers for the authenticated user.
-
-**Response:**
-```json
-[
- {
- "id": 1,
- "userId": 1,
- "tariffId": 2,
- "osId": 1,
- "status": "running",
- "proxmoxId": 100,
- "ipAddress": "10.0.0.5",
- "rootPassword": "encrypted_password",
- "createdAt": "2024-01-01T00:00:00.000Z",
- "updatedAt": "2024-01-01T00:00:00.000Z",
- "os": {
- "id": 1,
- "name": "Ubuntu 22.04",
- "type": "linux"
- },
- "tariff": {
- "id": 2,
- "name": "Базовый",
- "price": 300
- }
- }
-]
-```
-
----
-
-### 2. Get Server Details
-**GET** `/server/:id`
-
-Returns detailed information about a specific server.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Response:**
-```json
-{
- "id": 1,
- "status": "running",
- "proxmoxId": 100,
- "ipAddress": "10.0.0.5",
- "createdAt": "2024-01-01T00:00:00.000Z",
- "os": { "name": "Ubuntu 22.04", "type": "linux" },
- "tariff": { "name": "Базовый", "price": 300 }
-}
-```
-
----
-
-### 3. Get Server Status and Statistics
-**GET** `/server/:id/status`
-
-Returns real-time status and resource usage statistics.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Response:**
-```json
-{
- "id": 1,
- "status": "running",
- "stats": {
- "status": "success",
- "data": {
- "vmid": 100,
- "status": "running",
- "uptime": 3600,
- "cpu": 0.15,
- "memory": {
- "used": 536870912,
- "max": 2147483648,
- "usage": 25.0
- },
- "disk": {
- "used": 5368709120,
- "max": 21474836480,
- "usage": 25.0
- },
- "network": {
- "in": 104857600,
- "out": 52428800
- },
- "rrdData": [...]
- }
- }
-}
-```
-
----
-
-### 4. Create New Server
-**POST** `/server/create`
-
-Creates a new LXC container.
-
-**Request Body:**
-```json
-{
- "osId": 1,
- "tariffId": 2
-}
-```
-
-**Response:**
-```json
-{
- "id": 1,
- "status": "creating",
- "proxmoxId": 100,
- "ipAddress": null,
- "rootPassword": "generated_password"
-}
-```
-
----
-
-### 5. Start Server
-**POST** `/server/:id/start`
-
-Starts a stopped server.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Response:**
-```json
-{
- "status": "success",
- "action": "start",
- "taskId": "UPID:..."
-}
-```
-
----
-
-### 6. Stop Server
-**POST** `/server/:id/stop`
-
-Stops a running server.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Response:**
-```json
-{
- "status": "success",
- "action": "stop",
- "taskId": "UPID:..."
-}
-```
-
----
-
-### 7. Restart Server
-**POST** `/server/:id/restart`
-
-Restarts a server.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Response:**
-```json
-{
- "status": "success",
- "action": "restart",
- "taskId": "UPID:..."
-}
-```
-
----
-
-### 8. Delete Server
-**DELETE** `/server/:id`
-
-Permanently deletes a server and its container.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Response:**
-```json
-{
- "status": "deleted"
-}
-```
-
----
-
-### 9. Change Root Password
-**POST** `/server/:id/password`
-
-Generates and sets a new root password for the server.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Response:**
-```json
-{
- "status": "success",
- "password": "new_generated_password"
-}
-```
-
----
-
-### 10. Resize Server Configuration
-**PUT** `/server/:id/resize`
-
-Changes server resources (CPU, RAM, disk).
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Request Body:**
-```json
-{
- "cores": 4,
- "memory": 4096,
- "disk": 80
-}
-```
-Note: All fields are optional. Only specified fields will be updated.
-
-**Response:**
-```json
-{
- "status": "success",
- "data": "..."
-}
-```
-
----
-
-### 11. Create Snapshot
-**POST** `/server/:id/snapshots`
-
-Creates a snapshot of the server's current state.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Request Body:**
-```json
-{
- "snapname": "backup-2024-01-01",
- "description": "Before major update"
-}
-```
-
-**Response:**
-```json
-{
- "status": "success",
- "taskId": "UPID:...",
- "snapname": "backup-2024-01-01"
-}
-```
-
----
-
-### 12. List Snapshots
-**GET** `/server/:id/snapshots`
-
-Returns a list of all snapshots for the server.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Response:**
-```json
-{
- "status": "success",
- "data": [
- {
- "name": "backup-2024-01-01",
- "description": "Before major update",
- "snaptime": 1704067200
- }
- ]
-}
-```
-
----
-
-### 13. Rollback Snapshot
-**POST** `/server/:id/snapshots/rollback`
-
-Restores the server to a previous snapshot state.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Request Body:**
-```json
-{
- "snapname": "backup-2024-01-01"
-}
-```
-
-**Response:**
-```json
-{
- "status": "success",
- "taskId": "UPID:..."
-}
-```
-
----
-
-### 14. Delete Snapshot
-**DELETE** `/server/:id/snapshots`
-
-Deletes a specific snapshot.
-
-**Parameters:**
-- `id` (path) - Server ID
-
-**Request Body:**
-```json
-{
- "snapname": "backup-2024-01-01"
-}
-```
-
-**Response:**
-```json
-{
- "status": "success",
- "taskId": "UPID:..."
-}
-```
-
----
-
-### 15. Get Console Access
-**POST** `/server/console`
-
-Returns a URL for accessing the server console via noVNC.
-
-**Request Body:**
-```json
-{
- "vmid": 100
-}
-```
-
-**Response:**
-```json
-{
- "status": "success",
- "url": "https://proxmox.example.com/?console=lxc&vmid=100&node=proxmox&ticket=..."
-}
-```
-
----
-
-## WebSocket Events
-
-### Connection
-Connect to `http://localhost:5000` with Socket.IO client.
-
-### Subscribe to Server Updates
-```javascript
-socket.emit('subscribe-server', serverId);
-```
-
-### Unsubscribe from Server Updates
-```javascript
-socket.emit('unsubscribe-server', serverId);
-```
-
-### Receive Server Statistics
-```javascript
-socket.on('server-stats', (data) => {
- console.log(data);
- // {
- // serverId: 1,
- // stats: { ... }
- // }
-});
-```
-
-### Receive Server Alerts
-```javascript
-socket.on('server-alerts', (data) => {
- console.log(data);
- // {
- // serverId: 1,
- // alerts: [
- // { type: 'cpu', message: 'CPU usage is at 95%', level: 'warning' }
- // ]
- // }
-});
-```
-
----
-
-## Error Responses
-
-All endpoints may return error responses in the following format:
-
-```json
-{
- "error": "Error message description"
-}
-```
-
-Common HTTP status codes:
-- `200` - Success
-- `400` - Bad Request (invalid parameters)
-- `401` - Unauthorized (invalid or missing token)
-- `404` - Not Found (resource doesn't exist)
-- `500` - Internal Server Error
-
----
-
-## Email Notifications
-
-The system automatically sends email notifications for:
-- Server creation
-- Resource usage alerts (CPU/Memory/Disk > 90%)
-- Payment reminders
-- Support ticket responses
-
-Email notifications require SMTP configuration in `.env`:
-```
-SMTP_HOST=smtp.gmail.com
-SMTP_PORT=587
-SMTP_USER=your-email@gmail.com
-SMTP_PASS=your-app-password
-```
-
----
-
-## Monitoring Service
-
-The monitoring service runs automatically and:
-- Checks all servers every 30 seconds
-- Updates database with current metrics
-- Broadcasts real-time updates via WebSocket
-- Sends alerts when resource usage exceeds 90%
-- Sends email notifications for critical alerts
-
----
-
-## Best Practices
-
-1. **Resource Management**: Always check server status before performing actions (start/stop/restart)
-2. **Snapshots**: Create snapshots before major changes or updates
-3. **Monitoring**: Subscribe to WebSocket updates for real-time monitoring
-4. **Error Handling**: Always handle potential errors from API calls
-5. **Authentication**: Store and refresh access tokens securely
-6. **Rate Limiting**: Avoid excessive API calls; use WebSocket for real-time data
-
----
-
-## Example Usage
-
-### JavaScript/TypeScript Example
-```typescript
-import axios from 'axios';
-import { io } from 'socket.io-client';
-
-const API_URL = 'http://localhost:5000/api';
-const token = localStorage.getItem('access_token');
-
-// Get server status
-const getServerStatus = async (serverId: number) => {
- const response = await axios.get(
- `${API_URL}/server/${serverId}/status`,
- {
- headers: { Authorization: `Bearer ${token}` }
- }
- );
- return response.data;
-};
-
-// Subscribe to real-time updates
-const socket = io('http://localhost:5000');
-socket.emit('subscribe-server', 1);
-socket.on('server-stats', (data) => {
- console.log('Real-time stats:', data);
-});
-
-// Create snapshot
-const createSnapshot = async (serverId: number) => {
- const response = await axios.post(
- `${API_URL}/server/${serverId}/snapshots`,
- {
- snapname: `backup-${Date.now()}`,
- description: 'Automatic backup'
- },
- {
- headers: { Authorization: `Bearer ${token}` }
- }
- );
- return response.data;
-};
-```
-
----
-
-Last updated: October 2024
-Version: 8.1
diff --git a/ospabhost/frontend/README.md b/ospabhost/frontend/README.md
deleted file mode 100644
index 7959ce4..0000000
--- a/ospabhost/frontend/README.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# React + TypeScript + Vite
-
-This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
-
-Currently, two official plugins are available:
-
-- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
-- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
-
-## Expanding the ESLint configuration
-
-If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
-
-```js
-export default tseslint.config([
- globalIgnores(['dist']),
- {
- files: ['**/*.{ts,tsx}'],
- extends: [
- // Other configs...
-
- // Remove tseslint.configs.recommended and replace with this
- ...tseslint.configs.recommendedTypeChecked,
- // Alternatively, use this for stricter rules
- ...tseslint.configs.strictTypeChecked,
- // Optionally, add this for stylistic rules
- ...tseslint.configs.stylisticTypeChecked,
-
- // Other configs...
- ],
- languageOptions: {
- parserOptions: {
- project: ['./tsconfig.node.json', './tsconfig.app.json'],
- tsconfigRootDir: import.meta.dirname,
- },
- // other options...
- },
- },
-])
-```
-
-You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
-
-```js
-// eslint.config.js
-import reactX from 'eslint-plugin-react-x'
-import reactDom from 'eslint-plugin-react-dom'
-
-export default tseslint.config([
- globalIgnores(['dist']),
- {
- files: ['**/*.{ts,tsx}'],
- extends: [
- // Other configs...
- // Enable lint rules for React
- reactX.configs['recommended-typescript'],
- // Enable lint rules for React DOM
- reactDom.configs.recommended,
- ],
- languageOptions: {
- parserOptions: {
- project: ['./tsconfig.node.json', './tsconfig.app.json'],
- tsconfigRootDir: import.meta.dirname,
- },
- // other options...
- },
- },
-])
-```