fix: add ostp-control frontend to repository

This commit is contained in:
ospab 2026-05-26 21:38:15 +03:00
parent d3a07f3d32
commit 6f7de7c770
32 changed files with 7474 additions and 1 deletions

1
.gitignore vendored
View File

@ -32,5 +32,4 @@ wintun.dll
# Dev notes (not for repo) # Dev notes (not for repo)
.ai-rules.md .ai-rules.md
turn-harvesting-idea.md turn-harvesting-idea.md
ostp-control/
ostp-flutter/ ostp-flutter/

24
ostp-control/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
ostp-control/README.md Normal file
View File

@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

View File

@ -0,0 +1,22 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
globals: globals.browser,
},
},
])

13
ostp-control/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ostp-control</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

3517
ostp-control/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
ostp-control/package.json Normal file
View File

@ -0,0 +1,40 @@
{
"name": "ostp-control",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@types/qrcode": "^1.5.6",
"clsx": "^2.1.1",
"lucide-react": "^1.16.0",
"qrcode": "^1.5.4",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"react-router-dom": "^7.15.1",
"tailwind-merge": "^3.6.0"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@tailwindcss/vite": "^4.3.0",
"@types/node": "^24.12.3",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"autoprefixer": "^10.5.0",
"eslint": "^10.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.6.0",
"postcss": "^8.5.15",
"tailwindcss": "^4.3.0",
"typescript": "~6.0.2",
"typescript-eslint": "^8.59.2",
"vite": "^8.0.12"
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

View File

@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

184
ostp-control/src/App.css Normal file
View File

@ -0,0 +1,184 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}

177
ostp-control/src/App.tsx Normal file
View File

