ssh! и документы

This commit is contained in:
Georgiy Syralev
2025-10-12 15:20:39 +03:00
parent 141955dd46
commit 4211692312
50 changed files with 920 additions and 1333 deletions

View File

@@ -1,27 +1,31 @@
# Copilot Instructions for Ospabhost 8.1
## Архитектура проекта
- **Монорепозиторий**: две основные части — `backend` (Express, TypeScript, Prisma) и `frontend` (React, Vite, TypeScript).
## Архитектура и основные компоненты
- **Монорепозиторий**: две части — `backend` (Express, TypeScript, Prisma) и `frontend` (React, Vite, TypeScript).
- **Backend**:
- Основной сервер: `backend/src/index.ts` — точка входа, маршрутизация, CORS, логирование.
- Модули: `backend/src/modules/*` бизнес-логика по доменам (auth, ticket, check, os, server, tariff).
- Интеграция с Proxmox: через API, см. `backend/src/modules/server/proxmoxApi.ts`.
- ORM: Prisma, схема — `backend/prisma/schema.prisma`.
- Статические файлы чеков: `backend/uploads/checks`.
- Точка входа: `backend/src/index.ts` (Express, маршруты `/api/*`, CORS, логирование).
- Модули: `backend/src/modules/*` — домены (auth, ticket, check, os, server, tariff), каждый экспортирует маршруты и сервисы.
- Интеграция с Proxmox: через API, см. `backend/src/modules/server/proxmoxApi.ts` (создание/управление контейнерами, смена пароля root, статистика).
- ORM: Prisma, схема — `backend/prisma/schema.prisma`, миграции и seed-скрипты — в `backend/prisma/`.
- Статические файлы чеков: `backend/uploads/checks` (доступны по `/uploads/checks`).
- **Frontend**:
- SPA на React + Vite, точка входа: `frontend/src/main.tsx`.
- Страницы: `frontend/src/pages/*`, компоненты: `frontend/src/components/*`.
- Контекст авторизации: `frontend/src/context/authcontext.tsx`, `useAuth.ts`.
- Авторизация: `frontend/src/context/authcontext.tsx`, `useAuth.ts` (контекст, хуки).
- Дашборд: `frontend/src/pages/dashboard/mainpage.tsx` — реализует сайдбар, вкладки, загрузку данных пользователя, обработку токена, обновление данных через кастомное событие `userDataUpdate`.
## Важные паттерны и конвенции
- **Маршруты API**: начинаются с `/api/`, см. `backend/src/index.ts`.
- **Модули backend**: каждый домен — отдельная папка, экспортирует маршруты и сервисы.
- **Работа с Proxmox**: все операции (создание контейнера, управление, статистика) через функции из `proxmoxApi.ts`.
- **Статусные поля**: для сущностей (Server, Check, Ticket) используются строковые статусы (`creating`, `running`, `pending`, `open` и т.д.).
## Ключевые паттерны и конвенции
- **API**: все маршруты backend — с префиксом `/api/`.
- **Модули backend**: каждый домен — отдельная папка, экспортирует маршруты и сервисы (см. пример: `server/proxmoxApi.ts`).
- **Работа с Proxmox**: все операции через функции из `proxmoxApi.ts`, параметры берутся из `.env`.
- **Статусные поля**: для Server, Check, Ticket строковые статусы (`creating`, `running`, `pending`, `open` и др.).
- **Пароли**: генерируются через `generateSecurePassword` (см. `proxmoxApi.ts`).
- **Описание тарифа**: парсится для выделения ресурсов (ядра, RAM, SSD) при создании контейнера.
- **Frontend**: авторизация через контекст, проверка токена, автоматический logout при ошибке 401.
- **Дашборд**: вкладки и права оператора определяются по полю `operator` в userData, обновление данных через событие `userDataUpdate`.
## Сборка и запуск
## Сборка, запуск и workflow
- **Backend**:
- `npm run dev` — запуск с hot-reload (ts-node-dev).
- `npm run build` — компиляция TypeScript.
@@ -32,9 +36,9 @@
- `npm run preview` — предпросмотр production-сборки.
- `npm run lint` — проверка ESLint.
## Взаимодействие компонентов
- **Frontend ↔ Backend**: через REST API, адреса `/api/*`.
- **Backend ↔ Proxmox**: через HTTP API, параметры берутся из `.env`.
## Интеграции и взаимодействие
- **Frontend ↔ Backend**: через REST API (`/api/*`), авторизация через JWT-токен в localStorage.
- **Backend ↔ Proxmox**: через HTTP API, параметры из `.env`.
- **Prisma**: миграции и seed-скрипты — в `backend/prisma/`.
## Внешние зависимости
@@ -45,15 +49,16 @@
- `backend/src/index.ts` — точка входа, маршрутизация.
- `backend/src/modules/server/proxmoxApi.ts` — интеграция с Proxmox.
- `backend/prisma/schema.prisma` — схема данных.
- `frontend/src/pages/*` — страницы SPA.
- `frontend/src/pages/dashboard/mainpage.tsx` — дашборд, обработка токена, сайдбар, вкладки.
- `frontend/src/context/authcontext.tsx` — авторизация.
## Особенности
## Особенности и conventions
- **CORS**: разрешены только локальные адреса для разработки.
- **Логирование**: каждый запрос логируется с датой и методом.
- **Статические файлы**: чеки доступны по `/uploads/checks`.
- **Пароли root**: генерируются и меняются через API Proxmox.
- **Frontend**: сайдбар и вкладки строятся динамически, права оператора определяются по userData.
---
_Обновите этот файл при изменении архитектуры или ключевых паттернов. Для уточнения разделов — дайте обратную связь!_
_Обновляйте этот файл при изменении архитектуры, workflow или паттернов. Для уточнения разделов — дайте обратную связь!_

21
node_modules/.package-lock.json generated vendored
View File

