docs: Clean up documentation structure
- Removed 24 outdated documentation files from root - Created simple navigation README in root - All comprehensive documentation now in ospabhost/ directory: - ospabhost/README.md - complete project docs - ospabhost/CONTRIBUTIONS.md - contributor guide - Keeps project structure clean and organized
This commit is contained in:
291
ARCHITECTURE.md
291
ARCHITECTURE.md
@@ -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 логи
|
||||
@@ -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
|
||||
368
README.md
368
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 (
|
||||
<div>
|
||||
<div>Status: {connected ? 'Connected' : 'Disconnected'}</div>
|
||||
<div>CPU: {stats?.data?.cpu * 100}%</div>
|
||||
<div>RAM: {stats?.data?.memory?.usage}%</div>
|
||||
{alerts.map(alert => (
|
||||
<div key={alert.type}>Alert: {alert.message}</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 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.**
|
||||
|
||||
319
SECURITY.md
319
SECURITY.md
@@ -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
|
||||
1091
ospabhost/README.md
1091
ospabhost/README.md
File diff suppressed because it is too large
Load Diff
@@ -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 <access_token>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
@@ -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...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
Reference in New Issue
Block a user