feat: Добавлена веб-панель управления VPN-прокси и Docker-конфигурация.
This commit is contained in:
429
web/index.html
429
web/index.html
@@ -340,6 +340,163 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* Tabs */
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.tab {
|
||||
flex: 1;
|
||||
padding: 0.75rem 1rem;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 10px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.tab:hover {
|
||||
border-color: var(--accent);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: white;
|
||||
box-shadow: 0 4px 12px var(--accent-glow);
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tab-content.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Server List */
|
||||
.server-list {
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.server-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.875rem 1rem;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 10px;
|
||||
margin-bottom: 0.5rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.server-item:hover {
|
||||
border-color: var(--accent);
|
||||
background: rgba(99, 102, 241, 0.05);
|
||||
}
|
||||
|
||||
.server-item.selected {
|
||||
border-color: var(--accent);
|
||||
background: rgba(99, 102, 241, 0.1);
|
||||
box-shadow: 0 0 0 2px var(--accent-glow);
|
||||
}
|
||||
|
||||
.server-radio {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: 2px solid var(--border-color);
|
||||
border-radius: 50%;
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.server-item.selected .server-radio {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.server-item.selected .server-radio::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
background: var(--accent);
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.server-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.server-name {
|
||||
font-weight: 500;
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.server-details {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary);
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
|
||||
.server-type {
|
||||
font-size: 0.7rem;
|
||||
padding: 0.2rem 0.5rem;
|
||||
background: rgba(99, 102, 241, 0.15);
|
||||
color: var(--accent);
|
||||
border-radius: 4px;
|
||||
text-transform: uppercase;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
border-color: var(--accent);
|
||||
background: rgba(99, 102, 241, 0.1);
|
||||
}
|
||||
|
||||
.btn-group {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.btn-group .btn {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.empty-state-icon {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
/* Responsive */
|
||||
@media (max-width: 480px) {
|
||||
body {
|
||||
@@ -354,6 +511,15 @@
|
||||
h1 {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.btn-group {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
@@ -375,21 +541,62 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form id="proxyForm">
|
||||
<!-- Tabs -->
|
||||
<div class="tabs">
|
||||
<button class="tab active" data-tab="subscription">📡 Подписка</button>
|
||||
<button class="tab" data-tab="vless">🔑 VLESS Ключ</button>
|
||||
</div>
|
||||
|
||||
<!-- Subscription Tab Content -->
|
||||
<div id="subscription-tab" class="tab-content active">
|
||||
<div class="form-group">
|
||||
<label for="urlInput">VLESS Key</label>
|
||||
<label for="subUrlInput">URL подписки</label>
|
||||
<div class="input-wrapper">
|
||||
<input type="text" id="urlInput" placeholder="vless://..." autocomplete="off"
|
||||
<input type="text" id="subUrlInput" placeholder="https://..." autocomplete="off"
|
||||
spellcheck="false">
|
||||
</div>
|
||||
<p class="hint">Вставьте VLESS ссылку</p>
|
||||
<p class="hint">Вставьте ссылку подписки (sing-box формат)</p>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary" id="submitBtn">
|
||||
<span class="btn-icon">⚡</span>
|
||||
<span id="btnText">Применить</span>
|
||||
<button type="button" class="btn btn-secondary" id="fetchServersBtn" style="margin-bottom: 1rem;">
|
||||
<span class="btn-icon">🔄</span>
|
||||
<span id="fetchBtnText">Загрузить серверы</span>
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div id="serverListContainer" style="display: none;">
|
||||
<label style="margin-bottom: 0.75rem; display: block;">Выберите сервер</label>
|
||||
<div class="server-list" id="serverList"></div>
|
||||
|
||||
<button type="button" class="btn btn-primary" id="applySubBtn">
|
||||
<span class="btn-icon">⚡</span>
|
||||
<span id="applySubBtnText">Применить</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="emptyServers" class="empty-state" style="display: none;">
|
||||
<div class="empty-state-icon">📭</div>
|
||||
<p>Серверы не загружены</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- VLESS Tab Content -->
|
||||
<div id="vless-tab" class="tab-content">
|
||||
<form id="proxyForm">
|
||||
<div class="form-group">
|
||||
<label for="urlInput">VLESS Key</label>
|
||||
<div class="input-wrapper">
|
||||
<input type="text" id="urlInput" placeholder="vless://..." autocomplete="off"
|
||||
spellcheck="false">
|
||||
</div>
|
||||
<p class="hint">Вставьте VLESS ссылку</p>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary" id="submitBtn">
|
||||
<span class="btn-icon">⚡</span>
|
||||
<span id="btnText">Применить</span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="message" id="message">
|
||||
<span class="message-icon" id="messageIcon"></span>
|
||||
@@ -416,6 +623,7 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// DOM Elements
|
||||
const form = document.getElementById('proxyForm');
|
||||
const urlInput = document.getElementById('urlInput');
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
@@ -426,6 +634,36 @@
|
||||
const statusIndicator = document.getElementById('statusIndicator');
|
||||
const statusValue = document.getElementById('statusValue');
|
||||
|
||||
// Subscription elements
|
||||
const subUrlInput = document.getElementById('subUrlInput');
|
||||
const fetchServersBtn = document.getElementById('fetchServersBtn');
|
||||
const fetchBtnText = document.getElementById('fetchBtnText');
|
||||
const serverListContainer = document.getElementById('serverListContainer');
|
||||
const serverList = document.getElementById('serverList');
|
||||
const emptyServers = document.getElementById('emptyServers');
|
||||
const applySubBtn = document.getElementById('applySubBtn');
|
||||
const applySubBtnText = document.getElementById('applySubBtnText');
|
||||
|
||||
// State
|
||||
let subscriptionConfig = null;
|
||||
let selectedServer = null;
|
||||
let subscriptionUrl = null;
|
||||
|
||||
// Tab switching
|
||||
document.querySelectorAll('.tab').forEach(tab => {
|
||||
tab.addEventListener('click', () => {
|
||||
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
||||
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
|
||||
|
||||
tab.classList.add('active');
|
||||
const targetTab = tab.dataset.tab;
|
||||
document.getElementById(`${targetTab}-tab`).classList.add('active');
|
||||
|
||||
// Hide message when switching tabs
|
||||
message.className = 'message';
|
||||
});
|
||||
});
|
||||
|
||||
// Fetch initial status
|
||||
async function fetchStatus() {
|
||||
try {
|
||||
@@ -452,15 +690,16 @@
|
||||
messageText.textContent = text;
|
||||
}
|
||||
|
||||
function setLoading(loading) {
|
||||
submitBtn.disabled = loading;
|
||||
function setLoading(btn, textEl, loading, defaultText = 'Применить') {
|
||||
btn.disabled = loading;
|
||||
if (loading) {
|
||||
btnText.innerHTML = '<div class="spinner"></div>';
|
||||
textEl.innerHTML = '<div class="spinner"></div>';
|
||||
} else {
|
||||
btnText.textContent = 'Применить';
|
||||
textEl.textContent = defaultText;
|
||||
}
|
||||
}
|
||||
|
||||
// VLESS form submit
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -471,7 +710,7 @@
|
||||
}
|
||||
|
||||
message.className = 'message';
|
||||
setLoading(true);
|
||||
setLoading(submitBtn, btnText, true);
|
||||
|
||||
try {
|
||||
const res = await fetch('/apply', {
|
||||
@@ -492,12 +731,174 @@
|
||||
} catch (e) {
|
||||
showMessage('error', `Ошибка сети: ${e.message}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setLoading(submitBtn, btnText, false);
|
||||
}
|
||||
});
|
||||
|
||||
// Fetch servers from subscription
|
||||
fetchServersBtn.addEventListener('click', async () => {
|
||||
const url = subUrlInput.value.trim();
|
||||
if (!url) {
|
||||
showMessage('error', 'Введите URL подписки');
|
||||
return;
|
||||
}
|
||||
|
||||
message.className = 'message';
|
||||
setLoading(fetchServersBtn, fetchBtnText, true, 'Загрузить серверы');
|
||||
|
||||
try {
|
||||
const res = await fetch('/fetch-subscription', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (data.success && data.servers && data.servers.length > 0) {
|
||||
subscriptionConfig = data.config;
|
||||
subscriptionUrl = url; // Save URL for persistence
|
||||
renderServerList(data.servers);
|
||||
serverListContainer.style.display = 'block';
|
||||
emptyServers.style.display = 'none';
|
||||
showMessage('success', `Найдено ${data.servers.length} сервер(ов)`);
|
||||
} else {
|
||||
serverListContainer.style.display = 'none';
|
||||
emptyServers.style.display = 'block';
|
||||
showMessage('error', data.error || 'Серверы не найдены');
|
||||
}
|
||||
} catch (e) {
|
||||
showMessage('error', `Ошибка сети: ${e.message}`);
|
||||
} finally {
|
||||
setLoading(fetchServersBtn, fetchBtnText, false, 'Загрузить серверы');
|
||||
}
|
||||
});
|
||||
|
||||
// Render server list
|
||||
function renderServerList(servers, savedServerTag = null) {
|
||||
serverList.innerHTML = '';
|
||||
selectedServer = null;
|
||||
|
||||
servers.forEach((server, index) => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'server-item';
|
||||
item.dataset.tag = server.tag;
|
||||
|
||||
item.innerHTML = `
|
||||
<div class="server-radio"></div>
|
||||
<div class="server-info">
|
||||
<div class="server-name">${escapeHtml(server.tag)}</div>
|
||||
<div class="server-details">${escapeHtml(server.server)}:${server.port}</div>
|
||||
</div>
|
||||
<span class="server-type">${server.type}</span>
|
||||
`;
|
||||
|
||||
item.addEventListener('click', () => {
|
||||
document.querySelectorAll('.server-item').forEach(i => i.classList.remove('selected'));
|
||||
item.classList.add('selected');
|
||||
selectedServer = server.tag;
|
||||
});
|
||||
|
||||
// Select saved server or first by default
|
||||
const shouldSelect = savedServerTag
|
||||
? server.tag === savedServerTag
|
||||
: index === 0;
|
||||
|
||||
if (shouldSelect) {
|
||||
item.classList.add('selected');
|
||||
selectedServer = server.tag;
|
||||
}
|
||||
|
||||
serverList.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
// Escape HTML to prevent XSS
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// Apply subscription with selected server
|
||||
applySubBtn.addEventListener('click', async () => {
|
||||
if (!subscriptionConfig) {
|
||||
showMessage('error', 'Сначала загрузите серверы');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedServer) {
|
||||
showMessage('error', 'Выберите сервер');
|
||||
return;
|
||||
}
|
||||
|
||||
message.className = 'message';
|
||||
setLoading(applySubBtn, applySubBtnText, true);
|
||||
|
||||
try {
|
||||
const res = await fetch('/apply-subscription', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
config: subscriptionConfig,
|
||||
selectedServer: selectedServer,
|
||||
subUrl: subscriptionUrl
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (data.success) {
|
||||
showMessage('success', data.message || 'Конфигурация применена!');
|
||||
fetchStatus();
|
||||
} else {
|
||||
showMessage('error', data.error || 'Произошла ошибка');
|
||||
}
|
||||
} catch (e) {
|
||||
showMessage('error', `Ошибка сети: ${e.message}`);
|
||||
} finally {
|
||||
setLoading(applySubBtn, applySubBtnText, false);
|
||||
}
|
||||
});
|
||||
|
||||
// Load saved subscription
|
||||
async function loadSavedSubscription() {
|
||||
try {
|
||||
const res = await fetch('/subscription');
|
||||
const data = await res.json();
|
||||
|
||||
if (data.saved && data.url) {
|
||||
subUrlInput.value = data.url;
|
||||
subscriptionUrl = data.url;
|
||||
|
||||
// Auto-load servers from saved subscription
|
||||
setLoading(fetchServersBtn, fetchBtnText, true, 'Загрузить серверы');
|
||||
try {
|
||||
const subRes = await fetch('/fetch-subscription', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: data.url })
|
||||
});
|
||||
const subData = await subRes.json();
|
||||
|
||||
if (subData.success && subData.servers && subData.servers.length > 0) {
|
||||
subscriptionConfig = subData.config;
|
||||
renderServerList(subData.servers, data.selectedServer);
|
||||
serverListContainer.style.display = 'block';
|
||||
emptyServers.style.display = 'none';
|
||||
}
|
||||
} finally {
|
||||
setLoading(fetchServersBtn, fetchBtnText, false, 'Загрузить серверы');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('No saved subscription found');
|
||||
}
|
||||
}
|
||||
|
||||
// Initial load
|
||||
fetchStatus();
|
||||
loadSavedSubscription();
|
||||
// Refresh status every 30 seconds
|
||||
setInterval(fetchStatus, 30000);
|
||||
|
||||
|
||||
370
web/server.py
370
web/server.py
@@ -1,23 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Simple HTTP Web Server for VPN Proxy Control
|
||||
Provides a web UI to apply VLESS/subscription URLs
|
||||
Provides a web UI to manage sing-box subscriptions
|
||||
"""
|
||||
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import platform
|
||||
import socketserver
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import uuid
|
||||
from urllib.parse import parse_qs
|
||||
from pathlib import Path
|
||||
|
||||
PORT = 3456
|
||||
APP_NAME = "VPN-Proxy-Control by Dokril"
|
||||
APP_DIR = Path(__file__).parent
|
||||
BASE_DIR = APP_DIR.parent
|
||||
WEB_DIR = APP_DIR
|
||||
DATA_DIR = BASE_DIR / "data"
|
||||
CONFIG_FILE = DATA_DIR / "client.json"
|
||||
HWID_FILE = DATA_DIR / "hwid"
|
||||
SUBSCRIPTION_FILE = DATA_DIR / "subscription.json"
|
||||
|
||||
|
||||
def get_hwid() -> str:
|
||||
"""Get or generate hardware ID"""
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if HWID_FILE.exists():
|
||||
return HWID_FILE.read_text().strip()
|
||||
|
||||
# Generate new random HWID
|
||||
hwid = uuid.uuid4().hex[:16]
|
||||
HWID_FILE.write_text(hwid)
|
||||
return hwid
|
||||
|
||||
|
||||
def get_system_info() -> dict:
|
||||
"""Get system information for headers"""
|
||||
system = platform.system().lower() # windows, linux, darwin
|
||||
version = platform.release() # 10, 5.15.0, 22.0.0
|
||||
|
||||
return {
|
||||
"os": system,
|
||||
"version": version
|
||||
}
|
||||
|
||||
|
||||
def save_subscription(url: str, selected_server: str = None):
|
||||
"""Save subscription URL and selected server to file"""
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
data = {
|
||||
"url": url,
|
||||
"selectedServer": selected_server
|
||||
}
|
||||
SUBSCRIPTION_FILE.write_text(json.dumps(data, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
def load_subscription() -> dict:
|
||||
"""Load subscription from file"""
|
||||
if SUBSCRIPTION_FILE.exists():
|
||||
try:
|
||||
return json.loads(SUBSCRIPTION_FILE.read_text())
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def parse_vless_url(url: str) -> dict:
|
||||
"""Parse VLESS URL and extract connection parameters"""
|
||||
from urllib.parse import urlparse, parse_qs, unquote
|
||||
|
||||
if not url.startswith("vless://"):
|
||||
raise ValueError("URL must start with vless://")
|
||||
|
||||
# Remove scheme
|
||||
url_no_scheme = url[8:]
|
||||
|
||||
# Split by fragment (#tag)
|
||||
if '#' in url_no_scheme:
|
||||
url_part, tag = url_no_scheme.split('#', 1)
|
||||
tag = unquote(tag)
|
||||
else:
|
||||
url_part = url_no_scheme
|
||||
tag = "reality"
|
||||
|
||||
# Split by query (?)
|
||||
if '?' in url_part:
|
||||
uuid_host_port, query_string = url_part.split('?', 1)
|
||||
else:
|
||||
raise ValueError("Missing query parameters")
|
||||
|
||||
# Parse UUID@host:port
|
||||
if '@' not in uuid_host_port:
|
||||
raise ValueError("Missing @ separator")
|
||||
|
||||
uuid_str, host_port = uuid_host_port.split('@', 1)
|
||||
|
||||
if ':' not in host_port:
|
||||
raise ValueError("Missing port")
|
||||
|
||||
host, port_str = host_port.rsplit(':', 1)
|
||||
port = int(port_str)
|
||||
|
||||
# Parse query parameters
|
||||
params = {}
|
||||
for param in query_string.split('&'):
|
||||
if '=' in param:
|
||||
key, value = param.split('=', 1)
|
||||
params[key] = unquote(value)
|
||||
|
||||
# Extract required parameters
|
||||
pbk = params.get('pbk', '')
|
||||
sid = params.get('sid', '')
|
||||
sni = params.get('sni', host)
|
||||
fp = params.get('fp', 'chrome')
|
||||
flow = params.get('flow', '')
|
||||
|
||||
if not pbk or not sid:
|
||||
raise ValueError("Missing required parameters: pbk or sid")
|
||||
|
||||
return {
|
||||
'uuid': uuid_str,
|
||||
'server': host,
|
||||
'server_port': port,
|
||||
'tag': tag,
|
||||
'public_key': pbk,
|
||||
'short_id': sid,
|
||||
'server_name': sni,
|
||||
'fingerprint': fp,
|
||||
'flow': flow
|
||||
}
|
||||
|
||||
|
||||
def generate_vless_config(vless_params: dict) -> dict:
|
||||
"""Generate sing-box configuration from VLESS parameters"""
|
||||
config = {
|
||||
"log": {
|
||||
"level": "info",
|
||||
"timestamp": True
|
||||
},
|
||||
"inbounds": [
|
||||
{
|
||||
"type": "mixed",
|
||||
"tag": "mixed-in",
|
||||
"listen": "0.0.0.0",
|
||||
"listen_port": 8082,
|
||||
"sniff": True,
|
||||
"sniff_override_destination": True
|
||||
}
|
||||
],
|
||||
"outbounds": [
|
||||
{
|
||||
"type": "vless",
|
||||
"tag": vless_params['tag'],
|
||||
"server": vless_params['server'],
|
||||
"server_port": vless_params['server_port'],
|
||||
"uuid": vless_params['uuid'],
|
||||
"flow": vless_params['flow'],
|
||||
"tls": {
|
||||
"enabled": True,
|
||||
"server_name": vless_params['server_name'],
|
||||
"utls": {
|
||||
"enabled": True,
|
||||
"fingerprint": vless_params['fingerprint']
|
||||
},
|
||||
"reality": {
|
||||
"enabled": True,
|
||||
"public_key": vless_params['public_key'],
|
||||
"short_id": vless_params['short_id']
|
||||
}
|
||||
},
|
||||
"packet_encoding": "xudp"
|
||||
},
|
||||
{
|
||||
"type": "direct",
|
||||
"tag": "direct"
|
||||
},
|
||||
{
|
||||
"type": "block",
|
||||
"tag": "block"
|
||||
}
|
||||
],
|
||||
"route": {
|
||||
"final": vless_params['tag'],
|
||||
"auto_detect_interface": True
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
|
||||
|
||||
class ProxyControlHandler(http.server.BaseHTTPRequestHandler):
|
||||
@@ -48,6 +222,8 @@ class ProxyControlHandler(http.server.BaseHTTPRequestHandler):
|
||||
self.serve_index()
|
||||
elif self.path == "/status":
|
||||
self.get_status()
|
||||
elif self.path == "/subscription":
|
||||
self.get_subscription()
|
||||
elif self.path.startswith("/static/"):
|
||||
self.serve_static()
|
||||
else:
|
||||
@@ -57,6 +233,10 @@ class ProxyControlHandler(http.server.BaseHTTPRequestHandler):
|
||||
"""Handle POST requests"""
|
||||
if self.path == "/apply":
|
||||
self.apply_config()
|
||||
elif self.path == "/fetch-subscription":
|
||||
self.fetch_subscription()
|
||||
elif self.path == "/apply-subscription":
|
||||
self.apply_subscription()
|
||||
else:
|
||||
self.send_error(404)
|
||||
|
||||
@@ -103,8 +283,20 @@ class ProxyControlHandler(http.server.BaseHTTPRequestHandler):
|
||||
"server": current_server
|
||||
})
|
||||
|
||||
def get_subscription(self):
|
||||
"""Get saved subscription info"""
|
||||
sub = load_subscription()
|
||||
if sub:
|
||||
self.send_json({
|
||||
"saved": True,
|
||||
"url": sub.get("url"),
|
||||
"selectedServer": sub.get("selectedServer")
|
||||
})
|
||||
else:
|
||||
self.send_json({"saved": False})
|
||||
|
||||
def apply_config(self):
|
||||
"""Apply new config from URL"""
|
||||
"""Apply new config from VLESS URL"""
|
||||
try:
|
||||
content_length = int(self.headers.get("Content-Length", 0))
|
||||
body = self.rfile.read(content_length).decode("utf-8")
|
||||
@@ -119,39 +311,173 @@ class ProxyControlHandler(http.server.BaseHTTPRequestHandler):
|
||||
self.send_json({"success": False, "error": "Неверный формат. Поддерживаются только vless:// ссылки"}, 400)
|
||||
return
|
||||
|
||||
# Run gen-client-from-url.sh
|
||||
script_path = BASE_DIR / "gen-client-from-url.sh"
|
||||
result = subprocess.run(
|
||||
[str(script_path), url, str(CONFIG_FILE)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=str(BASE_DIR),
|
||||
timeout=30
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
error_msg = result.stderr or result.stdout or "Неизвестная ошибка"
|
||||
self.send_json({"success": False, "error": f"Ошибка генерации: {error_msg}"}, 500)
|
||||
# Parse VLESS URL
|
||||
try:
|
||||
vless_params = parse_vless_url(url)
|
||||
except ValueError as e:
|
||||
self.send_json({"success": False, "error": f"Ошибка парсинга URL: {str(e)}"}, 400)
|
||||
return
|
||||
|
||||
# Generate config
|
||||
config = generate_vless_config(vless_params)
|
||||
|
||||
# Ensure data directory exists
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Write config file
|
||||
CONFIG_FILE.write_text(json.dumps(config, indent=2, ensure_ascii=False))
|
||||
|
||||
# Trigger reload via internal control port
|
||||
try:
|
||||
import urllib.request
|
||||
urllib.request.urlopen("http://localhost:9090/reload", timeout=5)
|
||||
except Exception as e:
|
||||
print(f"[WebUI] Warning: reload request failed: {e}")
|
||||
# Continue anyway, config is generated
|
||||
|
||||
self.send_json({
|
||||
"success": True,
|
||||
"message": "Конфигурация применена успешно!",
|
||||
"output": result.stdout
|
||||
"message": f"Конфигурация '{vless_params['tag']}' успешно применена!"
|
||||
})
|
||||
|
||||
except json.JSONDecodeError:
|
||||
self.send_json({"success": False, "error": "Неверный JSON"}, 400)
|
||||
except Exception as e:
|
||||
self.send_json({"success": False, "error": str(e)}, 500)
|
||||
|
||||
def fetch_subscription(self):
|
||||
"""Fetch servers list from subscription URL"""
|
||||
try:
|
||||
content_length = int(self.headers.get("Content-Length", 0))
|
||||
body = self.rfile.read(content_length).decode("utf-8")
|
||||
data = json.loads(body)
|
||||
url = data.get("url", "").strip()
|
||||
|
||||
if not url:
|
||||
self.send_json({"success": False, "error": "URL подписки не указан"}, 400)
|
||||
return
|
||||
|
||||
# Fetch subscription config
|
||||
sys_info = get_system_info()
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"User-Agent": "singbox",
|
||||
"x-hwid": get_hwid(),
|
||||
"x-device-os": sys_info["os"],
|
||||
"x-ver-os": sys_info["version"],
|
||||
"x-device-model": APP_NAME
|
||||
}
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as response:
|
||||
config_text = response.read().decode("utf-8")
|
||||
config = json.loads(config_text)
|
||||
except urllib.error.HTTPError as e:
|
||||
self.send_json({"success": False, "error": f"Ошибка HTTP: {e.code}"}, 400)
|
||||
return
|
||||
except urllib.error.URLError as e:
|
||||
self.send_json({"success": False, "error": f"Ошибка подключения: {e.reason}"}, 400)
|
||||
return
|
||||
|
||||
# Extract outbound servers
|
||||
outbounds = config.get("outbounds", [])
|
||||
servers = []
|
||||
|
||||
for outbound in outbounds:
|
||||
if outbound.get("type") in ["vless", "vmess", "trojan", "shadowsocks", "hysteria2"]:
|
||||
servers.append({
|
||||
"tag": outbound.get("tag", "unknown"),
|
||||
"type": outbound.get("type"),
|
||||
"server": outbound.get("server", "unknown"),
|
||||
"port": outbound.get("server_port", 443)
|
||||
})
|
||||
|
||||
if not servers:
|
||||
self.send_json({"success": False, "error": "Серверы не найдены в подписке"}, 400)
|
||||
return
|
||||
|
||||
self.send_json({
|
||||
"success": True,
|
||||
"servers": servers,
|
||||
"config": config
|
||||
})
|
||||
|
||||
except json.JSONDecodeError:
|
||||
self.send_json({"success": False, "error": "Неверный JSON в ответе"}, 400)
|
||||
except Exception as e:
|
||||
self.send_json({"success": False, "error": str(e)}, 500)
|
||||
|
||||
def apply_subscription(self):
|
||||
"""Apply config from subscription with selected server"""
|
||||
try:
|
||||
content_length = int(self.headers.get("Content-Length", 0))
|
||||
body = self.rfile.read(content_length).decode("utf-8")
|
||||
data = json.loads(body)
|
||||
|
||||
config = data.get("config")
|
||||
selected_tag = data.get("selectedServer")
|
||||
sub_url = data.get("subUrl") # URL подписки для сохранения
|
||||
|
||||
if not config:
|
||||
self.send_json({"success": False, "error": "Конфигурация не указана"}, 400)
|
||||
return
|
||||
|
||||
if not selected_tag:
|
||||
self.send_json({"success": False, "error": "Сервер не выбран"}, 400)
|
||||
return
|
||||
|
||||
# Modify config to use only selected server
|
||||
outbounds = config.get("outbounds", [])
|
||||
new_outbounds = []
|
||||
selected_outbound = None
|
||||
|
||||
for outbound in outbounds:
|
||||
if outbound.get("tag") == selected_tag:
|
||||
selected_outbound = outbound
|
||||
elif outbound.get("type") in ["direct", "block", "dns"]:
|
||||
new_outbounds.append(outbound)
|
||||
elif outbound.get("type") == "selector":
|
||||
# Skip selector, we'll add selected server directly
|
||||
pass
|
||||
|
||||
if not selected_outbound:
|
||||
self.send_json({"success": False, "error": f"Сервер '{selected_tag}' не найден"}, 400)
|
||||
return
|
||||
|
||||
# Add selected server as main outbound
|
||||
new_outbounds.insert(0, selected_outbound)
|
||||
|
||||
# Update route rules to use selected server
|
||||
routes = config.get("route", {})
|
||||
final_outbound = selected_tag
|
||||
routes["final"] = final_outbound
|
||||
|
||||
config["outbounds"] = new_outbounds
|
||||
config["route"] = routes
|
||||
|
||||
# Ensure data directory exists
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Write config file
|
||||
CONFIG_FILE.write_text(json.dumps(config, indent=2, ensure_ascii=False))
|
||||
|
||||
# Save subscription URL for persistence
|
||||
if sub_url:
|
||||
save_subscription(sub_url, selected_tag)
|
||||
|
||||
# Trigger reload via internal control port
|
||||
try:
|
||||
urllib.request.urlopen("http://localhost:9090/reload", timeout=5)
|
||||
except Exception as e:
|
||||
print(f"[WebUI] Warning: reload request failed: {e}")
|
||||
|
||||
self.send_json({
|
||||
"success": True,
|
||||
"message": f"Сервер '{selected_tag}' успешно применён!"
|
||||
})
|
||||
|
||||
except json.JSONDecodeError:
|
||||
self.send_json({"success": False, "error": "Неверный JSON"}, 400)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.send_json({"success": False, "error": "Таймаут при генерации конфига"}, 500)
|
||||
except Exception as e:
|
||||
self.send_json({"success": False, "error": str(e)}, 500)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user