10 Commits
Author SHA1 Message Date
刘嘉伟 1bdd35a234 🚑 Fix proxy type issue. 2026-03-31 14:35:42 +08:00
刘嘉伟 e37661c6e9 docs: update license reference from MIT to Apache 2.0 in README files
The license reference in both the English and Chinese README files has been changed from MIT to Apache 2.0. This update aligns the documentation with the actual project license.
2026-03-26 16:21:33 +08:00
刘嘉伟 1578832510 docs: update release history and add license section to README files
- Add v0.1.5 release entry to changelog in both README.md and README_zh.md
- Include MIT license section in both README files for better project documentation
2026-03-26 16:20:07 +08:00
刘嘉伟 cfbbf31543 chore: bump version to 0.1.5. 2026-03-26 16:07:18 +08:00
刘嘉伟 3a1ad7ce65 feat(proxies): enhance clipboard compatibility and remote port display
- Improve clipboard copy functionality with fallback for older browsers
- Change remote port display logic to show empty string instead of "-" for missing values
- Maintain consistent copy feedback behavior across all browser environments
2026-03-26 15:28:21 +08:00
刘嘉伟 01c3a70d2b 🐛 Fix proxy list pagination. 2026-03-26 15:12:05 +08:00
刘嘉伟 3cc8d9406d 🔖 v0.1.4 2026-03-25 11:04:38 +08:00
刘嘉伟 edc2a0416d 🔊 UA 2026-03-25 11:02:52 +08:00
刘嘉伟 69afa49d1c 🐛 Fix data type error. 2026-03-25 09:43:38 +08:00
刘嘉伟 bb18a9e3d1 ⬆️ Upgrade dependencies. 2026-03-24 17:59:05 +08:00
23 changed files with 259 additions and 1419 deletions

No files matched your search

