From c0b4c7bb941f0b580e49f813b439d6e3c639e7b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=98=89=E4=BC=9F?= <8473136@qq.com> Date: Sat, 14 Mar 2026 18:42:14 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20support=20frpc=20user=20fie?= =?UTF-8?q?ld=20in=20server=20config=20and=20proxy=20name=20resolution?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add `user` field to fh_servers collection via migration - Set cfg.User from server record; call c.Complete(user) so proxy names get the correct "." prefix when looking up status - Mask sensitive fields (token/password/etc.) in frpc config debug logs - Support user field in TOML importer (parse + execute) - Add user input to server form page and display in server detail page - Add start/stop action buttons on server detail page - Add i18n keys for user field and start/stop feedback toasts Co-Authored-By: Claude Sonnet 4.6 --- internal/application/frpc/service.go | 44 +++++++-- internal/application/importer/service.go | 4 + migrations/1773366854_updated_fh_servers.go | 45 +++++++++ site/src/locales/en.json | 9 +- site/src/locales/zh.json | 9 +- .../ServerDetail/ServerDetailPage.view.tsx | 99 +++++++++++++++---- .../ServerFormPage/ServerFormPage.view.tsx | 9 ++ .../Servers/ServerFormPage/useServerForm.ts | 3 + site/src/pages/Servers/useServers.ts | 1 + 9 files changed, 195 insertions(+), 28 deletions(-) create mode 100644 migrations/1773366854_updated_fh_servers.go diff --git a/internal/application/frpc/service.go b/internal/application/frpc/service.go index bfd7df7..812ecb8 100644 --- a/internal/application/frpc/service.go +++ b/internal/application/frpc/service.go @@ -27,6 +27,7 @@ import ( ) var validServerID = regexp.MustCompile(`^[a-z0-9]{15}$`) +var sensitiveRegex = regexp.MustCompile(`"(?i)(token|password|sk|pwd|secretkey|httpuser|httppwd|oidctoken|oidcclientsecret)":"(?:[^"\\]|\\.)*"`) type Service struct { mu sync.RWMutex @@ -60,6 +61,7 @@ func (fs *Service) genCommonCfgs(id *string) (*v1.ClientCommonConfig, error) { // basic config cfg.ServerAddr = record.GetString("serverAddr") cfg.ServerPort = record.GetInt("serverPort") + cfg.User = record.GetString("user") logDirPath := filepath.Join("pb_data", "frpc", *id) if err := os.MkdirAll(logDirPath, 0755); err != nil { @@ -233,6 +235,19 @@ func (fs *Service) LaunchFrpc(serverId *string) error { fs.app.Logger().Debug("Config", "serverAddr", cfg.ServerAddr, "serverPort", cfg.ServerPort, "proxyCount", len(proxyCfgs)) + for _, c := range proxyCfgs { + c.Complete(cfg.User) + } + + // Print frp configurations in logs with sensitive data masked + commonCfgBytes, _ := json.Marshal(cfg) + proxyCfgsBytes, _ := json.Marshal(proxyCfgs) + + safeCommon := sensitiveRegex.ReplaceAll(commonCfgBytes, []byte(`"${1}":"***"`)) + safeProxies := sensitiveRegex.ReplaceAll(proxyCfgsBytes, []byte(`"${1}":"***"`)) + + fs.app.Logger().Info("FRP Configuration", "common", string(safeCommon), "proxies", string(safeProxies)) + cfg.Complete() log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor) @@ -269,13 +284,13 @@ func (fs *Service) LaunchFrpc(serverId *string) error { done <- err }() - go fs.monitorServiceStatus(serverId, svr, ctx, done) + go fs.monitorServiceStatus(serverId, svr, ctx, done, cfg.User) return nil } // monitorServiceStatus monitors service status and updates the database. -func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx context.Context, done <-chan error) { +func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx context.Context, done <-chan error, user string) { time.Sleep(2 * time.Second) select { @@ -292,7 +307,7 @@ func (fs *Service) monitorServiceStatus(id *string, svr *client.Service, ctx con fs.app.Logger().Info("Service is running", "id", *id) } - go fs.monitorProxyStatus(id, svr, ctx) + go fs.monitorProxyStatus(id, svr, ctx, user) ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() @@ -327,7 +342,7 @@ func (fs *Service) destroying(id *string) { } // monitorProxyStatus monitors proxy status from frp and updates the database. -func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx context.Context) { +func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx context.Context, user string) { fs.app.Logger().Info("Starting proxy status monitoring", "serverId", *serverId) statusExporter := svr.StatusExporter() @@ -348,8 +363,12 @@ func (fs *Service) monitorProxyStatus(serverId *string, svr *client.Service, ctx } for _, proxy := range proxies { - proxyName := proxy.Name + "-" + proxy.Id - status, exists := statusExporter.GetProxyStatus(proxyName) + baseName := proxy.Name + "-" + proxy.Id + prefix := "" + if user != "" { + prefix = user + "." + } + status, exists := statusExporter.GetProxyStatus(prefix + baseName) if exists { var bootStatus proxydomain.ProxyBootStatus @@ -474,6 +493,19 @@ func (fs *Service) ReloadFrpc(serverId *string) error { return err } + server, err := fs.app.FindRecordById("fh_servers", *serverId) + if err != nil { + return err + } + user := server.GetString("user") + for _, c := range proxyCfgs { + c.Complete(user) + } + + proxyCfgsBytes, _ := json.Marshal(proxyCfgs) + safeProxies := sensitiveRegex.ReplaceAll(proxyCfgsBytes, []byte(`"${1}":"***"`)) + fs.app.Logger().Info("FRP Reload Configurations", "proxies", string(safeProxies)) + fs.mu.RLock() svr := fs.processes[*serverId] fs.mu.RUnlock() diff --git a/internal/application/importer/service.go b/internal/application/importer/service.go index 811ad54..d26d9d0 100644 --- a/internal/application/importer/service.go +++ b/internal/application/importer/service.go @@ -14,6 +14,7 @@ import ( type tomlFrpClientConfig struct { ServerAddr string `toml:"serverAddr"` ServerPort int `toml:"serverPort"` + User string `toml:"user"` Auth tomlAuthConfig `toml:"auth"` Log tomlLogConfig `toml:"log"` Transport tomlTransportConfig `toml:"transport"` @@ -67,6 +68,7 @@ type ImportServerInfo struct { Name string `json:"name"` ServerAddr string `json:"serverAddr"` ServerPort int `json:"serverPort"` + User string `json:"user"` Auth map[string]interface{} `json:"auth"` Log map[string]interface{} `json:"log"` Transport map[string]interface{} `json:"transport"` @@ -200,6 +202,7 @@ func (s *Service) ParseToml(req *ParseTomlRequest) (*ImportPreviewResponse, erro Name: fmt.Sprintf("%s:%d", cfg.ServerAddr, serverPort), ServerAddr: cfg.ServerAddr, ServerPort: serverPort, + User: cfg.User, Auth: authMap, Log: logMap, Transport: transportMap, @@ -393,6 +396,7 @@ func (s *Service) handleServerImport( serverRecord.Set("serverName", serverName) serverRecord.Set("serverAddr", cfg.ServerAddr) serverRecord.Set("serverPort", serverPort) + serverRecord.Set("user", cfg.User) serverRecord.Set("serverVersion", "built-in") serverRecord.Set("auth", string(authJSON)) serverRecord.Set("log", string(logJSON)) diff --git a/migrations/1773366854_updated_fh_servers.go b/migrations/1773366854_updated_fh_servers.go new file mode 100644 index 0000000..7485c4a --- /dev/null +++ b/migrations/1773366854_updated_fh_servers.go @@ -0,0 +1,45 @@ +package migrations + +import ( + "github.com/pocketbase/pocketbase/core" + m "github.com/pocketbase/pocketbase/migrations" +) + +func init() { + m.Register(func(app core.App) error { + collection, err := app.FindCollectionByNameOrId("pbc_3738798621") + if err != nil { + return err + } + + // add field + if err := collection.Fields.AddMarshaledJSONAt(14, []byte(`{ + "autogeneratePattern": "", + "hidden": false, + "id": "text2375276105", + "max": 0, + "min": 0, + "name": "user", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }`)); err != nil { + return err + } + + return app.Save(collection) + }, func(app core.App) error { + collection, err := app.FindCollectionByNameOrId("pbc_3738798621") + if err != nil { + return err + } + + // remove field + collection.Fields.RemoveById("text2375276105") + + return app.Save(collection) + }) +} diff --git a/site/src/locales/en.json b/site/src/locales/en.json index e59db33..aac6277 100644 --- a/site/src/locales/en.json +++ b/site/src/locales/en.json @@ -87,7 +87,6 @@ "topologyLocalService": "Local Service", "noProxies": "No proxies configured", "noProxiesDesc": "Add a proxy to see the type distribution", - "quickActions": "Quick Actions", "qaServersDesc": "Manage server connections", "qaProxiesDesc": "Configure proxy tunnels", "qaImportDesc": "Import from TOML config", @@ -156,6 +155,8 @@ "failedToLoad": "Failed to load server", "backToServers": "Back to Servers", "serverNamePlaceholder": "e.g. Production Server", + "user": "User", + "userPlaceholder": "e.g. admin", "hostAddressLabel": "Host Address", "hostAddressPlaceholder": "e.g. frps.example.com", "portLabel": "Port", @@ -233,7 +234,11 @@ "saveChanges": "Save Changes", "errorInvalidIP": "Invalid IP address or domain name", "errorInvalidPort": "Port must be between 1 and 65535", - "errorInvalidServerName": "Only letters, numbers, Chinese characters, spaces, dots, underscores, and hyphens are allowed" + "errorInvalidServerName": "Only letters, numbers, Chinese characters, spaces, dots, underscores, and hyphens are allowed", + "startSuccess": "Server started successfully", + "startFailed": "Failed to start server", + "stopSuccess": "Server stopped successfully", + "stopFailed": "Failed to stop server" }, "proxy": { "title": "Proxies", diff --git a/site/src/locales/zh.json b/site/src/locales/zh.json index 652c1f7..32f0183 100644 --- a/site/src/locales/zh.json +++ b/site/src/locales/zh.json @@ -87,7 +87,6 @@ "topologyLocalService": "本地服务", "noProxies": "暂无代理配置", "noProxiesDesc": "添加代理后即可查看类型分布", - "quickActions": "快速操作", "qaServersDesc": "管理服务器连接", "qaProxiesDesc": "配置代理隧道", "qaImportDesc": "从 TOML 配置文件导入", @@ -156,6 +155,8 @@ "failedToLoad": "加载服务器失败", "backToServers": "返回服务器列表", "serverNamePlaceholder": "例如:生产服务器", + "user": "用户", + "userPlaceholder": "例如:admin", "hostAddressLabel": "主机地址", "hostAddressPlaceholder": "例如:frps.example.com", "portLabel": "端口", @@ -233,7 +234,11 @@ "saveChanges": "保存更改", "errorInvalidIP": "无效的 IP 地址或域名", "errorInvalidPort": "端口必须在 1 到 65535 之间", - "errorInvalidServerName": "仅允许字母、数字、中文字符、空格、点、下划线和连字符" + "errorInvalidServerName": "仅允许字母、数字、中文字符、空格、点、下划线和连字符", + "startSuccess": "服务器启动成功", + "startFailed": "服务器启动失败", + "stopSuccess": "服务器停止成功", + "stopFailed": "服务器停止失败" }, "proxy": { "title": "代理", diff --git a/site/src/pages/ServerDetail/ServerDetailPage.view.tsx b/site/src/pages/ServerDetail/ServerDetailPage.view.tsx index ccea4af..6422e76 100644 --- a/site/src/pages/ServerDetail/ServerDetailPage.view.tsx +++ b/site/src/pages/ServerDetail/ServerDetailPage.view.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { useEffect, useRef, useState, useCallback } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { Card, Flex, Text, Badge, Grid, Button, Heading, Box, Table, AlertDialog } from "@radix-ui/themes"; import { Icon } from "@iconify/react"; @@ -12,6 +12,7 @@ import { ServerLatency } from "../../components/ServerLatency"; import { ServerLocation } from "../../components/ServerLocation"; import { useTranslation } from "react-i18next"; import { useServerProxies } from "./useServerProxies"; +import { apiPost } from "../../lib/api"; export function ServerDetailPage() { const { t } = useTranslation(); @@ -40,26 +41,63 @@ export function ServerDetailPage() { return () => clearTimeout(timer); }, []); - useEffect(() => { + const [actionLoading, setActionLoading] = useState(false); + + const fetchServer = useCallback(async (showLoading = true) => { if (!id) return; + try { + if (showLoading) setLoading(true); + const record = await pb.collection("fh_servers").getOne(id); + setServer(record); + } catch (err: any) { + if (err.isAbort) return; + console.error("Failed to load server details:", err); + setError(err.message || t("server.failedToLoad")); + toast.error(t("server.failedToLoad")); + } finally { + if (showLoading) setLoading(false); + } + }, [id, t]); - const fetchServer = async () => { - try { - setLoading(true); - const record = await pb.collection("fh_servers").getOne(id); - setServer(record); - } catch (err: any) { - if (err.isAbort) return; - console.error("Failed to load server details:", err); - setError(err.message || t("server.failedToLoad")); - toast.error(t("server.failedToLoad")); - } finally { - setLoading(false); - } - }; - + useEffect(() => { fetchServer(); - }, [id, navigate]); + }, [fetchServer]); + + const handleStart = async () => { + if (!id) return; + try { + setActionLoading(true); + const response = await apiPost("/api/frpc/launch", { id }); + if (response.ok) { + toast.success(t("server.startSuccess")); + fetchServer(false); + } else { + toast.error(t("server.startFailed")); + } + } catch (err: any) { + toast.error(err.message || t("server.startFailed")); + } finally { + setActionLoading(false); + } + }; + + const handleStop = async () => { + if (!id) return; + try { + setActionLoading(true); + const response = await apiPost("/api/frpc/terminate", { id }); + if (response.ok) { + toast.success(t("server.stopSuccess")); + fetchServer(false); + } else { + toast.error(t("server.stopFailed")); + } + } catch (err: any) { + toast.error(err.message || t("server.stopFailed")); + } finally { + setActionLoading(false); + } + }; // SSE log streaming useEffect(() => { @@ -131,6 +169,21 @@ export function ServerDetailPage() { title={server.serverName} description={t("server.detailsAndLogs")} visible={mounted} + extra={ + + {server.bootStatus === "running" ? ( + + ) : ( + + )} + + } /> {/* + {server.user && ( + + + {t("server.user")} + + + {server.user} + + + )} {t("server.latency")} diff --git a/site/src/pages/Servers/ServerFormPage/ServerFormPage.view.tsx b/site/src/pages/Servers/ServerFormPage/ServerFormPage.view.tsx index e1485fe..1330877 100644 --- a/site/src/pages/Servers/ServerFormPage/ServerFormPage.view.tsx +++ b/site/src/pages/Servers/ServerFormPage/ServerFormPage.view.tsx @@ -190,6 +190,15 @@ export function ServerFormPageView({ /> + + onChange("user", e.target.value)} + /> + + {formData.auth.method === "token" && ( diff --git a/site/src/pages/Servers/ServerFormPage/useServerForm.ts b/site/src/pages/Servers/ServerFormPage/useServerForm.ts index 57a6502..a140360 100644 --- a/site/src/pages/Servers/ServerFormPage/useServerForm.ts +++ b/site/src/pages/Servers/ServerFormPage/useServerForm.ts @@ -7,6 +7,7 @@ import { REGEX } from "../../../lib/regex"; export interface ServerFormData { serverName: string; + user: string; serverAddr: string; serverPort: number; serverVersion: string; @@ -41,6 +42,7 @@ export interface ServerFormData { const defaultData: ServerFormData = { serverName: "", + user: "", serverAddr: "", serverPort: 7000, serverVersion: "built-in", @@ -100,6 +102,7 @@ export function useServerForm() { setFormData({ ...defaultData, serverName: record.serverName || "", + user: record.user || "", serverAddr: record.serverAddr || "", serverPort: record.serverPort || 7000, serverVersion: record.serverVersion || "built-in", diff --git a/site/src/pages/Servers/useServers.ts b/site/src/pages/Servers/useServers.ts index 0db3f86..51305a3 100644 --- a/site/src/pages/Servers/useServers.ts +++ b/site/src/pages/Servers/useServers.ts @@ -6,6 +6,7 @@ import { toast } from "sonner"; export interface Server { id: string; serverName: string; + user: string; serverAddr: string; serverPort: number; description: string;