diff --git a/internal/application/frpc/service.go b/internal/application/frpc/service.go index 65abb90..f10c443 100644 --- a/internal/application/frpc/service.go +++ b/internal/application/frpc/service.go @@ -4,12 +4,15 @@ import ( "bufio" "context" "encoding/json" + "errors" "fmt" "io" "net/http" "os" "os/signal" "path/filepath" + "regexp" + "sync" "syscall" "time" @@ -23,7 +26,10 @@ import ( "github.com/pocketbase/pocketbase/core" ) +var validServerID = regexp.MustCompile(`^[a-z0-9]{15}$`) + type Service struct { + mu sync.RWMutex app core.App processes map[string]*client.Service statusMonitors map[string]context.CancelFunc @@ -42,6 +48,9 @@ func NewService(app core.App, serverRepo serverdomain.Repository, proxyRepo prox } func (fs *Service) genCommonCfgs(id *string) (*v1.ClientCommonConfig, error) { + if !validServerID.MatchString(*id) { + return nil, errors.New("invalid server id") + } cfg := &v1.ClientCommonConfig{} record, err := fs.app.FindRecordById("fh_servers", *id) @@ -52,7 +61,7 @@ func (fs *Service) genCommonCfgs(id *string) (*v1.ClientCommonConfig, error) { cfg.ServerAddr = record.GetString("serverAddr") cfg.ServerPort = record.GetInt("serverPort") - logDirPath, _ := filepath.Abs("pb_data/frpc/" + *id + "/") + logDirPath := filepath.Join("pb_data", "frpc", *id) if err := os.MkdirAll(logDirPath, 0755); err != nil { return nil, err } @@ -93,7 +102,7 @@ func (fs *Service) genCommonCfgs(id *string) (*v1.ClientCommonConfig, error) { tlsKeyFile := filepath.Join(mainPath, "certs", "key.pem") tlsTrustedCaFile := filepath.Join(mainPath, "certs", "ca.pem") - if err := os.MkdirAll(filepath.Dir(tlsCertFile), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(tlsCertFile), 0700); err != nil { return nil, err } if err := os.WriteFile(tlsCertFile, []byte(cfg.Transport.TLS.CertFile), 0644); err != nil { @@ -201,7 +210,7 @@ func (fs *Service) LaunchFrpc(serverId *string) error { return err } - fs.app.Logger().Debug("Config", "cfg", cfg, "proxyCfgs", proxyCfgs) + fs.app.Logger().Debug("Config", "serverAddr", cfg.ServerAddr, "serverPort", cfg.ServerPort, "proxyCount", len(proxyCfgs)) cfg.Complete() log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor) @@ -218,13 +227,14 @@ func (fs *Service) LaunchFrpc(serverId *string) error { if shouldGracefulClose { go handleTermSignal(svr) } + ctx, cancel := context.WithCancel(context.Background()) + fs.mu.Lock() fs.processes[*serverId] = svr + fs.statusMonitors[*serverId] = cancel + fs.mu.Unlock() fs.serverRepo.UpdateBootStatus(*serverId, serverdomain.ServerStatusRunning) - ctx, cancel := context.WithCancel(context.Background()) - fs.statusMonitors[*serverId] = cancel - done := make(chan error, 1) go func() { @@ -289,8 +299,10 @@ func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx con func (fs *Service) destroying(id *string) { fs.serverRepo.UpdateBootStatus(*id, serverdomain.ServerStatusStopped) fs.proxyRepo.UpdateBootStatusByServerID(*id, proxydomain.ProxyBootStatusOffline) + fs.mu.Lock() delete(fs.processes, *id) delete(fs.statusMonitors, *id) + fs.mu.Unlock() } // monitorProxyStatus monitors proxy status from frp and updates the database. @@ -341,7 +353,9 @@ func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx func (fs *Service) TerminateFrpc(id *string) error { fs.app.Logger().Info("Stop frpc", "id", *id) + fs.mu.RLock() cancel, exists := fs.statusMonitors[*id] + fs.mu.RUnlock() if !exists { return nil } @@ -353,13 +367,17 @@ func (fs *Service) TerminateFrpc(id *string) error { } func (fs *Service) getFrpMainPath(id *string) string { - logDirPath, _ := filepath.Abs("pb_data/frpc/" + *id + "/") - return logDirPath + return filepath.Join("pb_data", "frpc", *id) } // StreamLog streams the frpc log file via SSE. // It sends the last 50 lines as initial content, then tails new lines every 500ms. func (fs *Service) StreamLog(serverId string, ctx context.Context, w http.ResponseWriter, flusher http.Flusher) { + if !validServerID.MatchString(serverId) { + fmt.Fprintf(w, "data: [invalid server id]\n\n") + flusher.Flush() + return + } mainPath := fs.getFrpMainPath(&serverId) logPath := filepath.Join(mainPath, "logs", "frpc.log") @@ -434,7 +452,9 @@ func (fs *Service) ReloadFrpc(serverId *string) error { return err } + fs.mu.RLock() svr := fs.processes[*serverId] + fs.mu.RUnlock() // TODO 2026-02-08 reload visitorCfgs svr.UpdateAllConfigurer(proxyCfgs, nil) @@ -443,7 +463,9 @@ func (fs *Service) ReloadFrpc(serverId *string) error { // IsServerRunning checks if a server is currently running. func (fs *Service) IsServerRunning(serverId string) bool { + fs.mu.RLock() _, exists := fs.processes[serverId] + fs.mu.RUnlock() return exists } diff --git a/internal/interfaces/http/dashboard_handler.go b/internal/interfaces/http/dashboard_handler.go index f2a58b3..23fc1c8 100644 --- a/internal/interfaces/http/dashboard_handler.go +++ b/internal/interfaces/http/dashboard_handler.go @@ -27,15 +27,15 @@ func NewDashboardHandler(dashboardService *dashboard.Service) *DashboardHandler } func (dh *DashboardHandler) RegisterHandlers(e *core.ServeEvent) { - e.Router.GET("/api/dashboard/topology", func(e *core.RequestEvent) error { + e.Router.GET("/api/dashboard/topology", requireAuth(func(e *core.RequestEvent) error { data, err := dh.dashboardService.GetTopology() if err != nil { return e.JSON(500, response.Error(err)) } return e.JSON(200, data) - }) + })) - e.Router.GET("/api/dashboard/stats", func(e *core.RequestEvent) error { + e.Router.GET("/api/dashboard/stats", requireAuth(func(e *core.RequestEvent) error { stats, err := dh.dashboardService.GetStats() if err != nil { return e.JSON(500, response.Error(err)) @@ -50,5 +50,5 @@ func (dh *DashboardHandler) RegisterHandlers(e *core.ServeEvent) { ProxyTypeCounts: stats.ProxyTypeCounts, UptimeSeconds: stats.UptimeSeconds, }) - }) + })) } diff --git a/internal/interfaces/http/frpc_handler.go b/internal/interfaces/http/frpc_handler.go index 1eada48..8f73b25 100644 --- a/internal/interfaces/http/frpc_handler.go +++ b/internal/interfaces/http/frpc_handler.go @@ -20,7 +20,7 @@ func NewFrpcHandler(app core.App, service *frpc.Service) *FrpcHandler { } func (h *FrpcHandler) RegisterHandlers(e *core.ServeEvent) { - e.Router.POST("/api/frpc/launch", func(e *core.RequestEvent) error { + e.Router.POST("/api/frpc/launch", requireAuth(func(e *core.RequestEvent) error { data := struct { ID string `json:"id"` }{} @@ -31,18 +31,24 @@ func (h *FrpcHandler) RegisterHandlers(e *core.ServeEvent) { 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", func(e *core.RequestEvent) error { + 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") @@ -56,9 +62,9 @@ func (h *FrpcHandler) RegisterHandlers(e *core.ServeEvent) { h.service.StreamLog(id, e.Request.Context(), w, flusher) return nil - }) + }, h.app)) - e.Router.POST("/api/frpc/terminate", func(e *core.RequestEvent) error { + e.Router.POST("/api/frpc/terminate", requireAuth(func(e *core.RequestEvent) error { data := struct { ID string `json:"id"` }{} @@ -69,10 +75,13 @@ func (h *FrpcHandler) RegisterHandlers(e *core.ServeEvent) { 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"}) - }) + })) } diff --git a/internal/interfaces/http/github_handler.go b/internal/interfaces/http/github_handler.go index fcdf9d4..8f06136 100644 --- a/internal/interfaces/http/github_handler.go +++ b/internal/interfaces/http/github_handler.go @@ -19,11 +19,11 @@ func NewGithubHandler(app core.App, service *github.Service) *GithubHandler { } func (h *GithubHandler) RegisterHandlers(e *core.ServeEvent) { - e.Router.GET("/api/github/frp/releases", func(e *core.RequestEvent) error { + e.Router.GET("/api/github/frp/releases", requireAuth(func(e *core.RequestEvent) error { releases, err := h.service.GetFrpReleases() if err != nil { return e.JSON(500, map[string]string{"error": err.Error()}) } return e.JSON(200, releases) - }) + })) } diff --git a/internal/interfaces/http/import_handler.go b/internal/interfaces/http/import_handler.go index 776f6a9..07bb422 100644 --- a/internal/interfaces/http/import_handler.go +++ b/internal/interfaces/http/import_handler.go @@ -18,7 +18,7 @@ func NewImportHandler(app core.App, service *importer.Service) *ImportHandler { func (h *ImportHandler) RegisterHandlers(e *core.ServeEvent) { // Preview: parse TOML content and return server/proxy info with duplicate flags - e.Router.POST("/api/import/preview", func(e *core.RequestEvent) error { + e.Router.POST("/api/import/preview", requireAuth(func(e *core.RequestEvent) error { var req importer.ParseTomlRequest if err := e.BindBody(&req); err != nil { return e.JSON(http.StatusBadRequest, map[string]interface{}{ @@ -39,10 +39,10 @@ func (h *ImportHandler) RegisterHandlers(e *core.ServeEvent) { } return e.JSON(http.StatusOK, preview) - }) + })) // Execute: import servers and proxies within a transaction - e.Router.POST("/api/import/execute", func(e *core.RequestEvent) error { + e.Router.POST("/api/import/execute", requireAuth(func(e *core.RequestEvent) error { var req importer.ExecuteImportRequest if err := e.BindBody(&req); err != nil { return e.JSON(http.StatusBadRequest, map[string]interface{}{ @@ -66,5 +66,5 @@ func (h *ImportHandler) RegisterHandlers(e *core.ServeEvent) { "message": "import successful", "result": result, }) - }) + })) } diff --git a/internal/interfaces/http/middleware.go b/internal/interfaces/http/middleware.go new file mode 100644 index 0000000..2af1aeb --- /dev/null +++ b/internal/interfaces/http/middleware.go @@ -0,0 +1,28 @@ +package httphandler + +import ( + "net/http" + "regexp" + + "github.com/pocketbase/pocketbase/core" +) + +var validID = regexp.MustCompile(`^[a-z0-9]{15}$`) + +// requireAuth wraps a handler with authentication check. +// Pass an optional core.App to also accept a ?token= query param (needed for EventSource/SSE). +func requireAuth(next func(*core.RequestEvent) error, apps ...core.App) func(*core.RequestEvent) error { + return func(e *core.RequestEvent) error { + if e.Auth == nil && len(apps) > 0 { + if token := e.Request.URL.Query().Get("token"); token != "" { + if record, err := apps[0].FindAuthRecordByToken(token, core.TokenTypeAuth); err == nil { + e.Auth = record + } + } + } + if e.Auth == nil { + return e.JSON(http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) + } + return next(e) + } +} diff --git a/internal/interfaces/http/system_handler.go b/internal/interfaces/http/system_handler.go index e3b886e..14212ff 100644 --- a/internal/interfaces/http/system_handler.go +++ b/internal/interfaces/http/system_handler.go @@ -33,7 +33,7 @@ func (h *SystemHandler) RegisterHandlers(e *core.ServeEvent) { }) }) - e.Router.GET("/api/system/settings", func(e *core.RequestEvent) error { + e.Router.GET("/api/system/settings", requireAuth(func(e *core.RequestEvent) error { settings, err := h.service.GetSettings() if err != nil { return e.JSON(http.StatusInternalServerError, map[string]interface{}{ @@ -42,10 +42,10 @@ func (h *SystemHandler) RegisterHandlers(e *core.ServeEvent) { } return e.JSON(http.StatusOK, settings) - }) + })) // Update system settings - e.Router.PUT("/api/system/settings", func(e *core.RequestEvent) error { + e.Router.PUT("/api/system/settings", requireAuth(func(e *core.RequestEvent) error { var req system.UpdateSettingsRequest if err := e.BindBody(&req); err != nil { return e.JSON(http.StatusBadRequest, map[string]interface{}{ @@ -62,15 +62,15 @@ func (h *SystemHandler) RegisterHandlers(e *core.ServeEvent) { return e.JSON(http.StatusOK, map[string]interface{}{ "message": "Settings updated successfully", }) - }) + })) - e.Router.GET("/api/system/version", func(e *core.RequestEvent) error { + e.Router.GET("/api/system/version", requireAuth(func(e *core.RequestEvent) error { return e.JSON(http.StatusOK, map[string]string{ "version": h.service.GetAppVersion(), }) - }) + })) - e.Router.GET("/api/system/latest-version", func(e *core.RequestEvent) error { + e.Router.GET("/api/system/latest-version", requireAuth(func(e *core.RequestEvent) error { latest, err := h.service.GetLatestVersion() if err != nil { return e.JSON(http.StatusInternalServerError, map[string]interface{}{ @@ -78,10 +78,23 @@ func (h *SystemHandler) RegisterHandlers(e *core.ServeEvent) { }) } return e.JSON(http.StatusOK, latest) - }) + })) - // Initialize system (create admin user and settings) + // Initialize system (create admin user and settings). + // Rejected if the system is already initialized to prevent unauthorized reset. e.Router.POST("/api/system/initialize", func(e *core.RequestEvent) error { + initialized, err := h.service.CheckInitialized() + if err != nil { + return e.JSON(http.StatusInternalServerError, map[string]interface{}{ + "error": err.Error(), + }) + } + if initialized { + return e.JSON(http.StatusForbidden, map[string]interface{}{ + "error": "system already initialized", + }) + } + var req system.InitializeRequest if err := e.BindBody(&req); err != nil { return e.JSON(http.StatusBadRequest, map[string]interface{}{ diff --git a/internal/interfaces/http/version_handler.go b/internal/interfaces/http/version_handler.go index 42bbdf4..a8520a6 100644 --- a/internal/interfaces/http/version_handler.go +++ b/internal/interfaces/http/version_handler.go @@ -19,9 +19,9 @@ func NewVersionHandler(app core.App, service *version.Service) *VersionHandler { } func (h *VersionHandler) RegisterHandlers(e *core.ServeEvent) { - e.Router.GET("/api/frp/version", func(e *core.RequestEvent) error { + e.Router.GET("/api/frp/version", requireAuth(func(e *core.RequestEvent) error { return e.JSON(200, map[string]string{ "frp": h.service.GetFrpVersion(), }) - }) + })) } diff --git a/migrations/1772260919_collections_snapshot.go b/migrations/1772506021_collections_snapshot.go similarity index 97% rename from migrations/1772260919_collections_snapshot.go rename to migrations/1772506021_collections_snapshot.go index 15529cf..77e4860 100644 --- a/migrations/1772260919_collections_snapshot.go +++ b/migrations/1772506021_collections_snapshot.go @@ -592,7 +592,7 @@ func init() { "body": "
Hello,
\nClick on the button below to confirm your new email address.
\n\n Confirm new email\n
\nIf you didn't ask to change your email address, you can ignore this email.
\n\n Thanks,
\n {APP_NAME} team\n