Compare commits
2 Commits
7eaa9750b0
...
6aa0349f5d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6aa0349f5d | ||
|
|
8c35022483 |
Submodule Meta-Docs updated: d31369ab45...eedcf074cd
7
RULES.md
7
RULES.md
@@ -1,8 +1,9 @@
|
|||||||
1. Все настройки обязательно сохранять в config.yaml и восстанавливать оттуда при первом запуске бинарника.
|
1. Все настройки всех подсистем обязательно сохранять в config.yaml и восстанавливать оттуда при первом запуске бинарника, затрия то, что осталось в конфигах управляемых сервисов.
|
||||||
2. Функциональные разделы админки писать отдельными html страницами и добавлять в главное меню.
|
2. Функциональные разделы админки писать отдельными html страницами и добавлять в главное меню.
|
||||||
|
3. Документировать весь новый функционал в docs/
|
||||||
|
|
||||||
|
|
||||||
|
Зависимости alpine:
|
||||||
Установить пакеты:
|
|
||||||
dnsmasq
|
dnsmasq
|
||||||
nftables
|
nftables
|
||||||
|
conntrack-tools
|
||||||
|
|||||||
BIN
alpine-router
BIN
alpine-router
Binary file not shown.
@@ -10,6 +10,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type InterfaceConfig struct {
|
type InterfaceConfig struct {
|
||||||
|
Label string `yaml:"label,omitempty"`
|
||||||
Auto bool `yaml:"auto"`
|
Auto bool `yaml:"auto"`
|
||||||
Mode string `yaml:"mode"`
|
Mode string `yaml:"mode"`
|
||||||
Address string `yaml:"address,omitempty"`
|
Address string `yaml:"address,omitempty"`
|
||||||
@@ -52,12 +53,32 @@ type MihomoConfig struct {
|
|||||||
Enabled bool `yaml:"enabled"`
|
Enabled bool `yaml:"enabled"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type FirewallRule struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||||
|
Action string `yaml:"action" json:"action"`
|
||||||
|
Protocol string `yaml:"protocol" json:"protocol"`
|
||||||
|
SrcAddr string `yaml:"src_addr" json:"src_addr"`
|
||||||
|
SrcPort string `yaml:"src_port" json:"src_port"`
|
||||||
|
DstAddr string `yaml:"dst_addr" json:"dst_addr"`
|
||||||
|
DstPort string `yaml:"dst_port" json:"dst_port"`
|
||||||
|
InIface string `yaml:"in_iface" json:"in_iface"`
|
||||||
|
OutIface string `yaml:"out_iface" json:"out_iface"`
|
||||||
|
Comment string `yaml:"comment" json:"comment"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type FirewallConfig struct {
|
||||||
|
Rules []FirewallRule `yaml:"rules" json:"rules"`
|
||||||
|
VLANIsolation bool `yaml:"vlan_isolation" json:"vlan_isolation"`
|
||||||
|
}
|
||||||
|
|
||||||
type AppConfig struct {
|
type AppConfig struct {
|
||||||
Interfaces map[string]*InterfaceConfig `yaml:"interfaces"`
|
Interfaces map[string]*InterfaceConfig `yaml:"interfaces"`
|
||||||
DHCP DHCPConfig `yaml:"dhcp"`
|
DHCP DHCPConfig `yaml:"dhcp"`
|
||||||
NAT NATConfig `yaml:"nat"`
|
NAT NATConfig `yaml:"nat"`
|
||||||
KnownDevices []KnownDevice `yaml:"known_devices"`
|
Firewall FirewallConfig `yaml:"firewall"`
|
||||||
Mihomo MihomoConfig `yaml:"mihomo"`
|
KnownDevices []KnownDevice `yaml:"known_devices"`
|
||||||
|
Mihomo MihomoConfig `yaml:"mihomo"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -176,6 +197,9 @@ func EnsureDefaults(cfg *AppConfig) {
|
|||||||
if cfg.NAT.Interfaces == nil {
|
if cfg.NAT.Interfaces == nil {
|
||||||
cfg.NAT.Interfaces = []string{}
|
cfg.NAT.Interfaces = []string{}
|
||||||
}
|
}
|
||||||
|
if cfg.Firewall.Rules == nil {
|
||||||
|
cfg.Firewall.Rules = []FirewallRule{}
|
||||||
|
}
|
||||||
if cfg.KnownDevices == nil {
|
if cfg.KnownDevices == nil {
|
||||||
cfg.KnownDevices = []KnownDevice{}
|
cfg.KnownDevices = []KnownDevice{}
|
||||||
}
|
}
|
||||||
|
|||||||
201
firewall/firewall.go
Normal file
201
firewall/firewall.go
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
package firewall
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const tableName = "alpine-router"
|
||||||
|
|
||||||
|
// Rule is a single stateless forward-filter rule.
|
||||||
|
type Rule struct {
|
||||||
|
ID string `yaml:"id" json:"id"`
|
||||||
|
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||||
|
Action string `yaml:"action" json:"action"` // accept | drop | reject
|
||||||
|
Protocol string `yaml:"protocol" json:"protocol"` // tcp | udp | icmp | all
|
||||||
|
SrcAddr string `yaml:"src_addr" json:"src_addr"` // CIDR or IP, empty = any
|
||||||
|
SrcPort string `yaml:"src_port" json:"src_port"` // "80" | "80-443", empty = any
|
||||||
|
DstAddr string `yaml:"dst_addr" json:"dst_addr"`
|
||||||
|
DstPort string `yaml:"dst_port" json:"dst_port"`
|
||||||
|
InIface string `yaml:"in_iface" json:"in_iface"` // input interface, empty = any
|
||||||
|
OutIface string `yaml:"out_iface" json:"out_iface"` // output interface, empty = any
|
||||||
|
Comment string `yaml:"comment" json:"comment"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config is the top-level firewall config stored in config.yaml.
|
||||||
|
type Config struct {
|
||||||
|
Rules []Rule `yaml:"rules" json:"rules"`
|
||||||
|
VLANIsolation bool `yaml:"vlan_isolation" json:"vlan_isolation"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// NATConfig holds NAT masquerade settings (passed to avoid a direct nat import).
|
||||||
|
type NATConfig struct {
|
||||||
|
Interfaces []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsInstalled reports whether the nft binary is available.
|
||||||
|
func IsInstalled() bool {
|
||||||
|
_, err := exec.LookPath("nft")
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplyAll atomically regenerates the complete nftables ruleset:
|
||||||
|
// - NAT masquerade for natCfg.Interfaces
|
||||||
|
// - Blocked client IP drops
|
||||||
|
// - User rules from fwCfg (in order, enabled only)
|
||||||
|
// - LAN isolation (if fwCfg.VLANIsolation): blocks traffic between any two LAN interfaces
|
||||||
|
// (native + tagged VLANs). User rules placed above have priority.
|
||||||
|
// - Default accept from LAN interfaces to WAN
|
||||||
|
//
|
||||||
|
// lanIfaces is the union of NAT interfaces and all VLAN interfaces — every interface
|
||||||
|
// that serves a local subnet. Isolation prevents any two of them from talking directly.
|
||||||
|
func ApplyAll(natCfg NATConfig, fwCfg Config, blockedIPs, lanIfaces []string) error {
|
||||||
|
if err := os.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1"), 0644); err != nil {
|
||||||
|
return fmt.Errorf("enable ip_forward: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove both old and new table names to ensure clean state.
|
||||||
|
exec.Command("nft", "delete", "table", "ip", "alpine-router-nat").Run()
|
||||||
|
exec.Command("nft", "delete", "table", "ip", tableName).Run()
|
||||||
|
|
||||||
|
var activeRules []Rule
|
||||||
|
for _, r := range fwCfg.Rules {
|
||||||
|
if r.Enabled {
|
||||||
|
activeRules = append(activeRules, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hasNAT := len(natCfg.Interfaces) > 0
|
||||||
|
hasBlocked := len(blockedIPs) > 0
|
||||||
|
hasVLANIsolation := fwCfg.VLANIsolation && len(lanIfaces) >= 2
|
||||||
|
|
||||||
|
if !hasNAT && !hasBlocked && !hasVLANIsolation && len(activeRules) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var sb strings.Builder
|
||||||
|
fmt.Fprintf(&sb, "table ip %s {\n", tableName)
|
||||||
|
|
||||||
|
// ── Forward chain ────────────────────────────────────────────────────────
|
||||||
|
sb.WriteString(" chain forward {\n")
|
||||||
|
sb.WriteString(" type filter hook forward priority filter; policy drop;\n")
|
||||||
|
sb.WriteString(" ct state established,related accept\n")
|
||||||
|
|
||||||
|
for _, ip := range blockedIPs {
|
||||||
|
fmt.Fprintf(&sb, " ip saddr %s drop\n", ip)
|
||||||
|
fmt.Fprintf(&sb, " ip daddr %s drop\n", ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, rule := range activeRules {
|
||||||
|
line := buildRuleLine(rule)
|
||||||
|
if line == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if rule.Comment != "" {
|
||||||
|
fmt.Fprintf(&sb, " # %s\n", rule.Comment)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&sb, " %s\n", line)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LAN isolation — drop traffic between any two local (LAN) interfaces.
|
||||||
|
// Placed AFTER user rules so explicit allow rules above still take effect.
|
||||||
|
if hasVLANIsolation {
|
||||||
|
quoted := make([]string, len(lanIfaces))
|
||||||
|
for i, v := range lanIfaces {
|
||||||
|
quoted[i] = fmt.Sprintf("%q", v)
|
||||||
|
}
|
||||||
|
set := "{ " + strings.Join(quoted, ", ") + " }"
|
||||||
|
fmt.Fprintf(&sb, " iifname %s oifname %s drop\n", set, set)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow from LAN/VLAN interfaces to WAN (non-VLAN, non-blocked traffic falls through above).
|
||||||
|
for _, iface := range natCfg.Interfaces {
|
||||||
|
fmt.Fprintf(&sb, " iifname %q accept\n", iface)
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.WriteString(" }\n")
|
||||||
|
|
||||||
|
// ── Postrouting (masquerade) ─────────────────────────────────────────────
|
||||||
|
if hasNAT {
|
||||||
|
sb.WriteString(" chain postrouting {\n")
|
||||||
|
sb.WriteString(" type nat hook postrouting priority srcnat; policy accept;\n")
|
||||||
|
for _, iface := range natCfg.Interfaces {
|
||||||
|
fmt.Fprintf(&sb, " iifname %q masquerade\n", iface)
|
||||||
|
}
|
||||||
|
sb.WriteString(" }\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.WriteString("}\n")
|
||||||
|
|
||||||
|
cmd := exec.Command("nft", "-f", "-")
|
||||||
|
cmd.Stdin = strings.NewReader(sb.String())
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("nft apply: %s: %w", strings.TrimSpace(string(out)), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush connection tracking table so existing sessions are re-evaluated
|
||||||
|
// against the new ruleset. Without this, traffic already tracked as
|
||||||
|
// "established/related" bypasses new drop rules until the session ends.
|
||||||
|
flushConntrack()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// flushConntrack clears the kernel connection tracking table so that all traffic
|
||||||
|
// is re-evaluated against the current nftables ruleset. This is necessary when
|
||||||
|
// adding new drop/reject rules to prevent previously-established sessions from
|
||||||
|
// continuing to bypass the new rules via ct state established,related accept.
|
||||||
|
func flushConntrack() {
|
||||||
|
// Preferred: conntrack utility (part of conntrack-tools package).
|
||||||
|
if err := exec.Command("conntrack", "-F").Run(); err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Fallback: write to /proc (available when nf_conntrack module is loaded).
|
||||||
|
_ = os.WriteFile("/proc/sys/net/netfilter/nf_conntrack_flush", []byte("1"), 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildRuleLine converts a Rule to a single nftables match+action string.
|
||||||
|
// Returns "" if the rule has no valid action.
|
||||||
|
func buildRuleLine(r Rule) string {
|
||||||
|
if r.Action == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
var parts []string
|
||||||
|
|
||||||
|
if r.InIface != "" {
|
||||||
|
parts = append(parts, fmt.Sprintf("iifname %q", r.InIface))
|
||||||
|
}
|
||||||
|
if r.OutIface != "" {
|
||||||
|
parts = append(parts, fmt.Sprintf("oifname %q", r.OutIface))
|
||||||
|
}
|
||||||
|
if r.SrcAddr != "" {
|
||||||
|
parts = append(parts, "ip saddr "+r.SrcAddr)
|
||||||
|
}
|
||||||
|
if r.DstAddr != "" {
|
||||||
|
parts = append(parts, "ip daddr "+r.DstAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
proto := strings.ToLower(r.Protocol)
|
||||||
|
switch proto {
|
||||||
|
case "tcp", "udp":
|
||||||
|
if r.SrcPort != "" || r.DstPort != "" {
|
||||||
|
if r.SrcPort != "" {
|
||||||
|
parts = append(parts, proto+" sport "+r.SrcPort)
|
||||||
|
}
|
||||||
|
if r.DstPort != "" {
|
||||||
|
parts = append(parts, proto+" dport "+r.DstPort)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
parts = append(parts, "ip protocol "+proto)
|
||||||
|
}
|
||||||
|
case "icmp":
|
||||||
|
parts = append(parts, "ip protocol icmp")
|
||||||
|
}
|
||||||
|
|
||||||
|
parts = append(parts, r.Action)
|
||||||
|
return strings.Join(parts, " ")
|
||||||
|
}
|
||||||
@@ -45,11 +45,16 @@ func HandleInterfaces(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
type iface struct {
|
type iface struct {
|
||||||
*network.InterfaceStats
|
*network.InterfaceStats
|
||||||
Pending bool `json:"pending"`
|
Pending bool `json:"pending"`
|
||||||
|
Label string `json:"label,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
appCfg, _ := config.Load()
|
||||||
|
|
||||||
result := make([]iface, 0, len(names))
|
result := make([]iface, 0, len(names))
|
||||||
|
existingNames := map[string]bool{}
|
||||||
for _, name := range names {
|
for _, name := range names {
|
||||||
|
existingNames[name] = true
|
||||||
s, err := network.GetInterfaceStats(name)
|
s, err := network.GetInterfaceStats(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
@@ -57,8 +62,39 @@ func HandleInterfaces(w http.ResponseWriter, r *http.Request) {
|
|||||||
if cfg, ok := fileCfg[name]; ok {
|
if cfg, ok := fileCfg[name]; ok {
|
||||||
s.Mode = cfg.Mode
|
s.Mode = cfg.Mode
|
||||||
}
|
}
|
||||||
_, hasPending := network.GetPendingConfig(name), network.GetPendingConfig(name) != nil
|
hasPending := network.GetPendingConfig(name) != nil
|
||||||
result = append(result, iface{s, hasPending})
|
label := ""
|
||||||
|
if appCfg != nil && appCfg.Interfaces != nil {
|
||||||
|
if ic, ok := appCfg.Interfaces[name]; ok {
|
||||||
|
label = ic.Label
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result = append(result, iface{s, hasPending, label})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also include pending VLAN configs not yet present in the system.
|
||||||
|
for name, cfg := range network.GetAllPending() {
|
||||||
|
if existingNames[name] || !network.IsVLAN(name) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
s := &network.InterfaceStats{
|
||||||
|
Name: name,
|
||||||
|
State: "unknown",
|
||||||
|
Mode: cfg.Mode,
|
||||||
|
IPv6: []string{},
|
||||||
|
}
|
||||||
|
if cfg.Mode == "static" {
|
||||||
|
s.IPv4 = cfg.Address
|
||||||
|
s.IPv4Mask = cfg.Netmask
|
||||||
|
s.Gateway = cfg.Gateway
|
||||||
|
}
|
||||||
|
label := cfg.Label
|
||||||
|
if label == "" && appCfg != nil && appCfg.Interfaces != nil {
|
||||||
|
if ic, ok := appCfg.Interfaces[name]; ok {
|
||||||
|
label = ic.Label
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result = append(result, iface{s, true, label})
|
||||||
}
|
}
|
||||||
|
|
||||||
ok(w, result)
|
ok(w, result)
|
||||||
@@ -100,6 +136,13 @@ func HandleInterfaceAction(w http.ResponseWriter, r *http.Request) {
|
|||||||
err = network.IfDown(name)
|
err = network.IfDown(name)
|
||||||
case "restart":
|
case "restart":
|
||||||
err = network.IfRestart(name)
|
err = network.IfRestart(name)
|
||||||
|
case "delete":
|
||||||
|
if !network.IsVLAN(name) {
|
||||||
|
fail(w, http.StatusBadRequest, "delete is only supported for VLAN interfaces")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
network.ClearPendingConfig(name)
|
||||||
|
err = network.DeleteVLAN(name)
|
||||||
default:
|
default:
|
||||||
fail(w, http.StatusBadRequest, "unknown action: "+action)
|
fail(w, http.StatusBadRequest, "unknown action: "+action)
|
||||||
return
|
return
|
||||||
@@ -121,8 +164,18 @@ func HandleConfig(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
|
appCfg, _ := config.Load()
|
||||||
|
label := ""
|
||||||
|
if appCfg != nil && appCfg.Interfaces != nil {
|
||||||
|
if ic, ok2 := appCfg.Interfaces[name]; ok2 {
|
||||||
|
label = ic.Label
|
||||||
|
}
|
||||||
|
}
|
||||||
if cfg := network.GetPendingConfig(name); cfg != nil {
|
if cfg := network.GetPendingConfig(name); cfg != nil {
|
||||||
ok(w, map[string]interface{}{"config": cfg, "pending": true})
|
if cfg.Label != "" {
|
||||||
|
label = cfg.Label
|
||||||
|
}
|
||||||
|
ok(w, map[string]interface{}{"config": cfg, "pending": true, "label": label})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fileCfg, err := network.ParseConfig()
|
fileCfg, err := network.ParseConfig()
|
||||||
@@ -131,11 +184,12 @@ func HandleConfig(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if cfg, exists := fileCfg[name]; exists {
|
if cfg, exists := fileCfg[name]; exists {
|
||||||
ok(w, map[string]interface{}{"config": cfg, "pending": false})
|
ok(w, map[string]interface{}{"config": cfg, "pending": false, "label": label})
|
||||||
} else {
|
} else {
|
||||||
ok(w, map[string]interface{}{
|
ok(w, map[string]interface{}{
|
||||||
"config": &network.InterfaceConfig{Name: name, Auto: true, Mode: "dhcp", Extra: map[string]string{}},
|
"config": &network.InterfaceConfig{Name: name, Auto: true, Mode: "dhcp", Extra: map[string]string{}},
|
||||||
"pending": false,
|
"pending": false,
|
||||||
|
"label": label,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,6 +214,7 @@ func HandleConfig(w http.ResponseWriter, r *http.Request) {
|
|||||||
appCfg.Interfaces = map[string]*config.InterfaceConfig{}
|
appCfg.Interfaces = map[string]*config.InterfaceConfig{}
|
||||||
}
|
}
|
||||||
appCfg.Interfaces[name] = &config.InterfaceConfig{
|
appCfg.Interfaces[name] = &config.InterfaceConfig{
|
||||||
|
Label: cfg.Label,
|
||||||
Auto: cfg.Auto,
|
Auto: cfg.Auto,
|
||||||
Mode: cfg.Mode,
|
Mode: cfg.Mode,
|
||||||
Address: cfg.Address,
|
Address: cfg.Address,
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
"alpine-router/clients"
|
"alpine-router/clients"
|
||||||
"alpine-router/config"
|
"alpine-router/config"
|
||||||
"alpine-router/dhcp"
|
"alpine-router/dhcp"
|
||||||
"alpine-router/nat"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func HandleClients(w http.ResponseWriter, r *http.Request) {
|
func HandleClients(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -88,37 +87,6 @@ func updateClient(mac, hostname string, blocked bool, staticIP string) error {
|
|||||||
return config.Save(cfg)
|
return config.Save(cfg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func applyBlockedFirewall() {
|
|
||||||
if !nat.IsInstalled() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cfg, err := config.Load()
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Warning: load config for blocked firewall: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var blockedIPs []string
|
|
||||||
for _, kd := range cfg.KnownDevices {
|
|
||||||
if kd.Blocked {
|
|
||||||
ip := kd.IP
|
|
||||||
if kd.StaticIP != "" {
|
|
||||||
ip = kd.StaticIP
|
|
||||||
}
|
|
||||||
if ip != "" {
|
|
||||||
blockedIPs = append(blockedIPs, ip)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
natCfg := &nat.Config{Interfaces: cfg.NAT.Interfaces}
|
|
||||||
if err := nat.ApplyRulesWithBlocked(natCfg, blockedIPs); err != nil {
|
|
||||||
log.Printf("Warning: apply blocked firewall rules: %v", err)
|
|
||||||
} else {
|
|
||||||
log.Printf("Applied firewall rules (%d blocked clients)", len(blockedIPs))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func applyDHCPStaticBindings() {
|
func applyDHCPStaticBindings() {
|
||||||
if !dhcp.IsInstalled() {
|
if !dhcp.IsInstalled() {
|
||||||
|
|||||||
100
handlers/firewall.go
Normal file
100
handlers/firewall.go
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"alpine-router/config"
|
||||||
|
"alpine-router/nat"
|
||||||
|
"alpine-router/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
func HandleFirewall(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.Method {
|
||||||
|
case http.MethodGet:
|
||||||
|
handleFirewallGet(w, r)
|
||||||
|
case http.MethodPost:
|
||||||
|
handleFirewallSave(w, r)
|
||||||
|
default:
|
||||||
|
fail(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleFirewallGet(w http.ResponseWriter, r *http.Request) {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
fail(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect interface names for the UI dropdowns.
|
||||||
|
names, _ := network.GetInterfaces()
|
||||||
|
|
||||||
|
ok(w, map[string]interface{}{
|
||||||
|
"installed": nat.IsInstalled(),
|
||||||
|
"rules": cfg.Firewall.Rules,
|
||||||
|
"vlan_isolation": cfg.Firewall.VLANIsolation,
|
||||||
|
"interfaces": names,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleFirewallSave(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var body struct {
|
||||||
|
Rules []config.FirewallRule `json:"rules"`
|
||||||
|
VLANIsolation bool `json:"vlan_isolation"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
|
fail(w, http.StatusBadRequest, "invalid json: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assign IDs to new rules that lack one.
|
||||||
|
for i := range body.Rules {
|
||||||
|
if body.Rules[i].ID == "" {
|
||||||
|
body.Rules[i].ID = fmt.Sprintf("%x", rand.Int63())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
fail(w, http.StatusInternalServerError, "load config: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.Firewall.Rules = body.Rules
|
||||||
|
cfg.Firewall.VLANIsolation = body.VLANIsolation
|
||||||
|
|
||||||
|
if err := config.Save(cfg); err != nil {
|
||||||
|
fail(w, http.StatusInternalServerError, "save config: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ok(w, map[string]string{"message": "saved"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleFirewallApply(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
fail(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !nat.IsInstalled() {
|
||||||
|
fail(w, http.StatusServiceUnavailable, "nftables (nft) не установлен — выполните: apk add nftables")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
fail(w, http.StatusInternalServerError, "load config: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := applyAllRules(cfg); err != nil {
|
||||||
|
fail(w, http.StatusInternalServerError, "apply: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ok(w, map[string]string{"message": "firewall applied"})
|
||||||
|
}
|
||||||
217
handlers/mihomo_proxy.go
Normal file
217
handlers/mihomo_proxy.go
Normal file
@@ -0,0 +1,217 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"alpine-router/mihomo"
|
||||||
|
)
|
||||||
|
|
||||||
|
func getMihomoAPIBase() string {
|
||||||
|
cfg, err := mihomo.LoadConfig()
|
||||||
|
if err != nil {
|
||||||
|
return "http://127.0.0.1:9090"
|
||||||
|
}
|
||||||
|
ec, _ := cfg["external-controller"].(string)
|
||||||
|
if ec == "" {
|
||||||
|
ec = "0.0.0.0:9090"
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(ec, "0.0.0.0:") || strings.HasPrefix(ec, ":") {
|
||||||
|
ec = "127.0.0.1" + strings.TrimPrefix(ec, "0.0.0.0")
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(ec, "http") {
|
||||||
|
ec = "http://" + ec
|
||||||
|
}
|
||||||
|
return ec
|
||||||
|
}
|
||||||
|
|
||||||
|
func getMihomoSecret() string {
|
||||||
|
cfg, err := mihomo.LoadConfig()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
s, _ := cfg["secret"].(string)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func getMihomoHostPort() (string, string) {
|
||||||
|
u, err := url.Parse(getMihomoAPIBase())
|
||||||
|
if err != nil {
|
||||||
|
return "127.0.0.1", "9090"
|
||||||
|
}
|
||||||
|
host := u.Hostname()
|
||||||
|
if host == "0.0.0.0" || host == "" {
|
||||||
|
host = "127.0.0.1"
|
||||||
|
}
|
||||||
|
port := u.Port()
|
||||||
|
if port == "" {
|
||||||
|
if u.Scheme == "https" {
|
||||||
|
port = "443"
|
||||||
|
} else {
|
||||||
|
port = "80"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return host, port
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleMihomoAPIProxy(w http.ResponseWriter, r *http.Request) {
|
||||||
|
base := getMihomoAPIBase()
|
||||||
|
secret := getMihomoSecret()
|
||||||
|
|
||||||
|
suffix := strings.TrimPrefix(r.URL.Path, "/api/mihomo/api/")
|
||||||
|
target, err := url.Parse(base + "/" + suffix)
|
||||||
|
if err != nil {
|
||||||
|
fail(w, http.StatusInternalServerError, "parse mihomo url: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
q := r.URL.Query()
|
||||||
|
if r.Method == http.MethodGet {
|
||||||
|
q.Set("nonce", "1")
|
||||||
|
}
|
||||||
|
target.RawQuery = q.Encode()
|
||||||
|
|
||||||
|
proxyReq, err := http.NewRequest(r.Method, target.String(), r.Body)
|
||||||
|
if err != nil {
|
||||||
|
fail(w, http.StatusInternalServerError, "create proxy request: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for k, vv := range r.Header {
|
||||||
|
if strings.EqualFold(k, "Authorization") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, v := range vv {
|
||||||
|
proxyReq.Header.Add(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if secret != "" {
|
||||||
|
proxyReq.Header.Set("Authorization", "Bearer "+secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
client := &http.Client{}
|
||||||
|
resp, err := client.Do(proxyReq)
|
||||||
|
if err != nil {
|
||||||
|
fail(w, http.StatusBadGateway, "mihomo api unreachable: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
for k, vv := range resp.Header {
|
||||||
|
if strings.EqualFold(k, "Content-Length") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, v := range vv {
|
||||||
|
w.Header().Add(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(resp.StatusCode)
|
||||||
|
_, err = io.Copy(w, resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("proxy copy error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleMihomoWSProxy(w http.ResponseWriter, r *http.Request) {
|
||||||
|
secret := getMihomoSecret()
|
||||||
|
host, port := getMihomoHostPort()
|
||||||
|
|
||||||
|
suffix := strings.TrimPrefix(r.URL.Path, "/api/mihomo/ws/")
|
||||||
|
path := "/" + suffix
|
||||||
|
if r.URL.RawQuery != "" {
|
||||||
|
path += "?" + r.URL.RawQuery
|
||||||
|
}
|
||||||
|
|
||||||
|
hj, ok := w.(http.Hijacker)
|
||||||
|
if !ok {
|
||||||
|
fail(w, http.StatusInternalServerError, "websocket hijack not supported")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
clientConn, _, err := hj.Hijack()
|
||||||
|
if err != nil {
|
||||||
|
fail(w, http.StatusInternalServerError, "hijack failed: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
remoteConn, err := net.Dial("tcp", net.JoinHostPort(host, port))
|
||||||
|
if err != nil {
|
||||||
|
fail(w, http.StatusBadGateway, "mihomo ws connect failed: "+err.Error())
|
||||||
|
clientConn.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
upgradeReq := "GET " + path + " HTTP/1.1\r\n"
|
||||||
|
upgradeReq += "Host: " + host + ":" + port + "\r\n"
|
||||||
|
upgradeReq += "Upgrade: websocket\r\n"
|
||||||
|
upgradeReq += "Connection: Upgrade\r\n"
|
||||||
|
upgradeReq += "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
|
||||||
|
upgradeReq += "Sec-WebSocket-Version: 13\r\n"
|
||||||
|
if secret != "" {
|
||||||
|
upgradeReq += "Authorization: Bearer " + secret + "\r\n"
|
||||||
|
}
|
||||||
|
for k, vv := range r.Header {
|
||||||
|
if strings.EqualFold(k, "Upgrade") || strings.EqualFold(k, "Connection") ||
|
||||||
|
strings.EqualFold(k, "Sec-Websocket-Key") || strings.EqualFold(k, "Sec-Websocket-Version") ||
|
||||||
|
strings.EqualFold(k, "Sec-Websocket-Extensions") || strings.EqualFold(k, "Sec-Websocket-Protocol") ||
|
||||||
|
strings.EqualFold(k, "Authorization") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, v := range vv {
|
||||||
|
upgradeReq += k + ": " + v + "\r\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for k, v := range r.Header {
|
||||||
|
if strings.EqualFold(k, "Sec-WebSocket-Protocol") {
|
||||||
|
upgradeReq += "Sec-WebSocket-Protocol: " + strings.Join(v, ", ") + "\r\n"
|
||||||
|
}
|
||||||
|
if strings.EqualFold(k, "Sec-WebSocket-Extensions") {
|
||||||
|
upgradeReq += "Sec-WebSocket-Extensions: " + strings.Join(v, ", ") + "\r\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
upgradeReq += "\r\n"
|
||||||
|
|
||||||
|
_, err = remoteConn.Write([]byte(upgradeReq))
|
||||||
|
if err != nil {
|
||||||
|
clientConn.Close()
|
||||||
|
remoteConn.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := make([]byte, 4096)
|
||||||
|
n, err := remoteConn.Read(buf)
|
||||||
|
if err != nil {
|
||||||
|
clientConn.Close()
|
||||||
|
remoteConn.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
respStr := string(buf[:n])
|
||||||
|
if !strings.Contains(respStr, "101") {
|
||||||
|
clientConn.Write(buf[:n])
|
||||||
|
clientConn.Close()
|
||||||
|
remoteConn.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
headerEnd := strings.Index(respStr, "\r\n\r\n")
|
||||||
|
if headerEnd >= 0 {
|
||||||
|
clientConn.Write(buf[:n])
|
||||||
|
} else {
|
||||||
|
clientConn.Write(buf[:n])
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
io.Copy(remoteConn, clientConn)
|
||||||
|
remoteConn.Close()
|
||||||
|
}()
|
||||||
|
go func() {
|
||||||
|
io.Copy(clientConn, remoteConn)
|
||||||
|
clientConn.Close()
|
||||||
|
}()
|
||||||
|
}
|
||||||
@@ -62,7 +62,7 @@ func HandleNATSave(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := nat.ApplyRules(&cfg); err != nil {
|
if err := applyAllRules(appCfg); err != nil {
|
||||||
fail(w, http.StatusInternalServerError, "apply: "+err.Error())
|
fail(w, http.StatusInternalServerError, "apply: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
98
handlers/rules.go
Normal file
98
handlers/rules.go
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"alpine-router/config"
|
||||||
|
"alpine-router/firewall"
|
||||||
|
"alpine-router/nat"
|
||||||
|
"alpine-router/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
// applyAllRules rebuilds the complete nftables ruleset from the current config:
|
||||||
|
// NAT masquerade + user firewall rules + VLAN isolation + blocked clients.
|
||||||
|
func applyAllRules(cfg *config.AppConfig) error {
|
||||||
|
if !nat.IsInstalled() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect blocked client IPs.
|
||||||
|
var blockedIPs []string
|
||||||
|
for _, kd := range cfg.KnownDevices {
|
||||||
|
if kd.Blocked {
|
||||||
|
ip := kd.IP
|
||||||
|
if kd.StaticIP != "" {
|
||||||
|
ip = kd.StaticIP
|
||||||
|
}
|
||||||
|
if ip != "" {
|
||||||
|
blockedIPs = append(blockedIPs, ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the LAN interface set for isolation:
|
||||||
|
// all NAT interfaces + all VLAN interfaces (active + pending).
|
||||||
|
// This ensures native interfaces (eth0) and their VLANs (eth0.100) are all
|
||||||
|
// mutually isolated when VLANIsolation is enabled.
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var lanIfaces []string
|
||||||
|
addLAN := func(name string) {
|
||||||
|
if name != "" && !seen[name] {
|
||||||
|
lanIfaces = append(lanIfaces, name)
|
||||||
|
seen[name] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, name := range cfg.NAT.Interfaces {
|
||||||
|
addLAN(name)
|
||||||
|
}
|
||||||
|
names, _ := network.GetInterfaces()
|
||||||
|
for _, name := range names {
|
||||||
|
if network.IsVLAN(name) {
|
||||||
|
addLAN(name)
|
||||||
|
addLAN(network.VLANParent(name)) // include parent (native VLAN) too
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name := range network.GetAllPending() {
|
||||||
|
if network.IsVLAN(name) {
|
||||||
|
addLAN(name)
|
||||||
|
addLAN(network.VLANParent(name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert config.FirewallRule → firewall.Rule.
|
||||||
|
fwRules := make([]firewall.Rule, len(cfg.Firewall.Rules))
|
||||||
|
for i, r := range cfg.Firewall.Rules {
|
||||||
|
fwRules[i] = firewall.Rule{
|
||||||
|
ID: r.ID,
|
||||||
|
Enabled: r.Enabled,
|
||||||
|
Action: r.Action,
|
||||||
|
Protocol: r.Protocol,
|
||||||
|
SrcAddr: r.SrcAddr,
|
||||||
|
SrcPort: r.SrcPort,
|
||||||
|
DstAddr: r.DstAddr,
|
||||||
|
DstPort: r.DstPort,
|
||||||
|
InIface: r.InIface,
|
||||||
|
OutIface: r.OutIface,
|
||||||
|
Comment: r.Comment,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return firewall.ApplyAll(
|
||||||
|
firewall.NATConfig{Interfaces: cfg.NAT.Interfaces},
|
||||||
|
firewall.Config{Rules: fwRules, VLANIsolation: cfg.Firewall.VLANIsolation},
|
||||||
|
blockedIPs,
|
||||||
|
lanIfaces,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyBlockedFirewall is the async helper called after client updates.
|
||||||
|
func applyBlockedFirewall() {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Warning: load config for firewall: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := applyAllRules(cfg); err != nil {
|
||||||
|
log.Printf("Warning: apply firewall rules: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
52
main.go
52
main.go
@@ -11,6 +11,7 @@ import (
|
|||||||
|
|
||||||
"alpine-router/config"
|
"alpine-router/config"
|
||||||
"alpine-router/dhcp"
|
"alpine-router/dhcp"
|
||||||
|
"alpine-router/firewall"
|
||||||
"alpine-router/handlers"
|
"alpine-router/handlers"
|
||||||
"alpine-router/mihomo"
|
"alpine-router/mihomo"
|
||||||
"alpine-router/nat"
|
"alpine-router/nat"
|
||||||
@@ -68,6 +69,9 @@ func main() {
|
|||||||
|
|
||||||
mux.HandleFunc("/api/config.yaml", handlers.HandleConfigYAML)
|
mux.HandleFunc("/api/config.yaml", handlers.HandleConfigYAML)
|
||||||
|
|
||||||
|
mux.HandleFunc("/api/firewall", handlers.HandleFirewall)
|
||||||
|
mux.HandleFunc("/api/firewall/apply", handlers.HandleFirewallApply)
|
||||||
|
|
||||||
mux.HandleFunc("/api/nat", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/api/nat", func(w http.ResponseWriter, r *http.Request) {
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case "GET":
|
case "GET":
|
||||||
@@ -100,6 +104,8 @@ func main() {
|
|||||||
mux.HandleFunc("/api/mihomo/config.yaml", handlers.HandleMihomoConfigYAML)
|
mux.HandleFunc("/api/mihomo/config.yaml", handlers.HandleMihomoConfigYAML)
|
||||||
mux.HandleFunc("/api/mihomo/logs", handlers.HandleMihomoLogs)
|
mux.HandleFunc("/api/mihomo/logs", handlers.HandleMihomoLogs)
|
||||||
mux.HandleFunc("/api/mihomo/upload-core", handlers.HandleMihomoUploadCore)
|
mux.HandleFunc("/api/mihomo/upload-core", handlers.HandleMihomoUploadCore)
|
||||||
|
mux.HandleFunc("/api/mihomo/api/", handlers.HandleMihomoAPIProxy)
|
||||||
|
mux.HandleFunc("/api/mihomo/ws/", handlers.HandleMihomoWSProxy)
|
||||||
|
|
||||||
sub, err := fs.Sub(publicFS, "public")
|
sub, err := fs.Sub(publicFS, "public")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -227,13 +233,51 @@ func applyConfig(cfg *config.AppConfig) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := nat.ApplyRulesWithBlocked(natCfg, blockedIPs); err != nil {
|
// Build LAN interface set: NAT interfaces + all VLAN interfaces + their parents.
|
||||||
log.Printf("Warning: apply NAT: %v", err)
|
seenLAN := map[string]bool{}
|
||||||
|
var lanIfaces []string
|
||||||
|
addLAN := func(name string) {
|
||||||
|
if name != "" && !seenLAN[name] {
|
||||||
|
lanIfaces = append(lanIfaces, name)
|
||||||
|
seenLAN[name] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, name := range cfg.NAT.Interfaces {
|
||||||
|
addLAN(name)
|
||||||
|
}
|
||||||
|
if names, err := network.GetInterfaces(); err == nil {
|
||||||
|
for _, name := range names {
|
||||||
|
if network.IsVLAN(name) {
|
||||||
|
addLAN(name)
|
||||||
|
addLAN(network.VLANParent(name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert config firewall rules.
|
||||||
|
fwRules := make([]firewall.Rule, len(cfg.Firewall.Rules))
|
||||||
|
for i, r := range cfg.Firewall.Rules {
|
||||||
|
fwRules[i] = firewall.Rule{
|
||||||
|
ID: r.ID, Enabled: r.Enabled, Action: r.Action, Protocol: r.Protocol,
|
||||||
|
SrcAddr: r.SrcAddr, SrcPort: r.SrcPort, DstAddr: r.DstAddr, DstPort: r.DstPort,
|
||||||
|
InIface: r.InIface, OutIface: r.OutIface, Comment: r.Comment,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err := firewall.ApplyAll(
|
||||||
|
firewall.NATConfig{Interfaces: cfg.NAT.Interfaces},
|
||||||
|
firewall.Config{Rules: fwRules, VLANIsolation: cfg.Firewall.VLANIsolation},
|
||||||
|
blockedIPs,
|
||||||
|
lanIfaces,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Warning: apply firewall/NAT rules: %v", err)
|
||||||
} else {
|
} else {
|
||||||
log.Printf("NAT rules applied (%d interfaces, %d blocked clients)", len(cfg.NAT.Interfaces), len(blockedIPs))
|
log.Printf("Firewall/NAT applied (%d NAT ifaces, %d fw rules, %d blocked, vlan_isolation=%v)",
|
||||||
|
len(cfg.NAT.Interfaces), len(fwRules), len(blockedIPs), cfg.Firewall.VLANIsolation)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.Printf("nftables not installed — NAT unavailable (install with: apk add nftables)")
|
log.Printf("nftables not installed — NAT/firewall unavailable (install with: apk add nftables)")
|
||||||
}
|
}
|
||||||
|
|
||||||
if dhcp.IsInstalled() {
|
if dhcp.IsInstalled() {
|
||||||
|
|||||||
65
nat/nat.go
65
nat/nat.go
@@ -6,19 +6,13 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const tableName = "alpine-router-nat"
|
|
||||||
|
|
||||||
// Config holds NAT masquerade settings per interface.
|
// Config holds NAT masquerade settings per interface.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
// Interfaces is the list of LAN interface names for which masquerade is enabled.
|
|
||||||
// Traffic arriving on these interfaces will be NATted to the outgoing WAN interface.
|
|
||||||
Interfaces []string `json:"interfaces"`
|
Interfaces []string `json:"interfaces"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// configPath returns the path to nat.json next to the running binary.
|
|
||||||
func configPath() string {
|
func configPath() string {
|
||||||
exe, err := os.Executable()
|
exe, err := os.Executable()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -34,7 +28,6 @@ func IsInstalled() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Load reads the NAT config from disk.
|
// Load reads the NAT config from disk.
|
||||||
// Returns an empty config if the file does not exist yet.
|
|
||||||
func Load() (*Config, error) {
|
func Load() (*Config, error) {
|
||||||
data, err := os.ReadFile(configPath())
|
data, err := os.ReadFile(configPath())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -53,7 +46,7 @@ func Load() (*Config, error) {
|
|||||||
return &cfg, nil
|
return &cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save writes the NAT config to the configs/ directory next to the binary.
|
// Save writes the NAT config to the configs/ directory.
|
||||||
func Save(cfg *Config) error {
|
func Save(cfg *Config) error {
|
||||||
p := configPath()
|
p := configPath()
|
||||||
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
|
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
|
||||||
@@ -65,59 +58,3 @@ func Save(cfg *Config) error {
|
|||||||
}
|
}
|
||||||
return os.WriteFile(p, data, 0644)
|
return os.WriteFile(p, data, 0644)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ApplyRules flushes the existing alpine-router NAT table and recreates it
|
|
||||||
// from the provided config. Called on every daemon startup and on config save.
|
|
||||||
//
|
|
||||||
// nftables is used instead of iptables because it applies all rules atomically
|
|
||||||
// in a single kernel call, which is faster and avoids partial-state issues.
|
|
||||||
func ApplyRules(cfg *Config) error {
|
|
||||||
return ApplyRulesWithBlocked(cfg, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ApplyRulesWithBlocked is like ApplyRules but also installs drop rules for
|
|
||||||
// the given list of blocked client IPs.
|
|
||||||
func ApplyRulesWithBlocked(cfg *Config, blockedIPs []string) error {
|
|
||||||
if err := os.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte("1"), 0644); err != nil {
|
|
||||||
return fmt.Errorf("enable ip_forward: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
exec.Command("nft", "delete", "table", "ip", tableName).Run()
|
|
||||||
|
|
||||||
if len(cfg.Interfaces) == 0 && len(blockedIPs) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var sb strings.Builder
|
|
||||||
fmt.Fprintf(&sb, "table ip %s {\n", tableName)
|
|
||||||
|
|
||||||
sb.WriteString(" chain forward {\n")
|
|
||||||
sb.WriteString(" type filter hook forward priority filter; policy drop;\n")
|
|
||||||
sb.WriteString(" ct state established,related accept\n")
|
|
||||||
|
|
||||||
for _, ip := range blockedIPs {
|
|
||||||
fmt.Fprintf(&sb, " ip saddr %s drop\n", ip)
|
|
||||||
fmt.Fprintf(&sb, " ip daddr %s drop\n", ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, iface := range cfg.Interfaces {
|
|
||||||
fmt.Fprintf(&sb, " iifname \"%s\" accept\n", iface)
|
|
||||||
}
|
|
||||||
sb.WriteString(" }\n")
|
|
||||||
|
|
||||||
sb.WriteString(" chain postrouting {\n")
|
|
||||||
sb.WriteString(" type nat hook postrouting priority srcnat; policy accept;\n")
|
|
||||||
for _, iface := range cfg.Interfaces {
|
|
||||||
fmt.Fprintf(&sb, " iifname \"%s\" masquerade\n", iface)
|
|
||||||
}
|
|
||||||
sb.WriteString(" }\n")
|
|
||||||
sb.WriteString("}\n")
|
|
||||||
|
|
||||||
cmd := exec.Command("nft", "-f", "-")
|
|
||||||
cmd.Stdin = strings.NewReader(sb.String())
|
|
||||||
out, err := cmd.CombinedOutput()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("nft apply: %s: %w", strings.TrimSpace(string(out)), err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -72,6 +72,13 @@ func ApplyPending() map[string]error {
|
|||||||
ClearPendingConfig(name)
|
ClearPendingConfig(name)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// For VLAN interfaces ensure the kernel interface exists before ifup.
|
||||||
|
if IsVLAN(name) {
|
||||||
|
if err := EnsureVLANExists(name); err != nil {
|
||||||
|
errs[name] = err
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
_ = IfDown(name)
|
_ = IfDown(name)
|
||||||
if cfg := configs[name]; cfg != nil && cfg.Auto {
|
if cfg := configs[name]; cfg != nil && cfg.Auto {
|
||||||
if err := IfUp(name); err != nil {
|
if err := IfUp(name); err != nil {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ const ConfigFile = "/etc/network/interfaces"
|
|||||||
// InterfaceConfig represents one stanza in /etc/network/interfaces.
|
// InterfaceConfig represents one stanza in /etc/network/interfaces.
|
||||||
type InterfaceConfig struct {
|
type InterfaceConfig struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
Label string `json:"label,omitempty"` // display name, stored in config.yaml only
|
||||||
Auto bool `json:"auto"`
|
Auto bool `json:"auto"`
|
||||||
Mode string `json:"mode"` // dhcp, static, loopback, manual
|
Mode string `json:"mode"` // dhcp, static, loopback, manual
|
||||||
Address string `json:"address,omitempty"` // static only
|
Address string `json:"address,omitempty"` // static only
|
||||||
@@ -154,12 +155,18 @@ func WriteConfig(configs map[string]*InterfaceConfig) error {
|
|||||||
}
|
}
|
||||||
defer f.Close()
|
defer f.Close()
|
||||||
|
|
||||||
// loopback first
|
// loopback first, then physical interfaces, then VLANs (sorted within each group)
|
||||||
if lo, ok := configs["lo"]; ok {
|
if lo, ok := configs["lo"]; ok {
|
||||||
writeStanza(f, lo)
|
writeStanza(f, lo)
|
||||||
}
|
}
|
||||||
for name, cfg := range configs {
|
for name, cfg := range configs {
|
||||||
if name == "lo" {
|
if name == "lo" || IsVLAN(name) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
writeStanza(f, cfg)
|
||||||
|
}
|
||||||
|
for name, cfg := range configs {
|
||||||
|
if !IsVLAN(name) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
writeStanza(f, cfg)
|
writeStanza(f, cfg)
|
||||||
@@ -188,6 +195,12 @@ func writeStanza(f *os.File, c *InterfaceConfig) {
|
|||||||
fmt.Fprintf(f, "\tdns-nameservers %s\n", strings.Join(c.DNS, " "))
|
fmt.Fprintf(f, "\tdns-nameservers %s\n", strings.Join(c.DNS, " "))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// VLAN interfaces need vlan-raw-device unless already in Extra
|
||||||
|
if IsVLAN(c.Name) {
|
||||||
|
if _, ok := c.Extra["vlan-raw-device"]; !ok {
|
||||||
|
fmt.Fprintf(f, "\tvlan-raw-device %s\n", VLANParent(c.Name))
|
||||||
|
}
|
||||||
|
}
|
||||||
for k, v := range c.Extra {
|
for k, v := range c.Extra {
|
||||||
fmt.Fprintf(f, "\t%s %s\n", k, v)
|
fmt.Fprintf(f, "\t%s %s\n", k, v)
|
||||||
}
|
}
|
||||||
|
|||||||
80
network/vlan.go
Normal file
80
network/vlan.go
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
package network
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsVLAN reports whether name is a VLAN interface (e.g. "eth0.100").
|
||||||
|
func IsVLAN(name string) bool {
|
||||||
|
idx := strings.LastIndex(name, ".")
|
||||||
|
if idx <= 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
suffix := name[idx+1:]
|
||||||
|
if suffix == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, err := strconv.Atoi(suffix)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VLANParent returns the parent interface (e.g. "eth0.100" → "eth0").
|
||||||
|
func VLANParent(name string) string {
|
||||||
|
idx := strings.LastIndex(name, ".")
|
||||||
|
if idx < 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return name[:idx]
|
||||||
|
}
|
||||||
|
|
||||||
|
// VLANId returns the VLAN ID (e.g. "eth0.100" → 100).
|
||||||
|
func VLANId(name string) int {
|
||||||
|
idx := strings.LastIndex(name, ".")
|
||||||
|
if idx < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
id, _ := strconv.Atoi(name[idx+1:])
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureVLANExists creates the VLAN interface in the kernel if it doesn't exist.
|
||||||
|
func EnsureVLANExists(name string) error {
|
||||||
|
if _, err := os.Stat("/sys/class/net/" + name); err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
parent := VLANParent(name)
|
||||||
|
id := VLANId(name)
|
||||||
|
if parent == "" || id == 0 {
|
||||||
|
return fmt.Errorf("invalid VLAN name: %s", name)
|
||||||
|
}
|
||||||
|
out, err := exec.Command("ip", "link", "add", "link", parent,
|
||||||
|
"name", name, "type", "vlan", "id", strconv.Itoa(id)).CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("ip link add %s: %s", name, strings.TrimSpace(string(out)))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteVLAN brings down and removes a VLAN interface and its /etc/network/interfaces stanza.
|
||||||
|
func DeleteVLAN(name string) error {
|
||||||
|
_ = IfDown(name)
|
||||||
|
if _, err := os.Stat("/sys/class/net/" + name); err == nil {
|
||||||
|
out, err2 := exec.Command("ip", "link", "delete", name).CombinedOutput()
|
||||||
|
if err2 != nil {
|
||||||
|
return fmt.Errorf("ip link delete %s: %s", name, strings.TrimSpace(string(out)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
configs, err := ParseConfig()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, ok := configs[name]; ok {
|
||||||
|
delete(configs, name)
|
||||||
|
return WriteConfig(configs)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
255
public/app.js
255
public/app.js
@@ -5,7 +5,8 @@
|
|||||||
const state = {
|
const state = {
|
||||||
interfaces: [], // latest data from /api/interfaces
|
interfaces: [], // latest data from /api/interfaces
|
||||||
pending: [], // interface names with pending config
|
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
|
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 post = (path, body) => api('POST', path, body);
|
||||||
const del = (path) => api('DELETE', path);
|
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 ───────────────────────────────────────────────────────────
|
// ── Format helpers ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function fmtBytes(n) {
|
function fmtBytes(n) {
|
||||||
@@ -50,15 +64,49 @@ function modeLabel(m) {
|
|||||||
return { dhcp: 'DHCP', static: 'Static', loopback: 'Loopback', manual: 'Manual' }[m] || (m || '?');
|
return { dhcp: 'DHCP', static: 'Static', loopback: 'Loopback', manual: 'Manual' }[m] || (m || '?');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── SVG icons ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const ICON = {
|
||||||
|
pencil: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||||
|
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
|
||||||
|
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
|
||||||
|
</svg>`,
|
||||||
|
restart: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15">
|
||||||
|
<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>`,
|
||||||
|
trash: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
||||||
|
<path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6"/>
|
||||||
|
</svg>`,
|
||||||
|
plus: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13">
|
||||||
|
<path d="M12 5v14M5 12h14"/>
|
||||||
|
</svg>`,
|
||||||
|
};
|
||||||
|
|
||||||
// ── Render ───────────────────────────────────────────────────────────────────
|
// ── Render ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function renderAll() {
|
function renderAll() {
|
||||||
const grid = document.getElementById('ifaceGrid');
|
const grid = document.getElementById('ifaceGrid');
|
||||||
grid.innerHTML = '';
|
grid.innerHTML = '';
|
||||||
|
|
||||||
state.interfaces.forEach(iface => {
|
// Group VLANs by parent
|
||||||
grid.appendChild(buildCard(iface));
|
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');
|
document.getElementById('loading').classList.add('hidden');
|
||||||
grid.classList.remove('hidden');
|
grid.classList.remove('hidden');
|
||||||
@@ -66,9 +114,12 @@ function renderAll() {
|
|||||||
renderPendingBanner();
|
renderPendingBanner();
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildCard(iface) {
|
function buildCard(iface, vlans) {
|
||||||
const hasPending = state.pending.includes(iface.name);
|
const hasPending = state.pending.includes(iface.name);
|
||||||
const sc = stateClass(iface.state);
|
const sc = stateClass(iface.state);
|
||||||
|
const isLo = iface.name === 'lo' || iface.mode === 'loopback';
|
||||||
|
const isUp = iface.state === 'up';
|
||||||
|
const label = iface.label || '';
|
||||||
|
|
||||||
const card = document.createElement('div');
|
const card = document.createElement('div');
|
||||||
card.className = 'iface-card' + (hasPending ? ' has-pending' : '');
|
card.className = 'iface-card' + (hasPending ? ' has-pending' : '');
|
||||||
@@ -78,23 +129,24 @@ function buildCard(iface) {
|
|||||||
`<div class="info-row"><span class="info-label">IPv6</span><span class="info-val">${a}</span></div>`
|
`<div class="info-row"><span class="info-label">IPv6</span><span class="info-val">${a}</span></div>`
|
||||||
).join('');
|
).join('');
|
||||||
|
|
||||||
|
const nameBlock = label
|
||||||
|
? `<div class="card-name-stack">
|
||||||
|
<span class="card-label-text">${label}</span>
|
||||||
|
<span class="card-iface-sub">${iface.name}</span>
|
||||||
|
</div>`
|
||||||
|
: `<span class="card-iface-name">${iface.name}</span>`;
|
||||||
|
|
||||||
card.innerHTML = `
|
card.innerHTML = `
|
||||||
<div class="card-header">
|
<div class="card-header">
|
||||||
<div class="card-name">
|
<div class="card-name">
|
||||||
<span class="state-dot ${sc}"></span>
|
<span class="state-dot ${sc}"></span>
|
||||||
<span>${iface.name}</span>
|
${nameBlock}
|
||||||
${hasPending ? '<span class="pending-badge">несохранено</span>' : ''}
|
${hasPending ? '<span class="pending-badge">несохранено</span>' : ''}
|
||||||
</div>
|
</div>
|
||||||
<div style="display:flex;gap:6px;align-items:center">
|
<span class="mode-badge ${iface.mode || 'unknown'}">${modeLabel(iface.mode)}</span>
|
||||||
<span class="mode-badge ${iface.mode || 'unknown'}">${modeLabel(iface.mode)}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card-info">
|
<div class="card-info">
|
||||||
<div class="info-row">
|
|
||||||
<span class="info-label">Статус</span>
|
|
||||||
<span class="info-val">${iface.state || 'unknown'}</span>
|
|
||||||
</div>
|
|
||||||
<div class="info-row">
|
<div class="info-row">
|
||||||
<span class="info-label">IPv4</span>
|
<span class="info-label">IPv4</span>
|
||||||
<span class="info-val">${iface.ipv4
|
<span class="info-val">${iface.ipv4
|
||||||
@@ -106,14 +158,13 @@ function buildCard(iface) {
|
|||||||
<span class="info-label">Шлюз</span>
|
<span class="info-label">Шлюз</span>
|
||||||
<span class="info-val">${iface.gateway || '<span class="none">—</span>'}</span>
|
<span class="info-val">${iface.gateway || '<span class="none">—</span>'}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="traffic-row">
|
<div class="traffic-row">
|
||||||
<div class="traffic-item">
|
<div class="traffic-item">
|
||||||
<span class="traffic-label">RX</span>
|
<span class="traffic-label">↓ RX</span>
|
||||||
<span class="traffic-val">${fmtBytes(iface.rx_bytes)}</span>
|
<span class="traffic-val">${fmtBytes(iface.rx_bytes)}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="traffic-item">
|
<div class="traffic-item">
|
||||||
<span class="traffic-label">TX</span>
|
<span class="traffic-label">↑ TX</span>
|
||||||
<span class="traffic-val">${fmtBytes(iface.tx_bytes)}</span>
|
<span class="traffic-val">${fmtBytes(iface.tx_bytes)}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="traffic-item">
|
<div class="traffic-item">
|
||||||
@@ -124,16 +175,72 @@ function buildCard(iface) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card-actions">
|
<div class="card-actions">
|
||||||
<button class="btn btn-success btn-sm" data-action="up" data-iface="${iface.name}">ON</button>
|
${!isLo ? `
|
||||||
<button class="btn btn-danger btn-sm" data-action="down" data-iface="${iface.name}">OFF</button>
|
<label class="toggle-label iface-power-toggle" title="${isUp ? 'Выключить интерфейс' : 'Включить интерфейс'}">
|
||||||
<button class="btn btn-ghost btn-sm" data-action="restart" data-iface="${iface.name}">RESTART</button>
|
<input type="checkbox" ${isUp ? 'checked' : ''} data-action="toggle" data-iface="${iface.name}">
|
||||||
<button class="btn btn-primary btn-sm" data-action="config" data-iface="${iface.name}" style="margin-left:auto">CONFIG</button>
|
<span class="toggle-slider"></span>
|
||||||
|
<span class="iface-toggle-label">${isUp ? 'Вкл' : 'Выкл'}</span>
|
||||||
|
</label>
|
||||||
|
<button class="btn-icon" data-action="restart" data-iface="${iface.name}" title="Перезапустить">${ICON.restart}</button>
|
||||||
|
` : ''}
|
||||||
|
<button class="btn-icon btn-icon-accent" data-action="config" data-iface="${iface.name}" title="Настроить" style="margin-left:auto">${ICON.pencil}</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
${!isLo ? buildVLANSection(iface.name, vlans) : ''}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
return card;
|
return card;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function buildVLANSection(parentName, vlans) {
|
||||||
|
const rows = vlans.map(v => {
|
||||||
|
const sc = stateClass(v.state);
|
||||||
|
const hasPending = state.pending.includes(v.name);
|
||||||
|
const isUp = v.state === 'up';
|
||||||
|
const label = v.label || '';
|
||||||
|
const ip = v.ipv4
|
||||||
|
? v.ipv4 + (v.ipv4_mask ? ' / ' + v.ipv4_mask : '')
|
||||||
|
: '<span class="none">—</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>
|
||||||
|
${label
|
||||||
|
? `<div class="vlan-name-stack"><span class="vlan-label-text">${label}</span><span class="vlan-iface-name">${v.name}</span></div>`
|
||||||
|
: `<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">
|
||||||
|
<label class="toggle-label" title="${isUp ? 'Выключить' : 'Включить'}">
|
||||||
|
<input type="checkbox" ${isUp ? 'checked' : ''} data-action="toggle" data-iface="${v.name}">
|
||||||
|
<span class="toggle-slider toggle-sm"></span>
|
||||||
|
</label>
|
||||||
|
<button class="btn-icon" data-action="config" data-iface="${v.name}" title="Настроить">${ICON.pencil}</button>
|
||||||
|
<button class="btn-icon btn-icon-danger" data-action="delete" data-iface="${v.name}" title="Удалить VLAN">${ICON.trash}</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}">${ICON.plus} Добавить</button>
|
||||||
|
</div>
|
||||||
|
<div class="vlan-list">
|
||||||
|
${rows}
|
||||||
|
${empty}
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
function renderPendingBanner() {
|
function renderPendingBanner() {
|
||||||
const banner = document.getElementById('pendingBanner');
|
const banner = document.getElementById('pendingBanner');
|
||||||
const list = document.getElementById('pendingList');
|
const list = document.getElementById('pendingList');
|
||||||
@@ -164,8 +271,17 @@ async function loadAll() {
|
|||||||
// ── Interface actions ─────────────────────────────────────────────────────────
|
// ── Interface actions ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
async function doAction(name, action) {
|
async function doAction(name, action) {
|
||||||
const btn = document.querySelector(`[data-action="${action}"][data-iface="${name}"]`);
|
if (action === 'delete') {
|
||||||
if (btn) { btn.disabled = true; btn.textContent = '...'; }
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await post(`/api/interfaces/${name}/${action}`);
|
await post(`/api/interfaces/${name}/${action}`);
|
||||||
@@ -173,8 +289,7 @@ async function doAction(name, action) {
|
|||||||
await loadAll();
|
await loadAll();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
showToast(`${name} ${action}: ${e.message}`, 'error');
|
showToast(`${name} ${action}: ${e.message}`, 'error');
|
||||||
} finally {
|
await loadAll(); // refresh to restore correct toggle state
|
||||||
if (btn) btn.disabled = false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,22 +297,56 @@ async function doAction(name, action) {
|
|||||||
|
|
||||||
async function openConfig(name) {
|
async function openConfig(name) {
|
||||||
state.configModal = name;
|
state.configModal = name;
|
||||||
|
state.configModalParent = null;
|
||||||
document.getElementById('modalTitle').textContent = `Настройка: ${name}`;
|
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 {
|
try {
|
||||||
const [{ config, pending }, natData] = await Promise.all([
|
const [configData, natData] = await Promise.all([
|
||||||
get(`/api/config/${name}`),
|
get(`/api/config/${name}`),
|
||||||
get('/api/nat').catch(() => null),
|
get('/api/nat').catch(() => null),
|
||||||
]);
|
]);
|
||||||
if (natData) state.nat = natData;
|
if (natData) state.nat = natData;
|
||||||
fillForm(config, pending, name);
|
fillForm(configData.config, configData.pending, name, configData.label || '');
|
||||||
document.getElementById('modal').classList.remove('hidden');
|
document.getElementById('modal').classList.remove('hidden');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
showToast('Ошибка загрузки конфига: ' + e.message, 'error');
|
showToast('Ошибка загрузки конфига: ' + e.message, 'error');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function fillForm(cfg, pending, 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, label = '') {
|
||||||
|
document.getElementById('cfgLabel').value = label;
|
||||||
document.getElementById('cfgAuto').checked = !!cfg.auto;
|
document.getElementById('cfgAuto').checked = !!cfg.auto;
|
||||||
document.getElementById('cfgAddress').value = cfg.address || '';
|
document.getElementById('cfgAddress').value = cfg.address || '';
|
||||||
document.getElementById('cfgNetmask').value = cfg.netmask || '';
|
document.getElementById('cfgNetmask').value = cfg.netmask || '';
|
||||||
@@ -207,10 +356,8 @@ function fillForm(cfg, pending, name) {
|
|||||||
const mode = cfg.mode === 'static' ? 'static' : 'dhcp';
|
const mode = cfg.mode === 'static' ? 'static' : 'dhcp';
|
||||||
setMode(mode);
|
setMode(mode);
|
||||||
|
|
||||||
// Mark pending visually
|
if (pending && name) {
|
||||||
const title = document.getElementById('modalTitle');
|
document.getElementById('modalTitle').textContent = `Настройка: ${name} (несохранённые изменения)`;
|
||||||
if (pending) {
|
|
||||||
title.textContent = `Настройка: ${state.configModal} (несохранённые изменения)`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NAT section — show for all non-loopback interfaces
|
// NAT section — show for all non-loopback interfaces
|
||||||
@@ -244,15 +391,34 @@ function closeModal() {
|
|||||||
document.getElementById('modal').classList.add('hidden');
|
document.getElementById('modal').classList.add('hidden');
|
||||||
document.getElementById('configForm').reset();
|
document.getElementById('configForm').reset();
|
||||||
state.configModal = null;
|
state.configModal = null;
|
||||||
|
state.configModalParent = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveConfig() {
|
async function saveConfig() {
|
||||||
const name = state.configModal;
|
let name = state.configModal;
|
||||||
if (!name) return;
|
|
||||||
|
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 (1–4094)', '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 mode = currentMode();
|
||||||
const cfg = {
|
const cfg = {
|
||||||
name,
|
name,
|
||||||
|
label: document.getElementById('cfgLabel').value.trim(),
|
||||||
auto: document.getElementById('cfgAuto').checked,
|
auto: document.getElementById('cfgAuto').checked,
|
||||||
mode,
|
mode,
|
||||||
address: document.getElementById('cfgAddress').value.trim(),
|
address: document.getElementById('cfgAddress').value.trim(),
|
||||||
@@ -262,7 +428,6 @@ async function saveConfig() {
|
|||||||
extra: {},
|
extra: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
// Basic validation for static
|
|
||||||
if (mode === 'static' && !cfg.address) {
|
if (mode === 'static' && !cfg.address) {
|
||||||
showToast('Укажите IP-адрес', 'error');
|
showToast('Укажите IP-адрес', 'error');
|
||||||
return;
|
return;
|
||||||
@@ -315,7 +480,6 @@ async function discardAll() {
|
|||||||
}
|
}
|
||||||
state.pending = [];
|
state.pending = [];
|
||||||
renderPendingBanner();
|
renderPendingBanner();
|
||||||
renderAll();
|
|
||||||
showToast('Изменения отменены', 'info');
|
showToast('Изменения отменены', 'info');
|
||||||
await loadAll();
|
await loadAll();
|
||||||
}
|
}
|
||||||
@@ -335,22 +499,33 @@ function showToast(msg, type = 'info') {
|
|||||||
// ── Event wiring ──────────────────────────────────────────────────────────────
|
// ── Event wiring ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
document.getElementById('refreshBtn').addEventListener('click', loadAll);
|
document.getElementById('refreshBtn').addEventListener('click', loadAll);
|
||||||
|
|
||||||
document.getElementById('applyBtn').addEventListener('click', applyAll);
|
document.getElementById('applyBtn').addEventListener('click', applyAll);
|
||||||
document.getElementById('discardAllBtn').addEventListener('click', discardAll);
|
document.getElementById('discardAllBtn').addEventListener('click', discardAll);
|
||||||
|
|
||||||
// Card action buttons (delegated)
|
// Card button clicks (delegated)
|
||||||
document.getElementById('ifaceGrid').addEventListener('click', e => {
|
document.getElementById('ifaceGrid').addEventListener('click', e => {
|
||||||
const btn = e.target.closest('[data-action]');
|
const btn = e.target.closest('[data-action]');
|
||||||
if (!btn) return;
|
if (!btn) return;
|
||||||
|
// Don't handle toggle inputs here (handled by 'change' below)
|
||||||
|
if (btn.tagName === 'INPUT' && btn.type === 'checkbox') return;
|
||||||
const { action, iface } = btn.dataset;
|
const { action, iface } = btn.dataset;
|
||||||
|
if (!action || !iface) return;
|
||||||
if (action === 'config') {
|
if (action === 'config') {
|
||||||
openConfig(iface);
|
openConfig(iface);
|
||||||
|
} else if (action === 'addvlan') {
|
||||||
|
openNewVLAN(iface);
|
||||||
} else {
|
} else {
|
||||||
doAction(iface, action);
|
doAction(iface, action);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Toggle switch (on/off) — delegated change event
|
||||||
|
document.getElementById('ifaceGrid').addEventListener('change', e => {
|
||||||
|
const input = e.target.closest('input[data-action="toggle"]');
|
||||||
|
if (!input) return;
|
||||||
|
doAction(input.dataset.iface, input.checked ? 'up' : 'down');
|
||||||
|
});
|
||||||
|
|
||||||
// Modal close
|
// Modal close
|
||||||
document.getElementById('closeModal').addEventListener('click', closeModal);
|
document.getElementById('closeModal').addEventListener('click', closeModal);
|
||||||
document.getElementById('cancelConfigBtn').addEventListener('click', closeModal);
|
document.getElementById('cancelConfigBtn').addEventListener('click', closeModal);
|
||||||
@@ -378,11 +553,5 @@ setInterval(loadAll, 10000);
|
|||||||
// ── Init ──────────────────────────────────────────────────────────────────────
|
// ── Init ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
// Try to get hostname
|
|
||||||
try {
|
|
||||||
const res = await fetch('/api/interfaces');
|
|
||||||
// hostname from Location header or just skip
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
await loadAll();
|
await loadAll();
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -50,9 +50,17 @@
|
|||||||
</svg>
|
</svg>
|
||||||
Клиенты
|
Клиенты
|
||||||
</a>
|
</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">
|
<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="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>
|
</svg>
|
||||||
Прокси
|
Прокси
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -50,9 +50,17 @@
|
|||||||
</svg>
|
</svg>
|
||||||
Клиенты
|
Клиенты
|
||||||
</a>
|
</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">
|
<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="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>
|
</svg>
|
||||||
Прокси
|
Прокси
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
234
public/firewall.html
Normal file
234
public/firewall.html
Normal 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
330
public/firewall.js
Normal 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, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 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();
|
||||||
@@ -62,9 +62,17 @@
|
|||||||
</svg>
|
</svg>
|
||||||
Клиенты
|
Клиенты
|
||||||
</a>
|
</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">
|
<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="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>
|
</svg>
|
||||||
Прокси
|
Прокси
|
||||||
</a>
|
</a>
|
||||||
@@ -88,6 +96,21 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form id="configForm" autocomplete="off">
|
<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">(1–4094)</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 for="cfgLabel">Название (метка)</label>
|
||||||
|
<input type="text" id="cfgLabel" placeholder="Например: WAN, LAN, Гости…" style="font-family:inherit">
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<label class="checkbox-label">
|
<label class="checkbox-label">
|
||||||
<input type="checkbox" id="cfgAuto">
|
<input type="checkbox" id="cfgAuto">
|
||||||
|
|||||||
1415
public/proxy.html
1415
public/proxy.html
File diff suppressed because it is too large
Load Diff
2149
public/proxy.js
2149
public/proxy.js
File diff suppressed because it is too large
Load Diff
679
public/style.css
679
public/style.css
@@ -1123,6 +1123,421 @@ select {
|
|||||||
padding-right: 30px;
|
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; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Icon-only action buttons ── */
|
||||||
|
.btn-icon-accent {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
.btn-icon-accent:hover {
|
||||||
|
color: var(--accent-h);
|
||||||
|
background: rgba(0, 212, 255, 0.1);
|
||||||
|
text-shadow: 0 0 8px var(--accent-glow);
|
||||||
|
}
|
||||||
|
.btn-icon-danger {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.btn-icon-danger:hover {
|
||||||
|
color: var(--danger);
|
||||||
|
background: rgba(255, 51, 102, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Card power toggle ── */
|
||||||
|
.iface-power-toggle {
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.iface-toggle-label {
|
||||||
|
font-size: .78rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-dim);
|
||||||
|
min-width: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Small toggle (VLAN rows) ── */
|
||||||
|
.toggle-sm {
|
||||||
|
width: 30px !important;
|
||||||
|
height: 17px !important;
|
||||||
|
border-radius: 9px !important;
|
||||||
|
}
|
||||||
|
.toggle-sm::after {
|
||||||
|
width: 11px !important;
|
||||||
|
height: 11px !important;
|
||||||
|
}
|
||||||
|
.toggle-label input:checked + .toggle-sm::after {
|
||||||
|
transform: translateX(13px) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Card name with label ── */
|
||||||
|
.card-name-stack {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1px;
|
||||||
|
}
|
||||||
|
.card-label-text {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.card-iface-sub {
|
||||||
|
font-size: .72rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||||
|
}
|
||||||
|
.card-iface-name {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── VLAN label in row ── */
|
||||||
|
.vlan-name-stack {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0;
|
||||||
|
}
|
||||||
|
.vlan-label-text {
|
||||||
|
font-size: .82rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.vlan-iface-name {
|
||||||
|
font-size: .72rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Proxy form helpers ── */
|
||||||
|
.field-select {
|
||||||
|
background: var(--bg-deep);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
color: var(--text);
|
||||||
|
padding: 9px 12px;
|
||||||
|
font-size: .9rem;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.mono-ta {
|
||||||
|
background: var(--bg-deep);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
color: var(--text);
|
||||||
|
padding: 9px 12px;
|
||||||
|
font-size: .85rem;
|
||||||
|
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||||
|
width: 100%;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
.settings-section-title {
|
||||||
|
color: var(--accent);
|
||||||
|
font-size: .85rem;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: .05em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.pf-section-title {
|
||||||
|
font-size: .8rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--accent);
|
||||||
|
letter-spacing: .05em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
.pf-subsection-title {
|
||||||
|
font-size: .78rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-muted);
|
||||||
|
letter-spacing: .04em;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Scanline overlay (subtle futuristic effect) ── */
|
/* ── Scanline overlay (subtle futuristic effect) ── */
|
||||||
body::after {
|
body::after {
|
||||||
content: '';
|
content: '';
|
||||||
@@ -1138,3 +1553,267 @@ body::after {
|
|||||||
rgba(0, 212, 255, 0.008) 4px
|
rgba(0, 212, 255, 0.008) 4px
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Dashboard ── */
|
||||||
|
.dash-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 16px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.dash-grid { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
.dash-card {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 18px;
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
}
|
||||||
|
.dash-card-title {
|
||||||
|
font-size: .85rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--accent);
|
||||||
|
letter-spacing: .05em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
.dash-traffic-card {
|
||||||
|
border-color: rgba(0, 212, 255, 0.15);
|
||||||
|
}
|
||||||
|
.dash-traffic-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 24px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
.dash-traffic-item {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
.dash-traffic-label {
|
||||||
|
font-size: .72rem;
|
||||||
|
color: var(--muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: .06em;
|
||||||
|
}
|
||||||
|
.dash-traffic-val {
|
||||||
|
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
color: var(--accent);
|
||||||
|
text-shadow: 0 0 8px rgba(0, 212, 255, 0.15);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.dash-traffic-total {
|
||||||
|
font-size: .95rem;
|
||||||
|
color: var(--text-dim);
|
||||||
|
text-shadow: none;
|
||||||
|
}
|
||||||
|
.dash-mem-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding-top: 8px;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
.dash-mode-switch {
|
||||||
|
display: flex;
|
||||||
|
background: var(--bg-deep);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
padding: 3px;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
.dash-mode-switch .seg-btn {
|
||||||
|
flex: 1;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: none;
|
||||||
|
border-radius: calc(var(--radius-sm) - 2px);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--muted);
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: .85rem;
|
||||||
|
font-weight: 600;
|
||||||
|
transition: all .2s ease;
|
||||||
|
}
|
||||||
|
.dash-mode-switch .seg-btn.active {
|
||||||
|
background: linear-gradient(135deg, #0090b3, #00d4ff);
|
||||||
|
color: #fff;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 212, 255, 0.2);
|
||||||
|
}
|
||||||
|
.dash-mode-switch .seg-btn:not(.active):hover { background: var(--surface-3); color: var(--text); }
|
||||||
|
|
||||||
|
.dash-info-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.dash-section {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
.dash-section-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.dash-section-header h3 {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 700;
|
||||||
|
background: linear-gradient(135deg, var(--text), var(--accent));
|
||||||
|
-webkit-background-clip: text;
|
||||||
|
-webkit-text-fill-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dash-group-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.dash-group-card {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
overflow: hidden;
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
transition: all .3s ease;
|
||||||
|
}
|
||||||
|
.dash-group-card:hover {
|
||||||
|
border-color: var(--border-hi);
|
||||||
|
box-shadow: var(--glow-sm);
|
||||||
|
}
|
||||||
|
.dash-group-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.dash-group-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.dash-group-name {
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: .95rem;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.dash-proxy-list {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||||
|
gap: 6px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
}
|
||||||
|
.dash-proxy-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 6px 10px;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--surface-2);
|
||||||
|
border: 1px solid transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all .15s ease;
|
||||||
|
font-size: .82rem;
|
||||||
|
}
|
||||||
|
.dash-proxy-item:hover {
|
||||||
|
border-color: var(--border-hi);
|
||||||
|
background: var(--surface-3);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
.dash-proxy-item.dash-proxy-active {
|
||||||
|
border-color: rgba(0, 255, 136, 0.4);
|
||||||
|
background: rgba(0, 255, 136, 0.06);
|
||||||
|
}
|
||||||
|
.dash-proxy-name {
|
||||||
|
flex: 1;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
color: var(--text);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.dash-proxy-type {
|
||||||
|
font-size: .68rem;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.dash-delay {
|
||||||
|
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||||
|
font-size: .78rem;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.dash-delay-good { color: var(--success); }
|
||||||
|
.dash-delay-medium { color: var(--warning); }
|
||||||
|
.dash-delay-slow { color: var(--danger); }
|
||||||
|
.dash-delay-unknown { color: var(--muted); }
|
||||||
|
|
||||||
|
.dash-conn-count {
|
||||||
|
font-size: .78rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--accent);
|
||||||
|
background: rgba(0, 212, 255, 0.1);
|
||||||
|
border: 1px solid rgba(0, 212, 255, 0.3);
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 12px;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.dash-conn-table-wrap {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
overflow-x: auto;
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
}
|
||||||
|
.dash-conn-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: .82rem;
|
||||||
|
}
|
||||||
|
.dash-conn-table thead {
|
||||||
|
background: rgba(0, 212, 255, 0.03);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.dash-conn-table th {
|
||||||
|
text-align: left;
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: .72rem;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: .06em;
|
||||||
|
color: var(--muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.dash-conn-table td {
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-bottom: 1px solid rgba(255, 255, 255, 0.03);
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
.dash-conn-table tbody tr:hover { background: rgba(0, 212, 255, 0.03); }
|
||||||
|
.dash-conn-host {
|
||||||
|
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||||
|
color: var(--text);
|
||||||
|
max-width: 200px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.dash-conn-chain {
|
||||||
|
color: var(--text-dim);
|
||||||
|
max-width: 220px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.dash-conn-traffic {
|
||||||
|
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||||
|
color: var(--text-dim);
|
||||||
|
font-size: .78rem;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
1
zashboard
Submodule
1
zashboard
Submodule
Submodule zashboard added at 132970daa3
Reference in New Issue
Block a user