From d7076400b18649810ec9a008a3b8bc349902ce86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=98=89=E4=BC=9F?= <8473136@qq.com> Date: Tue, 31 Mar 2026 14:26:00 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20Cloudflare=20tunnel=20support.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/application/dashboard/service.go | 47 ++++-- .../integration/cloudflare_service.go | 116 +++++++++++++ .../integration/cloudflare_tunnel.go | 147 ++++++++++++++++ internal/application/integration/service.go | 95 +++++++++++ internal/domain/proxy/model.go | 1 + internal/hooks/hooks.go | 14 ++ internal/hooks/integration_hooks.go | 60 +++++++ internal/hooks/proxy_hooks.go | 159 ++++++++++++++++++ .../persistence/proxy_repository.go | 94 ++++++++--- .../persistence/server_repository.go | 64 ------- .../persistence/tunnel_repository.go | 60 +++++++ internal/interfaces/http/frpc_handler.go | 112 ------------ .../interfaces/http/integration_handler.go | 120 +++++++++++++ internal/interfaces/http/server_handler.go | 65 ++++++- internal/interfaces/http/tunnel_handler.go | 106 ++++++++++++ main.go | 47 +++--- site/src/assets/frp.svg | 1 + site/src/locales/en.json | 1 + site/src/locales/zh.json | 1 + site/src/pages/Dashboard/TopologyChart.tsx | 4 +- site/src/pages/Proxies/ProxiesPage.view.tsx | 14 +- .../ProxyFormPage/ProxyFormPage.view.tsx | 2 +- .../Proxies/ProxyFormPage/useProxyForm.ts | 64 ++++--- site/src/pages/Proxies/useProxies.ts | 14 +- .../ServerDetail/ServerDetailPage.view.tsx | 27 +-- .../Servers/ServerFormPage/useServerForm.ts | 2 +- site/src/pages/Servers/ServersPage.view.tsx | 22 +-- 27 files changed, 1162 insertions(+), 297 deletions(-) create mode 100644 internal/application/integration/cloudflare_service.go create mode 100644 internal/application/integration/cloudflare_tunnel.go create mode 100644 internal/application/integration/service.go create mode 100644 internal/hooks/hooks.go create mode 100644 internal/hooks/integration_hooks.go create mode 100644 internal/hooks/proxy_hooks.go create mode 100644 internal/infrastructure/persistence/tunnel_repository.go delete mode 100644 internal/interfaces/http/frpc_handler.go create mode 100644 internal/interfaces/http/integration_handler.go create mode 100644 internal/interfaces/http/tunnel_handler.go create mode 100644 site/src/assets/frp.svg diff --git a/internal/application/dashboard/service.go b/internal/application/dashboard/service.go index f511d77..41b4802 100644 --- a/internal/application/dashboard/service.go +++ b/internal/application/dashboard/service.go @@ -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 { diff --git a/internal/application/integration/cloudflare_service.go b/internal/application/integration/cloudflare_service.go new file mode 100644 index 0000000..8169d88 --- /dev/null +++ b/internal/application/integration/cloudflare_service.go @@ -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) +} diff --git a/internal/application/integration/cloudflare_tunnel.go b/internal/application/integration/cloudflare_tunnel.go new file mode 100644 index 0000000..761369d --- /dev/null +++ b/internal/application/integration/cloudflare_tunnel.go @@ -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 +} diff --git a/internal/application/integration/service.go b/internal/application/integration/service.go new file mode 100644 index 0000000..4f2c294 --- /dev/null +++ b/internal/application/integration/service.go @@ -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 +} diff --git a/internal/domain/proxy/model.go b/internal/domain/proxy/model.go index 7e3b2fb..828e876 100644 --- a/internal/domain/proxy/model.go +++ b/internal/domain/proxy/model.go @@ -5,6 +5,7 @@ import "podux/pkg/types" // 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"` diff --git a/internal/hooks/hooks.go b/internal/hooks/hooks.go new file mode 100644 index 0000000..29d863a --- /dev/null +++ b/internal/hooks/hooks.go @@ -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) +} diff --git a/internal/hooks/integration_hooks.go b/internal/hooks/integration_hooks.go new file mode 100644 index 0000000..765ca2e --- /dev/null +++ b/internal/hooks/integration_hooks.go @@ -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() + }) +} diff --git a/internal/hooks/proxy_hooks.go b/internal/hooks/proxy_hooks.go new file mode 100644 index 0000000..3ce8504 --- /dev/null +++ b/internal/hooks/proxy_hooks.go @@ -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() + }) +} diff --git a/internal/infrastructure/persistence/proxy_repository.go b/internal/infrastructure/persistence/proxy_repository.go index 3fcc27f..ca08fa0 100644 --- a/internal/infrastructure/persistence/proxy_repository.go +++ b/internal/infrastructure/persistence/proxy_repository.go @@ -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 } - diff --git a/internal/infrastructure/persistence/server_repository.go b/internal/infrastructure/persistence/server_repository.go index 991348e..5cedcd6 100644 --- a/internal/infrastructure/persistence/server_repository.go +++ b/internal/infrastructure/persistence/server_repository.go @@ -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 } diff --git a/internal/infrastructure/persistence/tunnel_repository.go b/internal/infrastructure/persistence/tunnel_repository.go new file mode 100644 index 0000000..9cd744a --- /dev/null +++ b/internal/infrastructure/persistence/tunnel_repository.go @@ -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 +} diff --git a/internal/interfaces/http/frpc_handler.go b/internal/interfaces/http/frpc_handler.go deleted file mode 100644 index 53575f2..0000000 --- a/internal/interfaces/http/frpc_handler.go +++ /dev/null @@ -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"}) - })) -} diff --git a/internal/interfaces/http/integration_handler.go b/internal/interfaces/http/integration_handler.go new file mode 100644 index 0000000..8d31d8d --- /dev/null +++ b/internal/interfaces/http/integration_handler.go @@ -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": "" } + // 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": "" } + // Finds or creates a th_tunnels record (type=cloudflare) for the given integration. + // Returns { "tunnelId": "" } 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}) + })) +} diff --git a/internal/interfaces/http/server_handler.go b/internal/interfaces/http/server_handler.go index 563f913..6dbf1ff 100644 --- a/internal/interfaces/http/server_handler.go +++ b/internal/interfaces/http/server_handler.go @@ -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], }) } diff --git a/internal/interfaces/http/tunnel_handler.go b/internal/interfaces/http/tunnel_handler.go new file mode 100644 index 0000000..829f7d5 --- /dev/null +++ b/internal/interfaces/http/tunnel_handler.go @@ -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"}) + })) +} diff --git a/main.go b/main.go index 5ae75d1..81a5617 100644 --- a/main.go +++ b/main.go @@ -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) diff --git a/site/src/assets/frp.svg b/site/src/assets/frp.svg new file mode 100644 index 0000000..5cfa479 --- /dev/null +++ b/site/src/assets/frp.svg @@ -0,0 +1 @@ + diff --git a/site/src/locales/en.json b/site/src/locales/en.json index c3ff283..b194c76 100644 --- a/site/src/locales/en.json +++ b/site/src/locales/en.json @@ -279,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", diff --git a/site/src/locales/zh.json b/site/src/locales/zh.json index f1c516d..17fba7d 100644 --- a/site/src/locales/zh.json +++ b/site/src/locales/zh.json @@ -279,6 +279,7 @@ "addFirstProxy": "将您的本地服务连接到世界。添加您的第一个代理配置以开始使用。", "createYourFirstProxy": "创建您的第一个代理", "server": "服务器", + "tunnel": "协议", "bootStatus": "启动状态", "manageProxies": "管理您的代理配置", "allProxies": "所有代理", diff --git a/site/src/pages/Dashboard/TopologyChart.tsx b/site/src/pages/Dashboard/TopologyChart.tsx index a0d974d..a00ba8e 100644 --- a/site/src/pages/Dashboard/TopologyChart.tsx +++ b/site/src/pages/Dashboard/TopologyChart.tsx @@ -212,7 +212,7 @@ function VisitorNode({ data }: { data: Record }) { // Server Node function ServerNode({ data }: { data: Record }) { 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; diff --git a/site/src/pages/Proxies/ProxiesPage.view.tsx b/site/src/pages/Proxies/ProxiesPage.view.tsx index 22200de..203bb75 100644 --- a/site/src/pages/Proxies/ProxiesPage.view.tsx +++ b/site/src/pages/Proxies/ProxiesPage.view.tsx @@ -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({ {t("common.name")} {t("common.type")} + {t("proxy.tunnel")} {t("proxy.server")} {t("proxy.localIP")} {t("proxy.localPort")} @@ -213,13 +215,21 @@ export function ProxiesView({ {proxy.name || -} - {proxy.type === "cloudflare" ? ( + {proxy.proxyType?.toUpperCase()} + + + {proxy.tunnelType === "cloudflare" ? ( Cloudflare + ) : proxy.tunnelType === "frp" ? ( + + frp + FRP + ) : ( - {proxy.proxyType?.toUpperCase() ?? "FRP"} + - )} diff --git a/site/src/pages/Proxies/ProxyFormPage/ProxyFormPage.view.tsx b/site/src/pages/Proxies/ProxyFormPage/ProxyFormPage.view.tsx index 0f4809d..ee5c7b1 100644 --- a/site/src/pages/Proxies/ProxyFormPage/ProxyFormPage.view.tsx +++ b/site/src/pages/Proxies/ProxyFormPage/ProxyFormPage.view.tsx @@ -229,7 +229,7 @@ export function ProxyFormPageView({ {s.serverName} diff --git a/site/src/pages/Proxies/ProxyFormPage/useProxyForm.ts b/site/src/pages/Proxies/ProxyFormPage/useProxyForm.ts index 9f1cd7d..861a236 100644 --- a/site/src/pages/Proxies/ProxyFormPage/useProxyForm.ts +++ b/site/src/pages/Proxies/ProxyFormPage/useProxyForm.ts @@ -2,7 +2,7 @@ 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"; @@ -122,12 +122,14 @@ export function useProxyForm() { 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 | 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({ - proxyBackend: (record.type as ProxyFormData["proxyBackend"]) || "frp", - serverId: (record.serverId as string) || "", - integrationId: (record.integrationId 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", @@ -242,28 +244,40 @@ export function useProxyForm() { const isCloudflare = formData.proxyBackend === "cloudflare"; - const payload = { - type: formData.proxyBackend, - serverId: isCloudflare ? "" : formData.serverId, - integrationId: isCloudflare ? formData.integrationId : "", - proxyType: formData.type, - name: formData.name, - localIP: isCloudflare ? "" : formData.localIp, - localPort: isCloudflare ? "" : formData.localPort, - remotePort: isCloudflare ? "" : formData.remotePort, - subdomain: formData.subdomain, - customDomains: formData.customDomains, - transport: isCloudflare ? null : { - use_encryption: formData.encryption, - use_compression: formData.compression, - }, - plugin: isCloudflare ? null : plugin, - description: formData.description, - status: "enabled", - }; - 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 = { + 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"); diff --git a/site/src/pages/Proxies/useProxies.ts b/site/src/pages/Proxies/useProxies.ts index e10cef8..79b7209 100644 --- a/site/src/pages/Proxies/useProxies.ts +++ b/site/src/pages/Proxies/useProxies.ts @@ -5,9 +5,9 @@ import { toast } from "sonner"; export interface Proxy { id: string; - type: "frp" | "cloudflare"; + tunnelId: string; + tunnelType: string; // sourced from th_tunnels.type (e.g. "frp", "cloudflare") serverId: string; - integrationId?: string; proxyType: "tcp" | "udp" | "http" | "https"; name?: string; localIP?: string; @@ -60,16 +60,20 @@ export function useProxies() { : ""; const [result, onlineResult] = await Promise.all([ - pb.collection("fh_proxies").getList(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); diff --git a/site/src/pages/ServerDetail/ServerDetailPage.view.tsx b/site/src/pages/ServerDetail/ServerDetailPage.view.tsx index cb50572..ddc4065 100644 --- a/site/src/pages/ServerDetail/ServerDetailPage.view.tsx +++ b/site/src/pages/ServerDetail/ServerDetailPage.view.tsx @@ -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(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() { {t("server.backToServers")} - {server.bootStatus === "running" ? ( + {server.bootStatus === "active" ? (