🚧 Cloudflare tunnel support.

This commit is contained in:
刘嘉伟 committed 2026-03-31 14:26:00 +08:00
1 parent b86b7222cb
commit d7076400b1
27 files changed
+1162 -297

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
}
+1
View File
@@ -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"`
+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)
+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

+1
View File
@@ -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",
+1
View File
@@ -279,6 +279,7 @@
"addFirstProxy": "将您的本地服务连接到世界。添加您的第一个代理配置以开始使用。",
"createYourFirstProxy": "创建您的第一个代理",
"server": "服务器",
"tunnel": "协议",
"bootStatus": "启动状态",
"manageProxies": "管理您的代理配置",
"allProxies": "所有代理",
+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;
+12 -2
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,13 +215,21 @@ export function ProxiesView({
<Text weight="medium">{proxy.name || <Text color="gray">-</Text>}</Text>
</Table.Cell>
<Table.Cell>
{proxy.type === "cloudflare" ? (
<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>
) : (
<Badge variant="surface">{proxy.proxyType?.toUpperCase() ?? "FRP"}</Badge>
<Text color="gray">-</Text>
)}
</Table.Cell>
<Table.Cell>
@@ -229,7 +229,7 @@ export function ProxyFormPageView({
<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)]"
s.bootStatus === "active" ? "bg-[var(--green-9)]" : "bg-[var(--gray-7)]"
}`}
/>
<Text size="2">{s.serverName}</Text>
@@ -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<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({
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<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");
+9 -5
View File
@@ -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<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"