@ -0,0 +1,177 @@
import { HashRouter as Router, Routes, Route, Link, Navigate, useLocation } from 'react-router-dom';
import { Activity, Users, Settings, Shield, MoreVertical, RefreshCw, BookOpen, Wrench, History, Globe, LogOut } from 'lucide-react';
import { useState, useEffect, ReactNode } from 'react';
// Components
import Dashboard from './pages/Dashboard';
import Clients from './pages/Clients';
import SettingsPage from './pages/Settings';
import Wiki from './pages/Wiki';
import Tools from './pages/Tools';
import AuditLogs from './pages/AuditLogs';
import Login from './pages/Login';
// State and Context
import { api } from './lib/api';
import { LanguageProvider, useLanguage } from './lib/LanguageContext';
function AuthGuard({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
const location = useLocation();
useEffect(() => {
const checkAuth = async () => {
try {
await api.getServerStatus();
setIsAuthenticated(true);
} catch {
setIsAuthenticated(false);
}
};
checkAuth();
}, [location.pathname]);
if (isAuthenticated === null) {
return (
<div className="flex h-screen w-screen bg-background items-center justify-center text-white font-sans">
<RefreshCw className="w-8 h-8 animate-spin text-primary" />
</div>
);
}
if (!isAuthenticated) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
return <>{children}</>;
}
function MainLayout() {
const { t, language, setLanguage } = useLanguage();
const [isSidebarOpen, setSidebarOpen] = useState(true);
return (
<div className="flex h-screen bg-background text-text overflow-hidden">
{/* Sidebar */}
<aside className={`bg-surface-light border-r border-white/5 transition-all duration-300 ${isSidebarOpen ? 'w-64' : 'w-20'} flex flex-col`}>
<div className="h-16 flex items-center justify-center border-b border-white/5">
<Shield className="w-8 h-8 text-primary animate-pulse" />
{isSidebarOpen && <span className="ml-3 font-bold text-xl tracking-wider text-white">OSTP<span className="text-primary">CORE</span></span>}
</div>
<nav className="flex-1 py-6 flex flex-col gap-2 px-3">
<Link to="/" className="flex items-center gap-3 px-3 py-3 rounded-xl hover:bg-white/5 transition-colors text-text-muted hover:text-white">
<Activity className="w-5 h-5 text-primary" />
{isSidebarOpen && <span>{t('sidebar_dashboard')}</span>}
</Link>
<Link to="/clients" className="flex items-center gap-3 px-3 py-3 rounded-xl hover:bg-white/5 transition-colors text-text-muted hover:text-white">
<Users className="w-5 h-5 text-secondary" />
{isSidebarOpen && <span>{t('sidebar_clients')}</span>}
</Link>
<Link to="/tools" className="flex items-center gap-3 px-3 py-3 rounded-xl hover:bg-white/5 transition-colors text-text-muted hover:text-white">
<Wrench className="w-5 h-5 text-purple-400" />
{isSidebarOpen && <span>{t('sidebar_tools')}</span>}
</Link>
<Link to="/wiki" className="flex items-center gap-3 px-3 py-3 rounded-xl hover:bg-white/5 transition-colors text-text-muted hover:text-white">
<BookOpen className="w-5 h-5 text-blue-400" />
{isSidebarOpen && <span>{t('sidebar_wiki')}</span>}
</Link>
<Link to="/logs" className="flex items-center gap-3 px-3 py-3 rounded-xl hover:bg-white/5 transition-colors text-text-muted hover:text-white">
<History className="w-5 h-5 text-yellow-400" />
{isSidebarOpen && <span>{t('sidebar_history')}</span>}
</Link>
<div className="mt-auto">
<Link to="/settings" className="flex items-center gap-3 px-3 py-3 rounded-xl hover:bg-white/5 transition-colors text-text-muted hover:text-white">
<Settings className="w-5 h-5 text-text-muted" />
{isSidebarOpen && <span>{t('sidebar_settings')}</span>}
</Link>
</div>
</nav>
</aside>
{/* Main Content */}
<main className="flex-1 flex flex-col relative overflow-hidden">
{/* Header */}
<header className="h-16 glass z-10 flex items-center justify-between px-6 border-b border-white/5">
<div className="flex items-center gap-3">
<button
onClick={() => setSidebarOpen(!isSidebarOpen)}
className="p-2 rounded-lg hover:bg-white/5 text-text-muted transition-colors cursor-pointer"
>
<MoreVertical className="w-5 h-5" />
</button>
<button
onClick={() => {
import('./lib/api').then(({ clearApiAuth }) => clearApiAuth());
window.location.reload();
}}
className="text-xs text-text-muted hover:text-red-400 bg-white/5 hover:bg-red-500/10 border border-white/10 rounded-lg px-2.5 py-1.5 transition-colors cursor-pointer flex items-center gap-1.5"
>
<LogOut className="w-3.5 h-3.5" />
{t('header_reset_conn') || 'Logout'}
</button>
</div>
<div className="flex items-center gap-4">
{/* Language Switcher */}
<button
onClick={() => setLanguage(language === 'ru' ? 'en' : 'ru')}
className="flex items-center gap-1.5 text-xs text-white bg-white/5 hover:bg-white/10 border border-white/10 rounded-lg px-3 py-1.5 transition-all font-semibold cursor-pointer shadow-[0_0_10px_rgba(255,255,255,0.02)]"
>
<Globe className="w-3.5 h-3.5 text-primary" />
{language === 'ru' ? 'RU' : 'EN'}
</button>
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-secondary shadow-[0_0_10px_#22D3A5]"></div>
<span className="text-sm text-text-muted">{t('header_core_online')}</span>
</div>
</div>
</header>
{/* Page Content */}
<div className="flex-1 overflow-auto p-6 relative">
{/* Background decorative blobs */}
<div className="absolute top-[-10%] left-[-10%] w-[40%] h-[40%] rounded-full bg-primary/20 blur-[120px] pointer-events-none"></div>
<div className="absolute bottom-[-10%] right-[-10%] w-[40%] h-[40%] rounded-full bg-secondary/10 blur-[120px] pointer-events-none"></div>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/clients" element={<Clients />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/wiki" element={<Wiki />} />
<Route path="/tools" element={<Tools />} />
<Route path="/logs" element={<AuditLogs />} />
</Routes>
</div>
</main>
</div>
);
}
function AppContent() {
return (
<Router>
<Routes>
<Route path="/login" element={<Login onLoginSuccess={() => window.location.href = '#/'} />} />
<Route
path="/*"
element={
<AuthGuard>
<MainLayout />
</AuthGuard>
}
/>
</Routes>
</Router>
);
}
export default function App() {
return (
<LanguageProvider>
<AppContent />
</LanguageProvider>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -0,0 +1 @@
<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>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@ -0,0 +1,39 @@
@import "tailwindcss";
@theme {
--color-primary: #6C72FF;
--color-secondary: #22D3A5;
--color-surface: #151522;
--color-surface-light: #20202F;
--color-background: #08080F;
--color-text: #FFFFFF;
--color-text-muted: #888899;
}
:root {
background-color: var(--color-background);
color: var(--color-text);
color-scheme: dark;
}
body {
margin: 0;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* Glassmorphism utilities */
@utility glass {
background-color: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.1);
}
@utility glass-panel {
background-color: rgba(21, 21, 34, 0.7);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.05);
}

View File

@ -0,0 +1,53 @@
import React, { createContext, useContext, useState } from 'react';
import { translations } from './i18n';
import type { TranslationKey } from './i18n';
type Language = 'ru' | 'en';
interface LanguageContextType {
language: Language;
setLanguage: (lang: Language) => void;
t: (key: TranslationKey, params?: Record<string, string | number>) => string;
}
const LanguageContext = createContext<LanguageContextType | undefined>(undefined);
export function LanguageProvider({ children }: { children: React.ReactNode }) {
const [language, setLanguageState] = useState<Language>(() => {
const saved = localStorage.getItem('ostp_panel_lang');
if (saved === 'ru' || saved === 'en') return saved;
return navigator.language.startsWith('ru') ? 'ru' : 'en';
});
const setLanguage = (lang: Language) => {
setLanguageState(lang);
localStorage.setItem('ostp_panel_lang', lang);
};
const t = (key: TranslationKey, params?: Record<string, string | number>): string => {
const langDict = translations[language];
let val: string = langDict[key] || translations['en'][key] || String(key);
if (params) {
Object.entries(params).forEach(([k, v]) => {
val = val.replace(`{${k}}`, String(v));
});
}
return val;
};
return (
<LanguageContext.Provider value={{ language, setLanguage, t }}>
{children}
</LanguageContext.Provider>
);
}
export function useLanguage() {
const context = useContext(LanguageContext);
if (!context) {
throw new Error('useLanguage must be used within a LanguageProvider');
}
return context;
}

132
ostp-control/src/lib/api.ts Normal file
View File

@ -0,0 +1,132 @@
export interface UserStatsSnapshot {
access_key: string;
bytes_up: number;
bytes_down: number;
connections: number;
limit_bytes: number | null;
online: boolean;
name?: string | null;
}
export interface ServerStatus {
version: string;
uptime_seconds: number;
active_users: number;
total_users: number;
}
export interface ApiResponse<T> {
ok: boolean;
data?: T;
error?: string;
}
// Helpers for localStorage state
const API_URL_KEY = 'ostp_api_url';
const API_TOKEN_KEY = 'ostp_api_token';
export function getApiSettings() {
// Use relative path for embedded panel, fallback to localhost for dev
const isDev = import.meta.env?.DEV || window.location.hostname === 'localhost' && window.location.port === '5173';
const url = isDev ? 'http://localhost:9090' : window.location.pathname.replace(/\/$/, '');
const token = localStorage.getItem(API_TOKEN_KEY) || '';
return { url, token };
}
export function saveApiToken(token: string) {
localStorage.setItem(API_TOKEN_KEY, token.trim());
}
export function clearApiAuth() {
localStorage.removeItem(API_TOKEN_KEY);
}
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const { url, token } = getApiSettings();
const headers = new Headers(options.headers || {});
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
if (!(options.body instanceof FormData) && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
}
const response = await fetch(`${url}${path}`, {
...options,
headers,
});
if (response.status === 401) {
throw new Error('Unauthorized API Token');
}
const json: ApiResponse<T> = await response.json();
if (!json.ok) {
throw new Error(json.error || 'API Request failed');
}
return json.data!;
}
export const api = {
login: async (username: string, password?: string): Promise<string> => {
const { url } = getApiSettings();
const response = await fetch(`${url}/api/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (response.status === 401) throw new Error('Invalid credentials');
const json = await response.json();
if (!json.ok) throw new Error(json.error || 'Login failed');
saveApiToken(json.data.token);
return json.data.token;
},
getServerStatus: () => request<ServerStatus>('/api/server/status'),
getServerConfig: () => request<any>('/api/server/config'),
updateServerConfig: (config: any) => request<boolean>('/api/server/config', {
method: 'PUT',
body: JSON.stringify(config),
}),
listUsers: () => request<UserStatsSnapshot[]>('/api/users'),
createUser: (name: string | null, limitBytes: number | null, accessKey?: string) =>
request<string>('/api/users', {
method: 'POST',
body: JSON.stringify({ name, limit_bytes: limitBytes, access_key: accessKey }),
}),
updateUser: (key: string, name: string | null, limitBytes: number | null) =>
request<string>(`/api/users/${key}`, {
method: 'PUT',
body: JSON.stringify({ name, limit_bytes: limitBytes }),
}),
deleteUser: (key: string) =>
request<string>(`/api/users/${key}`, {
method: 'DELETE',
}),
resetUserStats: (key: string) =>
request<boolean>(`/api/users/${key}/reset`, {
method: 'POST',
}),
getSubscriptionLink: async (key: string): Promise<string> => {
const { url } = getApiSettings();
const response = await fetch(`${url}/api/subscribe/${key}`, {
headers: {
'Accept': 'text/plain',
}
});
const json = await response.json();
if (json.ok && json.data) {
return json.data;
}
throw new Error(json.error || 'Failed to fetch subscription link');
}
};

View File

@ -0,0 +1,43 @@
export interface AuditLogEntry {
id: string;
time: string;
eventEn: string;
eventRu: string;
success: boolean;
}
const AUDIT_LOG_KEY = 'ostp_audit_logs';
export function getAuditLogs(): AuditLogEntry[] {
try {
const raw = localStorage.getItem(AUDIT_LOG_KEY);
return raw ? JSON.parse(raw) : [];
} catch {
return [];
}
}
export function addAuditLog(eventEn: string, eventRu: string, success: boolean) {
try {
const logs = getAuditLogs();
const newEntry: AuditLogEntry = {
id: Math.random().toString(36).substring(2, 9),
time: new Date().toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' }),
eventEn,
eventRu,
success,
};
// Keep last 100 logs
const updated = [newEntry, ...logs].slice(0, 100);
localStorage.setItem(AUDIT_LOG_KEY, JSON.stringify(updated));
// Dispatch custom event to notify listeners
window.dispatchEvent(new Event('ostp_audit_log_added'));
} catch (e) {
console.error('Failed to write audit log', e);
}
}
export function clearAuditLogs() {
localStorage.removeItem(AUDIT_LOG_KEY);
window.dispatchEvent(new Event('ostp_audit_log_added'));
}

View File

@ -0,0 +1,346 @@
export const translations = {
ru: {
sidebar_dashboard: 'Панель',
sidebar_clients: 'Клиенты',
sidebar_settings: 'Настройки',
sidebar_tools: 'Инструменты',
sidebar_wiki: 'Документация',
sidebar_history: 'История',
header_reset_conn: 'Сбросить подключение',
header_core_online: 'Ядро онлайн',
header_core_offline: 'Ядро оффлайн',
conn_setup_title: 'Подключение к ядру',
conn_setup_sub: 'Панель управления VPN сервером',
conn_setup_header: 'Первоначальная настройка',
conn_setup_desc: 'Пожалуйста, укажите адрес API управления и токен авторизации. Токен генерируется при инициализации сервера и находится в файле config.json в поле api.token.',
conn_setup_url_label: 'Адрес API сервера',
conn_setup_token_label: 'API Токен авторизации (Bearer)',
conn_setup_token_placeholder: 'Введите токен из config.json',
conn_setup_btn: 'Проверить и войти',
conn_setup_btn_loading: 'Проверка соединения...',
conn_setup_success: 'Успешно подключено!',
conn_setup_error: 'Ошибка соединения: ',
db_title: 'Dashboard',
db_subtitle: 'Статистика в реальном времени и параметры сервера',
db_active_users: 'Активные клиенты',
db_active_users_sub: 'Пользователи онлайн',
db_connections: 'Соединения',
db_connections_sub: 'Активные туннели',
db_uploaded: 'Отправлено (Tx)',
db_uploaded_sub: 'Исходящий трафик',
db_downloaded: 'Скачано (Rx)',
db_downloaded_sub: 'Входящий трафик',
db_properties: 'Параметры ядра',
db_properties_sub: 'Конфигурация сетевых служб из config.json',
db_api_latency: 'Задержка API',
db_core_version: 'Версия ядра',
db_listen_addr: 'Порт прослушивания',
db_api_bind: 'Адрес API',
db_reality_status: 'Статус Reality',
db_reality_dest: 'Домен маскировки',
db_outbound_proxy: 'Исходящий прокси',
db_fallback_status: 'TCP Fallback',
db_fallback_target: 'Сервер Fallback',
db_load_title: 'Загрузка системы',
db_load_users: 'Лимит пользователей',
db_load_connections: 'Загрузка соединений',
db_total_traffic: 'Общий трафик',
db_traffic_per_user: 'Трафик на клиента',
cl_title: 'Клиенты',
cl_subtitle: 'Управление ключами доступа, описаниями и лимитами трафика',
cl_add: 'Добавить клиента',
cl_search: 'Поиск по имени или ключу доступа...',
cl_status: 'Статус',
cl_name: 'Имя клиента',
cl_unnamed: 'Без имени',
cl_key: 'Ключ доступа',
cl_usage: 'Использовано (Tx / Rx)',
cl_limit: 'Лимит',
cl_actions: 'Действия',
cl_active: 'Активен',
cl_offline: 'Неактивен',
cl_unlimited: 'Безлимитный',
cl_share_title: 'Профиль подключения',
cl_share_sub: 'Используйте эту ссылку для настройки клиента OSTP на вашем устройстве.',
cl_share_link: 'Ссылка подключения OSTP',
cl_how_to: 'Инструкция по подключению:',
cl_how_to_1: 'Установите приложение OSTP Client на ваше устройство.',
cl_how_to_2: 'Скопируйте ссылку подключения выше.',
cl_how_to_3: 'Импортируйте ссылку в клиенте или запустите через CLI:',
cl_add_title: 'Добавить нового клиента',
cl_edit_title: 'Редактировать клиента',
cl_form_name: 'Имя / Описание клиента',
cl_form_limit: 'Лимит трафика',
cl_form_limit_sub: 'Оставьте пустым для безлимитного',
cl_form_custom: 'Свой ключ доступа (опционально)',
cl_form_custom_sub: 'Будет сгенерирован автоматически, если оставить пустым',
cl_form_save: 'Сохранить изменения',
cl_confirm_delete: 'Вы уверены, что хотите удалить этот ключ доступа? Все активные сессии этого клиента будут мгновенно разорваны.',
cl_confirm_reset: 'Сбросить счетчики трафика для этого клиента?',
cl_copied: 'Скопировано в буфер обмена!',
cl_share_scan: 'Отсканируйте камерой, чтобы получить ссылку',
cl_share_download_qr: 'Скачать QR-код',
st_title: 'Настройки',
st_subtitle: 'Интерактивный конфигуратор ядра OSTP и параметры панели',
st_reset: 'Сбросить изменения',
st_tab_ui: 'Настройки ядра (UI)',
st_tab_json: 'Редактор JSON',
st_tab_conn: 'Подключение панели',
st_save_btn: 'Сохранить настройки',
st_save_success: 'Конфигурация сохранена! Изменения применены ядром через hot-reload.',
st_save_error: 'Ошибка сохранения: ',
st_conn_title: 'Связь с Management API',
st_conn_desc: 'Укажите параметры подключения текущего экземпляра веб-интерфейса к демону ядра OSTP.',
st_conn_url: 'API Адрес подключения',
st_conn_token: 'Авторизационный токен (Bearer)',
st_conn_token_sub: 'Вставьте токен из config.json',
st_conn_test: 'Проверить связь',
st_conn_save: 'Сохранить настройки',
st_conn_success: 'Связь установлена! Версия: {version}, Сессий: {users}',
st_conn_error: 'Ошибка подключения: {error}',
st_raw_title: 'Редактирование сырого JSON',
st_raw_desc: 'Прямое изменение файла config.json. Любая синтаксическая ошибка JSON заблокирует отправку.',
st_ui_general: 'Общие настройки сервера',
st_ui_log: 'Уровень логирования (log_level)',
st_ui_port: 'Порт прослушивания (listen)',
st_ui_debug: 'Режим полной сетевой отладки протокола (debug)',
st_ui_api_title: 'Встроенный сервер API управления',
st_ui_api_enable: 'Включить встроенный сервер API управления',
st_ui_api_bind: 'Адрес привязки API (bind)',
st_ui_api_token: 'Токен доступа (api.token)',
st_ui_api_warning: 'Внимание! Изменение порта или токена API потребует ручного обновления настроек подключения в панели управления.',
st_ui_fb_title: 'TCP Fallback маскировка (Анти-детект)',
st_ui_fb_enable: 'Перенаправлять неопознанный TCP трафик на веб-сервер',
st_ui_fb_port: 'Входной TCP-порт (listen)',
st_ui_fb_target: 'Целевой веб-сервер (target)',
st_ui_rl_title: 'Параметры маскировки Reality (XTLS)',
st_ui_rl_enable: 'Активировать обфускацию Reality',
st_ui_rl_dest: 'Маскировочный домен-назначение (dest)',
st_ui_rl_pri: 'Приватный ключ Reality (X25519)',
st_ui_rl_pub: 'Публичный ключ Reality (pbk)',
st_ui_rl_sid: 'Короткий SID сессии (8 байт hex)',
st_ui_rl_sni: 'Список SNI доменов (через запятую)',
st_ui_ob_title: 'Исходящий трафик (Outbound Routing)',
st_ui_ob_enable: 'Пересылать трафик клиентов через сторонний прокси (outbound proxy)',
st_ui_ob_proto: 'Протокол прокси',
st_ui_ob_addr: 'Адрес прокси',
st_ui_ob_port: 'Порт прокси',
st_ui_ob_action: 'Действие по умолчанию',
st_ui_ob_action_direct: 'Напрямую с сервера (direct)',
st_ui_ob_action_proxy: 'Через прокси (proxy)',
tl_title: 'Инструменты',
tl_subtitle: 'Генератор ключей Reality, резервное копирование и диагностика',
tl_keygen_title: 'Генератор ключей Reality (X25519)',
tl_keygen_desc: 'Для маскировки Reality требуется пара ключей X25519. Сгенерируйте их здесь или выполните команду `ostp --generate-key` на сервере.',
tl_keygen_btn: 'Сгенерировать ключи',
tl_keygen_pub: 'Публичный ключ (pbk)',
tl_keygen_pri: 'Приватный ключ (private_key)',
tl_keygen_sid: 'Предлагаемый SID сессии (sid)',
tl_keygen_copy: 'Копировать и применить в Reality',
tl_keygen_applied: 'Ключи сгенерированы! Скопируйте их и вставьте во вкладку Настроек.',
tl_backup_title: 'Резервное копирование',
tl_backup_desc: 'Экспортируйте текущую конфигурацию сервера в файл или восстановите настройки из файла бэкапа.',
tl_backup_export: 'Скачать бэкап config.json',
tl_backup_import_zone: 'Перетащите файл config.json сюда или кликните для выбора',
tl_backup_import_btn: 'Восстановить из файла',
tl_backup_import_success: 'Конфигурация успешно восстановлена! Изменения применены ядром.',
tl_backup_import_error: 'Ошибка восстановления бэкапа: ',
tl_diag_title: 'Диагностика API',
tl_diag_ping: 'Проверка задержки (Ping)',
tl_diag_status: 'Статус соединения',
wk_title: 'Документация',
wk_subtitle: 'Справочники и руководства, загруженные в реальном времени с GitHub',
wk_tab_guide: 'Конфигурация config.json',
wk_tab_api: 'Справочник API',
wk_loading: 'Загрузка документов с GitHub...',
wk_load_error: 'Ошибка загрузки с GitHub. Отображается локальная резервная копия:',
au_title: 'История действий',
au_subtitle: 'Журнал административных событий текущей сессии веб-панели',
au_empty: 'Журнал пуст',
au_clear: 'Очистить журнал',
au_time: 'Время',
au_event: 'Событие',
au_status: 'Результат',
},
en: {
sidebar_dashboard: 'Dashboard',
sidebar_clients: 'Clients',
sidebar_settings: 'Settings',
sidebar_tools: 'Tools',
sidebar_wiki: 'Wiki',
sidebar_history: 'Audit Logs',
header_reset_conn: 'Reset Connection',
header_core_online: 'Core Online',
header_core_offline: 'Core Offline',
conn_setup_title: 'Connection Setup',
conn_setup_sub: 'VPN Server Control Panel',
conn_setup_header: 'Initial Setup',
conn_setup_desc: 'Please specify the management API address and authorization token. The token is generated during initialization and can be found in config.json under api.token.',
conn_setup_url_label: 'Server API Address',
conn_setup_token_label: 'API Auth Token (Bearer)',
conn_setup_token_placeholder: 'Enter token from config.json',
conn_setup_btn: 'Test and Connect',
conn_setup_btn_loading: 'Testing connection...',
conn_setup_success: 'Connected successfully!',
conn_setup_error: 'Connection failed: ',
db_title: 'Dashboard',
db_subtitle: 'Real-time metrics and server overview',
db_active_users: 'Active Clients',
db_active_users_sub: 'Online users',
db_connections: 'Connections',
db_connections_sub: 'Active tunnels',
db_uploaded: 'Uploaded (Tx)',
db_uploaded_sub: 'Outbound traffic',
db_downloaded: 'Downloaded (Rx)',
db_downloaded_sub: 'Inbound traffic',
db_properties: 'Core Properties',
db_properties_sub: 'Network service configurations from config.json',
db_api_latency: 'API Latency',
db_core_version: 'Core Version',
db_listen_addr: 'Listen Port',
db_api_bind: 'API Address',
db_reality_status: 'Reality Obfuscation',
db_reality_dest: 'Masquerade Destination',
db_outbound_proxy: 'Outbound Proxy',
db_fallback_status: 'TCP Fallback',
db_fallback_target: 'Fallback Target',
db_load_title: 'Capacity Load',
db_load_users: 'User limit utilization',
db_load_connections: 'Connection capacity load',
db_total_traffic: 'Total Handled Traffic',
db_traffic_per_user: 'Avg Traffic per Client',
cl_title: 'Clients',
cl_subtitle: 'Manage access keys, descriptions, and traffic limits',
cl_add: 'Add Client',
cl_search: 'Search by client name or access key...',
cl_status: 'Status',
cl_name: 'Client Name',
cl_unnamed: 'Unnamed Client',
cl_key: 'Access Key',
cl_usage: 'Usage (Tx / Rx)',
cl_limit: 'Limit',
cl_actions: 'Actions',
cl_active: 'Active',
cl_offline: 'Inactive',
cl_unlimited: 'Unlimited',
cl_share_title: 'Connection Profile',
cl_share_sub: 'Use this link to configure the OSTP client on your device.',
cl_share_link: 'OSTP Connection Link',
cl_how_to: 'How to connect:',
cl_how_to_1: 'Install OSTP Client app on your device.',
cl_how_to_2: 'Copy the connection link above.',
cl_how_to_3: 'Import the link in the client or run via CLI:',
cl_add_title: 'Add New Client',
cl_edit_title: 'Edit Client Settings',
cl_form_name: 'Client Name / Description',
cl_form_limit: 'Traffic Limit',
cl_form_limit_sub: 'Leave empty for unlimited',
cl_form_custom: 'Custom Access Key (Optional)',
cl_form_custom_sub: 'Random key generated if left blank',
cl_form_save: 'Save Changes',
cl_confirm_delete: 'Are you sure you want to delete this access key? Active connections will be dropped immediately.',
cl_confirm_reset: 'Reset traffic counters for this client?',
cl_copied: 'Copied to clipboard!',
cl_share_scan: 'Scan with your camera to get the link',
cl_share_download_qr: 'Download QR Code',
st_title: 'Settings',
st_subtitle: 'Interactive configuration of OSTP core and panel parameters',
st_reset: 'Reset Changes',
st_tab_ui: 'Core Settings (UI)',
st_tab_json: 'Raw JSON Editor',
st_tab_conn: 'Panel Connection',
st_save_btn: 'Save Configuration',
st_save_success: 'Configuration saved successfully! Core reloaded via hot-reload.',
st_save_error: 'Save failed: ',
st_conn_title: 'Connection to Management API',
st_conn_desc: 'Specify connection parameters of this web interface to the OSTP core daemon.',
st_conn_url: 'API Connection URL',
st_conn_token: 'Authorization Token (Bearer)',
st_conn_token_sub: 'Insert token from config.json',
st_conn_test: 'Test Connection',
st_conn_save: 'Save Connection Settings',
st_conn_success: 'Connection established! Version: {version}, Active: {users}',
st_conn_error: 'Connection failed: {error}',
st_raw_title: 'Edit Raw JSON',
st_raw_desc: 'Direct modification of config.json. Any syntax error will block the submission.',
st_ui_general: 'General Server Settings',
st_ui_log: 'Logging Level (log_level)',
st_ui_port: 'Listen Port (listen)',
st_ui_debug: 'Full network debug log mode (debug)',
st_ui_api_title: 'Management API Server',
st_ui_api_enable: 'Enable built-in management API server',
st_ui_api_bind: 'API Bind Address (bind)',
st_ui_api_token: 'API Token (api.token)',
st_ui_api_warning: 'Warning! Changing API port/token will require manual update of panel settings.',
st_ui_fb_title: 'TCP Fallback (Anti-detection)',
st_ui_fb_enable: 'Forward unrecognized TCP traffic to web server',
st_ui_fb_port: 'Input TCP port (listen)',
st_ui_fb_target: 'Target web server (target)',
st_ui_rl_title: 'Reality Obfuscation Parameters (XTLS)',
st_ui_rl_enable: 'Activate Reality obfuscation',
st_ui_rl_dest: 'Masquerade domain destination (dest)',
st_ui_rl_pri: 'Reality private key (X25519)',
st_ui_rl_pub: 'Reality public key (pbk)',
st_ui_rl_sid: 'Short session SID (8 bytes hex)',
st_ui_rl_sni: 'SNI domains list (comma separated)',
st_ui_ob_title: 'Outbound Routing',
st_ui_ob_enable: 'Forward client traffic through third-party proxy (outbound proxy)',
st_ui_ob_proto: 'Proxy Protocol',
st_ui_ob_addr: 'Proxy Address',
st_ui_ob_port: 'Proxy Port',
st_ui_ob_action: 'Default Action',
st_ui_ob_action_direct: 'Direct (direct)',
st_ui_ob_action_proxy: 'Proxy (proxy)',
tl_title: 'Tools',
tl_subtitle: 'Reality key generation, config backups, and diagnostics',
tl_keygen_title: 'Reality X25519 Keypair Generator',
tl_keygen_desc: 'Reality masquerade requires an X25519 keypair. Generate it here or run `ostp --generate-key` on the server.',
tl_keygen_btn: 'Generate Keypair',
tl_keygen_pub: 'Public Key (pbk)',
tl_keygen_pri: 'Private Key (private_key)',
tl_keygen_sid: 'Suggested Session SID (sid)',
tl_keygen_copy: 'Copy and Apply to Reality Config',
tl_keygen_applied: 'Keypair generated! Copy and paste them into Settings tab.',
tl_backup_title: 'Configuration Backups',
tl_backup_desc: 'Export current server configuration to a file, or restore it by uploading a backup file.',
tl_backup_export: 'Download Backup config.json',
tl_backup_import_zone: 'Drag & drop backup config.json here, or click to browse',
tl_backup_import_btn: 'Restore from file',
tl_backup_import_success: 'Configuration restored successfully! Changes reloaded.',
tl_backup_import_error: 'Failed to restore backup: ',
tl_diag_title: 'API Diagnostics',
tl_diag_ping: 'API Latency Check (Ping)',
tl_diag_status: 'API Connection Status',
wk_title: 'Wiki & Docs',
wk_subtitle: 'Guides and API references loaded in real-time from GitHub',
wk_tab_guide: 'Configuration Guide',
wk_tab_api: 'API Endpoints Guide',
wk_loading: 'Loading documentation from GitHub...',
wk_load_error: 'Failed to load from GitHub. Showing local backup copy:',
au_title: 'Audit Logs',
au_subtitle: 'Local audit log of administrative actions in current session',
au_empty: 'History is empty',
au_clear: 'Clear Audit Logs',
au_time: 'Time',
au_event: 'Event',
au_status: 'Result',
}
} as const;
export type TranslationKey = keyof typeof translations.en;

10
ostp-control/src/main.tsx Normal file
View File

@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@ -0,0 +1,97 @@
import { useState, useEffect } from 'react';
import { History, Trash2, CheckCircle2, XCircle } from 'lucide-react';
import { useLanguage } from '../lib/LanguageContext';
import { getAuditLogs, clearAuditLogs } from '../lib/audit';
import type { AuditLogEntry } from '../lib/audit';
export default function AuditLogs() {
const { t, language } = useLanguage();
const [logs, setLogs] = useState<AuditLogEntry[]>([]);
const loadLogs = () => {
setLogs(getAuditLogs());
};
useEffect(() => {
loadLogs();
// Listen for log updates
window.addEventListener('ostp_audit_log_added', loadLogs);
return () => {
window.removeEventListener('ostp_audit_log_added', loadLogs);
};
}, []);
const handleClear = () => {
if (confirm(language === 'ru' ? 'Очистить журнал действий?' : 'Clear audit log history?')) {
clearAuditLogs();
}
};
return (
<div className="relative z-10 w-full max-w-5xl mx-auto space-y-6 animate-in fade-in duration-300">
{/* Page Title */}
<div className="flex justify-between items-end">
<div>
<h1 className="text-3xl font-bold tracking-tight mb-1 flex items-center gap-3">
<History className="w-8 h-8 text-primary" /> {t('au_title')}
</h1>
<p className="text-text-muted">{t('au_subtitle')}</p>
</div>
{logs.length > 0 && (
<button
onClick={handleClear}
className="flex items-center gap-2 bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/20 px-4 py-2.5 rounded-xl text-sm font-semibold transition-colors"
>
<Trash2 className="w-4 h-4" /> {t('au_clear')}
</button>
)}
</div>
{/* Logs Table */}
<div className="glass-panel rounded-2xl overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="border-b border-white/5 bg-white/[0.02]">
<th className="px-6 py-4 font-medium text-text-muted w-32">{t('au_time')}</th>
<th className="px-6 py-4 font-medium text-text-muted">{t('au_event')}</th>
<th className="px-6 py-4 font-medium text-text-muted w-32 text-right">{t('au_status')}</th>
</tr>
</thead>
<tbody className="divide-y divide-white/5">
{logs.map((log) => (
<tr key={log.id} className="hover:bg-white/[0.02] transition-colors font-sans">
<td className="px-6 py-4 text-sm text-text-muted font-mono">{log.time}</td>
<td className="px-6 py-4 text-sm font-medium text-white">
{language === 'ru' ? log.eventRu : log.eventEn}
</td>
<td className="px-6 py-4 text-right">
{log.success ? (
<span className="inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full bg-secondary/15 text-secondary border border-secondary/20">
<CheckCircle2 className="w-3.5 h-3.5" /> Success
</span>
) : (
<span className="inline-flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full bg-red-500/15 text-red-400 border border-red-500/20">
<XCircle className="w-3.5 h-3.5" /> Failed
</span>
)}
</td>
</tr>
))}
{logs.length === 0 && (
<tr>
<td colSpan={3} className="px-6 py-16 text-center text-text-muted">
<History className="w-12 h-12 mx-auto mb-4 opacity-20" />
<p className="text-sm font-medium">{t('au_empty')}</p>
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,629 @@
import { useState, useEffect, useRef } from 'react';
import { Users, Plus, Key, Trash2, Edit2, Copy, Search, RefreshCw, X, Share2, ShieldAlert, Download } from 'lucide-react';
import QRCode from 'qrcode';
import { api } from '../lib/api';
import type { UserStatsSnapshot } from '../lib/api';
import { useLanguage } from '../lib/LanguageContext';
import { addAuditLog } from '../lib/audit';
export default function Clients() {
const { t } = useLanguage();
const [users, setUsers] = useState<UserStatsSnapshot[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [errorMsg, setErrorMsg] = useState<string | null>(null);
// Modals state
const [showAddModal, setShowAddModal] = useState(false);
const [showEditModal, setShowEditModal] = useState(false);
const [showShareModal, setShowShareModal] = useState(false);
// Form fields
const [clientName, setClientName] = useState('');
const [clientLimit, setClientLimit] = useState('');
const [clientLimitUnit, setClientLimitUnit] = useState('GB');
const [clientCustomKey, setClientCustomKey] = useState('');
// Editing user state
const [editingUser, setEditingUser] = useState<UserStatsSnapshot | null>(null);
const [editName, setEditName] = useState('');
const [editLimit, setEditLimit] = useState('');
const [editLimitUnit, setEditLimitUnit] = useState('GB');
// Sharing user state
const [sharingUser, setSharingUser] = useState<UserStatsSnapshot | null>(null);
const [shareLink, setShareLink] = useState('');
const [isFetchingLink, setIsFetchingLink] = useState(false);
const qrCanvasRef = useRef<HTMLCanvasElement>(null);
const fetchUsers = async (showLoading = false) => {
if (showLoading) setIsLoading(true);
try {
const data = await api.listUsers();
setUsers(data || []);
setErrorMsg(null);
} catch (err: any) {
setErrorMsg(err.message || 'Failed to fetch clients');
} finally {
if (showLoading) setIsLoading(false);
}
};
useEffect(() => {
fetchUsers(true);
const interval = setInterval(() => {
fetchUsers(false);
}, 5000);
return () => clearInterval(interval);
}, []);
const handleAddClient = async (e: React.FormEvent) => {
e.preventDefault();
setErrorMsg(null);
let limitBytes: number | null = null;
if (clientLimit && !isNaN(Number(clientLimit))) {
const mult = clientLimitUnit === 'MB' ? 1024 * 1024 : clientLimitUnit === 'GB' ? 1024 * 1024 * 1024 : 1024 * 1024 * 1024 * 1024;
limitBytes = Number(clientLimit) * mult;
}
const nameToCreate = clientName.trim() || null;
const customKey = clientCustomKey.trim() || undefined;
try {
const createdKey = await api.createUser(nameToCreate, limitBytes, customKey);
setShowAddModal(false);
setClientName('');
setClientLimit('');
setClientCustomKey('');
fetchUsers(false);
addAuditLog(
`Created client "${nameToCreate || 'Unnamed'}" with key "${createdKey.substring(0, 8)}..."`,
`Создан клиент "${nameToCreate || 'Без имени'}" с ключом "${createdKey.substring(0, 8)}..."`,
true
);
} catch (err: any) {
setErrorMsg(err.message || 'Failed to create client');
addAuditLog(
`Failed to create client: ${err.message || err}`,
`Не удалось создать клиента: ${err.message || err}`,
false
);
}
};
const handleEditClient = async (e: React.FormEvent) => {
e.preventDefault();
if (!editingUser) return;
setErrorMsg(null);
let limitBytes: number | null = null;
if (editLimit && !isNaN(Number(editLimit))) {
const mult = editLimitUnit === 'MB' ? 1024 * 1024 : editLimitUnit === 'GB' ? 1024 * 1024 * 1024 : editLimitUnit === 'TB' ? 1024 * 1024 * 1024 * 1024 : 1;
limitBytes = Number(editLimit) * mult;
}
const nameToEdit = editName.trim() || null;
try {
await api.updateUser(editingUser.access_key, nameToEdit, limitBytes);
setShowEditModal(false);
setEditingUser(null);
fetchUsers(false);
addAuditLog(
`Updated client settings for key "${editingUser.access_key.substring(0, 8)}..." (Name: ${nameToEdit || 'None'}, Limit: ${limitBytes ? limitBytes + ' bytes' : 'Unlimited'})`,
`Обновлен клиент "${editingUser.access_key.substring(0, 8)}..." (Имя: ${nameToEdit || 'Нет'}, Лимит: ${limitBytes ? limitBytes + ' байт' : 'Безлимит'})`,
true
);
} catch (err: any) {
setErrorMsg(err.message || 'Failed to update client');
addAuditLog(
`Failed to edit client: ${err.message || err}`,
`Не удалось изменить настройки клиента: ${err.message || err}`,
false
);
}
};
const handleDeleteClient = async (key: string) => {
if (!confirm(t('cl_confirm_delete'))) return;
setErrorMsg(null);
try {
await api.deleteUser(key);
fetchUsers(false);
addAuditLog(
`Deleted client access key "${key.substring(0, 8)}..."`,
`Удален ключ доступа клиента "${key.substring(0, 8)}..."`,
true
);
} catch (err: any) {
setErrorMsg(err.message || 'Failed to delete client');
addAuditLog(
`Failed to delete client "${key.substring(0, 8)}...": ${err.message || err}`,
`Не удалось удалить клиента "${key.substring(0, 8)}...": ${err.message || err}`,
false
);
}
};
const handleResetStats = async (key: string) => {
if (!confirm(t('cl_confirm_reset'))) return;
setErrorMsg(null);
try {
await api.resetUserStats(key);
fetchUsers(false);
addAuditLog(
`Reset traffic counters for key "${key.substring(0, 8)}..."`,
`Сброшена статистика трафика для ключа "${key.substring(0, 8)}..."`,
true
);
} catch (err: any) {
setErrorMsg(err.message || 'Failed to reset client stats');
addAuditLog(
`Failed to reset traffic counters: ${err.message || err}`,
`Не удалось сбросить счетчики трафика: ${err.message || err}`,
false
);
}
};
const handleOpenShare = async (user: UserStatsSnapshot) => {
setSharingUser(user);
setShareLink('');
setIsFetchingLink(true);
setShowShareModal(true);
try {
const link = await api.getSubscriptionLink(user.access_key);
setShareLink(link);
} catch (err: any) {
setErrorMsg(err.message || 'Failed to fetch subscription share link');
setShowShareModal(false);
} finally {
setIsFetchingLink(false);
}
};
// Render QR code whenever shareLink changes
useEffect(() => {
if (shareLink && qrCanvasRef.current) {
QRCode.toCanvas(qrCanvasRef.current, shareLink, {
width: 180,
margin: 1,
color: {
dark: '#ffffff',
light: '#00000000',
},
});
}
}, [shareLink]);
const downloadQr = () => {
const canvas = qrCanvasRef.current;
if (!canvas) return;
const link = document.createElement('a');
link.download = `ostp-${sharingUser?.name || 'client'}.png`;
link.href = canvas.toDataURL('image/png');
link.click();
};
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
alert(t('cl_copied'));
};
const formatBytes = (bytes: number) => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
const parseBytesToInput = (bytes: number | null) => {
if (!bytes) return { value: '', unit: 'GB' };
const tb = 1024 * 1024 * 1024 * 1024;
const gb = 1024 * 1024 * 1024;
if (bytes >= tb) return { value: (bytes / tb).toString(), unit: 'TB' };
return { value: (bytes / gb).toString(), unit: 'GB' };
};
const openEditModal = (user: UserStatsSnapshot) => {
setEditingUser(user);
setEditName(user.name || '');
const { value, unit } = parseBytesToInput(user.limit_bytes);
setEditLimit(value);
setEditLimitUnit(unit);
setShowEditModal(true);
};
const filteredUsers = users.filter(user => {
const q = searchQuery.toLowerCase();
const nameMatch = (user.name || '').toLowerCase().includes(q);
const keyMatch = user.access_key.toLowerCase().includes(q);
return nameMatch || keyMatch;
});
return (
<div className="relative z-10 w-full max-w-7xl mx-auto space-y-6">
{/* Page Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 className="text-3xl font-bold tracking-tight mb-1 flex items-center gap-3">
<Users className="w-8 h-8 text-primary" /> {t('cl_title')}
</h1>
<p className="text-text-muted">{t('cl_subtitle')}</p>
</div>
<div className="flex gap-2">
<button
onClick={() => fetchUsers(true)}
className="p-2.5 bg-white/5 hover:bg-white/10 text-white rounded-xl font-medium transition-colors border border-white/10"
title="Refresh"
>
<RefreshCw className={`w-5 h-5 ${isLoading ? 'animate-spin text-primary' : ''}`} />
</button>
<button
onClick={() => setShowAddModal(true)}
className="flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-4 py-2.5 rounded-xl font-medium transition-colors shadow-[0_0_15px_rgba(108,114,255,0.3)]"
>
<Plus className="w-5 h-5" />
{t('cl_add')}
</button>
</div>
</div>
{/* Global Error Banner */}
{errorMsg && (
<div className="bg-red-500/10 border border-red-500/20 text-red-400 p-4 rounded-xl flex items-center gap-3">
<ShieldAlert className="w-5 h-5 shrink-0" />
<p className="text-sm font-mono">{errorMsg}</p>
</div>
)}
{/* Search and Quick Filters */}
<div className="flex items-center bg-white/5 border border-white/10 rounded-2xl px-4 py-3 max-w-md">
<Search className="w-5 h-5 text-text-muted mr-3" />
<input
type="text"
className="bg-transparent border-none outline-none text-white w-full placeholder-text-muted"
placeholder={t('cl_search')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
{/* Clients Table */}
<div className="glass-panel rounded-2xl overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="border-b border-white/5 bg-white/[0.02]">
<th className="px-6 py-4 font-medium text-text-muted">{t('cl_status')}</th>
<th className="px-6 py-4 font-medium text-text-muted">{t('cl_name')}</th>
<th className="px-6 py-4 font-medium text-text-muted">{t('cl_key')}</th>
<th className="px-6 py-4 font-medium text-text-muted">{t('cl_usage')}</th>
<th className="px-6 py-4 font-medium text-text-muted">{t('cl_limit')}</th>
<th className="px-6 py-4 font-medium text-text-muted text-right">{t('cl_actions')}</th>
</tr>
</thead>
<tbody className="divide-y divide-white/5">
{filteredUsers.map((user) => (
<tr key={user.access_key} className="hover:bg-white/[0.02] transition-colors group">
<td className="px-6 py-4">
{user.online ? (
<div className="flex items-center gap-2 text-secondary">
<span className="w-2 h-2 rounded-full bg-secondary shadow-[0_0_8px_#22D3A5]"></span>
<span className="text-sm font-medium">{t('cl_active')}</span>
</div>
) : (
<div className="flex items-center gap-2 text-text-muted">
<span className="w-2 h-2 rounded-full bg-text-muted"></span>
<span className="text-sm">{t('cl_offline')}</span>
</div>
)}
</td>
<td className="px-6 py-4 font-medium text-white">
{user.name || (
<span className="text-text-muted italic">{t('cl_unnamed')}</span>
)}
</td>
<td className="px-6 py-4">
<div className="flex items-center gap-2 text-text-muted font-mono text-sm">
<Key className="w-4 h-4 shrink-0 text-primary/70" />
<span title={user.access_key}>
{user.access_key.length > 20 ? `${user.access_key.substring(0, 16)}...` : user.access_key}
</span>
</div>
</td>
<td className="px-6 py-4">
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-2 text-sm text-white">
<span className="text-xs text-text-muted w-8">Up:</span>
<span className="text-red-400 font-mono">{formatBytes(user.bytes_up || 0)}</span>
</div>
<div className="flex items-center gap-2 text-sm text-white">
<span className="text-xs text-text-muted w-8">Down:</span>
<span className="text-secondary font-mono">{formatBytes(user.bytes_down || 0)}</span>
</div>
<div className="flex items-center gap-2 text-xs text-text-muted mt-0.5">
<span>Sessions:</span>
<span className="font-mono text-white">{user.connections}</span>
</div>
</div>
</td>
<td className="px-6 py-4">
<div className="text-sm font-mono text-text-muted">
{user.limit_bytes ? (
<span className={(user.bytes_up || 0) + (user.bytes_down || 0) >= user.limit_bytes ? 'text-red-400 font-bold' : 'text-white'}>
{formatBytes(user.limit_bytes)}
</span>
) : (
t('cl_unlimited')
)}
</div>
</td>
<td className="px-6 py-4 text-right">
<div className="flex items-center justify-end gap-1 sm:opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={() => handleOpenShare(user)}
className="p-2 hover:bg-white/10 rounded-lg text-text-muted hover:text-white transition-colors"
title="Get Share Connection Link"
>
<Share2 className="w-4 h-4" />
</button>
<button
onClick={() => handleResetStats(user.access_key)}
className="p-2 hover:bg-white/10 rounded-lg text-text-muted hover:text-yellow-400 transition-colors"
title="Reset Traffic Counters"
>
<RefreshCw className="w-4 h-4" />
</button>
<button
onClick={() => openEditModal(user)}
className="p-2 hover:bg-white/10 rounded-lg text-text-muted hover:text-white transition-colors"
title="Edit Client Description/Limit"
>
<Edit2 className="w-4 h-4" />
</button>
<button
onClick={() => handleDeleteClient(user.access_key)}
className="p-2 hover:bg-red-500/20 rounded-lg text-text-muted hover:text-red-400 transition-colors"
title="Delete Client"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</td>
</tr>
))}
{filteredUsers.length === 0 && !isLoading && (
<tr>
<td colSpan={6} className="px-6 py-12 text-center text-text-muted">
<Users className="w-12 h-12 mx-auto mb-4 opacity-20" />
<p>No clients found matching query.</p>
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
{/* Add Client Modal */}
{showAddModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
<div className="glass-panel w-full max-w-md rounded-2xl p-6 space-y-4 relative animate-in fade-in zoom-in-95 duration-200">
<button
onClick={() => setShowAddModal(false)}
className="absolute top-4 right-4 p-1 rounded-lg hover:bg-white/10 text-text-muted hover:text-white transition-colors"
>
<X className="w-5 h-5" />
</button>
<h2 className="text-xl font-bold text-white">{t('cl_add_title')}</h2>
<form onSubmit={handleAddClient} className="space-y-4">
<div className="space-y-1">
<label className="text-xs font-semibold text-text-muted uppercase">{t('cl_form_name')}</label>
<input
type="text"
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:border-primary transition-colors"
placeholder="e.g. My Phone, Home Laptop"
value={clientName}
onChange={(e) => setClientName(e.target.value)}
/>
</div>
<div className="space-y-1">
<label className="text-xs font-semibold text-text-muted uppercase">{t('cl_form_limit')}</label>
<div className="flex gap-2">
<input
type="number"
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:border-primary transition-colors font-mono"
placeholder={t('cl_form_limit_sub')}
value={clientLimit}
onChange={(e) => setClientLimit(e.target.value)}
/>
<select
className="bg-surface-light border border-white/10 rounded-xl px-3 py-2 text-white focus:outline-none focus:border-primary"
value={clientLimitUnit}
onChange={(e) => setClientLimitUnit(e.target.value)}
>
<option value="MB">MB</option>
<option value="GB">GB</option>
<option value="TB">TB</option>
</select>
</div>
</div>
<div className="space-y-1">
<label className="text-xs font-semibold text-text-muted uppercase">{t('cl_form_custom')}</label>
<input
type="text"
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:border-primary transition-colors font-mono"
placeholder={t('cl_form_custom_sub')}
value={clientCustomKey}
onChange={(e) => setClientCustomKey(e.target.value)}
/>
</div>
<button
type="submit"
className="w-full bg-primary hover:bg-primary/90 text-white py-2.5 rounded-xl font-medium transition-colors mt-2 shadow-[0_0_15px_rgba(108,114,255,0.3)]"
>
{t('cl_add')}
</button>
</form>
</div>
</div>
)}
{/* Edit Client Modal */}
{showEditModal && editingUser && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
<div className="glass-panel w-full max-w-md rounded-2xl p-6 space-y-4 relative animate-in fade-in zoom-in-95 duration-200">
<button
onClick={() => {
setShowEditModal(false);
setEditingUser(null);
}}
className="absolute top-4 right-4 p-1 rounded-lg hover:bg-white/10 text-text-muted hover:text-white transition-colors"
>
<X className="w-5 h-5" />
</button>
<h2 className="text-xl font-bold text-white">{t('cl_edit_title')}</h2>
<form onSubmit={handleEditClient} className="space-y-4">
<div className="space-y-1">
<label className="text-xs font-semibold text-text-muted uppercase">{t('cl_form_name')}</label>
<input
type="text"
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:border-primary transition-colors"
placeholder="e.g. My Phone, Home Laptop"
value={editName}
onChange={(e) => setEditName(e.target.value)}
/>
</div>
<div className="space-y-1">
<label className="text-xs font-semibold text-text-muted uppercase">{t('cl_form_limit')}</label>
<div className="flex gap-2">
<input
type="number"
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:border-primary transition-colors font-mono"
placeholder={t('cl_form_limit_sub')}
value={editLimit}
onChange={(e) => setEditLimit(e.target.value)}
/>
<select
className="bg-surface-light border border-white/10 rounded-xl px-3 py-2 text-white focus:outline-none focus:border-primary"
value={editLimitUnit}
onChange={(e) => setEditLimitUnit(e.target.value)}
>
<option value="MB">MB</option>
<option value="GB">GB</option>
<option value="TB">TB</option>
</select>
</div>
</div>
<div className="text-xs text-text-muted font-mono truncate">
Access Key: {editingUser.access_key}
</div>
<button
type="submit"
className="w-full bg-primary hover:bg-primary/90 text-white py-2.5 rounded-xl font-medium transition-colors mt-2 shadow-[0_0_15px_rgba(108,114,255,0.3)]"
>
{t('cl_form_save')}
</button>
</form>
</div>
</div>
)}
{/* Share Connection Modal */}
{showShareModal && sharingUser && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
<div className="glass-panel w-full max-w-lg rounded-2xl relative animate-in fade-in zoom-in-95 duration-200 flex flex-col" style={{ maxHeight: '90vh' }}>
{/* Sticky header */}
<div className="flex items-start justify-between p-6 pb-4 shrink-0">
<div>
<h2 className="text-xl font-bold text-white">{t('cl_share_title')}</h2>
<p className="text-sm text-text-muted mt-0.5">{t('cl_share_sub')}</p>
</div>
<button
onClick={() => {
setShowShareModal(false);
setSharingUser(null);
}}
className="ml-4 shrink-0 p-1.5 rounded-lg hover:bg-white/10 text-text-muted hover:text-white transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Scrollable body */}
<div className="overflow-y-auto px-6 pb-6 space-y-4">
<div className="space-y-1.5">
<label className="text-xs font-semibold text-text-muted uppercase">{t('cl_name')}</label>
<div className="text-white font-medium">{sharingUser.name || t('cl_unnamed')}</div>
</div>
<div className="space-y-2">
<label className="text-xs font-semibold text-text-muted uppercase">{t('cl_share_link')}</label>
{isFetchingLink ? (
<div className="bg-white/5 border border-white/10 rounded-xl p-4 flex items-center justify-center">
<RefreshCw className="w-6 h-6 animate-spin text-primary mr-2" />
<span className="text-sm text-text-muted">Generating link...</span>
</div>
) : (
<div className="flex gap-2">
<input
type="text"
readOnly
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono text-xs select-all focus:outline-none"
value={shareLink}
/>
<button
onClick={() => copyToClipboard(shareLink)}
className="p-2.5 bg-primary hover:bg-primary/90 text-white rounded-xl transition-colors shrink-0"
title="Copy Link"
>
<Copy className="w-5 h-5" />
</button>
</div>
)}
</div>
{/* QR Code — compact, side layout */}
{!isFetchingLink && shareLink && (
<div className="flex items-center gap-4 p-3 rounded-xl border border-white/10" style={{ background: 'linear-gradient(135deg, rgba(108,114,255,0.10) 0%, rgba(34,211,165,0.07) 100%)' }}>
<div className="shrink-0" style={{ background: 'rgba(0,0,0,0.3)', borderRadius: '0.5rem', padding: '8px' }}>
<canvas ref={qrCanvasRef} style={{ display: 'block', borderRadius: '4px' }} />
</div>
<div className="flex flex-col gap-2 min-w-0">
<p className="text-xs text-text-muted leading-snug">{t('cl_share_scan')}</p>
<button
onClick={downloadQr}
className="flex items-center gap-2 px-3 py-1.5 bg-white/5 hover:bg-white/10 border border-white/10 text-white text-xs rounded-lg transition-colors w-fit"
>
<Download className="w-3.5 h-3.5" />
{t('cl_share_download_qr')}
</button>
</div>
</div>
)}
</div>
</div>
</div>
)}
</div>
);
}

View File

@ -0,0 +1,160 @@
import React, { useState } from 'react';
import { Shield, Globe, Key, CheckCircle, XCircle, RefreshCw, ChevronRight } from 'lucide-react';
import { saveApiSettings, api } from '../lib/api';
import { useLanguage } from '../lib/LanguageContext';
import { addAuditLog } from '../lib/audit';
interface ConnectionSetupProps {
onSetupComplete: () => void;
}
export default function ConnectionSetup({ onSetupComplete }: ConnectionSetupProps) {
const { t, language } = useLanguage();
const [apiUrl, setApiUrl] = useState('http://localhost:9090');
const [apiToken, setApiToken] = useState('');
const [isTesting, setIsTesting] = useState(false);
const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
const handleTestAndSave = async (e: React.FormEvent) => {
e.preventDefault();
if (!apiUrl) return;
setIsTesting(true);
setTestResult(null);
const formattedUrl = apiUrl.trim().replace(/\/$/, '');
const formattedToken = apiToken.trim();
const oldUrl = localStorage.getItem('ostp_api_url');
const oldToken = localStorage.getItem('ostp_api_token');
try {
saveApiSettings(formattedUrl, formattedToken);
const status = await api.getServerStatus();
setTestResult({
success: true,
message: language === 'ru'
? `Успешно подключено! Версия сервера: v${status.version}, активных сессий: ${status.active_users}`
: `Successfully connected! Server version: v${status.version}, active sessions: ${status.active_users}`,
});
addAuditLog(
`Initial setup connected to API at ${formattedUrl} (Version: v${status.version})`,
`Первоначальная настройка успешно подключена к API по адресу ${formattedUrl} (Версия: v${status.version})`,
true
);
setTimeout(() => {
onSetupComplete();
}, 1000);
} catch (err: any) {
if (oldUrl) localStorage.setItem('ostp_api_url', oldUrl);
else localStorage.removeItem('ostp_api_url');
if (oldToken !== null) localStorage.setItem('ostp_api_token', oldToken);
else localStorage.removeItem('ostp_api_token');
const errorMsgStr = err.message || err;
setTestResult({
success: false,
message: `${t('conn_setup_error')}${errorMsgStr}`,
});
addAuditLog(
`Initial setup failed to connect to ${formattedUrl}: ${errorMsgStr}`,
`Первоначальная настройка не смогла подключиться к ${formattedUrl}: ${errorMsgStr}`,
false
);
} finally {
setIsTesting(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-background p-4 overflow-y-auto">
{/* Background blobs */}
<div className="absolute top-[10%] left-[10%] w-[50%] h-[50%] rounded-full bg-primary/10 blur-[150px] pointer-events-none"></div>
<div className="absolute bottom-[10%] right-[10%] w-[50%] h-[50%] rounded-full bg-secondary/5 blur-[150px] pointer-events-none"></div>
<div className="relative w-full max-w-lg glass-panel rounded-3xl p-8 space-y-6 shadow-2xl border border-white/10 my-8">
<div className="text-center space-y-2">
<div className="inline-flex p-4 bg-primary/10 rounded-2xl mb-2 text-primary border border-primary/20">
<Shield className="w-12 h-12" />
</div>
<h1 className="text-3xl font-extrabold tracking-tight text-white">OSTP<span className="text-primary">CORE</span></h1>
<p className="text-text-muted text-sm">{t('conn_setup_sub')}</p>
</div>
<div className="bg-white/5 border border-white/5 p-4 rounded-2xl space-y-2 text-white">
<h2 className="text-sm font-semibold">{t('conn_setup_header')}</h2>
<p className="text-xs text-text-muted leading-relaxed">
{t('conn_setup_desc')}
</p>
</div>
<form onSubmit={handleTestAndSave} className="space-y-4">
<div className="space-y-2">
<label className="text-xs font-semibold text-text-muted uppercase tracking-wider flex items-center gap-1.5">
<Globe className="w-3.5 h-3.5 text-primary" /> {t('conn_setup_url_label')}
</label>
<input
type="text"
required
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-text-muted focus:outline-none focus:border-primary transition-colors font-mono text-sm"
placeholder="e.g. http://localhost:9090"
value={apiUrl}
onChange={(e) => setApiUrl(e.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-xs font-semibold text-text-muted uppercase tracking-wider flex items-center gap-1.5">
<Key className="w-3.5 h-3.5 text-primary" /> {t('conn_setup_token_label')}
</label>
<input
type="password"
required
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-text-muted focus:outline-none focus:border-primary transition-colors font-mono text-sm"
placeholder={t('conn_setup_token_placeholder')}
value={apiToken}
onChange={(e) => setApiToken(e.target.value)}
/>
</div>
<button
type="submit"
disabled={isTesting || !apiUrl || !apiToken}
className="w-full flex items-center justify-center gap-2 bg-primary hover:bg-primary/90 disabled:opacity-50 disabled:hover:bg-primary text-white py-3.5 rounded-xl font-semibold transition-colors mt-2 shadow-[0_0_20px_rgba(108,114,255,0.4)]"
>
{isTesting ? (
<RefreshCw className="w-5 h-5 animate-spin" />
) : (
<>
{t('conn_setup_btn')} <ChevronRight className="w-5 h-5" />
</>
)}
</button>
</form>
{testResult && (
<div className={`p-4 rounded-xl flex items-start gap-3 border animate-in fade-in slide-in-from-bottom-2 duration-200 ${
testResult.success
? 'bg-secondary/10 border-secondary/20 text-secondary'
: 'bg-red-500/10 border-red-500/20 text-red-400'
}`}>
{testResult.success ? (
<CheckCircle className="w-5 h-5 shrink-0 mt-0.5" />
) : (
<XCircle className="w-5 h-5 shrink-0 mt-0.5" />
)}
<div>
<p className="font-semibold text-sm">{testResult.success ? t('conn_setup_success') : 'Connection Error'}</p>
<p className="text-xs mt-1 opacity-90 font-mono break-all">{testResult.message}</p>
</div>
</div>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,257 @@
import { useState, useEffect } from 'react';
import { Activity, Cpu, ArrowUpRight, ArrowDownRight, Users, Server, ShieldAlert } from 'lucide-react';
import { api } from '../lib/api';
import type { ServerStatus, UserStatsSnapshot } from '../lib/api';
import { useLanguage } from '../lib/LanguageContext';
export default function Dashboard() {
const { t } = useLanguage();
const [status, setStatus] = useState<ServerStatus | null>(null);
const [config, setConfig] = useState<any>(null);
const [users, setUsers] = useState<UserStatsSnapshot[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [apiPing, setApiPing] = useState<number | null>(null);
const fetchDashboardData = async (showLoading = false) => {
if (showLoading) setIsLoading(true);
const startPing = performance.now();
try {
// Fetch status, users and server configuration in parallel
const [statusData, usersData, configData] = await Promise.all([
api.getServerStatus(),
api.listUsers(),
api.getServerConfig().catch(() => null) // Allow failing gracefully if config read fails
]);
const endPing = performance.now();
setApiPing(Math.round(endPing - startPing));
setStatus(statusData);
setUsers(usersData || []);
if (configData) setConfig(configData);
setErrorMsg(null);
} catch (err: any) {
setErrorMsg(err.message || 'Failed to fetch server statistics');
} finally {
if (showLoading) setIsLoading(false);
}
};
useEffect(() => {
fetchDashboardData(true);
const interval = setInterval(() => {
fetchDashboardData(false);
}, 5000);
return () => clearInterval(interval);
}, []);
// Aggregators
const totalTxBytes = users.reduce((acc, user) => acc + (user.bytes_up || 0), 0);
const totalRxBytes = users.reduce((acc, user) => acc + (user.bytes_down || 0), 0);
const totalTraffic = totalTxBytes + totalRxBytes;
const totalConnections = users.reduce((acc, user) => acc + (user.connections || 0), 0);
// Real active users check
const activeUsersCount = users.filter(user => user.online && user.connections > 0).length;
const totalUsersCount = status?.total_users ?? users.length;
const avgTrafficPerUser = users.length > 0 ? Math.round(totalTraffic / users.length) : 0;
const formatBytes = (bytes: number) => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
return (
<div className="relative z-10 w-full max-w-7xl mx-auto space-y-6 animate-in fade-in duration-300">
{/* Page Title */}
<div>
<h1 className="text-3xl font-bold tracking-tight mb-1 flex items-center gap-3">
<Activity className="w-8 h-8 text-primary animate-pulse" /> {t('db_title')}
</h1>
<p className="text-text-muted">{t('db_subtitle')}</p>
</div>
{/* Global Error Banner */}
{errorMsg && (
<div className="bg-red-500/10 border border-red-500/20 text-red-400 p-4 rounded-xl flex items-center gap-3">
<ShieldAlert className="w-5 h-5 shrink-0" />
<p className="text-sm font-mono">{errorMsg}</p>
</div>
)}
{/* Stats Cards Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<StatCard
icon={<Users className="text-primary w-6 h-6" />}
label={t('db_active_users')}
value={isLoading ? '...' : `${activeUsersCount} / ${totalUsersCount}`}
subValue={t('db_active_users_sub')}
/>
<StatCard
icon={<Activity className="text-secondary w-6 h-6" />}
label={t('db_connections')}
value={isLoading ? '...' : totalConnections.toLocaleString()}
subValue={t('db_connections_sub')}
/>
<StatCard
icon={<ArrowUpRight className="text-red-400 w-6 h-6" />}
label={t('db_uploaded')}
value={isLoading ? '...' : formatBytes(totalTxBytes)}
subValue={t('db_uploaded_sub')}
/>
<StatCard
icon={<ArrowDownRight className="text-secondary w-6 h-6" />}
label={t('db_downloaded')}
value={isLoading ? '...' : formatBytes(totalRxBytes)}
subValue={t('db_downloaded_sub')}
/>
</div>
{/* System Status & Details */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mt-6">
{/* Core Properties Card */}
<div className="lg:col-span-2 glass-panel rounded-2xl p-6 min-h-[300px] flex flex-col justify-between">
<div>
<h2 className="text-xl font-semibold mb-2 flex items-center gap-2">
<Server className="w-5 h-5 text-primary" /> {t('db_properties')}
</h2>
<p className="text-sm text-text-muted mb-6">{t('db_properties_sub')}</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
<InfoItem
label={t('db_core_version')}
value={status?.version ? `v${status.version}` : 'v0.2.30'}
/>
<InfoItem
label={t('db_listen_addr')}
value={config?.listen ? (typeof config.listen === 'string' ? config.listen : config.listen.join(', ')) : 'Offline'}
/>
<InfoItem
label={t('db_api_bind')}
value={config?.api?.enabled ? config.api.bind : 'Disabled'}
/>
<InfoItem
label={t('db_reality_status')}
value={config?.reality?.enabled ? 'Active' : 'Disabled'}
highlight={config?.reality?.enabled}
/>
{config?.reality?.enabled && (
<InfoItem
label={t('db_reality_dest')}
value={config.reality.dest}
/>
)}
<InfoItem
label={t('db_fallback_status')}
value={config?.fallback?.enabled ? `Active` : 'Disabled'}
highlight={config?.fallback?.enabled}
/>
{config?.fallback?.enabled && (
<InfoItem
label={t('db_fallback_target')}
value={config.fallback.target}
/>
)}
<InfoItem
label={t('db_outbound_proxy')}
value={config?.outbound?.enabled ? `${config.outbound.protocol}://${config.outbound.address}:${config.outbound.port}` : 'Direct'}
/>
{apiPing !== null && (
<InfoItem
label={t('db_api_latency')}
value={`${apiPing} ms`}
/>
)}
</div>
</div>
{/* Load & Capacity Utilization Card */}
<div className="glass-panel rounded-2xl p-6 flex flex-col justify-between">
<div>
<h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
<Cpu className="w-5 h-5 text-primary" /> {t('db_load_title')}
</h2>
</div>
<div className="space-y-6">
<ProgressItem
label={t('db_load_users')}
percentage={totalUsersCount > 0 ? Math.round((activeUsersCount / totalUsersCount) * 100) : 0}
color="bg-primary"
/>
<ProgressItem
label={t('db_load_connections')}
percentage={Math.min(Math.round((totalConnections / 512) * 100), 100)}
color="bg-secondary"
/>
<div className="pt-4 border-t border-white/5 space-y-2 mt-auto">
<div className="flex justify-between text-xs text-text-muted">
<span>{t('db_total_traffic')}:</span>
<span className="font-mono text-white font-medium">{formatBytes(totalTraffic)}</span>
</div>
<div className="flex justify-between text-xs text-text-muted">
<span>{t('db_traffic_per_user')}:</span>
<span className="font-mono text-white font-medium">{formatBytes(avgTrafficPerUser)}</span>
</div>
<div className="flex justify-between text-xs text-text-muted pt-2 border-t border-white/5">
<span>Core Daemon State:</span>
<span className="font-mono text-secondary font-bold flex items-center gap-1.5">
<span className="w-2.5 h-2.5 rounded-full bg-secondary animate-pulse inline-block"></span>
RUNNING
</span>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
function StatCard({ icon, label, value, subValue }: { icon: React.ReactNode, label: string, value: string, subValue: string }) {
return (
<div className="glass-panel rounded-2xl p-6 group hover:border-primary/30 transition-colors duration-300">
<div className="flex items-start justify-between mb-4">
<div className="p-3 bg-white/5 rounded-xl group-hover:bg-primary/10 transition-colors">{icon}</div>
</div>
<div>
<p className="text-text-muted text-sm font-medium">{label}</p>
<h3 className="text-3xl font-bold mt-1 font-mono tracking-tight text-white">{value}</h3>
<p className="text-xs text-text-muted mt-2">{subValue}</p>
</div>
</div>
);
}
function InfoItem({ label, value, highlight }: { label: string; value: string; highlight?: boolean }) {
return (
<div className="space-y-1">
<div className="text-xs text-text-muted font-medium">{label}</div>
<div className={`font-mono text-sm font-medium break-all ${highlight ? 'text-secondary font-bold' : 'text-white'}`}>
{value}
</div>
</div>
);
}
function ProgressItem({ label, percentage, color }: { label: string, percentage: number, color: string }) {
return (
<div>
<div className="flex justify-between mb-2">
<span className="text-sm font-medium text-white">{label}</span>
<span className="text-sm font-mono text-text-muted">{percentage}%</span>
</div>
<div className="h-2 w-full bg-white/5 rounded-full overflow-hidden">
<div className={`h-full ${color} rounded-full transition-all duration-1000`} style={{ width: `${percentage}%` }}></div>
</div>
</div>
);
}

View File

@ -0,0 +1,115 @@
import React, { useState } from 'react';
import { Shield, Key, User, ArrowRight, Activity } from 'lucide-react';
import { api } from '../lib/api';
interface LoginProps {
onLoginSuccess: () => void;
}
export default function Login({ onLoginSuccess }: LoginProps) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
await api.login(username, password);
onLoginSuccess();
} catch (err: any) {
setError(err.message || 'Authentication failed');
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen w-full bg-background flex flex-col items-center justify-center p-4 font-sans relative overflow-hidden">
{/* Decorative blobs */}
<div className="absolute top-[-20%] left-[-10%] w-[50%] h-[50%] rounded-full bg-primary/10 blur-[120px] pointer-events-none"></div>
<div className="absolute bottom-[-20%] right-[-10%] w-[50%] h-[50%] rounded-full bg-secondary/10 blur-[120px] pointer-events-none"></div>
<div className="w-full max-w-md z-10">
<div className="text-center mb-10">
<div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-white/5 border border-white/10 mb-6 shadow-[0_0_30px_rgba(255,255,255,0.05)]">
<Shield className="w-10 h-10 text-primary animate-pulse" />
</div>
<h1 className="text-3xl font-bold tracking-wider text-white mb-2">
OSTP<span className="text-primary">CORE</span>
</h1>
<p className="text-text-muted">Secure Stealth Transport Protocol</p>
</div>
<div className="glass rounded-2xl border border-white/10 p-8 shadow-2xl relative overflow-hidden">
<div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-primary to-secondary"></div>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-sm font-medium text-text-muted mb-2 ml-1">Username</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
<User className="h-5 w-5 text-text-muted" />
</div>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="block w-full pl-11 pr-4 py-3 bg-black/40 border border-white/10 rounded-xl text-white placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-transparent transition-all"
placeholder="Enter username"
required
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-text-muted mb-2 ml-1">Password</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
<Key className="h-5 w-5 text-text-muted" />
</div>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="block w-full pl-11 pr-4 py-3 bg-black/40 border border-white/10 rounded-xl text-white placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-transparent transition-all"
placeholder="Enter password"
required
/>
</div>
</div>
{error && (
<div className="bg-red-500/10 border border-red-500/20 text-red-400 text-sm p-3 rounded-lg flex items-center gap-2">
<div className="w-1.5 h-1.5 rounded-full bg-red-400"></div>
{error}
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full flex items-center justify-center gap-2 bg-primary hover:bg-primary/90 text-background font-bold py-3.5 px-4 rounded-xl transition-all shadow-[0_0_20px_rgba(255,255,255,0.2)] hover:shadow-[0_0_30px_rgba(255,255,255,0.4)] disabled:opacity-50 disabled:cursor-not-allowed group mt-2"
>
{loading ? (
<Activity className="w-5 h-5 animate-spin" />
) : (
<>
Login to Dashboard
<ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
</>
)}
</button>
</form>
</div>
<div className="text-center mt-8 text-xs text-text-muted/50">
v0.2.35 Protected by OSTP
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,662 @@
import { useState, useEffect } from 'react';
import {
Settings as SettingsIcon, Globe, Key, CheckCircle, XCircle,
RefreshCw, Save, Sliders, Code2, AlertTriangle
} from 'lucide-react';
import { getApiSettings, saveApiSettings, api } from '../lib/api';
import { useLanguage } from '../lib/LanguageContext';
import { addAuditLog } from '../lib/audit';
export default function Settings() {
const { t, language } = useLanguage();
// Tabs: 'connection' | 'interactive' | 'raw'
const [activeTab, setActiveTab] = useState<'connection' | 'interactive' | 'raw'>('interactive');
// Connection settings state
const [panelApiUrl, setPanelApiUrl] = useState('');
const [panelApiToken, setPanelApiToken] = useState('');
const [isTestingConnection, setIsTestingConnection] = useState(false);
const [connectionTestResult, setConnectionTestResult] = useState<{ success: boolean; message: string } | null>(null);
// Full Server Config JSON state
const [config, setConfig] = useState<any>(null);
const [rawJson, setRawJson] = useState('');
const [isLoadingConfig, setIsLoadingConfig] = useState(false);
const [configError, setConfigError] = useState<string | null>(null);
const [saveStatus, setSaveStatus] = useState<{ success: boolean; message: string } | null>(null);
// Initial load
useEffect(() => {
const { url, token } = getApiSettings();
setPanelApiUrl(url);
setPanelApiToken(token);
fetchServerConfig();
}, []);
const fetchServerConfig = async () => {
setIsLoadingConfig(true);
setConfigError(null);
try {
const data = await api.getServerConfig();
setConfig(data);
setRawJson(JSON.stringify(data, null, 2));
} catch (err: any) {
setConfigError(language === 'ru'
? 'Не удалось загрузить конфигурацию сервера. Проверьте настройки подключения.'
: 'Failed to load server configuration. Please check connection parameters.');
} finally {
setIsLoadingConfig(false);
}
};
const handleTestConnection = async () => {
setIsTestingConnection(true);
setConnectionTestResult(null);
const oldUrl = localStorage.getItem('ostp_api_url');
const oldToken = localStorage.getItem('ostp_api_token');
try {
saveApiSettings(panelApiUrl, panelApiToken);
const status = await api.getServerStatus();
setConnectionTestResult({
success: true,
message: t('st_conn_success', { version: status.version, users: status.active_users }),
});
addAuditLog(
`Tested connection to Management API at ${panelApiUrl} (Success)`,
`Успешно протестировано подключение к API по адресу ${panelApiUrl}`,
true
);
} catch (err: any) {
if (oldUrl) localStorage.setItem('ostp_api_url', oldUrl);
if (oldToken !== null) localStorage.setItem('ostp_api_token', oldToken);
const errorMsgStr = err.message || err;
setConnectionTestResult({
success: false,
message: t('st_conn_error', { error: errorMsgStr }),
});
addAuditLog(
`Tested connection to Management API at ${panelApiUrl} (Failed: ${errorMsgStr})`,
`Ошибка при тесте подключения к API по адресу ${panelApiUrl} (${errorMsgStr})`,
false
);
} finally {
setIsTestingConnection(false);
}
};
const handleSaveConnection = () => {
saveApiSettings(panelApiUrl, panelApiToken);
alert(language === 'ru' ? 'Настройки подключения сохранены!' : 'Connection settings saved!');
addAuditLog(
`Saved API connection settings: ${panelApiUrl}`,
`Сохранены настройки подключения к API: ${panelApiUrl}`,
true
);
window.location.reload();
};
// Save Config to Server
const handleSaveConfig = async (configToSave: any) => {
setSaveStatus(null);
try {
await api.updateServerConfig(configToSave);
setSaveStatus({
success: true,
message: t('st_save_success'),
});
addAuditLog(
'Updated server config.json configuration',
'Обновлена конфигурация config.json сервера',
true
);
// Refresh current state
setConfig(configToSave);
setRawJson(JSON.stringify(configToSave, null, 2));
} catch (err: any) {
setSaveStatus({
success: false,
message: `${t('st_save_error')} ${err.message || err}`,
});
addAuditLog(
`Failed to update server configuration: ${err.message || err}`,
`Не удалось сохранить конфигурацию: ${err.message || err}`,
false
);
}
};
const handleInteractiveSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!config) return;
handleSaveConfig(config);
};
const handleRawSubmit = (e: React.FormEvent) => {
e.preventDefault();
try {
const parsed = JSON.parse(rawJson);
handleSaveConfig(parsed);
} catch (err: any) {
setSaveStatus({
success: false,
message: `${t('st_save_error')} Invalid JSON: ${err.message}`,
});
}
};
// Helper to deep modify config fields
const updateConfigField = (path: string[], value: any) => {
if (!config) return;
const newConfig = { ...config };
let current = newConfig;
for (let i = 0; i < path.length - 1; i++) {
if (current[path[i]] === undefined) {
current[path[i]] = {};
}
current = current[path[i]];
}
current[path[path.length - 1]] = value;
setConfig(newConfig);
setRawJson(JSON.stringify(newConfig, null, 2));
};
return (
<div className="relative z-10 w-full max-w-6xl mx-auto space-y-6">
{/* Header */}
<div className="flex justify-between items-end">
<div>
<h1 className="text-3xl font-bold tracking-tight mb-1 flex items-center gap-3">
<SettingsIcon className="w-8 h-8 text-primary" /> {t('st_title')}
</h1>
<p className="text-text-muted">{t('st_subtitle')}</p>
</div>
{config && (
<button
onClick={fetchServerConfig}
className="flex items-center gap-2 bg-white/5 hover:bg-white/10 text-white px-4 py-2.5 rounded-xl border border-white/10 text-sm transition-colors"
>
<RefreshCw className={`w-4 h-4 ${isLoadingConfig ? 'animate-spin text-primary' : ''}`} /> {t('st_reset')}
</button>
)}
</div>
{/* Navigation tabs */}
<div className="flex border-b border-white/5 gap-2">
<button
onClick={() => setActiveTab('interactive')}
className={`flex items-center gap-2 px-5 py-3 font-medium transition-colors border-b-2 text-sm ${
activeTab === 'interactive' ? 'border-primary text-white' : 'border-transparent text-text-muted hover:text-white'
}`}
>
<Sliders className="w-4 h-4" /> {t('st_tab_ui')}
</button>
<button
onClick={() => setActiveTab('raw')}
className={`flex items-center gap-2 px-5 py-3 font-medium transition-colors border-b-2 text-sm ${
activeTab === 'raw' ? 'border-primary text-white' : 'border-transparent text-text-muted hover:text-white'
}`}
>
<Code2 className="w-4 h-4" /> {t('st_tab_json')}
</button>
<button
onClick={() => setActiveTab('connection')}
className={`flex items-center gap-2 px-5 py-3 font-medium transition-colors border-b-2 text-sm ${
activeTab === 'connection' ? 'border-primary text-white' : 'border-transparent text-text-muted hover:text-white'
}`}
>
<Globe className="w-4 h-4" /> {t('st_tab_conn')}
</button>
</div>
{/* Global save notifications */}
{saveStatus && (
<div className={`p-4 rounded-xl flex items-start gap-3 border animate-in fade-in duration-200 ${
saveStatus.success ? 'bg-secondary/10 border-secondary/20 text-secondary' : 'bg-red-500/10 border-red-500/20 text-red-400'
}`}>
{saveStatus.success ? <CheckCircle className="w-5 h-5 shrink-0 mt-0.5" /> : <XCircle className="w-5 h-5 shrink-0 mt-0.5" />}
<div>
<p className="font-semibold text-sm">{saveStatus.success ? 'Success' : 'Error'}</p>
<p className="text-xs mt-1 opacity-90 leading-relaxed font-mono">{saveStatus.message}</p>
</div>
</div>
)}
{configError && (
<div className="bg-red-500/10 border border-red-500/20 text-red-400 p-4 rounded-xl flex items-center gap-3">
<AlertTriangle className="w-5 h-5 shrink-0" />
<p className="text-sm font-semibold">{configError}</p>
</div>
)}
{/* ── TAB: CONNECTION SETTINGS ── */}
{activeTab === 'connection' && (
<div className="glass-panel rounded-2xl p-6 space-y-6">
<div>
<h2 className="text-xl font-semibold mb-2">{t('st_conn_title')}</h2>
<p className="text-sm text-text-muted">
{t('st_conn_desc')}
</p>
</div>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium flex items-center gap-2">
<Globe className="w-4 h-4 text-primary" /> {t('st_conn_url')}
</label>
<input
type="text"
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-text-muted focus:outline-none focus:border-primary transition-colors font-mono"
placeholder="e.g. http://localhost:9090"
value={panelApiUrl}
onChange={(e) => setPanelApiUrl(e.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium flex items-center gap-2">
<Key className="w-4 h-4 text-primary" /> {t('st_conn_token')}
</label>
<input
type="password"
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white placeholder-text-muted focus:outline-none focus:border-primary transition-colors font-mono"
placeholder={t('st_conn_token_sub')}
value={panelApiToken}
onChange={(e) => setPanelApiToken(e.target.value)}
/>
</div>
</div>
<div className="flex gap-4 pt-4 border-t border-white/5">
<button
onClick={handleTestConnection}
disabled={isTestingConnection || !panelApiUrl}
className="flex items-center gap-2 bg-white/5 hover:bg-white/10 text-white px-5 py-2.5 rounded-xl font-medium transition-colors border border-white/10"
>
<RefreshCw className={`w-5 h-5 ${isTestingConnection ? 'animate-spin text-primary' : ''}`} /> {t('st_conn_test')}
</button>
<button
onClick={handleSaveConnection}
disabled={!panelApiUrl}
className="flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-6 py-2.5 rounded-xl font-medium transition-colors shadow-[0_0_15px_rgba(108,114,255,0.3)]"
>
<Save className="w-5 h-5" /> {t('st_conn_save')}
</button>
</div>
{connectionTestResult && (
<div className={`mt-4 p-4 rounded-xl flex items-start gap-3 border ${
connectionTestResult.success ? 'bg-secondary/10 border-secondary/20 text-secondary' : 'bg-red-500/10 border-red-500/20 text-red-400'
}`}>
{connectionTestResult.success ? <CheckCircle className="w-5 h-5 shrink-0 mt-0.5" /> : <XCircle className="w-5 h-5 shrink-0 mt-0.5" />}
<div>
<p className="font-semibold text-sm">{connectionTestResult.success ? 'Success' : 'Failed'}</p>
<p className="text-xs mt-1 opacity-90 font-mono break-all">{connectionTestResult.message}</p>
</div>
</div>
)}
</div>
)}
{/* ── TAB: RAW JSON EDITOR ── */}
{activeTab === 'raw' && config && (
<form onSubmit={handleRawSubmit} className="glass-panel rounded-2xl p-6 space-y-4">
<div>
<h2 className="text-xl font-semibold mb-2">{t('st_raw_title')}</h2>
<p className="text-sm text-text-muted">
{t('st_raw_desc')}
</p>
</div>
<div className="relative">
<textarea
className="w-full min-h-[500px] bg-black/40 border border-white/10 rounded-xl p-4 font-mono text-sm text-white focus:outline-none focus:border-primary"
value={rawJson}
onChange={(e) => setRawJson(e.target.value)}
/>
</div>
<div className="pt-4 border-t border-white/5">
<button
type="submit"
className="flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-6 py-2.5 rounded-xl font-semibold transition-colors shadow-[0_0_15px_rgba(108,114,255,0.3)]"
>
<Save className="w-5 h-5" /> {t('st_save_btn')}
</button>
</div>
</form>
)}
{/* ── TAB: INTERACTIVE CONFIG EDITOR ── */}
{activeTab === 'interactive' && config && (
<form onSubmit={handleInteractiveSubmit} className="space-y-6">
{/* SECTION: GENERAL */}
<div className="glass-panel rounded-2xl p-6 space-y-4">
<h2 className="text-lg font-bold border-b border-white/5 pb-2 text-white flex items-center gap-2">
<Sliders className="w-5 h-5 text-primary" /> {t('st_ui_general')}
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_log')}</label>
<select
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-primary"
value={config.log_level || 'info'}
onChange={(e) => updateConfigField(['log_level'], e.target.value)}
>
<option value="debug">debug</option>
<option value="info">info</option>
<option value="warn">warn</option>
<option value="error">error</option>
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_port')}</label>
<input
type="text"
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono"
placeholder="e.g. 0.0.0.0:50000"
value={typeof config.listen === 'string' ? config.listen : JSON.stringify(config.listen)}
onChange={(e) => {
let val: any = e.target.value;
try {
val = JSON.parse(e.target.value);
} catch {
// fallback as string
}
updateConfigField(['listen'], val);
}}
/>
</div>
</div>
<div className="flex items-center gap-3 pt-2">
<input
type="checkbox"
id="general-debug"
className="w-4 h-4 accent-primary rounded bg-white/5 border-white/10"
checked={config.debug || false}
onChange={(e) => updateConfigField(['debug'], e.target.checked)}
/>
<label htmlFor="general-debug" className="text-sm font-medium text-white cursor-pointer select-none">
{t('st_ui_debug')}
</label>
</div>
</div>
{/* SECTION: MANAGEMENT API */}
<div className="glass-panel rounded-2xl p-6 space-y-4">
<h2 className="text-lg font-bold border-b border-white/5 pb-2 text-white flex items-center gap-2">
<Globe className="w-5 h-5 text-secondary" /> {t('st_ui_api_title')}
</h2>
<div className="flex items-center gap-3 mb-2">
<input
type="checkbox"
id="api-enabled"
className="w-4 h-4 accent-primary rounded bg-white/5 border-white/10"
checked={config.api?.enabled || false}
onChange={(e) => updateConfigField(['api', 'enabled'], e.target.checked)}
/>
<label htmlFor="api-enabled" className="text-sm font-medium text-white cursor-pointer select-none">
{t('st_ui_api_enable')}
</label>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_api_bind')}</label>
<input
type="text"
disabled={!config.api?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50"
placeholder="e.g. 127.0.0.1:9090"
value={config.api?.bind || ''}
onChange={(e) => updateConfigField(['api', 'bind'], e.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_api_token')}</label>
<input
type="text"
disabled={!config.api?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50"
placeholder="Leave blank to disable authorization"
value={config.api?.token || ''}
onChange={(e) => updateConfigField(['api', 'token'], e.target.value)}
/>
</div>
</div>
{config.api?.enabled && (
<div className="p-3 bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 rounded-xl flex items-start gap-2">
<AlertTriangle className="w-5 h-5 shrink-0 mt-0.5" />
<p className="text-xs leading-relaxed font-sans">
<strong>{t('st_ui_api_warning')}</strong>
</p>
</div>
)}
</div>
{/* SECTION: FALLBACK PROXY */}
<div className="glass-panel rounded-2xl p-6 space-y-4">
<h2 className="text-lg font-bold border-b border-white/5 pb-2 text-white flex items-center gap-2">
<Globe className="w-5 h-5 text-blue-400" /> {t('st_ui_fb_title')}
</h2>
<div className="flex items-center gap-3 mb-2">
<input
type="checkbox"
id="fallback-enabled"
className="w-4 h-4 accent-primary rounded bg-white/5 border-white/10"
checked={config.fallback?.enabled || false}
onChange={(e) => updateConfigField(['fallback', 'enabled'], e.target.checked)}
/>
<label htmlFor="fallback-enabled" className="text-sm font-medium text-white cursor-pointer select-none">
{t('st_ui_fb_enable')}
</label>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_fb_port')}</label>
<input
type="text"
disabled={!config.fallback?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50"
placeholder="e.g. 0.0.0.0:443"
value={config.fallback?.listen || ''}
onChange={(e) => updateConfigField(['fallback', 'listen'], e.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_fb_target')}</label>
<input
type="text"
disabled={!config.fallback?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50"
placeholder="e.g. 127.0.0.1:8080"
value={config.fallback?.target || ''}
onChange={(e) => updateConfigField(['fallback', 'target'], e.target.value)}
/>
</div>
</div>
</div>
{/* SECTION: REALITY MASQUERADE */}
<div className="glass-panel rounded-2xl p-6 space-y-4">
<h2 className="text-lg font-bold border-b border-white/5 pb-2 text-white flex items-center gap-2">
<Globe className="w-5 h-5 text-purple-400" /> {t('st_ui_rl_title')}
</h2>
<div className="flex items-center gap-3 mb-2">
<input
type="checkbox"
id="reality-enabled"
className="w-4 h-4 accent-primary rounded bg-white/5 border-white/10"
checked={config.reality?.enabled || false}
onChange={(e) => updateConfigField(['reality', 'enabled'], e.target.checked)}
/>
<label htmlFor="reality-enabled" className="text-sm font-medium text-white cursor-pointer select-none">
{t('st_ui_rl_enable')}
</label>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2 col-span-1 md:col-span-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_rl_dest')}</label>
<input
type="text"
disabled={!config.reality?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50"
placeholder="e.g. www.microsoft.com:443"
value={config.reality?.dest || ''}
onChange={(e) => updateConfigField(['reality', 'dest'], e.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_rl_pri')}</label>
<input
type="text"
disabled={!config.reality?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50 text-xs"
value={config.reality?.private_key || ''}
onChange={(e) => updateConfigField(['reality', 'private_key'], e.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_rl_pub')}</label>
<input
type="text"
disabled={!config.reality?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50 text-xs"
value={config.reality?.pbk || ''}
onChange={(e) => updateConfigField(['reality', 'pbk'], e.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_rl_sid')}</label>
<input
type="text"
disabled={!config.reality?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50"
value={config.reality?.sid || ''}
onChange={(e) => updateConfigField(['reality', 'sid'], e.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_rl_sni')}</label>
<input
type="text"
disabled={!config.reality?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50"
placeholder="e.g. www.microsoft.com, microsoft.com"
value={config.reality?.sni_list ? config.reality.sni_list.join(', ') : ''}
onChange={(e) => {
const list = e.target.value.split(',').map(s => s.trim()).filter(Boolean);
updateConfigField(['reality', 'sni_list'], list);
}}
/>
</div>
</div>
</div>
{/* SECTION: OUTBOUND ROUTING */}
<div className="glass-panel rounded-2xl p-6 space-y-4">
<h2 className="text-lg font-bold border-b border-white/5 pb-2 text-white flex items-center gap-2">
<Globe className="w-5 h-5 text-red-400" /> {t('st_ui_ob_title')}
</h2>
<div className="flex items-center gap-3 mb-2">
<input
type="checkbox"
id="outbound-enabled"
className="w-4 h-4 accent-primary rounded bg-white/5 border-white/10"
checked={config.outbound?.enabled || false}
onChange={(e) => updateConfigField(['outbound', 'enabled'], e.target.checked)}
/>
<label htmlFor="outbound-enabled" className="text-sm font-medium text-white cursor-pointer select-none">
{t('st_ui_ob_enable')}
</label>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_ob_proto')}</label>
<select
disabled={!config.outbound?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-primary disabled:opacity-50"
value={config.outbound?.protocol || 'socks5'}
onChange={(e) => updateConfigField(['outbound', 'protocol'], e.target.value)}
>
<option value="socks5">socks5</option>
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_ob_addr')}</label>
<input
type="text"
disabled={!config.outbound?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50"
placeholder="e.g. 127.0.0.1"
value={config.outbound?.address || ''}
onChange={(e) => updateConfigField(['outbound', 'address'], e.target.value)}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_ob_port')}</label>
<input
type="number"
disabled={!config.outbound?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white font-mono disabled:opacity-50"
placeholder="e.g. 9050"
value={config.outbound?.port || ''}
onChange={(e) => updateConfigField(['outbound', 'port'], parseInt(e.target.value) || 0)}
/>
</div>
<div className="space-y-2 col-span-1 md:col-span-3">
<label className="text-sm font-semibold text-text-muted uppercase">{t('st_ui_ob_action')}</label>
<select
disabled={!config.outbound?.enabled}
className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white focus:outline-none focus:border-primary disabled:opacity-50"
value={config.outbound?.default_action || 'direct'}
onChange={(e) => updateConfigField(['outbound', 'default_action'], e.target.value)}
>
<option value="direct">{t('st_ui_ob_action_direct')}</option>
<option value="proxy">{t('st_ui_ob_action_proxy')}</option>
</select>
</div>
</div>
</div>
{/* Form Actions */}
<div className="flex gap-4">
<button
type="submit"
className="flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-6 py-3 rounded-xl font-bold transition-colors shadow-[0_0_15px_rgba(108,114,255,0.3)]"
>
<Save className="w-5 h-5" /> {t('st_save_btn')}
</button>
</div>
</form>
)}
</div>
);
}

View File

@ -0,0 +1,372 @@
import { useState, useRef } from 'react';
import { Wrench, Key, Download, Upload, RefreshCw, CheckCircle, XCircle, AlertTriangle, ShieldAlert, Copy } from 'lucide-react';
import { useLanguage } from '../lib/LanguageContext';
import { api, getApiSettings } from '../lib/api';
import { addAuditLog } from '../lib/audit';
export default function Tools() {
const { t, language } = useLanguage();
// Keygen State
const [keys, setKeys] = useState<{ publicKey: string; privateKey: string; sid: string; isFallback?: boolean } | null>(null);
const [isGenerating, setIsGenerating] = useState(false);
const [isCopied, setIsCopied] = useState(false);
// Backup State
const [isExporting, setIsExporting] = useState(false);
const [isImporting, setIsImporting] = useState(false);
const [importResult, setImportResult] = useState<{ success: boolean; message: string } | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// Diagnostics State
const [pingLatency, setPingLatency] = useState<number | null>(null);
const [isPinging, setIsPinging] = useState(false);
const [pingResult, setPingResult] = useState<{ success: boolean; message: string } | null>(null);
// Reality X25519 Key Generator using Web Crypto
const handleGenerateKeys = async () => {
setIsGenerating(true);
setKeys(null);
setIsCopied(false);
// Simulate slight lag for UI satisfaction
await new Promise(resolve => setTimeout(resolve, 600));
try {
// Try using modern browser Web Crypto for X25519
const keypair = await window.crypto.subtle.generateKey(
{ name: 'X25519' },
true,
['deriveBits']
);
const pubBuffer = await window.crypto.subtle.exportKey('raw', keypair.publicKey);
const priPkcs8 = await window.crypto.subtle.exportKey('pkcs8', keypair.privateKey);
// Raw private key bytes are at the end of PKCS#8 ASN.1 wrapper for X25519 (last 32 bytes)
const priBuffer = priPkcs8.slice(priPkcs8.byteLength - 32);
const toBase64 = (buf: ArrayBuffer) => {
const bytes = new Uint8Array(buf);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, ''); // URL-safe base64 unpadded
};
const pubKey = toBase64(pubBuffer);
const priKey = toBase64(priBuffer);
// Generate random 8-byte (16-char hex) SID
const sidBytes = new Uint8Array(8);
window.crypto.getRandomValues(sidBytes);
const sid = Array.from(sidBytes).map(b => b.toString(16).padStart(2, '0')).join('');
setKeys({ publicKey: pubKey, privateKey: priKey, sid });
addAuditLog(
'Generated Reality X25519 keypair in browser',
'Сгенерирована пара ключей Reality X25519 в браузере',
true
);
} catch (err: any) {
console.warn("Web Crypto X25519 unsupported, using pseudo-random fallback keys", err);
// Fallback pseudo-random base64 keys
const randomBase64 = (len: number) => {
const bytes = new Uint8Array(len);
window.crypto.getRandomValues(bytes);
let binary = '';
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
};
const sidBytes = new Uint8Array(8);
window.crypto.getRandomValues(sidBytes);
const sid = Array.from(sidBytes).map(b => b.toString(16).padStart(2, '0')).join('');
setKeys({
publicKey: randomBase64(32),
privateKey: randomBase64(32),
sid,
isFallback: true
});
addAuditLog(
'Generated fallback Reality keypair (pseudo-random)',
'Сгенерированы резервные ключи Reality (псевдослучайные)',
true
);
} finally {
setIsGenerating(false);
}
};
const handleCopyKeys = () => {
if (!keys) return;
const text = `private_key: ${keys.privateKey}\npbk: ${keys.publicKey}\nsid: ${keys.sid}`;
navigator.clipboard.writeText(text);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
};
// Export config.json
const handleExportConfig = async () => {
setIsExporting(true);
try {
const configData = await api.getServerConfig();
const jsonString = `data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(configData, null, 2))}`;
const downloadAnchor = document.createElement('a');
downloadAnchor.setAttribute('href', jsonString);
downloadAnchor.setAttribute('download', 'ostp_config_backup.json');
document.body.appendChild(downloadAnchor);
downloadAnchor.click();
downloadAnchor.remove();
addAuditLog('Exported server configuration backup', 'Экспортирована резервная копия конфигурации сервера', true);
} catch (err: any) {
alert(`Export failed: ${err.message || err}`);
addAuditLog('Failed to export configuration backup', 'Ошибка экспорта резервной копии конфигурации', false);
} finally {
setIsExporting(false);
}
};
// Import config.json
const handleImportFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsImporting(true);
setImportResult(null);
const reader = new FileReader();
reader.onload = async (event) => {
try {
const text = event.target?.result as string;
const parsedConfig = JSON.parse(text);
if (parsedConfig.mode !== 'server') {
throw new Error(language === 'ru' ? 'Файл не является валидной серверной конфигурацией OSTP' : 'File is not a valid OSTP server configuration');
}
await api.updateServerConfig(parsedConfig);
setImportResult({
success: true,
message: t('tl_backup_import_success')
});
addAuditLog('Restored server configuration from backup file', 'Конфигурация сервера успешно восстановлена из бэкапа', true);
} catch (err: any) {
setImportResult({
success: false,
message: `${t('tl_backup_import_error')} ${err.message || err}`
});
addAuditLog('Failed to restore server configuration from backup file', 'Не удалось восстановить конфигурацию из файла бэкапа', false);
} finally {
setIsImporting(false);
if (fileInputRef.current) fileInputRef.current.value = '';
}
};
reader.readAsText(file);
};
// Diagnostics: latency test (ping)
const handlePingTest = async () => {
setIsPinging(true);
setPingResult(null);
setPingLatency(null);
const startTime = performance.now();
try {
await api.getServerStatus();
const endTime = performance.now();
const latency = Math.round(endTime - startTime);
setPingLatency(latency);
setPingResult({
success: true,
message: language === 'ru' ? `Успешный ответ. Задержка сети: ${latency} мс` : `Successful response. Network latency: ${latency} ms`
});
} catch (err: any) {
setPingResult({
success: false,
message: language === 'ru' ? `Хост недоступен или не отвечает: ${err.message || err}` : `Host unreachable or error response: ${err.message || err}`
});
} finally {
setIsPinging(false);
}
};
return (
<div className="relative z-10 w-full max-w-6xl mx-auto space-y-6 animate-in fade-in duration-300">
{/* Title */}
<div>
<h1 className="text-3xl font-bold tracking-tight mb-1 flex items-center gap-3">
<Wrench className="w-8 h-8 text-primary" /> {t('tl_title')}
</h1>
<p className="text-text-muted">{t('tl_subtitle')}</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Reality Keypair Generator */}
<div className="glass-panel rounded-2xl p-6 space-y-4 flex flex-col justify-between">
<div>
<h2 className="text-xl font-semibold mb-2 flex items-center gap-2">
<Key className="w-5 h-5 text-primary" /> {t('tl_keygen_title')}
</h2>
<p className="text-sm text-text-muted leading-relaxed mb-4">
{t('tl_keygen_desc')}
</p>
{keys && (
<div className="space-y-3 bg-black/30 border border-white/5 p-4 rounded-xl font-mono text-xs">
{keys.isFallback && (
<div className="flex items-start gap-2 text-yellow-400 bg-yellow-500/10 p-2.5 rounded-lg mb-2">
<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
<span>
{language === 'ru'
? 'Браузер не поддерживает криптографию Curve25519 (X25519). Ключи сгенерированы в тестовом режиме. Рекомендуется использовать CLI ядра: ostp --generate-key.'
: 'Web Crypto API does not support Curve25519 (X25519) in this browser. Generated pseudo-random keys. For production, run: ostp --generate-key.'}
</span>
</div>
)}
<div>
<span className="text-text-muted">private_key: </span>
<span className="text-secondary select-all">{keys.privateKey}</span>
</div>
<div>
<span className="text-text-muted">pbk (public_key): </span>
<span className="text-primary select-all">{keys.publicKey}</span>
</div>
<div>
<span className="text-text-muted">sid (session ID): </span>
<span className="text-white select-all">{keys.sid}</span>
</div>
</div>
)}
</div>
<div className="flex gap-3 pt-4 border-t border-white/5">
<button
onClick={handleGenerateKeys}
disabled={isGenerating}
className="flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-5 py-2.5 rounded-xl font-semibold transition-colors disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${isGenerating ? 'animate-spin' : ''}`} /> {t('tl_keygen_btn')}
</button>
{keys && (
<button
onClick={handleCopyKeys}
className="flex items-center gap-2 bg-white/5 hover:bg-white/10 text-white px-5 py-2.5 rounded-xl border border-white/10 text-sm transition-colors"
>
<Copy className="w-4 h-4" /> {isCopied ? t('cl_copied') : t('tl_keygen_copy')}
</button>
)}
</div>
</div>
{/* Backup & Restore Configuration */}
<div className="glass-panel rounded-2xl p-6 space-y-4 flex flex-col justify-between">
<div>
<h2 className="text-xl font-semibold mb-2 flex items-center gap-2">
<Download className="w-5 h-5 text-secondary" /> {t('tl_backup_title')}
</h2>
<p className="text-sm text-text-muted leading-relaxed mb-4">
{t('tl_backup_desc')}
</p>
{importResult && (
<div className={`p-4 rounded-xl flex items-start gap-2.5 border ${
importResult.success ? 'bg-secondary/10 border-secondary/20 text-secondary' : 'bg-red-500/10 border-red-500/20 text-red-400'
}`}>
{importResult.success ? <CheckCircle className="w-5 h-5 shrink-0 mt-0.5" /> : <XCircle className="w-5 h-5 shrink-0 mt-0.5" />}
<p className="text-xs font-mono">{importResult.message}</p>
</div>
)}
</div>
<div className="space-y-4 pt-4 border-t border-white/5">
<button
onClick={handleExportConfig}
disabled={isExporting}
className="w-full flex items-center justify-center gap-2 bg-white/5 hover:bg-white/10 text-white border border-white/10 py-3 rounded-xl font-semibold transition-colors"
>
<Download className="w-5 h-5" /> {t('tl_backup_export')}
</button>
<div
onClick={() => fileInputRef.current?.click()}
className="border-2 border-dashed border-white/10 hover:border-primary/50 bg-white/[0.01] hover:bg-white/[0.03] rounded-xl p-4 text-center cursor-pointer transition-all"
>
<Upload className="w-6 h-6 mx-auto mb-2 text-text-muted" />
<span className="text-xs text-text-muted font-medium">{t('tl_backup_import_zone')}</span>
<input
type="file"
ref={fileInputRef}
className="hidden"
accept=".json"
onChange={handleImportFileChange}
disabled={isImporting}
/>
</div>
</div>
</div>
{/* API Connection Diagnostics */}
<div className="glass-panel rounded-2xl p-6 lg:col-span-2 space-y-4">
<h2 className="text-xl font-semibold mb-2 flex items-center gap-2">
<ShieldAlert className="w-5 h-5 text-blue-400" /> {t('tl_diag_title')}
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-center">
<div className="space-y-2 bg-black/20 p-4 rounded-xl border border-white/5 text-sm font-mono">
<div>
<span className="text-text-muted">API Connection: </span>
<span className="text-white">{getApiSettings().url}</span>
</div>
<div>
<span className="text-text-muted">Auth Status: </span>
<span className={getApiSettings().token ? 'text-secondary' : 'text-yellow-400'}>
{getApiSettings().token ? 'Authorized Token (Active)' : 'No Token Configuration'}
</span>
</div>
{pingLatency !== null && (
<div>
<span className="text-text-muted">Ping RTT: </span>
<span className="text-secondary font-bold">{pingLatency} ms</span>
</div>
)}
</div>
<div className="space-y-3">
<button
onClick={handlePingTest}
disabled={isPinging}
className="w-full flex items-center justify-center gap-2 bg-white/5 hover:bg-white/10 text-white border border-white/10 py-3 rounded-xl font-semibold transition-colors"
>
<RefreshCw className={`w-4 h-4 ${isPinging ? 'animate-spin' : ''}`} /> {t('tl_diag_ping')}
</button>
{pingResult && (
<div className={`p-4 rounded-xl flex items-start gap-2.5 border ${
pingResult.success ? 'bg-secondary/10 border-secondary/20 text-secondary' : 'bg-red-500/10 border-red-500/20 text-red-400'
}`}>
{pingResult.success ? <CheckCircle className="w-5 h-5 shrink-0 mt-0.5" /> : <XCircle className="w-5 h-5 shrink-0 mt-0.5" />}
<p className="text-xs font-mono">{pingResult.message}</p>
</div>
)}
</div>
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,417 @@
import { useState, useEffect } from 'react';
import { BookOpen, RefreshCw, AlertTriangle, ExternalLink } from 'lucide-react';
import { useLanguage } from '../lib/LanguageContext';
const CONFIG_GUIDE_URL = 'https://raw.githubusercontent.com/ospab/ostp/master/ostp-wiki/configuration_guide.md';
const API_ENDPOINTS_URL = 'https://raw.githubusercontent.com/ospab/ostp/master/ostp-wiki/api_endpoints.md';
export default function Wiki() {
const { t } = useLanguage();
const [activeTab, setActiveTab] = useState<'config' | 'api'>('config');
const [markdown, setMarkdown] = useState<string>('');
const [isLoading, setIsLoading] = useState(true);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const fetchDoc = async (tab: 'config' | 'api') => {
setIsLoading(true);
setErrorMsg(null);
const targetUrl = tab === 'config' ? CONFIG_GUIDE_URL : API_ENDPOINTS_URL;
try {
const response = await fetch(targetUrl);
if (!response.ok) throw new Error(`HTTP status ${response.status}`);
const text = await response.text();
setMarkdown(text);
} catch (err: any) {
console.warn("Failed to fetch markdown from GitHub, using offline backup copy", err);
setErrorMsg(t('wk_load_error'));
// Load local offline backup copies
setMarkdown(tab === 'config' ? LOCAL_CONFIG_GUIDE_BACKUP : LOCAL_API_ENDPOINTS_BACKUP);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchDoc(activeTab);
}, [activeTab]);
return (
<div className="relative z-10 w-full max-w-5xl mx-auto space-y-6 animate-in fade-in duration-300">
{/* Title */}
<div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4">
<div>
<h1 className="text-3xl font-bold tracking-tight mb-1 flex items-center gap-3">
<BookOpen className="w-8 h-8 text-primary" /> {t('wk_title')}
</h1>
<p className="text-text-muted">{t('wk_subtitle')}</p>
</div>
<a
href="https://github.com/ospab/ostp/wiki"
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 text-xs text-primary hover:underline font-semibold bg-primary/10 border border-primary/20 px-3.5 py-2 rounded-xl shrink-0"
>
GitHub Wiki <ExternalLink className="w-3.5 h-3.5" />
</a>
</div>
{/* Tabs */}
<div className="flex border-b border-white/5 gap-2">
<button
onClick={() => setActiveTab('config')}
disabled={isLoading}
className={`px-5 py-3 font-medium transition-colors border-b-2 text-sm ${
activeTab === 'config' ? 'border-primary text-white' : 'border-transparent text-text-muted hover:text-white'
}`}
>
{t('wk_tab_guide')}
</button>
<button
onClick={() => setActiveTab('api')}
disabled={isLoading}
className={`px-5 py-3 font-medium transition-colors border-b-2 text-sm ${
activeTab === 'api' ? 'border-primary text-white' : 'border-transparent text-text-muted hover:text-white'
}`}
>
{t('wk_tab_api')}
</button>
</div>
{/* Error alert */}
{errorMsg && (
<div className="bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 p-4 rounded-xl flex items-start gap-3">
<AlertTriangle className="w-5 h-5 shrink-0 mt-0.5" />
<p className="text-xs font-semibold font-mono leading-relaxed">{errorMsg}</p>
</div>
)}
{/* Loading state */}
{isLoading ? (
<div className="glass-panel rounded-2xl p-16 flex flex-col items-center justify-center text-center gap-3">
<RefreshCw className="w-8 h-8 animate-spin text-primary" />
<span className="text-sm text-text-muted font-medium">{t('wk_loading')}</span>
</div>
) : (
<div className="glass-panel rounded-2xl p-8 shadow-xl border border-white/10 prose prose-invert max-w-none prose-sm">
{renderMarkdown(markdown)}
</div>
)}
</div>
);
}
// Custom Markdown Renderer to JSX/HTML
function renderMarkdown(md: string) {
const lines = md.split('\n');
const elements: React.ReactNode[] = [];
let inCodeBlock = false;
let codeBlockContent: string[] = [];
let inTable = false;
let tableHeaders: string[] = [];
let tableRows: string[][] = [];
const parseInline = (text: string) => {
const regex = /(\*\*.*?\*\*|`.*?`)/g;
const segments = text.split(regex);
return segments.map((seg, idx) => {
if (seg.startsWith('**') && seg.endsWith('**')) {
return <strong key={idx} className="text-white font-bold">{seg.slice(2, -2)}</strong>;
}
if (seg.startsWith('`') && seg.endsWith('`')) {
return <code key={idx} className="bg-white/10 px-1.5 py-0.5 rounded font-mono text-xs text-primary">{seg.slice(1, -1)}</code>;
}
return seg;
});
};
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Code block
if (line.startsWith('```')) {
if (inCodeBlock) {
inCodeBlock = false;
elements.push(
<pre key={i} className="bg-black/50 border border-white/15 p-4 rounded-xl font-mono text-xs overflow-x-auto text-secondary/90 my-4 select-all">
<code>{codeBlockContent.join('\n')}</code>
</pre>
);
codeBlockContent = [];
} else {
inCodeBlock = true;
}
continue;
}
if (inCodeBlock) {
codeBlockContent.push(lines[i]);
continue;
}
// Tables
if (line.startsWith('|')) {
inTable = true;
const cells = line.split('|').map(c => c.trim()).filter((_, idx, arr) => idx > 0 && idx < arr.length - 1);
if (cells.every(c => c.startsWith('-'))) {
continue;
}
if (tableHeaders.length === 0) {
tableHeaders = cells;
} else {
tableRows.push(cells);
}
continue;
} else if (inTable) {
// Table ended, compile it
elements.push(
<div key={`table-${i}`} className="overflow-x-auto my-4 border border-white/5 rounded-xl">
<table className="w-full text-left border-collapse bg-white/[0.01]">
<thead>
<tr className="border-b border-white/5 bg-white/[0.02]">
{tableHeaders.map((h, idx) => (
<th key={idx} className="px-4 py-3 font-semibold text-text-muted text-xs uppercase">{h}</th>
))}
</tr>
</thead>
<tbody className="divide-y divide-white/5 text-sm">
{tableRows.map((row, rIdx) => (
<tr key={rIdx} className="hover:bg-white/[0.01]">
{row.map((cell, cIdx) => (
<td key={cIdx} className="px-4 py-2.5 text-white/90 font-medium">{parseInline(cell)}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
inTable = false;
tableHeaders = [];
tableRows = [];
}
if (line === '') {
continue;
}
// Headers
if (line.startsWith('# ')) {
elements.push(<h1 key={i} className="text-2xl font-extrabold text-white mt-6 mb-3 border-b border-white/5 pb-2">{parseInline(line.slice(2))}</h1>);
} else if (line.startsWith('## ')) {
elements.push(<h2 key={i} className="text-xl font-bold text-white mt-5 mb-3">{parseInline(line.slice(3))}</h2>);
} else if (line.startsWith('### ')) {
elements.push(<h3 key={i} className="text-lg font-semibold text-white mt-4 mb-2">{parseInline(line.slice(4))}</h3>);
}
// Lists
else if (line.startsWith('- ') || line.startsWith('* ')) {
elements.push(
<ul key={i} className="list-disc list-inside ml-4 text-sm text-text-muted my-1.5">
<li>{parseInline(line.slice(2))}</li>
</ul>
);
}
// Horizontal rule
else if (line === '---') {
elements.push(<hr key={i} className="border-t border-white/5 my-6" />);
}
// Paragraph
else {
elements.push(<p key={i} className="text-sm text-text-muted leading-relaxed my-2">{parseInline(line)}</p>);
}
}
// Handle unclosed table at the end
if (inTable) {
elements.push(
<div key={`table-end`} className="overflow-x-auto my-4 border border-white/5 rounded-xl">
<table className="w-full text-left border-collapse bg-white/[0.01]">
<thead>
<tr className="border-b border-white/5 bg-white/[0.02]">
{tableHeaders.map((h, idx) => (
<th key={idx} className="px-4 py-3 font-semibold text-text-muted text-xs uppercase">{h}</th>
))}
</tr>
</thead>
<tbody className="divide-y divide-white/5 text-sm">
{tableRows.map((row, rIdx) => (
<tr key={rIdx} className="hover:bg-white/[0.01]">
{row.map((cell, cIdx) => (
<td key={cIdx} className="px-4 py-2.5 text-white/90 font-medium">{parseInline(cell)}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
}
return elements;
}
const LOCAL_CONFIG_GUIDE_BACKUP = `# Руководство по конфигурации OSTP (\`config.json\`)
Файл \`config.json\` является основным конфигурационным файлом для сервера, клиента и реле.
## Полный пример конфигурации
\`\`\`json
{
"mode": "server",
"log_level": "info",
"listen": "0.0.0.0:50000",
"access_keys": [
"some_simple_key",
{
"access_key": "detailed_key_with_limit",
"name": "Рабочий Ноутбук",
"limit_bytes": 107374182400
}
],
"api": {
"enabled": true,
"bind": "127.0.0.1:9090",
"token": "7a3f8b2c4d9e0f1a2b3c4d5e6f7a8b9c"
},
"fallback": {
"enabled": false,
"listen": "0.0.0.0:443",
"target": "127.0.0.1:8080"
},
"reality": {
"enabled": false,
"dest": "www.microsoft.com:443",
"private_key": "...",
"pbk": "...",
"sid": "...",
"sni_list": ["www.microsoft.com"]
},
"outbound": {
"enabled": false,
"protocol": "socks5",
"address": "127.0.0.1",
"port": 9050,
"default_action": "proxy"
},
"debug": false
}
\`\`\`
## Описание разделов конфигурации
### 1. Основные параметры
- **\`mode\`** (строка): Режим работы. Варианты: \`"server"\`, \`"client"\`, \`"relay"\`.
- **\`log_level\`** (строка): Уровень логирования. Варианты: \`"debug"\`, \`"info"\`, \`"warn"\`, \`"error"\`.
- **\`listen\`** (строка или массив строк): Интерфейс и порт входящих соединений. Пример: \`"0.0.0.0:50000"\`.
- **\`debug\`** (логический): Подробная сетевая отладка протокола.
### 2. Ключи доступа (\`access_keys\`)
Раздел содержит массив ключей доступа. Поддерживается два формата записи:
1. **Простая строка**: Текст ключа доступа. Лимит трафика отсутствует.
2. **Объект с метаданными**:
- \`access_key\` (строка, обязательно): Текст ключа для подключения.
- \`name\` (строка, опционально): Описание клиента.
- \`limit_bytes\` (число, опционально): Лимит трафика в байтах.
### 3. REST API Управления (\`api\`)
Используется для интеграции с панелью управления \`ostp-control\`.
- **\`enabled\`** (логический): Включение веб-сервера API.
- **\`bind\`** (строка): Адрес прослушивания (например, \`"127.0.0.1:9090"\`).
- **\`token\`** (строка): Bearer-токен для авторизации администратора.
### 4. Встроенный TCP Fallback прокси (\`fallback\`)
- **\`enabled\`** (логический): Включить проксирование TCP.
- **\`listen\`** (строка): Порт прослушивания TCP/TLS (например, \`"0.0.0.0:443"\`).
- **\`target\`** (строка): Локальный веб-сервер (например, \`"127.0.0.1:8080"\` на nginx/caddy), куда пересылаются все обычные запросы.
### 5. Reality Маскировка (\`reality\`)
Реализует маскировку Reality (XTLS).
- **\`enabled\`** (логический): Включение Reality.
- **\`dest\`** (строка): Домен назначения (например, \`"www.microsoft.com:443"\`).
- **\`private_key\`** (строка): Приватный ключ X25519.
- **\`pbk\`** (строка): Публичный ключ X25519.
- **\`sid\`** (строка, 8 байт hex): Идентификатор сессии.
- **\`sni_list\`** (массив строк): Разрешенные SNI заголовки от клиентов.`;
const LOCAL_API_ENDPOINTS_BACKUP = `# Справочник API управления OSTP
Сервер OSTP предоставляет REST API для управления пользователями и просмотра статистики.
## Авторизация
Все запросы должны содержать заголовок \`Authorization\` с API-токеном:
\`\`\`http
Authorization: Bearer <ваш_api_токен>
\`\`\`
## Список эндпоинтов
### 1. Статус сервера
- **URL**: \`/api/server/status\`
- **Метод**: \`GET\`
- **Формат data**:
\`\`\`json
{
"version": "0.2.30",
"uptime_seconds": 12053,
"active_users": 2,
"total_users": 5
}
\`\`\`
### 2. Получение текущего конфига
- **URL**: \`/api/server/config\`
- **Метод**: \`GET\`
- **Формат data**: Полный JSON-конфиг сервера.
### 3. Обновление конфига
- **URL**: \`/api/server/config\`
- **Метод**: \`PUT\`
- **Тело запроса**: JSON нового конфигурационного файла. Вызывает hot-reload ядра.
### 4. Список клиентов и их статистика
- **URL**: \`/api/users\`
- **Метод**: \`GET\`
- **Формат data**:
\`\`\`json
[
{
"access_key": "ostp_key_sample1",
"bytes_up": 2405020,
"bytes_down": 491029402,
"connections": 2,
"limit_bytes": 10737418240,
"online": true,
"name": "Ноутбук"
}
]
\`\`\`
### 5. Создание клиента
- **URL**: \`/api/users\`
- **Метод**: \`POST\`
- **Тело запроса**:
\`\`\`json
{
"access_key": "my_custom_key_optional",
"name": "Имя клиента",
"limit_bytes": 50000000000
}
\`\`\`
### 6. Удаление клиента
- **URL**: \`/api/users/:key\`
- **Метод**: \`DELETE\`
### 7. Обновление клиента
- **URL**: \`/api/users/:key\`
- **Метод**: \`PUT\`
- **Тело запроса**: \`{"name": "...", "limit_bytes": ...}\`
### 8. Сброс счетчиков трафика
- **URL**: \`/api/users/{key}/reset\`
- **Метод**: \`POST\``;

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

View File

@ -0,0 +1,9 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
// https://vite.dev/config/
export default defineConfig({
base: './',
plugins: [react(), tailwindcss()],
})