Author SHA1 Message Date
刘嘉伟 d7076400b1 🚧 Cloudflare tunnel support. 2026-03-31 14:26:00 +08:00
刘嘉伟 b86b7222cb 🚧 Cloudflare tunnel support. 2026-03-27 17:27:53 +08:00
刘嘉伟 f1d4c7385d 🚧 Cloudflare tunnel support. 2026-03-27 17:26:41 +08:00
刘嘉伟 8578c204ab 🚧 Cloudflare tunnel support. 2026-03-27 15:37:18 +08:00
刘嘉伟 2f4320eda1 🚧 Cloudflare tunnel support. 2026-03-27 15:34:05 +08:00
64 changed files with 4311 additions and 659 deletions

No files matched your search

+30 -17
View File
@@ -4,9 +4,10 @@ import (
proxyapp "podux/internal/application/proxy"
serverapp "podux/internal/application/server"
proxydomain "podux/internal/domain/proxy"
serverdomain "podux/internal/domain/server"
tunneldomain "podux/internal/domain/tunnel"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
)
@@ -22,10 +23,10 @@ type DashboardStats struct {
}
type TopologyServerItem struct {
ID string `json:"id" db:"id"`
ServerName string `json:"serverName" db:"serverName"`
ServerAddr string `json:"serverAddr" db:"serverAddr"`
BootStatus string `json:"bootStatus" db:"bootStatus"`
ID string `json:"id" db:"id"`
ServerName string `json:"serverName" db:"serverName"`
ServerAddr string `json:"serverAddr" db:"serverAddr"`
TunnelStatus string `json:"bootStatus" db:"tunnelStatus"`
}
type TopologyProxyItem struct {
@@ -49,28 +50,29 @@ type Service struct {
app core.App
serverService *serverapp.Service
proxyService *proxyapp.Service
tunnelRepo tunneldomain.Repository
startTime time.Time
}
func NewService(app core.App, serverService *serverapp.Service, proxyService *proxyapp.Service) *Service {
func NewService(app core.App, serverService *serverapp.Service, proxyService *proxyapp.Service, tunnelRepo tunneldomain.Repository) *Service {
return &Service{
app: app,
serverService: serverService,
proxyService: proxyService,
tunnelRepo: tunnelRepo,
startTime: time.Now(),
}
}
func (s *Service) GetStats() (*DashboardStats, error) {
runningCount, err := s.serverService.GetServerCountByStatus(serverdomain.ServerStatusRunning)
if err != nil {
return nil, err
}
stoppedCount, err := s.serverService.GetServerCountByStatus(serverdomain.ServerStatusStopped)
if err != nil {
return nil, err
}
// Running/stopped server counts derived from FRP tunnel statuses.
var runningCount, stoppedCount int64
s.app.DB().Select("COUNT(*)").From("th_tunnels").
Where(dbx.And(dbx.HashExp{"type": "frp"}, dbx.HashExp{"status": string(tunneldomain.TunnelStatusActive)})).
Row(&runningCount)
s.app.DB().Select("COUNT(*)").From("th_tunnels").
Where(dbx.And(dbx.HashExp{"type": "frp"}, dbx.HashExp{"status": string(tunneldomain.TunnelStatusInactive)})).
Row(&stoppedCount)
proxiesEnabledCount, err := s.proxyService.GetProxyCountByStatus(proxydomain.ProxyStatusEnabled)
if err != nil {
@@ -110,16 +112,27 @@ func (s *Service) GetStats() (*DashboardStats, error) {
}
func (s *Service) GetTopology() (*TopologyData, error) {
// Servers: join with th_tunnels (type=frp) to get running status.
var servers []TopologyServerItem
if err := s.app.DB().Select("id", "serverName", "serverAddr", "bootStatus").From("fh_servers").All(&servers); err != nil {
err := s.app.DB().
Select("fs.id", "fs.serverName", "fs.serverAddr",
"COALESCE(tt.status, 'inactive') as tunnelStatus").
From("fh_servers fs").
LeftJoin("th_tunnels tt", dbx.NewExp("tt.serverId = fs.id AND tt.serverId IS NOT NULL AND tt.serverId != ''")).
All(&servers)
if err != nil {
return nil, err
}
if servers == nil {
servers = []TopologyServerItem{}
}
// Proxies: bootStatus still comes from fh_proxies directly.
var proxies []TopologyProxyItem
if err := s.app.DB().Select("id", "name", "proxyType", "localIP", "localPort", "remotePort", "status", "bootStatus", "serverId").From("fh_proxies").All(&proxies); err != nil {
if err := s.app.DB().
Select("id", "name", "proxyType", "localIP", "localPort", "remotePort", "status", "bootStatus", "serverId").
From("fh_proxies").
All(&proxies); err != nil {
return nil, err
}
if proxies == nil {
@@ -0,0 +1,116 @@
package integration
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"github.com/pocketbase/pocketbase/core"
)
// CloudflareService manages the lifecycle of Cloudflare tunnels and route
// synchronisation for a given integration record.
type CloudflareService struct {
app core.App
logger *slog.Logger
}
func NewCloudflareService(app core.App) *CloudflareService {
return &CloudflareService{app: app, logger: app.Logger()}
}
// IntegrationMeta is the shape stored in fh_integrations.metadata.
type IntegrationMeta struct {
Accounts []CloudflareAccount `json:"accounts"`
Tunnel *TunnelInfo `json:"tunnel,omitempty"`
}
// SyncTunnelForProxy is called after a cloudflare proxy is created, updated, or
// deleted. It ensures a tunnel exists for the integration and pushes the current
// full ingress config to Cloudflare.
func (s *CloudflareService) SyncTunnelForProxy(ctx context.Context, integrationID string) error {
logger := s.logger.With("integrationId", integrationID)
// 1. Load integration record
record, err := s.app.FindRecordById("fh_integrations", integrationID)
if err != nil {
return fmt.Errorf("find integration: %w", err)
}
apiToken := record.GetString("credentials")
if apiToken == "" {
return fmt.Errorf("integration has no credentials")
}
// 2. Parse metadata
var meta IntegrationMeta
rawMeta := record.Get("metadata")
if rawMeta != nil {
b, _ := json.Marshal(rawMeta)
_ = json.Unmarshal(b, &meta)
}
if len(meta.Accounts) == 0 {
return fmt.Errorf("integration has no validated accounts; validate first")
}
accountID := meta.Accounts[0].ID
// 3. Ensure tunnel exists
tunnel, err := EnsureTunnel(ctx, apiToken, accountID, meta.Tunnel, logger)
if err != nil {
return fmt.Errorf("ensure tunnel: %w", err)
}
// Persist tunnel info back if it was just created
if meta.Tunnel == nil || meta.Tunnel.ID == "" {
meta.Tunnel = tunnel
metaBytes, _ := json.Marshal(meta)
var metaMap map[string]any
_ = json.Unmarshal(metaBytes, &metaMap)
record.Set("metadata", metaMap)
if saveErr := s.app.Save(record); saveErr != nil {
logger.Error("failed to persist tunnel metadata", "error", saveErr)
}
}
// 4. Collect all enabled cloudflare proxies for this integration
proxies, err := s.app.FindRecordsByFilter(
"fh_proxies",
`type = "cloudflare" && integrationId = {:integrationId} && status = "enabled"`,
"-created", 0, 0,
map[string]any{"integrationId": integrationID},
)
if err != nil {
return fmt.Errorf("list proxies: %w", err)
}
// 5. Build ingress routes
routes := make([]IngressRoute, 0, len(proxies))
for _, p := range proxies {
domains, ok := p.Get("customDomains").([]any)
if !ok || len(domains) == 0 {
continue
}
localIP := p.GetString("localIP")
if localIP == "" {
localIP = "127.0.0.1"
}
localPort := p.GetString("localPort")
if localPort == "" {
continue
}
service := fmt.Sprintf("http://%s:%s", localIP, localPort)
// Each hostname in customDomains gets its own ingress entry
for _, d := range domains {
hostname, _ := d.(string)
if hostname == "" {
continue
}
routes = append(routes, IngressRoute{Hostname: hostname, Service: service})
}
}
// 6. Push ingress config to Cloudflare
return SyncIngress(ctx, apiToken, accountID, tunnel.ID, routes, logger)
}
@@ -0,0 +1,147 @@
package integration
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
)
// TunnelInfo holds a Cloudflare tunnel's identity and secret token.
// It is persisted inside fh_integrations.metadata under the key "tunnel".
type TunnelInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Token string `json:"token"`
}
// IngressRoute maps a public hostname to an internal service URL.
type IngressRoute struct {
Hostname string
Service string // e.g. "http://127.0.0.1:3000"
}
// EnsureTunnel returns the existing tunnel for the integration, or creates a new
// one named "podux" under the given Cloudflare account.
// It returns the up-to-date TunnelInfo; callers must persist it back to metadata.
func EnsureTunnel(ctx context.Context, apiToken, accountID string, existing *TunnelInfo, logger *slog.Logger) (*TunnelInfo, error) {
if existing != nil && existing.ID != "" && existing.Token != "" {
logger.Debug("cloudflare tunnel already exists", "tunnelId", existing.ID)
return existing, nil
}
logger.Info("creating cloudflare tunnel", "accountId", accountID)
body, _ := json.Marshal(map[string]any{
"name": "podux",
"config_src": "cloudflare",
})
url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/cfd_tunnel", accountID)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("build request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+apiToken)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("network error: %w", err)
}
defer resp.Body.Close()
var result struct {
Success bool `json:"success"`
Errors []struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"errors"`
Result struct {
ID string `json:"id"`
Name string `json:"name"`
Token string `json:"token"`
} `json:"result"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
if !result.Success {
if len(result.Errors) > 0 {
return nil, fmt.Errorf("cloudflare: %s (code %d)", result.Errors[0].Message, result.Errors[0].Code)
}
return nil, fmt.Errorf("cloudflare: create tunnel failed")
}
info := &TunnelInfo{
ID: result.Result.ID,
Name: result.Result.Name,
Token: result.Result.Token,
}
logger.Info("cloudflare tunnel created", "tunnelId", info.ID, "tunnelName", info.Name)
return info, nil
}
// SyncIngress pushes the full ingress configuration (all routes + catch-all) to
// the Cloudflare tunnel. A catch-all "http_status:404" rule is always appended.
func SyncIngress(ctx context.Context, apiToken, accountID, tunnelID string, routes []IngressRoute, logger *slog.Logger) error {
logger.Info("syncing cloudflare tunnel ingress", "tunnelId", tunnelID, "routeCount", len(routes))
type ingressEntry struct {
Hostname string `json:"hostname,omitempty"`
Service string `json:"service"`
}
ingress := make([]ingressEntry, 0, len(routes)+1)
for _, r := range routes {
ingress = append(ingress, ingressEntry{Hostname: r.Hostname, Service: r.Service})
}
// Cloudflare requires a catch-all entry with no hostname
ingress = append(ingress, ingressEntry{Service: "http_status:404"})
payload := map[string]any{
"config": map[string]any{
"ingress": ingress,
},
}
body, _ := json.Marshal(payload)
url := fmt.Sprintf(
"https://api.cloudflare.com/client/v4/accounts/%s/cfd_tunnel/%s/configurations",
accountID, tunnelID,
)
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("build request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+apiToken)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("network error: %w", err)
}
defer resp.Body.Close()
var result struct {
Success bool `json:"success"`
Errors []struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"errors"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("decode response: %w", err)
}
if !result.Success {
if len(result.Errors) > 0 {
return fmt.Errorf("cloudflare: %s (code %d)", result.Errors[0].Message, result.Errors[0].Code)
}
return fmt.Errorf("cloudflare: sync ingress failed")
}
logger.Info("cloudflare tunnel ingress synced", "tunnelId", tunnelID, "routeCount", len(routes))
return nil
}
@@ -0,0 +1,95 @@
// Package integration provides validation helpers for external service integrations.
package integration
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
)
// CloudflareAccount holds the identifier and display name of a Cloudflare account
// returned by the /v4/accounts endpoint.
type CloudflareAccount struct {
ID string `json:"id"`
Name string `json:"name"`
}
// maskToken returns a redacted representation of a credential token safe for logging.
// e.g. "abcd1234efgh5678" → "abcd****5678"
// Tokens shorter than 8 characters are replaced entirely with "****".
func maskToken(token string) string {
if len(token) <= 8 {
return "****"
}
return token[:4] + "****" + token[len(token)-4:]
}
// ValidateCloudflare calls GET /v4/accounts to verify the token and returns
// the list of accessible accounts. The caller should persist the result in
// the record metadata.
func ValidateCloudflare(ctx context.Context, token string, logger *slog.Logger) ([]CloudflareAccount, error) {
logger.Info("cloudflare validation started", "token", maskToken(token))
req, err := http.NewRequestWithContext(
ctx, http.MethodGet,
"https://api.cloudflare.com/client/v4/accounts",
nil,
)
if err != nil {
logger.Error("cloudflare: failed to build request", "error", err)
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
logger.Error("cloudflare: network error", "error", err)
return nil, fmt.Errorf("network error: %w", err)
}
defer resp.Body.Close()
logger.Debug("cloudflare API response received", "statusCode", resp.StatusCode)
var body struct {
Success bool `json:"success"`
Errors []struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"errors"`
Result []struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"result"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
logger.Error("cloudflare: failed to decode response", "error", err)
return nil, fmt.Errorf("decode response: %w", err)
}
if !body.Success {
if len(body.Errors) > 0 {
err := fmt.Errorf("cloudflare: %s (code %d)", body.Errors[0].Message, body.Errors[0].Code)
logger.Warn("cloudflare validation rejected",
"code", body.Errors[0].Code,
"message", body.Errors[0].Message,
"token", maskToken(token),
)
return nil, err
}
logger.Warn("cloudflare validation failed without details", "token", maskToken(token))
return nil, fmt.Errorf("cloudflare validation failed")
}
accounts := make([]CloudflareAccount, 0, len(body.Result))
for _, a := range body.Result {
accounts = append(accounts, CloudflareAccount{ID: a.ID, Name: a.Name})
}
logger.Info("cloudflare validation passed",
"accountCount", len(accounts),
"token", maskToken(token),
)
return accounts, nil
}
-14
View File
@@ -15,20 +15,6 @@ func NewService(app core.App, repo serverdomain.Repository) *Service {
return &Service{app: app, repo: repo}
}
func (s *Service) GetServerCountByStatus(status serverdomain.ServerStatus) (int64, error) {
return s.repo.CountByBootStatus(status)
}
func (s *Service) UpdateServerBootStatus(serverID string, status serverdomain.ServerStatus) error {
return s.repo.UpdateBootStatus(serverID, status)
}
func (s *Service) ResetAllServerStatus() {
if err := s.repo.ResetAllBootStatus(); err != nil {
s.app.Logger().Error("ResetAllServerStatus failed", "error", err)
}
}
func (s *Service) GetMaxLatency() (int64, error) {
return s.repo.GetMaxLatency()
}
@@ -0,0 +1,229 @@
// Package cloudflare manages cloudflared daemon processes, one per integration.
// It implements tunnel.Provider.
package cloudflare
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
"podux/internal/application/integration"
"podux/internal/application/tunnel"
proxydomain "podux/internal/domain/proxy"
tunneldomain "podux/internal/domain/tunnel"
"podux/pkg/binary"
"github.com/pocketbase/pocketbase/core"
)
// Provider manages cloudflared tunnel daemon processes, one per integration.
// It implements tunnel.Provider.
type Provider struct {
app core.App
proxyRepo proxydomain.Repository
tunnelRepo tunneldomain.Repository
mu sync.RWMutex
processes map[string]*os.Process
cancelFns map[string]context.CancelFunc
}
func NewProvider(app core.App, proxyRepo proxydomain.Repository, tunnelRepo tunneldomain.Repository) *Provider {
return &Provider{
app: app,
proxyRepo: proxyRepo,
tunnelRepo: tunnelRepo,
processes: make(map[string]*os.Process),
cancelFns: make(map[string]context.CancelFunc),
}
}
func (p *Provider) logDir(id string) string {
return filepath.Join("pb_data", "cloudflare", id)
}
func (p *Provider) logPath(id string) string {
return filepath.Join(p.logDir(id), "cloudflared.log")
}
// Launch starts cloudflared for the given integration ID. Implements tunnel.Provider.
func (p *Provider) Launch(id string) error {
if p.IsRunning(id) {
return fmt.Errorf("cloudflared already running for integration %s", id)
}
p.app.Logger().Info("launching cloudflared", "integrationId", id)
// 1. Load integration record and tunnel token from metadata.
record, err := p.app.FindRecordById("fh_integrations", id)
if err != nil {
return fmt.Errorf("find integration: %w", err)
}
var meta integration.IntegrationMeta
if rawMeta := record.Get("metadata"); rawMeta != nil {
b, _ := json.Marshal(rawMeta)
_ = json.Unmarshal(b, &meta)
}
if meta.Tunnel == nil || meta.Tunnel.Token == "" {
return fmt.Errorf("integration %s has no tunnel token; create a cloudflare proxy first", id)
}
token := meta.Tunnel.Token
// 2. Ensure cloudflared binary is installed.
binDir, err := binary.DefaultBinDir()
if err != nil {
return fmt.Errorf("resolve bin dir: %w", err)
}
mgr := binary.New("cloudflared", "latest", binDir)
installCtx, installCancel := context.WithTimeout(context.Background(), 120*time.Second)
defer installCancel()
if err := mgr.EnsureInstalled(installCtx); err != nil {
return fmt.Errorf("install cloudflared: %w", err)
}
// 3. Prepare log file.
if err := os.MkdirAll(p.logDir(id), 0755); err != nil {
return fmt.Errorf("create log dir: %w", err)
}
logFile, err := os.OpenFile(p.logPath(id), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("open log file: %w", err)
}
// 4. Start cloudflared process.
runCtx, runCancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(runCtx, mgr.GetPath(), "tunnel", "--no-autoupdate", "run", "--token", token)
cmd.Stdout = logFile
cmd.Stderr = logFile
if err := cmd.Start(); err != nil {
runCancel()
logFile.Close()
return fmt.Errorf("start cloudflared: %w", err)
}
p.mu.Lock()
p.processes[id] = cmd.Process
p.cancelFns[id] = runCancel
p.mu.Unlock()
p.app.Logger().Info("cloudflared started", "integrationId", id, "pid", cmd.Process.Pid)
// 5. Monitor process exit and update statuses.
go func() {
defer logFile.Close()
if err := cmd.Wait(); err != nil && runCtx.Err() == nil {
p.app.Logger().Error("cloudflared exited unexpectedly", "integrationId", id, "error", err)
} else {
p.app.Logger().Info("cloudflared stopped", "integrationId", id)
}
p.cleanup(id)
}()
// Mark tunnel active and proxies online after a brief startup window.
go func() {
time.Sleep(3 * time.Second)
if p.IsRunning(id) {
p.tunnelRepo.UpdateStatusByIntegrationID(id, tunneldomain.TunnelStatusActive)
p.proxyRepo.UpdateBootStatusByIntegrationID(id, proxydomain.ProxyBootStatusOnline)
}
}()
return nil
}
// Terminate stops the cloudflared process for the given integration ID. Implements tunnel.Provider.
func (p *Provider) Terminate(id string) error {
p.app.Logger().Info("terminating cloudflared", "integrationId", id)
p.mu.RLock()
cancel, exists := p.cancelFns[id]
p.mu.RUnlock()
if !exists {
return nil
}
cancel()
p.app.Logger().Info("cloudflared stop signal sent", "integrationId", id)
return nil
}
// Reload is a no-op for cloudflared: tunnels with config_src=cloudflare
// automatically poll for ingress changes from the Cloudflare API.
// Implements tunnel.Provider.
func (p *Provider) Reload(id string) error {
p.app.Logger().Debug("cloudflare tunnel reload is a no-op (cloudflare-managed config)", "integrationId", id)
return nil
}
// IsRunning reports whether cloudflared is running for the given integration. Implements tunnel.Provider.
func (p *Provider) IsRunning(id string) bool {
p.mu.RLock()
_, exists := p.processes[id]
p.mu.RUnlock()
return exists
}
// AutoStart starts cloudflared for all active integrations that have a tunnel token.
// Implements tunnel.Provider.
func (p *Provider) AutoStart() {
p.app.Logger().Info("waiting 10s before auto-starting cloudflare tunnels")
time.Sleep(10 * time.Second)
records, err := p.app.FindRecordsByFilter(
"fh_integrations",
`integrationsType = "cloudflare" && status = "active"`,
"-created", 0, 0, nil,
)
if err != nil {
p.app.Logger().Error("cloudflare auto-start: failed to list integrations", "error", err)
return
}
count := 0
for _, record := range records {
var meta integration.IntegrationMeta
if rawMeta := record.Get("metadata"); rawMeta != nil {
b, _ := json.Marshal(rawMeta)
_ = json.Unmarshal(b, &meta)
}
if meta.Tunnel == nil || meta.Tunnel.Token == "" {
continue
}
integrationId := record.Id
p.app.Logger().Info("auto-starting cloudflare tunnel", "integrationId", integrationId)
go func(id string, delay int) {
time.Sleep(time.Duration(delay) * 500 * time.Millisecond)
if err := p.Launch(id); err != nil {
p.app.Logger().Error("cloudflare auto-start failed", "integrationId", id, "error", err)
}
}(integrationId, count)
count++
time.Sleep(1 * time.Second)
}
p.app.Logger().Info("cloudflare auto-start initiated", "count", count)
}
// StreamLog streams the cloudflared log file via SSE. Implements tunnel.Provider.
func (p *Provider) StreamLog(id string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher) {
tunnel.StreamLogFile(ctx, w, flusher, p.logPath(id), 50)
}
func (p *Provider) cleanup(id string) {
p.mu.Lock()
delete(p.processes, id)
delete(p.cancelFns, id)
p.mu.Unlock()
p.tunnelRepo.UpdateStatusByIntegrationID(id, tunneldomain.TunnelStatusInactive)
p.proxyRepo.UpdateBootStatusByIntegrationID(id, proxydomain.ProxyBootStatusOffline)
}
@@ -1,12 +1,12 @@
package frpc
// Package frp manages frp client processes, one per server.
// It implements tunnel.Provider.
package frp
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/signal"
@@ -16,9 +16,10 @@ import (
"syscall"
"time"
"podux/internal/application/tunnel"
proxydomain "podux/internal/domain/proxy"
serverdomain "podux/internal/domain/server"
"podux/pkg/utils"
tunneldomain "podux/internal/domain/tunnel"
"github.com/fatedier/frp/client"
frpcsource "github.com/fatedier/frp/pkg/config/source"
@@ -30,73 +31,69 @@ import (
var validServerID = regexp.MustCompile(`^[a-z0-9]{15}$`)
var sensitiveRegex = regexp.MustCompile(`"(?i)(token|password|sk|pwd|secretkey|httpuser|httppwd|oidctoken|oidcclientsecret)":"(?:[^"\\]|\\.)*"`)
type Service struct {
// Provider manages frp client processes, one per server. It implements tunnel.Provider.
type Provider struct {
mu sync.RWMutex
app core.App
processes map[string]*client.Service
statusMonitors map[string]context.CancelFunc
serverRepo serverdomain.Repository
proxyRepo proxydomain.Repository
tunnelRepo tunneldomain.Repository
}
func NewService(app core.App, serverRepo serverdomain.Repository, proxyRepo proxydomain.Repository) *Service {
return &Service{
func NewProvider(app core.App, serverRepo serverdomain.Repository, proxyRepo proxydomain.Repository, tunnelRepo tunneldomain.Repository) *Provider {
return &Provider{
app: app,
processes: make(map[string]*client.Service),
statusMonitors: make(map[string]context.CancelFunc),
serverRepo: serverRepo,
proxyRepo: proxyRepo,
tunnelRepo: tunnelRepo,
}
}
func (fs *Service) genCommonCfgs(id *string) (*v1.ClientCommonConfig, error) {
if !validServerID.MatchString(*id) {
func (p *Provider) genCommonCfgs(id string) (*v1.ClientCommonConfig, error) {
if !validServerID.MatchString(id) {
return nil, errors.New("invalid server id")
}
cfg := &v1.ClientCommonConfig{}
record, err := fs.app.FindRecordById("fh_servers", *id)
record, err := p.app.FindRecordById("fh_servers", id)
if err != nil {
return nil, err
}
// basic config
cfg.ServerAddr = record.GetString("serverAddr")
cfg.ServerPort = record.GetInt("serverPort")
cfg.User = record.GetString("user")
logDirPath := filepath.Join("pb_data", "frpc", *id)
logDirPath := filepath.Join("pb_data", "frpc", id)
if err := os.MkdirAll(logDirPath, 0755); err != nil {
return nil, err
}
// log config
logStr := record.GetString("log")
mainPath := fs.getFrpMainPath(id)
mainPath := p.mainPath(id)
var logConfig v1.LogConfig
err = json.Unmarshal([]byte(logStr), &logConfig)
if err != nil {
if err = json.Unmarshal([]byte(logStr), &logConfig); err != nil {
return nil, err
}
logPath := filepath.Join(mainPath, "logs", "frpc.log")
logConfig.To = logPath
cfg.Log = logConfig
// auth config
authStr := record.GetString("auth")
var authConfig v1.AuthClientConfig
err = json.Unmarshal([]byte(authStr), &authConfig)
if err != nil {
if err = json.Unmarshal([]byte(authStr), &authConfig); err != nil {
return nil, err
}
if authConfig.Method != "none" && authConfig.Method != "" {
cfg.Auth = authConfig
}
// transport config
transportStr := record.GetString("transport")
var transportConfig v1.ClientTransportConfig
err = json.Unmarshal([]byte(transportStr), &transportConfig)
if err != nil {
if err = json.Unmarshal([]byte(transportStr), &transportConfig); err != nil {
return nil, err
}
cfg.Transport = transportConfig
@@ -136,21 +133,19 @@ func (fs *Service) genCommonCfgs(id *string) (*v1.ClientCommonConfig, error) {
}
}
// metadata config
metadataStr := record.GetString("metadatas")
var metadataConfig map[string]string
err = json.Unmarshal([]byte(metadataStr), &metadataConfig)
if err != nil {
if err = json.Unmarshal([]byte(metadataStr), &metadataConfig); err != nil {
return nil, err
}
cfg.Metadatas = metadataConfig
return cfg, nil
}
func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error) {
proxies, err := fs.proxyRepo.FindEnabledByServerID(*serverId)
func (p *Provider) genProxyCfgs(serverId string) ([]v1.ProxyConfigurer, error) {
proxies, err := p.proxyRepo.FindEnabledByServerID(serverId)
if err != nil {
fs.app.Logger().Error("genProxyCfgs", "err", err)
p.app.Logger().Error("genProxyCfgs", "err", err)
return nil, err
}
@@ -161,7 +156,6 @@ func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error)
return nil, err
}
// Convert to map to manipulate fields
var proxyData map[string]interface{}
if err := json.Unmarshal(jsonData, &proxyData); err != nil {
return nil, err
@@ -172,7 +166,6 @@ func (fs *Service) genProxyCfgs(serverId *string) ([]v1.ProxyConfigurer, error)
}
proxyData["name"] = proxyMap.Name + "-" + proxyMap.Id
// Remove empty plugin map so frp doesn't try to parse a typeless plugin
if plugin, ok := proxyData["plugin"].(map[string]interface{}); ok {
if _, hasType := plugin["type"]; !hasType {
delete(proxyData, "plugin")
@@ -222,28 +215,26 @@ func handleTermSignal(svr *client.Service) {
svr.GracefulClose(500 * time.Millisecond)
}
func (fs *Service) LaunchFrpc(serverId *string) error {
fs.app.Logger().Info("Launch frpc", "id", *serverId)
cfg, err := fs.genCommonCfgs(serverId)
// Launch starts the frp client for the given server ID. Implements tunnel.Provider.
func (p *Provider) Launch(id string) error {
p.app.Logger().Info("Launch frpc", "id", id)
cfg, err := p.genCommonCfgs(id)
if err != nil {
return err
}
proxyCfgs, err := fs.genProxyCfgs(serverId)
proxyCfgs, err := p.genProxyCfgs(id)
if err != nil {
return err
}
fs.app.Logger().Debug("Config", "serverAddr", cfg.ServerAddr, "serverPort", cfg.ServerPort, "proxyCount", len(proxyCfgs))
p.app.Logger().Debug("Config", "serverAddr", cfg.ServerAddr, "serverPort", cfg.ServerPort, "proxyCount", len(proxyCfgs))
// Print frp configurations in logs with sensitive data masked
commonCfgBytes, _ := json.Marshal(cfg)
proxyCfgsBytes, _ := json.Marshal(proxyCfgs)
safeCommon := sensitiveRegex.ReplaceAll(commonCfgBytes, []byte(`"${1}":"***"`))
safeProxies := sensitiveRegex.ReplaceAll(proxyCfgsBytes, []byte(`"${1}":"***"`))
fs.app.Logger().Info("FRP Configuration", "common", string(safeCommon), "proxies", string(safeProxies))
p.app.Logger().Info("FRP Configuration", "common", string(safeCommon), "proxies", string(safeProxies))
cfg.Complete()
log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
@@ -257,58 +248,53 @@ func (fs *Service) LaunchFrpc(serverId *string) error {
ConfigSourceAggregator: frpcsource.NewAggregator(configSrc),
})
if err != nil {
fs.app.Logger().Error("NewService", "err", err)
p.app.Logger().Error("NewService", "err", err)
return err
}
shouldGracefulClose := cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic"
if shouldGracefulClose {
if cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic" {
go handleTermSignal(svr)
}
ctx, cancel := context.WithCancel(context.Background())
fs.mu.Lock()
fs.processes[*serverId] = svr
fs.statusMonitors[*serverId] = cancel
fs.mu.Unlock()
fs.serverRepo.UpdateBootStatus(*serverId, serverdomain.ServerStatusRunning)
ctx, cancel := context.WithCancel(context.Background())
p.mu.Lock()
p.processes[id] = svr
p.statusMonitors[id] = cancel
p.mu.Unlock()
done := make(chan error, 1)
go func() {
fs.app.Logger().Info("Frpc service starting execution", "id", *serverId)
p.app.Logger().Info("Frpc service starting execution", "id", id)
err := svr.Run(ctx)
if err != nil {
fs.app.Logger().Error("Frpc service exited with error", "id", *serverId, "error", err)
p.app.Logger().Error("Frpc service exited with error", "id", id, "error", err)
} else {
fs.app.Logger().Info("Frpc service exited normally", "id", *serverId)
p.app.Logger().Info("Frpc service exited normally", "id", id)
}
done <- err
}()
go fs.monitorServiceStatus(serverId, svr, ctx, done)
go p.monitorServiceStatus(id, 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) {
func (p *Provider) monitorServiceStatus(id string, svr *client.Service, ctx context.Context, done <-chan error) {
time.Sleep(2 * time.Second)
select {
case err := <-done:
fs.app.Logger().Error("Service exited during startup", "id", *id, "error", err)
fs.destroying(id)
p.app.Logger().Error("Service exited during startup", "id", id, "error", err)
p.destroying(id)
return
case <-ctx.Done():
fs.app.Logger().Info("Service context cancelled during startup", "id", *id)
fs.destroying(id)
p.app.Logger().Info("Service context cancelled during startup", "id", id)
p.destroying(id)
return
default:
fs.serverRepo.UpdateBootStatus(*id, serverdomain.ServerStatusRunning)
fs.app.Logger().Info("Service is running", "id", *id)
p.tunnelRepo.UpdateStatusByServerID(id, tunneldomain.TunnelStatusActive)
p.app.Logger().Info("Service is running", "id", id)
}
go fs.monitorProxyStatus(id, svr, ctx)
go p.monitorProxyStatus(id, svr, ctx)
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
@@ -317,34 +303,33 @@ func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx con
select {
case err := <-done:
if err != nil {
fs.app.Logger().Error("Service exited with error", "id", *id, "error", err)
p.app.Logger().Error("Service exited with error", "id", id, "error", err)
} else {
fs.app.Logger().Info("Service exited normally", "id", *id)
p.app.Logger().Info("Service exited normally", "id", id)
}
fs.destroying(id)
p.destroying(id)
return
case <-ctx.Done():
fs.app.Logger().Info("Service stopped by user", "id", *id)
fs.destroying(id)
p.app.Logger().Info("Service stopped by user", "id", id)
p.destroying(id)
return
case <-ticker.C:
fs.app.Logger().Debug("Service status check", "id", *id, "status", "running")
p.app.Logger().Debug("Service status check", "id", id, "status", "running")
}
}
}
func (fs *Service) destroying(id *string) {
fs.serverRepo.UpdateBootStatus(*id, serverdomain.ServerStatusStopped)
fs.proxyRepo.UpdateBootStatusByServerID(*id, proxydomain.ProxyBootStatusOffline)
fs.mu.Lock()
delete(fs.processes, *id)
delete(fs.statusMonitors, *id)
fs.mu.Unlock()
func (p *Provider) destroying(id string) {
p.tunnelRepo.UpdateStatusByServerID(id, tunneldomain.TunnelStatusInactive)
p.proxyRepo.UpdateBootStatusByServerID(id, proxydomain.ProxyBootStatusOffline)
p.mu.Lock()
delete(p.processes, id)
delete(p.statusMonitors, id)
p.mu.Unlock()
}
// monitorProxyStatus monitors proxy status from frp and updates the database.
func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx context.Context) {
fs.app.Logger().Info("Starting proxy status monitoring", "serverId", *serverId)
func (p *Provider) monitorProxyStatus(serverId string, svr *client.Service, ctx context.Context) {
p.app.Logger().Info("Starting proxy status monitoring", "serverId", serverId)
statusExporter := svr.StatusExporter()
@@ -354,19 +339,19 @@ func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx
for {
select {
case <-ctx.Done():
fs.app.Logger().Info("Proxy status monitoring stopped", "serverId", *serverId)
p.app.Logger().Info("Proxy status monitoring stopped", "serverId", serverId)
return
case <-ticker.C:
proxies, err := fs.proxyRepo.FindByServerID(*serverId)
proxies, err := p.proxyRepo.FindByServerID(serverId)
if err != nil {
fs.app.Logger().Error("Failed to get proxies", "serverId", *serverId, "error", err)
p.app.Logger().Error("Failed to get proxies", "serverId", serverId, "error", err)
continue
}
for _, proxy := range proxies {
baseName := proxy.Name + "-" + proxy.Id
status, exists := statusExporter.GetProxyStatus(baseName)
fs.app.Logger().Info("proxy status check", "baseName", baseName, "exists", exists, "phase", func() string {
p.app.Logger().Info("proxy status check", "baseName", baseName, "exists", exists, "phase", func() string {
if status != nil {
return status.Phase
}
@@ -383,149 +368,70 @@ func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx
default:
bootStatus = proxydomain.ProxyBootStatusOffline
}
fs.proxyRepo.UpdateBootStatus(proxy.Id, bootStatus)
p.proxyRepo.UpdateBootStatus(proxy.Id, bootStatus)
} else {
// Proxy is not in frp (disabled or removed) — mark as offline
fs.proxyRepo.UpdateBootStatus(proxy.Id, proxydomain.ProxyBootStatusOffline)
p.proxyRepo.UpdateBootStatus(proxy.Id, proxydomain.ProxyBootStatusOffline)
}
}
}
}
}
// TerminateFrpc stops the specified frpc service.
func (fs *Service) TerminateFrpc(id *string) error {
fs.app.Logger().Info("Stop frpc", "id", *id)
// Terminate stops the frp client for the given server ID. Implements tunnel.Provider.
func (p *Provider) Terminate(id string) error {
p.app.Logger().Info("Stop frpc", "id", id)
fs.mu.RLock()
cancel, exists := fs.statusMonitors[*id]
fs.mu.RUnlock()
p.mu.RLock()
cancel, exists := p.statusMonitors[id]
p.mu.RUnlock()
if !exists {
return nil
}
cancel()
fs.app.Logger().Info("Frpc stop signal sent", "id", *id)
p.app.Logger().Info("Frpc stop signal sent", "id", id)
return nil
}
func (fs *Service) getFrpMainPath(id *string) string {
return filepath.Join("pb_data", "frpc", *id)
}
// Reload hot-reloads the proxy configuration for the given server. Implements tunnel.Provider.
func (p *Provider) Reload(id string) error {
p.app.Logger().Info("Reload frpc", "id", id)
// StreamLog streams the frpc log file via SSE.
// It sends the last 50 lines as initial content, then tails new lines every 500ms.
func (fs *Service) StreamLog(serverId string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher) {
if !validServerID.MatchString(serverId) {
fmt.Fprintf(w, "data: [invalid server id]\n\n")
flusher.Flush()
return
}
mainPath := fs.getFrpMainPath(&serverId)
logPath := filepath.Join(mainPath, "logs", "frpc.log")
file, err := os.Open(logPath)
if err != nil {
fs.app.Logger().Warn("Log file not found", "serverId", serverId, "path", logPath, "error", err)
fmt.Fprintf(w, "data: [No log file found]\n\n")
flusher.Flush()
return
}
defer file.Close()
initialLines := utils.ReadLastNLines(file, 50)
fs.app.Logger().Info("Streaming log file", "serverId", serverId, "initialLines", len(initialLines))
for _, line := range initialLines {
fmt.Fprintf(w, "data: %s\n\n", line)
}
flusher.Flush()
offset, err := file.Seek(0, io.SeekEnd)
if err != nil {
return
}
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
fi, err := os.Stat(logPath)
if err != nil {
continue
}
if fi.Size() < offset {
file.Close()
file, err = os.Open(logPath)
if err != nil {
continue
}
offset = 0
}
file.Seek(offset, io.SeekStart)
scanner := bufio.NewScanner(file)
hasData := false
for scanner.Scan() {
line := scanner.Text()
if line != "" {
fmt.Fprintf(w, "data: %s\n\n", line)
hasData = true
}
}
newOffset, _ := file.Seek(0, io.SeekCurrent)
offset = newOffset
if hasData {
flusher.Flush()
}
}
}
}
func (fs *Service) ReloadFrpc(serverId *string) error {
fs.app.Logger().Info("Reload frpc", "id", *serverId)
proxyCfgs, err := fs.genProxyCfgs(serverId)
proxyCfgs, err := p.genProxyCfgs(id)
if err != nil {
return err
}
proxyCfgsBytes, _ := json.Marshal(proxyCfgs)
safeProxies := sensitiveRegex.ReplaceAll(proxyCfgsBytes, []byte(`"${1}":"***"`))
fs.app.Logger().Info("FRP Reload Configurations", "proxies", string(safeProxies))
p.app.Logger().Info("FRP Reload Configurations", "proxies", string(safeProxies))
fs.mu.RLock()
svr := fs.processes[*serverId]
fs.mu.RUnlock()
p.mu.RLock()
svr := p.processes[id]
p.mu.RUnlock()
// TODO 2026-02-08 reload visitorCfgs
svr.UpdateAllConfigurer(proxyCfgs, nil)
return nil
}
// IsServerRunning checks if a server is currently running.
func (fs *Service) IsServerRunning(serverId string) bool {
fs.mu.RLock()
_, exists := fs.processes[serverId]
fs.mu.RUnlock()
// IsRunning reports whether the frp client for the given server is active. Implements tunnel.Provider.
func (p *Provider) IsRunning(id string) bool {
p.mu.RLock()
_, exists := p.processes[id]
p.mu.RUnlock()
return exists
}
// AutoStartServers automatically starts all servers with autoConnection=true.
func (fs *Service) AutoStartServers() {
fs.app.Logger().Info("Auto-starting servers with autoConnection enabled")
fs.app.Logger().Info("Waiting for 10 seconds before auto-starting servers")
// AutoStart starts all servers configured with autoConnection=true. Implements tunnel.Provider.
func (p *Provider) AutoStart() {
p.app.Logger().Info("Auto-starting servers with autoConnection enabled")
p.app.Logger().Info("Waiting for 10 seconds before auto-starting servers")
time.Sleep(10 * time.Second)
records, err := fs.serverRepo.FindAllWithAutoConnect()
records, err := p.serverRepo.FindAllWithAutoConnect()
if err != nil {
fs.app.Logger().Error("Failed to find auto-connection servers", "error", err)
p.app.Logger().Error("Failed to find auto-connection servers", "error", err)
return
}
@@ -534,22 +440,37 @@ func (fs *Service) AutoStartServers() {
serverId := record.ID
serverName := record.ServerName
fs.app.Logger().Info("Auto-starting server", "id", serverId, "name", serverName)
p.app.Logger().Info("Auto-starting server", "id", serverId, "name", serverName)
go func(id string) {
time.Sleep(time.Duration(count) * 500 * time.Millisecond)
if err := fs.LaunchFrpc(&id); err != nil {
fs.app.Logger().Error("Failed to auto-start server", "id", id, "error", err)
go func(id string, delay int) {
time.Sleep(time.Duration(delay) * 500 * time.Millisecond)
if err := p.Launch(id); err != nil {
p.app.Logger().Error("Failed to auto-start server", "id", id, "error", err)
} else {
fs.app.Logger().Info("Successfully auto-started server", "id", id)
p.app.Logger().Info("Successfully auto-started server", "id", id)
}
}(serverId)
}(serverId, count)
count++
fs.app.Logger().Info("Waiting for 1s before auto-starting next server")
p.app.Logger().Info("Waiting for 1s before auto-starting next server")
time.Sleep(1 * time.Second)
}
fs.app.Logger().Info("Auto-start initiated for servers", "count", count)
p.app.Logger().Info("Auto-start initiated for servers", "count", count)
}
// StreamLog streams the frpc log file via SSE. Implements tunnel.Provider.
func (p *Provider) StreamLog(id string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher) {
if !validServerID.MatchString(id) {
fmt.Fprintf(w, "data: [invalid server id]\n\n")
flusher.Flush()
return
}
logPath := filepath.Join(p.mainPath(id), "logs", "frpc.log")
tunnel.StreamLogFile(ctx, w, flusher, logPath, 50)
}
func (p *Provider) mainPath(id string) string {
return filepath.Join("pb_data", "frpc", id)
}
+26
View File
@@ -0,0 +1,26 @@
// Package tunnel defines the common Provider interface implemented by all
// tunnel backends (frpc, cloudflare).
package tunnel
import (
"context"
"net/http"
)
// Provider defines the lifecycle interface for a tunnel backend.
// Each implementation manages a set of running tunnel processes,
// keyed by an entity ID (serverId for frpc, integrationId for cloudflare).
type Provider interface {
// Launch starts the tunnel for the given entity ID.
Launch(id string) error
// Terminate stops the tunnel for the given entity ID.
Terminate(id string) error
// Reload reloads the proxy configuration without a full restart.
Reload(id string) error
// IsRunning reports whether the tunnel for the given entity is active.
IsRunning(id string) bool
// AutoStart starts all tunnels configured for automatic connection.
AutoStart()
// StreamLog tails the tunnel log via Server-Sent Events.
StreamLog(id string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher)
}
+78
View File
@@ -0,0 +1,78 @@
package tunnel
import (
"bufio"
"context"
"fmt"
"io"
"net/http"
"os"
"time"
"podux/pkg/utils"
)
// WriteSSEHeaders sets the standard response headers for a Server-Sent Events stream.
func WriteSSEHeaders(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
}
// StreamLogFile tails logPath via SSE. It first sends up to initialLines of
// recent history, then polls for new content every 500 ms until ctx is done.
func StreamLogFile(ctx context.Context, w http.ResponseWriter, flusher http.Flusher, logPath string, initialLines int) {
file, err := os.Open(logPath)
if err != nil {
fmt.Fprintf(w, "data: [No log file found]\n\n")
flusher.Flush()
return
}
defer file.Close()
for _, line := range utils.ReadLastNLines(file, initialLines) {
fmt.Fprintf(w, "data: %s\n\n", line)
}
flusher.Flush()
offset, err := file.Seek(0, io.SeekEnd)
if err != nil {
return
}
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
fi, err := os.Stat(logPath)
if err != nil {
continue
}
if fi.Size() < offset {
file.Close()
file, err = os.Open(logPath)
if err != nil {
continue
}
offset = 0
}
file.Seek(offset, io.SeekStart)
scanner := bufio.NewScanner(file)
hasData := false
for scanner.Scan() {
if line := scanner.Text(); line != "" {
fmt.Fprintf(w, "data: %s\n\n", line)
hasData = true
}
}
offset, _ = file.Seek(0, io.SeekCurrent)
if hasData {
flusher.Flush()
}
}
}
}
+2 -1
View File
@@ -2,9 +2,10 @@ package proxy
import "podux/pkg/types"
// Proxy represents a frpc proxy configuration record.
// Proxy represents a proxy configuration record.
type Proxy struct {
Id string `db:"id" json:"id"`
// Deprecated: Use TunnelId instead. Resolve the server via fh_proxies.tunnelId → th_tunnels.serverId.
ServerId string `db:"serverId" json:"serverId"`
ProxyType string `db:"proxyType" json:"proxyType"`
Name string `db:"name" json:"name"`
+1
View File
@@ -7,6 +7,7 @@ type Repository interface {
CountByType() (map[string]int64, error)
UpdateBootStatus(id string, status ProxyBootStatus) error
UpdateBootStatusByServerID(serverID string, status ProxyBootStatus) error
UpdateBootStatusByIntegrationID(integrationID string, status ProxyBootStatus) error
ResetAllBootStatus() error
FindByServerID(serverID string) ([]Proxy, error)
FindEnabledByServerID(serverID string) ([]Proxy, error)
-7
View File
@@ -1,12 +1,5 @@
package server
type ServerStatus string
const (
ServerStatusRunning ServerStatus = "running"
ServerStatusStopped ServerStatus = "stopped"
)
// ServerRecord is a lightweight struct for DB scanning operations.
type ServerRecord struct {
ID string `db:"id"`
-3
View File
@@ -2,9 +2,6 @@ package server
// Repository defines persistence operations for the server domain.
type Repository interface {
CountByBootStatus(status ServerStatus) (int64, error)
UpdateBootStatus(id string, status ServerStatus) error
ResetAllBootStatus() error
GetMaxLatency() (int64, error)
FindAllWithAutoConnect() ([]ServerRecord, error)
}
+9
View File
@@ -0,0 +1,9 @@
package tunnel
type TunnelStatus string
const (
TunnelStatusActive TunnelStatus = "active"
TunnelStatusInactive TunnelStatus = "inactive"
TunnelStatusError TunnelStatus = "error"
)
+8
View File
@@ -0,0 +1,8 @@
package tunnel
type Repository interface {
UpdateStatusByServerID(serverID string, status TunnelStatus) error
UpdateStatusByIntegrationID(integrationID string, status TunnelStatus) error
ResetAllStatus() error
CountByStatus(status TunnelStatus) (int64, error)
}
+14
View File
@@ -0,0 +1,14 @@
package hooks
import (
"podux/internal/application/integration"
"podux/internal/application/tunnel"
"github.com/pocketbase/pocketbase/core"
)
// Register wires all PocketBase record hooks for the application.
func Register(app core.App, cloudflareService *integration.CloudflareService, frpcProvider tunnel.Provider) {
registerIntegrationHooks(app)
registerProxyHooks(app, cloudflareService, frpcProvider)
}
+60
View File
@@ -0,0 +1,60 @@
package hooks
import (
"context"
"time"
"podux/internal/application/integration"
"github.com/pocketbase/pocketbase/core"
)
// registerIntegrationHooks handles fh_integrations events.
func registerIntegrationHooks(app core.App) {
// Auto-validate integration credentials after creation.
// Runs in a goroutine so the create response is not blocked.
app.OnRecordAfterCreateSuccess("fh_integrations").BindFunc(func(e *core.RecordEvent) error {
id := e.Record.Id
intType := e.Record.GetString("integrationsType")
credentials := e.Record.GetString("credentials")
go func(id, intType, credentials string) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
logger := app.Logger().With(
"integrationId", id,
"integrationType", intType,
"source", "auto-validate",
)
record, err := app.FindRecordById("fh_integrations", id)
if err != nil {
logger.Error("auto-validate: record not found", "error", err)
return
}
switch intType {
case "cloudflare":
accounts, validateErr := integration.ValidateCloudflare(ctx, credentials, logger)
if validateErr != nil {
record.Set("status", "invalid")
logger.Warn("auto-validate: cloudflare validation failed", "error", validateErr)
} else {
record.Set("status", "active")
record.Set("metadata", map[string]any{"accounts": accounts})
logger.Info("auto-validate: cloudflare validation passed", "accountCount", len(accounts))
}
default:
logger.Debug("auto-validate: skipping unsupported type", "type", intType)
return
}
if saveErr := app.Save(record); saveErr != nil {
logger.Error("auto-validate: failed to save record", "error", saveErr)
}
}(id, intType, credentials)
return e.Next()
})
}
+159
View File
@@ -0,0 +1,159 @@
package hooks
import (
"context"
"fmt"
"time"
"podux/internal/application/integration"
"podux/internal/application/tunnel"
"github.com/pocketbase/pocketbase/core"
)
// registerProxyHooks handles fh_proxies events.
func registerProxyHooks(app core.App, cloudflareService *integration.CloudflareService, frpcProvider tunnel.Provider) {
// ensureFrpTunnel finds or creates the th_tunnels record (type=frp) for the
// given serverId. One server maps to exactly one FRP tunnel.
ensureFrpTunnel := func(serverId string) (string, error) {
existing, err := app.FindFirstRecordByFilter(
"th_tunnels",
fmt.Sprintf(`serverId = "%s" && type = "frp"`, serverId),
)
if err == nil {
return existing.Id, nil
}
collection, err := app.FindCollectionByNameOrId("th_tunnels")
if err != nil {
return "", fmt.Errorf("th_tunnels collection not found: %w", err)
}
record := core.NewRecord(collection)
record.Set("serverId", serverId)
record.Set("type", "frp")
if err := app.Save(record); err != nil {
return "", fmt.Errorf("save frp tunnel: %w", err)
}
app.Logger().Info("Auto-created FRP tunnel", "tunnelId", record.Id, "serverId", serverId)
return record.Id, nil
}
// Ensure FRP tunnel exists (and set tunnelId) on proxy create/update.
// Primary path: tunnelId is set directly by the caller.
// Fallback path: derive tunnel from the deprecated serverId field for backwards compat.
// Note: proxyType is always a protocol (tcp/udp/http/https); tunnel type is in th_tunnels.type.
bindFrpTunnel := func(e *core.RecordEvent) error {
if e.Record.GetString("tunnelId") != "" {
return e.Next()
}
// tunnelId not set — fall back to serverId (deprecated).
serverId := e.Record.GetString("serverId")
if serverId == "" {
return e.Next()
}
tunnelId, err := ensureFrpTunnel(serverId)
if err != nil {
app.Logger().Error("ensure FRP tunnel failed", "error", err, "serverId", serverId)
return e.Next()
}
e.Record.Set("tunnelId", tunnelId)
return e.Next()
}
app.OnRecordCreate("fh_proxies").BindFunc(bindFrpTunnel)
app.OnRecordUpdate("fh_proxies").BindFunc(bindFrpTunnel)
// Sync Cloudflare tunnel ingress on proxy create/update/delete.
// Tunnel type is resolved via tunnelId → th_tunnels.type; integrationId lives on th_tunnels.
syncCloudflare := func(e *core.RecordEvent) error {
tunnelId := e.Record.GetString("tunnelId")
if tunnelId == "" {
return e.Next()
}
tunnelRecord, err := app.FindRecordById("th_tunnels", tunnelId)
if err != nil || tunnelRecord.GetString("type") != "cloudflare" {
return e.Next()
}
integrationID := tunnelRecord.GetString("integrationId")
if integrationID == "" {
return e.Next()
}
go func(id string) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := cloudflareService.SyncTunnelForProxy(ctx, id); err != nil {
app.Logger().Error("cloudflare tunnel sync failed", "error", err, "integrationId", id)
}
}(integrationID)
return e.Next()
}
app.OnRecordAfterCreateSuccess("fh_proxies").BindFunc(syncCloudflare)
app.OnRecordAfterUpdateSuccess("fh_proxies").BindFunc(syncCloudflare)
app.OnRecordAfterDeleteSuccess("fh_proxies").BindFunc(syncCloudflare)
// Reload frpc when an FRP proxy is updated: resolve server via tunnelId → th_tunnels.serverId.
app.OnRecordAfterUpdateSuccess("fh_proxies").BindFunc(func(e *core.RecordEvent) error {
tunnelId := e.Record.GetString("tunnelId")
if tunnelId == "" {
return e.Next()
}
tunnelRecord, err := app.FindRecordById("th_tunnels", tunnelId)
if err != nil {
return e.Next()
}
serverId := tunnelRecord.GetString("serverId")
if serverId != "" && frpcProvider.IsRunning(serverId) {
app.Logger().Info("Proxy updated, reloading frpc configuration", "proxyId", e.Record.Id, "serverId", serverId)
if err := frpcProvider.Reload(serverId); err != nil {
app.Logger().Error("Failed to reload frpc after proxy update", "error", err, "serverId", serverId)
}
}
return e.Next()
})
// EnsureServerTunnels runs at startup:
// 1. Scans all fh_servers and ensures each has a th_tunnels record (type=frp).
// 2. Links any proxies still using the deprecated serverId field to their server's tunnel.
app.OnServe().BindFunc(func(e *core.ServeEvent) error {
go func() {
servers, err := app.FindAllRecords("fh_servers")
if err != nil {
app.Logger().Error("ensureServerTunnels: failed to list servers", "error", err)
return
}
for _, server := range servers {
serverId := server.Id
tunnelId, err := ensureFrpTunnel(serverId)
if err != nil {
app.Logger().Error("ensureServerTunnels: ensure tunnel failed", "error", err, "serverId", serverId)
continue
}
// Link proxies that still reference this server via the deprecated serverId field.
proxies, err := app.FindRecordsByFilter(
"fh_proxies",
fmt.Sprintf(`serverId = "%s" && tunnelId = ""`, serverId),
"", 0, 0, nil,
)
if err != nil {
app.Logger().Error("ensureServerTunnels: query proxies failed", "error", err, "serverId", serverId)
continue
}
for _, proxy := range proxies {
proxy.Set("tunnelId", tunnelId)
if err := app.Save(proxy); err != nil {
app.Logger().Error("ensureServerTunnels: save proxy failed", "error", err, "proxyId", proxy.Id)
}
}
if len(proxies) > 0 {
app.Logger().Info("ensureServerTunnels: linked proxies to tunnel",
"serverId", serverId, "tunnelId", tunnelId, "count", len(proxies))
}
}
app.Logger().Info("ensureServerTunnels: done", "serverCount", len(servers))
}()
return e.Next()
})
}
@@ -27,7 +27,6 @@ func (r *ProxyRepository) CountByStatus(status proxy.ProxyStatus) (int64, error)
r.app.Logger().Error("Failed to get proxy count by status", "error", err)
return 0, err
}
return count, nil
}
@@ -43,7 +42,6 @@ func (r *ProxyRepository) CountByBootStatus(status proxy.ProxyBootStatus) (int64
r.app.Logger().Error("Failed to get proxy count by bootStatus", "error", err)
return 0, err
}
return count, nil
}
@@ -69,7 +67,6 @@ func (r *ProxyRepository) CountByType() (map[string]int64, error) {
for _, result := range results {
counts[result.ProxyType] = result.Count
}
return counts, nil
}
@@ -79,9 +76,7 @@ func (r *ProxyRepository) UpdateBootStatus(id string, status proxy.ProxyBootStat
result, err := r.app.DB().
Update("fh_proxies", dbx.Params{
"bootStatus": string(status),
}, dbx.HashExp{
"id": id,
}).
}, dbx.HashExp{"id": id}).
Execute()
if err != nil {
@@ -97,12 +92,32 @@ func (r *ProxyRepository) UpdateBootStatus(id string, status proxy.ProxyBootStat
func (r *ProxyRepository) UpdateBootStatusByServerID(serverID string, status proxy.ProxyBootStatus) error {
r.app.Logger().Info("Update proxy boot status by server id", "id", serverID, "status", status)
// Route through th_tunnels: fh_proxies.tunnelId → th_tunnels.serverId
type tunnelRow struct {
ID string `db:"id"`
}
var tunnels []tunnelRow
if err := r.app.DB().
Select("id").
From("th_tunnels").
Where(dbx.HashExp{"serverId": serverID}).
All(&tunnels); err != nil {
r.app.Logger().Error("Failed to find tunnels for server", "serverID", serverID, "error", err)
return err
}
if len(tunnels) == 0 {
return nil
}
tunnelIDs := make([]any, len(tunnels))
for i, t := range tunnels {
tunnelIDs[i] = t.ID
}
result, err := r.app.DB().
Update("fh_proxies", dbx.Params{
"bootStatus": string(status),
}, dbx.HashExp{
"serverId": serverID,
}).
}, dbx.In("tunnelId", tunnelIDs...)).
Execute()
if err != nil {
@@ -115,6 +130,48 @@ func (r *ProxyRepository) UpdateBootStatusByServerID(serverID string, status pro
return nil
}
func (r *ProxyRepository) UpdateBootStatusByIntegrationID(integrationID string, status proxy.ProxyBootStatus) error {
r.app.Logger().Info("Update proxy boot status by integration id", "id", integrationID, "status", status)
// fh_proxies.integrationId has been replaced by tunnelId (→ th_tunnels).
// Find tunnel IDs for this integration, then batch-update proxies.
type tunnelRow struct {
ID string `db:"id"`
}
var tunnels []tunnelRow
if err := r.app.DB().
Select("id").
From("th_tunnels").
Where(dbx.HashExp{"integrationId": integrationID}).
All(&tunnels); err != nil {
r.app.Logger().Error("Failed to find tunnels for integration", "integrationID", integrationID, "error", err)
return err
}
if len(tunnels) == 0 {
return nil
}
tunnelIDs := make([]any, len(tunnels))
for i, t := range tunnels {
tunnelIDs[i] = t.ID
}
result, err := r.app.DB().
Update("fh_proxies", dbx.Params{
"bootStatus": string(status),
}, dbx.In("tunnelId", tunnelIDs...)).
Execute()
if err != nil {
r.app.Logger().Error("Failed to update proxy boot status by integration id", "integrationID", integrationID, "error", err)
return err
}
rowsAffected, _ := result.RowsAffected()
r.app.Logger().Info("Proxy boot status updated successfully", "integrationID", integrationID, "status", status, "count", rowsAffected)
return nil
}
func (r *ProxyRepository) ResetAllBootStatus() error {
r.app.Logger().Info("Resetting all proxy boot status to offline")
@@ -139,27 +196,28 @@ func (r *ProxyRepository) ResetAllBootStatus() error {
func (r *ProxyRepository) FindByServerID(serverID string) ([]proxy.Proxy, error) {
var proxies []proxy.Proxy
err := r.app.DB().
Select("fh_proxies.*").
From("fh_proxies").
Where(dbx.HashExp{"serverId": serverID}).
Select("fp.*").
From("fh_proxies fp").
InnerJoin("th_tunnels tt", dbx.NewExp("tt.id = fp.tunnelId")).
Where(dbx.HashExp{"tt.serverId": serverID}).
All(&proxies)
if err != nil {
r.app.Logger().Error("Failed to find proxies by server id", "serverID", serverID, "error", err)
return nil, err
}
return proxies, nil
}
func (r *ProxyRepository) FindEnabledByServerID(serverID string) ([]proxy.Proxy, error) {
var proxies []proxy.Proxy
err := r.app.DB().
Select("fh_proxies.*").
From("fh_proxies").
Select("fp.*").
From("fh_proxies fp").
InnerJoin("th_tunnels tt", dbx.NewExp("tt.id = fp.tunnelId")).
Where(dbx.And(
dbx.HashExp{"serverId": serverID},
dbx.HashExp{"status": string(proxy.ProxyStatusEnabled)},
dbx.HashExp{"tt.serverId": serverID},
dbx.HashExp{"fp.status": string(proxy.ProxyStatusEnabled)},
)).
All(&proxies)
@@ -167,7 +225,5 @@ func (r *ProxyRepository) FindEnabledByServerID(serverID string) ([]proxy.Proxy,
r.app.Logger().Error("Failed to find enabled proxies by server id", "serverID", serverID, "error", err)
return nil, err
}
return proxies, nil
}
@@ -15,71 +15,8 @@ func NewServerRepository(app core.App) *ServerRepository {
return &ServerRepository{app: app}
}
func (r *ServerRepository) CountByBootStatus(status server.ServerStatus) (int64, error) {
var count int64
err := r.app.DB().
Select("COUNT(*)").
From("fh_servers").
Where(dbx.HashExp{"bootStatus": string(status)}).
Row(&count)
if err != nil {
r.app.Logger().Error("Failed to get server count by status", "error", err)
return 0, err
}
return count, nil
}
func (r *ServerRepository) UpdateBootStatus(id string, status server.ServerStatus) error {
r.app.Logger().Info("Update server boot status", "id", id, "status", status)
result, err := r.app.DB().
Update("fh_servers",
dbx.Params{"bootStatus": string(status)},
dbx.NewExp("id = {:id} AND bootStatus != {:status}", dbx.Params{
"id": id,
"status": string(status),
}),
).Execute()
if err != nil {
r.app.Logger().Error("Failed to update server boot status", "id", id, "error", err)
return err
}
rowsAffected, _ := result.RowsAffected()
if rowsAffected > 0 {
r.app.Logger().Info("Server boot status updated successfully", "id", id, "status", status)
} else {
r.app.Logger().Debug("Server boot status unchanged", "id", id, "status", status)
}
return nil
}
func (r *ServerRepository) ResetAllBootStatus() error {
r.app.Logger().Info("Resetting all server status to stopped")
result, err := r.app.DB().
Update("fh_servers",
dbx.Params{"bootStatus": string(server.ServerStatusStopped)},
dbx.NewExp("bootStatus != {:status} AND bootStatus != ''", dbx.Params{"status": string(server.ServerStatusStopped)}),
).Execute()
if err != nil {
r.app.Logger().Error("Failed to reset server status", "error", err)
return err
}
rowsAffected, _ := result.RowsAffected()
r.app.Logger().Info("Server status reset completed", "count", rowsAffected)
return nil
}
func (r *ServerRepository) GetMaxLatency() (int64, error) {
var maxLatency int64
// Get the max latency among each target's most recent measurement.
err := r.app.DB().
Select("MAX(val)").
From("fh_metrics_raw").
@@ -90,7 +27,6 @@ func (r *ServerRepository) GetMaxLatency() (int64, error) {
r.app.Logger().Error("Failed to get max latency", "error", err)
return 0, err
}
return maxLatency, nil
}
@@ -0,0 +1,60 @@
package persistence
import (
tunneldomain "podux/internal/domain/tunnel"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/core"
)
type TunnelRepository struct {
app core.App
}
func NewTunnelRepository(app core.App) *TunnelRepository {
return &TunnelRepository{app: app}
}
func (r *TunnelRepository) UpdateStatusByServerID(serverID string, status tunneldomain.TunnelStatus) error {
_, err := r.app.DB().
Update("th_tunnels", dbx.Params{"status": string(status)}, dbx.HashExp{"serverId": serverID}).
Execute()
if err != nil {
r.app.Logger().Error("Failed to update tunnel status by server id", "serverID", serverID, "error", err)
}
return err
}
func (r *TunnelRepository) UpdateStatusByIntegrationID(integrationID string, status tunneldomain.TunnelStatus) error {
_, err := r.app.DB().
Update("th_tunnels", dbx.Params{"status": string(status)}, dbx.HashExp{"integrationId": integrationID}).
Execute()
if err != nil {
r.app.Logger().Error("Failed to update tunnel status by integration id", "integrationID", integrationID, "error", err)
}
return err
}
func (r *TunnelRepository) ResetAllStatus() error {
_, err := r.app.DB().
Update("th_tunnels", dbx.Params{"status": string(tunneldomain.TunnelStatusInactive)},
dbx.Not(dbx.HashExp{"status": string(tunneldomain.TunnelStatusInactive)})).
Execute()
if err != nil {
r.app.Logger().Error("Failed to reset all tunnel status", "error", err)
}
return err
}
func (r *TunnelRepository) CountByStatus(status tunneldomain.TunnelStatus) (int64, error) {
var count int64
err := r.app.DB().
Select("COUNT(*)").
From("th_tunnels").
Where(dbx.HashExp{"status": string(status)}).
Row(&count)
if err != nil {
r.app.Logger().Error("Failed to count tunnels by status", "status", status, "error", err)
}
return count, err
}
-112
View File
@@ -1,112 +0,0 @@
package httphandler
import (
"podux/internal/application/frpc"
"net/http"
"github.com/pocketbase/pocketbase/core"
)
type FrpcHandler struct {
app core.App
service *frpc.Service
}
func NewFrpcHandler(app core.App, service *frpc.Service) *FrpcHandler {
return &FrpcHandler{
app: app,
service: service,
}
}
func (h *FrpcHandler) RegisterHandlers(e *core.ServeEvent) {
e.Router.POST("/api/frpc/launch", requireAuth(func(e *core.RequestEvent) error {
data := struct {
ID string `json:"id"`
}{}
if err := e.BindBody(&data); err != nil {
return e.JSON(400, map[string]string{"error": "invalid request body"})
}
id := data.ID
if id == "" {
return e.JSON(400, map[string]string{"error": "id is required"})
}
if !validID.MatchString(id) {
return e.JSON(400, map[string]string{"error": "invalid id format"})
}
err := h.service.LaunchFrpc(&id)
if err != nil {
return e.JSON(500, map[string]string{"error": err.Error()})
}
return e.JSON(200, map[string]string{"message": "frpc started"})
}))
e.Router.GET("/api/frpc/logs/stream", requireAuth(func(e *core.RequestEvent) error {
id := e.Request.URL.Query().Get("id")
if id == "" {
return e.JSON(400, map[string]string{"error": "id is required"})
}
if !validID.MatchString(id) {
return e.JSON(400, map[string]string{"error": "invalid id format"})
}
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, map[string]string{"error": "streaming not supported"})
}
h.service.StreamLog(id, e.Request.Context(), w, flusher)
return nil
}, h.app))
e.Router.POST("/api/frpc/terminate", requireAuth(func(e *core.RequestEvent) error {
data := struct {
ID string `json:"id"`
}{}
if err := e.BindBody(&data); err != nil {
return e.JSON(400, map[string]string{"error": "invalid request body"})
}
id := data.ID
if id == "" {
return e.JSON(400, map[string]string{"error": "id is required"})
}
if !validID.MatchString(id) {
return e.JSON(400, map[string]string{"error": "invalid id format"})
}
err := h.service.TerminateFrpc(&id)
if err != nil {
return e.JSON(500, map[string]string{"error": err.Error()})
}
return e.JSON(200, map[string]string{"message": "frpc terminated"})
}))
e.Router.POST("/api/frpc/reload", requireAuth(func(e *core.RequestEvent) error {
data := struct {
ID string `json:"id"`
}{}
if err := e.BindBody(&data); err != nil {
return e.JSON(400, map[string]string{"error": "invalid request body"})
}
id := data.ID
if id == "" {
return e.JSON(400, map[string]string{"error": "id is required"})
}
if !validID.MatchString(id) {
return e.JSON(400, map[string]string{"error": "invalid id format"})
}
// Only reload if the server is currently running
if !h.service.IsServerRunning(id) {
return e.JSON(200, map[string]string{"message": "server not running, skipped"})
}
err := h.service.ReloadFrpc(&id)
if err != nil {
return e.JSON(500, map[string]string{"error": err.Error()})
}
return e.JSON(200, map[string]string{"message": "frpc reloaded"})
}))
}
@@ -0,0 +1,120 @@
package httphandler
import (
"fmt"
"podux/internal/application/integration"
"github.com/pocketbase/pocketbase/core"
)
// IntegrationHandler exposes integration-related API routes.
type IntegrationHandler struct {
app core.App
}
func NewIntegrationHandler(app core.App) *IntegrationHandler {
return &IntegrationHandler{app: app}
}
func (h *IntegrationHandler) RegisterHandlers(e *core.ServeEvent) {
// POST /api/integrations/validate
// Body: { "id": "<record id>" }
// Validates the credentials of the given integration, updates its status,
// and writes discovered account info into metadata.
e.Router.POST("/api/integrations/validate", requireAuth(func(e *core.RequestEvent) error {
var body struct {
ID string `json:"id"`
}
if err := e.BindBody(&body); err != nil {
return e.JSON(400, map[string]string{"error": "invalid request body"})
}
if !validID.MatchString(body.ID) {
return e.JSON(400, map[string]string{"error": "invalid id format"})
}
record, err := h.app.FindRecordById("fh_integrations", body.ID)
if err != nil {
return e.JSON(404, map[string]string{"error": "integration not found"})
}
intType := record.GetString("integrationsType")
name := record.GetString("name")
credentials := record.GetString("credentials")
logger := h.app.Logger().With(
"integrationId", body.ID,
"integrationName", name,
"integrationType", intType,
)
logger.Info("integration validation requested")
switch intType {
case "cloudflare":
accounts, validateErr := integration.ValidateCloudflare(e.Request.Context(), credentials, logger)
if validateErr != nil {
record.Set("status", "invalid")
if saveErr := h.app.Save(record); saveErr != nil {
logger.Error("failed to update status to invalid", "error", saveErr)
} else {
logger.Info("integration status set to invalid")
}
return e.JSON(422, map[string]string{"error": validateErr.Error()})
}
record.Set("status", "active")
record.Set("metadata", map[string]any{"accounts": accounts})
if saveErr := h.app.Save(record); saveErr != nil {
logger.Error("failed to update status to active", "error", saveErr)
return e.JSON(500, map[string]string{"error": "failed to update status"})
}
logger.Info("integration validation succeeded, metadata updated", "accountCount", len(accounts))
return e.JSON(200, map[string]any{
"message": "validation successful",
"status": "active",
"accounts": accounts,
})
default:
logger.Warn("unsupported integration type for validation", "type", intType)
return e.JSON(400, map[string]string{"error": "unsupported integration type: " + intType})
}
}))
// POST /api/integrations/ensure-tunnel
// Body: { "integrationId": "<id>" }
// Finds or creates a th_tunnels record (type=cloudflare) for the given integration.
// Returns { "tunnelId": "<id>" } for the caller to set on fh_proxies.
e.Router.POST("/api/integrations/ensure-tunnel", requireAuth(func(e *core.RequestEvent) error {
var body struct {
IntegrationID string `json:"integrationId"`
}
if err := e.BindBody(&body); err != nil {
return e.JSON(400, map[string]string{"error": "invalid request body"})
}
if !validID.MatchString(body.IntegrationID) {
return e.JSON(400, map[string]string{"error": "invalid integrationId"})
}
existing, err := h.app.FindFirstRecordByFilter(
"th_tunnels",
fmt.Sprintf(`integrationId = "%s" && type = "cloudflare"`, body.IntegrationID),
)
if err == nil {
return e.JSON(200, map[string]string{"tunnelId": existing.Id})
}
collection, err := h.app.FindCollectionByNameOrId("th_tunnels")
if err != nil {
return e.JSON(500, map[string]string{"error": "th_tunnels collection not found"})
}
record := core.NewRecord(collection)
record.Set("integrationId", body.IntegrationID)
record.Set("type", "cloudflare")
if err := h.app.Save(record); err != nil {
return e.JSON(500, map[string]string{"error": "failed to create tunnel: " + err.Error()})
}
h.app.Logger().Info("Auto-created Cloudflare tunnel", "tunnelId", record.Id, "integrationId", body.IntegrationID)
return e.JSON(200, map[string]string{"tunnelId": record.Id})
}))
}
+63 -2
View File
@@ -63,6 +63,27 @@ type probePoint struct {
Val float64 `json:"val"`
}
// fetchFRPTunnelStatusMap returns a map of serverId → tunnel status (active/inactive/error/...).
// Filters by non-empty serverId (FRP tunnels); defaults to "inactive" when status is NULL.
func (h *ServerHandler) fetchFRPTunnelStatusMap() map[string]string {
type row struct {
ServerID string `db:"serverId"`
Status string `db:"status"`
}
var rows []row
h.app.DB().
Select("serverId", "COALESCE(status, 'inactive') as status").
From("th_tunnels").
Where(dbx.NewExp("serverId IS NOT NULL AND serverId != ''")).
All(&rows)
m := make(map[string]string, len(rows))
for _, r := range rows {
m[r.ServerID] = r.Status
}
return m
}
func (h *ServerHandler) RegisterHandlers(e *core.ServeEvent) {
// Paginated server list with assembled latency metrics.
e.Router.GET("/api/servers", requireAuth(func(e *core.RequestEvent) error {
@@ -114,6 +135,8 @@ func (h *ServerHandler) RegisterHandlers(e *core.ServeEvent) {
latencyMap = map[string]*monitoring.NetworkStatus{}
}
tunnelStatusMap := h.fetchFRPTunnelStatusMap()
totalPages := int(math.Ceil(float64(total) / float64(perPage)))
items := make([]serverVO, 0, len(records))
for _, r := range records {
@@ -124,7 +147,7 @@ func (h *ServerHandler) RegisterHandlers(e *core.ServeEvent) {
ServerAddr: r.GetString("serverAddr"),
ServerPort: r.GetInt("serverPort"),
Description: r.GetString("description"),
BootStatus: r.GetString("bootStatus"),
BootStatus: tunnelStatusMap[r.Id],
AutoConnection: r.GetBool("autoConnection"),
SendRate: r.GetFloat("sendRate"),
RecvRate: r.GetFloat("recvRate"),
@@ -148,6 +171,42 @@ func (h *ServerHandler) RegisterHandlers(e *core.ServeEvent) {
})
}))
// Single server detail with bootStatus sourced from th_tunnels.
e.Router.GET("/api/servers/{id}", requireAuth(func(e *core.RequestEvent) error {
serverID := e.Request.PathValue("id")
r, err := h.app.FindRecordById("fh_servers", serverID)
if err != nil {
return e.JSON(404, response.Error(fmt.Errorf("server not found")))
}
tunnelStatusMap := h.fetchFRPTunnelStatusMap()
latencyMap, _ := h.metricsService.GetLatestLatencyBatch()
ns := latencyMap[serverID]
vo := serverVO{
ID: r.Id,
ServerName: r.GetString("serverName"),
User: r.GetString("user"),
ServerAddr: r.GetString("serverAddr"),
ServerPort: r.GetInt("serverPort"),
Description: r.GetString("description"),
BootStatus: tunnelStatusMap[r.Id],
AutoConnection: r.GetBool("autoConnection"),
SendRate: r.GetFloat("sendRate"),
RecvRate: r.GetFloat("recvRate"),
GeoLocation: r.Get("geoLocation"),
Log: r.Get("log"),
Auth: r.Get("auth"),
Transport: r.Get("transport"),
Metadatas: r.Get("metadatas"),
Created: r.GetString("created"),
Updated: r.GetString("updated"),
NetworkStatus: ns,
}
return e.JSON(200, vo)
}))
// Probe history for a single server — last 30 minutes of latency data.
e.Router.GET("/api/servers/probe-history", requireAuth(func(e *core.RequestEvent) error {
serverID := e.Request.URL.Query().Get("serverId")
@@ -203,12 +262,14 @@ func (h *ServerHandler) RegisterHandlers(e *core.ServeEvent) {
latencyMap = map[string]*monitoring.NetworkStatus{}
}
tunnelStatusMap := h.fetchFRPTunnelStatusMap()
items := make([]serverOptionVO, 0, len(records))
for _, r := range records {
items = append(items, serverOptionVO{
ID: r.Id,
ServerName: r.GetString("serverName"),
BootStatus: r.GetString("bootStatus"),
BootStatus: tunnelStatusMap[r.Id],
NetworkStatus: latencyMap[r.Id],
})
}
+106
View File
@@ -0,0 +1,106 @@
package httphandler
import (
"net/http"
"podux/internal/application/tunnel"
"github.com/pocketbase/pocketbase/core"
)
// TunnelHandler provides launch/terminate/reload/log-stream endpoints for any
// tunnel.Provider implementation. The URL prefix (e.g. "/api/frpc" or
// "/api/cloudflare") is supplied at construction time so that the same handler
// code serves both backends without URL collisions.
type TunnelHandler struct {
app core.App
provider tunnel.Provider
prefix string
}
func NewTunnelHandler(app core.App, provider tunnel.Provider, prefix string) *TunnelHandler {
return &TunnelHandler{app: app, provider: provider, prefix: prefix}
}
func (h *TunnelHandler) RegisterHandlers(e *core.ServeEvent) {
e.Router.POST(h.prefix+"/launch", requireAuth(func(e *core.RequestEvent) error {
var body struct {
ID string `json:"id"`
}
if err := e.BindBody(&body); err != nil {
return e.JSON(400, map[string]string{"error": "invalid request body"})
}
if body.ID == "" {
return e.JSON(400, map[string]string{"error": "id is required"})
}
if !validID.MatchString(body.ID) {
return e.JSON(400, map[string]string{"error": "invalid id format"})
}
if err := h.provider.Launch(body.ID); err != nil {
return e.JSON(500, map[string]string{"error": err.Error()})
}
return e.JSON(200, map[string]string{"message": "tunnel started"})
}))
e.Router.GET(h.prefix+"/logs/stream", requireAuth(func(e *core.RequestEvent) error {
id := e.Request.URL.Query().Get("id")
if id == "" {
return e.JSON(400, map[string]string{"error": "id is required"})
}
if !validID.MatchString(id) {
return e.JSON(400, map[string]string{"error": "invalid id format"})
}
w := e.Response
tunnel.WriteSSEHeaders(w)
flusher, ok := w.(http.Flusher)
if !ok {
return e.JSON(500, map[string]string{"error": "streaming not supported"})
}
h.provider.StreamLog(id, e.Request.Context(), w, flusher)
return nil
}, h.app))
e.Router.POST(h.prefix+"/terminate", requireAuth(func(e *core.RequestEvent) error {
var body struct {
ID string `json:"id"`
}
if err := e.BindBody(&body); err != nil {
return e.JSON(400, map[string]string{"error": "invalid request body"})
}
if body.ID == "" {
return e.JSON(400, map[string]string{"error": "id is required"})
}
if !validID.MatchString(body.ID) {
return e.JSON(400, map[string]string{"error": "invalid id format"})
}
if err := h.provider.Terminate(body.ID); err != nil {
return e.JSON(500, map[string]string{"error": err.Error()})
}
return e.JSON(200, map[string]string{"message": "tunnel terminated"})
}))
e.Router.POST(h.prefix+"/reload", requireAuth(func(e *core.RequestEvent) error {
var body struct {
ID string `json:"id"`
}
if err := e.BindBody(&body); err != nil {
return e.JSON(400, map[string]string{"error": "invalid request body"})
}
if body.ID == "" {
return e.JSON(400, map[string]string{"error": "id is required"})
}
if !validID.MatchString(body.ID) {
return e.JSON(400, map[string]string{"error": "invalid id format"})
}
if !h.provider.IsRunning(body.ID) {
return e.JSON(200, map[string]string{"message": "not running, skipped"})
}
if err := h.provider.Reload(body.ID); err != nil {
return e.JSON(500, map[string]string{"error": err.Error()})
}
return e.JSON(200, map[string]string{"message": "tunnel reloaded"})
}))
}
+24 -23
View File
@@ -2,18 +2,22 @@ package main
import (
"embed"
"github.com/spf13/cobra"
"io/fs"
"log"
"github.com/spf13/cobra"
"podux/internal/application/dashboard"
"podux/internal/application/frpc"
"podux/internal/application/importer"
"podux/internal/application/integration"
"podux/internal/application/monitoring"
"podux/internal/application/proxy"
"podux/internal/application/server"
"podux/internal/application/system"
cftunnel "podux/internal/application/tunnel/cloudflare"
frptunnel "podux/internal/application/tunnel/frp"
"podux/internal/application/version"
"podux/internal/hooks"
"podux/internal/infrastructure/persistence"
httphandler "podux/internal/interfaces/http"
_ "podux/migrations"
@@ -38,12 +42,13 @@ func main() {
// Infrastructure (Repository implementations)
serverRepo := persistence.NewServerRepository(app)
proxyRepo := persistence.NewProxyRepository(app)
tunnelRepo := persistence.NewTunnelRepository(app)
// Application Services
serverService := server.NewService(app, serverRepo)
proxyService := proxy.NewService(app, proxyRepo)
frpcService := frpc.NewService(app, serverRepo, proxyRepo)
dashboardService := dashboard.NewService(app, serverService, proxyService)
frpcService := frptunnel.NewProvider(app, serverRepo, proxyRepo, tunnelRepo)
dashboardService := dashboard.NewService(app, serverService, proxyService, tunnelRepo)
settingsService := system.NewService(app)
geoService := monitoring.NewGeoService(app)
metricsService := monitoring.NewMetricsService(app)
@@ -53,39 +58,33 @@ func main() {
versionService := version.NewService(app)
//githubService := github.NewService(app)
cloudflareService := integration.NewCloudflareService(app)
cloudflareProvider := cftunnel.NewProvider(app, proxyRepo, tunnelRepo)
// HTTP Handlers
//githubHandler := httphandler.NewGithubHandler(app, githubService)
frpcHandler := httphandler.NewFrpcHandler(app, frpcService)
integrationHandler := httphandler.NewIntegrationHandler(app)
frpcHandler := httphandler.NewTunnelHandler(app, frpcService, "/api/frpc")
cloudflareHandler := httphandler.NewTunnelHandler(app, cloudflareProvider, "/api/cloudflare")
versionHandler := httphandler.NewVersionHandler(app, versionService)
dashboardHandler := httphandler.NewDashboardHandler(dashboardService)
systemHandler := httphandler.NewSystemHandler(app, settingsService)
importHandler := httphandler.NewImportHandler(app, importService)
serverHandler := httphandler.NewServerHandler(app, metricsService)
// Hook: Reload frpc when proxy is updated
app.OnRecordAfterUpdateSuccess("fh_proxies").BindFunc(func(e *core.RecordEvent) error {
serverId := e.Record.GetString("serverId")
if serverId != "" {
// Check if the server is currently running
if frpcService.IsServerRunning(serverId) {
app.Logger().Info("Proxy updated, reloading frpc configuration", "proxyId", e.Record.Id, "serverId", serverId)
if err := frpcService.ReloadFrpc(&serverId); err != nil {
app.Logger().Error("Failed to reload frpc after proxy update", "error", err, "serverId", serverId)
}
}
}
return e.Next()
})
// Register all record hooks
hooks.Register(app, cloudflareService, frpcService)
// register custom routes
app.OnServe().BindFunc(func(e *core.ServeEvent) error {
// Reset all server statuses to stopped on startup
serverService.ResetAllServerStatus()
// Reset all tunnel statuses to inactive on startup
tunnelRepo.ResetAllStatus()
// Reset all proxy statuses to offline on startup
proxyService.ResetAllProxyBootStatus()
// Auto-start servers with autoConnection enabled (non-blocking)
go frpcService.AutoStartServers()
// Auto-start tunnels (non-blocking)
go frpcService.AutoStart()
go cloudflareProvider.AutoStart()
// Start network monitoring service using intervals from settings
latencyInterval, geoInterval := settingsService.GetMonitoringIntervals()
@@ -94,7 +93,9 @@ func main() {
// Register routes for each module
//githubHandler.RegisterHandlers(e)
integrationHandler.RegisterHandlers(e)
frpcHandler.RegisterHandlers(e)
cloudflareHandler.RegisterHandlers(e)
versionHandler.RegisterHandlers(e)
dashboardHandler.RegisterHandlers(e)
systemHandler.RegisterHandlers(e)
@@ -0,0 +1,141 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
jsonData := `{
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"hidden": false,
"id": "text3208210256",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text1579384326",
"max": 0,
"min": 0,
"name": "name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "select490931977",
"maxSelect": 1,
"name": "integrationsType",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"cloudflare"
]
},
{
"hidden": false,
"id": "json1326724116",
"maxSize": 0,
"name": "metadata",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"autogeneratePattern": "",
"hidden": false,
"id": "text4194641934",
"max": 0,
"min": 0,
"name": "credentials",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "select2063623452",
"maxSelect": 1,
"name": "status",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"active",
"invalid",
"expired"
]
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_1339991802",
"indexes": [],
"listRule": null,
"name": "fh_integrations",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
}`
collection := &core.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_1339991802")
if err != nil {
return err
}
return app.Delete(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_1442576311")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"listRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''"
}`), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_1442576311")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": null,
"deleteRule": null,
"listRule": null,
"updateRule": null,
"viewRule": null
}`), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_793044944")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"listRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''"
}`), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_793044944")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": null,
"deleteRule": null,
"listRule": null,
"updateRule": null,
"viewRule": null
}`), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_316017333")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"listRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''"
}`), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_316017333")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": null,
"deleteRule": null,
"listRule": null,
"updateRule": null,
"viewRule": null
}`), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3875966484")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"listRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''"
}`), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3875966484")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": null,
"deleteRule": null,
"listRule": null,
"updateRule": null,
"viewRule": null
}`), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_1339991802")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"listRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''"
}`), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_1339991802")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": null,
"deleteRule": null,
"listRule": null,
"updateRule": null,
"viewRule": null
}`), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -0,0 +1,45 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2245327697")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(13, []byte(`{
"hidden": false,
"id": "select2363381545",
"maxSelect": 1,
"name": "type",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"frp",
"cloudflare"
]
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2245327697")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("select2363381545")
return app.Save(collection)
})
}
@@ -0,0 +1,43 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2245327697")
if err != nil {
return err
}
// add integrationId field (relation to fh_integrations)
if err := collection.Fields.AddMarshaledJSONAt(14, []byte(`{
"cascadeDelete": false,
"collectionId": "pbc_1339991802",
"hidden": false,
"id": "relation3461722399",
"maxSelect": 1,
"minSelect": 0,
"name": "integrationId",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2245327697")
if err != nil {
return err
}
collection.Fields.RemoveById("relation3461722399")
return app.Save(collection)
})
}
@@ -0,0 +1,58 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2245327697")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(3, []byte(`{
"cascadeDelete": false,
"collectionId": "pbc_3738798621",
"hidden": false,
"id": "relation2665642495",
"maxSelect": 1,
"minSelect": 0,
"name": "serverId",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2245327697")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(3, []byte(`{
"cascadeDelete": false,
"collectionId": "pbc_3738798621",
"hidden": false,
"id": "relation2665642495",
"maxSelect": 1,
"minSelect": 0,
"name": "serverId",
"presentable": false,
"required": true,
"system": false,
"type": "relation"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
+101
View File
@@ -0,0 +1,101 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
jsonData := `{
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"hidden": false,
"id": "text3208210256",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": false,
"collectionId": "pbc_3738798621",
"hidden": false,
"id": "relation2665642495",
"maxSelect": 1,
"minSelect": 0,
"name": "serverId",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"cascadeDelete": false,
"collectionId": "pbc_1339991802",
"hidden": false,
"id": "relation2332815407",
"maxSelect": 1,
"minSelect": 0,
"name": "integrationId",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_2035192674",
"indexes": [],
"listRule": "",
"name": "th_tunnels",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
}`
collection := &core.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2035192674")
if err != nil {
return err
}
return app.Delete(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2035192674")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"listRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''"
}`), &collection); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2035192674")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"createRule": null,
"deleteRule": null,
"listRule": "",
"updateRule": null,
"viewRule": null
}`), &collection); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -0,0 +1,45 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2035192674")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(3, []byte(`{
"hidden": false,
"id": "select2363381545",
"maxSelect": 1,
"name": "type",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"frp",
"cloudflare"
]
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2035192674")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("select2363381545")
return app.Save(collection)
})
}
@@ -0,0 +1,64 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2245327697")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("relation3461722399")
// add field
if err := collection.Fields.AddMarshaledJSONAt(14, []byte(`{
"cascadeDelete": false,
"collectionId": "pbc_2035192674",
"hidden": false,
"id": "relation3250945265",
"maxSelect": 1,
"minSelect": 0,
"name": "tunnelId",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2245327697")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(14, []byte(`{
"cascadeDelete": false,
"collectionId": "pbc_1339991802",
"hidden": false,
"id": "relation3461722399",
"maxSelect": 1,
"minSelect": 0,
"name": "integrationId",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
}`)); err != nil {
return err
}
// remove field
collection.Fields.RemoveById("relation3250945265")
return app.Save(collection)
})
}
@@ -0,0 +1,63 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3738798621")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"indexes": []
}`), &collection); err != nil {
return err
}
// remove field
collection.Fields.RemoveById("text1774220776")
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3738798621")
if err != nil {
return err
}
// update collection data
if err := json.Unmarshal([]byte(`{
"indexes": [
"CREATE INDEX ` + "`" + `idx_wNtroMytle` + "`" + ` ON ` + "`" + `fh_servers` + "`" + ` (` + "`" + `bootStatus` + "`" + `)"
]
}`), &collection); err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(10, []byte(`{
"autogeneratePattern": "stopped",
"hidden": false,
"id": "text1774220776",
"max": 0,
"min": 0,
"name": "bootStatus",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"github.com/pocketbase/pocketbase/core"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2035192674")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(4, []byte(`{
"hidden": false,
"id": "select2063623452",
"maxSelect": 1,
"name": "status",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"active",
"inactive",
"error",
"pending",
"deleting"
]
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_2035192674")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("select2063623452")
return app.Save(collection)
})
}
+85
View File
@@ -0,0 +1,85 @@
package binary
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"fmt"
"io"
"os"
"strings"
)
// extractEntry pulls a single file out of an archive (.tar.gz / .tgz / .zip)
// and writes it to destPath. entryPath is the path of the target file inside
// the archive.
func extractEntry(archivePath, entryPath, destPath string) error {
lower := strings.ToLower(archivePath)
switch {
case strings.HasSuffix(lower, ".tar.gz") || strings.HasSuffix(lower, ".tgz"):
return extractTarGz(archivePath, entryPath, destPath)
case strings.HasSuffix(lower, ".zip"):
return extractZip(archivePath, entryPath, destPath)
default:
return fmt.Errorf("unsupported archive format: %s", archivePath)
}
}
func extractTarGz(archivePath, entryPath, destPath string) error {
f, err := os.Open(archivePath)
if err != nil {
return err
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return fmt.Errorf("gzip reader: %w", err)
}
defer gz.Close()
tr := tar.NewReader(gz)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("tar read: %w", err)
}
if hdr.Name == entryPath {
return writeStream(tr, destPath)
}
}
return fmt.Errorf("entry %q not found in archive", entryPath)
}
func extractZip(archivePath, entryPath, destPath string) error {
r, err := zip.OpenReader(archivePath)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
if f.Name == entryPath {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
return writeStream(rc, destPath)
}
}
return fmt.Errorf("entry %q not found in zip", entryPath)
}
func writeStream(r io.Reader, destPath string) error {
out, err := os.Create(destPath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, r)
return err
}
+170
View File
@@ -0,0 +1,170 @@
// Package binary manages the download and installation of external executables
// (cloudflared, frpc, rathole) into a local bin directory.
package binary
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
)
// BinaryManager handles downloading and installing a single external binary.
type BinaryManager struct {
Name string // "cloudflared" | "frpc" | "rathole"
Version string // "latest" or a specific tag, e.g. "v1.2.3"
BinDir string // directory where the binary will be stored
}
// New creates a BinaryManager. Use DefaultBinDir() to obtain the standard location.
func New(name, version, binDir string) *BinaryManager {
return &BinaryManager{Name: name, Version: version, BinDir: binDir}
}
// DefaultBinDir returns ~/.podux/bin, creating the directory if it does not exist.
func DefaultBinDir() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("determine home directory: %w", err)
}
dir := filepath.Join(home, ".podux", "bin")
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", fmt.Errorf("create bin dir %s: %w", dir, err)
}
return dir, nil
}
// GetPath returns the absolute path of the binary.
// On Windows the ".exe" suffix is appended automatically.
func (m *BinaryManager) GetPath() string {
name := m.Name
if runtime.GOOS == "windows" {
name += ".exe"
}
return filepath.Join(m.BinDir, name)
}
// EnsureInstalled downloads and installs the binary only when it is not already
// present. It is safe to call repeatedly; subsequent calls are no-ops.
func (m *BinaryManager) EnsureInstalled(ctx context.Context) error {
if _, err := os.Stat(m.GetPath()); err == nil {
return nil // already installed
}
return m.download(ctx)
}
// Update downloads the binary unconditionally, replacing any existing version.
func (m *BinaryManager) Update(ctx context.Context) error {
return m.download(ctx)
}
// download resolves the version, fetches the asset, extracts it if needed,
// and places the binary at GetPath() with executable permissions.
func (m *BinaryManager) download(ctx context.Context) error {
if err := os.MkdirAll(m.BinDir, 0o755); err != nil {
return fmt.Errorf("create bin dir: %w", err)
}
s, ok := specs[m.Name]
if !ok {
return fmt.Errorf("unknown binary %q (supported: cloudflared, frpc, rathole)", m.Name)
}
// Resolve "latest" to the actual tag via the GitHub API.
version := m.Version
if version == "" || version == "latest" {
var err error
version, err = githubLatestTag(ctx, s.githubOwner, s.githubRepo)
if err != nil {
return fmt.Errorf("resolve latest version for %s: %w", m.Name, err)
}
}
assetFilename, entryPath, err := s.resolveAsset(version, runtime.GOOS, runtime.GOARCH)
if err != nil {
return err
}
downloadURL := fmt.Sprintf(
"https://github.com/%s/%s/releases/download/%s/%s",
s.githubOwner, s.githubRepo, version, assetFilename,
)
// Download to a temporary file in the same directory so the final rename
// is atomic (same filesystem).
tmpFile, err := os.CreateTemp(m.BinDir, ".download-*")
if err != nil {
return fmt.Errorf("create temp file: %w", err)
}
tmpPath := tmpFile.Name()
defer func() {
tmpFile.Close()
os.Remove(tmpPath) // clean up on error; harmless if already renamed
}()
if err := fetchURL(ctx, downloadURL, tmpFile); err != nil {
return fmt.Errorf("download %s: %w", downloadURL, err)
}
tmpFile.Close()
dest := m.GetPath()
if entryPath != "" {
// Asset is an archive; extract the binary from it.
if err := extractEntry(tmpPath, entryPath, dest); err != nil {
return fmt.Errorf("extract %s from archive: %w", entryPath, err)
}
} else {
// Asset is a raw binary; rename or copy into place.
if err := os.Rename(tmpPath, dest); err != nil {
// Rename can fail across mount points; fall back to copy.
if err2 := copyFile(tmpPath, dest); err2 != nil {
return fmt.Errorf("install binary: %w", err2)
}
}
}
return os.Chmod(dest, 0o755)
}
// fetchURL downloads url into w, following redirects.
func fetchURL(ctx context.Context, url string, w io.Writer) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
req.Header.Set("User-Agent", "podux")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("HTTP %d from %s", resp.StatusCode, url)
}
_, err = io.Copy(w, resp.Body)
return err
}
// copyFile copies src to dst.
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
return err
}
+129
View File
@@ -0,0 +1,129 @@
package binary
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
)
type binarySpec struct {
githubOwner string
githubRepo string
// resolveAsset returns (assetFilename, entryPath).
// entryPath is the path of the binary inside the archive; empty means the asset is a raw binary.
resolveAsset func(version, goos, goarch string) (assetFilename, entryPath string, err error)
}
var specs = map[string]binarySpec{
"cloudflared": {
githubOwner: "cloudflare",
githubRepo: "cloudflared",
resolveAsset: func(version, goos, goarch string) (string, string, error) {
switch goos + "/" + goarch {
case "linux/amd64":
return "cloudflared-linux-amd64", "", nil
case "linux/arm64":
return "cloudflared-linux-arm64", "", nil
case "darwin/amd64":
return "cloudflared-darwin-amd64.tgz", "cloudflared", nil
case "darwin/arm64":
return "cloudflared-darwin-arm64.tgz", "cloudflared", nil
case "windows/amd64":
return "cloudflared-windows-amd64.exe", "", nil
default:
return "", "", fmt.Errorf("cloudflared: unsupported platform %s/%s", goos, goarch)
}
},
},
"frpc": {
githubOwner: "fatedier",
githubRepo: "frp",
resolveAsset: func(version, goos, goarch string) (string, string, error) {
ver := strings.TrimPrefix(version, "v")
var osStr, archStr string
switch goos {
case "linux":
osStr = "linux"
case "darwin":
osStr = "darwin"
case "windows":
osStr = "windows"
default:
return "", "", fmt.Errorf("frpc: unsupported OS %s", goos)
}
switch goarch {
case "amd64":
archStr = "amd64"
case "arm64":
archStr = "arm64"
case "arm":
archStr = "arm"
default:
return "", "", fmt.Errorf("frpc: unsupported arch %s", goarch)
}
asset := fmt.Sprintf("frp_%s_%s_%s.tar.gz", ver, osStr, archStr)
binName := "frpc"
if goos == "windows" {
binName = "frpc.exe"
}
entry := fmt.Sprintf("frp_%s_%s_%s/%s", ver, osStr, archStr, binName)
return asset, entry, nil
},
},
"rathole": {
githubOwner: "rapiz1",
githubRepo: "rathole",
resolveAsset: func(version, goos, goarch string) (string, string, error) {
switch goos + "/" + goarch {
case "linux/amd64":
return "rathole-x86_64-unknown-linux-musl.zip", "rathole", nil
case "linux/arm64":
return "rathole-aarch64-unknown-linux-musl.zip", "rathole", nil
case "darwin/amd64":
return "rathole-x86_64-apple-darwin.zip", "rathole", nil
case "darwin/arm64":
return "rathole-aarch64-apple-darwin.zip", "rathole", nil
case "windows/amd64":
return "rathole-x86_64-pc-windows-msvc.zip", "rathole.exe", nil
default:
return "", "", fmt.Errorf("rathole: unsupported platform %s/%s", goos, goarch)
}
},
},
}
// githubLatestTag returns the tag_name of the latest GitHub release.
func githubLatestTag(ctx context.Context, owner, repo string) (string, error) {
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/releases/latest", owner, repo)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", err
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", "podux")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("GitHub API request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("GitHub API returned HTTP %d", resp.StatusCode)
}
var release struct {
TagName string `json:"tag_name"`
}
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return "", fmt.Errorf("decode GitHub response: %w", err)
}
if release.TagName == "" {
return "", fmt.Errorf("empty tag_name from GitHub API")
}
return release.TagName, nil
}
+9
View File
@@ -32,6 +32,12 @@ const ServerFormPage = lazy(() =>
const ServerLogPage = lazy(() =>
import("./pages/ServerLog/ServerLogPage").then((m) => ({ default: m.ServerLogPage }))
);
const IntegrationsPage = lazy(() =>
import("./pages/Integrations").then((m) => ({ default: m.IntegrationsPage }))
);
const IntegrationFormPage = lazy(() =>
import("./pages/Integrations/IntegrationFormPage").then((m) => ({ default: m.IntegrationFormPage }))
);
function AuthenticatedLayout() {
console.log("AuthenticatedLayout rendered");
@@ -77,6 +83,9 @@ function App() {
<Route path="/servers/:id/logs" element={<ServerLogPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="/import" element={<ImportPage />} />
<Route path="/integrations" element={<IntegrationsPage />} />
<Route path="/integrations/new" element={<IntegrationFormPage />} />
<Route path="/integrations/:id/edit" element={<IntegrationFormPage />} />
{/* <Route path="/versions" element={<VersionPage />} /> */}
</Route>
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 196"><path d="M0 0C1.55372433 1.34031496 3.09552869 2.69457421 4.625 4.0625c.82886719.68707031 1.65773437 1.37414062 2.51171875 2.08203125C25.42258854 21.68612043 36.54980032 44.43390409 39.3125 68.125c2.07030459 26.82769694-4.71759167 51.88460621-21.6875 72.9375C16.95984375 141.89265625 16.2946875 142.7228125 15.609375 143.578125-.48954121 162.53907075-23.36088313 173.85843847-47.9453125 176.78515625-71.93322964 178.72495365-97.49538979 173.22783488-116.75 158.125-118.30372433 156.78468504-119.84552869 155.43042579-121.375 154.0625-122.20386719 153.37542969-123.03273437 152.68835938-123.88671875 151.98046875-142.17258854 136.43887957-153.29980032 113.69109591-156.0625 90-158.13280459 63.17230306-151.34490833 38.11539379-134.375 17.0625-133.70984375 16.23234375-133.0446875 15.4021875-132.359375 14.546875-116.26045879-4.41407075-93.38911687-15.73343847-68.8046875-18.66015625-44.81677036-20.59995365-19.25461021-15.10283488.0.0z" fill="#307fec" transform="translate(156.375,18.9375)"></path><path d="M0 0C9.14866886.037533 17.22012512 2.42754171 25.875 5.3125 25.24816224 9.20323238 24.06490291 12.41180682 22.40625 15.98046875 21.91769531 17.03814453 21.42914063 18.09582031 20.92578125 19.18554688 20.41402344 20.27931641 19.90226562 21.37308594 19.375 22.5 18.86324219 23.60537109 18.35148437 24.71074219 17.82421875 25.84960938 14.22879464 33.60491071 14.22879464 33.60491071 12.875 36.3125c6.6.0 13.2.0 20 0-2.74311757 8.2293527-5.81983443 14.5072504-10 22-6.6.0-13.2.0-20 0-.66 1.98-1.32 3.96-2 6C-.30574675 66.89295828-1.51012196 69.4485972-2.75 72-7.20837762 81.30592927-11.1713474 90.78137319-15.125 100.3125c-11.55.0-23.1.0-35 0 1.12511809-6.75070855 1.12511809-6.75070855 2.92578125-10.4609375C-46.81443359 89.04976563-46.42964844 88.24796875-46.03320312 87.421875-45.63037109 86.60203125-45.22753906 85.7821875-44.8125 84.9375-44.42126953 84.12539062-44.03003906 83.31328125-43.62695312 82.4765625c1.48804651-3.07973806 2.98287133-6.15404921 4.54638671-9.19628906C-37.35389762 69.91812423-35.79432282 66.56321047-34.42578125 63.0390625-31.06119644 54.44632958-27.11915997 46.09069224-23.3125 37.6875c1.57027085-3.47078555 3.13906321-6.94223608 4.70703125-10.4140625C-18.22574921 26.43367371-17.84602966 25.59390991-17.45480347 24.72869873c2.79794821-6.20059747 5.53869159-12.4246724 8.22062683-18.67636108C-6.76291797.33468549-6.2733019.13332521.0.0z" fill="#fcfdfe" transform="translate(86.125,50.6875)"></path><path d="M0 0C5.49110072-.07550699 10.98188377-.12922511 16.47338867-.16479492c1.85877765-.01486511 3.71752171-.03516313 5.57617188-.06152344C56.20891765-.69780069 56.20891765-.69780069 69 7 69.88558594 7.51433594 69.88558594 7.51433594 70.7890625 8.0390625 73.62173603 9.79773659 75.12383176 11.18574763 77 14c.265625 2.92578125.265625 2.92578125.25 6.3125C77.25773437 21.97732422 77.25773437 21.97732422 77.265625 23.67578125 77 27 77 27 75 33c-11.55.0-23.1.0-35 0C40.33 31.02 40.66 29.04 41 27 41.92939473 18.83651171 41.92939473 18.83651171 39 11.5 30.21072208 4.17560173 20.01523416 2.92347445 8.9375 1.875c-.86560547-.08636719-1.73121094-.17273437-2.62304688-.26171875C4.21011156 1.40400971 2.10511876 1.20130332.0 1 0 .67.0.34.0.0z" fill="#f8fafe" transform="translate(83,45)"></path></svg>

After

Width:  |  Height:  |  Size: 3.2 KiB

+5
View File
@@ -62,6 +62,11 @@ const navItems = [
path: "/proxies",
icon: <Icon icon="lucide:network" width="18" height="18" />,
},
{
labelKey: "nav.integrations",
path: "/integrations",
icon: <Icon icon="lucide:plug" width="18" height="18" />,
},
];
const mobileBottomNavItems = navItems;
+54 -1
View File
@@ -36,6 +36,7 @@
"dashboard": "Dashboard",
"servers": "Servers",
"proxies": "Proxies",
"integrations": "Integrations",
"settings": "Settings",
"logout": "Logout",
"pbAdmin": "Admin Panel",
@@ -278,6 +279,7 @@
"addFirstProxy": "Connect your local services to the world. Add your first proxy configuration to get started.",
"createYourFirstProxy": "Create Your First Proxy",
"server": "Server",
"tunnel": "Protocol",
"bootStatus": "Boot Status",
"manageProxies": "Manage your proxy configurations",
"allProxies": "All Proxies",
@@ -343,7 +345,18 @@
"errorInvalidIP": "Invalid IP or hostname",
"errorInvalidPort": "Invalid port (1-65535)",
"errorRequired": "Required",
"errorSubdomainRequired": "Subdomain or custom domains required"
"errorSubdomainRequired": "Subdomain or custom domains required",
"proxyBackend": "Proxy Backend",
"backendFrp": "FRP",
"backendCloudflare": "Cloudflare",
"selectIntegration": "Select Integration",
"selectIntegrationPlaceholder": "Select an integration",
"noIntegrationsAvailable": "No integrations available",
"goAddIntegration": "Add an integration",
"publicHostnames": "Public Hostnames",
"publicHostnamesDesc": "Cloudflare will route these hostnames through the tunnel to your local service",
"addHostname": "Add Hostname",
"errorHostnameRequired": "At least one public hostname is required"
},
"settings": {
"title": "Settings",
@@ -460,6 +473,46 @@
"viewServers": "View Servers",
"importSuccess": "Import completed successfully"
},
"integration": {
"title": "Integrations",
"manageIntegrations": "Manage your external service integrations",
"totalIntegrations": "Total Integrations",
"active": "Active",
"inactive": "Inactive",
"allIntegrations": "All Integrations",
"searchIntegrations": "Search integrations...",
"refresh": "Refresh",
"addIntegration": "Add Integration",
"addIntegrationDesc": "Connect a new external service",
"editIntegration": "Edit Integration",
"updateIntegrationDesc": "Update integration settings",
"noIntegrations": "No Integrations Configured",
"addFirstIntegration": "Connect your first external service to get started.",
"addYourFirstIntegration": "Add Your First Integration",
"noResultsFound": "No results found",
"noIntegrationsMatch": "No integrations match your search query",
"clearSearch": "Clear Search",
"confirmDeletion": "Confirm Deletion",
"deleteConfirmMessage": "Are you sure you want to delete this integration? This action cannot be undone.",
"sectionBasic": "Basic Info",
"sectionCredentials": "Credentials",
"sectionMetadata": "Metadata",
"namePlaceholder": "e.g. My Cloudflare Account",
"cloudflareDesc": "Cloudflare DNS & Tunnel management",
"apiToken": "API Token",
"apiTokenPlaceholder": "Your Cloudflare API token",
"accountId": "Account ID",
"accountIdPlaceholder": "Your Cloudflare account ID",
"email": "Email",
"emailPlaceholder": "your@email.com",
"status_active": "Active",
"status_invalid": "Invalid",
"status_expired": "Expired",
"saving": "Saving...",
"saveChanges": "Save Changes",
"validate": "Validate",
"validating": "Validating..."
},
"error": {
"notFound": "Page Not Found",
"goHome": "Go to Home",
+54 -1
View File
@@ -36,6 +36,7 @@
"dashboard": "仪表板",
"servers": "服务器",
"proxies": "代理",
"integrations": "集成",
"settings": "设置",
"logout": "退出登录",
"pbAdmin": "后台管理",
@@ -278,6 +279,7 @@
"addFirstProxy": "将您的本地服务连接到世界。添加您的第一个代理配置以开始使用。",
"createYourFirstProxy": "创建您的第一个代理",
"server": "服务器",
"tunnel": "协议",
"bootStatus": "启动状态",
"manageProxies": "管理您的代理配置",
"allProxies": "所有代理",
@@ -343,7 +345,18 @@
"errorInvalidIP": "无效的 IP 或主机名",
"errorInvalidPort": "无效的端口(1-65535)",
"errorRequired": "必填",
"errorSubdomainRequired": "子域名或自定义域名为必填项"
"errorSubdomainRequired": "子域名或自定义域名为必填项",
"proxyBackend": "代理后端",
"backendFrp": "FRP",
"backendCloudflare": "Cloudflare",
"selectIntegration": "选择集成",
"selectIntegrationPlaceholder": "选择一个集成",
"noIntegrationsAvailable": "暂无可用集成",
"goAddIntegration": "添加集成",
"publicHostnames": "公开域名",
"publicHostnamesDesc": "Cloudflare 会将这些域名通过隧道路由到你的本地服务",
"addHostname": "添加域名",
"errorHostnameRequired": "至少需要一个公开域名"
},
"settings": {
"title": "设置",
@@ -460,6 +473,46 @@
"viewServers": "查看服务器",
"importSuccess": "导入完成"
},
"integration": {
"title": "集成",
"manageIntegrations": "管理您的外部服务集成",
"totalIntegrations": "集成总数",
"active": "已激活",
"inactive": "未激活",
"allIntegrations": "所有集成",
"searchIntegrations": "搜索集成...",
"refresh": "刷新",
"addIntegration": "添加集成",
"addIntegrationDesc": "连接一个新的外部服务",
"editIntegration": "编辑集成",
"updateIntegrationDesc": "更新集成配置",
"noIntegrations": "未配置集成",
"addFirstIntegration": "添加您的第一个外部服务集成以开始使用。",
"addYourFirstIntegration": "添加您的第一个集成",
"noResultsFound": "未找到结果",
"noIntegrationsMatch": "没有集成匹配您的搜索",
"clearSearch": "清除搜索",
"confirmDeletion": "确认删除",
"deleteConfirmMessage": "您确定要删除此集成吗?此操作无法撤消。",
"sectionBasic": "基本信息",
"sectionCredentials": "凭据",
"sectionMetadata": "元数据",
"namePlaceholder": "例如:我的 Cloudflare 账户",
"cloudflareDesc": "Cloudflare DNS 与隧道管理",
"apiToken": "API 令牌",
"apiTokenPlaceholder": "您的 Cloudflare API 令牌",
"accountId": "账户 ID",
"accountIdPlaceholder": "您的 Cloudflare 账户 ID",
"email": "邮箱",
"emailPlaceholder": "your@email.com",
"status_active": "已激活",
"status_invalid": "无效",
"status_expired": "已过期",
"saving": "保存中...",
"saveChanges": "保存更改",
"validate": "验证",
"validating": "验证中..."
},
"error": {
"notFound": "页面未找到",
"goHome": "返回首页",
+2 -2
View File
@@ -212,7 +212,7 @@ function VisitorNode({ data }: { data: Record<string, string> }) {
// Server Node
function ServerNode({ data }: { data: Record<string, string> }) {
const p = data.isDark === "1" ? DARK : LIGHT;
const online = data.bootStatus === "running";
const online = data.bootStatus === "active";
const accent = online ? C.online : C.eOff;
const handleColor = online ? C.eOn : C.eOff;
return (
@@ -404,7 +404,7 @@ export function TopologyChart({ topology }: TopologyChartProps) {
});
for (const { server, sProxies, startRow, rowCount } of serverRows) {
const serverOnline = server.bootStatus === "running";
const serverOnline = server.bootStatus === "active";
const serverCY = (startRow + rowCount / 2) * ROW_H;
const serverY = serverCY - SERVER_H / 2;
@@ -0,0 +1,185 @@
import {
Button,
Card,
Flex,
Text,
TextField,
Separator,
} from "@radix-ui/themes";
import { Icon } from "@iconify/react";
import { motion } from "framer-motion";
import { PageHeader } from "../../../components/PageHeader";
import { Loading } from "../../../components/Loading";
import { useTranslation } from "react-i18next";
import type { IntegrationFormData } from "./useIntegrationForm";
interface IntegrationFormPageViewProps {
isEditing: boolean;
formData: IntegrationFormData;
errors: Record<string, string>;
submitting: boolean;
loadingRecord: boolean;
mounted: boolean;
onChange: (field: keyof IntegrationFormData, value: string) => void;
onSubmit: () => void;
onCancel: () => void;
}
function SectionHeading({ title }: { title: string }) {
return (
<Text size="2" weight="bold" color="gray" style={{ textTransform: "uppercase", letterSpacing: "0.05em" }}>
{title}
</Text>
);
}
function FormItem({
label,
required,
error,
children,
}: {
label: string;
required?: boolean;
error?: string;
children: React.ReactNode;
}) {
return (
<Flex direction="column" gap="1">
<Text size="2" weight="medium">
{label}
{required && (
<Text color="red" ml="1">
*
</Text>
)}
</Text>
{children}
{error && (
<Text size="1" color="red">
{error}
</Text>
)}
</Flex>
);
}
export function IntegrationFormPageView({
isEditing,
formData,
errors,
submitting,
loadingRecord,
mounted,
onChange,
onSubmit,
onCancel,
}: IntegrationFormPageViewProps) {
const { t } = useTranslation();
if (loadingRecord) {
return (
<Flex align="center" justify="center" className="h-full py-20">
<Loading size="small" />
</Flex>
);
}
return (
<Flex direction="column" gap="5" className="flex flex-1 flex-col">
<PageHeader
title={isEditing ? t("integration.editIntegration") : t("integration.addIntegration")}
description={
isEditing ? t("integration.updateIntegrationDesc") : t("integration.addIntegrationDesc")
}
visible={mounted}
/>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
transition={{ duration: 0.5, delay: 0.1, ease: "easeOut" }}
>
<Card>
<Flex direction="column" gap="5" p="2">
{/* Basic Info */}
<Flex direction="column" gap="3">
<SectionHeading title={t("integration.sectionBasic")} />
<Separator size="4" />
<FormItem label={t("common.name")} required error={errors.name}>
<TextField.Root
placeholder={t("integration.namePlaceholder")}
value={formData.name}
onChange={(e) => onChange("name", e.target.value)}
/>
</FormItem>
<FormItem label={t("common.type")}>
<Flex
align="center"
gap="3"
p="3"
style={{
border: "2px solid var(--orange-8)",
borderRadius: "var(--radius-3)",
backgroundColor: "var(--orange-a2)",
}}
>
<Icon icon="simple-icons:cloudflare" width="24" height="24" color="var(--orange-11)" />
<Flex direction="column" gap="0">
<Text size="2" weight="bold">
Cloudflare
</Text>
<Text size="1" color="gray">
{t("integration.cloudflareDesc")}
</Text>
</Flex>
</Flex>
</FormItem>
</Flex>
{/* Credentials */}
<Flex direction="column" gap="3">
<SectionHeading title={t("integration.sectionCredentials")} />
<Separator size="4" />
<FormItem
label={t("integration.apiToken")}
required
error={errors.credentials}
>
<TextField.Root
type="password"
placeholder={t("integration.apiTokenPlaceholder")}
value={formData.credentials}
onChange={(e) => onChange("credentials", e.target.value)}
/>
</FormItem>
</Flex>
{/* Actions */}
<Flex gap="3" justify="end">
<Button variant="soft" color="gray" onClick={onCancel} disabled={submitting}>
{t("common.cancel")}
</Button>
<Button onClick={onSubmit} disabled={submitting}>
{submitting ? (
<>
<Icon icon="lucide:loader" width="14" height="14" className="animate-spin" />
{t("integration.saving")}
</>
) : isEditing ? (
t("integration.saveChanges")
) : (
t("integration.addIntegration")
)}
</Button>
</Flex>
</Flex>
</Card>
</motion.div>
</Flex>
);
}
@@ -0,0 +1,29 @@
import { useState, useEffect } from "react";
import { useIntegrationForm } from "./useIntegrationForm";
import { IntegrationFormPageView } from "./IntegrationFormPage.view";
export function IntegrationFormPage() {
const form = useIntegrationForm();
const [mounted, setMounted] = useState(false);
useEffect(() => {
const timer = setTimeout(() => setMounted(true), 100);
return () => clearTimeout(timer);
}, []);
return (
<IntegrationFormPageView
isEditing={form.isEditing}
formData={form.formData}
errors={form.errors}
submitting={form.submitting}
loadingRecord={form.loadingRecord}
mounted={mounted}
onChange={form.handleChange}
onSubmit={form.handleSubmit}
onCancel={() => form.navigate("/integrations")}
/>
);
}
export default IntegrationFormPage;
@@ -0,0 +1,102 @@
import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import pb from "../../../lib/pocketbase";
import { toast } from "sonner";
export interface IntegrationFormData {
name: string;
integrationsType: "cloudflare";
credentials: string;
}
const defaultData: IntegrationFormData = {
name: "",
integrationsType: "cloudflare",
credentials: "",
};
export function useIntegrationForm() {
const navigate = useNavigate();
const { id } = useParams<{ id: string }>();
const isEditing = !!id;
const [formData, setFormData] = useState<IntegrationFormData>(defaultData);
const [errors, setErrors] = useState<Record<string, string>>({});
const [submitting, setSubmitting] = useState(false);
const [loadingRecord, setLoadingRecord] = useState(isEditing);
useEffect(() => {
if (!id) return;
setLoadingRecord(true);
pb.collection("fh_integrations")
.getOne(id)
.then((record) => {
setFormData({
name: record.name || "",
integrationsType: record.integrationsType || "cloudflare",
credentials: record.credentials || "",
});
})
.catch(() => {
toast.error("Failed to load integration");
navigate("/integrations");
})
.finally(() => setLoadingRecord(false));
}, [id, navigate]);
const handleChange = (field: keyof IntegrationFormData, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
if (field === "name") {
setErrors((prev) => ({ ...prev, name: value ? "" : "Required" }));
}
if (field === "credentials") {
setErrors((prev) => ({ ...prev, credentials: value ? "" : "Required" }));
}
};
const validate = (): boolean => {
const newErrors: Record<string, string> = {};
if (!formData.name.trim()) newErrors.name = "Required";
if (!formData.credentials.trim()) newErrors.credentials = "Required";
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = async () => {
if (!validate()) return;
try {
setSubmitting(true);
const payload = {
name: formData.name.trim(),
integrationsType: formData.integrationsType,
credentials: formData.credentials.trim(),
status: "active",
};
if (isEditing) {
await pb.collection("fh_integrations").update(id!, payload);
toast.success("Integration updated successfully");
} else {
await pb.collection("fh_integrations").create(payload);
toast.success("Integration created successfully");
}
navigate("/integrations");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to save integration");
} finally {
setSubmitting(false);
}
};
return {
isEditing,
formData,
errors,
submitting,
loadingRecord,
handleChange,
handleSubmit,
navigate,
};
}
@@ -0,0 +1,453 @@
import {
Button,
Card,
Flex,
Heading,
Text,
Badge,
Table,
TextField,
AlertDialog,
} from "@radix-ui/themes";
import { useNavigate } from "react-router-dom";
import { useState, useEffect } from "react";
import { Icon } from "@iconify/react";
import { motion, AnimatePresence } from "framer-motion";
import { AnimateNumber } from "../../components/AnimateNumber";
import { EmptyState } from "../../components/EmptyState";
import type { Integration } from "./useIntegrations";
import { PageHeader } from "../../components/PageHeader";
import { Loading } from "../../components/Loading";
import { StatCard } from "../../components/StatCard";
import { useTranslation } from "react-i18next";
interface IntegrationsViewProps {
integrations: Integration[];
loading?: boolean;
refreshing: boolean;
deleteIntegration: (id: string) => void;
validateIntegration: (id: string) => void;
validatingId: string | null;
search: string;
setSearch: (value: string) => void;
refreshIntegrations: () => void;
page: number;
setPage: (page: number) => void;
totalPages: number;
}
const STATUS_COLOR: Record<string, "green" | "red" | "orange" | "gray"> = {
active: "green",
invalid: "red",
expired: "orange",
};
export function IntegrationsView({
integrations,
loading,
refreshing,
deleteIntegration,
validateIntegration,
validatingId,
search,
setSearch,
refreshIntegrations,
page,
setPage,
totalPages,
}: IntegrationsViewProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const [deleteId, setDeleteId] = useState<string | null>(null);
const [mounted, setMounted] = useState(false);
useEffect(() => {
const timer = setTimeout(() => setMounted(true), 100);
return () => clearTimeout(timer);
}, []);
return (
<>
<Flex direction="column" gap="5" className="flex flex-1 flex-col">
{/* Header */}
<PageHeader
title={t("integration.title")}
description={t("integration.manageIntegrations")}
visible={mounted}
/>
{/* Stats Cards */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
transition={{ duration: 0.5, delay: 0.1, ease: "easeOut" }}
>
<StatCard
title={t("integration.totalIntegrations")}
value={<AnimateNumber value={integrations.length} decimalPlaces={0} />}
color="gray"
icon={<Icon icon="lucide:plug" width="32" height="32" color="var(--gray-11)" />}
/>
</motion.div>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
transition={{ duration: 0.5, delay: 0.2, ease: "easeOut" }}
>
<StatCard
title={t("integration.active")}
value={
<span className="text-[#30A46C]">
<AnimateNumber
value={integrations.filter((i) => i.status === "active").length}
decimalPlaces={0}
/>
</span>
}
color="green"
icon={<Icon icon="lucide:check-circle" width="32" height="32" color="var(--green-11)" />}
/>
</motion.div>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
transition={{ duration: 0.5, delay: 0.3, ease: "easeOut" }}
>
<StatCard
title={t("integration.inactive")}
value={
<span className="text-[#E5484D]">
<AnimateNumber
value={integrations.filter((i) => i.status !== "active").length}
decimalPlaces={0}
/>
</span>
}
color="red"
icon={<Icon icon="lucide:x-circle" width="32" height="32" color="var(--red-11)" />}
/>
</motion.div>
</div>
{/* Table */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
transition={{ duration: 0.5, delay: 0.4, ease: "easeOut" }}
className="flex flex-1 flex-col overflow-hidden"
>
<Card className="flex flex-1 flex-col">
<Flex direction="column" gap="3" mb="4" p="2">
<Flex justify="between" align="center" wrap="wrap" gap="2">
<Text size="3" weight="bold">
{t("integration.allIntegrations")}
</Text>
<Flex gap="2" wrap="wrap" align="center">
<TextField.Root
size="2"
placeholder={t("integration.searchIntegrations")}
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={refreshIntegrations} disabled={refreshing}>
<Icon
icon="lucide:refresh-cw"
width="14"
height="14"
className={refreshing ? "animate-spin" : ""}
/>
{t("integration.refresh")}
</Button>
<Button onClick={() => navigate("/integrations/new")}>
<Icon icon="lucide:plus" width="14" height="14" />
{t("integration.addIntegration")}
</Button>
</Flex>
</Flex>
</Flex>
<AnimatePresence mode="wait">
{loading ? (
<motion.div
key="loading"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="flex-1"
>
<Flex
direction="column"
align="center"
justify="center"
gap="2"
className="h-full py-12"
>
<Loading size="small" />
</Flex>
</motion.div>
) : integrations.length === 0 ? (
search ? (
<motion.div
key="no-results"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="flex-1"
>
<Flex
direction="column"
align="center"
justify="center"
gap="2"
className="h-full"
>
<Icon icon="lucide:search" width="32" height="32" color="gray" />
<Heading size="4">{t("integration.noResultsFound")}</Heading>
<Text color="gray" size="2">
{t("integration.noIntegrationsMatch")} "{search}"
</Text>
<Button variant="soft" mt="2" onClick={() => setSearch("")}>
{t("integration.clearSearch")}
</Button>
</Flex>
</motion.div>
) : (
<motion.div
key="empty-state"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="flex-1"
>
<Flex direction="column" align="center" justify="center" className="h-full">
<EmptyState
title={t("integration.noIntegrations")}
description={t("integration.addFirstIntegration")}
actionText={t("integration.addYourFirstIntegration")}
onAction={() => navigate("/integrations/new")}
/>
</Flex>
</motion.div>
)
) : (
<motion.div
key="table"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
>
<div className="overflow-x-auto">
<Table.Root>
<Table.Header>
<Table.Row>
<Table.ColumnHeaderCell>{t("common.name")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("common.type")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("common.status")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("common.created")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("common.actions")}</Table.ColumnHeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{integrations.map((integration) => (
<Table.Row key={integration.id}>
<Table.Cell>
<Text weight="medium">{integration.name}</Text>
</Table.Cell>
<Table.Cell>
<Flex align="center" gap="1">
<Icon icon="simple-icons:cloudflare" width="16" height="16" color="var(--orange-11)" />
<Badge variant="surface" color="orange">
{integration.integrationsType}
</Badge>
</Flex>
</Table.Cell>
<Table.Cell>
<Badge
radius="full"
color={STATUS_COLOR[integration.status] ?? "gray"}
>
<span
className={`status-dot ${
integration.status === "active"
? "status-dot-green"
: "status-dot-red"
}`}
/>
{t(`integration.status_${integration.status}`)}
</Badge>
</Table.Cell>
<Table.Cell>
<Text size="2" color="gray">
{new Date(integration.created).toLocaleDateString()}
</Text>
</Table.Cell>
<Table.Cell>
<Flex gap="2">
<Button
size="1"
variant="soft"
color="green"
className="cursor-pointer"
disabled={validatingId === integration.id}
onClick={() => validateIntegration(integration.id)}
>
<Icon
icon={validatingId === integration.id ? "lucide:loader" : "lucide:shield-check"}
width="14"
height="14"
className={validatingId === integration.id ? "animate-spin" : ""}
/>
{t("integration.validate")}
</Button>
<Button
size="1"
variant="soft"
className="cursor-pointer"
onClick={() => navigate(`/integrations/${integration.id}/edit`)}
>
<Icon icon="lucide:pencil" width="14" height="14" />
{t("common.edit")}
</Button>
<Button
size="1"
variant="soft"
className="cursor-pointer"
color="red"
onClick={() => setDeleteId(integration.id)}
>
<Icon icon="lucide:trash" width="14" height="14" />
{t("common.delete")}
</Button>
</Flex>
</Table.Cell>
</Table.Row>
))}
</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>
</Card>
</motion.div>
</Flex>
<AlertDialog.Root open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
<AlertDialog.Content maxWidth="450px">
<AlertDialog.Title>{t("integration.confirmDeletion")}</AlertDialog.Title>
<AlertDialog.Description size="2">
{t("integration.deleteConfirmMessage")}
</AlertDialog.Description>
<Flex gap="3" mt="4" justify="end">
<AlertDialog.Cancel>
<Button variant="soft" color="gray">
{t("common.cancel")}
</Button>
</AlertDialog.Cancel>
<AlertDialog.Action>
<Button
variant="solid"
color="red"
onClick={() => {
if (deleteId) {
deleteIntegration(deleteId);
setDeleteId(null);
}
}}
>
{t("common.delete")}
</Button>
</AlertDialog.Action>
</Flex>
</AlertDialog.Content>
</AlertDialog.Root>
</>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { useIntegrations } from "./useIntegrations";
import { IntegrationsView } from "./IntegrationsPage.view";
export function IntegrationsPage() {
const state = useIntegrations();
return <IntegrationsView {...state} />;
}
export default IntegrationsPage;
@@ -0,0 +1,120 @@
import { useState, useEffect, useCallback, useRef } from "react";
import pb from "../../lib/pocketbase";
import { apiPost } from "../../lib/api";
import { toast } from "sonner";
export interface Integration {
id: string;
name: string;
integrationsType: "cloudflare";
metadata: Record<string, string>;
credentials: string;
status: "active" | "invalid" | "expired";
created: string;
updated: string;
}
export function useIntegrations() {
const [integrations, setIntegrations] = useState<Integration[]>([]);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const initializedRef = useRef(false);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const PER_PAGE = 10;
const [search, setSearch] = useState("");
const fetchIntegrations = useCallback(
async (isRefresh = false) => {
try {
if (!initializedRef.current) {
setLoading(true);
} else if (isRefresh) {
setRefreshing(true);
}
let filter = "";
if (search) {
filter = `name ~ "${search}"`;
}
const result = await pb.collection("fh_integrations").getList(page, PER_PAGE, {
filter,
sort: "-created",
});
setIntegrations(result.items as unknown as Integration[]);
setTotalPages(result.totalPages);
initializedRef.current = true;
} catch (err) {
if ((err as any)?.isAbort) return;
toast.error(err instanceof Error ? err.message : "Failed to fetch integrations");
} finally {
setLoading(false);
setRefreshing(false);
}
},
[page, search]
);
useEffect(() => {
setPage(1);
if (initializedRef.current) {
setLoading(true);
}
}, [search]);
useEffect(() => {
const timer = setTimeout(() => {
fetchIntegrations();
}, 300);
return () => clearTimeout(timer);
}, [fetchIntegrations]);
const [validatingId, setValidatingId] = useState<string | null>(null);
const deleteIntegration = async (id: string) => {
try {
await pb.collection("fh_integrations").delete(id);
await fetchIntegrations();
toast.success("Integration deleted successfully");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to delete integration");
}
};
const validateIntegration = async (id: string) => {
try {
setValidatingId(id);
const res = await apiPost("/api/integrations/validate", { id });
const data = await res.json();
if (!res.ok) {
toast.error(data.error || "Validation failed");
} else {
toast.success("Validation successful");
}
await fetchIntegrations();
} catch (err) {
toast.error(err instanceof Error ? err.message : "Validation failed");
} finally {
setValidatingId(null);
}
};
return {
integrations,
loading,
refreshing,
deleteIntegration,
validateIntegration,
validatingId,
page,
setPage,
totalPages,
search,
setSearch,
refreshIntegrations: () => fetchIntegrations(true),
};
}
+18 -1
View File
@@ -1,4 +1,5 @@
import { Icon } from "@iconify/react";
import frpLogo from "../../assets/frp.svg";
import { Badge, Button, Card, Flex, Table, Text, TextField, AlertDialog } from "@radix-ui/themes";
import { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
@@ -196,6 +197,7 @@ export function ProxiesView({
<Table.Row>
<Table.ColumnHeaderCell>{t("common.name")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("common.type")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("proxy.tunnel")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("proxy.server")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("proxy.localIP")}</Table.ColumnHeaderCell>
<Table.ColumnHeaderCell>{t("proxy.localPort")}</Table.ColumnHeaderCell>
@@ -213,7 +215,22 @@ export function ProxiesView({
<Text weight="medium">{proxy.name || <Text color="gray">-</Text>}</Text>
</Table.Cell>
<Table.Cell>
<Badge variant="surface">{proxy.proxyType.toUpperCase()}</Badge>
<Badge variant="surface">{proxy.proxyType?.toUpperCase()}</Badge>
</Table.Cell>
<Table.Cell>
{proxy.tunnelType === "cloudflare" ? (
<Badge variant="surface" color="orange">
<Icon icon="simple-icons:cloudflare" width="10" height="10" />
Cloudflare
</Badge>
) : proxy.tunnelType === "frp" ? (
<Badge variant="surface" color="blue">
<img src={frpLogo} alt="frp" width="10" height="10" style={{ display: "inline-block" }} />
FRP
</Badge>
) : (
<Text color="gray">-</Text>
)}
</Table.Cell>
<Table.Cell>
{(proxy as { expand?: { serverId?: { serverName?: string } } }).expand?.serverId ? (
@@ -21,7 +21,12 @@ import { PageHeader } from "../../../components/PageHeader";
import { SectionHeading } from "../../../components/SectionHeading";
import { RadioCardGroup } from "../../../components/RadioCardGroup";
import { ServerLatency } from "../../../components/ServerLatency";
import { type ProxyFormData, type ServerOption } from "./useProxyForm";
import { type ProxyFormData, type ServerOption, type IntegrationOption } from "./useProxyForm";
const backendOptions = [
{ value: "frp", label: "FRP", icon: "lucide:server", comingSoon: false },
{ value: "cloudflare", label: "Cloudflare", icon: "simple-icons:cloudflare", comingSoon: false },
];
const proxyTypes = [
{ value: "tcp", label: "TCP", icon: "lucide:arrow-right-left", comingSoon: false },
@@ -51,34 +56,42 @@ interface ProxyFormPageViewProps {
isEditing: boolean;
formData: ProxyFormData;
servers: ServerOption[];
integrations: IntegrationOption[];
loadingServers: boolean;
loadingIntegrations: boolean;
loadingProxy: boolean;
submitting: boolean;
errors: Partial<Record<keyof ProxyFormData, string>>;
isHttpType: boolean;
isSocks5Plugin: boolean;
isCloudflare: boolean;
mounted: boolean;
onChange: (field: keyof ProxyFormData, value: string | boolean | string[]) => void;
onSubmit: () => void;
onCancel: () => void;
onNavigateToServers: () => void;
onNavigateToIntegrations: () => void;
}
export function ProxyFormPageView({
isEditing,
formData,
servers,
integrations,
loadingServers,
loadingIntegrations,
loadingProxy,
submitting,
errors,
isHttpType,
isSocks5Plugin,
isCloudflare,
mounted,
onChange,
onSubmit,
onCancel,
onNavigateToServers,
onNavigateToIntegrations,
}: ProxyFormPageViewProps) {
const { t } = useTranslation();
const scrollContainerRef = useRef<HTMLDivElement>(null);
@@ -115,62 +128,144 @@ export function ProxyFormPageView({
<section>
<SectionHeading id="section-basic" title={t("proxy.sectionBasic")} icon="lucide:info" />
<Flex direction="column" gap="4">
<FormItem label={t("proxy.selectServer")} required>
<Select.Root
value={formData.serverId}
onValueChange={(v) => onChange("serverId", v)}
disabled={loadingServers || servers.length === 0}
>
<Select.Trigger
placeholder={
loadingServers
? t("common.loading")
: servers.length === 0
? t("proxy.noServersAvailable")
: t("proxy.selectServerPlaceholder")
}
style={{ width: "100%" }}
/>
<Select.Content>
{servers.map((s) => (
<Select.Item key={s.id} value={s.id}>
<Flex align="center" gap="2">
<span
className={`inline-block h-1.5 w-1.5 shrink-0 rounded-full ${
s.bootStatus === "running" ? "bg-[var(--green-9)]" : "bg-[var(--gray-7)]"
}`}
/>
<Text size="2">{s.serverName}</Text>
<ServerLatency networkStatus={s.networkStatus} size="1" />
</Flex>
</Select.Item>
))}
</Select.Content>
</Select.Root>
{servers.length === 0 && !loadingServers && (
<Callout.Root size="1" color="orange" mt="2">
<Callout.Icon>
<Icon icon="lucide:triangle-alert" width="14" height="14" />
</Callout.Icon>
<Callout.Text>
<Flex align="center" justify="between" gap="2">
<Text size="1">{t("proxy.noServersAvailable")}</Text>
<Button
size="1"
variant="ghost"
color="orange"
className="cursor-pointer shrink-0"
onClick={onNavigateToServers}
>
{t("proxy.goAddServer")}
<Icon icon="lucide:arrow-right" width="12" height="12" />
</Button>
</Flex>
</Callout.Text>
</Callout.Root>
)}
<FormItem label={t("proxy.proxyBackend")} required>
<RadioCardGroup
options={backendOptions}
value={formData.proxyBackend}
onChange={(v) => onChange("proxyBackend", v as ProxyFormData["proxyBackend"])}
comingSoonLabel={t("common.comingSoon")}
/>
</FormItem>
<AnimatePresence mode="wait">
{isCloudflare ? (
<motion.div
key="integration-selector"
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.2, ease: "easeInOut" }}
style={{ overflow: "hidden" }}
>
<FormItem label={t("proxy.selectIntegration")} required error={errors.integrationId}>
<Select.Root
value={formData.integrationId}
onValueChange={(v) => onChange("integrationId", v)}
disabled={loadingIntegrations || integrations.length === 0}
>
<Select.Trigger
placeholder={
loadingIntegrations
? t("common.loading")
: integrations.length === 0
? t("proxy.noIntegrationsAvailable")
: t("proxy.selectIntegrationPlaceholder")
}
style={{ width: "100%" }}
/>
<Select.Content>
{integrations.map((i) => (
<Select.Item key={i.id} value={i.id}>
<Flex align="center" gap="2">
<Icon icon="lucide:plug" width="12" height="12" />
<Text size="2">{i.name}</Text>
</Flex>
</Select.Item>
))}
</Select.Content>
</Select.Root>
{integrations.length === 0 && !loadingIntegrations && (
<Callout.Root size="1" color="orange" mt="2">
<Callout.Icon>
<Icon icon="lucide:triangle-alert" width="14" height="14" />
</Callout.Icon>
<Callout.Text>
<Flex align="center" justify="between" gap="2">
<Text size="1">{t("proxy.noIntegrationsAvailable")}</Text>
<Button
size="1"
variant="ghost"
color="orange"
className="cursor-pointer shrink-0"
onClick={onNavigateToIntegrations}
>
{t("proxy.goAddIntegration")}
<Icon icon="lucide:arrow-right" width="12" height="12" />
</Button>
</Flex>
</Callout.Text>
</Callout.Root>
)}
</FormItem>
</motion.div>
) : (
<motion.div
key="server-selector"
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.2, ease: "easeInOut" }}
style={{ overflow: "hidden" }}
>
<FormItem label={t("proxy.selectServer")} required error={errors.serverId}>
<Select.Root
value={formData.serverId}
onValueChange={(v) => onChange("serverId", v)}
disabled={loadingServers || servers.length === 0}
>
<Select.Trigger
placeholder={
loadingServers
? t("common.loading")
: servers.length === 0
? t("proxy.noServersAvailable")
: t("proxy.selectServerPlaceholder")
}
style={{ width: "100%" }}
/>
<Select.Content>
{servers.map((s) => (
<Select.Item key={s.id} value={s.id}>
<Flex align="center" gap="2">
<span
className={`inline-block h-1.5 w-1.5 shrink-0 rounded-full ${
s.bootStatus === "active" ? "bg-[var(--green-9)]" : "bg-[var(--gray-7)]"
}`}
/>
<Text size="2">{s.serverName}</Text>
<ServerLatency networkStatus={s.networkStatus} size="1" />
</Flex>
</Select.Item>
))}
</Select.Content>
</Select.Root>
{servers.length === 0 && !loadingServers && (
<Callout.Root size="1" color="orange" mt="2">
<Callout.Icon>
<Icon icon="lucide:triangle-alert" width="14" height="14" />
</Callout.Icon>
<Callout.Text>
<Flex align="center" justify="between" gap="2">
<Text size="1">{t("proxy.noServersAvailable")}</Text>
<Button
size="1"
variant="ghost"
color="orange"
className="cursor-pointer shrink-0"
onClick={onNavigateToServers}
>
{t("proxy.goAddServer")}
<Icon icon="lucide:arrow-right" width="12" height="12" />
</Button>
</Flex>
</Callout.Text>
</Callout.Root>
)}
</FormItem>
</motion.div>
)}
</AnimatePresence>
<FormItem label={t("proxy.proxyName")} required error={errors.name}>
<TextField.Root
size="2"
@@ -181,14 +276,16 @@ export function ProxyFormPageView({
/>
</FormItem>
<FormItem label={t("proxy.proxyType")} required>
<RadioCardGroup
options={proxyTypes}
value={formData.type}
onChange={(v) => onChange("type", v as ProxyFormData["type"])}
comingSoonLabel={t("common.comingSoon")}
/>
</FormItem>
{!isCloudflare && (
<FormItem label={t("proxy.proxyType")} required>
<RadioCardGroup
options={proxyTypes}
value={formData.type}
onChange={(v) => onChange("type", v as ProxyFormData["type"])}
comingSoonLabel={t("common.comingSoon")}
/>
</FormItem>
)}
</Flex>
</section>
@@ -198,55 +295,43 @@ export function ProxyFormPageView({
<section>
<SectionHeading id="section-network" title={t("proxy.sectionNetwork")} icon="lucide:network" />
<Flex direction="column" gap="4">
<AnimatePresence>
{!isSocks5Plugin && (
<motion.div
key="local-addr"
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.2, ease: "easeInOut" }}
style={{ overflow: "hidden" }}
>
<Flex gap="3">
<Box className="flex-[2]">
<FormItem label={t("proxy.localAddress")} required error={errors.localIp}>
<TextField.Root
size="2"
placeholder={t("proxy.localAddressPlaceholder")}
value={formData.localIp}
onChange={(e) => onChange("localIp", e.target.value)}
color={errors.localIp ? "red" : undefined}
/>
</FormItem>
</Box>
<Box className="flex-1">
<FormItem label={t("proxy.localPort")} required error={errors.localPort}>
<TextField.Root
size="2"
placeholder={t("proxy.localPortPlaceholder")}
type="number"
value={formData.localPort}
onChange={(e) => onChange("localPort", e.target.value)}
color={errors.localPort ? "red" : undefined}
/>
</FormItem>
</Box>
</Flex>
</motion.div>
)}
</AnimatePresence>
{isHttpType ? (
{isCloudflare ? (
<>
<FormItem label={t("proxy.customDomainsLabel")}>
{/* Cloudflare: local service + public hostnames */}
<Flex gap="3">
<Box className="flex-[2]">
<FormItem label={t("proxy.localAddress")} required error={errors.localIp}>
<TextField.Root
size="2"
placeholder={t("proxy.localAddressPlaceholder")}
value={formData.localIp}
onChange={(e) => onChange("localIp", e.target.value)}
color={errors.localIp ? "red" : undefined}
/>
</FormItem>
</Box>
<Box className="flex-1">
<FormItem label={t("proxy.localPort")} required error={errors.localPort}>
<TextField.Root
size="2"
placeholder={t("proxy.localPortPlaceholder")}
type="number"
value={formData.localPort}
onChange={(e) => onChange("localPort", e.target.value)}
color={errors.localPort ? "red" : undefined}
/>
</FormItem>
</Box>
</Flex>
<FormItem label={t("proxy.publicHostnames")} required error={errors.customDomains}>
<Flex direction="column" gap="2">
{formData.customDomains.map((domain, index) => (
<Flex key={index} gap="2" align="center">
<TextField.Root
size="2"
style={{ flex: 1 }}
placeholder={`example.com`}
placeholder="app.example.com"
value={domain}
onChange={(e) => {
const next = [...formData.customDomains];
@@ -275,44 +360,134 @@ export function ProxyFormPageView({
onClick={() => onChange("customDomains", [...formData.customDomains, ""])}
>
<Icon icon="lucide:plus" />
{t("proxy.addCustomDomain")}
{t("proxy.addHostname")}
</Button>
</Flex>
</FormItem>
<FormItem label={t("proxy.subdomain")}>
<TextField.Root
size="2"
placeholder={t("proxy.subdomainPlaceholder")}
value={formData.subdomain}
onChange={(e) => onChange("subdomain", e.target.value)}
/>
<Text size="1" color="gray" mt="1">
{t("proxy.subdomainDesc")}
{t("proxy.publicHostnamesDesc")}
</Text>
</FormItem>
</>
) : (
<FormItem label={t("proxy.remotePortLabel")} required error={errors.remotePort}>
<TextField.Root
size="2"
placeholder={t("proxy.remotePortPlaceholder")}
type="number"
value={formData.remotePort}
onChange={(e) => onChange("remotePort", e.target.value)}
color={errors.remotePort ? "red" : undefined}
/>
<Text size="1" color="gray" mt="1">
{t("proxy.remotePortDesc")}
</Text>
</FormItem>
<>
{/* FRP: local addr + remote port or domain */}
<AnimatePresence>
{!isSocks5Plugin && (
<motion.div
key="local-addr"
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.2, ease: "easeInOut" }}
style={{ overflow: "hidden" }}
>
<Flex gap="3">
<Box className="flex-[2]">
<FormItem label={t("proxy.localAddress")} required error={errors.localIp}>
<TextField.Root
size="2"
placeholder={t("proxy.localAddressPlaceholder")}
value={formData.localIp}
onChange={(e) => onChange("localIp", e.target.value)}
color={errors.localIp ? "red" : undefined}
/>
</FormItem>
</Box>
<Box className="flex-1">
<FormItem label={t("proxy.localPort")} required error={errors.localPort}>
<TextField.Root
size="2"
placeholder={t("proxy.localPortPlaceholder")}
type="number"
value={formData.localPort}
onChange={(e) => onChange("localPort", e.target.value)}
color={errors.localPort ? "red" : undefined}
/>
</FormItem>
</Box>
</Flex>
</motion.div>
)}
</AnimatePresence>
{isHttpType ? (
<>
<FormItem label={t("proxy.customDomainsLabel")}>
<Flex direction="column" gap="2">
{formData.customDomains.map((domain, index) => (
<Flex key={index} gap="2" align="center">
<TextField.Root
size="2"
style={{ flex: 1 }}
placeholder="example.com"
value={domain}
onChange={(e) => {
const next = [...formData.customDomains];
next[index] = e.target.value;
onChange("customDomains", next);
}}
/>
<Button
type="button"
size="2"
variant="soft"
color="red"
onClick={() => {
const next = formData.customDomains.filter((_, i) => i !== index);
onChange("customDomains", next);
}}
>
<Icon icon="lucide:x" />
</Button>
</Flex>
))}
<Button
type="button"
size="2"
variant="soft"
onClick={() => onChange("customDomains", [...formData.customDomains, ""])}
>
<Icon icon="lucide:plus" />
{t("proxy.addCustomDomain")}
</Button>
</Flex>
</FormItem>
<FormItem label={t("proxy.subdomain")}>
<TextField.Root
size="2"
placeholder={t("proxy.subdomainPlaceholder")}
value={formData.subdomain}
onChange={(e) => onChange("subdomain", e.target.value)}
/>
<Text size="1" color="gray" mt="1">
{t("proxy.subdomainDesc")}
</Text>
</FormItem>
</>
) : (
<FormItem label={t("proxy.remotePortLabel")} required error={errors.remotePort}>
<TextField.Root
size="2"
placeholder={t("proxy.remotePortPlaceholder")}
type="number"
value={formData.remotePort}
onChange={(e) => onChange("remotePort", e.target.value)}
color={errors.remotePort ? "red" : undefined}
/>
<Text size="1" color="gray" mt="1">
{t("proxy.remotePortDesc")}
</Text>
</FormItem>
)}
</>
)}
</Flex>
</section>
<Separator size="4" />
{!isCloudflare && <Separator size="4" />}
{/* 传输选项 */}
<section>
{!isCloudflare && <section>
<SectionHeading id="section-transport" title={t("proxy.sectionTransport")} icon="lucide:shield" />
<Flex direction="column" gap="3">
<Flex justify="between" align="center">
@@ -339,12 +514,12 @@ export function ProxyFormPageView({
/>
</Flex>
</Flex>
</section>
</section>}
<Separator size="4" />
{!isCloudflare && <Separator size="4" />}
{/* 插件 */}
<section>
{!isCloudflare && <section>
<SectionHeading id="section-plugin" title={t("proxy.sectionPlugin")} icon="lucide:puzzle" />
<Flex direction="column" gap="4">
<Flex justify="between" align="center">
@@ -414,7 +589,7 @@ export function ProxyFormPageView({
)}
</AnimatePresence>
</Flex>
</section>
</section>}
<Separator size="4" />
@@ -16,17 +16,21 @@ export function ProxyFormPage() {
isEditing={form.isEditing}
formData={form.formData}
servers={form.servers}
integrations={form.integrations}
loadingServers={form.loadingServers}
loadingIntegrations={form.loadingIntegrations}
loadingProxy={form.loadingProxy}
submitting={form.submitting}
errors={form.errors}
isHttpType={form.isHttpType}
isSocks5Plugin={form.isSocks5Plugin}
isCloudflare={form.isCloudflare}
mounted={mounted}
onChange={form.handleChange}
onSubmit={form.handleSubmit}
onCancel={() => form.navigate("/proxies")}
onNavigateToServers={() => form.navigate("/servers")}
onNavigateToIntegrations={() => form.navigate("/integrations")}
/>
);
}
@@ -2,12 +2,21 @@ import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import pb from "../../../lib/pocketbase";
import { apiGet } from "../../../lib/api";
import { apiGet, apiPost } from "../../../lib/api";
import { toast } from "sonner";
import { REGEX } from "../../../lib/regex";
export interface IntegrationOption {
id: string;
name: string;
integrationsType: string;
status: string;
}
export interface ProxyFormData {
proxyBackend: "frp" | "cloudflare";
serverId: string;
integrationId: string;
name: string;
type: "tcp" | "udp" | "http" | "https" | "tcpmux" | "stcp" | "sudp" | "xtcp";
localIp: string;
@@ -25,7 +34,9 @@ export interface ProxyFormData {
}
const DEFAULT_FORM: ProxyFormData = {
proxyBackend: "frp",
serverId: "",
integrationId: "",
name: "",
type: "tcp",
localIp: "127.0.0.1",
@@ -60,7 +71,9 @@ export function useProxyForm() {
const [formData, setFormData] = useState<ProxyFormData>(DEFAULT_FORM);
const [servers, setServers] = useState<ServerOption[]>([]);
const [integrations, setIntegrations] = useState<IntegrationOption[]>([]);
const [loadingServers, setLoadingServers] = useState(false);
const [loadingIntegrations, setLoadingIntegrations] = useState(false);
const [loadingProxy, setLoadingProxy] = useState(isEditing);
const [submitting, setSubmitting] = useState(false);
const [errors, setErrors] = useState<Partial<Record<keyof ProxyFormData, string>>>({});
@@ -86,15 +99,37 @@ export function useProxyForm() {
fetchServers();
}, [isEditing]);
useEffect(() => {
const fetchIntegrations = async () => {
try {
setLoadingIntegrations(true);
const result = await pb.collection("fh_integrations").getFullList<IntegrationOption>({
sort: "name",
fields: "id,name,integrationsType,status",
});
setIntegrations(result);
} catch (err) {
console.error("Failed to fetch integrations:", err);
} finally {
setLoadingIntegrations(false);
}
};
fetchIntegrations();
}, []);
useEffect(() => {
if (!id) return;
const fetchProxy = async () => {
try {
setLoadingProxy(true);
const record = await pb.collection("fh_proxies").getOne(id);
const record = await pb.collection("fh_proxies").getOne(id, { expand: "tunnelId" });
const plugin = record.plugin as Record<string, string> | null | undefined;
const tunnel = (record as any).expand?.tunnelId as { type?: string; integrationId?: string; serverId?: string } | undefined;
const proxyBackend: ProxyFormData["proxyBackend"] = tunnel?.type === "cloudflare" ? "cloudflare" : "frp";
setFormData({
serverId: record.serverId as string,
proxyBackend,
serverId: tunnel?.serverId || (record.serverId as string) || "",
integrationId: tunnel?.integrationId || "",
name: (record.name as string) || "",
type: record.proxyType as ProxyFormData["type"],
localIp: (record.localIP as string) || "127.0.0.1",
@@ -154,29 +189,42 @@ export function useProxyForm() {
};
const validate = (data: ProxyFormData): boolean => {
const isCloudflare = data.proxyBackend === "cloudflare";
const isHttp = data.type === "http" || data.type === "https";
const isSocks5 = data.pluginEnabled && data.pluginType === "socks5";
const newErrors: Partial<Record<keyof ProxyFormData, string>> = {};
if (!data.serverId) newErrors.serverId = t("proxy.errorRequired");
if (!data.name) newErrors.name = t("proxy.errorRequired");
else if (!REGEX.PROXY_NAME.test(data.name)) newErrors.name = t("proxy.errorInvalidName");
if (!isSocks5) {
if (isCloudflare) {
if (!data.integrationId) newErrors.integrationId = t("proxy.errorRequired");
if (!data.localIp) newErrors.localIp = t("proxy.errorRequired");
else if (!REGEX.IP_OR_HOSTNAME.test(data.localIp)) newErrors.localIp = t("proxy.errorInvalidIP");
if (!data.localPort) newErrors.localPort = t("proxy.errorRequired");
else if (!REGEX.PORT.test(data.localPort)) newErrors.localPort = t("proxy.errorInvalidPort");
}
if (data.customDomains.length === 0 || data.customDomains.every((d) => !d.trim())) {
newErrors.customDomains = t("proxy.errorHostnameRequired");
}
} else {
if (!data.serverId) newErrors.serverId = t("proxy.errorRequired");
if (!isHttp && !isSocks5) {
if (!data.remotePort) newErrors.remotePort = t("proxy.errorRequired");
else if (!REGEX.PORT.test(data.remotePort)) newErrors.remotePort = t("proxy.errorInvalidPort");
}
if (!isSocks5) {
if (!data.localIp) newErrors.localIp = t("proxy.errorRequired");
else if (!REGEX.IP_OR_HOSTNAME.test(data.localIp)) newErrors.localIp = t("proxy.errorInvalidIP");
if (isHttp && !data.subdomain && data.customDomains.length === 0) {
newErrors.subdomain = t("proxy.errorSubdomainRequired");
if (!data.localPort) newErrors.localPort = t("proxy.errorRequired");
else if (!REGEX.PORT.test(data.localPort)) newErrors.localPort = t("proxy.errorInvalidPort");
}
if (!isHttp && !isSocks5) {
if (!data.remotePort) newErrors.remotePort = t("proxy.errorRequired");
else if (!REGEX.PORT.test(data.remotePort)) newErrors.remotePort = t("proxy.errorInvalidPort");
}
if (isHttp && !data.subdomain && data.customDomains.length === 0) {
newErrors.subdomain = t("proxy.errorSubdomainRequired");
}
}
setErrors(newErrors);
@@ -194,26 +242,42 @@ export function useProxyForm() {
}
: null;
const payload = {
serverId: formData.serverId,
proxyType: formData.type,
name: formData.name,
localIP: formData.localIp,
localPort: formData.localPort,
remotePort: formData.remotePort,
subdomain: formData.subdomain,
customDomains: formData.customDomains,
transport: {
use_encryption: formData.encryption,
use_compression: formData.compression,
},
plugin,
description: formData.description,
status: "enabled",
};
const isCloudflare = formData.proxyBackend === "cloudflare";
try {
setSubmitting(true);
let tunnelId = "";
if (isCloudflare) {
const res = await apiPost("/api/integrations/ensure-tunnel", { integrationId: formData.integrationId });
if (!res.ok) throw new Error("Failed to resolve Cloudflare tunnel");
const data = await res.json();
tunnelId = data.tunnelId;
}
const payload: Record<string, unknown> = {
proxyType: formData.type,
name: formData.name,
localIP: formData.localIp,
localPort: formData.localPort,
customDomains: formData.customDomains,
subdomain: formData.subdomain,
description: formData.description,
status: "enabled",
};
if (isCloudflare) {
payload.tunnelId = tunnelId;
payload.remotePort = "";
payload.transport = null;
payload.plugin = null;
} else {
payload.serverId = formData.serverId;
payload.remotePort = formData.remotePort;
payload.transport = { use_encryption: formData.encryption, use_compression: formData.compression };
payload.plugin = plugin;
}
if (isEditing) {
await pb.collection("fh_proxies").update(id!, payload);
toast.success("Proxy updated successfully");
@@ -231,17 +295,21 @@ export function useProxyForm() {
const isHttpType = formData.type === "http" || formData.type === "https";
const isSocks5Plugin = formData.pluginEnabled && formData.pluginType === "socks5";
const isCloudflare = formData.proxyBackend === "cloudflare";
return {
isEditing,
formData,
servers,
integrations,
loadingServers,
loadingIntegrations,
loadingProxy,
submitting,
errors,
isHttpType,
isSocks5Plugin,
isCloudflare,
handleChange,
handleSubmit,
navigate,
+9 -3
View File
@@ -5,6 +5,8 @@ import { toast } from "sonner";
export interface Proxy {
id: string;
tunnelId: string;
tunnelType: string; // sourced from th_tunnels.type (e.g. "frp", "cloudflare")
serverId: string;
proxyType: "tcp" | "udp" | "http" | "https";
name?: string;
@@ -58,16 +60,20 @@ export function useProxies() {
: "";
const [result, onlineResult] = await Promise.all([
pb.collection("fh_proxies").getList<Proxy>(page, PER_PAGE, {
pb.collection("fh_proxies").getList(page, PER_PAGE, {
sort: "-created",
expand: "serverId",
expand: "serverId,tunnelId",
filter: searchFilter,
}),
pb.collection("fh_proxies").getList(1, 1, {
filter: 'bootStatus = "online"',
}),
]);
setProxies(result.items);
const items: Proxy[] = result.items.map((item: any) => ({
...item,
tunnelType: item.expand?.tunnelId?.type ?? "",
}));
setProxies(items);
setTotalPages(result.totalPages);
setTotalItems(result.totalItems);
setOnlineCount(onlineResult.totalItems);
@@ -4,7 +4,6 @@ import { Card, Flex, Text, Badge, Grid, Button, Heading, Box, Table, AlertDialog
import { Icon } from "@iconify/react";
import { PageHeader } from "../../components/PageHeader";
import { Loading } from "../../components/Loading";
import pb from "../../lib/pocketbase";
import type { Server } from "../Servers/useServers";
import { toast } from "sonner";
import { motion } from "framer-motion";
@@ -14,7 +13,7 @@ import { LatencyChart } from "../../components/LatencyChart";
import { ServerLogViewer } from "../../components/ServerLogViewer";
import { useTranslation } from "react-i18next";
import { useServerProxies } from "./useServerProxies";
import { apiPost } from "../../lib/api";
import { apiGet, apiPost } from "../../lib/api";
export function ServerDetailPage() {
const { t } = useTranslation();
@@ -47,8 +46,10 @@ export function ServerDetailPage() {
if (!id) return;
try {
if (showLoading) setLoading(true);
const record = await pb.collection("fh_servers").getOne<Server>(id);
setServer(record);
const res = await apiGet(`/api/servers/${id}`);
if (!res.ok) throw new Error(t("server.failedToLoad"));
const data: Server = await res.json();
setServer(data);
} catch (err: any) {
if (err.isAbort) return;
console.error("Failed to load server details:", err);
@@ -102,9 +103,9 @@ export function ServerDetailPage() {
const getStatusColor = (status: string) => {
switch (status) {
case "running":
case "active":
return "green";
case "stopped":
case "inactive":
return "red";
default:
return "gray";
@@ -149,7 +150,7 @@ export function ServerDetailPage() {
<Icon icon="lucide:arrow-left" width="16" height="16" />
{t("server.backToServers")}
</Button>
{server.bootStatus === "running" ? (
{server.bootStatus === "active" ? (
<Button size="2" color="red" variant="soft" onClick={handleStop} disabled={actionLoading}>
{actionLoading ? <Icon icon="lucide:loader-2" className="animate-spin" /> : <Icon icon="lucide:square" width="16" height="16" />}
{t("server.stop")}
@@ -238,25 +239,25 @@ export function ServerDetailPage() {
color={getStatusColor(server.bootStatus)}
variant="soft"
className={`animate-status-appear ${
server.bootStatus === "running"
server.bootStatus === "active"
? "animate-status-pulse"
: server.bootStatus === "stopped"
: server.bootStatus === "inactive"
? "animate-status-fade"
: ""
}`}
>
<span
className={`status-dot ${
server.bootStatus === "running"
server.bootStatus === "active"
? "status-dot-green"
: server.bootStatus === "stopped"
: server.bootStatus === "inactive"
? "status-dot-red"
: "status-dot-gray"
}`}
/>
{server.bootStatus === "running"
{server.bootStatus === "active"
? t("server.running")
: server.bootStatus === "stopped"
: server.bootStatus === "inactive"
? t("server.stopped")
: t("common.status")}
</Badge>
@@ -208,7 +208,7 @@ export function useServerForm() {
await pb.collection("fh_servers").update(id!, payload);
toast.success("Server updated successfully");
} else {
await pb.collection("fh_servers").create({ ...payload, bootStatus: "stopped" });
await pb.collection("fh_servers").create(payload);
toast.success("Server created successfully");
}
navigate("/servers");
+11 -11
View File
@@ -56,9 +56,9 @@ export function ServersView({
const navigate = useNavigate();
const getStatusColor = (status: string) => {
switch (status) {
case "running":
case "active":
return "green";
case "stopped":
case "inactive":
return "red";
default:
return "gray";
@@ -107,7 +107,7 @@ export function ServersView({
value={
<span className="text-[#30A46C]">
<AnimateNumber
value={servers.filter((s) => s.bootStatus === "running").length}
value={servers.filter((s) => s.bootStatus === "active").length}
decimalPlaces={0}
/>
</span>
@@ -126,7 +126,7 @@ export function ServersView({
value={
<span className="text-[#E5484D]">
<AnimateNumber
value={servers.filter((s) => s.bootStatus === "stopped").length}
value={servers.filter((s) => s.bootStatus === "inactive").length}
decimalPlaces={0}
/>
</span>
@@ -314,25 +314,25 @@ export function ServersView({
radius="full"
color={getStatusColor(server.bootStatus)}
className={`animate-status-appear ${
server.bootStatus === "running"
server.bootStatus === "active"
? "animate-status-pulse"
: server.bootStatus === "stopped"
: server.bootStatus === "inactive"
? "animate-status-fade"
: ""
}`}
>
<span
className={`status-dot ${
server.bootStatus === "running"
server.bootStatus === "active"
? "status-dot-green"
: server.bootStatus === "stopped"
: server.bootStatus === "inactive"
? "status-dot-red"
: "status-dot-gray"
}`}
/>
{server.bootStatus === "running"
{server.bootStatus === "active"
? t("server.running")
: server.bootStatus === "stopped"
: server.bootStatus === "inactive"
? t("server.stopped")
: t("common.status")}
</Badge>
@@ -340,7 +340,7 @@ export function ServersView({
<Table.Cell>
<Flex gap="2">
{server.bootStatus === "running" ? (
{server.bootStatus === "active" ? (
<Button
size="1"
variant="soft"