feat: добавлены компоненты для управления конфигурацией и логами
Добавлены новые компоненты для отображения и управления конфигурацией, логами и правилами маршрутизации. Реализована логика для работы с API, включая запросы на получение и сохранение данных. Также добавлены шаблоны правил и утилиты для валидации. Refs: None
This commit is contained in:
453
src/web/App.jsx
453
src/web/App.jsx
@@ -1,32 +1,18 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import './styles.css';
|
||||
|
||||
function formatBytes(value) {
|
||||
if (!value) return '0 B';
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
let size = value;
|
||||
let index = 0;
|
||||
while (size >= 1024 && index < units.length - 1) {
|
||||
size /= 1024;
|
||||
index += 1;
|
||||
}
|
||||
return `${size.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
|
||||
}
|
||||
|
||||
function maskUrl(value) {
|
||||
if (!value) return '';
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return `${url.hostname}/...`;
|
||||
} catch {
|
||||
return value.length > 48 ? `${value.slice(0, 48)}...` : value;
|
||||
}
|
||||
}
|
||||
import { api } from './api.js';
|
||||
import { SubscriptionPanel } from './components/SubscriptionPanel.jsx';
|
||||
import { ServerList } from './components/ServerList.jsx';
|
||||
import { RuntimePanel } from './components/RuntimePanel.jsx';
|
||||
import { RulesPanel } from './components/RulesPanel.jsx';
|
||||
import { LogsPanel } from './components/LogsPanel.jsx';
|
||||
import { ConfigViewer } from './components/ConfigViewer.jsx';
|
||||
|
||||
function App() {
|
||||
const [state, setState] = useState(null);
|
||||
const [subscriptionUrl, setSubscriptionUrl] = useState('');
|
||||
const [editingSubscription, setEditingSubscription] = useState(false);
|
||||
const [servers, setServers] = useState([]);
|
||||
const [customRules, setCustomRules] = useState([]);
|
||||
const [selectedTag, setSelectedTag] = useState('');
|
||||
@@ -34,33 +20,22 @@ function App() {
|
||||
const [log, setLog] = useState([]);
|
||||
const [error, setError] = useState('');
|
||||
const [rulesSaveStatus, setRulesSaveStatus] = useState('saved');
|
||||
const [configOpen, setConfigOpen] = useState(false);
|
||||
const rulesDirtyRef = useRef(false);
|
||||
const rulesSaveTimerRef = useRef(null);
|
||||
const rulesRevisionRef = useRef(0);
|
||||
|
||||
const userTraffic = useMemo(() => {
|
||||
const info = state?.userInfo;
|
||||
if (!info) return 'нет данных';
|
||||
const used = formatBytes((info.upload || 0) + (info.download || 0));
|
||||
const total = info.total ? formatBytes(info.total) : 'без лимита';
|
||||
return `${used} / ${total}`;
|
||||
}, [state]);
|
||||
|
||||
function addLog(message) {
|
||||
const time = new Date().toLocaleTimeString('ru-RU', { hour12: false });
|
||||
setLog((items) => [{ time, message }, ...items].slice(0, 8));
|
||||
}
|
||||
|
||||
async function loadState() {
|
||||
const response = await fetch('/api/state');
|
||||
const data = await response.json();
|
||||
const data = await api.state();
|
||||
setState(data);
|
||||
setServers(data.servers || []);
|
||||
if (!rulesDirtyRef.current) {
|
||||
setCustomRules(data.customRules || []);
|
||||
}
|
||||
setSelectedTag(data.selectedTag || '');
|
||||
if (data.subscriptionUrl && !subscriptionUrl) setSubscriptionUrl(data.subscriptionUrl);
|
||||
if (!rulesDirtyRef.current) setCustomRules(data.customRules || []);
|
||||
setSelectedTag((prev) => prev || data.selectedTag || '');
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -69,93 +44,75 @@ function App() {
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (rulesSaveTimerRef.current) clearTimeout(rulesSaveTimerRef.current);
|
||||
};
|
||||
useEffect(() => () => {
|
||||
if (rulesSaveTimerRef.current) clearTimeout(rulesSaveTimerRef.current);
|
||||
}, []);
|
||||
|
||||
async function fetchServers() {
|
||||
async function withBusy(label, fn) {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
addLog(`SYNC ${maskUrl(subscriptionUrl)}`);
|
||||
|
||||
if (label) addLog(label);
|
||||
try {
|
||||
const response = await fetch('/api/subscription/fetch', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ url: subscriptionUrl }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) throw new Error(data.error || 'sync failed');
|
||||
|
||||
setServers(data.servers || []);
|
||||
setSelectedTag(data.servers?.[0]?.tag || '');
|
||||
addLog(`FOUND ${data.servers.length} servers`);
|
||||
await loadState();
|
||||
await fn();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
addLog(`ERROR ${err.message}`);
|
||||
addLog(`ОШИБКА: ${err.message}`);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchServers() {
|
||||
await withBusy('Загрузка подписки', async () => {
|
||||
const data = await api.subscription.fetch(subscriptionUrl);
|
||||
setServers(data.servers || []);
|
||||
setSelectedTag(data.servers?.[0]?.tag || '');
|
||||
addLog(`Найдено серверов: ${data.servers.length}`);
|
||||
await loadState();
|
||||
});
|
||||
}
|
||||
|
||||
async function forgetSubscription() {
|
||||
if (!confirm('Удалить подписку и остановить sing-box?')) return;
|
||||
await withBusy('Удаление подписки', async () => {
|
||||
await api.subscription.forget();
|
||||
setSubscriptionUrl('');
|
||||
setServers([]);
|
||||
setSelectedTag('');
|
||||
setEditingSubscription(true);
|
||||
await loadState();
|
||||
});
|
||||
}
|
||||
|
||||
async function applyServer() {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
addLog(`APPLY ${selectedTag}`);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/apply', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ selectedTag }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) throw new Error(data.error || 'apply failed');
|
||||
|
||||
addLog(`SING-BOX ${data.singboxRunning ? 'RUNNING' : 'STOPPED'}`);
|
||||
await withBusy(`Применяем ${selectedTag}`, async () => {
|
||||
const data = await api.apply(selectedTag);
|
||||
addLog(`sing-box: ${data.singboxRunning ? 'работает' : 'не запущен'}`);
|
||||
await loadState();
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
addLog(`ERROR ${err.message}`);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function emptyRule() {
|
||||
return {
|
||||
id: `rule-${Date.now()}`,
|
||||
name: 'Новый список',
|
||||
enabled: true,
|
||||
outbound: 'direct',
|
||||
domains: [],
|
||||
domainSuffixes: [],
|
||||
domainKeywords: [],
|
||||
ipCidrs: [],
|
||||
ports: [],
|
||||
networks: [],
|
||||
};
|
||||
async function stopSingbox() {
|
||||
if (!confirm('Остановить sing-box? Трафик через шлюз перестанет ходить.')) return;
|
||||
await withBusy('Остановка sing-box', async () => {
|
||||
await api.singbox.stop();
|
||||
await loadState();
|
||||
});
|
||||
}
|
||||
|
||||
function listToText(value) {
|
||||
return Array.isArray(value) ? value.join('\n') : '';
|
||||
async function restartSingbox() {
|
||||
await withBusy('Перезапуск sing-box', async () => {
|
||||
await api.singbox.restart();
|
||||
await loadState();
|
||||
});
|
||||
}
|
||||
|
||||
function textToList(value) {
|
||||
return value
|
||||
.split(/\r?\n|,/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function updateRule(id, patch) {
|
||||
setCustomRules((rules) => {
|
||||
const nextRules = rules.map((rule) => (rule.id === id ? { ...rule, ...patch } : rule));
|
||||
queueRulesSave(nextRules);
|
||||
return nextRules;
|
||||
async function clearConfig() {
|
||||
if (!confirm('Сбросить config sing-box и остановить процесс?')) return;
|
||||
await withBusy('Сброс конфига', async () => {
|
||||
await api.singbox.clear();
|
||||
setSelectedTag('');
|
||||
await loadState();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -175,23 +132,16 @@ function App() {
|
||||
const { silent = false, revision = rulesRevisionRef.current + 1 } = options;
|
||||
if (!silent) setBusy(true);
|
||||
setError('');
|
||||
if (!silent) addLog('SAVE ROUTING RULES');
|
||||
if (!silent) addLog('Сохранение правил');
|
||||
setRulesSaveStatus('saving');
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/rules', {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ rules: nextRules }),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.success) throw new Error(data.error || 'rules save failed');
|
||||
|
||||
const data = await api.rules.save(nextRules);
|
||||
if (rulesRevisionRef.current === revision) {
|
||||
rulesDirtyRef.current = false;
|
||||
setCustomRules(data.rules || []);
|
||||
setRulesSaveStatus('saved');
|
||||
addLog(`RULES SAVED ${data.rules.length}`);
|
||||
addLog(`Правил сохранено: ${data.rules.length}`);
|
||||
await loadState();
|
||||
} else {
|
||||
setRulesSaveStatus('pending');
|
||||
@@ -199,7 +149,7 @@ function App() {
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setRulesSaveStatus('error');
|
||||
addLog(`ERROR ${err.message}`);
|
||||
addLog(`ОШИБКА: ${err.message}`);
|
||||
} finally {
|
||||
if (!silent) setBusy(false);
|
||||
}
|
||||
@@ -213,6 +163,29 @@ function App() {
|
||||
saveRules(customRules, { silent: false, revision });
|
||||
}
|
||||
|
||||
function emptyRule() {
|
||||
return {
|
||||
id: `rule-${Date.now()}`,
|
||||
name: 'Новый список',
|
||||
enabled: true,
|
||||
outbound: 'direct',
|
||||
domains: [],
|
||||
domainSuffixes: [],
|
||||
domainKeywords: [],
|
||||
ipCidrs: [],
|
||||
ports: [],
|
||||
networks: [],
|
||||
};
|
||||
}
|
||||
|
||||
function updateRule(id, patch) {
|
||||
setCustomRules((rules) => {
|
||||
const nextRules = rules.map((rule) => (rule.id === id ? { ...rule, ...patch } : rule));
|
||||
queueRulesSave(nextRules);
|
||||
return nextRules;
|
||||
});
|
||||
}
|
||||
|
||||
function addRule() {
|
||||
setCustomRules((rules) => {
|
||||
const nextRules = [emptyRule(), ...rules];
|
||||
@@ -221,6 +194,14 @@ function App() {
|
||||
});
|
||||
}
|
||||
|
||||
function addRuleFromTemplate(template) {
|
||||
setCustomRules((rules) => {
|
||||
const nextRules = [template, ...rules];
|
||||
queueRulesSave(nextRules);
|
||||
return nextRules;
|
||||
});
|
||||
}
|
||||
|
||||
function removeRule(id) {
|
||||
setCustomRules((rules) => {
|
||||
const nextRules = rules.filter((rule) => rule.id !== id);
|
||||
@@ -229,20 +210,25 @@ function App() {
|
||||
});
|
||||
}
|
||||
|
||||
function reorderRules(nextRules) {
|
||||
setCustomRules(nextRules);
|
||||
queueRulesSave(nextRules);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="shell">
|
||||
<section className="hero panel">
|
||||
<div>
|
||||
<p className="eyebrow">VPN Proxy / Gateway Mode</p>
|
||||
<h1>Transparent gateway for the whole network</h1>
|
||||
<p className="eyebrow">VPN Proxy / Gateway</p>
|
||||
<h1>Прозрачный VPN-шлюз для всей сети</h1>
|
||||
<p className="lead">
|
||||
Вставь subscription URL, выбери outbound, и контейнер сгенерирует gateway-конфиг для sing-box: TProxy для роутера и mixed proxy для ручных клиентов.
|
||||
Загрузи подписку, выбери сервер — контейнер сгенерирует gateway-конфиг для sing-box: TProxy для роутера и mixed proxy для ручных клиентов.
|
||||
</p>
|
||||
</div>
|
||||
<div className="status-card">
|
||||
<span className={state?.singboxRunning ? 'dot on' : 'dot'} />
|
||||
<div>
|
||||
<strong>{state?.singboxRunning ? 'sing-box running' : 'sing-box standby'}</strong>
|
||||
<strong>{state?.singboxRunning ? 'sing-box работает' : 'sing-box остановлен'}</strong>
|
||||
<small>{state?.selectedTag || 'сервер не выбран'}</small>
|
||||
</div>
|
||||
</div>
|
||||
@@ -250,200 +236,53 @@ function App() {
|
||||
|
||||
<section className="grid">
|
||||
<div className="panel primary-flow">
|
||||
<div className="section-title">
|
||||
<span>1</span>
|
||||
<h2>Subscription</h2>
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>Subscription URL</span>
|
||||
<input
|
||||
value={subscriptionUrl}
|
||||
onChange={(event) => setSubscriptionUrl(event.target.value)}
|
||||
placeholder="https://provider.example/sub/..."
|
||||
/>
|
||||
</label>
|
||||
|
||||
<button className="button" disabled={busy || !subscriptionUrl} onClick={fetchServers}>
|
||||
{busy ? 'Working...' : 'Parse subscription'}
|
||||
</button>
|
||||
|
||||
<div className="section-title compact">
|
||||
<span>2</span>
|
||||
<h2>Servers</h2>
|
||||
</div>
|
||||
|
||||
<div className="server-list">
|
||||
{servers.length === 0 && <div className="empty">Серверы еще не загружены</div>}
|
||||
{servers.map((server) => (
|
||||
<button
|
||||
key={server.tag}
|
||||
className={server.tag === selectedTag ? 'server active' : 'server'}
|
||||
onClick={() => setSelectedTag(server.tag)}
|
||||
>
|
||||
<strong>{server.tag}</strong>
|
||||
<small>{server.type} / {server.server}:{server.server_port}</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button className="button apply" disabled={busy || !selectedTag} onClick={applyServer}>
|
||||
Apply selected gateway route
|
||||
</button>
|
||||
|
||||
<SubscriptionPanel
|
||||
subscriptionUrl={subscriptionUrl}
|
||||
setSubscriptionUrl={setSubscriptionUrl}
|
||||
hasSubscription={Boolean(state?.hasSubscription)}
|
||||
subscriptionHost={state?.subscriptionHost}
|
||||
busy={busy}
|
||||
onFetch={fetchServers}
|
||||
onForget={forgetSubscription}
|
||||
editing={editingSubscription || !state?.hasSubscription}
|
||||
setEditing={setEditingSubscription}
|
||||
/>
|
||||
<ServerList
|
||||
servers={servers}
|
||||
selectedTag={selectedTag}
|
||||
setSelectedTag={setSelectedTag}
|
||||
busy={busy}
|
||||
onApply={applyServer}
|
||||
/>
|
||||
{error && <div className="error">{error}</div>}
|
||||
</div>
|
||||
|
||||
<aside className="panel details">
|
||||
<div className="section-title">
|
||||
<span>3</span>
|
||||
<h2>Gateway runtime</h2>
|
||||
</div>
|
||||
|
||||
<dl>
|
||||
<div><dt>UI</dt><dd>:{state?.port || 3456}</dd></div>
|
||||
<div><dt>Mixed proxy</dt><dd>:{state?.proxyPort || 8080}</dd></div>
|
||||
<div><dt>TProxy</dt><dd>:{state?.tproxyPort || 7895}</dd></div>
|
||||
<div><dt>RU direct</dt><dd>{state?.routingRuDirect ? 'enabled' : 'disabled'}</dd></div>
|
||||
<div><dt>Traffic</dt><dd>{userTraffic}</dd></div>
|
||||
</dl>
|
||||
|
||||
<div className="route-card">
|
||||
<span>Routing policy</span>
|
||||
<p>private IP -> direct</p>
|
||||
<p>geoip-ru/geosite-category-ru -> direct</p>
|
||||
<p>everything else -> selected VPN outbound</p>
|
||||
</div>
|
||||
|
||||
<div className="logs">
|
||||
{log.length === 0 && <p>Waiting for actions...</p>}
|
||||
{log.map((entry) => (
|
||||
<p key={`${entry.time}-${entry.message}`}><span>{entry.time}</span> {entry.message}</p>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
<RuntimePanel
|
||||
state={state}
|
||||
log={log}
|
||||
busy={busy}
|
||||
onStop={stopSingbox}
|
||||
onRestart={restartSingbox}
|
||||
onClear={clearConfig}
|
||||
onShowConfig={() => setConfigOpen(true)}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="panel rules-panel">
|
||||
<div className="rules-header">
|
||||
<div className="section-title">
|
||||
<span>4</span>
|
||||
<h2>Routing lists</h2>
|
||||
</div>
|
||||
<div className="rules-actions">
|
||||
<button className="ghost-button" type="button" onClick={addRule}>Add list</button>
|
||||
<button className="ghost-button solid" type="button" disabled={busy || rulesSaveStatus === 'saving'} onClick={saveRulesNow}>
|
||||
{rulesSaveStatus === 'saving' ? 'Saving...' : rulesSaveStatus === 'pending' ? 'Save now' : rulesSaveStatus === 'error' ? 'Retry save' : 'Saved'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<RulesPanel
|
||||
rules={customRules}
|
||||
saveStatus={rulesSaveStatus}
|
||||
busy={busy}
|
||||
onAdd={addRule}
|
||||
onAddTemplate={addRuleFromTemplate}
|
||||
onUpdate={updateRule}
|
||||
onRemove={removeRule}
|
||||
onSaveNow={saveRulesNow}
|
||||
onReorder={reorderRules}
|
||||
/>
|
||||
|
||||
<p className="rules-note">
|
||||
Эти правила автосохраняются после изменений и вставляются после safety private-direct и до стандартного RU-direct. Для игр в gateway-режиме указывай домены, suffix, CIDR или порты: процесс на клиентском ПК gateway не видит.
|
||||
</p>
|
||||
<LogsPanel />
|
||||
|
||||
<div className="rule-grid">
|
||||
{customRules.length === 0 && (
|
||||
<div className="empty rule-empty">
|
||||
Нет пользовательских списков. Добавь список, например `League direct`, и отправь его в `direct`.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{customRules.map((rule) => (
|
||||
<article className="rule-card" key={rule.id}>
|
||||
<div className="rule-top">
|
||||
<input
|
||||
value={rule.name}
|
||||
onChange={(event) => updateRule(rule.id, { name: event.target.value })}
|
||||
placeholder="Название списка"
|
||||
/>
|
||||
<label className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rule.enabled}
|
||||
onChange={(event) => updateRule(rule.id, { enabled: event.target.checked })}
|
||||
/>
|
||||
enabled
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>Route to</span>
|
||||
<select value={rule.outbound} onChange={(event) => updateRule(rule.id, { outbound: event.target.value })}>
|
||||
<option value="direct">direct</option>
|
||||
<option value="vpn">vpn</option>
|
||||
<option value="block">block</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div className="rule-fields">
|
||||
<label className="field">
|
||||
<span>Domains exact</span>
|
||||
<textarea
|
||||
value={listToText(rule.domains)}
|
||||
onChange={(event) => updateRule(rule.id, { domains: textToList(event.target.value) })}
|
||||
placeholder="riotgames.com"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Domain suffixes</span>
|
||||
<textarea
|
||||
value={listToText(rule.domainSuffixes)}
|
||||
onChange={(event) => updateRule(rule.id, { domainSuffixes: textToList(event.target.value) })}
|
||||
placeholder={'leagueoflegends.com\nriotcdn.net'}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>IP CIDR</span>
|
||||
<textarea
|
||||
value={listToText(rule.ipCidrs)}
|
||||
onChange={(event) => updateRule(rule.id, { ipCidrs: textToList(event.target.value) })}
|
||||
placeholder="104.160.128.0/19"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Ports</span>
|
||||
<textarea
|
||||
value={listToText(rule.ports)}
|
||||
onChange={(event) => updateRule(rule.id, { ports: textToList(event.target.value) })}
|
||||
placeholder={'5000\n5223'}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="rule-footer">
|
||||
<label className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(rule.networks || []).includes('tcp')}
|
||||
onChange={(event) => {
|
||||
const set = new Set(rule.networks || []);
|
||||
event.target.checked ? set.add('tcp') : set.delete('tcp');
|
||||
updateRule(rule.id, { networks: Array.from(set) });
|
||||
}}
|
||||
/>
|
||||
tcp
|
||||
</label>
|
||||
<label className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(rule.networks || []).includes('udp')}
|
||||
onChange={(event) => {
|
||||
const set = new Set(rule.networks || []);
|
||||
event.target.checked ? set.add('udp') : set.delete('udp');
|
||||
updateRule(rule.id, { networks: Array.from(set) });
|
||||
}}
|
||||
/>
|
||||
udp
|
||||
</label>
|
||||
<button className="danger-button" type="button" onClick={() => removeRule(rule.id)}>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<ConfigViewer open={configOpen} onClose={() => setConfigOpen(false)} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
33
src/web/api.js
Normal file
33
src/web/api.js
Normal file
@@ -0,0 +1,33 @@
|
||||
async function request(url, options = {}) {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...(options.headers || {}),
|
||||
},
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok || (data && data.success === false)) {
|
||||
throw new Error(data?.error || `Запрос ${url} завершился ошибкой ${response.status}`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
state: () => request('/api/state'),
|
||||
config: () => request('/api/config'),
|
||||
rules: {
|
||||
get: () => request('/api/rules'),
|
||||
save: (rules) => request('/api/rules', { method: 'PUT', body: JSON.stringify({ rules }) }),
|
||||
},
|
||||
subscription: {
|
||||
fetch: (url) => request('/api/subscription/fetch', { method: 'POST', body: JSON.stringify({ url }) }),
|
||||
forget: () => request('/api/subscription', { method: 'DELETE' }),
|
||||
},
|
||||
apply: (selectedTag) => request('/api/apply', { method: 'POST', body: JSON.stringify({ selectedTag }) }),
|
||||
singbox: {
|
||||
stop: () => request('/api/singbox/stop', { method: 'POST' }),
|
||||
restart: () => request('/api/singbox/restart', { method: 'POST' }),
|
||||
clear: () => request('/api/singbox/clear', { method: 'POST' }),
|
||||
},
|
||||
};
|
||||
63
src/web/components/ConfigViewer.jsx
Normal file
63
src/web/components/ConfigViewer.jsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { api } from '../api.js';
|
||||
|
||||
export function ConfigViewer({ open, onClose }) {
|
||||
const [config, setConfig] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let cancelled = false;
|
||||
api
|
||||
.config()
|
||||
.then((data) => {
|
||||
if (!cancelled) setConfig(data.config);
|
||||
})
|
||||
.catch((err) => !cancelled && setError(err.message));
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const text = config ? JSON.stringify(config, null, 2) : '';
|
||||
|
||||
function copy() {
|
||||
navigator.clipboard?.writeText(text).catch(() => {});
|
||||
}
|
||||
|
||||
function download() {
|
||||
const blob = new Blob([text], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'sing-box-config.json';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal" onClick={(event) => event.stopPropagation()}>
|
||||
<div className="modal-header">
|
||||
<h3>Текущий конфиг sing-box</h3>
|
||||
<div className="rules-actions">
|
||||
<button className="ghost-button" type="button" disabled={!config} onClick={copy}>
|
||||
Скопировать
|
||||
</button>
|
||||
<button className="ghost-button" type="button" disabled={!config} onClick={download}>
|
||||
Скачать
|
||||
</button>
|
||||
<button className="ghost-button solid" type="button" onClick={onClose}>
|
||||
Закрыть
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{error && <div className="error">{error}</div>}
|
||||
{!error && !config && <p>Конфиг ещё не сгенерирован.</p>}
|
||||
{config && <pre className="config-view">{text}</pre>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
75
src/web/components/LogsPanel.jsx
Normal file
75
src/web/components/LogsPanel.jsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { formatTime } from '../utils/format.js';
|
||||
|
||||
export function LogsPanel() {
|
||||
const [entries, setEntries] = useState([]);
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [filter, setFilter] = useState('all');
|
||||
const containerRef = useRef(null);
|
||||
const pausedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
pausedRef.current = paused;
|
||||
}, [paused]);
|
||||
|
||||
useEffect(() => {
|
||||
const source = new EventSource('/api/logs/stream');
|
||||
source.onmessage = (event) => {
|
||||
if (pausedRef.current) return;
|
||||
try {
|
||||
const entry = JSON.parse(event.data);
|
||||
setEntries((prev) => {
|
||||
const next = [...prev, entry];
|
||||
if (next.length > 500) next.splice(0, next.length - 500);
|
||||
return next;
|
||||
});
|
||||
} catch {}
|
||||
};
|
||||
source.onerror = () => {
|
||||
// EventSource сам делает реконнект
|
||||
};
|
||||
return () => source.close();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (paused || !containerRef.current) return;
|
||||
containerRef.current.scrollTop = containerRef.current.scrollHeight;
|
||||
}, [entries, paused]);
|
||||
|
||||
const filtered = entries.filter((entry) => filter === 'all' || entry.level === filter);
|
||||
|
||||
return (
|
||||
<section className="panel logs-panel">
|
||||
<div className="rules-header">
|
||||
<div className="section-title">
|
||||
<span>5</span>
|
||||
<h2>Логи sing-box</h2>
|
||||
</div>
|
||||
<div className="rules-actions">
|
||||
<select value={filter} onChange={(event) => setFilter(event.target.value)}>
|
||||
<option value="all">все уровни</option>
|
||||
<option value="info">info</option>
|
||||
<option value="error">error</option>
|
||||
</select>
|
||||
<button className="ghost-button" type="button" onClick={() => setPaused((p) => !p)}>
|
||||
{paused ? 'Возобновить' : 'Пауза'}
|
||||
</button>
|
||||
<button className="ghost-button" type="button" onClick={() => setEntries([])}>
|
||||
Очистить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref={containerRef} className="logs-stream">
|
||||
{filtered.length === 0 && <p className="empty">Логов пока нет.</p>}
|
||||
{filtered.map((entry, index) => (
|
||||
<p key={`${entry.ts}-${index}`} className={`log-line log-${entry.level}`}>
|
||||
<span className="log-time">{formatTime(entry.ts)}</span>
|
||||
<span className="log-level">{entry.level}</span>
|
||||
<span className="log-text">{entry.line}</span>
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
127
src/web/components/RuleCard.jsx
Normal file
127
src/web/components/RuleCard.jsx
Normal file
@@ -0,0 +1,127 @@
|
||||
import React from 'react';
|
||||
import { useSortable } from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { ruleErrors, hasErrors } from '../utils/validation.js';
|
||||
|
||||
function listToText(value) {
|
||||
return Array.isArray(value) ? value.join('\n') : '';
|
||||
}
|
||||
|
||||
function textToList(value) {
|
||||
return value
|
||||
.split(/\r?\n|,/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
export function RuleCard({ rule, index, total, onUpdate, onRemove }) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: rule.id });
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.6 : 1,
|
||||
};
|
||||
const errors = ruleErrors(rule);
|
||||
const errored = hasErrors(errors);
|
||||
|
||||
return (
|
||||
<article ref={setNodeRef} style={style} className={errored ? 'rule-card invalid' : 'rule-card'}>
|
||||
<div className="rule-top">
|
||||
<span className="drag-handle" {...attributes} {...listeners} title="Перетащить">
|
||||
⠿ #{index + 1}/{total}
|
||||
</span>
|
||||
<input
|
||||
value={rule.name}
|
||||
onChange={(event) => onUpdate(rule.id, { name: event.target.value })}
|
||||
placeholder="Название списка"
|
||||
/>
|
||||
<label className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rule.enabled}
|
||||
onChange={(event) => onUpdate(rule.id, { enabled: event.target.checked })}
|
||||
/>
|
||||
включено
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>Outbound</span>
|
||||
<select value={rule.outbound} onChange={(event) => onUpdate(rule.id, { outbound: event.target.value })}>
|
||||
<option value="direct">direct (напрямую)</option>
|
||||
<option value="vpn">vpn (через выбранный сервер)</option>
|
||||
<option value="block">block (заблокировать)</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div className="rule-fields">
|
||||
<label className={errors.domains.length ? 'field has-error' : 'field'}>
|
||||
<span>Домены (точное совпадение)</span>
|
||||
<textarea
|
||||
value={listToText(rule.domains)}
|
||||
onChange={(event) => onUpdate(rule.id, { domains: textToList(event.target.value) })}
|
||||
placeholder="riotgames.com"
|
||||
/>
|
||||
{errors.domains.length > 0 && <small className="error">Невалидно: {errors.domains.join(', ')}</small>}
|
||||
</label>
|
||||
<label className={errors.domainSuffixes.length ? 'field has-error' : 'field'}>
|
||||
<span>Суффиксы доменов</span>
|
||||
<textarea
|
||||
value={listToText(rule.domainSuffixes)}
|
||||
onChange={(event) => onUpdate(rule.id, { domainSuffixes: textToList(event.target.value) })}
|
||||
placeholder={'leagueoflegends.com\nriotcdn.net'}
|
||||
/>
|
||||
{errors.domainSuffixes.length > 0 && <small className="error">Невалидно: {errors.domainSuffixes.join(', ')}</small>}
|
||||
</label>
|
||||
<label className={errors.ipCidrs.length ? 'field has-error' : 'field'}>
|
||||
<span>IP CIDR</span>
|
||||
<textarea
|
||||
value={listToText(rule.ipCidrs)}
|
||||
onChange={(event) => onUpdate(rule.id, { ipCidrs: textToList(event.target.value) })}
|
||||
placeholder="104.160.128.0/19"
|
||||
/>
|
||||
{errors.ipCidrs.length > 0 && <small className="error">Невалидно: {errors.ipCidrs.join(', ')}</small>}
|
||||
</label>
|
||||
<label className={errors.ports.length ? 'field has-error' : 'field'}>
|
||||
<span>Порты</span>
|
||||
<textarea
|
||||
value={listToText(rule.ports)}
|
||||
onChange={(event) => onUpdate(rule.id, { ports: textToList(event.target.value) })}
|
||||
placeholder={'5000\n5223'}
|
||||
/>
|
||||
{errors.ports.length > 0 && <small className="error">Невалидно: {errors.ports.join(', ')}</small>}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="rule-footer">
|
||||
<label className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(rule.networks || []).includes('tcp')}
|
||||
onChange={(event) => {
|
||||
const set = new Set(rule.networks || []);
|
||||
event.target.checked ? set.add('tcp') : set.delete('tcp');
|
||||
onUpdate(rule.id, { networks: Array.from(set) });
|
||||
}}
|
||||
/>
|
||||
tcp
|
||||
</label>
|
||||
<label className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(rule.networks || []).includes('udp')}
|
||||
onChange={(event) => {
|
||||
const set = new Set(rule.networks || []);
|
||||
event.target.checked ? set.add('udp') : set.delete('udp');
|
||||
onUpdate(rule.id, { networks: Array.from(set) });
|
||||
}}
|
||||
/>
|
||||
udp
|
||||
</label>
|
||||
<button className="danger-button" type="button" onClick={() => onRemove(rule.id)}>
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
112
src/web/components/RulesPanel.jsx
Normal file
112
src/web/components/RulesPanel.jsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
arrayMove,
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { RuleCard } from './RuleCard.jsx';
|
||||
import { ruleTemplates } from '../templates/ruleTemplates.js';
|
||||
|
||||
export function RulesPanel({ rules, saveStatus, busy, onAdd, onAddTemplate, onUpdate, onRemove, onSaveNow, onReorder }) {
|
||||
const [templateKey, setTemplateKey] = useState('');
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
);
|
||||
|
||||
function handleDragEnd(event) {
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) return;
|
||||
const oldIndex = rules.findIndex((rule) => rule.id === active.id);
|
||||
const newIndex = rules.findIndex((rule) => rule.id === over.id);
|
||||
if (oldIndex < 0 || newIndex < 0) return;
|
||||
onReorder(arrayMove(rules, oldIndex, newIndex));
|
||||
}
|
||||
|
||||
function handleAddTemplate() {
|
||||
const tpl = ruleTemplates.find((t) => t.key === templateKey);
|
||||
if (!tpl) return;
|
||||
onAddTemplate(tpl.build());
|
||||
setTemplateKey('');
|
||||
}
|
||||
|
||||
const saveLabel =
|
||||
saveStatus === 'saving'
|
||||
? 'Сохраняем…'
|
||||
: saveStatus === 'pending'
|
||||
? 'Сохранить сейчас'
|
||||
: saveStatus === 'error'
|
||||
? 'Повторить сохранение'
|
||||
: 'Сохранено';
|
||||
|
||||
return (
|
||||
<section className="panel rules-panel">
|
||||
<div className="rules-header">
|
||||
<div className="section-title">
|
||||
<span>4</span>
|
||||
<h2>Правила маршрутизации</h2>
|
||||
</div>
|
||||
<div className="rules-actions">
|
||||
<select value={templateKey} onChange={(event) => setTemplateKey(event.target.value)}>
|
||||
<option value="">Шаблон…</option>
|
||||
{ruleTemplates.map((tpl) => (
|
||||
<option key={tpl.key} value={tpl.key}>
|
||||
{tpl.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="ghost-button" type="button" disabled={!templateKey} onClick={handleAddTemplate}>
|
||||
Добавить шаблон
|
||||
</button>
|
||||
<button className="ghost-button" type="button" onClick={onAdd}>
|
||||
Пустое правило
|
||||
</button>
|
||||
<button
|
||||
className="ghost-button solid"
|
||||
type="button"
|
||||
disabled={busy || saveStatus === 'saving'}
|
||||
onClick={onSaveNow}
|
||||
>
|
||||
{saveLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="rules-note">
|
||||
Правила применяются <strong>сверху вниз</strong> (first match wins). Перетаскивай за «⠿» чтобы менять порядок.
|
||||
Они вставляются после safety private-direct и до RU-direct. Для игр указывай домены, суффиксы, CIDR или порты.
|
||||
</p>
|
||||
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
||||
<SortableContext items={rules.map((r) => r.id)} strategy={verticalListSortingStrategy}>
|
||||
<div className="rule-grid">
|
||||
{rules.length === 0 && (
|
||||
<div className="empty rule-empty">
|
||||
Нет правил. Добавь шаблон (например «League of Legends → direct») или пустое правило.
|
||||
</div>
|
||||
)}
|
||||
{rules.map((rule, index) => (
|
||||
<RuleCard
|
||||
key={rule.id}
|
||||
rule={rule}
|
||||
index={index}
|
||||
total={rules.length}
|
||||
onUpdate={onUpdate}
|
||||
onRemove={onRemove}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
86
src/web/components/RuntimePanel.jsx
Normal file
86
src/web/components/RuntimePanel.jsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import React from 'react';
|
||||
import { formatBytes, formatRelative } from '../utils/format.js';
|
||||
|
||||
export function RuntimePanel({ state, log, busy, onStop, onRestart, onClear, onShowConfig }) {
|
||||
const userInfo = state?.userInfo;
|
||||
const traffic = userInfo
|
||||
? `${formatBytes((userInfo.upload || 0) + (userInfo.download || 0))} / ${
|
||||
userInfo.total ? formatBytes(userInfo.total) : 'без лимита'
|
||||
}`
|
||||
: 'нет данных';
|
||||
|
||||
return (
|
||||
<aside className="panel details">
|
||||
<div className="section-title">
|
||||
<span>3</span>
|
||||
<h2>Шлюз</h2>
|
||||
</div>
|
||||
|
||||
<dl>
|
||||
<div>
|
||||
<dt>UI</dt>
|
||||
<dd>:{state?.port || 3456}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Mixed proxy</dt>
|
||||
<dd>:{state?.proxyPort || 8080}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>TProxy</dt>
|
||||
<dd>:{state?.tproxyPort || 7895}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>RU direct</dt>
|
||||
<dd>{state?.routingRuDirect ? 'включено' : 'выключено'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Трафик</dt>
|
||||
<dd>{traffic}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>sing-box</dt>
|
||||
<dd>
|
||||
{state?.singboxRunning
|
||||
? `работает${state.singboxStartedAt ? ` (${formatRelative(state.singboxStartedAt)})` : ''}`
|
||||
: 'остановлен'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Применено</dt>
|
||||
<dd>{state?.appliedAt ? formatRelative(state.appliedAt) : 'не применено'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div className="runtime-actions">
|
||||
<button className="ghost-button" type="button" disabled={busy || !state?.singboxRunning} onClick={onStop}>
|
||||
Остановить
|
||||
</button>
|
||||
<button className="ghost-button" type="button" disabled={busy || !state?.configExists} onClick={onRestart}>
|
||||
Перезапустить
|
||||
</button>
|
||||
<button className="ghost-button" type="button" disabled={busy || !state?.configExists} onClick={onClear}>
|
||||
Сбросить конфиг
|
||||
</button>
|
||||
<button className="ghost-button" type="button" disabled={!state?.configExists} onClick={onShowConfig}>
|
||||
Показать config
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="route-card">
|
||||
<span>Политика роутинга</span>
|
||||
<p>private IP → direct</p>
|
||||
<p>geoip-ru / geosite-category-ru → direct</p>
|
||||
<p>остальное → выбранный VPN outbound</p>
|
||||
</div>
|
||||
|
||||
<div className="logs">
|
||||
{log.length === 0 && <p>Ожидание действий…</p>}
|
||||
{log.map((entry, index) => (
|
||||
<p key={`${entry.time}-${index}`}>
|
||||
<span>{entry.time}</span> {entry.message}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
32
src/web/components/ServerList.jsx
Normal file
32
src/web/components/ServerList.jsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import React from 'react';
|
||||
|
||||
export function ServerList({ servers, selectedTag, setSelectedTag, busy, onApply }) {
|
||||
return (
|
||||
<div className="primary-block">
|
||||
<div className="section-title compact">
|
||||
<span>2</span>
|
||||
<h2>Серверы</h2>
|
||||
</div>
|
||||
|
||||
<div className="server-list">
|
||||
{servers.length === 0 && <div className="empty">Серверы ещё не загружены</div>}
|
||||
{servers.map((server) => (
|
||||
<button
|
||||
key={server.tag}
|
||||
className={server.tag === selectedTag ? 'server active' : 'server'}
|
||||
onClick={() => setSelectedTag(server.tag)}
|
||||
>
|
||||
<strong>{server.tag}</strong>
|
||||
<small>
|
||||
{server.type} / {server.server}:{server.server_port}
|
||||
</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button className="button apply" disabled={busy || !selectedTag} onClick={onApply}>
|
||||
Применить выбранный сервер
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
58
src/web/components/SubscriptionPanel.jsx
Normal file
58
src/web/components/SubscriptionPanel.jsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import React from 'react';
|
||||
|
||||
export function SubscriptionPanel({
|
||||
subscriptionUrl,
|
||||
setSubscriptionUrl,
|
||||
hasSubscription,
|
||||
subscriptionHost,
|
||||
busy,
|
||||
onFetch,
|
||||
onForget,
|
||||
editing,
|
||||
setEditing,
|
||||
}) {
|
||||
const masked = hasSubscription && !editing;
|
||||
|
||||
return (
|
||||
<div className="primary-block">
|
||||
<div className="section-title">
|
||||
<span>1</span>
|
||||
<h2>Подписка</h2>
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>Subscription URL</span>
|
||||
{masked ? (
|
||||
<div className="masked-row">
|
||||
<code className="masked">{subscriptionHost}</code>
|
||||
<button className="ghost-button" type="button" onClick={() => setEditing(true)}>
|
||||
Изменить
|
||||
</button>
|
||||
<button className="danger-button" type="button" disabled={busy} onClick={onForget}>
|
||||
Забыть
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<input
|
||||
value={subscriptionUrl}
|
||||
onChange={(event) => setSubscriptionUrl(event.target.value)}
|
||||
placeholder="https://provider.example/sub/..."
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
|
||||
{!masked && (
|
||||
<button
|
||||
className="button"
|
||||
disabled={busy || !subscriptionUrl}
|
||||
onClick={() => {
|
||||
onFetch();
|
||||
setEditing(false);
|
||||
}}
|
||||
>
|
||||
{busy ? 'Загрузка…' : 'Загрузить серверы'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -438,3 +438,93 @@ dd {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
/* Дополнения для новых компонентов */
|
||||
.primary-block { display: flex; flex-direction: column; gap: 12px; }
|
||||
.masked-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.masked-row .masked {
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
border-radius: 10px;
|
||||
background: rgba(255,255,255,0.04);
|
||||
font-family: 'Space Grotesk', monospace;
|
||||
color: var(--muted);
|
||||
}
|
||||
.runtime-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.runtime-actions button { flex: 1 1 auto; }
|
||||
|
||||
.rule-card.invalid { border-color: rgba(255, 107, 107, 0.55); }
|
||||
.field.has-error textarea, .field.has-error input { border-color: var(--red); }
|
||||
.field small.error { color: var(--red); margin-top: 4px; display: block; }
|
||||
.drag-handle {
|
||||
cursor: grab;
|
||||
user-select: none;
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
background: rgba(255,255,255,0.05);
|
||||
color: var(--muted);
|
||||
font-family: 'Space Grotesk', monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
.drag-handle:active { cursor: grabbing; }
|
||||
|
||||
.logs-panel .logs-stream {
|
||||
max-height: 360px;
|
||||
overflow-y: auto;
|
||||
background: rgba(0,0,0,0.35);
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
font-family: 'Space Grotesk', monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.log-line { display: flex; gap: 10px; margin: 0 0 2px; }
|
||||
.log-time { color: var(--muted); flex: 0 0 auto; }
|
||||
.log-level { color: var(--amber); flex: 0 0 50px; text-transform: uppercase; font-size: 10px; padding-top: 2px; }
|
||||
.log-error .log-level { color: var(--red); }
|
||||
.log-text { flex: 1; word-break: break-all; }
|
||||
|
||||
.modal-backdrop {
|
||||
position: fixed; inset: 0;
|
||||
background: rgba(3, 8, 6, 0.7);
|
||||
backdrop-filter: blur(6px);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
z-index: 100;
|
||||
padding: 24px;
|
||||
}
|
||||
.modal {
|
||||
background: var(--panel-strong);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 24px;
|
||||
box-shadow: var(--shadow);
|
||||
width: min(900px, 100%);
|
||||
max-height: 90vh;
|
||||
display: flex; flex-direction: column;
|
||||
padding: 24px;
|
||||
gap: 16px;
|
||||
}
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.modal-header h3 { margin: 0; font-family: 'Space Grotesk', sans-serif; }
|
||||
.config-view {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
background: rgba(0,0,0,0.4);
|
||||
padding: 16px;
|
||||
border-radius: 14px;
|
||||
font-family: 'Space Grotesk', monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
85
src/web/templates/ruleTemplates.js
Normal file
85
src/web/templates/ruleTemplates.js
Normal file
@@ -0,0 +1,85 @@
|
||||
// Готовые шаблоны правил роутинга. domains/suffixes/cidr/ports собраны из публичных
|
||||
// reference-конфигов sing-box. Это пресеты «на старт», а не исчерпывающие списки.
|
||||
|
||||
let counter = 0;
|
||||
function id(prefix) {
|
||||
counter += 1;
|
||||
return `${prefix}-${Date.now()}-${counter}`;
|
||||
}
|
||||
|
||||
function template(name, outbound, fields) {
|
||||
return {
|
||||
id: id('tpl'),
|
||||
name,
|
||||
enabled: true,
|
||||
outbound,
|
||||
domains: [],
|
||||
domainSuffixes: [],
|
||||
domainKeywords: [],
|
||||
ipCidrs: [],
|
||||
ports: [],
|
||||
networks: [],
|
||||
...fields,
|
||||
};
|
||||
}
|
||||
|
||||
export const ruleTemplates = [
|
||||
{
|
||||
key: 'lol-direct',
|
||||
label: 'League of Legends → direct',
|
||||
description: 'Riot/LoL домены и порты — играть напрямую без VPN.',
|
||||
build: () =>
|
||||
template('League of Legends', 'direct', {
|
||||
domainSuffixes: ['leagueoflegends.com', 'riotgames.com', 'riotcdn.net', 'dyn.riotcdn.net'],
|
||||
ports: ['5000', '5223', '5222', '8088'],
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: 'discord-direct',
|
||||
label: 'Discord/Vesktop → direct',
|
||||
description: 'Discord voice/video и WebSocket напрямую.',
|
||||
build: () =>
|
||||
template('Discord', 'direct', {
|
||||
domainSuffixes: ['discord.com', 'discord.gg', 'discord.media', 'discordapp.com', 'discordapp.net'],
|
||||
ports: ['50000-65535'],
|
||||
networks: ['udp'],
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: 'telegram-vpn',
|
||||
label: 'Telegram → VPN',
|
||||
description: 'Telegram через выбранный VPN outbound.',
|
||||
build: () =>
|
||||
template('Telegram', 'vpn', {
|
||||
domainSuffixes: ['telegram.org', 't.me', 'telegram.me', 'telegra.ph', 'tdesktop.com'],
|
||||
ipCidrs: ['149.154.160.0/20', '91.108.4.0/22', '91.108.8.0/22', '91.108.12.0/22', '91.108.16.0/22', '91.108.56.0/22'],
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: 'youtube-vpn',
|
||||
label: 'YouTube → VPN',
|
||||
description: 'YouTube/Google Video через VPN.',
|
||||
build: () =>
|
||||
template('YouTube', 'vpn', {
|
||||
domainSuffixes: ['youtube.com', 'youtu.be', 'ytimg.com', 'googlevideo.com', 'youtube-nocookie.com'],
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: 'steam-direct',
|
||||
label: 'Steam → direct',
|
||||
description: 'Загрузка/обновления Steam напрямую.',
|
||||
build: () =>
|
||||
template('Steam', 'direct', {
|
||||
domainSuffixes: ['steampowered.com', 'steamcontent.com', 'steamcommunity.com', 'steamserver.net', 'cm.steampowered.com'],
|
||||
}),
|
||||
},
|
||||
{
|
||||
key: 'ads-block',
|
||||
label: 'Реклама → block',
|
||||
description: 'Базовый набор рекламных доменов — заблокировать.',
|
||||
build: () =>
|
||||
template('Реклама (block)', 'block', {
|
||||
domainSuffixes: ['doubleclick.net', 'googlesyndication.com', 'googleadservices.com', 'adservice.google.com', 'adnxs.com'],
|
||||
}),
|
||||
},
|
||||
];
|
||||
31
src/web/utils/format.js
Normal file
31
src/web/utils/format.js
Normal file
@@ -0,0 +1,31 @@
|
||||
export function formatBytes(value) {
|
||||
if (!value) return '0 Б';
|
||||
const units = ['Б', 'КБ', 'МБ', 'ГБ', 'ТБ'];
|
||||
let size = value;
|
||||
let index = 0;
|
||||
while (size >= 1024 && index < units.length - 1) {
|
||||
size /= 1024;
|
||||
index += 1;
|
||||
}
|
||||
return `${size.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
|
||||
}
|
||||
|
||||
export function formatRelative(iso) {
|
||||
if (!iso) return '';
|
||||
const ts = new Date(iso).getTime();
|
||||
if (Number.isNaN(ts)) return '';
|
||||
const diff = Math.max(0, Date.now() - ts);
|
||||
const sec = Math.floor(diff / 1000);
|
||||
if (sec < 60) return `${sec} с назад`;
|
||||
const min = Math.floor(sec / 60);
|
||||
if (min < 60) return `${min} мин назад`;
|
||||
const hr = Math.floor(min / 60);
|
||||
if (hr < 24) return `${hr} ч назад`;
|
||||
const days = Math.floor(hr / 24);
|
||||
return `${days} дн назад`;
|
||||
}
|
||||
|
||||
export function formatTime(iso) {
|
||||
if (!iso) return '';
|
||||
return new Date(iso).toLocaleTimeString('ru-RU', { hour12: false });
|
||||
}
|
||||
54
src/web/utils/validation.js
Normal file
54
src/web/utils/validation.js
Normal file
@@ -0,0 +1,54 @@
|
||||
// Простые валидаторы для полей правил роутинга. Возвращают массив ошибочных строк.
|
||||
|
||||
const IPV4 = /^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$/;
|
||||
const IPV6 = /^[0-9a-f:]+$/i;
|
||||
const DOMAIN = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;
|
||||
|
||||
export function invalidCidrs(values) {
|
||||
return (values || []).filter((value) => !isValidCidr(value));
|
||||
}
|
||||
|
||||
export function isValidCidr(value) {
|
||||
const trimmed = String(value || '').trim();
|
||||
if (!trimmed) return false;
|
||||
const [addr, mask] = trimmed.split('/');
|
||||
if (!addr) return false;
|
||||
|
||||
if (IPV4.test(addr)) {
|
||||
if (mask === undefined) return true;
|
||||
const m = Number(mask);
|
||||
return Number.isInteger(m) && m >= 0 && m <= 32;
|
||||
}
|
||||
if (IPV6.test(addr) && addr.includes(':')) {
|
||||
if (mask === undefined) return true;
|
||||
const m = Number(mask);
|
||||
return Number.isInteger(m) && m >= 0 && m <= 128;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function invalidPorts(values) {
|
||||
return (values || []).filter((value) => !isValidPort(value));
|
||||
}
|
||||
|
||||
export function isValidPort(value) {
|
||||
const n = Number.parseInt(String(value).trim(), 10);
|
||||
return Number.isInteger(n) && n > 0 && n <= 65535;
|
||||
}
|
||||
|
||||
export function invalidDomains(values) {
|
||||
return (values || []).filter((value) => !DOMAIN.test(String(value).trim()));
|
||||
}
|
||||
|
||||
export function ruleErrors(rule) {
|
||||
return {
|
||||
domains: invalidDomains(rule.domains),
|
||||
domainSuffixes: invalidDomains(rule.domainSuffixes),
|
||||
ipCidrs: invalidCidrs(rule.ipCidrs),
|
||||
ports: invalidPorts(rule.ports),
|
||||
};
|
||||
}
|
||||
|
||||
export function hasErrors(errors) {
|
||||
return Object.values(errors).some((arr) => arr.length > 0);
|
||||
}
|
||||
Reference in New Issue
Block a user