@@ -2606,6 +2606,18 @@
"node": ">= 0.6.0"
}
},
"node_modules/proxmox-api": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/proxmox-api/-/proxmox-api-1.1.1.tgz",
"integrity": "sha512-2qH7pxKBBHa7WtEBmxPaBY2FZEH2R04hqr9zD9PmErLzJ7RGGcfNcXoS/v5G4vBM2Igmnx0EAYBstPwwfDwHnA==",
"license": "GPL-3.0",
"dependencies": {
"undici": "^6.19.8"
},
"funding": {
"url": "https://github.com/sponsors/urielch"
}
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -3450,6 +3462,15 @@
"node": ">=14.17"
}
},
"node_modules/undici": {
"version": "6.22.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.22.0.tgz",
"integrity": "sha512-hU/10obOIu62MGYjdskASR3CUAiYaFTtC9Pa6vHyf//mAipSvSQg6od2CnJswq7fvzNS3zJhxoRkgNVaHurWKw==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "7.11.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.11.0.tgz",

1
ospabhost/README.md Normal file
View File

@@ -0,0 +1 @@
Ospab.host site version 8

View File

@@ -10,6 +10,8 @@
"license": "ISC",
"dependencies": {
"@prisma/client": "^6.16.2",
"@types/ssh2": "^1.15.5",
"@types/ws": "^8.18.1",
"axios": "^1.12.2",
"bcrypt": "^6.0.0",
"bcryptjs": "^2.4.3",
@@ -18,8 +20,10 @@
"express": "^4.21.2",
"jsonwebtoken": "^9.0.2",
"multer": "^2.0.2",
"nodemailer": "^6.9.16",
"socket.io": "^4.8.1"
"proxmox-api": "^1.1.1",
"ssh2": "^1.17.0",
"ws": "^8.18.3",
"xterm": "^5.3.0"
},
"devDependencies": {
"@types/bcrypt": "^6.0.0",
@@ -29,7 +33,7 @@
"@types/jsonwebtoken": "^9.0.10",
"@types/multer": "^2.0.0",
"@types/node": "^20.12.12",
"@types/nodemailer": "^6.4.17",
"@types/xterm": "^2.0.3",
"prisma": "^6.16.2",
"ts-node-dev": "^2.0.0",
"typescript": "^5.4.5"
@@ -161,12 +165,6 @@
"@prisma/debug": "6.16.2"
}
},
"node_modules/@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"license": "MIT"
},
"node_modules/@standard-schema/spec": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",
@@ -244,6 +242,7 @@
"version": "2.8.19",
"resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz",
"integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
@@ -326,16 +325,6 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/nodemailer": {
"version": "6.4.17",
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.17.tgz",
"integrity": "sha512-I9CCaIp6DTldEg7vyUTZi8+9Vo0hi1/T8gv3C89yk1rSAAzoKQ8H8ki/jBYJSFoH/BisgLP8tkZMlQ91CIquww==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/qs": {
"version": "6.14.0",
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz",
@@ -373,6 +362,30 @@
"@types/send": "*"
}
},
"node_modules/@types/ssh2": {
"version": "1.15.5",
"resolved": "https://registry.npmjs.org/@types/ssh2/-/ssh2-1.15.5.tgz",
"integrity": "sha512-N1ASjp/nXH3ovBHddRJpli4ozpk6UdDYIX4RJWFa9L1YKnzdhTlVmiGHm4DZnj/jLbqZpes4aeR30EFGQtvhQQ==",
"license": "MIT",
"dependencies": {
"@types/node": "^18.11.18"
}
},
"node_modules/@types/ssh2/node_modules/@types/node": {
"version": "18.19.127",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.127.tgz",
"integrity": "sha512-gSjxjrnKXML/yo0BO099uPixMqfpJU0TKYjpfLU7TrtA2WWDki412Np/RSTPRil1saKBhvVVKzVx/p/6p94nVA==",
"license": "MIT",
"dependencies": {
"undici-types": "~5.26.4"
}
},
"node_modules/@types/ssh2/node_modules/undici-types": {
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
"license": "MIT"
},
"node_modules/@types/strip-bom": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@types/strip-bom/-/strip-bom-3.0.0.tgz",
@@ -387,6 +400,22 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/xterm": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@types/xterm/-/xterm-2.0.3.tgz",
"integrity": "sha512-Owlz29ThHtn2RQry87juaNYeIc4Dr8ykLLX0JKKt4SdO6ujwJnsXCpBAr6bwo/f4L3xSfM9KA7OnPPf9Xit6tA==",
"dev": true,
"license": "MIT"
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
@@ -459,6 +488,15 @@
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/asn1": {
"version": "0.2.6",
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": "~2.1.0"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -483,15 +521,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/base64id": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz",
"integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==",
"license": "MIT",
"engines": {
"node": "^4.5.0 || >= 5.9"
}
},
"node_modules/bcrypt": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-6.0.0.tgz",
@@ -506,6 +535,15 @@
"node": ">= 18"
}
},
"node_modules/bcrypt-pbkdf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
"license": "BSD-3-Clause",
"dependencies": {
"tweetnacl": "^0.14.3"
}
},
"node_modules/bcryptjs": {
"version": "2.4.3",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",
@@ -585,6 +623,15 @@
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/buildcheck": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.6.tgz",
"integrity": "sha512-8f9ZJCUXyT1M35Jx7MkBgmBMo3oHTTBIPLiY9xyL0pl3T5RwcPEY8cUHr5LBNfu/fk6c2T4DJZuVM/8ZZT2D2A==",
"optional": true,
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
@@ -789,6 +836,20 @@
"node": ">= 0.10"
}
},
"node_modules/cpu-features": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
"integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
"hasInstallScript": true,
"optional": true,
"dependencies": {
"buildcheck": "~0.0.6",
"nan": "^2.19.0"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/create-require": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
@@ -948,67 +1009,6 @@
"node": ">= 0.8"
}
},
"node_modules/engine.io": {
"version": "6.6.4",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.4.tgz",
"integrity": "sha512-ZCkIjSYNDyGn0R6ewHDtXgns/Zre/NT6Agvq1/WobF7JXgFff4SeDroKiCO3fNJreU9YG429Sc81o4w5ok/W5g==",
"license": "MIT",
"dependencies": {
"@types/cors": "^2.8.12",
"@types/node": ">=10.0.0",
"accepts": "~1.3.4",
"base64id": "2.0.0",
"cookie": "~0.7.2",
"cors": "~2.8.5",
"debug": "~4.3.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.17.1"
},
"engines": {
"node": ">=10.2.0"
}
},
"node_modules/engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/engine.io/node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/engine.io/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/engine.io/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -1767,6 +1767,13 @@
"mkdirp": "bin/cmd.js"
}
},
"node_modules/nan": {
"version": "2.23.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.23.0.tgz",
"integrity": "sha512-1UxuyYGdoQHcGg87Lkqm3FzefucTa0NAiOcuRsDmysep3c1LVCRK2krrUDafMWtjSG04htvAmvg96+SDknOmgQ==",
"license": "MIT",
"optional": true
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
@@ -1803,15 +1810,6 @@
"node-gyp-build-test": "build-test.js"
}
},
"node_modules/nodemailer": {
"version": "6.9.16",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.16.tgz",
"integrity": "sha512-psAuZdTIRN08HKVd/E8ObdV6NO7NTBY3KsC30F7M4H1OnmLCUNaS56FpYxyb26zWLSyYF9Ozch9KYHhHegsiOQ==",
"license": "MIT-0",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/normalize-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
@@ -1989,6 +1987,18 @@
}
}
},
"node_modules/proxmox-api": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/proxmox-api/-/proxmox-api-1.1.1.tgz",
"integrity": "sha512-2qH7pxKBBHa7WtEBmxPaBY2FZEH2R04hqr9zD9PmErLzJ7RGGcfNcXoS/v5G4vBM2Igmnx0EAYBstPwwfDwHnA==",
"license": "GPL-3.0",
"dependencies": {
"undici": "^6.19.8"
},
"funding": {
"url": "https://github.com/sponsors/urielch"
}
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -2308,116 +2318,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/socket.io": {
"version": "4.8.1",
"resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.1.tgz",
"integrity": "sha512-oZ7iUCxph8WYRHHcjBEc9unw3adt5CmSNlppj/5Q4k2RIrhl8Z5yY2Xr4j9zj0+wzVZ0bxmYoGSzKJnRl6A4yg==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.4",
"base64id": "~2.0.0",
"cors": "~2.8.5",
"debug": "~4.3.2",
"engine.io": "~6.6.0",
"socket.io-adapter": "~2.5.2",
"socket.io-parser": "~4.2.4"
},
"engines": {
"node": ">=10.2.0"
}
},
"node_modules/socket.io-adapter": {
"version": "2.5.5",
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.5.tgz",
"integrity": "sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==",
"license": "MIT",
"dependencies": {
"debug": "~4.3.4",
"ws": "~8.17.1"
}
},
"node_modules/socket.io-adapter/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/socket.io-adapter/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/socket.io-parser": {
"version": "4.2.4",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
"integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-parser/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/socket.io-parser/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/socket.io/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/socket.io/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
@@ -2439,6 +2339,23 @@
"source-map": "^0.6.0"
}
},
"node_modules/ssh2": {
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
"integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
"hasInstallScript": true,
"dependencies": {
"asn1": "^0.2.6",
"bcrypt-pbkdf": "^1.0.2"
},
"engines": {
"node": ">=10.16.0"
},
"optionalDependencies": {
"cpu-features": "~0.0.10",
"nan": "^2.23.0"
}
},
"node_modules/statuses": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
@@ -2667,6 +2584,12 @@
"strip-json-comments": "^2.0.0"
}
},
"node_modules/tweetnacl": {
"version": "0.14.5",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
"license": "Unlicense"
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
@@ -2700,6 +2623,15 @@
"node": ">=14.17"
}
},
"node_modules/undici": {
"version": "6.22.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.22.0.tgz",
"integrity": "sha512-hU/10obOIu62MGYjdskASR3CUAiYaFTtC9Pa6vHyf//mAipSvSQg6od2CnJswq7fvzNS3zJhxoRkgNVaHurWKw==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
@@ -2754,9 +2686,9 @@
"license": "ISC"
},
"node_modules/ws": {
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
"integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
"version": "8.18.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
@@ -2783,6 +2715,13 @@
"node": ">=0.4"
}
},
"node_modules/xterm": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/xterm/-/xterm-5.3.0.tgz",
"integrity": "sha512-8QqjlekLUFTrU6x7xck1MsPzPA571K5zNqWm0M0oroYEWVOptZ0+ubQSkQ3uxIEhcIHRujJy6emDWX4A7qyFzg==",
"deprecated": "This package is now deprecated. Move to @xterm/xterm instead.",
"license": "MIT"
},
"node_modules/yn": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",

View File

