Firewall added & some fixes

This commit is contained in:
MoonDev
2026-04-13 12:40:49 +03:00
parent 7eaa9750b0
commit 8c35022483
22 changed files with 1659 additions and 134 deletions

View File

@@ -5,7 +5,8 @@
const state = {
interfaces: [], // latest data from /api/interfaces
pending: [], // interface names with pending config
configModal: null, // name of interface being configured
configModal: null, // name of interface being configured (null = new VLAN)
configModalParent: null, // parent interface when creating a new VLAN
nat: null, // {installed, interfaces} from /api/nat
};
@@ -29,6 +30,19 @@ const get = (path) => api('GET', path);
const post = (path, body) => api('POST', path, body);
const del = (path) => api('DELETE', path);
// ── VLAN helpers ─────────────────────────────────────────────────────────────
function isVLAN(name) {
return /\.\d+$/.test(name);
}
function vlanParent(name) {
return name.replace(/\.\d+$/, '');
}
function vlanId(name) {
const m = name.match(/\.(\d+)$/);
return m ? parseInt(m[1]) : 0;
}
// ── Format helpers ───────────────────────────────────────────────────────────
function fmtBytes(n) {
@@ -56,9 +70,24 @@ function renderAll() {
const grid = document.getElementById('ifaceGrid');
grid.innerHTML = '';
state.interfaces.forEach(iface => {
grid.appendChild(buildCard(iface));
});
// Group VLANs by parent
const vlansByParent = {};
const physicals = [];
for (const iface of state.interfaces) {
if (isVLAN(iface.name)) {
const p = vlanParent(iface.name);
if (!vlansByParent[p]) vlansByParent[p] = [];
vlansByParent[p].push(iface);
} else {
physicals.push(iface);
}
}
for (const iface of physicals) {
const vlans = vlansByParent[iface.name] || [];
grid.appendChild(buildCard(iface, vlans));
}
document.getElementById('loading').classList.add('hidden');
grid.classList.remove('hidden');
@@ -66,9 +95,10 @@ function renderAll() {
renderPendingBanner();
}
function buildCard(iface) {
function buildCard(iface, vlans) {
const hasPending = state.pending.includes(iface.name);
const sc = stateClass(iface.state);
const isLo = iface.name === 'lo' || iface.mode === 'loopback';
const card = document.createElement('div');
card.className = 'iface-card' + (hasPending ? ' has-pending' : '');
@@ -129,11 +159,56 @@ function buildCard(iface) {
<button class="btn btn-ghost btn-sm" data-action="restart" data-iface="${iface.name}">RESTART</button>
<button class="btn btn-primary btn-sm" data-action="config" data-iface="${iface.name}" style="margin-left:auto">CONFIG</button>
</div>
${!isLo ? buildVLANSection(iface.name, vlans) : ''}
`;
return card;
}
function buildVLANSection(parentName, vlans) {
const rows = vlans.map(v => {
const sc = stateClass(v.state);
const hasPending = state.pending.includes(v.name);
const ip = v.ipv4
? v.ipv4 + (v.ipv4_mask ? ' / ' + v.ipv4_mask : '')
: '<span class="none">&mdash;</span>';
return `
<div class="vlan-row" data-name="${v.name}">
<div class="vlan-row-left">
<span class="state-dot ${sc}" style="width:8px;height:8px"></span>
<span class="vlan-iface-name">${v.name}</span>
<span class="vlan-id-tag">VLAN ${vlanId(v.name)}</span>
<span class="mode-badge ${v.mode || 'unknown'}">${modeLabel(v.mode)}</span>
${hasPending ? '<span class="pending-badge">несохранено</span>' : ''}
</div>
<div class="vlan-row-info">${ip}</div>
<div class="vlan-row-actions">
<button class="btn btn-success btn-xs" data-action="up" data-iface="${v.name}">ON</button>
<button class="btn btn-danger btn-xs" data-action="down" data-iface="${v.name}">OFF</button>
<button class="btn btn-primary btn-xs" data-action="config" data-iface="${v.name}">CONFIG</button>
<button class="btn btn-danger btn-xs" data-action="delete" data-iface="${v.name}" title="Удалить VLAN">✕</button>
</div>
</div>`;
}).join('');
const empty = vlans.length === 0
? `<div class="vlan-empty">Нет тегированных VLAN</div>`
: '';
return `
<div class="vlan-section">
<div class="vlan-header">
<span class="vlan-title">Теговые VLAN</span>
<button class="btn btn-ghost btn-xs" data-action="addvlan" data-iface="${parentName}">+ Добавить</button>
</div>
<div class="vlan-list">
${rows}
${empty}
</div>
</div>`;
}
function renderPendingBanner() {
const banner = document.getElementById('pendingBanner');
const list = document.getElementById('pendingList');
@@ -164,6 +239,18 @@ async function loadAll() {
// ── Interface actions ─────────────────────────────────────────────────────────
async function doAction(name, action) {
if (action === 'delete') {
if (!confirm(`Удалить VLAN ${name}?`)) return;
try {
await post(`/api/interfaces/${name}/delete`);
showToast(`${name}: удалён`, 'success');
await loadAll();
} catch (e) {
showToast(`${name} delete: ${e.message}`, 'error');
}
return;
}
const btn = document.querySelector(`[data-action="${action}"][data-iface="${name}"]`);
if (btn) { btn.disabled = true; btn.textContent = '...'; }
@@ -182,8 +269,21 @@ async function doAction(name, action) {
async function openConfig(name) {
state.configModal = name;
state.configModalParent = null;
document.getElementById('modalTitle').textContent = `Настройка: ${name}`;
// Show/hide VLAN ID field
const vlanSection = document.getElementById('vlanIdSection');
const vlanInput = document.getElementById('cfgVLANId');
if (isVLAN(name)) {
vlanSection.classList.remove('hidden');
vlanInput.value = vlanId(name);
vlanInput.readOnly = true;
} else {
vlanSection.classList.add('hidden');
vlanInput.readOnly = false;
}
try {
const [{ config, pending }, natData] = await Promise.all([
get(`/api/config/${name}`),
@@ -197,6 +297,26 @@ async function openConfig(name) {
}
}
async function openNewVLAN(parentName) {
state.configModal = null;
state.configModalParent = parentName;
document.getElementById('modalTitle').textContent = `Новый VLAN на ${parentName}`;
const vlanSection = document.getElementById('vlanIdSection');
const vlanInput = document.getElementById('cfgVLANId');
vlanSection.classList.remove('hidden');
vlanInput.readOnly = false;
vlanInput.value = '';
try {
const natData = await get('/api/nat').catch(() => null);
if (natData) state.nat = natData;
} catch (_) {}
fillForm({ auto: true, mode: 'static' }, false, '');
document.getElementById('modal').classList.remove('hidden');
}
function fillForm(cfg, pending, name) {
document.getElementById('cfgAuto').checked = !!cfg.auto;
document.getElementById('cfgAddress').value = cfg.address || '';
@@ -208,9 +328,8 @@ function fillForm(cfg, pending, name) {
setMode(mode);
// Mark pending visually
const title = document.getElementById('modalTitle');
if (pending) {
title.textContent = `Настройка: ${state.configModal} (несохранённые изменения)`;
if (pending && name) {
document.getElementById('modalTitle').textContent = `Настройка: ${name} (несохранённые изменения)`;
}
// NAT section — show for all non-loopback interfaces
@@ -244,11 +363,29 @@ function closeModal() {
document.getElementById('modal').classList.add('hidden');
document.getElementById('configForm').reset();
state.configModal = null;
state.configModalParent = null;
}
async function saveConfig() {
const name = state.configModal;
if (!name) return;
let name = state.configModal;
if (!name) {
// New VLAN — build name from parent + VLAN ID
const parent = state.configModalParent;
const id = parseInt(document.getElementById('cfgVLANId').value);
if (!parent) return;
if (!id || id < 1 || id > 4094) {
showToast('Укажите корректный VLAN ID (14094)', 'error');
return;
}
name = `${parent}.${id}`;
// Check for duplicate
if (state.interfaces.find(i => i.name === name)) {
showToast(`VLAN ${name} уже существует`, 'error');
return;
}
}
const mode = currentMode();
const cfg = {
@@ -262,7 +399,6 @@ async function saveConfig() {
extra: {},
};
// Basic validation for static
if (mode === 'static' && !cfg.address) {
showToast('Укажите IP-адрес', 'error');
return;
@@ -346,6 +482,8 @@ document.getElementById('ifaceGrid').addEventListener('click', e => {
const { action, iface } = btn.dataset;
if (action === 'config') {
openConfig(iface);
} else if (action === 'addvlan') {
openNewVLAN(iface);
} else {
doAction(iface, action);
}
@@ -378,11 +516,5 @@ setInterval(loadAll, 10000);
// ── Init ──────────────────────────────────────────────────────────────────────
(async () => {
// Try to get hostname
try {
const res = await fetch('/api/interfaces');
// hostname from Location header or just skip
} catch (_) {}
await loadAll();
})();

View File

@@ -50,9 +50,17 @@
</svg>
Клиенты
</a>
<a href="/proxy.html" class="tab-link">
<a href="/firewall.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
<path d="M9 12l2 2 4-4"/>
</svg>
Файрвол
</a>
<a href="/proxy.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<circle cx="12" cy="12" r="3"/>
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
</svg>
Прокси
</a>

View File

@@ -50,9 +50,17 @@
</svg>
Клиенты
</a>
<a href="/proxy.html" class="tab-link">
<a href="/firewall.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
<path d="M9 12l2 2 4-4"/>
</svg>
Файрвол
</a>
<a href="/proxy.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<circle cx="12" cy="12" r="3"/>
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
</svg>
Прокси
</a>

234
public/firewall.html Normal file
View File

@@ -0,0 +1,234 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Файрвол — AlpineRouter</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<div class="header-left">
<svg class="logo" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 2L2 7l10 5 10-5-10-5z"/>
<path d="M2 17l10 5 10-5"/>
<path d="M2 12l10 5 10-5"/>
</svg>
<h1>AlpineRouter</h1>
</div>
<div class="header-right">
<button class="btn btn-ghost" id="refreshBtn" title="Обновить">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16">
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/>
<path d="M3 3v5h5"/>
</svg>
Обновить
</button>
</div>
</header>
<nav class="tab-nav">
<a href="/" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<path d="M12 2L2 7l10 5 10-5-10-5z"/>
<path d="M2 17l10 5 10-5"/>
<path d="M2 12l10 5 10-5"/>
</svg>
Интерфейсы
</a>
<a href="/dhcp.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<path d="M5 12h14M12 5l7 7-7 7"/>
</svg>
DHCP сервер
</a>
<a href="/clients.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<circle cx="9" cy="7" r="4"/><path d="M3 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2"/>
<path d="M16 3.13a4 4 0 0 1 0 7.75M21 21v-2a4 4 0 0 0-3-3.87"/>
</svg>
Клиенты
</a>
<a href="/firewall.html" class="tab-link active">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
<path d="M9 12l2 2 4-4"/>
</svg>
Файрвол
</a>
<a href="/proxy.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<circle cx="12" cy="12" r="3"/>
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
</svg>
Прокси
</a>
</nav>
<main class="fw-main">
<div id="notInstalledBanner" class="alert alert-error hidden">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18">
<circle cx="12" cy="12" r="10"/><path d="M12 8v4m0 4h.01"/>
</svg>
<div>
<strong>nftables не установлен.</strong>
Для работы файрвола выполните на роутере:
<code>apk add nftables</code>
</div>
</div>
<!-- Top controls bar -->
<div class="fw-toolbar">
<div class="fw-toolbar-left">
<label class="toggle-label" id="vlanIsolationLabel" title="Запрещает трафик между VLAN-интерфейсами по умолчанию. Явные правила разрешения выше имеют приоритет.">
<input type="checkbox" id="vlanIsolation">
<span class="toggle-slider"></span>
<span>Изоляция VLAN</span>
</label>
<span class="fw-hint">— теговые VLAN не видят друг друга; NAT — только выход в интернет</span>
</div>
<div class="fw-toolbar-right">
<button class="btn btn-ghost btn-sm" id="addRuleBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M12 5v14M5 12h14"/></svg>
Добавить правило
</button>
<button class="btn btn-primary" id="applyBtn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M5 12l5 5L20 7"/></svg>
Сохранить и применить
</button>
</div>
</div>
<!-- Rules table -->
<div class="fw-card">
<div class="fw-table-wrap">
<table class="fw-table" id="rulesTable">
<thead>
<tr>
<th class="col-drag"></th>
<th class="col-num">#</th>
<th class="col-en">Вкл</th>
<th class="col-action">Действие</th>
<th class="col-proto">Протокол</th>
<th class="col-iface">Вх. интерфейс</th>
<th class="col-iface">Вых. интерфейс</th>
<th class="col-addr">Источник</th>
<th class="col-addr">Назначение</th>
<th class="col-comment">Комментарий</th>
<th class="col-btns"></th>
</tr>
</thead>
<tbody id="rulesTbody">
<tr id="emptyRow">
<td colspan="11" class="fw-empty">
Правил нет. Нажмите «Добавить правило» для создания.
</td>
</tr>
</tbody>
</table>
</div>
<div class="fw-policy-note">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
<circle cx="12" cy="12" r="10"/><path d="M12 8v4m0 4h.01"/>
</svg>
Политика по умолчанию: <strong>DROP</strong> — весь трафик запрещён, если не разрешён явно выше или через NAT.
Трафик established/related всегда разрешается.
</div>
</div>
</main>
<!-- Rule Edit Modal -->
<div id="ruleModal" class="modal hidden" role="dialog" aria-modal="true">
<div class="modal-backdrop" id="ruleModalBackdrop"></div>
<div class="modal-box modal-wide">
<div class="modal-header">
<h2 id="ruleModalTitle">Добавить правило</h2>
<button class="btn-icon" id="closeRuleModal"></button>
</div>
<form id="ruleForm" autocomplete="off">
<div class="form-row">
<label for="rComment">Комментарий</label>
<input type="text" id="rComment" placeholder="Описание правила (необязательно)">
</div>
<div class="form-row">
<label>Действие</label>
<div class="segmented" id="actionSwitch">
<button type="button" class="seg-btn active" data-val="accept">Разрешить</button>
<button type="button" class="seg-btn" data-val="drop">Запретить</button>
<button type="button" class="seg-btn" data-val="reject">Отклонить</button>
</div>
</div>
<div class="form-row">
<label>Протокол</label>
<div class="segmented" id="protoSwitch">
<button type="button" class="seg-btn active" data-val="all">Любой</button>
<button type="button" class="seg-btn" data-val="tcp">TCP</button>
<button type="button" class="seg-btn" data-val="udp">UDP</button>
<button type="button" class="seg-btn" data-val="icmp">ICMP</button>
</div>
</div>
<div class="form-grid-2">
<div class="form-row">
<label for="rInIface">Входящий интерфейс</label>
<input type="text" id="rInIface" placeholder="eth0, eth0.100 … (пусто = любой)" list="ifaceList">
</div>
<div class="form-row">
<label for="rOutIface">Исходящий интерфейс</label>
<input type="text" id="rOutIface" placeholder="eth1 … (пусто = любой)" list="ifaceList">
</div>
</div>
<div class="form-grid-2">
<div class="form-row">
<label for="rSrcAddr">Источник (адрес/подсеть)</label>
<input type="text" id="rSrcAddr" placeholder="192.168.1.0/24 или 10.0.0.5">
</div>
<div class="form-row">
<label for="rDstAddr">Назначение (адрес/подсеть)</label>
<input type="text" id="rDstAddr" placeholder="10.0.0.0/24 или 8.8.8.8">
</div>
</div>
<div class="form-grid-2" id="portFields">
<div class="form-row">
<label for="rSrcPort">Порт источника</label>
<input type="text" id="rSrcPort" placeholder="80 или 1000-2000">
</div>
<div class="form-row">
<label for="rDstPort">Порт назначения</label>
<input type="text" id="rDstPort" placeholder="443 или 8080-8090">
</div>
</div>
<div class="form-row">
<label class="checkbox-label">
<input type="checkbox" id="rEnabled" checked>
<span>Правило активно</span>
</label>
</div>
</form>
<div class="modal-footer">
<button class="btn btn-ghost" id="cancelRuleBtn">Отмена</button>
<button class="btn btn-primary" id="saveRuleBtn">Сохранить</button>
</div>
</div>
</div>
<datalist id="ifaceList"></datalist>
<div id="toast" class="toast hidden"></div>
<script src="firewall.js"></script>
</body>
</html>

330
public/firewall.js Normal file
View File

@@ -0,0 +1,330 @@
'use strict';
// ── State ────────────────────────────────────────────────────────────────────
const state = {
rules: [], // current rule list (order matters)
interfaces: [], // available interface names for autocomplete
editIdx: -1, // index in state.rules being edited (-1 = new)
};
// ── API helpers ──────────────────────────────────────────────────────────────
async function api(method, path, body) {
const res = await fetch(path, {
method,
headers: body ? { 'Content-Type': 'application/json' } : {},
body: body ? JSON.stringify(body) : undefined,
});
const json = await res.json();
if (!res.ok || !json.success) throw new Error(json.error || `HTTP ${res.status}`);
return json.data;
}
const get = p => api('GET', p);
const post = (p, b) => api('POST', p, b);
// ── Load ─────────────────────────────────────────────────────────────────────
async function loadAll() {
try {
const data = await get('/api/firewall');
state.rules = data.rules || [];
state.interfaces = data.interfaces || [];
document.getElementById('vlanIsolation').checked = !!data.vlan_isolation;
const notInstalled = document.getElementById('notInstalledBanner');
if (!data.installed) {
notInstalled.classList.remove('hidden');
} else {
notInstalled.classList.add('hidden');
}
// Populate datalist for interface autocomplete.
const dl = document.getElementById('ifaceList');
dl.innerHTML = state.interfaces.map(n => `<option value="${n}">`).join('');
renderRules();
} catch (e) {
showToast('Ошибка загрузки: ' + e.message, 'error');
}
}
// ── Render ───────────────────────────────────────────────────────────────────
const ACTION_LABELS = { accept: 'Разрешить', drop: 'Запретить', reject: 'Отклонить' };
const ACTION_CLASS = { accept: 'fw-accept', drop: 'fw-drop', reject: 'fw-reject' };
const PROTO_LABELS = { all: 'Любой', tcp: 'TCP', udp: 'UDP', icmp: 'ICMP' };
function addrPort(addr, port) {
if (!addr && !port) return '<span class="none">любой</span>';
const a = addr || '<span class="none">*</span>';
const p = port ? `:<b>${port}</b>` : '';
return a + p;
}
function renderRules() {
const tbody = document.getElementById('rulesTbody');
const emptyRow = document.getElementById('emptyRow');
// Remove all rows except the empty placeholder.
[...tbody.querySelectorAll('.fw-row')].forEach(r => r.remove());
if (state.rules.length === 0) {
emptyRow.classList.remove('hidden');
return;
}
emptyRow.classList.add('hidden');
state.rules.forEach((rule, idx) => {
const tr = document.createElement('tr');
tr.className = 'fw-row' + (rule.enabled ? '' : ' fw-row-disabled');
tr.draggable = true;
tr.dataset.ruleId = rule.id || String(idx);
const inIface = rule.in_iface || '<span class="none">—</span>';
const outIface = rule.out_iface || '<span class="none">—</span>';
tr.innerHTML = `
<td class="col-drag"><span class="drag-handle" title="Перетащить">⠿</span></td>
<td class="col-num">${idx + 1}</td>
<td class="col-en">
<label class="mini-toggle" title="${rule.enabled ? 'Отключить' : 'Включить'}">
<input type="checkbox" data-idx="${idx}" class="rule-toggle" ${rule.enabled ? 'checked' : ''}>
<span class="mini-slider"></span>
</label>
</td>
<td class="col-action"><span class="action-badge ${ACTION_CLASS[rule.action] || 'fw-drop'}">${ACTION_LABELS[rule.action] || rule.action}</span></td>
<td class="col-proto">${PROTO_LABELS[rule.protocol] || rule.protocol || 'Любой'}</td>
<td class="col-iface">${inIface}</td>
<td class="col-iface">${outIface}</td>
<td class="col-addr">${addrPort(rule.src_addr, rule.src_port)}</td>
<td class="col-addr">${addrPort(rule.dst_addr, rule.dst_port)}</td>
<td class="col-comment">${rule.comment ? `<span class="fw-comment">${esc(rule.comment)}</span>` : '<span class="none">—</span>'}</td>
<td class="col-btns">
<button class="btn btn-ghost btn-xs rule-edit" data-idx="${idx}" title="Редактировать">✎</button>
<button class="btn btn-danger btn-xs rule-del" data-idx="${idx}" title="Удалить">✕</button>
</td>
`;
addDragHandlers(tr);
tbody.appendChild(tr);
});
}
function esc(s) {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
// ── Drag-to-reorder ───────────────────────────────────────────────────────────
let dragSrc = null;
function addDragHandlers(row) {
row.addEventListener('dragstart', e => {
dragSrc = row;
e.dataTransfer.effectAllowed = 'move';
setTimeout(() => row.classList.add('dragging'), 0);
});
row.addEventListener('dragend', () => {
row.classList.remove('dragging');
document.querySelectorAll('.fw-row').forEach(r => r.classList.remove('drag-over'));
commitDragOrder();
dragSrc = null;
});
row.addEventListener('dragover', e => {
e.preventDefault();
if (!dragSrc || dragSrc === row) return;
document.querySelectorAll('.fw-row').forEach(r => r.classList.remove('drag-over'));
row.classList.add('drag-over');
});
row.addEventListener('drop', e => {
e.preventDefault();
if (!dragSrc || dragSrc === row) return;
const tbody = row.parentNode;
const rows = [...tbody.querySelectorAll('.fw-row')];
const si = rows.indexOf(dragSrc);
const ti = rows.indexOf(row);
if (si < ti) {
tbody.insertBefore(dragSrc, row.nextSibling);
} else {
tbody.insertBefore(dragSrc, row);
}
});
}
function commitDragOrder() {
const rows = [...document.querySelectorAll('.fw-row')];
const byId = {};
state.rules.forEach(r => { byId[r.id] = r; });
const newRules = [];
rows.forEach((row, i) => {
const id = row.dataset.ruleId;
const r = byId[id] || state.rules[parseInt(id)];
if (r) newRules.push(r);
});
state.rules = newRules;
renderRules();
}
// ── Modal ─────────────────────────────────────────────────────────────────────
function openModal(idx) {
state.editIdx = idx;
const isNew = idx === -1;
document.getElementById('ruleModalTitle').textContent = isNew ? 'Добавить правило' : 'Редактировать правило';
const rule = isNew ? { enabled: true, action: 'accept', protocol: 'all' } : state.rules[idx];
document.getElementById('rEnabled').checked = rule.enabled !== false;
document.getElementById('rComment').value = rule.comment || '';
document.getElementById('rSrcAddr').value = rule.src_addr || '';
document.getElementById('rSrcPort').value = rule.src_port || '';
document.getElementById('rDstAddr').value = rule.dst_addr || '';
document.getElementById('rDstPort').value = rule.dst_port || '';
document.getElementById('rInIface').value = rule.in_iface || '';
document.getElementById('rOutIface').value = rule.out_iface || '';
setSegmented('actionSwitch', rule.action || 'accept');
setSegmented('protoSwitch', rule.protocol || 'all');
updatePortFields(rule.protocol || 'all');
document.getElementById('ruleModal').classList.remove('hidden');
}
function closeModal() {
document.getElementById('ruleModal').classList.add('hidden');
document.getElementById('ruleForm').reset();
}
function setSegmented(id, val) {
document.querySelectorAll(`#${id} .seg-btn`).forEach(b => {
b.classList.toggle('active', b.dataset.val === val);
});
}
function getSegmented(id) {
return document.querySelector(`#${id} .seg-btn.active`)?.dataset.val ?? '';
}
function updatePortFields(proto) {
const show = proto === 'tcp' || proto === 'udp';
document.getElementById('portFields').classList.toggle('hidden', !show);
}
function saveRule() {
const rule = {
id: state.editIdx === -1 ? genId() : (state.rules[state.editIdx]?.id || genId()),
enabled: document.getElementById('rEnabled').checked,
action: getSegmented('actionSwitch'),
protocol: getSegmented('protoSwitch'),
src_addr: document.getElementById('rSrcAddr').value.trim(),
src_port: document.getElementById('rSrcPort').value.trim(),
dst_addr: document.getElementById('rDstAddr').value.trim(),
dst_port: document.getElementById('rDstPort').value.trim(),
in_iface: document.getElementById('rInIface').value.trim(),
out_iface: document.getElementById('rOutIface').value.trim(),
comment: document.getElementById('rComment').value.trim(),
};
if (!rule.action) { showToast('Выберите действие', 'error'); return; }
if (state.editIdx === -1) {
state.rules.push(rule);
} else {
state.rules[state.editIdx] = rule;
}
closeModal();
renderRules();
}
function genId() {
return Math.random().toString(36).slice(2, 10);
}
// ── Save & Apply ──────────────────────────────────────────────────────────────
async function saveAndApply() {
const btn = document.getElementById('applyBtn');
btn.disabled = true;
btn.textContent = 'Применяю...';
try {
await post('/api/firewall', {
rules: state.rules,
vlan_isolation: document.getElementById('vlanIsolation').checked,
});
await post('/api/firewall/apply');
showToast('Правила файрвола применены', 'success');
} catch (e) {
showToast('Ошибка: ' + e.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = 'Сохранить и применить';
}
}
// ── Toast ─────────────────────────────────────────────────────────────────────
let toastTimer;
function showToast(msg, type = 'info') {
const t = document.getElementById('toast');
t.textContent = msg;
t.className = `toast ${type}`;
t.classList.remove('hidden');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => t.classList.add('hidden'), 3500);
}
// ── Event wiring ──────────────────────────────────────────────────────────────
document.getElementById('refreshBtn').addEventListener('click', loadAll);
document.getElementById('applyBtn').addEventListener('click', saveAndApply);
document.getElementById('addRuleBtn').addEventListener('click', () => openModal(-1));
// Table events (delegated)
document.getElementById('rulesTbody').addEventListener('click', e => {
const editBtn = e.target.closest('.rule-edit');
const delBtn = e.target.closest('.rule-del');
if (editBtn) { openModal(parseInt(editBtn.dataset.idx)); return; }
if (delBtn) {
const idx = parseInt(delBtn.dataset.idx);
if (confirm(`Удалить правило ${idx + 1}?`)) {
state.rules.splice(idx, 1);
renderRules();
}
return;
}
});
document.getElementById('rulesTbody').addEventListener('change', e => {
const toggle = e.target.closest('.rule-toggle');
if (toggle) {
const idx = parseInt(toggle.dataset.idx);
state.rules[idx].enabled = toggle.checked;
renderRules();
}
});
// Modal
document.getElementById('closeRuleModal').addEventListener('click', closeModal);
document.getElementById('cancelRuleBtn').addEventListener('click', closeModal);
document.getElementById('ruleModalBackdrop').addEventListener('click', closeModal);
document.getElementById('saveRuleBtn').addEventListener('click', saveRule);
document.getElementById('ruleForm').addEventListener('submit', e => { e.preventDefault(); saveRule(); });
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
// Segmented switchers
document.getElementById('actionSwitch').addEventListener('click', e => {
const b = e.target.closest('.seg-btn');
if (b) setSegmented('actionSwitch', b.dataset.val);
});
document.getElementById('protoSwitch').addEventListener('click', e => {
const b = e.target.closest('.seg-btn');
if (b) { setSegmented('protoSwitch', b.dataset.val); updatePortFields(b.dataset.val); }
});
// ── Init ──────────────────────────────────────────────────────────────────────
loadAll();

View File

@@ -62,9 +62,17 @@
</svg>
Клиенты
</a>
<a href="/proxy.html" class="tab-link">
<a href="/firewall.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
<path d="M9 12l2 2 4-4"/>
</svg>
Файрвол
</a>
<a href="/proxy.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<circle cx="12" cy="12" r="3"/>
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
</svg>
Прокси
</a>
@@ -88,6 +96,16 @@
</div>
<form id="configForm" autocomplete="off">
<!-- VLAN ID — shown only for VLAN interfaces -->
<div id="vlanIdSection" class="hidden">
<div class="form-row">
<label for="cfgVLANId">VLAN ID <span class="form-hint-inline">(14094)</span></label>
<input type="number" id="cfgVLANId" min="1" max="4094" placeholder="100">
</div>
<div class="form-divider"></div>
</div>
<div class="form-row">
<label class="checkbox-label">
<input type="checkbox" id="cfgAuto">

View File

@@ -44,9 +44,17 @@
</svg>
Клиенты
</a>
<a href="/proxy.html" class="tab-link active">
<a href="/firewall.html" class="tab-link">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
<path d="M9 12l2 2 4-4"/>
</svg>
Файрвол
</a>
<a href="/proxy.html" class="tab-link active">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
<circle cx="12" cy="12" r="3"/>
<path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/>
</svg>
Прокси
</a>

View File

@@ -1123,6 +1123,294 @@ select {
padding-right: 30px;
}
/* ── VLAN section inside interface card ── */
.vlan-section {
border-top: 1px solid var(--border);
padding: 10px 16px 12px;
background: rgba(0, 0, 0, 0.15);
}
.vlan-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.vlan-title {
font-size: .75rem;
font-weight: 700;
letter-spacing: .08em;
text-transform: uppercase;
color: var(--text-dim);
}
.btn-xs {
padding: 3px 9px;
font-size: .75rem;
border-radius: 5px;
}
.vlan-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.vlan-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
padding: 7px 10px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
transition: border-color .2s;
}
.vlan-row:hover { border-color: var(--border-hi); }
.vlan-row-left {
display: flex;
align-items: center;
gap: 7px;
flex: 1 1 auto;
min-width: 0;
}
.vlan-iface-name {
font-size: .85rem;
font-weight: 700;
font-family: "JetBrains Mono", "Fira Code", monospace;
color: var(--accent);
}
.vlan-id-tag {
font-size: .68rem;
font-weight: 700;
letter-spacing: .06em;
text-transform: uppercase;
padding: 2px 8px;
border-radius: 20px;
background: rgba(0, 212, 255, 0.06);
border: 1px solid rgba(0, 212, 255, 0.2);
color: var(--text-dim);
white-space: nowrap;
}
.vlan-row-info {
font-size: .8rem;
color: var(--text-dim);
font-family: "JetBrains Mono", "Fira Code", monospace;
flex: 0 1 auto;
}
.vlan-row-actions {
display: flex;
gap: 5px;
flex-shrink: 0;
}
.vlan-empty {
font-size: .8rem;
color: var(--muted);
text-align: center;
padding: 8px 0 4px;
font-style: italic;
}
/* Modal hint inline */
.form-hint-inline {
font-size: .78rem;
color: var(--muted);
font-weight: 400;
}
/* ── Firewall page ── */
.fw-main {
padding: 28px;
display: flex;
flex-direction: column;
gap: 18px;
}
.fw-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 12px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 14px 20px;
backdrop-filter: blur(10px);
}
.fw-toolbar-left { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
.fw-toolbar-right { display: flex; align-items: center; gap: 10px; }
.fw-hint { font-size: .78rem; color: var(--muted); }
.fw-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
overflow: hidden;
backdrop-filter: blur(10px);
}
.fw-table-wrap { overflow-x: auto; }
.fw-table {
width: 100%;
border-collapse: collapse;
font-size: .85rem;
}
.fw-table thead th {
padding: 10px 12px;
text-align: left;
font-size: .72rem;
font-weight: 700;
letter-spacing: .07em;
text-transform: uppercase;
color: var(--text-dim);
border-bottom: 1px solid var(--border);
white-space: nowrap;
background: rgba(0,0,0,.15);
}
.fw-table tbody td {
padding: 9px 12px;
vertical-align: middle;
border-bottom: 1px solid rgba(0,200,255,.04);
}
.fw-table tbody tr:last-child td { border-bottom: none; }
.fw-row { transition: background .15s; }
.fw-row:hover { background: var(--surface-2); }
.fw-row.fw-row-disabled { opacity: .45; }
.fw-row.dragging { opacity: .4; background: rgba(0,212,255,.05); }
.fw-row.drag-over { border-top: 2px solid var(--accent); }
/* Column widths */
.col-drag { width: 28px; }
.col-num { width: 32px; color: var(--muted); font-size: .78rem; }
.col-en { width: 44px; }
.col-action { width: 110px; }
.col-proto { width: 80px; }
.col-iface { width: 120px; font-family: "JetBrains Mono","Fira Code",monospace; font-size: .8rem; }
.col-addr { min-width: 160px; font-family: "JetBrains Mono","Fira Code",monospace; font-size: .8rem; }
.col-comment { color: var(--text-dim); font-size: .82rem; }
.col-btns { width: 80px; white-space: nowrap; }
.drag-handle {
cursor: grab;
color: var(--muted);
font-size: 1.1rem;
user-select: none;
display: inline-block;
line-height: 1;
padding: 2px 4px;
}
.drag-handle:active { cursor: grabbing; }
/* Action badges */
.action-badge {
display: inline-block;
font-size: .7rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: .07em;
padding: 3px 10px;
border-radius: 20px;
border: 1px solid;
}
.fw-accept {
border-color: rgba(0, 255, 136, 0.4);
color: var(--success);
background: rgba(0, 255, 136, 0.08);
}
.fw-drop {
border-color: rgba(255, 51, 102, 0.4);
color: var(--danger);
background: rgba(255, 51, 102, 0.08);
}
.fw-reject {
border-color: rgba(255, 170, 0, 0.4);
color: var(--warning);
background: rgba(255, 170, 0, 0.08);
}
/* Empty state */
.fw-empty {
text-align: center;
padding: 40px 20px;
color: var(--muted);
font-style: italic;
}
/* Policy note */
.fw-policy-note {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 16px;
font-size: .78rem;
color: var(--muted);
border-top: 1px solid var(--border);
background: rgba(0,0,0,.1);
}
.fw-policy-note strong { color: var(--danger); }
/* Mini toggle (inline in table) */
.mini-toggle {
display: inline-flex;
align-items: center;
cursor: pointer;
}
.mini-toggle input { display: none; }
.mini-slider {
display: inline-block;
width: 30px; height: 16px;
background: var(--surface-3);
border: 1px solid var(--border);
border-radius: 8px;
position: relative;
transition: all .2s;
}
.mini-slider::after {
content: '';
position: absolute;
top: 2px; left: 2px;
width: 11px; height: 11px;
background: var(--muted);
border-radius: 50%;
transition: all .2s;
}
.mini-toggle input:checked + .mini-slider {
background: rgba(0,255,136,.2);
border-color: rgba(0,255,136,.4);
}
.mini-toggle input:checked + .mini-slider::after {
transform: translateX(14px);
background: var(--success);
}
/* Comment display */
.fw-comment { color: var(--text-dim); }
/* Wider modal for rule editing */
.modal-wide { max-width: 680px; }
/* Two-column form grid */
.form-grid-2 {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0 16px;
}
@media (max-width: 560px) {
.form-grid-2 { grid-template-columns: 1fr; }
}
/* ── Scanline overlay (subtle futuristic effect) ── */
body::after {
content: '';