+6
View File
@@ -61,6 +61,12 @@
- 2026-03-12: Released v0.1.1
- 2026-03-12: Released v0.1.2
- 2026-03-16: Released v0.1.3
- 2026-03-25: Released v0.1.4
- 2026-03-26: Released v0.1.5
## License
[Apache 2.0](LICENSE)
## Star History
+6
View File
@@ -61,6 +61,12 @@
- 2026-03-12: 发布 v0.1.1
- 2026-03-14: 发布 v0.1.2
- 2026-03-16: 发布 v0.1.3
- 2026-03-25: 发布 v0.1.4
- 2026-03-26: 发布 v0.1.5
## License
[Apache 2.0](LICENSE)
## Star 历史
+1 -2
View File
@@ -3,7 +3,7 @@ module podux
go 1.25.5
require (
github.com/fatedier/frp v0.67.0
github.com/fatedier/frp v0.68.0
github.com/pelletier/go-toml/v2 v2.2.0
github.com/pocketbase/dbx v1.11.0
github.com/pocketbase/pocketbase v0.35.0
@@ -26,7 +26,6 @@ require (
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect
github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/gopacket v1.1.19 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/hashicorp/yamux v0.1.1 // indirect
+2 -7
View File
@@ -27,6 +27,8 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fatedier/frp v0.67.0 h1:w6xHLkruAJcq+fZP9VOiY6w/FBy/wB1aPqA4frs98K8=
github.com/fatedier/frp v0.67.0/go.mod h1:0Q3mAI0c9WtAsgMQpTQhinWTKa2Qp121YWsqaFu41Zg=
github.com/fatedier/frp v0.68.0 h1:woKC31EpgCLQDirRAOAUgHP3IRxLu2mBHS6zGpcw7tw=
github.com/fatedier/frp v0.68.0/go.mod h1:qFdez6Z+RDqoqF1xJhh48+IW91SVQ+pNWnrmcl43Wjs=
github.com/fatedier/golib v0.5.1 h1:hcKAnaw5mdI/1KWRGejxR+i1Hn/NvbY5UsMKDr7o13M=
github.com/fatedier/golib v0.5.1/go.mod h1:W6kIYkIFxHsTzbgqg5piCxIiDo4LzwgTY6R5W8l9NFQ=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
@@ -67,8 +69,6 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=
github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=
github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d h1:KJIErDwbSHjnp/SGzE5ed8Aol7JsKiI5X7yWKAtzhM0=
github.com/google/pprof v0.0.0-20251007162407-5df77e3f7d1d/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -165,7 +165,6 @@ go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
@@ -182,8 +181,6 @@ golang.org/x/image v0.34.0/go.mod h1:2RNFBZRB+vnwwFil8GkMdRvrJOFd1AzdZI6vOY+eJVU
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
@@ -254,13 +251,11 @@ golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
+20 -24
View File
@@ -21,6 +21,7 @@ import (
"podux/pkg/utils"
"github.com/fatedier/frp/client"
frpcsource "github.com/fatedier/frp/pkg/config/source"
v1 "github.com/fatedier/frp/pkg/config/v1"
"github.com/fatedier/frp/pkg/util/log"
"github.com/pocketbase/pocketbase/core"
@@ -169,6 +170,8 @@ func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error)
if proxyMap.ProxyType == "http" || proxyMap.ProxyType == "https" {
delete(proxyData, "remotePort")
}
proxyData["type"] = proxyMap.ProxyType
delete(proxyData, "proxyType")
proxyData["name"] = proxyMap.Name + "-" + proxyMap.Id
// Remove empty plugin map so frp doesn't try to parse a typeless plugin
@@ -235,10 +238,6 @@ func (fs *Service) LaunchFrpc(serverId *string) error {
fs.app.Logger().Debug("Config", "serverAddr", cfg.ServerAddr, "serverPort", cfg.ServerPort, "proxyCount", len(proxyCfgs))
for _, c := range proxyCfgs {
c.Complete(cfg.User)
}
// Print frp configurations in logs with sensitive data masked
commonCfgBytes, _ := json.Marshal(cfg)
proxyCfgsBytes, _ := json.Marshal(proxyCfgs)
@@ -251,9 +250,13 @@ func (fs *Service) LaunchFrpc(serverId *string) error {
cfg.Complete()
log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
configSrc := frpcsource.NewConfigSource()
if err := configSrc.ReplaceAll(proxyCfgs, nil); err != nil {
return err
}
svr, err := client.NewService(client.ServiceOptions{
Common: cfg,
ProxyCfgs: proxyCfgs,
Common: cfg,
ConfigSourceAggregator: frpcsource.NewAggregator(configSrc),
})
if err != nil {
fs.app.Logger().Error("NewService", "err", err)
@@ -284,13 +287,13 @@ func (fs *Service) LaunchFrpc(serverId *string) error {
done <- err
}()
go fs.monitorServiceStatus(serverId, svr, ctx, done, cfg.User)
go fs.monitorServiceStatus(serverId, svr, ctx, done)
return nil
}
// monitorServiceStatus monitors service status and updates the database.
func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx context.Context, done <-chan error, user string) {
func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx context.Context, done <-chan error) {
time.Sleep(2 * time.Second)
select {
@@ -307,7 +310,7 @@ func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx con
fs.app.Logger().Info("Service is running", "id", *id)
}
go fs.monitorProxyStatus(id, svr, ctx, user)
go fs.monitorProxyStatus(id, svr, ctx)
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
@@ -342,7 +345,7 @@ func (fs *Service) destroying(id *string) {
}
// monitorProxyStatus monitors proxy status from frp and updates the database.
func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx context.Context, user string) {
func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx context.Context) {
fs.app.Logger().Info("Starting proxy status monitoring", "serverId", *serverId)
statusExporter := svr.StatusExporter()
@@ -364,11 +367,13 @@ func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx
for _, proxy := range proxies {
baseName := proxy.Name + "-" + proxy.Id
prefix := ""
if user != "" {
prefix = user + "."
}
status, exists := statusExporter.GetProxyStatus(prefix + baseName)
status, exists := statusExporter.GetProxyStatus(baseName)
fs.app.Logger().Info("proxy status check", "baseName", baseName, "exists", exists, "phase", func() string {
if status != nil {
return status.Phase
}
return "nil"
}())
if exists {
var bootStatus proxydomain.ProxyBootStatus
@@ -493,15 +498,6 @@ func (fs *Service) ReloadFrpc(serverId *string) error {
return err
}
server, err := fs.app.FindRecordById("fh_servers", *serverId)
if err != nil {
return err
}
user := server.GetString("user")
for _, c := range proxyCfgs {
c.Complete(user)
}
proxyCfgsBytes, _ := json.Marshal(proxyCfgs)
safeProxies := sensitiveRegex.ReplaceAll(proxyCfgsBytes, []byte(`"${1}":"***"`))
fs.app.Logger().Info("FRP Reload Configurations", "proxies", string(safeProxies))
-570
View File
@@ -1,570 +0,0 @@
package scanner
import (
"bufio"
"context"
"errors"
"net"
"os"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/afpacket"
"github.com/google/gopacket/layers"
)
// Device represents a discovered LAN host.
type Device struct {
IP string `json:"ip"`
MAC string `json:"mac"`
Hostname string `json:"hostname"`
Interface string `json:"interface"`
}
// LocalNetwork describes one scannable subnet on this host.
type LocalNetwork struct {
Interface string `json:"interface"`
CIDR string `json:"cidr"`
Hosts int `json:"hosts"`
}
// PortResult is the result of scanning a single TCP port.
type PortResult struct {
Port int `json:"port"`
Open bool `json:"open"`
Service string `json:"service"`
Done bool `json:"done,omitempty"` // signals end-of-stream
}
// wellKnownPorts maps port numbers to service names.
var wellKnownPorts = map[int]string{
21: "FTP",
22: "SSH",
23: "Telnet",
25: "SMTP",
53: "DNS",
80: "HTTP",
110: "POP3",
143: "IMAP",
443: "HTTPS",
445: "SMB",
1433: "MSSQL",
1521: "Oracle",
3306: "MySQL",
3389: "RDP",
5432: "PostgreSQL",
5900: "VNC",
6379: "Redis",
8080: "HTTP-Alt",
8443: "HTTPS-Alt",
8888: "HTTP-Dev",
9200: "Elasticsearch",
11211: "Memcached",
27017: "MongoDB",
}
// CommonPorts is the default port list for port scanning.
var CommonPorts = func() []int {
ports := make([]int, 0, len(wellKnownPorts))
for p := range wellKnownPorts {
ports = append(ports, p)
}
return ports
}()
// hostProbePorts are the ports tried when checking whether a host is alive
// without ARP (TCP fallback mode).
var hostProbePorts = []int{22, 80, 443, 445, 3389, 8080, 8443}
// maxPrefixLen is the smallest prefix we will scan (/20 = 4094 hosts max).
// Subnets larger than this (e.g. Docker /16) are skipped automatically.
const maxPrefixLen = 20
// Service provides LAN discovery and port-scan capabilities.
type Service struct{}
func NewService() *Service { return &Service{} }
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
// GetLocalNetworks returns the subnets that will be scanned.
func (s *Service) GetLocalNetworks() []LocalNetwork {
var out []LocalNetwork
for _, iface := range upInterfaces() {
addrs, _ := iface.Addrs()
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if !ok || ipNet.IP.To4() == nil || ipNet.IP.IsLoopback() {
continue
}
ones, _ := ipNet.Mask.Size()
if ones < maxPrefixLen {
continue
}
hosts := (1 << (32 - ones)) - 2
out = append(out, LocalNetwork{
Interface: iface.Name,
CIDR: ipNet.String(),
Hosts: hosts,
})
}
}
return out
}
// DiscoverDevices scans local subnets for active hosts.
// It first attempts a gopacket/afpacket ARP sweep (requires CAP_NET_RAW).
// If that is unavailable it falls back to TCP-connect probing + reading the
// kernel ARP cache from /proc/net/arp.
func (s *Service) DiscoverDevices(ctx context.Context) ([]Device, error) {
ifaces := upInterfaces()
if len(ifaces) == 0 {
return []Device{}, nil
}
// Try ARP sweep on first suitable interface; if permission denied use TCP.
devices, err := s.arpDiscover(ctx, ifaces)
if err != nil {
if isPermissionDenied(err) {
return s.tcpDiscover(ctx, ifaces)
}
return nil, err
}
return devices, nil
}
// ScanPorts does a concurrent TCP-connect scan on ip for ports.
// Results are written to ch; the caller must close ch after this returns.
func (s *Service) ScanPorts(ctx context.Context, ip string, ports []int, ch chan<- PortResult) {
const concurrency = 200
sem := make(chan struct{}, concurrency)
var wg sync.WaitGroup
for _, port := range ports {
if ctx.Err() != nil {
break
}
sem <- struct{}{}
wg.Add(1)
go func(p int) {
defer wg.Done()
defer func() { <-sem }()
addr := net.JoinHostPort(ip, strconv.Itoa(p))
conn, err := net.DialTimeout("tcp", addr, 500*time.Millisecond)
open := err == nil
if conn != nil {
conn.Close()
}
result := PortResult{Port: p, Open: open}
if open {
result.Service = wellKnownPorts[p]
}
select {
case ch <- result:
case <-ctx.Done():
}
}(port)
}
wg.Wait()
}
// ---------------------------------------------------------------------------
// ARP-based discovery (gopacket + afpacket, needs CAP_NET_RAW)
// ---------------------------------------------------------------------------
func (s *Service) arpDiscover(ctx context.Context, ifaces []net.Interface) ([]Device, error) {
var (
mu sync.Mutex
wg sync.WaitGroup
devices = make([]Device, 0)
seen = map[string]bool{}
lastErr error
)
for _, iface := range ifaces {
if len(iface.HardwareAddr) == 0 {
continue
}
addrs, _ := iface.Addrs()
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if !ok || ipNet.IP.To4() == nil || ipNet.IP.IsLoopback() {
continue
}
ones, _ := ipNet.Mask.Size()
if ones < maxPrefixLen {
continue // skip huge subnets like Docker /16
}
wg.Add(1)
go func(iface net.Interface, ip net.IP, network *net.IPNet) {
defer wg.Done()
found, err := arpSweep(ctx, iface, ip, network)
if err != nil {
mu.Lock()
lastErr = err
mu.Unlock()
return
}
mu.Lock()
for _, d := range found {
if !seen[d.IP] {
seen[d.IP] = true
devices = append(devices, d)
}
}
mu.Unlock()
}(iface, ipNet.IP, ipNet)
}
}
wg.Wait()
if len(devices) == 0 && lastErr != nil {
return nil, lastErr
}
return devices, nil
}
func arpSweep(ctx context.Context, iface net.Interface, src net.IP, network *net.IPNet) ([]Device, error) {
handle, err := afpacket.NewTPacket(
afpacket.OptInterface(iface.Name),
afpacket.OptBlockTimeout(5*time.Millisecond),
)
if err != nil {
return nil, err
}
sweepCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
results := make(chan Device, 512)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
captureARP(sweepCtx, handle, results)
close(results)
}()
sendARP(sweepCtx, handle, iface, src, network)
<-sweepCtx.Done()
handle.Close()
wg.Wait()
selfIP := src.String()
var devices []Device
seen := map[string]bool{selfIP: true}
for d := range results {
if seen[d.IP] {
continue
}
seen[d.IP] = true
d.Interface = iface.Name
if names, err := net.LookupAddr(d.IP); err == nil && len(names) > 0 {
d.Hostname = strings.TrimSuffix(names[0], ".")
}
devices = append(devices, d)
}
return devices, nil
}
func captureARP(ctx context.Context, handle *afpacket.TPacket, out chan<- Device) {
pktSrc := gopacket.NewPacketSource(handle, layers.LinkTypeEthernet)
pktSrc.NoCopy = true
for {
select {
case <-ctx.Done():
return
default:
}
pkt, err := pktSrc.NextPacket()
if err != nil {
if ctx.Err() != nil {
return
}
continue
}
arpLayer := pkt.Layer(layers.LayerTypeARP)
if arpLayer == nil {
continue
}
arp := arpLayer.(*layers.ARP)
if arp.Operation != layers.ARPReply {
continue
}
ip := net.IP(arp.SourceProtAddress).String()
mac := net.HardwareAddr(arp.SourceHwAddress).String()
select {
case out <- Device{IP: ip, MAC: mac}:
default:
}
}
}
func sendARP(ctx context.Context, handle *afpacket.TPacket, iface net.Interface, src net.IP, network *net.IPNet) {
eth := layers.Ethernet{
SrcMAC: iface.HardwareAddr,
DstMAC: net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
EthernetType: layers.EthernetTypeARP,
}
arp := layers.ARP{
AddrType: layers.LinkTypeEthernet,
Protocol: layers.EthernetTypeIPv4,
HwAddressSize: 6,
ProtAddressSize: 4,
Operation: layers.ARPRequest,
SourceHwAddress: []byte(iface.HardwareAddr),
SourceProtAddress: []byte(src.To4()),
DstHwAddress: []byte{0, 0, 0, 0, 0, 0},
}
buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}
for ip := cloneIP(network.IP.Mask(network.Mask)); network.Contains(ip); incrementIP(ip) {
select {
case <-ctx.Done():
return
default:
}
target := make(net.IP, 4)
copy(target, ip.To4())
arp.DstProtAddress = target
if err := gopacket.SerializeLayers(buf, opts, &eth, &arp); err != nil {
continue
}
_ = handle.WritePacketData(buf.Bytes())
time.Sleep(500 * time.Microsecond)
}
}
// ---------------------------------------------------------------------------
// TCP-based host discovery fallback (no special privileges required)
// ---------------------------------------------------------------------------
// tcpDiscover probes each host in every local subnet using TCP connect.
// A host is "alive" if any probe port responds (open or connection refused).
// After the sweep it enriches results with MAC addresses from /proc/net/arp.
func (s *Service) tcpDiscover(ctx context.Context, ifaces []net.Interface) ([]Device, error) {
type result struct {
ip string
iface string
}
resultCh := make(chan result, 512)
var sweepWg sync.WaitGroup
const hostConcurrency = 100
for _, iface := range ifaces {
addrs, _ := iface.Addrs()
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if !ok || ipNet.IP.To4() == nil || ipNet.IP.IsLoopback() {
continue
}
ones, _ := ipNet.Mask.Size()
if ones < maxPrefixLen {
continue
}
// Enumerate all host addresses in this subnet.
var ips []string
selfIP := ipNet.IP.String()
for ip := cloneIP(ipNet.IP.Mask(ipNet.Mask)); ipNet.Contains(ip); incrementIP(ip) {
candidate := ip.String()
if candidate == selfIP {
continue
}
ips = append(ips, candidate)
}
sweepWg.Add(1)
go func(ifaceName string, ips []string) {
defer sweepWg.Done()
sem := make(chan struct{}, hostConcurrency)
var wg sync.WaitGroup
for _, ip := range ips {
if ctx.Err() != nil {
break
}
sem <- struct{}{}
wg.Add(1)
go func(ip string) {
defer wg.Done()
defer func() { <-sem }()
if isHostAlive(ctx, ip) {
select {
case resultCh <- result{ip: ip, iface: ifaceName}:
case <-ctx.Done():
}
}
}(ip)
}
wg.Wait()
}(iface.Name, ips)
}
}
// Close resultCh once all sweeps complete.
go func() {
sweepWg.Wait()
close(resultCh)
}()
// Collect results.
arpCache := readARPCache()
devices := make([]Device, 0)
seen := map[string]bool{}
for r := range resultCh {
if seen[r.ip] {
continue
}
seen[r.ip] = true
d := Device{IP: r.ip, Interface: r.iface}
if mac, ok := arpCache[r.ip]; ok {
d.MAC = mac
}
if names, err := net.LookupAddr(r.ip); err == nil && len(names) > 0 {
d.Hostname = strings.TrimSuffix(names[0], ".")
}
devices = append(devices, d)
}
return devices, nil
}
// isHostAlive returns true if the host has any TCP port open or actively
// refusing connections (which proves the host is up).
func isHostAlive(ctx context.Context, ip string) bool {
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
found := make(chan struct{}, 1)
var wg sync.WaitGroup
for _, port := range hostProbePorts {
wg.Add(1)
go func(p int) {
defer wg.Done()
addr := net.JoinHostPort(ip, strconv.Itoa(p))
d := net.Dialer{}
conn, err := d.DialContext(ctx, "tcp", addr)
if conn != nil {
conn.Close()
}
if err == nil || isConnRefused(err) {
select {
case found <- struct{}{}:
default:
}
cancel()
}
}(port)
}
wg.Wait()
select {
case <-found:
return true
default:
return false
}
}
// isConnRefused checks whether err is ECONNREFUSED (host alive, port closed).
func isConnRefused(err error) bool {
if err == nil {
return false
}
var opErr *net.OpError
if !errors.As(err, &opErr) {
return false
}
var syscallErr *os.SyscallError
if !errors.As(opErr.Err, &syscallErr) {
return false
}
errno, ok := syscallErr.Err.(syscall.Errno)
return ok && errno == syscall.ECONNREFUSED
}
// readARPCache parses /proc/net/arp and returns an ip→mac map.
func readARPCache() map[string]string {
f, err := os.Open("/proc/net/arp")
if err != nil {
return map[string]string{}
}
defer f.Close()
cache := map[string]string{}
scanner := bufio.NewScanner(f)
scanner.Scan() // skip header line
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 4 {
continue
}
ip := fields[0]
mac := fields[3]
if mac == "00:00:00:00:00:00" {
continue
}
cache[ip] = mac
}
return cache
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
func upInterfaces() []net.Interface {
ifaces, err := net.Interfaces()
if err != nil {
return nil
}
var out []net.Interface
for _, iface := range ifaces {
if iface.Flags&net.FlagLoopback != 0 {
continue
}
if iface.Flags&net.FlagUp == 0 {
continue
}
out = append(out, iface)
}
return out
}
func isPermissionDenied(err error) bool {
if err == nil {
return false
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "permission denied") ||
strings.Contains(s, "operation not permitted")
}
func cloneIP(ip net.IP) net.IP {
clone := make(net.IP, len(ip))
copy(clone, ip)
return clone
}
func incrementIP(ip net.IP) {
for i := len(ip) - 1; i >= 0; i-- {
ip[i]++
if ip[i] != 0 {
break
}
}
}
+1 -1
View File
@@ -177,7 +177,7 @@ func (s *Service) GetLatestVersion() (*LatestVersionResponse, error) {
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "podux-server")
req.Header.Set("User-Agent", "podux-server/"+buildinfo.AppVersion)
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := client.Do(req)
-131
View File
@@ -1,131 +0,0 @@
package httphandler
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"podux/internal/application/scanner"
"podux/pkg/response"
"github.com/pocketbase/pocketbase/core"
)
type ScannerHandler struct {
app core.App
service *scanner.Service
}
func NewScannerHandler(app core.App, service *scanner.Service) *ScannerHandler {
return &ScannerHandler{app: app, service: service}
}
func (h *ScannerHandler) RegisterHandlers(e *core.ServeEvent) {
// GET /api/scanner/interfaces
// Returns local networks that will be scanned.
e.Router.GET("/api/scanner/interfaces", requireAuth(func(e *core.RequestEvent) error {
return e.JSON(200, h.service.GetLocalNetworks())
}, h.app))
// GET /api/scanner/discover
// ARP-sweep local network, returns discovered hosts.
e.Router.GET("/api/scanner/discover", requireAuth(func(e *core.RequestEvent) error {
ctx := e.Request.Context()
devices, err := h.service.DiscoverDevices(ctx)
if err != nil {
h.app.Logger().Error("LAN discovery failed", "error", err)
return e.JSON(500, response.Error(err))
}
return e.JSON(200, devices)
}, h.app))
// GET /api/scanner/ports/stream?ip=<ip>[&ports=<p1,p2,...>]
// Streams port-scan results as Server-Sent Events.
e.Router.GET("/api/scanner/ports/stream", requireAuth(func(e *core.RequestEvent) error {
q := e.Request.URL.Query()
ip := q.Get("ip")
if ip == "" {
return e.JSON(400, response.Error(fmt.Errorf("ip is required")))
}
if net.ParseIP(ip) == nil {
return e.JSON(400, response.Error(fmt.Errorf("invalid ip address")))
}
var ports []int
switch {
case q.Get("full") == "true":
ports = allPorts()
case q.Get("ports") != "":
ports = parsePortList(q.Get("ports"))
default:
ports = scanner.CommonPorts
}
w := e.Response
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
flusher, ok := w.(http.Flusher)
if !ok {
return e.JSON(500, response.Error(fmt.Errorf("streaming not supported")))
}
ctx, cancel := context.WithCancel(e.Request.Context())
defer cancel()
results := make(chan scanner.PortResult, 128)
go func() {
defer close(results)
h.service.ScanPorts(ctx, ip, ports, results)
}()
for res := range results {
data, err := json.Marshal(res)
if err != nil {
continue
}
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
}
// Signal completion
done, _ := json.Marshal(scanner.PortResult{Done: true})
fmt.Fprintf(w, "data: %s\n\n", done)
flusher.Flush()
return nil
}, h.app))
}
// allPorts returns every valid TCP port (1-65535).
func allPorts() []int {
ports := make([]int, 65535)
for i := range ports {
ports[i] = i + 1
}
return ports
}
// parsePortList parses a comma-separated list of port numbers.
func parsePortList(s string) []int {
if s == "" {
return nil
}
var ports []int
for _, part := range strings.Split(s, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
if n, err := strconv.Atoi(part); err == nil && n > 0 && n <= 65535 {
ports = append(ports, n)
}
}
return ports
}
-4
View File
@@ -11,7 +11,6 @@ import (
"podux/internal/application/importer"
"podux/internal/application/monitoring"
"podux/internal/application/proxy"
"podux/internal/application/scanner"
"podux/internal/application/server"
"podux/internal/application/system"
"podux/internal/application/version"
@@ -52,13 +51,11 @@ func main() {
networkMonitorService := monitoring.NewMonitorService(app, geoService, metricsService)
importService := importer.NewService(app)
versionService := version.NewService(app)
scannerService := scanner.NewService()
//githubService := github.NewService(app)
// HTTP Handlers
//githubHandler := httphandler.NewGithubHandler(app, githubService)
frpcHandler := httphandler.NewFrpcHandler(app, frpcService)
scannerHandler := httphandler.NewScannerHandler(app, scannerService)
versionHandler := httphandler.NewVersionHandler(app, versionService)
dashboardHandler := httphandler.NewDashboardHandler(dashboardService)
systemHandler := httphandler.NewSystemHandler(app, settingsService)
@@ -103,7 +100,6 @@ func main() {
systemHandler.RegisterHandlers(e)
importHandler.RegisterHandlers(e)
serverHandler.RegisterHandlers(e)
scannerHandler.RegisterHandlers(e)
// Serve static files from embedded FS
content, err := fs.Sub(pbPublicDir, "pb_public")
@@ -1657,29 +1657,33 @@ func init() {
},
{
"hidden": false,
"id": "date2095552691",
"max": "",
"min": "",
"id": "number3814843458",
"max": null,
"min": null,
"name": "valMax",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "date"
"type": "number"
},
{
"hidden": false,
"id": "date1089120234",
"max": "",
"min": "",
"id": "number3748453147",
"max": null,
"min": null,
"name": "valMin",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "date"
"type": "number"
}
],
"id": "pbc_3875966484",
"indexes": [],
"indexes": [
"CREATE INDEX ` + "`" + `idx_cytGPviJew` + "`" + ` ON ` + "`" + `fh_metrics_daily` + "`" + ` (\n ` + "`" + `targetId` + "`" + `,\n ` + "`" + `metricKey` + "`" + `,\n ` + "`" + `t` + "`" + `\n)"
],
"listRule": null,
"name": "fh_metrics_daily",
"system": false,
+1 -1
View File
@@ -2,4 +2,4 @@ package buildinfo
// AppVersion is the single source of truth for the application version.
// Update this value to release a new version.
const AppVersion = "0.1.4"
const AppVersion = "0.1.5"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "podux-web",
"private": true,
"version": "0.1.4",
"version": "0.1.5",
"type": "module",
"scripts": {
"dev": "vite",
-4
View File
@@ -32,9 +32,6 @@ const ServerFormPage = lazy(() =>
const ServerLogPage = lazy(() =>
import("./pages/ServerLog/ServerLogPage").then((m) => ({ default: m.ServerLogPage }))
);
const ScannerPage = lazy(() =>
import("./pages/Scanner").then((m) => ({ default: m.ScannerPage }))
);
function AuthenticatedLayout() {
console.log("AuthenticatedLayout rendered");
@@ -80,7 +77,6 @@ function App() {
<Route path="/servers/:id/logs" element={<ServerLogPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/import" element={<ImportPage />} />
<Route path="/scanner" element={<ScannerPage />} />
{/* <Route path="/versions" element={<VersionPage />} /> */}
</Route>
-5
View File
@@ -62,11 +62,6 @@ const navItems = [
path: "/proxies",
icon: <Icon icon="lucide:network" width="18" height="18" />,
},
{
labelKey: "nav.scanner",
path: "/scanner",
icon: <Icon icon="lucide:radar" width="18" height="18" />,
},
];
const mobileBottomNavItems = navItems;
+1 -35
View File
@@ -40,8 +40,7 @@
"logout": "Logout",
"pbAdmin": "Admin Panel",
"version": "Version",
"import": "Import",
"scanner": "Scanner"
"import": "Import"
},
"auth": {
"login": "Login",
@@ -488,38 +487,5 @@
"setupFailed": "Failed to initialize system. Please try again.",
"settingsCreateFailed": "Failed to initialize system settings"
}
},
"scanner": {
"title": "LAN Scanner",
"description": "Discover devices on your local network and scan their open ports",
"step1Title": "Step 1 — Device Discovery",
"step1Desc": "Scan your local network for active hosts using ARP. Requires root / CAP_NET_RAW on the server.",
"discovering": "Scanning...",
"discoverBtn": "Start Discovery",
"devicesFound": "{{count}} device(s) found",
"hosts": "hosts",
"ipAddress": "IP Address",
"macAddress": "MAC Address",
"hostname": "Hostname",
"iface": "Interface",
"scanPorts": "Scan Ports",
"scanTarget": "Target",
"startScan": "Start Port Scan",
"stop": "Stop",
"mode": "Mode",
"modeCommon": "Common",
"modeCustom": "Custom",
"modeFull": "All ports",
"customPorts": "Custom ports",
"customPortsPlaceholder": "e.g. 22,80,443,8080",
"customPortsHint": "Comma-separated port numbers",
"fullScanWarning": "Scanning all 65535 ports will take several minutes. The results will stream in real time.",
"scanned": "Scanned",
"openPorts": "Open",
"complete": "Done",
"port": "Port",
"status": "Status",
"service": "Service",
"open": "Open"
}
}
+1 -35
View File
@@ -40,8 +40,7 @@
"logout": "退出登录",
"pbAdmin": "后台管理",
"version": "版本",
"import": "导入",
"scanner": "局域网扫描"
"import": "导入"
},
"auth": {
"login": "登录",
@@ -488,38 +487,5 @@
"setupFailed": "系统初始化失败。请重试。",
"settingsCreateFailed": "初始化系统设置失败"
}
},
"scanner": {
"title": "局域网扫描",
"description": "发现局域网内的在线设备并扫描其开放端口",
"step1Title": "第一步 — 设备发现",
"step1Desc": "使用 ARP 扫描本地网络中的活跃主机。服务器需要 root 权限或 CAP_NET_RAW 能力。",
"discovering": "扫描中...",
"discoverBtn": "开始发现",
"devicesFound": "发现 {{count}} 台设备",
"hosts": "台主机",
"ipAddress": "IP 地址",
"macAddress": "MAC 地址",
"hostname": "主机名",
"iface": "网口",
"scanPorts": "扫描端口",
"scanTarget": "目标",
"startScan": "开始端口扫描",
"stop": "停止",
"mode": "模式",
"modeCommon": "常用端口",
"modeCustom": "自定义",
"modeFull": "全部端口",
"customPorts": "自定义端口",
"customPortsPlaceholder": "例如 22,80,443,8080",
"customPortsHint": "用逗号分隔端口号",
"fullScanWarning": "扫描全部 65535 个端口将耗时数分钟,结果会实时流式显示。",
"scanned": "已扫描",
"openPorts": "开放",
"complete": "完成",
"port": "端口",
"status": "状态",
"service": "服务",
"open": "开放"
}
}
+100 -4
View File
@@ -21,6 +21,11 @@ interface ProxiesViewProps {
onDeleteProxy: (id: string) => Promise<void>;
onToggleStatus: (proxy: Proxy) => Promise<void>;
refreshProxies: () => void;
page: number;
setPage: (page: number) => void;
totalPages: number;
search: string;
setSearch: (value: string) => void;
}
export function ProxiesView({
@@ -31,6 +36,11 @@ export function ProxiesView({
onDeleteProxy,
onToggleStatus,
refreshProxies,
page,
setPage,
totalPages,
search,
setSearch,
}: ProxiesViewProps) {
const { t } = useTranslation();
const navigate = useNavigate();
@@ -40,10 +50,23 @@ export function ProxiesView({
const [togglingId, setTogglingId] = useState<string | null>(null);
const handleCopy = (text: string, id: string) => {
navigator.clipboard.writeText(text).then(() => {
const done = () => {
setCopiedId(id);
setTimeout(() => setCopiedId(null), 1500);
});
};
if (navigator.clipboard) {
navigator.clipboard.writeText(text).then(done);
} else {
const el = document.createElement("textarea");
el.value = text;
el.style.position = "fixed";
el.style.opacity = "0";
document.body.appendChild(el);
el.select();
document.execCommand("copy");
document.body.removeChild(el);
done();
}
};
useEffect(() => {
@@ -121,10 +144,21 @@ export function ProxiesView({
size="2"
placeholder={t("proxy.searchProxies")}
className="min-w-32 flex-1"
value={search}
onChange={(e) => setSearch(e.target.value)}
>
<TextField.Slot>
<Icon icon="lucide:search" width="16" height="16" />
</TextField.Slot>
{search && (
<TextField.Slot
pr="2"
onClick={() => setSearch("")}
style={{ cursor: "pointer" }}
>
<Icon icon="lucide:x" width="16" height="16" />
</TextField.Slot>
)}
</TextField.Root>
<Button variant="soft" onClick={refreshProxies} disabled={refreshing}>
<Icon
@@ -155,6 +189,7 @@ export function ProxiesView({
onAction={() => navigate("/proxies/new")}
/>
) : (
<>
<div className="overflow-x-auto">
<Table.Root>
<Table.Header>
@@ -172,6 +207,7 @@ export function ProxiesView({
</Table.Header>
<Table.Body>
{proxies.map((proxy) => (
<Table.Row key={proxy.id}>
<Table.Cell>
<Text weight="medium">{proxy.name || <Text color="gray">-</Text>}</Text>
@@ -278,8 +314,8 @@ export function ProxiesView({
</Flex>
);
}
const displayText = proxy.remotePort || "-";
if (displayText === "-")
const displayText = proxy.remotePort ? String(proxy.remotePort) : "";
if (!displayText)
return <Text size="2" color="gray">-</Text>;
const copyKey = `${proxy.id}-port`;
const isCopied = copiedId === copyKey;
@@ -379,6 +415,66 @@ export function ProxiesView({
</Table.Body>
</Table.Root>
</div>
{totalPages > 1 && (
<Flex justify="between" align="center" pt="4" px="1">
<Text size="2" color="gray">
{page} / {totalPages}
</Text>
<Flex align="center" style={{ border: "1px solid var(--gray-6)", borderRadius: "var(--radius-3)", overflow: "hidden" }}>
<button
disabled={page === 1}
onClick={() => setPage(page - 1)}
style={{
padding: "6px 10px",
background: "none",
border: "none",
borderRight: "1px solid var(--gray-6)",
cursor: page === 1 ? "not-allowed" : "pointer",
opacity: page === 1 ? 0.4 : 1,
display: "flex",
alignItems: "center",
}}
>
<Icon icon="lucide:chevron-left" width="14" height="14" />
</button>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
<button
key={p}
onClick={() => setPage(p)}
style={{
padding: "6px 12px",
background: p === page ? "var(--accent-9)" : "none",
color: p === page ? "white" : "inherit",
border: "none",
borderRight: p === totalPages ? "none" : "1px solid var(--gray-6)",
cursor: "pointer",
fontSize: "var(--font-size-2)",
fontWeight: p === page ? 600 : 400,
}}
>
{p}
</button>
))}
<button
disabled={page === totalPages}
onClick={() => setPage(page + 1)}
style={{
padding: "6px 10px",
background: "none",
border: "none",
borderLeft: "1px solid var(--gray-6)",
cursor: page === totalPages ? "not-allowed" : "pointer",
opacity: page === totalPages ? 0.4 : 1,
display: "flex",
alignItems: "center",
}}
>
<Icon icon="lucide:chevron-right" width="14" height="14" />
</button>
</Flex>
</Flex>
)}
</>
)}
</Card>
</motion.div>
+6 -1
View File
@@ -2,7 +2,7 @@ import { useProxies } from "./useProxies";
import { ProxiesView } from "./ProxiesPage.view";
export function ProxiesPage() {
const { proxies, loading, refreshing, stats, deleteProxy, toggleStatus, refreshProxies } = useProxies();
const { proxies, loading, refreshing, stats, deleteProxy, toggleStatus, refreshProxies, page, setPage, totalPages, search, setSearch } = useProxies();
return (
<ProxiesView
@@ -13,6 +13,11 @@ export function ProxiesPage() {
onDeleteProxy={deleteProxy}
onToggleStatus={toggleStatus}
refreshProxies={refreshProxies}
page={page}
setPage={setPage}
totalPages={totalPages}
search={search}
setSearch={setSearch}
/>
);
}
+35 -8
View File
@@ -29,8 +29,21 @@ export function useProxies() {
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [totalItems, setTotalItems] = useState(0);
const [onlineCount, setOnlineCount] = useState(0);
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const PER_PAGE = 10;
useEffect(() => {
const timer = setTimeout(() => setDebouncedSearch(search), 300);
return () => clearTimeout(timer);
}, [search]);
useEffect(() => {
setPage(1);
}, [debouncedSearch]);
const fetchProxies = useCallback(
async (isRefresh = false) => {
try {
@@ -40,12 +53,24 @@ export function useProxies() {
setRefreshing(true);
}
const result = await pb.collection("fh_proxies").getList<Proxy>(page, PER_PAGE, {
sort: "-created",
expand: "serverId",
});
const searchFilter = debouncedSearch
? `name ~ "${debouncedSearch}" || localIP ~ "${debouncedSearch}" || remotePort ~ "${debouncedSearch}"`
: "";
const [result, onlineResult] = await Promise.all([
pb.collection("fh_proxies").getList<Proxy>(page, PER_PAGE, {
sort: "-created",
expand: "serverId",
filter: searchFilter,
}),
pb.collection("fh_proxies").getList(1, 1, {
filter: 'bootStatus = "online"',
}),
]);
setProxies(result.items);
setTotalPages(result.totalPages);
setTotalItems(result.totalItems);
setOnlineCount(onlineResult.totalItems);
initializedRef.current = true;
} catch (err) {
if ((err as Record<string, unknown>)?.isAbort) return;
@@ -55,7 +80,7 @@ export function useProxies() {
setRefreshing(false);
}
},
[page]
[page, debouncedSearch]
);
useEffect(() => {
@@ -104,9 +129,9 @@ export function useProxies() {
};
const stats = {
total: proxies.length,
online: proxies.filter((p) => p.bootStatus === "online").length,
offline: proxies.filter((p) => p.bootStatus === "offline").length,
total: totalItems,
online: onlineCount,
offline: totalItems - onlineCount,
};
const isEmpty = !loading && proxies.length === 0;
@@ -122,6 +147,8 @@ export function useProxies() {
setPage,
totalPages,
stats,
search,
setSearch,
refreshProxies: () => fetchProxies(true),
};
}
-407
View File
@@ -1,407 +0,0 @@
import {
Badge,
Box,
Button,
Card,
Callout,
Flex,
Spinner,
Table,
Text,
TextField,
SegmentedControl,
Progress,
} from "@radix-ui/themes";
import { useState, useEffect } from "react";
import { Icon } from "@iconify/react";
import { motion, AnimatePresence } from "framer-motion";
import { useTranslation } from "react-i18next";
import { PageHeader } from "../../components/PageHeader";
import type { Device, LocalNetwork, PortResult, ScanMode, ScanStep } from "./useScanner";
interface ScannerViewProps {
step: ScanStep;
discovering: boolean;
devices: Device[];
localNetworks: LocalNetwork[];
selectedDevice: Device | null;
scanning: boolean;
portResults: PortResult[];
scanDone: boolean;
error: string | null;
scanMode: ScanMode;
setScanMode: (m: ScanMode) => void;
customPorts: string;
setCustomPorts: (v: string) => void;
totalPorts: number;
discoverDevices: () => void;
selectDevice: (device: Device) => void;
startPortScan: () => void;
stopScan: () => void;
backToDiscover: () => void;
}
export function ScannerView({
step,
discovering,
devices,
localNetworks,
selectedDevice,
scanning,
portResults,
scanDone,
error,
scanMode,
setScanMode,
customPorts,
setCustomPorts,
totalPorts,
discoverDevices,
selectDevice,
startPortScan,
stopScan,
backToDiscover,
}: ScannerViewProps) {
const { t } = useTranslation();
const [mounted, setMounted] = useState(false);
useEffect(() => {
const timer = setTimeout(() => setMounted(true), 100);
return () => clearTimeout(timer);
}, []);
const openPorts = portResults.filter((r) => r.open);
const scannedCount = portResults.length;
const progressPct = totalPorts > 0 ? Math.round((scannedCount / totalPorts) * 100) : 0;
return (
<Flex direction="column" gap="5" className="flex flex-1 flex-col">
<PageHeader
title={t("scanner.title")}
description={t("scanner.description")}
visible={mounted}
/>
<AnimatePresence>
{error && (
<motion.div
initial={{ opacity: 0, y: -8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -8 }}
>
<Callout.Root color="red">
<Callout.Icon>
<Icon icon="lucide:alert-circle" width="16" height="16" />
</Callout.Icon>
<Callout.Text>{error}</Callout.Text>
</Callout.Root>
</motion.div>
)}
</AnimatePresence>
{/* ── Step 1: Device Discovery ── */}
{step === "discover" && (
<motion.div
key="discover"
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -16 }}
>
<Flex direction="column" gap="4">
<Card>
<Flex direction="column" gap="3" p="2">
<Flex align="center" gap="2">
<Icon icon="lucide:wifi" width="20" height="20" style={{ color: "var(--accent-9)" }} />
<Text size="3" weight="bold">{t("scanner.step1Title")}</Text>
</Flex>
<Text size="2" color="gray">{t("scanner.step1Desc")}</Text>
{localNetworks.length > 0 && (
<Flex gap="2" wrap="wrap">
{localNetworks.map((n) => (
<Badge key={n.cidr} variant="outline" color="blue">
<Icon icon="lucide:ethernet-port" width="12" height="12" />
{n.interface} · {n.cidr} · {n.hosts} {t("scanner.hosts")}
</Badge>
))}
</Flex>
)}
<Button onClick={discoverDevices} disabled={discovering} style={{ alignSelf: "flex-start" }}>
{discovering ? (
<Flex align="center" gap="2">
<Spinner size="1" />
{t("scanner.discovering")}
</Flex>
) : (
<Flex align="center" gap="2">
<Icon icon="lucide:search" width="16" height="16" />
{t("scanner.discoverBtn")}
</Flex>
)}
</Button>
</Flex>
</Card>
<AnimatePresence>
{devices.length > 0 && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
>
<Card>
<Flex direction="column" gap="3" p="2">
<Flex align="center" justify="between">
<Flex align="center" gap="2">
<Icon icon="lucide:monitor-check" width="18" height="18" style={{ color: "var(--green-9)" }} />
<Text size="3" weight="bold">
{t("scanner.devicesFound", { count: devices.length })}
</Text>
</Flex>
<Badge color="green" variant="soft">
{devices.length} {t("scanner.hosts")}
</Badge>
</Flex>
<Table.Root variant="surface">
<Table.Header>
<Table.Row>
<Table.ColumnHeaderCell>{t("scanner.ipAddress")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("scanner.macAddress")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("scanner.hostname")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("scanner.iface")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("common.actions")}</Table.ColumnHeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{devices.map((device) => (
<motion.tr
key={device.ip}
initial={{ opacity: 0, x: -8 }}
animate={{ opacity: 1, x: 0 }}
>
<Table.Cell>
<Flex align="center" gap="2">
<Icon icon="lucide:network" width="14" height="14" style={{ color: "var(--accent-9)" }} />
<Text size="2" weight="medium" style={{ fontFamily: "monospace" }}>
{device.ip}
</Text>
</Flex>
</Table.Cell>
<Table.Cell>
<Text size="2" color="gray" style={{ fontFamily: "monospace" }}>
{device.mac || "—"}
</Text>
</Table.Cell>
<Table.Cell>
<Text size="2" color="gray">{device.hostname || "—"}</Text>
</Table.Cell>
<Table.Cell>
<Badge variant="outline" size="1">{device.interface || "—"}</Badge>
</Table.Cell>
<Table.Cell>
<Button size="1" variant="soft" onClick={() => selectDevice(device)}>
<Icon icon="lucide:scan-line" width="14" height="14" />
{t("scanner.scanPorts")}
</Button>
</Table.Cell>
</motion.tr>
))}
</Table.Body>
</Table.Root>
</Flex>
</Card>
</motion.div>
)}
</AnimatePresence>
</Flex>
</motion.div>
)}
{/* ── Step 2: Port Scanner ── */}
{step === "scan" && selectedDevice && (
<motion.div
key="scan"
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -16 }}
>
<Flex direction="column" gap="4">
{/* Target + controls */}
<Card>
<Flex direction="column" gap="4" p="2">
{/* Row 1: back / target / start-stop */}
<Flex align="center" justify="between" wrap="wrap" gap="3">
<Flex align="center" gap="3">
<Button variant="ghost" size="2" onClick={backToDiscover}>
<Icon icon="lucide:arrow-left" width="16" height="16" />
{t("common.back")}
</Button>
<Flex align="center" gap="2">
<Icon icon="lucide:target" width="20" height="20" style={{ color: "var(--accent-9)" }} />
<Text size="3" weight="bold">
{t("scanner.scanTarget")}: {selectedDevice.ip}
</Text>
{selectedDevice.hostname && (
<Badge variant="soft" color="blue">{selectedDevice.hostname}</Badge>
)}
</Flex>
</Flex>
<Flex align="center" gap="2">
{scanning ? (
<Button color="red" variant="soft" onClick={stopScan}>
<Icon icon="lucide:square" width="14" height="14" />
{t("scanner.stop")}
</Button>
) : (
<Button onClick={startPortScan}>
<Icon icon="lucide:play" width="14" height="14" />
{t("scanner.startScan")}
</Button>
)}
</Flex>
</Flex>
{/* Row 2: mode selector */}
<Flex align="center" gap="3" wrap="wrap">
<Text size="2" color="gray" style={{ whiteSpace: "nowrap" }}>
{t("scanner.mode")}:
</Text>
<SegmentedControl.Root
value={scanMode}
onValueChange={(v) => setScanMode(v as ScanMode)}
disabled={scanning}
size="2"
>
<SegmentedControl.Item value="common">
<Flex align="center" gap="1">
<Icon icon="lucide:star" width="13" height="13" />
{t("scanner.modeCommon")}
</Flex>
</SegmentedControl.Item>
<SegmentedControl.Item value="custom">
<Flex align="center" gap="1">
<Icon icon="lucide:list" width="13" height="13" />
{t("scanner.modeCustom")}
</Flex>
</SegmentedControl.Item>
<SegmentedControl.Item value="full">
<Flex align="center" gap="1">
<Icon icon="lucide:infinity" width="13" height="13" />
{t("scanner.modeFull")}
</Flex>
</SegmentedControl.Item>
</SegmentedControl.Root>
</Flex>
{/* Row 3: custom ports input (only when mode=custom) */}
{scanMode === "custom" && (
<Flex align="center" gap="2" wrap="wrap">
<Box style={{ flex: 1, minWidth: 200, maxWidth: 420 }}>
<TextField.Root
placeholder={t("scanner.customPortsPlaceholder")}
value={customPorts}
onChange={(e) => setCustomPorts(e.target.value)}
disabled={scanning}
/>
</Box>
<Text size="1" color="gray">{t("scanner.customPortsHint")}</Text>
</Flex>
)}
{/* Row 4: full-scan warning */}
{scanMode === "full" && (
<Callout.Root color="amber" size="1">
<Callout.Icon>
<Icon icon="lucide:triangle-alert" width="14" height="14" />
</Callout.Icon>
<Callout.Text>{t("scanner.fullScanWarning")}</Callout.Text>
</Callout.Root>
)}
</Flex>
</Card>
{/* Progress */}
{(scanning || scannedCount > 0) && (
<Flex direction="column" gap="2">
<Flex align="center" justify="between" wrap="wrap" gap="2">
<Flex align="center" gap="3">
{scanning && <Spinner size="1" />}
<Text size="2" color="gray">
{t("scanner.scanned")}: {scannedCount}
{totalPorts > 0 && ` / ${totalPorts}`}
</Text>
<Badge color="green" variant="soft">
<Icon icon="lucide:unlock" width="12" height="12" />
{t("scanner.openPorts")}: {openPorts.length}
</Badge>
{scanDone && (
<Badge color="blue" variant="soft">
<Icon icon="lucide:check" width="12" height="12" />
{t("scanner.complete")}
</Badge>
)}
</Flex>
{totalPorts > 0 && (
<Text size="1" color="gray">{progressPct}%</Text>
)}
</Flex>
{totalPorts > 0 && (
<Progress value={progressPct} size="1" />
)}
</Flex>
)}
{/* Results */}
<AnimatePresence>
{openPorts.length > 0 && (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
<Card>
<Table.Root variant="surface">
<Table.Header>
<Table.Row>
<Table.ColumnHeaderCell>{t("scanner.port")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("scanner.status")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("scanner.service")}</Table.ColumnHeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{[...openPorts]
.sort((a, b) => a.port - b.port)
.map((r) => (
<motion.tr
key={r.port}
initial={{ opacity: 0, x: -8 }}
animate={{ opacity: 1, x: 0 }}
>
<Table.Cell>
<Text size="2" weight="medium" style={{ fontFamily: "monospace" }}>
{r.port}
</Text>
</Table.Cell>
<Table.Cell>
<Badge color="green" variant="soft">
<Icon icon="lucide:unlock" width="12" height="12" />
{t("scanner.open")}
</Badge>
</Table.Cell>
<Table.Cell>
<Text size="2" color="gray">{r.service || "—"}</Text>
</Table.Cell>
</motion.tr>
))}
</Table.Body>
</Table.Root>
</Card>
</motion.div>
)}
</AnimatePresence>
</Flex>
</motion.div>
)}
</Flex>
);
}
-9
View File
@@ -1,9 +0,0 @@
import { useScanner } from "./useScanner";
import { ScannerView } from "./ScannerPage.view";
export function ScannerPage() {
const state = useScanner();
return <ScannerView {...state} />;
}
export default ScannerPage;
-161
View File
@@ -1,161 +0,0 @@
import { useState, useRef, useCallback } from "react";
import { apiGet } from "../../lib/api";
import pb from "../../lib/pocketbase";
export interface Device {
ip: string;
mac: string;
hostname: string;
interface: string;
}
export interface LocalNetwork {
interface: string;
cidr: string;
hosts: number;
}
export interface PortResult {
port: number;
open: boolean;
service: string;
done?: boolean;
}
export type ScanStep = "discover" | "scan";
export type ScanMode = "common" | "custom" | "full";
const COMMON_PORT_COUNT = 23; // mirrors wellKnownPorts in service.go
const FULL_PORT_COUNT = 65535;
export function useScanner() {
const [step, setStep] = useState<ScanStep>("discover");
const [discovering, setDiscovering] = useState(false);
const [devices, setDevices] = useState<Device[]>([]);
const [localNetworks, setLocalNetworks] = useState<LocalNetwork[]>([]);
const [selectedDevice, setSelectedDevice] = useState<Device | null>(null);
const [scanning, setScanning] = useState(false);
const [portResults, setPortResults] = useState<PortResult[]>([]);
const [scanDone, setScanDone] = useState(false);
const [error, setError] = useState<string | null>(null);
const [scanMode, setScanMode] = useState<ScanMode>("common");
const [customPorts, setCustomPorts] = useState("");
const [totalPorts, setTotalPorts] = useState(0);
const esRef = useRef<EventSource | null>(null);
const discoverDevices = useCallback(async () => {
setDiscovering(true);
setDevices([]);
setError(null);
try {
const [netRes, discoverRes] = await Promise.all([
apiGet("/api/scanner/interfaces"),
apiGet("/api/scanner/discover"),
]);
if (netRes.ok) {
const nets: LocalNetwork[] = await netRes.json();
setLocalNetworks(nets ?? []);
}
if (!discoverRes.ok) {
const body = await discoverRes.json().catch(() => ({}));
throw new Error(body.error || `HTTP ${discoverRes.status}`);
}
const data: Device[] = await discoverRes.json();
setDevices(data ?? []);
} catch (e: unknown) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setDiscovering(false);
}
}, []);
const selectDevice = useCallback((device: Device) => {
setSelectedDevice(device);
setPortResults([]);
setScanDone(false);
setStep("scan");
}, []);
const startPortScan = useCallback(() => {
if (!selectedDevice) return;
esRef.current?.close();
setPortResults([]);
setScanDone(false);
setScanning(true);
setError(null);
const token = pb.authStore.token;
const params = new URLSearchParams({ ip: selectedDevice.ip, token });
let total = COMMON_PORT_COUNT;
if (scanMode === "full") {
params.set("full", "true");
total = FULL_PORT_COUNT;
} else if (scanMode === "custom" && customPorts.trim()) {
params.set("ports", customPorts.trim());
total = customPorts.split(",").filter((p) => p.trim()).length;
}
setTotalPorts(total);
const es = new EventSource(`/api/scanner/ports/stream?${params.toString()}`);
esRef.current = es;
es.onmessage = (ev) => {
try {
const result: PortResult = JSON.parse(ev.data);
if (result.done) {
setScanDone(true);
setScanning(false);
es.close();
return;
}
setPortResults((prev) => [...prev, result]);
} catch {
/* ignore */
}
};
es.onerror = () => {
setScanning(false);
setScanDone(true);
es.close();
};
}, [selectedDevice, scanMode, customPorts]);
const stopScan = useCallback(() => {
esRef.current?.close();
setScanning(false);
setScanDone(true);
}, []);
const backToDiscover = useCallback(() => {
stopScan();
setStep("discover");
setSelectedDevice(null);
setPortResults([]);
setScanDone(false);
}, [stopScan]);
return {
step,
discovering,
devices,
localNetworks,
selectedDevice,
scanning,
portResults,
scanDone,
error,
scanMode,
setScanMode,
customPorts,
setCustomPorts,
totalPorts,
discoverDevices,
selectDevice,
startPortScan,
stopScan,
backToDiscover,
};
}
@@ -33,6 +33,9 @@ interface ServersViewProps {
search: string;
setSearch: (value: string) => void;
refreshServers: () => void;
page: number;
setPage: (page: number) => void;
totalPages: number;
}
export function ServersView({
@@ -45,6 +48,9 @@ export function ServersView({
search,
setSearch,
refreshServers,
page,
setPage,
totalPages,
}: ServersViewProps) {
const { t } = useTranslation();
const navigate = useNavigate();
@@ -411,6 +417,65 @@ export function ServersView({
</Table.Body>
</Table.Root>
</div>
{totalPages > 1 && (
<Flex justify="between" align="center" pt="4" px="1">
<Text size="2" color="gray">
{page} / {totalPages}
</Text>
<Flex align="center" style={{ border: "1px solid var(--gray-6)", borderRadius: "var(--radius-3)", overflow: "hidden" }}>
<button
disabled={page === 1}
onClick={() => setPage(page - 1)}
style={{
padding: "6px 10px",
background: "none",
border: "none",
borderRight: "1px solid var(--gray-6)",
cursor: page === 1 ? "not-allowed" : "pointer",
opacity: page === 1 ? 0.4 : 1,
display: "flex",
alignItems: "center",
}}
>
<Icon icon="lucide:chevron-left" width="14" height="14" />
</button>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
<button
key={p}
onClick={() => setPage(p)}
style={{
padding: "6px 12px",
background: p === page ? "var(--accent-9)" : "none",
color: p === page ? "white" : "inherit",
border: "none",
borderRight: p === totalPages ? "none" : "1px solid var(--gray-6)",
cursor: "pointer",
fontSize: "var(--font-size-2)",
fontWeight: p === page ? 600 : 400,
}}
>
{p}
</button>
))}
<button
disabled={page === totalPages}
onClick={() => setPage(page + 1)}
style={{
padding: "6px 10px",
background: "none",
border: "none",
borderLeft: "1px solid var(--gray-6)",
cursor: page === totalPages ? "not-allowed" : "pointer",
opacity: page === totalPages ? 0.4 : 1,
display: "flex",
alignItems: "center",
}}
>
<Icon icon="lucide:chevron-right" width="14" height="14" />
</button>
</Flex>
</Flex>
)}
</motion.div>
)}
</AnimatePresence>