✨ feat: support frpc user field in server config and proxy name resolution

- 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 "<user>.<name>" 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 <noreply@anthropic.com>
This commit is contained in:
刘嘉伟andClaude Sonnet 4.6 committed 2026-03-14 18:42:14 +08:00
1 parent d10538f1c3
commit c0b4c7bb94
9 files changed
+195 -28

No files matched your search

+38 -6
View File
@@ -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()
+4
View File
@@ -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))
@@ -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)
})
}
+7 -2
View File
@@ -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",
+7 -2
View File
@@ -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": "代理",
@@ -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<Server>(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<Server>(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={
<Flex gap="3" align="center">
{server.bootStatus === "running" ? (
<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")}
</Button>
) : (
<Button size="2" color="green" variant="soft" onClick={handleStart} disabled={actionLoading}>
{actionLoading ? <Icon icon="lucide:loader-2" className="animate-spin" /> : <Icon icon="lucide:play" width="16" height="16" />}
{t("server.start")}
</Button>
)}
</Flex>
}
/>
{/*<motion.div*/}
{/* initial={{ opacity: 0, y: -20 }}*/}
@@ -178,6 +231,16 @@ export function ServerDetailPage() {
{server.serverPort}
</Text>
</Box>
{server.user && (
<Box>
<Text size="2" color="gray">
{t("server.user")}
</Text>
<Text as="div" size="3" weight="medium">
{server.user}
</Text>
</Box>
)}
<Box>
<Text size="2" color="gray">
{t("server.latency")}
@@ -190,6 +190,15 @@ export function ServerFormPageView({
/>
</FormItem>
<FormItem label={t("server.user")}>
<TextField.Root
size="2"
placeholder={t("server.userPlaceholder")}
value={formData.user}
onChange={(e) => onChange("user", e.target.value)}
/>
</FormItem>
<AnimatePresence>
{formData.auth.method === "token" && (
<FormItem key="token-field" label={t("server.token")} animate>
@@ -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",
+1
View File
@@ -6,6 +6,7 @@ import { toast } from "sonner";
export interface Server {
id: string;
serverName: string;
user: string;
serverAddr: string;
serverPort: number;
description: string;