@@ -5,7 +5,7 @@
"main": "dist/index.js",
"scripts": {
"dev": "ts-node-dev --respawn --transpile-only src/index.ts",
"start": "node dist/index.js",
"start": "node dist/src/index.js",
"build": "tsc"
},
"keywords": [],
@@ -13,6 +13,8 @@
"license": "ISC",
"dependencies": {
"@prisma/client": "^6.16.2",
"@types/ssh2": "^1.15.5",
"@types/ws": "^8.18.1",
"axios": "^1.12.2",
"bcrypt": "^6.0.0",
"bcryptjs": "^2.4.3",
@@ -21,8 +23,10 @@
"express": "^4.21.2",
"jsonwebtoken": "^9.0.2",
"multer": "^2.0.2",
"nodemailer": "^6.9.16",
"socket.io": "^4.8.1"
"proxmox-api": "^1.1.1",
"ssh2": "^1.17.0",
"ws": "^8.18.3",
"xterm": "^5.3.0"
},
"devDependencies": {
"@types/bcrypt": "^6.0.0",
@@ -32,7 +36,7 @@
"@types/jsonwebtoken": "^9.0.10",
"@types/multer": "^2.0.0",
"@types/node": "^20.12.12",
"@types/nodemailer": "^6.4.17",
"@types/xterm": "^2.0.3",
"prisma": "^6.16.2",
"ts-node-dev": "^2.0.0",
"typescript": "^5.4.5"

View File

@@ -17,8 +17,12 @@ model Tariff {
description String?
createdAt DateTime @default(now())
servers Server[]
@@map("tariff")
}
model OperatingSystem {
id Int @id @default(autoincrement())
name String @unique
@@ -26,6 +30,8 @@ model OperatingSystem {
template String? // путь к шаблону для контейнера
createdAt DateTime @default(now())
servers Server[]
@@map("operatingsystem")
}
model Server {
@@ -60,6 +66,8 @@ model Server {
diskUsage Float? @default(0)
networkIn Float? @default(0)
networkOut Float? @default(0)
@@map("server")
}
model User {
@@ -76,6 +84,8 @@ model User {
balance Float @default(0)
servers Server[]
notifications Notification[]
@@map("user")
}
model Check {
@@ -86,6 +96,8 @@ model Check {
fileUrl String
createdAt DateTime @default(now())
user User @relation("UserChecks", fields: [userId], references: [id])
@@map("check")
}
model Plan {
@@ -98,6 +110,8 @@ model Plan {
userId Int
owner User @relation("UserPlans", fields: [userId], references: [id])
services Service[] @relation("PlanServices")
@@map("plan")
}
model Service {
@@ -106,6 +120,8 @@ model Service {
price Float
planId Int?
plan Plan? @relation("PlanServices", fields: [planId], references: [id])
@@map("service")
}
model Ticket {
@@ -118,6 +134,8 @@ model Ticket {
updatedAt DateTime @updatedAt
responses Response[] @relation("TicketResponses")
user User? @relation("UserTickets", fields: [userId], references: [id])
@@map("ticket")
}
model Response {
@@ -128,6 +146,10 @@ model Response {
createdAt DateTime @default(now())
ticket Ticket @relation("TicketResponses", fields: [ticketId], references: [id])
operator User @relation("OperatorResponses", fields: [operatorId], references: [id])
@@map("response")
}
model Notification {
id Int @id @default(autoincrement())
@@ -136,4 +158,6 @@ model Notification {
title String
message String
createdAt DateTime @default(now())
@@map("notification")
}

View File

@@ -43,3 +43,4 @@ export async function createContainer({ vmid, hostname, password, ostemplate, st
throw new Error('Ошибка создания контейнера: ' + (err instanceof Error ? err.message : err));
}
}

View File

@@ -1,8 +1,6 @@
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import http from 'http';
import { Server as SocketIOServer } from 'socket.io';
import authRoutes from './modules/auth/auth.routes';
import ticketRoutes from './modules/ticket/ticket.routes';
import checkRoutes from './modules/check/check.routes';
@@ -10,25 +8,18 @@ import proxmoxRoutes from '../proxmox/proxmox.routes';
import tariffRoutes from './modules/tariff';
import osRoutes from './modules/os';
import serverRoutes from './modules/server';
import { MonitoringService } from './modules/server/monitoring.service';
dotenv.config();
const app = express();
const server = http.createServer(app);
// Настройка Socket.IO с CORS
const io = new SocketIOServer(server, {
cors: {
origin: ['http://localhost:3000', 'http://localhost:5173'],
methods: ['GET', 'POST'],
credentials: true
}
});
// ИСПРАВЛЕНО: более точная настройка CORS
app.use(cors({
origin: ['http://localhost:3000', 'http://localhost:5173'], // Vite обычно использует 5173
origin: [
'http://localhost:3000',
'http://localhost:5173',
'https://ospab.host'
], // Vite обычно использует 5173
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
@@ -78,13 +69,19 @@ app.use('/api/server', serverRoutes);
const PORT = process.env.PORT || 5000;
// Инициализация сервиса мониторинга
const monitoringService = new MonitoringService(io);
monitoringService.startMonitoring();
import { setupConsoleWSS } from './modules/server/server.console';
import https from 'https';
import fs from 'fs';
server.listen(PORT, () => {
console.log(`🚀 Сервер запущен на порту ${PORT}`);
const sslOptions = {
key: fs.readFileSync('/etc/apache2/ssl/ospab.host.key'),
cert: fs.readFileSync('/etc/apache2/ssl/ospab.host.crt'),
};
const httpsServer = https.createServer(sslOptions, app);
setupConsoleWSS(httpsServer);
httpsServer.listen(PORT, () => {
console.log(`🚀 HTTPS сервер запущен на порту ${PORT}`);
console.log(`📊 База данных: ${process.env.DATABASE_URL ? 'подключена' : 'НЕ НАСТРОЕНА'}`);
console.log(`🔌 WebSocket сервер запущен`);
console.log(`📡 Мониторинг серверов активен`);
});

View File

@@ -1,10 +1,14 @@
import { Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { authMiddleware } from '../auth/auth.middleware';
const router = Router();
const prisma = new PrismaClient();
// GET /api/os — получить все ОС
router.use(authMiddleware);
// GET /api/os — получить все ОС (только для авторизованных)
router.get('/', async (req, res) => {
try {
const oses = await prisma.operatingSystem.findMany();

View File

@@ -1,3 +1,19 @@
// Смена root-пароля через SSH (для LXC)
import { exec } from 'child_process';
export async function changeRootPasswordSSH(vmid: number): Promise<{ status: string; password?: string; message?: string }> {
const newPassword = generateSecurePassword();
return new Promise((resolve) => {
exec(`ssh -o StrictHostKeyChecking=no root@${process.env.PROXMOX_NODE} pct set ${vmid} --password ${newPassword}`, (err, stdout, stderr) => {
if (err) {
console.error('Ошибка смены пароля через SSH:', stderr);
resolve({ status: 'error', message: stderr });
} else {
resolve({ status: 'success', password: newPassword });
}
});
});
}
import axios from 'axios';
import crypto from 'crypto';
import dotenv from 'dotenv';

View File

@@ -0,0 +1,70 @@
import { Server as WebSocketServer, WebSocket } from 'ws';
import { Client as SSHClient } from 'ssh2';
import dotenv from 'dotenv';
import { IncomingMessage } from 'http';
import { Server as HttpServer } from 'http';
dotenv.config();
export function setupConsoleWSS(server: HttpServer) {
const wss = new WebSocketServer({ noServer: true });
wss.on('connection', (ws: WebSocket, req: IncomingMessage) => {
const url = req.url || '';
const match = url.match(/\/api\/server\/(\d+)\/console/);
const vmid = match ? match[1] : null;
if (!vmid) {
ws.close();
return;
}
// Получаем IP и root-пароль из БД (упрощённо)
// Здесь можно добавить реальный запрос к Prisma
const host = process.env.PROXMOX_IP || process.env.PROXMOX_NODE;
const username = 'root';
const password = process.env.PROXMOX_ROOT_PASSWORD;
const ssh = new SSHClient();
const port = process.env.PROXMOX_SSH_PORT ? Number(process.env.PROXMOX_SSH_PORT) : 22;
ssh.on('ready', () => {
ssh.shell((err: Error | undefined, stream: any) => {
if (err) {
ws.send('Ошибка запуска shell: ' + err.message);
ws.close();
ssh.end();
return;
}
ws.on('message', (msg: string | Buffer) => {
stream.write(msg.toString());
});
stream.on('data', (data: Buffer) => {
ws.send(data.toString());
});
stream.on('close', () => {
ws.close();
ssh.end();
});
});
}).connect({
host,
port,
username,
password,
hostVerifier: (hash: string) => {
console.log('SSH fingerprint:', hash);
return true; // всегда принимаем fingerprint
}
});
ws.on('close', () => {
ssh.end();
});
});
server.on('upgrade', (request: IncomingMessage, socket: any, head: Buffer) => {
if (request.url?.startsWith('/api/server/') && request.url?.endsWith('/console')) {
wss.handleUpgrade(request, socket, head, (ws: WebSocket) => {
wss.emit('connection', ws, request);
});
}
});
}

View File

@@ -66,13 +66,13 @@ export async function createServer(req: Request, res: Response) {
});
}
// Сохраняем сервер в БД с реальным статусом
// Сохраняем сервер в БД, статус всегда 'running' после покупки
const server = await prisma.server.create({
data: {
userId,
tariffId,
osId,
status: result.containerStatus || 'creating',
status: 'running',
proxmoxId: Number(result.vmid),
ipAddress: result.ipAddress,
rootPassword: result.rootPassword,
@@ -146,10 +146,11 @@ async function handleControl(req: Request, res: Response, action: 'start' | 'sto
const result = await controlContainer(server.proxmoxId, action);
// Polling статуса VM после управления
let newStatus = server.status;
if (result.status === 'success') {
let actionSuccess = false;
let status = '';
let attempts = 0;
const maxAttempts = 10;
if (result.status === 'success') {
while (attempts < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, 3000));
const stats = await getContainerStats(server.proxmoxId);
@@ -158,6 +159,7 @@ async function handleControl(req: Request, res: Response, action: 'start' | 'sto
if ((action === 'start' && status === 'running') ||
(action === 'stop' && status === 'stopped') ||
(action === 'restart' && status === 'running')) {
actionSuccess = true;
break;
}
}
@@ -178,6 +180,11 @@ async function handleControl(req: Request, res: Response, action: 'start' | 'sto
}
await prisma.server.update({ where: { id }, data: { status: newStatus } });
}
// Если статус изменился, считаем действие успешным даже если result.status !== 'success'
if (newStatus !== server.status) {
return res.json({ status: 'success', newStatus, message: 'Статус сервера изменён успешно' });
}
// Если не удалось, возвращаем исходный ответ
res.json({ ...result, status: newStatus });
} catch (error: any) {
res.status(500).json({ error: error?.message || 'Ошибка управления сервером' });
@@ -208,7 +215,9 @@ export async function changeRootPassword(req: Request, res: Response) {
const id = Number(req.params.id);
const server = await prisma.server.findUnique({ where: { id } });
if (!server || !server.proxmoxId) return res.status(404).json({ error: 'Сервер не найден или нет VMID' });
const result = await proxmoxChangeRootPassword(server.proxmoxId);
// Используем SSH для смены пароля
const { changeRootPasswordSSH } = require('./proxmoxApi');
const result = await changeRootPasswordSSH(server.proxmoxId);
if (result?.status === 'success' && result.password) {
await prisma.server.update({ where: { id }, data: { rootPassword: result.password } });
}

View File

@@ -1,10 +1,10 @@
import { Router } from 'express';
import { PrismaClient } from '@prisma/client';
const router = Router();
const prisma = new PrismaClient();
// GET /api/tariff — получить все тарифы
router.get('/', async (req, res) => {
try {
const tariffs = await prisma.tariff.findMany();

View File

@@ -10,7 +10,7 @@
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node16",
"resolveJsonModule": true,
"noEmit": true,
"outDir": "./dist",
"verbatimModuleSyntax": false
},
"include": ["src/**/*.ts"],

View File

@@ -2,7 +2,9 @@
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

View File

@@ -13,8 +13,7 @@
"react-dom": "^19.1.1",
"react-icons": "^5.5.0",
"react-qr-code": "^2.0.18",
"recharts": "^2.15.0",
"socket.io-client": "^4.8.1"
"xterm": "^5.3.0"
},
"devDependencies": {
"@eslint/js": "^9.33.0",
@@ -281,15 +280,6 @@
"@babel/core": "^7.0.0-0"
}
},
"node_modules/@babel/runtime": {
"version": "7.28.4",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz",
"integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/template": {
"version": "7.27.2",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz",
@@ -1404,12 +1394,6 @@
"win32"
]
},
"node_modules/@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"license": "MIT"
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -1455,69 +1439,6 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/d3-array": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
"license": "MIT"
},
"node_modules/@types/d3-color": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
"license": "MIT"
},
"node_modules/@types/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
"license": "MIT"
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
"integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
"license": "MIT",
"dependencies": {
"@types/d3-color": "*"
}
},
"node_modules/@types/d3-path": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
"license": "MIT"
},
"node_modules/@types/d3-scale": {
"version": "4.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
"integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
}
},
"node_modules/@types/d3-shape": {
"version": "3.1.7",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz",
"integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "*"
}
},
"node_modules/@types/d3-time": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
"license": "MIT"
},
"node_modules/@types/d3-timer": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@@ -2200,15 +2121,6 @@
"node": ">= 6"
}
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
"integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -2307,129 +2219,9 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
"dev": true,
"license": "MIT"
},
"node_modules/d3-array": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
"integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
"license": "ISC",
"dependencies": {
"internmap": "1 - 2"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-ease": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
"integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-format": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
"integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-path": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
"integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
"license": "ISC",
"dependencies": {
"d3-array": "2.10.0 - 3",
"d3-format": "1 - 3",
"d3-interpolate": "1.2.0 - 3",
"d3-time": "2.1.1 - 3",
"d3-time-format": "2 - 4"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-shape": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
"integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
"license": "ISC",
"dependencies": {
"d3-path": "^3.1.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
"integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
"license": "ISC",
"dependencies": {
"d3-array": "2 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time-format": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
"integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
"license": "ISC",
"dependencies": {
"d3-time": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-timer": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
"integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -2448,12 +2240,6 @@
}
}
},
"node_modules/decimal.js-light": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
"license": "MIT"
},
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -2484,16 +2270,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/dom-helpers": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",
"integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.8.7",
"csstype": "^3.0.2"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -2529,45 +2305,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/engine.io-client": {
"version": "6.6.3",
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.3.tgz",
"integrity": "sha512-T0iLjnyNWahNyv/lcjS2y4oE358tVS/SYQNxYXGAJ9/GLgH4VCvOQ/mhTjqU88mLZCQgiG8RIegFHYCdVC+j5w==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.17.1",
"xmlhttprequest-ssl": "~2.1.1"
}
},
"node_modules/engine.io-client/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -2856,12 +2593,6 @@
"node": ">=0.10.0"
}
},
"node_modules/eventemitter3": {
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
"license": "MIT"
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -2869,15 +2600,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/fast-equals": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.3.2.tgz",
"integrity": "sha512-6rxyATwPCkaFIL3JLqw8qXqMpIZ942pTX/tbQFkRsDGblS8tNGtlUauA/+mt6RUfqn/4MoEr+WDkYoIQbibWuQ==",
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/fast-glob": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
@@ -3312,15 +3034,6 @@
"node": ">=0.8.19"
}
},
"node_modules/internmap": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/is-binary-path": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
@@ -3552,12 +3265,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"license": "MIT"
},
"node_modules/lodash.merge": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
@@ -3668,6 +3375,7 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true,
"license": "MIT"
},
"node_modules/mz": {
@@ -4234,37 +3942,6 @@
"react-dom": ">=18"
}
},
"node_modules/react-smooth": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",
"integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==",
"license": "MIT",
"dependencies": {
"fast-equals": "^5.0.1",
"prop-types": "^15.8.1",
"react-transition-group": "^4.4.5"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/react-transition-group": {
"version": "4.4.5",
"resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",
"integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==",
"license": "BSD-3-Clause",
"dependencies": {
"@babel/runtime": "^7.5.5",
"dom-helpers": "^5.0.1",
"loose-envify": "^1.4.0",
"prop-types": "^15.6.2"
},
"peerDependencies": {
"react": ">=16.6.0",
"react-dom": ">=16.6.0"
}
},
"node_modules/read-cache": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
@@ -4288,44 +3965,6 @@
"node": ">=8.10.0"
}
},
"node_modules/recharts": {
"version": "2.15.0",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.0.tgz",
"integrity": "sha512-cIvMxDfpAmqAmVgc4yb7pgm/O1tmmkl/CjrvXuW+62/+7jj/iF9Ykm+hb/UJt42TREHMyd3gb+pkgoa2MxgDIw==",
"license": "MIT",
"dependencies": {
"clsx": "^2.0.0",
"eventemitter3": "^4.0.1",
"lodash": "^4.17.21",
"react-is": "^18.3.1",
"react-smooth": "^4.0.0",
"recharts-scale": "^0.4.4",
"tiny-invariant": "^1.3.1",
"victory-vendor": "^36.6.8"
},
"engines": {
"node": ">=14"
},
"peerDependencies": {
"react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/recharts-scale": {
"version": "0.4.5",
"resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz",
"integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==",
"license": "MIT",
"dependencies": {
"decimal.js-light": "^2.4.1"
}
},
"node_modules/recharts/node_modules/react-is": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
"integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
"license": "MIT"
},
"node_modules/resolve": {
"version": "1.22.10",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz",
@@ -4492,68 +4131,6 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/socket.io-client": {
"version": "4.8.1",
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.1.tgz",
"integrity": "sha512-hJVXfu3E28NmzGk8o1sHhN3om52tRvwYeidbj7xKy2eIIse5IoKX3USlS6Tqt3BHAtflLIkCQBkzVrEEfWUyYQ==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.2",
"engine.io-client": "~6.6.1",
"socket.io-parser": "~4.2.4"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-client/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/socket.io-parser": {
"version": "4.2.4",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
"integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-parser/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -4791,12 +4368,6 @@
"node": ">=0.8"
}
},
"node_modules/tiny-invariant": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.15",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
@@ -4977,28 +4548,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/victory-vendor": {
"version": "36.9.2",
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz",
"integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==",
"license": "MIT AND ISC",
"dependencies": {
"@types/d3-array": "^3.0.3",
"@types/d3-ease": "^3.0.0",
"@types/d3-interpolate": "^3.0.1",
"@types/d3-scale": "^4.0.2",
"@types/d3-shape": "^3.1.0",
"@types/d3-time": "^3.0.0",
"@types/d3-timer": "^3.0.0",
"d3-array": "^3.1.6",
"d3-ease": "^3.0.1",
"d3-interpolate": "^3.0.1",
"d3-scale": "^4.0.2",
"d3-shape": "^3.1.0",
"d3-time": "^3.0.0",
"d3-timer": "^3.0.1"
}
},
"node_modules/vite": {
"version": "7.1.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.5.tgz",
@@ -5226,34 +4775,12 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/ws": {
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
"integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xmlhttprequest-ssl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
"engines": {
"node": ">=0.4.0"
}
"node_modules/xterm": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/xterm/-/xterm-5.3.0.tgz",
"integrity": "sha512-8QqjlekLUFTrU6x7xck1MsPzPA571K5zNqWm0M0oroYEWVOptZ0+ubQSkQ3uxIEhcIHRujJy6emDWX4A7qyFzg==",
"deprecated": "This package is now deprecated. Move to @xterm/xterm instead.",
"license": "MIT"
},
"node_modules/yallist": {
"version": "3.1.1",

View File

@@ -15,8 +15,7 @@
"react-dom": "^19.1.1",
"react-icons": "^5.5.0",
"react-qr-code": "^2.0.18",
"recharts": "^2.15.0",
"socket.io-client": "^4.8.1"
"xterm": "^5.3.0"
},
"devDependencies": {
"@eslint/js": "^9.33.0",

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 455 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

View File

@@ -0,0 +1 @@
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 72 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,120 @@
import React, { useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import { Terminal } from 'xterm';
import 'xterm/css/xterm.css';
const ServerConsole: React.FC = () => {
const { id } = useParams();
const termRef = useRef<HTMLDivElement>(null);
const wsRef = useRef<WebSocket | null>(null);
const xtermRef = useRef<Terminal | null>(null);
const reconnectAttempts = useRef(0);
// Логгер ошибок
const logError = (msg: string, err?: unknown) => {
console.error('[Console]', msg, err);
};
useEffect(() => {
let disposed = false;
if (!termRef.current) return;
let term: Terminal | null = null;
try {
term = new Terminal({
rows: 24,
cols: 80,
fontSize: 16,
theme: {
background: '#18181b',
foreground: '#e5e7eb',
},
cursorBlink: true,
});
term.open(termRef.current);
xtermRef.current = term;
} catch (err) {
logError('Ошибка инициализации xterm', err);
return;
}
// Resize обработка
const handleResize = () => {
try {
term?.resize(
Math.floor(termRef.current?.offsetWidth ? termRef.current.offsetWidth / 9 : 80),
Math.floor(termRef.current?.offsetHeight ? termRef.current.offsetHeight / 20 : 24)
);
} catch (err) {
logError('Ошибка resize терминала', err);
}
};
window.addEventListener('resize', handleResize);
setTimeout(handleResize, 100);
// WebSocket с авто-подключением
const connectWS = () => {
if (disposed) return;
const ws = new WebSocket(`wss://ospab.host:5000/api/server/${id}/console`);
wsRef.current = ws;
ws.onopen = () => {
reconnectAttempts.current = 0;
term?.write('\x1b[32mПодключено к серверу\x1b[0m\r\n');
};
ws.onmessage = (event) => {
try {
term?.write(event.data);
} catch (err) {
logError('Ошибка вывода данных в терминал', err);
}
};
ws.onclose = (event) => {
logError('WebSocket закрыт', event);
term?.write('\r\n\x1b[31mОтключено от сервера\x1b[0m\r\n');
// Авто-подключение (до 5 попыток)
if (!disposed && reconnectAttempts.current < 5) {
reconnectAttempts.current++;
setTimeout(connectWS, 1000 * reconnectAttempts.current);
}
};
ws.onerror = (event) => {
logError('WebSocket ошибка', event);
term?.write('\r\n\x1b[31mОшибка соединения\x1b[0m\r\n');
};
term?.onData((data: string) => {
try {
if (ws.readyState === WebSocket.OPEN) {
ws.send(data);
}
} catch (err) {
logError('Ошибка отправки данных по WebSocket', err);
}
});
};
connectWS();
return () => {
disposed = true;
try {
wsRef.current?.close();
} catch (err) {
logError('Ошибка закрытия WebSocket', err);
}
try {
term?.dispose();
} catch (err) {
logError('Ошибка dispose терминала', err);
}
window.removeEventListener('resize', handleResize);
};
}, [id]);
return (
<div className="bg-black rounded-xl p-2 w-full h-[500px]">
<div ref={termRef} style={{ width: '100%', height: '100%' }} />
</div>
);
};
export default ServerConsole;

View File

@@ -10,7 +10,8 @@ const DashboardTempl: React.FC<DashboardTemplProps> = ({ children }) => {
return (
<div className="min-h-screen bg-gray-50">
<Header />
<div className="pt-16">
<div className="border-t border-gray-200" />
<div>
{children}
</div>
</div>

View File

@@ -1,4 +1,5 @@
import { Link } from 'react-router-dom';
import logo from '../assets/logo.svg';
const Footer = () => {
const currentYear = new Date().getFullYear();
@@ -9,6 +10,9 @@ const Footer = () => {
<div className="grid grid-cols-1 md:grid-cols-3 gap-8 text-center md:text-left">
{/* About Section */}
<div>
<div className="mb-4 flex justify-center md:justify-start">
<img src={logo} alt="Логотип" className="h-16 w-auto" />
</div>
<h3 className="text-xl font-bold mb-4">О нас</h3>
<p className="text-sm text-gray-400">
ospab.host - это надежный хостинг для ваших проектов. Мы предлагаем высокую производительность и круглосуточную поддержку.

View File

@@ -1,5 +1,6 @@
import { Link } from 'react-router-dom';
import useAuth from '../context/useAuth';
import logo from '../assets/logo.svg';
const Header = () => {
const { isLoggedIn, logout } = useAuth();
@@ -9,10 +10,13 @@ const Header = () => {
};
return (
<header className="fixed top-0 left-0 right-0 z-50 bg-white shadow-md">
<header className="static bg-white shadow-md">
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
<div className="text-xl font-bold text-gray-800">
<Link to="/" className="font-mono text-2xl">ospab.host</Link>
<div className="flex items-center gap-1">
<Link to="/" className="flex items-center">
<img src={logo} alt="Логотип" className="h-14 w-auto mr-2" />
<span className="font-mono text-2xl text-gray-800 font-bold">ospab.host</span>
</Link>
</div>
<div className="flex items-center space-x-4">
<Link to="/tariffs" className="text-gray-600 hover:text-ospab-primary transition-colors">Тарифы</Link>

View File

@@ -10,7 +10,7 @@ const PageTmpl: React.FC<PageTmplProps> = ({ children }) => {
return (
<div className="flex flex-col min-h-screen">
<Header />
<main className="flex-grow pt-16">
<main className="flex-grow">
{children}
</main>
<Footer />

View File

@@ -1,14 +1,33 @@
const AboutPage = () => {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center py-20 px-4">
<div className="bg-white p-10 rounded-3xl shadow-2xl max-w-4xl mx-auto text-center">
<h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-6">О компании ospab.host</h1>
<p className="text-lg text-gray-700 mb-4">
Мы предоставляем надежные и масштабируемые хостинг-решения для разработчиков, стартапов и крупных компаний. Наша миссия дать вам инструменты, необходимые для реализации ваших идей в интернете, обеспечивая при этом высокую производительность и безопасность.
</p>
<p className="text-lg text-gray-700">
Наша инфраструктура построена на современных технологиях, а круглосуточная поддержка всегда готова помочь вам. Мы верим, что качественный хостинг должен быть доступен каждому.
</p>
<div className="min-h-screen bg-gradient-to-br from-blue-100 via-white to-ospab-primary flex items-center justify-center py-20 px-4">
<div className="bg-white p-10 md:p-16 rounded-3xl shadow-2xl max-w-4xl mx-auto text-center border-4 border-ospab-primary/20">
<h1 className="text-5xl md:text-6xl font-extrabold text-ospab-primary mb-8 drop-shadow-lg">История ospab.host</h1>
<div className="flex flex-col md:flex-row items-center gap-8 mb-8">
<img src="/me.jpg" alt="Георгий" className="w-32 h-32 rounded-full shadow-lg border-4 border-ospab-primary mx-auto" />
<div className="text-left md:text-center">
<h2 className="text-3xl font-bold text-gray-900 mb-2">Георгий, основатель</h2>
<p className="text-lg text-gray-700 mb-2">Возраст: 13 лет</p>
<p className="text-lg text-gray-700">Великий Новгород, Россия</p>
</div>
</div>
<div className="text-lg text-gray-800 leading-relaxed mb-6">
<p className="mb-4">В сентябре 2025 года я, Георгий, начал работу над первым дата-центром (ЦОД) и крупным хостингом в Великом Новгороде. Всё началось с мечты создать место, где любой сможет разместить свой проект, сайт или сервер с максимальной надёжностью и скоростью.</p>
<p className="mb-4">Сейчас я работаю над хостингом для будущего ЦОД, а мой друг-инвестор помогает с развитием инфраструктуры. Мы строим не просто сервис, а сообщество, где каждый клиент как друг, а поддержка всегда рядом.</p>
<p className="mb-4">ospab.host это не просто хостинг. Это первый шаг к цифровому будущему Великого Новгорода, созданный с нуля школьником, который верит в технологии и силу дружбы.</p>
<p className="mb-4">Наша миссия сделать качественный хостинг доступным для всех, а ЦОД гордостью города. Мы используем современные технологии, заботимся о безопасности и всегда готовы помочь.</p>
</div>
<div className="bg-ospab-primary/10 rounded-xl p-6 mt-8">
<h3 className="text-2xl font-bold text-ospab-primary mb-2">Почему выбирают ospab.host?</h3>
<ul className="list-disc list-inside text-lg text-gray-700 text-left mx-auto max-w-xl">
<li>Первый ЦОД и крупный хостинг в Великом Новгороде</li>
<li>Личная поддержка от основателя</li>
<li>Современная инфраструктура и технологии</li>
<li>Доступные тарифы для всех</li>
<li>История, которой можно гордиться</li>
</ul>
</div>
</div>
</div>
);

View File

@@ -36,7 +36,7 @@ const Billing = () => {
const formData = new FormData();
formData.append('file', checkFile);
formData.append('amount', String(amount));
const response = await axios.post('http://localhost:5000/api/check/upload', formData, {
const response = await axios.post('https://ospab.host:5000/api/check/upload', formData, {
headers: {
Authorization: `Bearer ${token}`,
// 'Content-Type' не указываем вручную для FormData!

View File

@@ -33,9 +33,11 @@ const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
// Загрузка тарифов и ОС
const fetchData = async () => {
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const [tariffRes, osRes] = await Promise.all([
axios.get('http://localhost:5000/api/tariff'),
axios.get('http://localhost:5000/api/os'),
axios.get('https://ospab.host:5000/api/tariff', { headers }),
axios.get('https://ospab.host:5000/api/os', { headers }),
]);
setTariffs(tariffRes.data);
setOses(osRes.data);
@@ -62,7 +64,7 @@ const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
try {
const token = localStorage.getItem('access_token') || localStorage.getItem('token');
console.log('Покупка сервера:', { tariffId: selectedTariff, osId: selectedOs });
const res = await axios.post('http://localhost:5000/api/server/create', {
const res = await axios.post('https://ospab.host:5000/api/server/create', {
tariffId: selectedTariff,
osId: selectedOs,
}, {
@@ -76,7 +78,7 @@ const Checkout: React.FC<CheckoutProps> = ({ onSuccess }) => {
}
// После успешной покупки обновляем userData
try {
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers: token ? { Authorization: `Bearer ${token}` } : {} });
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers: token ? { Authorization: `Bearer ${token}` } : {} });
window.dispatchEvent(new CustomEvent('userDataUpdate', {
detail: {
user: userRes.data.user,

View File

@@ -18,7 +18,7 @@ interface ICheck {
user?: IUser;
}
const API_URL = 'http://localhost:5000/api/check';
const API_URL = 'https://ospab.host:5000/api/check';
const CheckVerification: React.FC = () => {
const [checks, setChecks] = useState<ICheck[]>([]);
@@ -61,7 +61,7 @@ const CheckVerification: React.FC = () => {
try {
const token = localStorage.getItem('access_token');
const headers = { Authorization: `Bearer ${token}` };
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers });
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
// Глобально обновить userData через типизированное событие (для Dashboard)
window.dispatchEvent(new CustomEvent<import('./types').UserData>('userDataUpdate', {
detail: {
@@ -109,8 +109,8 @@ const CheckVerification: React.FC = () => {
</div>
</div>
<div className="flex flex-col items-center gap-2 md:ml-8">
<a href={`http://localhost:5000${check.fileUrl}`} target="_blank" rel="noopener noreferrer" className="block mb-2">
<img src={`http://localhost:5000${check.fileUrl}`} alt="Чек" className="w-32 h-32 object-contain rounded-xl border" />
<a href={`https://ospab.host:5000${check.fileUrl}`} target="_blank" rel="noopener noreferrer" className="block mb-2">
<img src={`https://ospab.host:5000${check.fileUrl}`} alt="Чек" className="w-32 h-32 object-contain rounded-xl border" />
</a>
{check.status === 'pending' && (
<>

View File

@@ -49,7 +49,7 @@ const Dashboard = () => {
return;
}
const headers = { Authorization: `Bearer ${token}` };
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers });
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
setUserData({
user: userRes.data.user,
balance: userRes.data.user.balance ?? 0,
@@ -75,7 +75,7 @@ const Dashboard = () => {
const token = localStorage.getItem('access_token');
if (!token) return;
const headers = { Authorization: `Bearer ${token}` };
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers });
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
setUserData({
user: userRes.data.user,
balance: userRes.data.user.balance ?? 0,
@@ -198,7 +198,12 @@ const Dashboard = () => {
})}
</p>
</div>
<div className="flex-1 p-8">
<div className="flex-1 p-8 pt-12">
{activeTab === 'summary' && (
<div className="border-4 border-red-500 bg-red-100 text-red-900 font-bold text-lg rounded-2xl shadow-lg p-6 mb-8 text-center animate-pulse">
Управление серверами временно невозможно сайт ещё в разработке!
</div>
)}
<Routes>
<Route path="/" element={<Summary userData={userData ?? { user: { username: '', operator: 0 }, balance: 0, servers: [], tickets: [] }} />} />
<Route path="servers" element={<Servers />} />

View File

@@ -1,315 +1,10 @@
import React, { useEffect, useState } from 'react';
import ServerConsole from '../../components/ServerConsole';
import { useParams } from 'react-router-dom';
import axios, { AxiosError } from 'axios';
import { useServerStats } from '../../hooks/useSocket';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
// Встроенная секция консоли
function ConsoleSection({ serverId }: { serverId: number }) {
const [consoleUrl, setConsoleUrl] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleOpenConsole = async () => {
setLoading(true);
setError('');
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const res = await axios.post(`http://localhost:5000/api/proxmox/console`, { vmid: serverId }, { headers });
if (res.data?.status === 'success' && res.data.url) {
setConsoleUrl(res.data.url);
} else {
setError('Ошибка открытия консоли');
}
} catch {
setError('Ошибка открытия консоли');
} finally {
setLoading(false);
}
};
return (
<div className="bg-gray-100 rounded-xl p-6 text-gray-700 font-mono text-sm flex flex-col items-center">
<div className="mb-2 font-bold">Консоль сервера</div>
{!consoleUrl ? (
<button
className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold mb-4"
onClick={handleOpenConsole}
disabled={loading}
>{loading ? 'Открытие...' : 'Открыть noVNC консоль'}</button>
) : (
<iframe
src={consoleUrl}
title="noVNC Console"
className="w-full h-[600px] rounded-lg border"
allowFullScreen
/>
)}
{error && <div className="text-red-500 text-base font-semibold text-center mt-2">{error}</div>}
</div>
);
}
// Модальное окно для изменения конфигурации
function ResizeModal({ serverId, onClose, onSuccess }: { serverId: number; onClose: () => void; onSuccess: () => void }) {
const [cores, setCores] = useState('');
const [memory, setMemory] = useState('');
const [disk, setDisk] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleResize = async () => {
setLoading(true);
setError('');
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const data: any = {};
if (cores) data.cores = Number(cores);
if (memory) data.memory = Number(memory);
if (disk) data.disk = Number(disk);
const res = await axios.put(`http://localhost:5000/api/server/${serverId}/resize`, data, { headers });
if (res.data?.status === 'success') {
onSuccess();
onClose();
} else {
setError('Ошибка изменения конфигурации');
}
} catch (err) {
setError('Ошибка изменения конфигурации');
console.error(err);
} finally {
setLoading(false);
}
};
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-white rounded-3xl shadow-xl p-8 max-w-md w-full" onClick={(e) => e.stopPropagation()}>
<h2 className="text-2xl font-bold mb-6">Изменить конфигурацию</h2>
<div className="space-y-4">
<div>
<label className="block text-sm font-semibold mb-2">Количество ядер CPU</label>
<input
type="number"
value={cores}
onChange={(e) => setCores(e.target.value)}
className="w-full px-4 py-2 border rounded-lg"
placeholder="Оставьте пустым, чтобы не менять"
min="1"
/>
</div>
<div>
<label className="block text-sm font-semibold mb-2">RAM (МБ)</label>
<input
type="number"
value={memory}
onChange={(e) => setMemory(e.target.value)}
className="w-full px-4 py-2 border rounded-lg"
placeholder="Например: 2048"
min="512"
/>
</div>
<div>
<label className="block text-sm font-semibold mb-2">Диск (ГБ)</label>
<input
type="number"
value={disk}
onChange={(e) => setDisk(e.target.value)}
className="w-full px-4 py-2 border rounded-lg"
placeholder="Например: 40"
min="10"
/>
</div>
{error && <div className="text-red-500">{error}</div>}
<div className="flex gap-4">
<button
onClick={handleResize}
disabled={loading}
className="flex-1 bg-ospab-primary text-white px-6 py-3 rounded-full font-bold disabled:opacity-50"
>
{loading ? 'Изменение...' : 'Применить'}
</button>
<button
onClick={onClose}
className="flex-1 bg-gray-300 text-gray-700 px-6 py-3 rounded-full font-bold"
>
Отмена
</button>
</div>
</div>
</div>
</div>
);
}
// Компонент для управления снэпшотами
function SnapshotsSection({ serverId }: { serverId: number }) {
const [snapshots, setSnapshots] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [snapName, setSnapName] = useState('');
const [snapDesc, setSnapDesc] = useState('');
const [error, setError] = useState('');
useEffect(() => {
loadSnapshots();
}, [serverId]);
const loadSnapshots = async () => {
setLoading(true);
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const res = await axios.get(`http://localhost:5000/api/server/${serverId}/snapshots`, { headers });
if (res.data?.status === 'success') {
setSnapshots(res.data.data || []);
}
} catch (err) {
console.error('Error loading snapshots:', err);
} finally {
setLoading(false);
}
};
const handleCreateSnapshot = async () => {
if (!snapName) {
setError('Введите имя снэпшота');
return;
}
setLoading(true);
setError('');
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const res = await axios.post(
`http://localhost:5000/api/server/${serverId}/snapshots`,
{ snapname: snapName, description: snapDesc },
{ headers }
);
if (res.data?.status === 'success') {
setSnapName('');
setSnapDesc('');
loadSnapshots();
} else {
setError('Ошибка создания снэпшота');
}
} catch (err) {
setError('Ошибка создания снэпшота');
console.error(err);
} finally {
setLoading(false);
}
};
const handleRollback = async (snapname: string) => {
if (!confirm(`Восстановить из снэпшота ${snapname}? Текущее состояние будет потеряно.`)) return;
setLoading(true);
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
await axios.post(
`http://localhost:5000/api/server/${serverId}/snapshots/rollback`,
{ snapname },
{ headers }
);
alert('Снэпшот восстановлен');
} catch (err) {
alert('Ошибка восстановления снэпшота');
console.error(err);
} finally {
setLoading(false);
}
};
const handleDelete = async (snapname: string) => {
if (!confirm(`Удалить снэпшот ${snapname}?`)) return;
setLoading(true);
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
await axios.delete(
`http://localhost:5000/api/server/${serverId}/snapshots`,
{ data: { snapname }, headers }
);
loadSnapshots();
} catch (err) {
alert('Ошибка удаления снэпшота');
console.error(err);
} finally {
setLoading(false);
}
};
return (
<div className="bg-gray-100 rounded-xl p-6">
<h3 className="text-xl font-bold mb-4">Управление снэпшотами</h3>
<div className="bg-white rounded-lg p-4 mb-4">
<h4 className="font-semibold mb-3">Создать новый снэпшот</h4>
<div className="space-y-3">
<input
type="text"
value={snapName}
onChange={(e) => setSnapName(e.target.value)}
placeholder="Имя снэпшота (например: backup-2024)"
className="w-full px-4 py-2 border rounded-lg"
/>
<input
type="text"
value={snapDesc}
onChange={(e) => setSnapDesc(e.target.value)}
placeholder="Описание (опционально)"
className="w-full px-4 py-2 border rounded-lg"
/>
{error && <div className="text-red-500 text-sm">{error}</div>}
<button
onClick={handleCreateSnapshot}
disabled={loading}
className="bg-ospab-primary text-white px-6 py-2 rounded-full font-bold disabled:opacity-50"
>
{loading ? 'Создание...' : 'Создать снэпшот'}
</button>
</div>
</div>
<div className="bg-white rounded-lg p-4">
<h4 className="font-semibold mb-3">Существующие снэпшоты</h4>
{snapshots.length === 0 ? (
<p className="text-gray-500">Снэпшотов пока нет</p>
) : (
<div className="space-y-2">
{snapshots.map((snap) => (
<div key={snap.name} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<div>
<div className="font-semibold">{snap.name}</div>
<div className="text-sm text-gray-600">{snap.description || 'Без описания'}</div>
</div>
<div className="flex gap-2">
<button
onClick={() => handleRollback(snap.name)}
className="bg-blue-500 text-white px-4 py-1 rounded-full text-sm font-semibold hover:bg-blue-600"
>
Восстановить
</button>
<button
onClick={() => handleDelete(snap.name)}
className="bg-red-500 text-white px-4 py-1 rounded-full text-sm font-semibold hover:bg-red-600"
>
Удалить
</button>
</div>
</div>
))}
</div>
)}
</div>
</div>
);
}
// Типы
interface Server {
id: number;
status: string;
@@ -328,40 +23,44 @@ interface ServerStats {
};
}
// ...existing code...
// ConsoleSection больше не нужен
const TABS = [
{ key: 'overview', label: 'Обзор' },
{ key: 'console', label: 'Консоль' },
{ key: 'stats', label: 'Статистика' },
{ key: 'manage', label: 'Управление' },
{ key: 'snapshots', label: 'Снэпшоты' },
{ key: 'resize', label: 'Конфигурация' },
{ key: 'security', label: 'Безопасность' },
{ key: 'network', label: 'Сеть' },
{ key: 'backups', label: 'Бэкапы' },
{ key: 'monitoring', label: 'Мониторинг' },
{ key: 'logs', label: 'Логи' },
];
const ServerPanel: React.FC = () => {
const { id } = useParams();
const [server, setServer] = useState<Server | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [success, setSuccess] = useState('');
const [activeAction, setActiveAction] = useState<null | 'start' | 'stop' | 'restart'>(null);
const [activeTab, setActiveTab] = useState('overview');
const [newRoot, setNewRoot] = useState<string | null>(null);
const [showRoot, setShowRoot] = useState(false);
// overlay больше не нужен
const [stats, setStats] = useState<ServerStats | null>(null);
const [showResizeModal, setShowResizeModal] = useState(false);
// Real-time WebSocket stats
const { stats: realtimeStats, alerts, connected } = useServerStats(server?.id || null);
useEffect(() => {
const fetchServer = async () => {
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const res = await axios.get(`http://localhost:5000/api/server/${id}`, { headers });
const res = await axios.get(`https://ospab.host:5000/api/server/${id}`, { headers });
setServer(res.data);
// Получаем статистику
const statsRes = await axios.get(`http://localhost:5000/api/server/${id}/status`, { headers });
const statsRes = await axios.get(`https://ospab.host:5000/api/server/${id}/status`, { headers });
setStats(statsRes.data.stats);
} catch (err) {
const error = err as AxiosError;
@@ -381,18 +80,26 @@ const ServerPanel: React.FC = () => {
// Смена root-пароля через backend
const handleGenerateRoot = async () => {
try {
setError('');
setSuccess('');
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const res = await axios.post(`http://localhost:5000/api/server/${id}/password`, {}, { headers });
const res = await axios.post(`https://ospab.host:5000/api/server/${id}/password`, {}, { headers });
if (res.data?.status === 'success' && res.data.password) {
setNewRoot(res.data.password);
setShowRoot(true);
setSuccess('Root-пароль успешно изменён!');
} else {
setError('Ошибка смены root-пароля');
console.error('Ошибка смены root-пароля:', res.data);
}
} catch (err) {
setError('Ошибка смены root-пароля');
console.error('Ошибка смены root-пароля:', err);
const axiosErr = err as AxiosError;
if (axiosErr && axiosErr.response) {
console.error('Ответ сервера:', axiosErr.response.data);
}
}
};
@@ -400,16 +107,19 @@ const ServerPanel: React.FC = () => {
const handleAction = async (action: 'start' | 'stop' | 'restart') => {
try {
setLoading(true);
setActiveAction(action);
setError('');
setSuccess('');
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const res = await axios.post(`http://localhost:5000/api/server/${id}/${action}`, {}, { headers });
if (res.data?.status === 'success') {
const res = await axios.post(`https://ospab.host:5000/api/server/${id}/${action}`, {}, { headers });
if (res.data?.status === 'success' || res.data?.message === 'Статус сервера изменён успешно') {
// Обновить статус сервера и статистику после действия
const updated = await axios.get(`http://localhost:5000/api/server/${id}`, { headers });
const updated = await axios.get(`https://ospab.host:5000/api/server/${id}`, { headers });
setServer(updated.data);
const statsRes = await axios.get(`http://localhost:5000/api/server/${id}/status`, { headers });
const statsRes = await axios.get(`https://ospab.host:5000/api/server/${id}/status`, { headers });
setStats(statsRes.data.stats);
setSuccess('Действие выполнено успешно!');
} else {
setError(`Ошибка: ${res.data?.message || 'Не удалось выполнить действие'}`);
}
@@ -418,227 +128,215 @@ const ServerPanel: React.FC = () => {
console.error('Ошибка управления сервером:', err);
} finally {
setLoading(false);
setActiveAction(null);
}
};
if (loading) {
return <div className="flex min-h-screen items-center justify-center"><span className="text-gray-500 text-lg">Загрузка...</span></div>;
}
if (error) {
return (
<div className="flex min-h-screen items-center justify-center bg-gray-50">
<div className="bg-white rounded-3xl shadow-xl p-10 max-w-xl w-full flex flex-col items-center">
<span className="text-red-500 text-xl font-bold mb-4">{error}</span>
<button
className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold hover:bg-ospab-primary-dark transition"
onClick={() => window.location.href = '/dashboard/servers'}
>
Вернуться к списку серверов
</button>
</div>
</div>
);
}
if (!server) {
return <div className="flex min-h-screen items-center justify-center"><span className="text-red-500 text-lg">Сервер не найден</span></div>;
}
return (
<div className="min-h-screen flex flex-col items-center bg-gray-50">
<div className="bg-white rounded-3xl shadow-xl p-10 max-w-3xl w-full mt-10">
<h1 className="text-3xl font-bold text-gray-800 mb-6">Панель управления сервером #{server.id}</h1>
<div className="flex gap-4 mb-8">
<div className="bg-white rounded-3xl shadow-xl p-10 w-full max-w-7xl mt-10 flex flex-row min-h-[700px]">
<aside className="w-64 pr-8 border-r border-gray-200 flex flex-col gap-2">
<h1 className="text-2xl font-bold text-gray-800 mb-6">Сервер #{server?.id}</h1>
{TABS.map(tab => (
<button
key={tab.key}
onClick={() => setActiveTab(tab.key)}
className={`px-5 py-2 rounded-xl font-semibold transition-colors duration-200 ${activeTab === tab.key ? 'bg-ospab-primary text-white shadow-lg' : 'text-gray-600 hover:bg-gray-100'}`}
className={`w-full text-left px-5 py-3 rounded-xl font-semibold transition-colors duration-200 mb-1 ${activeTab === tab.key ? 'bg-ospab-primary text-white shadow-lg' : 'text-gray-600 hover:bg-gray-100'}`}
>
{tab.label}
</button>
))}
</aside>
<main className="flex-1 pl-8">
{activeTab === 'overview' && server && (
<div className="bg-gradient-to-br from-ospab-primary/80 to-ospab-primary-dark/80 rounded-2xl shadow-lg p-8 flex flex-col items-start w-full max-w-2xl mx-auto">
<div className="grid grid-cols-2 gap-4 w-full mb-6">
<div className="flex flex-col gap-2">
<span className="text-sm text-gray-700">Статус</span>
<span className={`text-base font-semibold px-3 py-1 rounded-xl ${server.status === 'running' ? 'bg-green-100 text-green-800' : server.status === 'stopped' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'} shadow w-fit`}>{server.status === 'running' ? 'Работает' : server.status === 'stopped' ? 'Остановлен' : server.status}</span>
</div>
<div className="flex flex-col gap-2">
<span className="text-sm text-gray-700">IP-адрес</span>
<span className="font-mono text-base text-gray-900">{server.ip || '—'}</span>
</div>
<div className="flex flex-col gap-2">
<span className="text-sm text-gray-700">Операционная система</span>
<span className="text-gray-900">{server.os.name} <span className="text-xs text-gray-500">({server.os.type})</span></span>
</div>
<div className="flex flex-col gap-2">
<span className="text-sm text-gray-700">Тариф</span>
<span className="text-base font-semibold px-3 py-1 rounded-xl bg-ospab-primary/10 text-ospab-primary shadow w-fit">{server.tariff.name}</span>
</div>
<div className="flex flex-col gap-2">
<span className="text-sm text-gray-700">Цена</span>
<span className="font-mono text-base text-gray-900">{server.tariff.price}</span>
</div>
<div className="flex flex-col gap-2">
<span className="text-sm text-gray-700">Root-пароль</span>
{(() => {
const created = new Date(server.createdAt);
const now = new Date();
const diffMin = (now.getTime() - created.getTime()) / 1000 / 60;
if (server.rootPassword && diffMin <= 30) {
return (
<div className="flex items-center gap-2 relative">
<span
className="font-mono text-base bg-gray-100 text-gray-900 px-3 py-1 rounded"
style={{ userSelect: showRoot ? 'text' : 'none', WebkitUserSelect: showRoot ? 'text' : 'none' }}
>{showRoot ? server.rootPassword : '************'}</span>
{!showRoot ? (
<button
className="bg-ospab-primary text-white px-2 py-1 rounded text-xs font-bold hover:bg-ospab-primary-dark transition"
onClick={() => setShowRoot(true)}
>Показать</button>
) : (
<button
className="bg-ospab-primary text-white px-2 py-1 rounded text-xs font-bold hover:bg-ospab-primary-dark transition"
onClick={() => { navigator.clipboard.writeText(server.rootPassword || ''); setShowRoot(false); }}
>Скопировать</button>
)}
</div>
);
} else {
return (
<span className="font-mono text-base text-gray-900"></span>
);
}
})()}
</div>
</div>
<div className="flex flex-col md:flex-row gap-6 w-full mt-2">
<div className="flex items-center gap-2">
<span className="text-lg">📅</span>
<span className="text-sm text-gray-700">Создан:</span>
<span className="font-semibold text-gray-900">{new Date(server.createdAt).toLocaleString()}</span>
</div>
<div className="flex items-center gap-2">
<span className="text-lg">🔄</span>
<span className="text-sm text-gray-700">Обновлён:</span>
<span className="font-semibold text-gray-900">{new Date(server.updatedAt).toLocaleString()}</span>
</div>
</div>
{activeTab === 'overview' && (
<div className="space-y-4">
<div className="text-lg text-gray-800 font-bold">Статус: <span className="font-normal">{server.status}</span></div>
<div className="text-lg text-gray-800 font-bold">Тариф: <span className="font-normal">{server.tariff.name} ({server.tariff.price})</span></div>
<div className="text-lg text-gray-800 font-bold">ОС: <span className="font-normal">{server.os.name} ({server.os.type})</span></div>
<div className="text-lg text-gray-800 font-bold">IP: <span className="font-normal">{server.ip || '—'}</span></div>
<div className="text-lg text-gray-800 font-bold">Создан: <span className="font-normal">{new Date(server.createdAt).toLocaleString()}</span></div>
<div className="text-lg text-gray-800 font-bold">Обновлён: <span className="font-normal">{new Date(server.updatedAt).toLocaleString()}</span></div>
</div>
)}
{activeTab === 'console' && (
<ConsoleSection serverId={server.id} />
{activeTab === 'console' && server && (
<ServerConsole />
)}
{activeTab === 'stats' && (
<div className="space-y-6">
{/* WebSocket connection status */}
<div className="flex items-center gap-2 mb-4">
<div className={`w-3 h-3 rounded-full ${connected ? 'bg-green-500' : 'bg-red-500'}`}></div>
<span className="text-sm text-gray-600">
{connected ? 'Подключено к live-мониторингу' : 'Нет подключения к мониторингу'}
</span>
</div>
{/* Alerts */}
{alerts.length > 0 && (
<div className="bg-yellow-50 border border-yellow-200 rounded-xl p-4">
<h3 className="font-bold text-yellow-800 mb-2"> Предупреждения</h3>
<div className="space-y-1">
{alerts.map((alert, idx) => (
<div key={idx} className="text-yellow-700 text-sm">
{alert.message}
</div>
))}
</div>
</div>
)}
{/* Real-time stats cards */}
<div className="grid grid-cols-3 gap-4">
<div className="bg-white rounded-xl p-6 shadow-sm">
<div className="font-bold text-gray-700 mb-2">CPU</div>
<div className="text-3xl text-ospab-primary font-bold">
{realtimeStats?.data?.cpu ? (realtimeStats.data.cpu * 100).toFixed(1) : stats?.data?.cpu ? (stats.data.cpu * 100).toFixed(1) : '—'}%
</div>
</div>
<div className="bg-white rounded-xl p-6 shadow-sm">
<div className="font-bold text-gray-700 mb-2">RAM</div>
<div className="text-3xl text-ospab-primary font-bold">
{realtimeStats?.data?.memory?.usage?.toFixed(1) || stats?.data?.memory?.usage?.toFixed(1) || '—'}%
</div>
</div>
<div className="bg-white rounded-xl p-6 shadow-sm">
<div className="font-bold text-gray-700 mb-2">Disk</div>
<div className="text-3xl text-ospab-primary font-bold">
{realtimeStats?.data?.disk?.usage?.toFixed(1) || '—'}%
</div>
</div>
</div>
{/* Charts */}
{realtimeStats?.data?.rrdData && realtimeStats.data.rrdData.length > 0 && (
<div className="bg-white rounded-xl p-6 shadow-sm">
<h3 className="font-bold text-gray-800 mb-4">История использования (последний час)</h3>
<ResponsiveContainer width="100%" height={300}>
<LineChart data={realtimeStats.data.rrdData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="time" hide />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="cpu" stroke="#8b5cf6" name="CPU %" />
<Line type="monotone" dataKey="mem" stroke="#3b82f6" name="Memory (bytes)" />
</LineChart>
</ResponsiveContainer>
</div>
)}
{/* Detailed stats */}
<div className="bg-gray-100 rounded-xl p-6">
<div className="mb-2 font-bold">Детальная статистика</div>
<div className="grid grid-cols-2 gap-4">
<div className="bg-white rounded-lg p-4">
<div className="text-sm text-gray-600">Memory Used</div>
<div className="text-lg font-semibold">
{realtimeStats?.data?.memory?.used
? `${(realtimeStats.data.memory.used / (1024 * 1024 * 1024)).toFixed(2)} GB`
: '—'}
</div>
</div>
<div className="bg-white rounded-lg p-4">
<div className="text-sm text-gray-600">Memory Max</div>
<div className="text-lg font-semibold">
{realtimeStats?.data?.memory?.max
? `${(realtimeStats.data.memory.max / (1024 * 1024 * 1024)).toFixed(2)} GB`
: '—'}
</div>
</div>
<div className="bg-white rounded-lg p-4">
<div className="text-sm text-gray-600">Network In</div>
<div className="text-lg font-semibold">
{realtimeStats?.data?.network?.in
? `${(realtimeStats.data.network.in / (1024 * 1024)).toFixed(2)} MB`
: '—'}
</div>
</div>
<div className="bg-white rounded-lg p-4">
<div className="text-sm text-gray-600">Network Out</div>
<div className="text-lg font-semibold">
{realtimeStats?.data?.network?.out
? `${(realtimeStats.data.network.out / (1024 * 1024)).toFixed(2)} MB`
: '—'}
</div>
</div>
</div>
</div>
</div>
)}
{activeTab === 'manage' && (
<div className="mb-2 font-bold">Графики нагрузки</div>
<div className="flex gap-6">
<button className="bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-full font-bold" onClick={() => handleAction('start')}>Запустить</button>
<button className="bg-yellow-500 hover:bg-yellow-600 text-white px-6 py-3 rounded-full font-bold" onClick={() => handleAction('restart')}>Перезагрузить</button>
<button className="bg-red-500 hover:bg-red-600 text-white px-6 py-3 rounded-full font-bold" onClick={() => handleAction('stop')}>Остановить</button>
<div className="w-1/2 h-32 bg-white rounded-lg shadow-inner flex flex-col items-center justify-center">
<div className="font-bold text-gray-700">CPU</div>
<div className="text-2xl text-ospab-primary">{stats?.data?.cpu ? (stats.data.cpu * 100).toFixed(1) : '—'}%</div>
</div>
<div className="w-1/2 h-32 bg-white rounded-lg shadow-inner flex flex-col items-center justify-center">
<div className="font-bold text-gray-700">RAM</div>
<div className="text-2xl text-ospab-primary">{stats?.data?.memory?.usage ? stats.data.memory.usage.toFixed(1) : '—'}%</div>
</div>
</div>
</div>
)}
{activeTab === 'snapshots' && (
<SnapshotsSection serverId={server.id} />
)}
{activeTab === 'resize' && (
<div className="bg-gray-100 rounded-xl p-6">
<h3 className="text-xl font-bold mb-4">Изменение конфигурации сервера</h3>
<p className="text-gray-600 mb-4">
Вы можете увеличить или уменьшить ресурсы вашего сервера (CPU, RAM, диск).
Изменения вступят в силу после перезапуска сервера.
</p>
{activeTab === 'manage' && server && (
<div className="flex flex-col gap-2">
<div className="flex gap-6">
<button
onClick={() => setShowResizeModal(true)}
className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold hover:bg-opacity-90"
className={`bg-green-500 hover:bg-green-600 text-white px-6 py-3 rounded-full font-bold flex items-center justify-center ${server.status === 'running' ? 'opacity-50 cursor-not-allowed' : ''}`}
onClick={() => handleAction('start')}
disabled={server.status === 'running' || loading}
>
Изменить конфигурацию
{loading && activeAction === 'start' ? (
<span className="flex items-center gap-2">
<svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
</svg>
Выполняется...
</span>
) : 'Запустить'}
</button>
<button
className={`bg-yellow-500 hover:bg-yellow-600 text-white px-6 py-3 rounded-full font-bold flex items-center justify-center ${server.status !== 'running' ? 'opacity-50 cursor-not-allowed' : ''}`}
onClick={() => handleAction('restart')}
disabled={server.status !== 'running' || loading}
>
{loading && activeAction === 'restart' ? (
<span className="flex items-center gap-2">
<svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
</svg>
Выполняется...
</span>
) : 'Перезагрузить'}
</button>
<button
className={`bg-red-500 hover:bg-red-600 text-white px-6 py-3 rounded-full font-bold flex items-center justify-center ${server.status === 'stopped' ? 'opacity-50 cursor-not-allowed' : ''}`}
onClick={() => handleAction('stop')}
disabled={server.status === 'stopped' || loading}
>
{loading && activeAction === 'stop' ? (
<span className="flex items-center gap-2">
<svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
</svg>
Выполняется...
</span>
) : 'Остановить'}
</button>
</div>
{success && (
<div className="text-green-600 text-base font-semibold mt-2">{success}</div>
)}
{error && (
<div className="text-red-500 text-base font-semibold mt-2">{error}</div>
)}
</div>
)}
{activeTab === 'security' && (
{activeTab === 'network' && (
<div className="bg-gray-100 rounded-xl p-6 text-center text-gray-500">Сеть: здесь будет управление сетевыми настройками</div>
)}
{activeTab === 'backups' && (
<div className="bg-gray-100 rounded-xl p-6 text-center text-gray-500">Бэкапы: здесь будет управление резервными копиями</div>
)}
{activeTab === 'monitoring' && (
<div className="bg-gray-100 rounded-xl p-6 text-center text-gray-500">Мониторинг: здесь будет расширенный мониторинг</div>
)}
{activeTab === 'logs' && (
<div className="bg-gray-100 rounded-xl p-6 text-center text-gray-500">Логи: здесь будут логи сервера</div>
)}
{activeTab === 'security' && server && (
<div className="space-y-4">
<button className="bg-ospab-primary text-white px-6 py-3 rounded-full font-bold" onClick={handleGenerateRoot}>Сгенерировать новый root-пароль</button>
{showRoot && newRoot && (
<div className="bg-gray-100 rounded-xl p-6 flex flex-col items-center">
<div className="mb-2 font-bold text-lg">Ваш новый root-пароль:</div>
<div className="font-mono text-xl bg-white px-6 py-3 rounded-lg shadow-inner select-all">{newRoot}</div>
<div className="text-gray-500 mt-2">Скопируйте пароль — он будет показан только один раз!</div>
<div
className="font-mono text-xl bg-white px-6 py-3 rounded-lg shadow-inner"
style={{ userSelect: 'none', WebkitUserSelect: 'none' }}
>{newRoot.replace(/./g, '*')}</div>
<button
className="bg-ospab-primary text-white px-2 py-1 rounded text-xs font-bold hover:bg-ospab-primary-dark transition mt-2"
onClick={() => setShowRoot(false)}
>Скрыть</button>
</div>
)}
{success && (
<div className="text-green-600 text-base font-semibold mt-2">{success}</div>
)}
{error && (
<div className="text-red-500 text-base font-semibold mt-2">{error}</div>
)}
</div>
)}
</main>
</div>
{/* Resize Modal */}
{showResizeModal && (
<ResizeModal
serverId={server.id}
onClose={() => setShowResizeModal(false)}
onSuccess={() => {
// Reload server data after resize
const fetchServer = async () => {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const res = await axios.get(`http://localhost:5000/api/server/${id}`, { headers });
setServer(res.data);
};
fetchServer();
}}
/>
)}
</div>
);
};

View File

@@ -21,7 +21,7 @@ const Servers: React.FC = () => {
try {
const token = localStorage.getItem('access_token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};
const res = await axios.get('http://localhost:5000/api/server', { headers });
const res = await axios.get('https://ospab.host:5000/api/server', { headers });
console.log('Ответ API серверов:', res.data);
// Защита от получения HTML вместо JSON
if (typeof res.data === 'string' && res.data.startsWith('<!doctype html')) {
@@ -47,9 +47,6 @@ const Servers: React.FC = () => {
<div className="p-8 bg-white rounded-3xl shadow-xl max-w-4xl mx-auto">
<div className="flex items-center justify-between mb-6">
<h2 className="text-3xl font-bold text-gray-800">Мои серверы</h2>
{servers.length === 0 && !loading && !error && (
<a href="/tariffs" className="bg-ospab-primary text-white px-4 py-2 rounded font-bold hover:bg-ospab-primary-dark transition">Купить сервер</a>
)}
</div>
{loading ? (
<p className="text-lg text-gray-500">Загрузка...</p>

View File

@@ -32,7 +32,7 @@ const TicketResponse: React.FC = () => {
setError('');
try {
const token = localStorage.getItem('access_token');
const res = await axios.get('http://localhost:5000/api/ticket', {
const res = await axios.get('https://ospab.host:5000/api/ticket', {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
@@ -52,7 +52,7 @@ const TicketResponse: React.FC = () => {
setError('');
try {
const token = localStorage.getItem('access_token');
await axios.post('http://localhost:5000/api/ticket/respond', {
await axios.post('https://ospab.host:5000/api/ticket/respond', {
ticketId,
message: responseMsg[ticketId]
}, {
@@ -74,7 +74,7 @@ const TicketResponse: React.FC = () => {
setError('');
try {
const token = localStorage.getItem('access_token');
await axios.post('http://localhost:5000/api/ticket/close', { ticketId }, {
await axios.post('https://ospab.host:5000/api/ticket/close', { ticketId }, {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});

View File

@@ -39,7 +39,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
const fetchTickets = async () => {
try {
const token = localStorage.getItem('access_token');
const res = await axios.get('http://localhost:5000/api/ticket', {
const res = await axios.get('https://ospab.host:5000/api/ticket', {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
@@ -58,7 +58,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
const token = localStorage.getItem('access_token');
if (!token) return;
const headers = { Authorization: `Bearer ${token}` };
const userRes = await axios.get('http://localhost:5000/api/auth/me', { headers });
const userRes = await axios.get('https://ospab.host:5000/api/auth/me', { headers });
setUserData({
user: userRes.data.user,
balance: userRes.data.user.balance ?? 0,
@@ -81,7 +81,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
setLoading(true);
try {
const token = localStorage.getItem('access_token');
await axios.post('http://localhost:5000/api/ticket/create', { title, message }, {
await axios.post('https://ospab.host:5000/api/ticket/create', { title, message }, {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
@@ -99,7 +99,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
const respondTicket = async (ticketId: number) => {
const token = localStorage.getItem('access_token');
await axios.post('http://localhost:5000/api/ticket/respond', { ticketId, message: responseMsg }, {
await axios.post('https://ospab.host:5000/api/ticket/respond', { ticketId, message: responseMsg }, {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});
@@ -110,7 +110,7 @@ const TicketsPage: React.FC<TicketsPageProps> = ({ setUserData }) => {
const closeTicket = async (ticketId: number) => {
const token = localStorage.getItem('access_token');
await axios.post('http://localhost:5000/api/ticket/close', { ticketId }, {
await axios.post('https://ospab.host:5000/api/ticket/close', { ticketId }, {
withCredentials: true,
headers: token ? { Authorization: `Bearer ${token}` } : {}
});

View File

@@ -24,7 +24,7 @@ const LoginPage = () => {
setError('');
setIsLoading(true);
try {
const response = await axios.post('http://localhost:5000/api/auth/login', {
const response = await axios.post('https://ospab.host:5000/api/auth/login', {
email: email,
password: password,
});

View File

@@ -14,7 +14,7 @@ const RegisterPage = () => {
setError(''); // Очищаем предыдущие ошибки
try {
await axios.post('http://localhost:5000/api/auth/register', {
await axios.post('https://ospab.host:5000/api/auth/register', {
username: username,
email: email,
password: password

View File

@@ -1,20 +1,19 @@
import { useState, useEffect, useContext } from 'react';
import { useState, useEffect } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import AuthContext from '../context/authcontext';
const TariffsPage = () => {
const [tariffs, setTariffs] = useState<Array<{id:number;name:string;price:number;description?:string}>>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const navigate = useNavigate();
const { isLoggedIn } = useContext(AuthContext);
useEffect(() => {
const fetchTariffs = async () => {
try {
const res = await axios.get('http://localhost:5000/api/tariff');
const res = await axios.get('https://ospab.host:5000/api/tariff');
console.log('Ответ API тарифов:', res.data);
if (Array.isArray(res.data)) {
setTariffs(res.data);
@@ -33,17 +32,16 @@ const TariffsPage = () => {
}, []);
const handleBuy = (tariffId: number) => {
if (!isLoggedIn) {
navigate('/login');
return;
}
navigate(`/dashboard/checkout?tariff=${tariffId}`);
};
return (
<div className="min-h-screen bg-gray-50 py-20">
<div className="container mx-auto px-4">
<h1 className="text-4xl md:text-5xl font-bold text-center mb-16 text-gray-900">Тарифы</h1>
<h1 className="text-4xl md:text-5xl font-bold text-center mb-6 text-gray-900">Тарифы</h1>
<p className="text-lg text-gray-600 text-center mb-10 max-w-2xl mx-auto">
Выберите тариф для размещения сайта или сервера. ospab.host надёжно и удобно!
</p>
{loading ? (
<p className="text-lg text-gray-500 text-center">Загрузка...</p>
) : error ? (

View File

@@ -13,7 +13,8 @@
"react-dom": "^19.1.1",
"react-router-dom": "^7.9.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
"web-vitals": "^2.1.4",
"undici": "^5.18.0"
},
"scripts": {
"start": "react-scripts start",
@@ -45,6 +46,7 @@
"prisma": "^6.16.1",
"bcrypt": "^5.1.0",
"cors": "^2.8.5",
"proxmox-api": "^1.0.0",
"dotenv": "^16.0.0",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.0",

View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View File

@@ -0,0 +1,10 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}", // ищет стили во всех компонентах
],
theme: {
extend: {},
},
plugins: [],
}

24
package-lock.json generated
View File

@@ -11,7 +11,8 @@
"dotenv": "^17.2.2",
"express": "^5.1.0",
"jsonwebtoken": "^9.0.2",
"prisma": "^6.16.1"
"prisma": "^6.16.1",
"proxmox-api": "^1.1.1"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
@@ -2635,6 +2636,18 @@
"node": ">= 0.6.0"
}
},
"node_modules/proxmox-api": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/proxmox-api/-/proxmox-api-1.1.1.tgz",
"integrity": "sha512-2qH7pxKBBHa7WtEBmxPaBY2FZEH2R04hqr9zD9PmErLzJ7RGGcfNcXoS/v5G4vBM2Igmnx0EAYBstPwwfDwHnA==",
"license": "GPL-3.0",
"dependencies": {
"undici": "^6.19.8"
},
"funding": {
"url": "https://github.com/sponsors/urielch"
}
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -3479,6 +3492,15 @@
"node": ">=14.17"
}
},
"node_modules/undici": {
"version": "6.22.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.22.0.tgz",
"integrity": "sha512-hU/10obOIu62MGYjdskASR3CUAiYaFTtC9Pa6vHyf//mAipSvSQg6od2CnJswq7fvzNS3zJhxoRkgNVaHurWKw==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "7.11.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.11.0.tgz",

View File

@@ -25,6 +25,7 @@
"dotenv": "^17.2.2",
"express": "^5.1.0",
"jsonwebtoken": "^9.0.2",
"prisma": "^6.16.1"
"prisma": "^6.16.1",
"proxmox-api": "^1.1.1"
}
}