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,

\n

Click on the button below to confirm your new email address.

\n

\n Confirm new email\n

\n

If you didn't ask to change your email address, you can ignore this email.

\n

\n Thanks,
\n {APP_NAME} team\n

", "subject": "Confirm your {APP_NAME} new email address" }, - "createRule": "", + "createRule": "@collection.fh_settings.initialized = false", "deleteRule": "id = @request.auth.id", "emailChangeToken": { "duration": 1800 @@ -794,8 +794,8 @@ func init() { "viewRule": "id = @request.auth.id" }, { - "createRule": "", - "deleteRule": "", + "createRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", "fields": [ { "autogeneratePattern": "[a-z0-9]{15}", @@ -985,16 +985,16 @@ func init() { "CREATE INDEX ` + "`" + `idx_Xk5mWLcPl1` + "`" + ` ON ` + "`" + `fh_proxies` + "`" + ` (` + "`" + `proxyType` + "`" + `)", "CREATE INDEX ` + "`" + `idx_4azMuuySpx` + "`" + ` ON ` + "`" + `fh_proxies` + "`" + ` (` + "`" + `status` + "`" + `)" ], - "listRule": "", + "listRule": "@request.auth.id != ''", "name": "fh_proxies", "system": false, "type": "base", - "updateRule": "", - "viewRule": "" + "updateRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''" }, { - "createRule": "", - "deleteRule": "", + "createRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", "fields": [ { "autogeneratePattern": "[a-z0-9]{15}", @@ -1188,12 +1188,12 @@ func init() { "indexes": [ "CREATE INDEX ` + "`" + `idx_wNtroMytle` + "`" + ` ON ` + "`" + `fh_servers` + "`" + ` (` + "`" + `bootStatus` + "`" + `)" ], - "listRule": "", + "listRule": "@request.auth.id != ''", "name": "fh_servers", "system": false, "type": "base", - "updateRule": "", - "viewRule": "" + "updateRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''" }, { "createRule": null, @@ -1272,8 +1272,8 @@ func init() { "viewRule": null }, { - "createRule": "", - "deleteRule": "", + "createRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", "fields": [ { "autogeneratePattern": "[a-z0-9]{15}", @@ -1331,12 +1331,12 @@ func init() { ], "id": "pbc_3433790316", "indexes": [], - "listRule": "", + "listRule": "@request.auth.id != ''", "name": "fh_settings", "system": false, "type": "base", - "updateRule": "", - "viewRule": "" + "updateRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''" } ]` diff --git a/migrations/1772508315_updated_fh_servers.go b/migrations/1772508315_updated_fh_servers.go new file mode 100644 index 0000000..d28192a --- /dev/null +++ b/migrations/1772508315_updated_fh_servers.go @@ -0,0 +1,40 @@ +package migrations + +import ( + "encoding/json" + + "github.com/pocketbase/pocketbase/core" + m "github.com/pocketbase/pocketbase/migrations" +) + +func init() { + m.Register(func(app core.App) error { + collection, err := app.FindCollectionByNameOrId("pbc_3738798621") + if err != nil { + return err + } + + // update collection data + if err := json.Unmarshal([]byte(`{ + "listRule": null + }`), &collection); err != nil { + return err + } + + return app.Save(collection) + }, func(app core.App) error { + collection, err := app.FindCollectionByNameOrId("pbc_3738798621") + if err != nil { + return err + } + + // update collection data + if err := json.Unmarshal([]byte(`{ + "listRule": "@request.auth.id != ''" + }`), &collection); err != nil { + return err + } + + return app.Save(collection) + }) +} diff --git a/migrations/1772508333_updated_fh_servers.go b/migrations/1772508333_updated_fh_servers.go new file mode 100644 index 0000000..e0c717a --- /dev/null +++ b/migrations/1772508333_updated_fh_servers.go @@ -0,0 +1,40 @@ +package migrations + +import ( + "encoding/json" + + "github.com/pocketbase/pocketbase/core" + m "github.com/pocketbase/pocketbase/migrations" +) + +func init() { + m.Register(func(app core.App) error { + collection, err := app.FindCollectionByNameOrId("pbc_3738798621") + if err != nil { + return err + } + + // update collection data + if err := json.Unmarshal([]byte(`{ + "listRule": "" + }`), &collection); err != nil { + return err + } + + return app.Save(collection) + }, func(app core.App) error { + collection, err := app.FindCollectionByNameOrId("pbc_3738798621") + if err != nil { + return err + } + + // update collection data + if err := json.Unmarshal([]byte(`{ + "listRule": null + }`), &collection); err != nil { + return err + } + + return app.Save(collection) + }) +} diff --git a/migrations/1772508338_updated_fh_servers.go b/migrations/1772508338_updated_fh_servers.go new file mode 100644 index 0000000..092c346 --- /dev/null +++ b/migrations/1772508338_updated_fh_servers.go @@ -0,0 +1,40 @@ +package migrations + +import ( + "encoding/json" + + "github.com/pocketbase/pocketbase/core" + m "github.com/pocketbase/pocketbase/migrations" +) + +func init() { + m.Register(func(app core.App) error { + collection, err := app.FindCollectionByNameOrId("pbc_3738798621") + if err != nil { + return err + } + + // update collection data + if err := json.Unmarshal([]byte(`{ + "listRule": "@request.auth.id != ''" + }`), &collection); err != nil { + return err + } + + return app.Save(collection) + }, func(app core.App) error { + collection, err := app.FindCollectionByNameOrId("pbc_3738798621") + if err != nil { + return err + } + + // update collection data + if err := json.Unmarshal([]byte(`{ + "listRule": "" + }`), &collection); err != nil { + return err + } + + return app.Save(collection) + }) +} diff --git a/site/src/lib/api.ts b/site/src/lib/api.ts new file mode 100644 index 0000000..2059839 --- /dev/null +++ b/site/src/lib/api.ts @@ -0,0 +1,35 @@ +import pb from "./pocketbase"; + +function authHeaders(extra?: HeadersInit): HeadersInit { + return { + Authorization: `Bearer ${pb.authStore.token}`, + ...extra, + }; +} + +export function apiFetch(url: string, init: RequestInit = {}): Promise { + return fetch(url, { + ...init, + headers: authHeaders(init.headers as HeadersInit), + }); +} + +export function apiGet(url: string): Promise { + return apiFetch(url); +} + +export function apiPost(url: string, body: unknown): Promise { + return apiFetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +export function apiPut(url: string, body: unknown): Promise { + return apiFetch(url, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} diff --git a/site/src/pages/Dashboard/useDashboard.ts b/site/src/pages/Dashboard/useDashboard.ts index b13add3..f8171bf 100644 --- a/site/src/pages/Dashboard/useDashboard.ts +++ b/site/src/pages/Dashboard/useDashboard.ts @@ -1,4 +1,5 @@ import { useState, useEffect } from "react"; +import { apiGet } from "../../lib/api"; export interface DashboardStats { totalProxies: number; @@ -78,7 +79,7 @@ export function useDashboard() { const loadDashboard = async () => { try { // Fetch dashboard stats from API - const response = await fetch(`/api/dashboard/stats`, {}); + const response = await apiGet(`/api/dashboard/stats`); if (!response.ok) { throw new Error("Failed to fetch dashboard stats"); @@ -103,7 +104,7 @@ export function useDashboard() { // Fetch topology from API try { - const topoResponse = await fetch(`/api/dashboard/topology`); + const topoResponse = await apiGet(`/api/dashboard/topology`); if (topoResponse.ok) { const topoData = await topoResponse.json(); setTopology(topoData); @@ -114,7 +115,7 @@ export function useDashboard() { // Fetch traffic history from API try { - const historyResponse = await fetch(`/api/dashboard/traffic-history?hours=24`); + const historyResponse = await apiGet(`/api/dashboard/traffic-history?hours=24`); if (historyResponse.ok) { const historyData = await historyResponse.json(); setTrafficHistory(historyData); diff --git a/site/src/pages/Import/useImport.ts b/site/src/pages/Import/useImport.ts index 58d37ee..625f102 100644 --- a/site/src/pages/Import/useImport.ts +++ b/site/src/pages/Import/useImport.ts @@ -1,6 +1,7 @@ import { useState, useCallback } from "react"; import { toast } from "sonner"; import { useTranslation } from "react-i18next"; +import { apiPost } from "../../lib/api"; export interface ImportServerInfo { name: string; @@ -84,11 +85,7 @@ export function useImport() { setParsing(true); setParseError(null); try { - const res = await fetch("/api/import/preview", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ tomlContent }), - }); + const res = await apiPost("/api/import/preview", { tomlContent }); const data = await res.json(); if (!res.ok) { setParseError(data.error || t("import.errorParseFailed")); @@ -129,16 +126,12 @@ export function useImport() { if (!preview) return; setImporting(true); try { - const res = await fetch("/api/import/execute", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - tomlContent, - serverName, - importServer, - overwriteServer, - proxies: proxySelections, - }), + const res = await apiPost("/api/import/execute", { + tomlContent, + serverName, + importServer, + overwriteServer, + proxies: proxySelections, }); const data = await res.json(); if (!res.ok) { diff --git a/site/src/pages/ServerDetail/ServerDetailPage.view.tsx b/site/src/pages/ServerDetail/ServerDetailPage.view.tsx index 0239c21..6ddbc76 100644 --- a/site/src/pages/ServerDetail/ServerDetailPage.view.tsx +++ b/site/src/pages/ServerDetail/ServerDetailPage.view.tsx @@ -54,7 +54,8 @@ export function ServerDetailPage() { useEffect(() => { if (!id) return; - const es = new EventSource(`/api/frpc/logs/stream?id=${id}`); + const token = pb.authStore.token; + const es = new EventSource(`/api/frpc/logs/stream?id=${id}&token=${token}`); es.onmessage = (event) => { setLogs((prev) => [...prev, event.data]); diff --git a/site/src/pages/Servers/useServers.ts b/site/src/pages/Servers/useServers.ts index 7c69ea5..f6eb9f0 100644 --- a/site/src/pages/Servers/useServers.ts +++ b/site/src/pages/Servers/useServers.ts @@ -1,5 +1,6 @@ import { useState, useEffect, useCallback } from "react"; import pb from "../../lib/pocketbase"; +import { apiPost } from "../../lib/api"; import { toast } from "sonner"; export interface Server { @@ -268,13 +269,7 @@ export function useServers() { const launchServer = async (id: string) => { console.log("launching server", id); - const response = await fetch("/api/frpc/launch", { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ id }), - }); + const response = await apiPost("/api/frpc/launch", { id }); if (response.ok) { await fetchServers(); toast.success("Server launched successfully"); @@ -283,13 +278,7 @@ export function useServers() { const terminateServer = async (id: string) => { console.log("terminating server", id); - const response = await fetch("/api/frpc/terminate", { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ id }), - }); + const response = await apiPost("/api/frpc/terminate", { id }); if (response.ok) { await fetchServers(); toast.success("Server launched successfully"); diff --git a/site/src/pages/Settings/ChangePasswordDialog.tsx b/site/src/pages/Settings/ChangePasswordDialog.tsx index 7e82a3a..4bc0765 100644 --- a/site/src/pages/Settings/ChangePasswordDialog.tsx +++ b/site/src/pages/Settings/ChangePasswordDialog.tsx @@ -50,15 +50,21 @@ export function ChangePasswordDialog({ const userEmail = pb.authStore.record.email; const collectionName = pb.authStore.record.collectionName || "fh_users"; - console.log("Updating password for user:", pb.authStore.record.id); - console.log("Collection:", collectionName); + if (import.meta.env.DEV) { + console.log("Updating password for user:", pb.authStore.record.id); + console.log("Collection:", collectionName); + } // First, verify the old password by attempting to re-authenticate try { await pb.collection(collectionName).authWithPassword(userEmail, oldPassword); - console.log("Old password verified successfully"); + if (import.meta.env.DEV) { + console.log("Old password verified successfully"); + } } catch (authErr: any) { - console.error("Old password verification failed:", authErr); + if (import.meta.env.DEV) { + console.error("Old password verification failed:", authErr); + } setError(t("settings.incorrectPassword")); setLoading(false); return; @@ -82,7 +88,9 @@ export function ChangePasswordDialog({ pb.authStore.clear(); navigate("/login", { replace: true }); } catch (err: any) { - console.error("Password update error:", err); + if (import.meta.env.DEV) { + console.error("Password update error:", err); + } // Handle PocketBase validation errors if (err.response?.data) { diff --git a/site/src/pages/Settings/GeneralSettings.tsx b/site/src/pages/Settings/GeneralSettings.tsx index a2fdc53..9eab151 100644 --- a/site/src/pages/Settings/GeneralSettings.tsx +++ b/site/src/pages/Settings/GeneralSettings.tsx @@ -1,4 +1,5 @@ import { useState, useEffect } from "react"; +import { apiGet, apiPut } from "../../lib/api"; import { Box, Flex, Heading, Text, Separator, TextField, Button } from "@radix-ui/themes"; import { Icon } from "@iconify/react"; import { FormItem } from "../../components/FormItem"; @@ -25,7 +26,7 @@ export function GeneralSettings() { useEffect(() => { const loadSettings = async () => { try { - const response = await fetch("/api/system/settings"); + const response = await apiGet("/api/system/settings"); if (response.ok) { const data = await response.json(); if (data.general) { @@ -48,15 +49,7 @@ export function GeneralSettings() { const handleSave = async () => { setSaving(true); try { - const response = await fetch("/api/system/settings", { - method: "PUT", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ - general: settings, - }), - }); + const response = await apiPut("/api/system/settings", { general: settings }); if (!response.ok) { throw new Error("Failed to save settings"); diff --git a/site/src/pages/Version/useVersion.ts b/site/src/pages/Version/useVersion.ts index 7d4eca5..590b5e3 100644 --- a/site/src/pages/Version/useVersion.ts +++ b/site/src/pages/Version/useVersion.ts @@ -1,4 +1,5 @@ import { useState, useEffect } from "react"; +import { apiGet } from "../../lib/api"; export interface GithubRelease { tag_name: string; @@ -17,7 +18,7 @@ export function useVersion() { async function fetchReleases() { try { setLoading(true); - const response = await fetch("/api/github/frp/releases"); + const response = await apiGet("/api/github/frp/releases"); if (!response.ok) { throw new Error("Failed to fetch releases"); } diff --git a/site/src/stores/systemStore.ts b/site/src/stores/systemStore.ts index 30dce77..fc399ef 100644 --- a/site/src/stores/systemStore.ts +++ b/site/src/stores/systemStore.ts @@ -1,5 +1,6 @@ import { create } from "zustand"; import { persist } from "zustand/middleware"; +import { apiGet } from "../lib/api"; interface SystemSettings { initialized: boolean; @@ -47,7 +48,7 @@ export const useSystemStore = create()( getSettings: async () => { set({ isLoading: true, error: null }); try { - const response = await fetch("/api/system/settings"); + const response = await apiGet("/api/system/settings"); const data = await response.json(); if (!response.ok) {