97 Commits

Author SHA1 Message Date
lxh2875931338 1473083548 小修补后的deploy.sh部署逻辑,当前为LTS可用版本 2026-07-30 20:25:29 +08:00
lxh2875931338 0147f482e2 更新日志 2026-07-30 13:11:12 +08:00
lxh2875931338 94558dfa25 更新日志 2026-07-30 13:08:59 +08:00
lxh2875931338 26f184399f 更新日志调整 2026-07-30 13:08:20 +08:00
lxh2875931338 bd40eea81c 更新日志 2026-07-30 13:06:28 +08:00
lxh2875931338 461831414b Merge branch 'test' 2026-07-30 13:03:00 +08:00
lxh2875931338 d122456276 更新日志补充 2026-07-30 13:01:34 +08:00
lxh2875931338 2ad151e44b 合并test分支代码 2026-07-30 12:48:46 +08:00
lxh2875931338 5a28775f84 Merge branch 'test' 2026-07-30 12:48:29 +08:00
lxh2875931338 66fc634706 数据库备份逻辑容错机制优化 2026-07-30 11:45:31 +08:00
lxh2875931338 18fd797207 调整更新日志信息 2026-07-30 11:24:58 +08:00
lxh2875931338 db03b4bb1a 优化部署脚本的进程监测逻辑 2026-07-30 00:35:12 +08:00
lxh2875931338 62e48a25d9 文件夹挂载逻辑变动2 2026-07-30 00:20:11 +08:00
lxh2875931338 defc9d00d3 文件夹挂载逻辑变动 2026-07-30 00:18:06 +08:00
lxh2875931338 826ce399e7 全新优化的部署流程 2026-07-30 00:08:44 +08:00
lxh2875931338 1748cee251 优化冗余 2026-07-29 23:52:58 +08:00
lxh2875931338 1888252298 确认test分支更新内容 2026-07-29 23:52:37 +08:00
lxh2875931338 93d11d00a2 在test分支完成测试之前,自动部署脚本会恢复到原有版本 2026-07-29 23:51:16 +08:00
lxh2875931338 8657d95402 事务后钩子增加对冗余镜像的清理 2026-07-29 23:48:06 +08:00
lxh2875931338 8a5a541bc6 dockerfile调整更新 2026-07-29 23:45:51 +08:00
lxh2875931338 3329209274 调整dockerfile部署策略 2026-07-29 23:40:26 +08:00
lxh2875931338 151ef597db 添加容器内监测数据库的能力 2026-07-29 23:32:29 +08:00
lxh2875931338 7a7688bbe0 部分部署逻辑调整 2026-07-29 23:28:53 +08:00
lxh2875931338 5c89232004 部分部署逻辑调整 2026-07-29 23:28:39 +08:00
lxh2875931338 74f6478e4e 部分逻辑修复 2026-07-29 23:27:46 +08:00
lxh2875931338 cd178a1a9d 部署逻辑存在调整,与test端同步 2026-07-29 23:23:25 +08:00
lxh2875931338 acbab598e4 部署逻辑存在优化 2026-07-29 23:23:05 +08:00
lxh2875931338 a87e9aa0b8 给main端添加最新的自动化脚本进行测试 2026-07-29 23:17:19 +08:00
lxh2875931338 2e88b4f779 新脚本测试 2026-07-29 23:16:19 +08:00
lxh2875931338 ebb656f6da 统一为小写的版本注释文件 2026-07-29 23:10:20 +08:00
lxh2875931338 761047009e 更新部分内容,重测中 2026-07-29 22:55:02 +08:00
lxh2875931338 42058e724d 优化部署逻辑,正在进行验证 2026-07-29 22:47:29 +08:00
lxh2875931338 94bd61daa1 2.4-接入全新部署逻辑设计,内容较多,后续会在日志内单开一个md文件说明 2026-07-29 20:23:25 +08:00
lxh2875931338 205525c243 调整更新文档 2026-07-29 19:53:28 +08:00
lxh2875931338 16204200de 增加独立的更新日志页面 2026-07-29 19:51:27 +08:00
lxh2875931338 e1cf6f4f47 推送新的日志 2026-07-28 23:14:39 +08:00
lxh2875931338 a5c33580e2 调整部分部署逻辑 2026-07-28 22:56:45 +08:00
lxh2875931338 f2af48f8d0 调整部分部署逻辑 2026-07-28 22:50:17 +08:00
lxh2875931338 2663e71b4f 调整部分部署逻辑 2026-07-28 22:35:48 +08:00
lxh2875931338 bf24d3cb00 调整部分部署逻辑 2026-07-28 22:29:42 +08:00
lxh2875931338 00f2b9fd14 重新设计新的部署逻辑,去掉本机自己的go build,合并到docker多阶段构建部分进行 2026-07-28 22:23:39 +08:00
lxh2875931338 76ac9503c6 调整部分部署逻辑 2026-07-28 21:58:12 +08:00
lxh2875931338 04851d244f 调整部分部署逻辑 2026-07-28 21:55:33 +08:00
lxh2875931338 a2f4326882 确认部分逻辑 2026-07-28 21:50:04 +08:00
lxh2875931338 948aef0fe4 优化部分逻辑 2026-07-28 21:41:55 +08:00
lxh2875931338 4cd438ed3e Merge branch 'test' 2026-07-28 21:24:54 +08:00
lxh2875931338 c340e3934c 更新部署逻辑 2026-07-28 21:22:31 +08:00
lxh2875931338 ef6c75aef9 需要测试相关功能 2026-07-28 20:47:41 +08:00
lxh2875931338 6904e4993f 延迟监测逻辑更新 2026-07-28 20:38:21 +08:00
lxh2875931338 1bfa2383c1 docker脚本部分逻辑更新 2026-07-28 20:21:01 +08:00
lxh2875931338 b13f2d5047 指南更新 2026-07-28 20:13:14 +08:00
lxh2875931338 7a2737bc83 指南更新 2026-07-28 20:11:53 +08:00
lxh2875931338 1fd845a981 readme更新 2026-07-28 20:09:34 +08:00
lxh2875931338 f9a97a0af5 版本更新说明 2026-07-28 20:06:14 +08:00
lxh2875931338 ab73a38f06 直接更新 2026-07-28 20:03:20 +08:00
lxh2875931338 21c9c9556b 2.2逻辑设计已完成 2026-07-28 20:01:43 +08:00
lxh2875931338 babfdee02b 2.2技术预览版更新内容已写入 2026-07-28 19:30:26 +08:00
lxh2875931338 aaac3fc791 引入2.1应做的全新UI变更 2026-07-28 19:11:40 +08:00
lxh2875931338 509de72d10 2.2的部分代码新增实现 2026-07-28 18:46:08 +08:00
lxh2875931338 c2516dc8ff 2.2测试代码引入中 2026-07-28 18:43:56 +08:00
lxh2875931338 74a054d90c 更新 readme.md
readme更新2.0-LTS发布信息
2026-07-28 00:28:23 +08:00
lxh2875931338 d2b3dd8803 2.0前的最后几个版本推送 2026-07-27 23:34:07 +08:00
lxh2875931338 1afb56edfc readme更新 2026-07-27 18:32:32 +08:00
lxh2875931338 73f0011b54 readme援引项目更新 2026-07-27 18:31:26 +08:00
lxh2875931338 1d0e98e1fd readme更新 2026-07-27 18:10:44 +08:00
lxh2875931338 fb8fecc59a readme更新 2026-07-27 18:05:12 +08:00
lxh2875931338 0c21dd5d07 更新 readme.md 2026-07-27 13:07:16 +08:00
lxh2875931338 8b5de14cce 更新 readme.md
readme措辞调整

Signed-off-by: 不安的亡命樱 <1+lxh2875931338@noreply.localhost>
2026-07-27 13:04:25 +08:00
lxh2875931338 4bd3554140 readme补充 2026-07-27 12:40:04 +08:00
lxh2875931338 6934835394 readme补充 2026-07-27 12:39:44 +08:00
lxh2875931338 2c044890d8 readme补充 2026-07-27 12:38:59 +08:00
lxh2875931338 f9d817031e 调整日志内容 2026-07-27 12:38:24 +08:00
lxh2875931338 a97b3a7669 readme补充 2026-07-27 12:37:23 +08:00
lxh2875931338 059e4638da readme补充 2026-07-27 12:34:56 +08:00
lxh2875931338 b80238029a 阐述一个新的设计理念“阴阳模式” 2026-07-27 12:33:24 +08:00
lxh2875931338 e64a8687d2 第一份2.0-LTS代码上传 2026-07-26 21:55:42 +08:00
lxh2875931338 542f265a35 1.5正式完结,即将进入LTS更新环节 2026-07-26 14:00:16 +08:00
lxh2875931338 88046018a8 优化自动脚本逻辑 2026-07-26 12:53:11 +08:00
lxh2875931338 ebba194fbc 优化自动脚本逻辑 2026-07-26 12:49:56 +08:00
lxh2875931338 73a7bbea09 优化自动脚本逻辑 2026-07-26 12:40:26 +08:00
lxh2875931338 bfc6f9b6e2 docker安装自动脚本重构部署逻辑 2026-07-26 12:37:27 +08:00
lxh2875931338 7851bea1c3 增加对Arch分支系统的自动配置支持 2026-07-26 12:30:02 +08:00
lxh2875931338 469a3687ca 编译工具优化 2026-07-26 12:17:09 +08:00
lxh2875931338 18e8098aa4 日志部分再次小改动(行高亮取消) 2026-07-25 23:41:35 +08:00
lxh2875931338 2a9eee4582 部分布局优化(小调整) 2026-07-25 23:37:57 +08:00
lxh2875931338 6dbebc27f6 部分布局调整 2026-07-25 23:36:13 +08:00
lxh2875931338 f49bc07f42 新增功能:frp v2 隧道支持(1.5版本下为灰标无法点击) 2026-07-25 22:42:16 +08:00
lxh2875931338 ce07f4f0f0 正在进行1.5版本更新,导入第一批代码 2026-07-25 22:15:41 +08:00
lxh2875931338 1669abf9e8 readme更新 2026-07-25 20:51:52 +08:00
lxh2875931338 5023064a36 readme更新 2026-07-25 20:47:52 +08:00
lxh2875931338 078842f620 readme更新 2026-07-25 20:46:55 +08:00
lxh2875931338 ebaecfe66c readme更新 2026-07-25 20:45:00 +08:00
lxh2875931338 a174c342f5 readme更新 2026-07-25 20:41:44 +08:00
lxh2875931338 3901698e31 补充部分安装文档与readme引用 2026-07-25 00:12:12 +08:00
lxh2875931338 d4aef6dbb1 补充部分安装文档与readme引用 2026-07-25 00:08:02 +08:00
lxh2875931338 7cce698281 补充部分安装文档 2026-07-25 00:02:28 +08:00
lxh2875931338 24f5766568 补充部分安装文档 2026-07-24 23:59:38 +08:00
22 changed files with 2862 additions and 730 deletions
+6 -24
View File
@@ -1,48 +1,30 @@
# ============================================================
# 构建阶段
# ============================================================
# 多阶段构建
FROM golang:alpine AS builder
WORKDIR /app
# 复制依赖文件
COPY go.mod go.sum ./
RUN sed -i 's/go 1.2[6-9].*/go 1.21/' go.mod && go mod tidy
RUN go env -w GOPROXY=https://goproxy.cn,direct
RUN go mod download
# 复制源码(确保 bin/ 和 static/ 目录存在)
COPY . .
# 编译 Linux 版(CGO_ENABLED=0 保证静态编译
# 编译时不注入任何版本信息(纯净二进制
RUN CGO_ENABLED=0 GOOS=linux go build \
-ldflags="-s -w" \
-o frpc-console .
# ============================================================
# 运行阶段
# ============================================================
FROM alpine:latest
# 安装 ca-certificates tzdata(确保 HTTPS 和时区正常)
RUN apk --no-cache add ca-certificates tzdata
RUN apk --no-cache add ca-certificates tzdata sqlite
WORKDIR /app
# 从构建阶段复制编译好的二进制
COPY --from=builder /app/frpc-console /app/frpc-console
COPY static/ /app/static/
# 创建数据目录(用于持久化 db 和日志)
RUN mkdir -p /app/data
# 暴露端口(默认 9300
EXPOSE 9300
# 环境变量
ENV PORT=9300
ENV TZ=Asia/Shanghai
# 数据卷(持久化数据库、配置、日志)
VOLUME ["/app/data"]
# 启动
ENTRYPOINT ["/app/frpc-console"]
+78 -2
View File
@@ -5,9 +5,11 @@ import (
"embed"
"fmt"
"io/fs"
"net"
"net/http"
"strconv"
"text/template"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
@@ -40,10 +42,13 @@ func SetupRouter() *gin.Engine {
api := r.Group("/api")
{
// ---- 公开路由(不需要认证) ----
api.GET("/check/users", checkUsersHandler)
api.POST("/register", registerHandler)
api.POST("/login", loginHandler)
api.GET("/ping", pingHandler)
// ---- 需要认证的路由 ----
auth := api.Group("/")
auth.Use(AuthMiddleware())
{
@@ -60,6 +65,7 @@ func SetupRouter() *gin.Engine {
auth.POST("/frpc/start", startFrpcHandler)
auth.POST("/frpc/stop", stopFrpcHandler)
auth.GET("/frpc/status", getFrpcStatusHandler)
auth.GET("/frpc/log", getFrpcLogHandler)
auth.POST("/import/toml", importTomlHandler)
auth.GET("/export/toml", ExportTomlHandler)
@@ -71,7 +77,7 @@ func SetupRouter() *gin.Engine {
return r
}
// ========== 所有 Handler ==========
// ========== 认证 Handler ==========
func checkUsersHandler(c *gin.Context) {
count, err := CountUsers()
@@ -219,6 +225,8 @@ func changePasswordHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "密码修改成功"})
}
// ========== 配置 Handler ==========
func getConfigHandler(c *gin.Context) {
cfg, err := GetGlobalConfig()
if err != nil {
@@ -254,6 +262,8 @@ func updateConfigHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "配置更新成功"})
}
// ========== 隧道 Handler ==========
func getProxiesHandler(c *gin.Context) {
proxies, err := GetProxies()
if err != nil {
@@ -344,6 +354,8 @@ func deleteProxyHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "隧道删除成功"})
}
// ========== frpc 进程管理 Handler ==========
func reloadFrpcHandler(c *gin.Context) {
if err := GenerateFrpcConfig(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "生成配置失败: " + err.Error()})
@@ -381,6 +393,63 @@ func getFrpcStatusHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"running": running}})
}
// ========== 日志 Handler ==========
func getFrpcLogHandler(c *gin.Context) {
// readTailLog 在 frp.go 中定义,读取 ./data/frpc.log
lines, err := readTailLog("./data/frpc.log", 200)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": gin.H{
"lines": []string{},
"total": 0,
"error": err.Error(),
},
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": gin.H{
"lines": lines,
"total": len(lines),
},
})
}
// ========== Ping Handler ==========
func pingHandler(c *gin.Context) {
target := c.Query("target")
if target == "" {
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "缺少 target 参数"})
return
}
cfg, err := GetGlobalConfig()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "读取配置失败"})
return
}
port := cfg.ServerPort
address := net.JoinHostPort(target, strconv.Itoa(port))
start := time.Now()
conn, err := net.DialTimeout("tcp", address, 5*time.Second)
if err != nil {
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "ping 失败", "latency": -1})
return
}
conn.Close()
latency := time.Since(start).Milliseconds()
c.JSON(http.StatusOK, gin.H{"code": 0, "latency": latency})
}
// ========== 导入/导出 TOML ==========
func importTomlHandler(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
@@ -468,12 +537,19 @@ func ExportTomlHandler(c *gin.Context) {
data := struct {
*GlobalConfig
Proxies []Proxy
Proxies []Proxy
WireProtocolLine string
}{
GlobalConfig: cfg,
Proxies: activeProxies,
}
if cfg.WireProtocolV2 {
data.WireProtocolLine = `wireProtocol = "v2"`
} else {
data.WireProtocolLine = ""
}
tmpl, err := template.New("frpc").Parse(FrpcTemplateContent)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "解析模板失败: " + err.Error()})
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
+91
View File
@@ -0,0 +1,91 @@
package main
// ============================================================
// db-history.go - Schema 版本声明与字段映射
// ============================================================
type SchemaVersionDef struct {
Version string
TableName string
Columns map[string]ColumnDef
}
type ColumnDef struct {
Type string
NotNull bool
Default string
Primary bool
}
var schemaHistory = []SchemaVersionDef{
// v1:初始版本
{
Version: "v1",
TableName: "proxies",
Columns: map[string]ColumnDef{
"id": {Type: "INTEGER", Primary: true},
"name": {Type: "TEXT", NotNull: true},
"type": {Type: "TEXT", NotNull: true, Default: "'tcp'"},
"local_ip": {Type: "TEXT", NotNull: true},
"local_port": {Type: "INTEGER", NotNull: true},
"remote_port": {Type: "INTEGER", NotNull: true},
"enabled": {Type: "INTEGER", NotNull: true, Default: "1"},
"created_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"},
"updated_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"},
},
},
// v2:当前版本(frpc-console 2.0 LTS
{
Version: "v2",
TableName: "proxies",
Columns: map[string]ColumnDef{
"id": {Type: "INTEGER", Primary: true},
"name": {Type: "TEXT", NotNull: true},
"type": {Type: "TEXT", NotNull: true, Default: "'tcp'"},
"local_ip": {Type: "TEXT", NotNull: true},
"local_port": {Type: "INTEGER", NotNull: true},
"remote_port": {Type: "INTEGER", NotNull: true},
"enabled": {Type: "INTEGER", NotNull: true, Default: "1"},
"created_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"},
"updated_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"},
},
},
}
func getSchemaDef(version string) *SchemaVersionDef {
for _, def := range schemaHistory {
if def.Version == version {
return &def
}
}
return nil
}
func getLatestSchemaDef() *SchemaVersionDef {
if len(schemaHistory) == 0 {
return nil
}
return &schemaHistory[len(schemaHistory)-1]
}
func schemaVersionsEqual(v1, v2 *SchemaVersionDef) bool {
if v1 == nil || v2 == nil {
return false
}
if v1.TableName != v2.TableName {
return false
}
if len(v1.Columns) != len(v2.Columns) {
return false
}
for name, col1 := range v1.Columns {
col2, ok := v2.Columns[name]
if !ok {
return false
}
if col1.Type != col2.Type || col1.NotNull != col2.NotNull || col1.Default != col2.Default {
return false
}
}
return true
}
+317 -42
View File
@@ -4,14 +4,21 @@ import (
"crypto/rand"
"database/sql"
"encoding/hex"
"fmt"
"io"
"log"
"os"
"sort"
"strings"
"time"
_ "modernc.org/sqlite"
)
var DB *sql.DB
// ===== 全局配置表(A表)=====
const SchemaVersion = "v2"
type GlobalConfig struct {
ID int `json:"id"`
ServerAddr string `json:"serverAddr"`
@@ -24,9 +31,9 @@ type GlobalConfig struct {
HeartbeatInterval int `json:"heartbeatInterval"`
HeartbeatTimeout int `json:"heartbeatTimeout"`
PoolCount int `json:"poolCount"`
WireProtocolV2 bool `json:"wireProtocolV2"`
}
// ===== 隧道表(B表)=====
type Proxy struct {
ID int `json:"id"`
Name string `json:"name"`
@@ -37,7 +44,6 @@ type Proxy struct {
Enabled bool `json:"enabled"`
}
// ===== 用户表(C表)=====
type User struct {
ID int `json:"id"`
Username string `json:"username"`
@@ -45,16 +51,37 @@ type User struct {
CreatedAt string `json:"createdAt"`
}
// ===== 初始化数据库 =====
func InitDB() error {
// 确保 data 目录存在
if err := os.MkdirAll("./data", 0755); err != nil {
return fmt.Errorf("创建数据目录失败: %w", err)
}
dbPath := "./data/frpc-console.db"
var err error
DB, err = sql.Open("sqlite", "./frpc-console.db")
DB, err = sql.Open("sqlite", dbPath)
if err != nil {
return err
}
// 用户表(C表)
_, err = DB.Exec(`
if err := createTables(); err != nil {
return err
}
if err := runMigrations(); err != nil {
return err
}
if err := ensureJwtSecret(); err != nil {
return err
}
log.Println("✅ 数据库初始化完成 (Schema " + SchemaVersion + ")")
return nil
}
func createTables() error {
_, err := DB.Exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
@@ -67,13 +94,12 @@ func InitDB() error {
return err
}
// 全局配置表(A表)
_, err = DB.Exec(`
CREATE TABLE IF NOT EXISTS global_config (
id INTEGER PRIMARY KEY CHECK (id = 1),
server_addr TEXT NOT NULL DEFAULT 'frp.whitetop.xyz',
server_port INTEGER NOT NULL DEFAULT 9358,
token TEXT NOT NULL DEFAULT 'Lxh10020328',
server_addr TEXT NOT NULL DEFAULT 'frp.example.com',
server_port INTEGER NOT NULL DEFAULT 7000,
token TEXT NOT NULL DEFAULT 'CHANGE_ME',
log_level TEXT NOT NULL DEFAULT 'info',
log_max_days INTEGER NOT NULL DEFAULT 3,
tcp_mux INTEGER NOT NULL DEFAULT 1,
@@ -81,6 +107,7 @@ func InitDB() error {
heartbeat_interval INTEGER NOT NULL DEFAULT 15,
heartbeat_timeout INTEGER NOT NULL DEFAULT 70,
pool_count INTEGER NOT NULL DEFAULT 8,
wire_protocol_v2 INTEGER NOT NULL DEFAULT 0,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`)
@@ -88,22 +115,6 @@ func InitDB() error {
return err
}
var count int
DB.QueryRow("SELECT COUNT(*) FROM global_config").Scan(&count)
if count == 0 {
_, err = DB.Exec(`
INSERT INTO global_config (
id, server_addr, server_port, token, log_level, log_max_days,
tcp_mux, tcp_mux_keepalive, heartbeat_interval, heartbeat_timeout, pool_count
) VALUES (1, 'frp.whitetop.xyz', 9358, 'Lxh10020328', 'info', 3, 1, 30, 15, 70, 8)
`)
if err != nil {
return err
}
log.Println("✅ 全局配置初始化完成")
}
// 隧道表(B表)
_, err = DB.Exec(`
CREATE TABLE IF NOT EXISTS proxies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -121,7 +132,6 @@ func InitDB() error {
return err
}
// 应用配置表(JWT密钥等)
_, err = DB.Exec(`
CREATE TABLE IF NOT EXISTS app_config (
key TEXT PRIMARY KEY,
@@ -133,15 +143,282 @@ func InitDB() error {
return err
}
if err := ensureJwtSecret(); err != nil {
return err
var count int
DB.QueryRow("SELECT COUNT(*) FROM global_config").Scan(&count)
if count == 0 {
_, err = DB.Exec(`
INSERT INTO global_config (
id, server_addr, server_port, token, log_level, log_max_days,
tcp_mux, tcp_mux_keepalive, heartbeat_interval, heartbeat_timeout, pool_count,
wire_protocol_v2
) VALUES (1, 'frp.example.com', 7000, 'CHANGE_ME', 'info', 3, 1, 30, 15, 70, 8, 0)
`)
if err != nil {
return err
}
log.Println("✅ 全局配置初始化完成")
}
log.Println("✅ 数据库初始化完成")
return nil
}
// ===== JWT 密钥管理 =====
func getCurrentSchemaVersion() string {
var version string
err := DB.QueryRow("SELECT value FROM app_config WHERE key = 'schema_version'").Scan(&version)
if err != nil {
if err == sql.ErrNoRows {
var count int
DB.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
if count > 0 {
return "v1"
}
return SchemaVersion
}
log.Printf("⚠️ 读取 Schema 版本失败: %v", err)
return "v1"
}
return version
}
func setSchemaVersion(version string) error {
_, err := DB.Exec(`
INSERT INTO app_config (key, value) VALUES ('schema_version', ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP
`, version)
return err
}
func backupDatabase() (string, error) {
src := "./data/frpc-console.db"
if _, err := os.Stat(src); os.IsNotExist(err) {
return "", nil
}
timestamp := time.Now().Format("20060102_150405")
dst := fmt.Sprintf("./data/frpc-console.db.pre-%s.%s", SchemaVersion, timestamp)
srcFile, err := os.Open(src)
if err != nil {
return "", fmt.Errorf("打开源数据库失败: %w", err)
}
defer srcFile.Close()
dstFile, err := os.Create(dst)
if err != nil {
return "", fmt.Errorf("创建备份文件失败: %w", err)
}
defer dstFile.Close()
if _, err := io.Copy(dstFile, srcFile); err != nil {
return "", fmt.Errorf("复制数据库失败: %w", err)
}
log.Printf("✅ 数据库备份完成: %s", dst)
return dst, nil
}
func restoreDatabase(backupPath string) error {
srcFile, err := os.Open(backupPath)
if err != nil {
return err
}
defer srcFile.Close()
dstFile, err := os.Create("./data/frpc-console.db")
if err != nil {
return err
}
defer dstFile.Close()
if _, err := io.Copy(dstFile, srcFile); err != nil {
return err
}
log.Printf("✅ 数据库已从备份恢复: %s", backupPath)
return nil
}
func runMigrations() error {
currentVer := getCurrentSchemaVersion()
targetVer := SchemaVersion
log.Printf("📌 当前数据库 Schema: %s, 目标版本: %s", currentVer, targetVer)
if currentVer == targetVer {
var userCount int
err := DB.QueryRow("SELECT COUNT(*) FROM users").Scan(&userCount)
if err != nil || userCount == 0 {
log.Println(" 数据库为空或无效,无需迁移,直接初始化")
return nil
}
log.Println("✅ Schema 已是最新,数据库有效")
return nil
}
log.Printf("🔄 检测到版本变更 (%s → %s),开始迁移...", currentVer, targetVer)
backupPath, err := backupDatabase()
if err != nil {
return fmt.Errorf("备份数据库失败: %w", err)
}
if backupPath != "" {
log.Printf("📦 备份文件: %s", backupPath)
}
currentSchema := getSchemaDef(currentVer)
targetSchema := getSchemaDef(targetVer)
if targetSchema == nil {
return fmt.Errorf("目标 Schema 版本 %s 未在 schemaHistory 中定义", targetVer)
}
if currentSchema == nil || schemaVersionsEqual(currentSchema, targetSchema) {
log.Println(" 迁移类型: 轻量复制(Schema 无变更)")
var userCount int
err := DB.QueryRow("SELECT COUNT(*) FROM users").Scan(&userCount)
if err != nil || userCount == 0 {
log.Println(" 数据库为空或无效,跳过迁移,直接初始化")
return nil
}
log.Println(" 数据库有效,继续使用")
} else {
log.Println(" 迁移类型: 重型迁移(Schema 有变更,新建表 + 搬数据)")
if err := heavyMigration(currentSchema, targetSchema); err != nil {
if backupPath != "" {
log.Printf("❌ 迁移失败,尝试恢复备份: %s", backupPath)
if restoreErr := restoreDatabase(backupPath); restoreErr != nil {
log.Printf("⚠️ 恢复备份失败: %v", restoreErr)
}
}
return fmt.Errorf("重型迁移失败: %w", err)
}
}
if err := setSchemaVersion(targetVer); err != nil {
return fmt.Errorf("更新 Schema 版本失败: %w", err)
}
log.Printf("✅ 迁移完成,当前 Schema: %s", targetVer)
return nil
}
func heavyMigration(oldDef, newDef *SchemaVersionDef) error {
if oldDef == nil {
return fmt.Errorf("旧 Schema 定义为空,无法执行重型迁移")
}
oldTable := oldDef.TableName
newTable := oldTable + "_new"
createSQL := buildCreateTableSQL(newTable, newDef)
log.Printf(" 创建新表: %s", newTable)
if _, err := DB.Exec(createSQL); err != nil {
return fmt.Errorf("创建新表失败: %w", err)
}
insertSQL, err := buildInsertSQL(oldTable, newTable, oldDef, newDef)
if err != nil {
return fmt.Errorf("构建数据迁移 SQL 失败: %w", err)
}
log.Printf(" 迁移数据: %s → %s", oldTable, newTable)
if _, err := DB.Exec(insertSQL); err != nil {
return fmt.Errorf("数据迁移失败: %w", err)
}
var oldCount, newCount int
DB.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", oldTable)).Scan(&oldCount)
DB.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", newTable)).Scan(&newCount)
if oldCount != newCount {
return fmt.Errorf("数据迁移不完整: 旧表 %d 行,新表 %d 行", oldCount, newCount)
}
log.Printf(" 数据迁移验证通过: %d 行", newCount)
tempTable := oldTable + "_old_temp"
if _, err := DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", oldTable, tempTable)); err != nil {
return fmt.Errorf("重命名旧表失败: %w", err)
}
if _, err := DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", newTable, oldTable)); err != nil {
DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", tempTable, oldTable))
return fmt.Errorf("重命名新表失败: %w", err)
}
if _, err := DB.Exec(fmt.Sprintf("DROP TABLE %s", tempTable)); err != nil {
log.Printf("⚠️ 删除临时表失败(不影响使用): %v", err)
}
log.Printf(" 表交换完成: %s (新表已生效)", oldTable)
return nil
}
func buildCreateTableSQL(tableName string, def *SchemaVersionDef) string {
var cols []string
var primaryKey string
names := make([]string, 0, len(def.Columns))
for name := range def.Columns {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
col := def.Columns[name]
parts := []string{name, col.Type}
if col.NotNull {
parts = append(parts, "NOT NULL")
}
if col.Default != "" {
parts = append(parts, "DEFAULT "+col.Default)
}
if col.Primary {
primaryKey = "PRIMARY KEY (" + name + ")"
} else {
cols = append(cols, strings.Join(parts, " "))
}
}
if primaryKey != "" {
cols = append(cols, primaryKey)
}
return fmt.Sprintf("CREATE TABLE %s (\n %s\n)", tableName, strings.Join(cols, ",\n "))
}
func buildInsertSQL(oldTable, newTable string, oldDef, newDef *SchemaVersionDef) (string, error) {
newCols := make([]string, 0, len(newDef.Columns))
for name := range newDef.Columns {
newCols = append(newCols, name)
}
sort.Strings(newCols)
var selectParts []string
var colNames []string
for _, name := range newCols {
colNames = append(colNames, name)
if _, ok := oldDef.Columns[name]; ok {
selectParts = append(selectParts, name)
} else {
colDef := newDef.Columns[name]
if colDef.Default != "" {
selectParts = append(selectParts, colDef.Default+" AS "+name)
} else if colDef.Type == "INTEGER" {
selectParts = append(selectParts, "0 AS "+name)
} else if colDef.Type == "TEXT" {
selectParts = append(selectParts, "'' AS "+name)
} else {
selectParts = append(selectParts, "NULL AS "+name)
}
}
}
return fmt.Sprintf(
"INSERT INTO %s (%s) SELECT %s FROM %s",
newTable,
strings.Join(colNames, ", "),
strings.Join(selectParts, ", "),
oldTable,
), nil
}
func ensureJwtSecret() error {
var value string
err := DB.QueryRow("SELECT value FROM app_config WHERE key = 'jwt_secret'").Scan(&value)
@@ -161,7 +438,7 @@ func ensureJwtSecret() error {
if err != nil {
return err
}
log.Printf("✅ JWT 密钥已生成并保存到数据库")
log.Printf("✅ JWT 密钥已生成")
return nil
}
@@ -174,17 +451,18 @@ func GetJwtSecret() (string, error) {
return secret, nil
}
// ===== 全局配置 CRUD =====
func GetGlobalConfig() (*GlobalConfig, error) {
var cfg GlobalConfig
err := DB.QueryRow(`
SELECT id, server_addr, server_port, token, log_level, log_max_days,
tcp_mux, tcp_mux_keepalive, heartbeat_interval, heartbeat_timeout, pool_count
tcp_mux, tcp_mux_keepalive, heartbeat_interval, heartbeat_timeout, pool_count,
wire_protocol_v2
FROM global_config WHERE id = 1
`).Scan(
&cfg.ID, &cfg.ServerAddr, &cfg.ServerPort, &cfg.Token,
&cfg.LogLevel, &cfg.LogMaxDays, &cfg.TcpMux, &cfg.TcpMuxKeepalive,
&cfg.HeartbeatInterval, &cfg.HeartbeatTimeout, &cfg.PoolCount,
&cfg.WireProtocolV2,
)
if err != nil {
return nil, err
@@ -199,14 +477,15 @@ func UpdateGlobalConfig(cfg *GlobalConfig) error {
server_addr = ?, server_port = ?, token = ?, log_level = ?, log_max_days = ?,
tcp_mux = 1,
tcp_mux_keepalive = ?, heartbeat_interval = ?, heartbeat_timeout = ?, pool_count = ?,
wire_protocol_v2 = ?,
updated_at = CURRENT_TIMESTAMP
WHERE id = 1
`, cfg.ServerAddr, cfg.ServerPort, cfg.Token, cfg.LogLevel, cfg.LogMaxDays,
cfg.TcpMuxKeepalive, cfg.HeartbeatInterval, cfg.HeartbeatTimeout, cfg.PoolCount)
cfg.TcpMuxKeepalive, cfg.HeartbeatInterval, cfg.HeartbeatTimeout, cfg.PoolCount,
cfg.WireProtocolV2)
return err
}
// ===== 隧道 CRUD =====
func GetProxies() ([]Proxy, error) {
rows, err := DB.Query(`
SELECT id, name, type, local_ip, local_port, remote_port, enabled
@@ -226,10 +505,7 @@ func GetProxies() ([]Proxy, error) {
}
proxies = append(proxies, p)
}
if err = rows.Err(); err != nil {
return nil, err
}
return proxies, nil
return proxies, rows.Err()
}
func GetProxy(id int) (*Proxy, error) {
@@ -272,7 +548,6 @@ func DeleteProxy(id int) error {
return err
}
// ===== 用户 CRUD =====
func GetUserByUsername(username string) (*User, error) {
var u User
err := DB.QueryRow(`
+580 -272
View File
@@ -1,330 +1,638 @@
#!/bin/bash
# ============================================================
# frpc-console 一键部署脚本
# 支持:Linux x86_64 / ARM64 / ARMv7
# 自动安装:git / curl / wget / Go / Docker
# frpc-console 一键部署脚本 (Docker 优先)
# 用法:
# run-deploy.sh 引导后自动执行
# ============================================================
set -e
# ---------- 颜色输出 ----------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'
# ---------- 颜色检测 ----------
if [ -t 1 ]; then
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; CYAN='\033[0;36m'; MAGENTA='\033[0;35m'; NC='\033[0m'
else
RED=''; GREEN=''; YELLOW=''; BLUE=''; CYAN=''; MAGENTA=''; NC=''
fi
# ---------- 配置 ----------
REPO_URL="https://git.whitetop.xyz/lxh2875931338/frpc-console.git"
BRANCH="main"
WORK_DIR="/tmp/frpc-console-build"
DEPLOY_DIR="/opt/frpc-console"
DATA_DIR="${DEPLOY_DIR}/data"
DEFAULT_PORT=9300
DEFAULT_DEPLOY_DIR="/opt/frpc-console"
IMAGE_NAME="frpc-console"
GO_VERSION="1.25.0"
KEEP_IMAGES=3
# ---------- 状态变量 ----------
OS=""; OS_VERSION=""; ARCH=""
HAS_GIT=false; HAS_CURL=false; HAS_WGET=false; HAS_DOCKER=false
NEED_INSTALL_GIT=false; NEED_INSTALL_CURL=false; NEED_INSTALL_WGET=false
PORT=${DEFAULT_PORT}
DEPLOY_DIR=${DEFAULT_DEPLOY_DIR}
DATA_DIR="${DEPLOY_DIR}/data"
CONTAINER_EXISTS=false; CONTAINER_RUNNING=false
SKIP_CONFIRM=false; CHECK_ONLY=false; DRY_RUN=false
CHANNEL=""; BRANCH=""; TARGET_VERSION=""; IMAGE_TAG=""
CURRENT_VERSION=""
# ---------- 打印函数 ----------
print_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[✓]${NC} $1"; }
print_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
print_error() { echo -e "${RED}[✗]${NC} $1"; }
print_step() { echo -e "\n${CYAN}${NC} $1"; }
print_title() { echo -e "\n${MAGENTA}════════════════════════════════════════════════════════${NC}"; }
print_subtitle() { echo -e "${MAGENTA} $1${NC}"; }
# ---------- 检查 root ----------
if [ "$EUID" -ne 0 ]; then
print_error "请使用 root 权限运行此脚本"
echo " sudo bash deploy.sh"
exit 1
fi
# ---------- 解析命令行参数 ----------
parse_args() {
for arg in "$@"; do
case $arg in
--yes|-y) SKIP_CONFIRM=true ;;
--check) CHECK_ONLY=true ;;
--dry-run) DRY_RUN=true ;;
--help|-h)
echo "用法: ./deploy.sh [选项]"
echo "选项:"
echo " --yes, -y 跳过所有确认提示"
echo " --check 只检测环境,不执行部署"
echo " --dry-run 显示将执行的操作,不实际执行"
echo " --help, -h 显示帮助信息"
exit 0
;;
*) print_error "未知选项: $arg"; exit 1 ;;
esac
done
}
# ---------- 1. 检测操作系统 ----------
print_step "检测操作系统..."
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID
OS_VERSION=$VERSION_ID
else
print_error "无法识别操作系统"
exit 1
fi
print_info "系统: $OS $OS_VERSION"
# ---------- 2. 检测 CPU 架构 ----------
print_step "检测 CPU 架构..."
ARCH=$(uname -m)
case $ARCH in
x86_64|amd64)
GO_ARCH="amd64"
;;
aarch64|arm64)
GO_ARCH="arm64"
;;
armv7l|armhf)
GO_ARCH="armv6l"
;;
*)
print_error "不支持的 CPU 架构: $ARCH"
check_root() {
if [ "$EUID" -ne 0 ]; then
print_error "请使用 root 权限运行此脚本"
echo " sudo bash deploy.sh"
exit 1
;;
esac
print_success "CPU 架构: $ARCH → Go 架构: $GO_ARCH"
fi
}
# ---------- 3. 安装必要工具 ----------
print_step "检查必要工具..."
detect_os() {
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID; OS_VERSION=$VERSION_ID
else
print_error "无法识别操作系统"
exit 1
fi
}
# git
if ! command -v git &> /dev/null; then
print_warn "git 未安装,正在安装..."
case $OS in
opensuse*|suse*|opensuse-tumbleweed|opensuse-slowroll)
zypper install -y git
;;
ubuntu|debian|linuxmint)
apt update -qq && apt install -y git
;;
centos|rhel|fedora|rocky|almalinux)
yum install -y git
;;
alpine)
apk add git
detect_arch() {
ARCH=$(uname -m)
case $ARCH in
x86_64|amd64|aarch64|arm64|armv7l|armhf)
print_success "CPU 架构: $ARCH"
;;
*)
print_error "无法识别包管理器,请手动安装 git"
print_error "不支持的 CPU 架构: $ARCH"
exit 1
;;
esac
print_success "git 安装完成"
else
print_success "git 已安装: $(git --version | awk '{print $3}')"
fi
}
# curl
if ! command -v curl &> /dev/null; then
print_warn "curl 未安装,正在安装..."
case $OS in
opensuse*|suse*|opensuse-tumbleweed|opensuse-slowroll) zypper install -y curl ;;
ubuntu|debian|linuxmint) apt install -y curl ;;
centos|rhel|fedora|rocky|almalinux) yum install -y curl ;;
alpine) apk add curl ;;
*) print_error "无法安装 curl"; exit 1 ;;
esac
print_success "curl 安装完成"
else
print_success "curl 已安装"
fi
check_tools() {
command -v git &> /dev/null && HAS_GIT=true || NEED_INSTALL_GIT=true
command -v curl &> /dev/null && HAS_CURL=true || NEED_INSTALL_CURL=true
command -v wget &> /dev/null && HAS_WGET=true || NEED_INSTALL_WGET=true
command -v docker &> /dev/null && HAS_DOCKER=true
}
# wget(备用)
if ! command -v wget &> /dev/null; then
print_warn "wget 未安装,正在安装..."
case $OS in
opensuse*|suse*|opensuse-tumbleweed|opensuse-slowroll) zypper install -y wget ;;
ubuntu|debian|linuxmint) apt install -y wget ;;
centos|rhel|fedora|rocky|almalinux) yum install -y wget ;;
alpine) apk add wget ;;
*) print_warn "wget 未安装,但不影响主要功能" ;;
esac
else
print_success "wget 已安装"
fi
check_container() {
if docker ps -a --format '{{.Names}}' 2>/dev/null | grep -q "^frpc-console$"; then
CONTAINER_EXISTS=true
if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "^frpc-console$"; then
CONTAINER_RUNNING=true
fi
fi
}
# ---------- 4. 安装 Go ----------
print_step "检查 Go 环境..."
if ! command -v go &> /dev/null; then
print_warn "Go 未安装,正在下载 Go ${GO_VERSION} (${GO_ARCH})..."
# ---------- 版本管理 ----------
read_version_from_remote() {
local branch="$1"
local version_url="https://git.whitetop.xyz/lxh2875931338/frpc-console/raw/${branch}/version.ini"
local content
content=$(curl -sSL "$version_url" 2>/dev/null)
if [ -z "$content" ]; then
print_error "无法从远程读取 version.ini: $version_url"
return 1
fi
SEMVER=$(echo "$content" | grep -v "^[;#]" | head -1 | awk '{print $1}')
echo "$SEMVER"
}
GO_TMP="/tmp/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
if [ -f "$GO_TMP" ]; then
print_info "使用缓存: $GO_TMP"
generate_target_version() {
local channel="$1"
local branch="${2:-$BRANCH}"
SEMVER=$(read_version_from_remote "$branch")
if [ -z "$SEMVER" ]; then
print_error "读取语义版本失败"
exit 1
fi
local minor="${SEMVER#*.}"
if [ "$minor" = "0" ] || [ "$minor" = "5" ]; then
CHANNEL_TYPE="lts"
else
print_info "正在下载..."
MIRRORS=(
"https://mirrors.aliyun.com/golang/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
"https://mirrors.tuna.tsinghua.edu.cn/golang/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
"https://golang.google.cn/dl/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
"https://dl.google.com/go/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
)
CHANNEL_TYPE="preview"
fi
if [ "$channel" = "lts" ] || [ "$CHANNEL_TYPE" = "lts" ]; then
TARGET_VERSION="${SEMVER}-lts-$(date +%Y%m%d)"
IMAGE_TAG="${SEMVER}-lts-$(date +%Y%m%d)"
else
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
TARGET_VERSION="${SEMVER}-preview-${TIMESTAMP}"
IMAGE_TAG="preview-${TIMESTAMP}"
fi
}
DOWNLOADED=false
for MIRROR in "${MIRRORS[@]}"; do
print_info "尝试: $MIRROR"
if curl -# -f -L -o "$GO_TMP" "$MIRROR"; then
print_success "下载成功"
DOWNLOADED=true
break
get_current_version() {
local version_file="${DEPLOY_DIR}/data/version.ini"
if [ -f "$version_file" ]; then
grep -v "^[;#]" "$version_file" | head -1 | tr -d '\n'
else
if [ "$CONTAINER_EXISTS" = true ]; then
docker exec frpc-console cat /app/data/version.ini 2>/dev/null | grep -v "^[;#]" | head -1 | tr -d '\n' || echo ""
else
echo ""
fi
fi
}
# ---------- 通道选择 ----------
select_channel() {
if [ -n "$DEPLOY_CHANNEL" ] && [ -n "$DEPLOY_BRANCH" ]; then
CHANNEL="$DEPLOY_CHANNEL"
BRANCH="$DEPLOY_BRANCH"
print_info "使用环境变量: ${CHANNEL} 通道 (${BRANCH} 分支)"
return
fi
if [ -n "$CHANNEL" ]; then
if [ "$CHANNEL" != "lts" ] && [ "$CHANNEL" != "preview" ]; then
print_error "无效通道: $CHANNEL"
exit 1
fi
BRANCH="$([ "$CHANNEL" = "preview" ] && echo "test" || echo "main")"
return
fi
echo ""
echo -e "${CYAN}请选择部署通道:${NC}"
echo " 1. LTS (稳定版) [默认] → main 分支"
echo " 2. Preview (技术预览版) → test 分支"
echo ""
read -p "请选择 [1]: " CHANNEL_INPUT </dev/tty
CHANNEL_INPUT=${CHANNEL_INPUT:-1}
case $CHANNEL_INPUT in
1|"") CHANNEL="lts"; BRANCH="main" ;;
2) CHANNEL="preview"; BRANCH="test" ;;
*) print_error "无效选择"; exit 1 ;;
esac
print_info "已选择: ${CHANNEL} 通道 (${BRANCH} 分支)"
}
# ---------- 环境汇总 ----------
print_environment_summary() {
print_title
print_subtitle "环境检测结果"
echo ""
echo -e " ${CYAN}操作系统:${NC} $OS $OS_VERSION"
echo -e " ${CYAN}CPU 架构:${NC} $ARCH"
echo ""
echo " ${CYAN}必要工具:${NC}"
if [ "$HAS_GIT" = true ]; then
echo -e " git ✅ 已安装 ($(git --version | awk '{print $3}'))"
else
echo " git ❌ 未安装 (将自动安装)"
fi
if [ "$HAS_CURL" = true ]; then
echo " curl ✅ 已安装"
else
echo " curl ❌ 未安装 (将自动安装)"
fi
if [ "$HAS_WGET" = true ]; then
echo " wget ✅ 已安装"
else
echo " wget ❌ 未安装 (将自动安装)"
fi
echo ""
echo " ${CYAN}Docker 环境:${NC}"
if [ "$HAS_DOCKER" = true ]; then
echo -e " docker ✅ 已安装 ($(docker --version | awk '{print $3}' | tr -d ','))"
else
echo " docker ❌ 未安装"
print_error "Docker 未安装,请先安装 Docker"
exit 1
fi
if [ "$CONTAINER_EXISTS" = true ]; then
echo ""
echo " ${CYAN}容器状态:${NC}"
if [ "$CONTAINER_RUNNING" = true ]; then
echo -e " frpc-console ✅ 运行中"
else
echo -e " frpc-console ⏸️ 已停止"
fi
CURRENT_VERSION=$(get_current_version)
[ -n "$CURRENT_VERSION" ] && echo -e " ${CYAN}当前版本:${NC} $CURRENT_VERSION"
fi
echo ""
}
# ---------- 部署计划 ----------
generate_plan() {
PLAN=""
if [ "$NEED_INSTALL_GIT" = true ] || [ "$NEED_INSTALL_CURL" = true ] || [ "$NEED_INSTALL_WGET" = true ]; then
local pkgs=""
[ "$NEED_INSTALL_GIT" = true ] && pkgs="${pkgs} git"
[ "$NEED_INSTALL_CURL" = true ] && pkgs="${pkgs} curl"
[ "$NEED_INSTALL_WGET" = true ] && pkgs="${pkgs} wget"
PLAN="${PLAN} • 安装必要工具:${pkgs}\n"
fi
PLAN="${PLAN} • 拉取 frpc-console 源码 (${BRANCH} 分支)\n"
PLAN="${PLAN} • 构建 Docker 镜像: ${IMAGE_NAME}:${IMAGE_TAG}\n"
PLAN="${PLAN} • 目标版本: ${TARGET_VERSION}\n"
if [ "$CONTAINER_EXISTS" = true ]; then
PLAN="${PLAN} • 停止并删除旧容器\n"
fi
PLAN="${PLAN} • 启动 frpc-console 容器 (端口 ${PORT})"
}
print_deployment_plan() {
print_title
print_subtitle "部署计划"
echo ""
echo -e " ${CYAN}将执行以下操作:${NC}"
echo -e "$(echo -e "$PLAN")"
echo ""
echo -e " ${CYAN}配置信息:${NC}"
echo -e " ────────────────────────────────────"
echo -e " 监听端口 : ${PORT}"
echo -e " 部署目录 : ${DEPLOY_DIR}"
echo -e " 目标版本 : ${TARGET_VERSION}"
echo -e " 镜像标签 : ${IMAGE_TAG}"
echo -e " 源码分支 : ${BRANCH}"
echo -e " ────────────────────────────────────"
if [ "$CONTAINER_EXISTS" = true ]; then
echo ""
echo -e " ${YELLOW}⚠ 检测到已存在的 frpc-console 容器${NC}"
echo -e " 当前版本: ${CURRENT_VERSION}"
echo -e " 目标版本: ${TARGET_VERSION}"
fi
echo ""
}
confirm_deploy() {
if [ "$SKIP_CONFIRM" = true ]; then
echo -e "${GREEN}▶ 已启用 --yes,自动确认${NC}"
return 0
fi
echo -e -n "${CYAN}确认执行? 输入 Y 继续,输入 n 自定义配置 [Y/n]: ${NC}"
read -r CONFIRM </dev/tty
case $CONFIRM in
n|N) return 1 ;;
*) return 0 ;;
esac
}
custom_config() {
print_title
print_subtitle "自定义配置"
echo ""
read -p "请输入监听端口 [${DEFAULT_PORT}]: " INPUT_PORT </dev/tty
PORT=${INPUT_PORT:-$DEFAULT_PORT}
read -p "请输入部署目录 [${DEFAULT_DEPLOY_DIR}]: " INPUT_DEPLOY_DIR </dev/tty
DEPLOY_DIR=${INPUT_DEPLOY_DIR:-$DEFAULT_DEPLOY_DIR}
DATA_DIR="${DEPLOY_DIR}/data"
echo ""
echo -e " ${CYAN}更新后的配置:${NC}"
echo -e " ────────────────────────────────────"
echo -e " 监听端口 : ${PORT}"
echo -e " 部署目录 : ${DEPLOY_DIR}"
echo -e " 数据目录 : ${DATA_DIR}"
echo -e " ────────────────────────────────────"
echo ""
}
# ---------- 执行部署 ----------
do_deploy() {
print_title
print_subtitle "开始部署"
echo ""
# ----- 事务前钩子:备份数据库(仅降级时) -----
BACKUP_DIR=""
if [ -n "$CURRENT_VERSION" ] && [ -n "$TARGET_VERSION" ]; then
CUR_SEMVER=$(echo "$CURRENT_VERSION" | sed -E 's/^([0-9]+\.[0-9]+).*$/\1/')
TGT_SEMVER=$(echo "$TARGET_VERSION" | sed -E 's/^([0-9]+\.[0-9]+).*$/\1/')
if [ "$TGT_SEMVER" \< "$CUR_SEMVER" ] 2>/dev/null; then
print_warn "检测到降级操作: $CURRENT_VERSION$TARGET_VERSION"
echo ""
echo -e "${YELLOW}⚠ 降级可能导致数据不兼容${NC}"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/opt/frpc-console-backups/${TIMESTAMP}_${CHANNEL}"
echo -e "${CYAN}备份目录: ${BACKUP_DIR}${NC}"
read -p "确认执行降级? [y/N]: " CONFIRM_DOWNGRADE </dev/tty
if [[ ! "$CONFIRM_DOWNGRADE" =~ ^[Yy]$ ]]; then
print_info "已取消降级操作"
exit 0
fi
print_step "执行降级前备份..."
mkdir -p "$BACKUP_DIR"
if [ -d "$DEPLOY_DIR" ]; then
cp -r "$DEPLOY_DIR" "$BACKUP_DIR/frpc-console"
print_success "备份完成: $BACKUP_DIR"
else
print_warn "失败,尝试下一个镜像..."
rm -f "$GO_TMP"
print_warn "部署目录不存在,跳过备份"
fi
fi
else
print_info "首次部署,跳过版本比对"
fi
# ----- 安装必要工具 -----
if [ "$NEED_INSTALL_GIT" = true ] || [ "$NEED_INSTALL_CURL" = true ] || [ "$NEED_INSTALL_WGET" = true ]; then
print_step "安装必要工具..."
local pkgs=""
[ "$NEED_INSTALL_GIT" = true ] && pkgs="${pkgs} git"
[ "$NEED_INSTALL_CURL" = true ] && pkgs="${pkgs} curl"
[ "$NEED_INSTALL_WGET" = true ] && pkgs="${pkgs} wget"
case $OS in
opensuse*|suse*|opensuse-tumbleweed|opensuse-slowroll|opensuse-leap)
if [ "$NEED_INSTALL_GIT" = true ]; then
zypper install -y git-core
pkgs=$(echo "$pkgs" | sed -E 's/(^| )git( |$)/ /g' | sed 's/ */ /g' | sed 's/^ //;s/ $//')
fi
[ -n "$pkgs" ] && zypper install -y $pkgs
;;
ubuntu|debian|linuxmint) apt update -qq && apt install -y $pkgs ;;
centos|rhel|fedora|rocky|almalinux) yum install -y $pkgs ;;
alpine) apk add $pkgs ;;
arch|manjaro|endeavouros) pacman -S --needed --noconfirm $pkgs ;;
*) print_error "无法识别包管理器"; exit 1 ;;
esac
print_success "必要工具安装完成"
fi
# ----- 拉取代码 -----
print_step "拉取代码..."
rm -rf "$WORK_DIR"
git clone --depth 1 --branch "$BRANCH" "$REPO_URL" "$WORK_DIR"
cd "$WORK_DIR"
mkdir -p bin static
print_success "代码拉取完成 (分支: ${BRANCH})"
# ----- 停止旧容器 -----
if [ "$CONTAINER_EXISTS" = true ]; then
print_step "停止旧容器..."
if [ "$CONTAINER_RUNNING" = true ]; then
docker stop frpc-console 2>/dev/null || true
fi
docker rm frpc-console 2>/dev/null || true
print_success "旧容器已清理"
fi
# ----- 准备部署目录 -----
print_step "准备部署目录..."
mkdir -p "$DEPLOY_DIR"
mkdir -p "$DATA_DIR"
# ----- 检测并迁移旧版本文件(从根目录迁移到 data/)-----
print_step "检测旧版本文件..."
OLD_DB="${DEPLOY_DIR}/frpc-console.db"
OLD_TOML="${DEPLOY_DIR}/frpc.toml"
OLD_LOG="${DEPLOY_DIR}/frpc.log"
OLD_PID="${DEPLOY_DIR}/frpc.pid"
OLD_VERSION="${DEPLOY_DIR}/version.ini"
NEW_DB="${DATA_DIR}/frpc-console.db"
if [ -f "$OLD_DB" ] && [ ! -f "$NEW_DB" ]; then
print_warn "检测到旧版本数据库文件在根目录,将迁移到 data/ 子目录"
BACKUP_OLD_DIR="${DEPLOY_DIR}/.old_backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_OLD_DIR"
for file in frpc-console.db frpc.toml frpc.log frpc.pid version.ini; do
if [ -f "${DEPLOY_DIR}/${file}" ]; then
cp "${DEPLOY_DIR}/${file}" "${BACKUP_OLD_DIR}/" 2>/dev/null || true
print_info " 已备份: ${file}"
fi
done
if [ "$DOWNLOADED" = false ]; then
print_error "所有镜像源均下载失败"
exit 1
for file in frpc-console.db frpc.toml frpc.log frpc.pid version.ini; do
if [ -f "${DEPLOY_DIR}/${file}" ]; then
cp "${DEPLOY_DIR}/${file}" "${DATA_DIR}/" 2>/dev/null || true
print_info " 已迁移: ${file} → data/"
fi
done
print_success "旧文件已迁移到 data/ 目录"
print_info "旧文件备份位置: ${BACKUP_OLD_DIR}"
print_info "确认服务正常后,可手动删除备份目录"
else
print_info "未检测到需要迁移的旧文件"
fi
# ----- 构建 Docker 镜像 -----
print_step "构建 Docker 镜像..."
docker build --no-cache \
-t "${IMAGE_NAME}:${IMAGE_TAG}" \
.
if [ $? -ne 0 ]; then
print_error "Docker 构建失败"
exit 1
fi
print_success "Docker 镜像构建完成: ${IMAGE_NAME}:${IMAGE_TAG}"
# 验证镜像内容
print_step "验证镜像内容..."
if docker run --rm --entrypoint ls "${IMAGE_NAME}:${IMAGE_TAG}" -l /app/frpc-console 2>/dev/null; then
print_success "二进制文件存在于镜像中"
else
print_error "镜像中缺少 /app/frpc-console"
exit 1
fi
# 标记通道标签
if [ "$CHANNEL" = "lts" ]; then
docker tag "${IMAGE_NAME}:${IMAGE_TAG}" "${IMAGE_NAME}:lts"
print_info "已标记 ${IMAGE_NAME}:lts"
else
docker tag "${IMAGE_NAME}:${IMAGE_TAG}" "${IMAGE_NAME}:preview"
print_info "已标记 ${IMAGE_NAME}:preview"
fi
# ----- 启动新容器 -----
print_step "启动 frpc-console 容器..."
docker run -d \
--name frpc-console \
--restart=always \
--network host \
-v ${DEPLOY_DIR}/data:/app/data \
-e PORT=${PORT} \
-e TZ=Asia/Shanghai \
${IMAGE_NAME}:${IMAGE_TAG}
if docker ps | grep -q frpc-console; then
print_success "容器启动成功!"
else
print_error "容器启动失败,请检查日志: docker logs frpc-console"
exit 1
fi
# ----- 写入版本文件 -----
print_step "写入版本文件..."
echo "$TARGET_VERSION" > "${DEPLOY_DIR}/data/version.ini"
print_success "版本写入: ${TARGET_VERSION}"
# ----- 检查 frpc 子进程(基于 PID 文件)-----
print_step "检查 frpc 状态..."
sleep 3
PID_FILE="${DEPLOY_DIR}/data/frpc.pid"
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE" 2>/dev/null | tr -d ' \n')
if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
print_success "frpc 进程运行正常 (PID: $PID)"
else
print_warn "frpc 进程未运行(PID 文件存在但进程已退出,可能配置为空)"
fi
else
print_warn "frpc 进程未运行(PID 文件不存在,请导入 TOML 后重试)"
fi
# ----- 事务后钩子:检测数据库 -----
print_step "验证数据库状态..."
if docker exec frpc-console sqlite3 /app/data/frpc-console.db "SELECT COUNT(*) FROM users;" 2>/dev/null | grep -q "^[0-9]"; then
print_success "数据库可用"
else
print_warn "数据库为空或不可用,请通过 WebUI 注册管理员账户"
fi
# ----- 验证版本 -----
print_step "验证版本..."
sleep 1
CONTAINER_VERSION=$(docker exec frpc-console cat /app/data/version.ini 2>/dev/null | grep -v "^[;#]" | head -1 | tr -d '\n' || echo "unknown")
echo -e " 容器版本: ${CONTAINER_VERSION}"
echo -e " 目标版本: ${TARGET_VERSION}"
if [ "$CONTAINER_VERSION" = "$TARGET_VERSION" ]; then
print_success "版本写入成功"
else
print_warn "版本不匹配,请检查"
fi
# ----- 清理旧镜像 -----
print_step "清理旧镜像..."
CURRENT_IMAGE_ID=$(docker images -q "${IMAGE_NAME}:${IMAGE_TAG}" 2>/dev/null)
if [ -n "$CURRENT_IMAGE_ID" ]; then
ALL_IMAGES=$(docker images "${IMAGE_NAME}:*" --format "{{.ID}} {{.CreatedAt}}" 2>/dev/null | sort -k2 -r | awk '{print $1}')
COUNTER=0
TO_DELETE=""
for IMG_ID in $ALL_IMAGES; do
if [ "$IMG_ID" = "$CURRENT_IMAGE_ID" ]; then
continue
fi
COUNTER=$((COUNTER + 1))
if [ $COUNTER -le $KEEP_IMAGES ]; then
continue
fi
TO_DELETE="$TO_DELETE $IMG_ID"
done
if [ -n "$TO_DELETE" ]; then
docker rmi -f $TO_DELETE 2>/dev/null || true
print_info "已清理旧镜像"
else
print_info "无需清理,镜像数量未超过保留策略"
fi
fi
# 安装 Go
rm -rf /usr/local/go
tar -C /usr/local -xzf "$GO_TMP"
export PATH=$PATH:/usr/local/go/bin
echo 'export PATH=$PATH:/usr/local/go/bin' > /etc/profile.d/go.sh
# ----- 备份目录提示 -----
if [ -n "$BACKUP_DIR" ]; then
echo ""
print_warn "降级前数据已备份到: $BACKUP_DIR"
echo " 如需回退: cp -r $BACKUP_DIR/frpc-console/* $DEPLOY_DIR/"
fi
# 配置 Go 代理
/usr/local/go/bin/go env -w GOPROXY=https://goproxy.cn,direct
/usr/local/go/bin/go env -w GOPRIVATE=git.whitetop.xyz
# ----- 清理临时文件 -----
print_step "清理临时文件..."
rm -rf "$WORK_DIR"
print_success "临时文件已清理"
print_success "Go ${GO_VERSION} (${GO_ARCH}) 安装完成"
else
print_success "Go 已安装: $(go version | awk '{print $3}') (架构: $(go env GOARCH))"
go env -w GOPROXY=https://goproxy.cn,direct 2>/dev/null || true
go env -w GOPRIVATE=git.whitetop.xyz 2>/dev/null || true
fi
# ---------- 5. 检查 Docker ----------
print_step "检查 Docker 环境..."
if ! command -v docker &> /dev/null; then
print_error "Docker 未安装,请先安装 Docker"
# ----- 输出 -----
print_title
print_success "frpc-console 部署完成!"
print_title
echo ""
echo " 快速安装:"
echo " curl -fsSL https://get.docker.com | bash"
echo " systemctl enable --now docker"
echo -e " ${CYAN}📍 访问地址:${NC} http://$(hostname -I | awk '{print $1}'):${PORT}"
echo -e " ${CYAN}📂 数据目录:${NC} ${DEPLOY_DIR}"
echo -e " ${CYAN}🐳 容器名称:${NC} frpc-console"
echo -e " ${CYAN}🏷️ 版本:${NC} ${TARGET_VERSION}"
echo -e " ${CYAN}🌿 分支:${NC} ${BRANCH}"
echo ""
exit 1
else
print_success "Docker 已安装: $(docker --version | awk '{print $3}' | tr -d ',')"
fi
echo -e " ${CYAN}常用命令:${NC}"
echo " docker logs frpc-console # 查看日志"
echo " docker restart frpc-console # 重启服务"
echo " cat ${DEPLOY_DIR}/data/version.ini # 查看当前版本"
echo ""
echo -e " ${YELLOW}首次访问需要注册管理员账户${NC}"
echo ""
print_title
}
# ---------- 6. 交互式配置 ----------
print_step "部署配置"
read -p "监听端口 [${DEFAULT_PORT}]: " PORT
PORT=${PORT:-$DEFAULT_PORT}
# ---------- 主流程 ----------
main() {
clear 2>/dev/null || true
parse_args "$@"
check_root
read -p "部署目录 [${DEPLOY_DIR}]: " DEPLOY_DIR_INPUT
DEPLOY_DIR=${DEPLOY_DIR_INPUT:-$DEPLOY_DIR}
DATA_DIR="${DEPLOY_DIR}/data"
print_step "检测环境..."
detect_os
detect_arch
check_tools
check_container
print_info "端口: $PORT"
print_info "部署目录: $DEPLOY_DIR"
print_info "数据目录: $DATA_DIR"
select_channel
generate_target_version "$CHANNEL" "$BRANCH"
# ---------- 7. 拉取代码 ----------
print_step "拉取代码..."
rm -rf "$WORK_DIR"
git clone --depth 1 --branch "$BRANCH" "$REPO_URL" "$WORK_DIR"
cd "$WORK_DIR"
CURRENT_VERSION=""
if [ "$CONTAINER_EXISTS" = true ]; then
CURRENT_VERSION=$(get_current_version)
fi
# 确保目录存在
mkdir -p bin static
print_environment_summary
print_success "代码拉取完成"
if [ "$CHECK_ONLY" = true ]; then
print_info "环境检测完成(--check 模式)"
exit 0
fi
# ---------- 8. 修复 go.mod 版本(防止 toolchain 下载) ----------
print_step "检查 go.mod..."
if grep -q "go 1.26" go.mod 2>/dev/null; then
print_warn "检测到 go.mod 版本过高,自动降级到 go 1.21"
sed -i 's/go 1.26.*/go 1.21/' go.mod
fi
if [ "$HAS_DOCKER" = false ]; then
print_error "Docker 未安装"
exit 1
fi
# ---------- 9. 下载依赖 ----------
print_step "下载 Go 依赖..."
go mod download
print_success "依赖下载完成"
generate_plan
print_deployment_plan
# ---------- 10. 编译 ----------
print_step "编译 frpc-console..."
CGO_ENABLED=0 GOOS=linux go build \
-ldflags="-s -w" \
-o frpc-console .
if ! confirm_deploy; then
custom_config
generate_plan
print_deployment_plan
if ! confirm_deploy; then
print_info "已取消部署"
exit 0
fi
fi
if [ -f "frpc-console" ]; then
SIZE=$(du -h frpc-console | cut -f1)
print_success "编译完成 ($SIZE)"
else
print_error "编译失败"
exit 1
fi
if [ "$DRY_RUN" = true ]; then
print_info "演练模式(--dry-run"
exit 0
fi
# ---------- 11. 准备部署目录 ----------
print_step "准备部署目录..."
mkdir -p "$DEPLOY_DIR"
mkdir -p "$DATA_DIR"
do_deploy
}
# 如果已有数据,保留;否则创建空占位
if [ ! -f "$DATA_DIR/frpc-console.db" ]; then
touch "$DATA_DIR/frpc-console.db"
print_info "新数据目录已创建"
else
print_info "已有数据目录,保留现有数据"
fi
cp frpc-console "$DEPLOY_DIR/"
print_success "二进制已复制到 $DEPLOY_DIR"
# ---------- 12. 构建 Docker 镜像 ----------
print_step "构建 Docker 镜像..."
docker build -t "${IMAGE_NAME}:latest" .
print_success "Docker 镜像构建完成: ${IMAGE_NAME}:latest"
# ---------- 13. 停止旧容器 ----------
print_step "检查旧容器..."
if docker ps -a --format '{{.Names}}' | grep -q "^frpc-console$"; then
print_warn "发现旧容器,正在停止并删除..."
docker stop frpc-console 2>/dev/null || true
docker rm frpc-console 2>/dev/null || true
print_success "旧容器已清理"
fi
# ---------- 14. 启动新容器 ----------
print_step "启动 frpc-console 容器..."
docker run -d \
--name frpc-console \
--restart=always \
--network host \
-v ${DATA_DIR}:/app/data \
-e PORT=9300 \
-e TZ=Asia/Shanghai \
${IMAGE_NAME}:latest
if docker ps | grep -q frpc-console; then
print_success "容器启动成功!"
else
print_error "容器启动失败,请检查日志: docker logs frpc-console"
exit 1
fi
# ---------- 15. 检查 frpc 子进程 ----------
print_step "检查 frpc 状态..."
sleep 3
if docker exec frpc-console ps aux 2>/dev/null | grep -q "[f]rpc -c"; then
print_success "frpc 进程运行正常"
else
print_warn "frpc 进程未运行(可能配置为空,请在 WebUI 中导入 TOML"
fi
# ---------- 16. 清理临时文件 ----------
print_step "清理临时文件..."
rm -rf "$WORK_DIR"
print_success "临时文件已清理"
# ---------- 17. 输出信息 ----------
echo ""
echo "=========================================="
echo -e "${GREEN}✅ frpc-console 部署完成!${NC}"
echo "=========================================="
echo ""
echo "📍 访问地址: http://$(hostname -I | awk '{print $1}'):${PORT}"
echo "📂 数据目录: ${DATA_DIR}"
echo "🐳 容器名称: frpc-console"
echo ""
echo "常用命令:(可提前复制,如果有宝塔或者1panel那当我没说)"
echo " docker logs frpc-console # 查看日志"
echo " docker restart frpc-console # 重启服务"
echo " docker stop frpc-console # 停止服务"
echo " docker start frpc-console # 启动服务"
echo ""
echo "首次访问需要注册管理员账户"
echo "=========================================="
main "$@"
+109 -42
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"embed"
"fmt"
"io"
"log"
"os"
"os/exec"
@@ -24,16 +25,12 @@ var FrpcTemplateContent string
var (
cachedFrpcPath string
frpcPathMutex sync.Mutex
frpsPathMutex sync.Mutex
)
// getFrpcPath 获取 frpc 路径,优先级:
// 1. 当前目录 ./bin/<platform> (便于用户手动管理 frpc 版本)
// 2. embed 解压到 /tmp (便于开箱即用)
// 3. 系统 PATH 中的 frpc (降级方案)
func getFrpcPath() (string, error) {
frpcPathMutex.Lock()
defer frpcPathMutex.Unlock()
frpsPathMutex.Lock()
defer frpsPathMutex.Unlock()
if cachedFrpcPath != "" {
if _, err := os.Stat(cachedFrpcPath); err == nil {
@@ -46,14 +43,12 @@ func getFrpcPath() (string, error) {
switch {
case runtime.GOOS == "windows" && runtime.GOARCH == "amd64":
fileName = "frpc_windows_amd64.exe"
case runtime.GOOS == "windows" && runtime.GOARCH == "386":
fileName = "frpc_windows_386.exe"
case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
fileName = "frpc_linux_amd64"
case runtime.GOOS == "linux" && runtime.GOARCH == "arm64":
fileName = "frpc_linux_arm64"
case runtime.GOOS == "linux" && runtime.GOARCH == "arm":
fileName = "frpc_linux_armv7"
fileName = "frpc_linux_arm_hf"
default:
path, err := exec.LookPath("frpc")
if err == nil {
@@ -63,14 +58,12 @@ func getFrpcPath() (string, error) {
return "", fmt.Errorf("不支持的平台: %s/%s", runtime.GOOS, runtime.GOARCH)
}
// 优先级1:本地 ./bin/
localPath := filepath.Join(".", "bin", fileName)
if _, err := os.Stat(localPath); err == nil {
cachedFrpcPath = localPath
return localPath, nil
}
// 优先级2:embed 解压到临时目录
data, err := embeddedFrpc.ReadFile("bin/" + fileName)
if err == nil {
tmpPath := filepath.Join(os.TempDir(), "frpc")
@@ -87,17 +80,15 @@ func getFrpcPath() (string, error) {
}
}
// 优先级3:系统 PATH
path, err := exec.LookPath("frpc")
if err == nil {
cachedFrpcPath = path
return path, nil
}
return "", fmt.Errorf("未找到 frpc 文件 (本地 bin/、embed、PATH 均无)")
return "", fmt.Errorf("未找到 frpc 文件")
}
// GenerateFrpcConfig 生成 frpc.toml
func GenerateFrpcConfig() error {
cfg, err := GetGlobalConfig()
if err != nil {
@@ -118,12 +109,19 @@ func GenerateFrpcConfig() error {
data := struct {
*GlobalConfig
Proxies []Proxy
Proxies []Proxy
WireProtocolLine string
}{
GlobalConfig: cfg,
Proxies: activeProxies,
}
if cfg.WireProtocolV2 {
data.WireProtocolLine = `wireProtocol = "v2"`
} else {
data.WireProtocolLine = ""
}
var tmplContent string
if _, err := os.Stat("frpc.tmpl"); err == nil {
content, readErr := os.ReadFile("frpc.tmpl")
@@ -146,16 +144,20 @@ func GenerateFrpcConfig() error {
return fmt.Errorf("渲染模板失败: %w", err)
}
if err := os.WriteFile("./frpc.toml", buf.Bytes(), 0644); err != nil {
// 所有文件写入 ./data/ 目录
if err := os.MkdirAll("./data", 0755); err != nil {
return fmt.Errorf("创建 data 目录失败: %w", err)
}
if err := os.WriteFile("./data/frpc.toml", buf.Bytes(), 0644); err != nil {
return fmt.Errorf("写入配置文件失败: %w", err)
}
return nil
}
// isFrpcRunning 通过 PID 文件检查 frpc 是否在运行
func isFrpcRunning() bool {
pidData, err := os.ReadFile("./frpc.pid")
pidData, err := os.ReadFile("./data/frpc.pid")
if err != nil {
return false
}
@@ -165,7 +167,6 @@ func isFrpcRunning() bool {
}
if runtime.GOOS == "windows" {
// Windows 用 tasklist 检查
cmd := exec.Command("tasklist", "/FI", "PID eq", strconv.Itoa(pid))
output, err := cmd.CombinedOutput()
if err != nil {
@@ -174,7 +175,6 @@ func isFrpcRunning() bool {
return strings.Contains(string(output), strconv.Itoa(pid))
}
// Linux/Unix: 用 kill 0 检查进程是否存在
process, err := os.FindProcess(pid)
if err != nil {
return false
@@ -182,14 +182,17 @@ func isFrpcRunning() bool {
return process.Signal(syscall.Signal(0)) == nil
}
// StartFrpc 启动 frpc(独立进程,脱离父进程)
func StartFrpc() error {
frpcPath, err := getFrpcPath()
if err != nil {
return fmt.Errorf("获取 frpc 路径失败: %w", err)
}
if _, err := os.Stat("./frpc.toml"); os.IsNotExist(err) {
if err := os.MkdirAll("./data", 0755); err != nil {
return fmt.Errorf("创建 data 目录失败: %w", err)
}
if _, err := os.Stat("./data/frpc.toml"); os.IsNotExist(err) {
if err := GenerateFrpcConfig(); err != nil {
return fmt.Errorf("生成配置文件失败: %w", err)
}
@@ -199,17 +202,13 @@ func StartFrpc() error {
return nil
}
// 清理旧的 PID 文件
os.Remove("./frpc.pid")
os.Remove("./data/frpc.pid")
cmd := exec.Command(frpcPath, "-c", "./frpc.toml")
cmd := exec.Command(frpcPath, "-c", "./data/frpc.toml")
setWindowHide(cmd)
// ✅ 设置进程属性(Unix: Setsid 脱离父进程,Windows: 不处理)
setSysProcAttr(cmd)
// 把输出重定向到日志文件
logFile, err := os.OpenFile("./frpc.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
logFile, err := os.OpenFile("./data/frpc.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return fmt.Errorf("打开日志文件失败: %w", err)
}
@@ -220,29 +219,25 @@ func StartFrpc() error {
return fmt.Errorf("启动 frpc 失败: %w", err)
}
// ✅ 保存 PID 到文件
if err := os.WriteFile("./frpc.pid", []byte(fmt.Sprintf("%d", cmd.Process.Pid)), 0644); err != nil {
if err := os.WriteFile("./data/frpc.pid", []byte(fmt.Sprintf("%d", cmd.Process.Pid)), 0644); err != nil {
return fmt.Errorf("保存 PID 失败: %w", err)
}
return nil
}
// StopFrpc 停止 frpc(通过 PID 文件精准杀进程)
func StopFrpc() error {
if runtime.GOOS == "windows" {
cmd := exec.Command("taskkill", "/F", "/IM", "frpc.exe")
if err := cmd.Run(); err != nil && !strings.Contains(err.Error(), "not found") {
return fmt.Errorf("停止 frpc 失败: %w", err)
}
os.Remove("./frpc.pid")
os.Remove("./data/frpc.pid")
return nil
}
// Linux: 读取 PID 文件精准杀进程
pidData, err := os.ReadFile("./frpc.pid")
pidData, err := os.ReadFile("./data/frpc.pid")
if err != nil {
// 降级到 pkill
cmd := exec.Command("pkill", "-f", "frpc")
if err := cmd.Run(); err != nil && !strings.Contains(err.Error(), "no process") {
return fmt.Errorf("停止 frpc 失败: %w", err)
@@ -253,7 +248,7 @@ func StopFrpc() error {
pid, _ := strconv.Atoi(strings.TrimSpace(string(pidData)))
process, err := os.FindProcess(pid)
if err != nil {
os.Remove("./frpc.pid")
os.Remove("./data/frpc.pid")
return nil
}
@@ -261,16 +256,14 @@ func StopFrpc() error {
return fmt.Errorf("杀死进程失败: %w", err)
}
os.Remove("./frpc.pid")
os.Remove("./data/frpc.pid")
return nil
}
// GetFrpcStatus 获取 frpc 运行状态(通过 PID 文件)
func GetFrpcStatus() (bool, error) {
return isFrpcRunning(), nil
}
// ReloadFrpc 热加载,失败时自动降级为重启
func ReloadFrpc() error {
running := isFrpcRunning()
if !running {
@@ -282,7 +275,7 @@ func ReloadFrpc() error {
return fmt.Errorf("获取 frpc 路径失败: %w", err)
}
cmd := exec.Command(frpcPath, "reload", "-c", "./frpc.toml")
cmd := exec.Command(frpcPath, "reload", "-c", "./data/frpc.toml")
_, err = cmd.CombinedOutput()
if err != nil {
log.Printf("⚠️ 热加载失败 (%v),自动降级为重启 frpc", err)
@@ -296,3 +289,77 @@ func ReloadFrpc() error {
}
return nil
}
// readTailLog 读取文件末尾 n 行
func readTailLog(filePath string, n int) ([]string, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return nil, err
}
fileSize := info.Size()
if fileSize == 0 {
return []string{}, nil
}
const chunkSize = 4096
var lines []string
var leftover []byte
offset := fileSize
for len(lines) < n && offset > 0 {
readSize := chunkSize
if offset < int64(chunkSize) {
readSize = int(offset)
}
offset -= int64(readSize)
buf := make([]byte, readSize)
_, err := file.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return nil, err
}
data := append(buf, leftover...)
leftover = nil
start := 0
for i := len(data) - 1; i >= 0; i-- {
if data[i] == '\n' {
if i+1 < len(data) {
line := string(data[i+1:])
if line != "" {
lines = append([]string{line}, lines...)
if len(lines) >= n {
break
}
}
}
start = i
}
}
if len(lines) < n && start > 0 {
leftover = data[:start]
}
}
if len(lines) < n && len(leftover) > 0 {
parts := strings.Split(string(leftover), "\n")
for i := len(parts) - 1; i >= 0; i-- {
if parts[i] != "" {
lines = append([]string{parts[i]}, lines...)
if len(lines) >= n {
break
}
}
}
}
return lines, nil
}
+3
View File
@@ -15,6 +15,9 @@ tcpMuxKeepaliveInterval = {{.TcpMuxKeepalive}}
heartbeatInterval = {{.HeartbeatInterval}}
heartbeatTimeout = {{.HeartbeatTimeout}}
poolCount = {{.PoolCount}}
{{if .WireProtocolLine}}
{{.WireProtocolLine}}
{{end}}
[webServer]
addr = "127.0.0.1:7400"
+147
View File
@@ -0,0 +1,147 @@
## 📦 二进制安装指南
> 直接下载编译好的二进制文件,开箱即用,无需 Docker、无需 Go 环境。
### 一、📥 下载
从 [Releases](https://git.whitetop.xyz/lxh2875931338/frpc-console/releases) 页面下载对应平台的二进制文件:
| 平台 | 文件名 |
|---|---|
| Linux x86-64 | `frpc-console-linux-amd64.tar.gz` |
| Linux ARM64 | `frpc-console-linux-arm64.tar.gz` |
| Windows x86-64 | `frpc-console-windows-amd64.zip` |
### 二、🐧 Linux 部署
**1. 解压并放好**
```bash
tar -xzf frpc-console-linux-amd64.tar.gz
sudo mv frpc-console-linux-amd64 /usr/local/bin/frpc-console
sudo chmod +x /usr/local/bin/frpc-console
```
**2. 直接运行**
```bash
./frpc-console
```
默认监听 `http://localhost:9300`
**3. 注册为 systemd 服务(推荐,开机自启)**
创建服务文件:
```bash
sudo nano /etc/systemd/system/frpc-console.service
```
写入:
```ini
[Unit]
Description=frpc-console
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/frpc-console
ExecStart=/usr/local/bin/frpc-console
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
```
启动并启用:
```bash
sudo systemctl daemon-reload
sudo systemctl enable frpc-console
sudo systemctl start frpc-console
sudo systemctl status frpc-console
```
### 三、🪟 Windows 部署
**1. 解压**
`frpc-console-windows-amd64.zip` 解压到目标文件夹,比如 `C:\frpc-console\`
**2. 直接运行**
双击 `frpc-console.exe`,或打开命令行:
```cmd
cd C:\frpc-console
frpc-console.exe
```
默认监听 `http://localhost:9300`
**3. 后台运行(隐藏窗口)**
方式一:使用 `start /b`
```cmd
start /b frpc-console.exe
```
方式二:使用 `nssm` 注册为 Windows 服务
```cmd
nssm install frpc-console
# 按提示填写路径
nssm start frpc-console
```
### 四、🚀 首次访问
启动后,浏览器打开:
```
http://localhost:9300
```
首次访问会自动跳转到注册页面,填写用户名和密码,完成管理员账户创建。
登录后,在「隧道列表」页面点击「导入 TOML」,即可将现有的 `frpc.toml` 迁移到 WebUI 中管理。
### 五、📂 数据目录说明
默认情况下,数据文件会生成在与二进制同级的目录下:
| 文件 | 说明 |
|---|---|
| `frpc-console.db` | SQLite 数据库 |
| `frpc.toml` | 生成的 frpc 配置文件 |
| `frpc.log` | frpc 运行日志 |
| `frpc.pid` | frpc 进程 PIDLinux |
建议将数据目录单独存放,便于备份和迁移。
### 六、🔄 升级
下载新版本二进制,覆盖旧文件,重启服务即可。数据文件会自动保留,无需额外操作。
**Linux systemd 升级:**
```bash
sudo systemctl stop frpc-console
sudo cp frpc-console-linux-amd64 /usr/local/bin/frpc-console
sudo systemctl start frpc-console
```
**Windows 升级:**
停止旧进程,替换 `frpc-console.exe`,重新运行。
+139
View File
@@ -0,0 +1,139 @@
## 🐳 Docker 版安装指南
> 推荐方式:一键脚本自动部署,无需手动编译,无需安装 Go 环境。</br>
> ⚠️ **注意**:Docker 版直接从源码构建,使用的是当前 `main` 分支的最新代码,更新进度会远快于 Release 版本。⚠️</br>
> 如需使用特定版本(如 LTS),请查看 [Releases](https://git.whitetop.xyz/lxh2875931338/frpc-console/releases) 确认版本号,并通过二进制方式部署指定版本。
### 一、📥 前置条件
- 已安装 Docker(必须)
- 已安装 curl / wget(脚本会自动检查并安装)
- 操作系统:Linuxx86_64 / ARM64 / ARMv7 均可)
### 二、🚀 一键部署(推荐)
在目标 Linux 服务器上执行:
```bash
curl -sSL https://git.whitetop.xyz/lxh2875931338/frpc-console/raw/main/deploy.sh | sudo bash
```
或手动下载执行:
```bash
wget https://git.whitetop.xyz/lxh2875931338/frpc-console/raw/main/deploy.sh
chmod +x deploy.sh
sudo bash deploy.sh
```
### 三、⚙️ 脚本自动完成内容
| 步骤 | 说明 |
|---|---|
| 检测系统 | 自动识别 OpenSUSE(猫猫特有的夹带私货) / Ubuntu / Debian / CentOS / Alpine |
| 检测 CPU 架构 | 自动适配 x86_64 / ARM64 / ARMv7 |
| 安装依赖 | git / curl / wget(如未安装) |
| 安装 Go | 从国内镜像下载,自动配置代理 |
| 拉取源码 | 从 Gitea 仓库克隆最新代码 |
| 编译二进制 | 根据当前架构编译 Linux 版 |
| 构建 Docker 镜像 | 使用源码中的 Dockerfile 构建 |
| 启动容器 | 挂载数据卷,开机自启 |
### 四、📂 数据持久化
脚本默认将数据存储在 `/opt/frpc-console/data/`
| 文件 | 说明 |
|---|---|
| `frpc-console.db` | SQLite 数据库(用户、隧道、配置) |
| `frpc.toml` | 生成的 frpc 配置文件 |
| `frpc.log` | frpc 运行日志 |
| `frpc.pid` | frpc 进程 PID |
升级或重建容器时,数据自动保留,不会丢失。
### 五、🔄 升级
**方式一:重新运行脚本**
```bash
sudo bash deploy.sh
```
脚本会自动停止旧容器、拉取最新代码、重新编译并启动新容器,数据卷保持不变。
**方式二:手动更新**
```bash
# 停止旧容器
docker stop frpc-console
docker rm frpc-console
# 重新运行 deploy.sh
sudo bash deploy.sh
```
### 六、🧹 常用命令
```bash
# 查看日志
docker logs -f frpc-console
# 查看 frpc 子进程状态
docker exec frpc-console ps aux | grep frpc
# 重启容器
docker restart frpc-console
# 停止容器
docker stop frpc-console
# 启动容器
docker start frpc-console
```
### 七、🌐 访问地址
部署完成后,浏览器打开:
```
http://你的服务器IP:9300
```
首次访问会自动跳转到注册页面,填写用户名和密码,完成管理员账户创建。
登录后,在「隧道列表」页面点击「导入 TOML」,即可将现有的 `frpc.toml` 迁移到 WebUI 中管理。
### 八、📌 手动部署(不使用脚本)
如果你已有源码,或想自行定制:
```bash
# 1. 克隆代码
git clone https://git.whitetop.xyz/lxh2875931338/frpc-console.git
cd frpc-console
# 2. 构建镜像
docker build -t frpc-console:latest .
# 3. 创建数据目录
mkdir -p /opt/frpc-console/data
# 4. 启动容器
docker run -d \
--name frpc-console \
--restart=always \
--network host \
-v /opt/frpc-console/data:/app\
-e PORT=9300 \
-e TZ=Asia/Shanghai \
frpc-console:latest
```
+15 -3
View File
@@ -2,15 +2,29 @@ package main
import (
"log"
"os"
"strings"
"time"
)
func main() {
// 确保 data 目录存在
if err := os.MkdirAll("./data", 0755); err != nil {
log.Printf("⚠️ 创建 data 目录失败: %v", err)
}
// 读取 version.ini 显示版本
if data, err := os.ReadFile("./data/version.ini"); err == nil {
version := strings.TrimSpace(string(data))
log.Printf("📌 版本: %s", version)
} else {
log.Printf("📌 版本: (未记录)")
}
if err := InitDB(); err != nil {
log.Fatal("❌ 数据库初始化失败:", err)
}
// 启动时生成配置并启动 frpc
if err := GenerateFrpcConfig(); err != nil {
log.Println("⚠️ 生成配置文件失败:", err)
}
@@ -19,7 +33,6 @@ func main() {
log.Println("⚠️ 启动 frpc 失败:", err)
}
// ✅ 启动 Watchdog:每 30 秒检查一次 frpc 状态,挂了自动重启
go startWatchdog()
r := SetupRouter()
@@ -32,7 +45,6 @@ func main() {
}
}
// Watchdog 协程:定期检查 frpc 是否存活
func startWatchdog() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
+116 -66
View File
@@ -1,16 +1,21 @@
# 🚀 frpc-console
<p align="center">
<img src="static/logo.svg" alt="frpc-console" width="360" />
</p>
# frpc-console
> 轻量级 frpc 管理面板 —— 为你的内网穿透插上翅膀
[![Release](https://img.shields.io/gitea/v/release/lxh2875931338/frpc-console?gitea_url=https://git.whitetop.xyz)](https://git.whitetop.xyz/lxh2875931338/frpc-console/releases)
[![Go Version](https://img.shields.io/badge/Go-1.21+-00ADD8?style=flat&logo=go)](https://golang.org/)
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Release](https://img.shields.io/github/v/release/lxh2875931338/frpc-console)](https://git.whitetop.xyz/lxh2875931338/frpc-console/releases)
---
## 📖 简介
**frpc-console** 是一个专为 [frp](https://github.com/fatedier/frp) 设计的轻量级管理工具。它解决了 frpc 配置文件手动维护繁琐、缺少可视化界面的痛点,让你在浏览器中轻松管理所有隧道。
**frpc-console** 是一个专为 [frp](https://github.com/fatedier/frp) 设计的轻量级管理工具。本项目旨在以无限接近原生占用的情况下,实现完全图形化的控制工具(毕竟 WebUI 也算图形化,对吧?)
### ✨ 核心特性
@@ -26,60 +31,59 @@
## 🚀 快速开始
### 方式一:直接运行二进制
### 🐧 二进制安装(推荐)
从 [Releases](https://git.whitetop.xyz/lxh2875931338/frpc-console/releases) 下载对应平台版本:
适用于 Linux / Windows,无需 Docker,单文件运行。
👉 详见:[二进制安装指南](./INSTALL_BINARY.md)
### 🐳 Docker 部署(一键脚本)
适用于 Linux 服务器,自动编译 + 自动部署。
```bash
# Linux / macOS
chmod +x frpc-console
./frpc-console
# Windows
frpc-console.exe
curl -sSL https://git.whitetop.xyz/lxh2875931338/frpc-console/raw/main/deploy.sh | sudo bash
```
首次启动会在终端提示设置管理员账户,之后访问 http://localhost:8080 即可。
👉 详见:[Docker 安装指南](./INSTALL_DOCKER.md)
### 方式二:Docker 运行
### 🔧 源码编译
适合开发者或需要自定义配置的用户。
```bash
docker run -d \
--name frpc-console \
-p 9300:9300 \
-v ./data:/app/data \
lxh2875931338/frpc-console:latest
```
### 方式三:源码编译
```bash
git clone https://github.com/lxh2875931338/frpc-console.git
git clone https://git.whitetop.xyz/lxh2875931338/frpc-console.git
cd frpc-console
go mod tidy
go build -o frpc-console .
./frpc-console
```
首次访问 `http://localhost:9300` 注册管理员账户,然后导入你的 `frpc.toml` 即可开始使用。
---
## 🗂️ 项目结构
```txt
frpc-console/
├── main.go # 入口
├── api.go # HTTP 路由 & Handler
├── db.go # SQLite 数据库操作
├── auth.go # JWT 认证 & 密码管理
├── frp.go # frpc 管理核心逻辑
├── toml_parser.go # TOML 解析器
├── static/ # 前端静态资源
├── main.go # 入口
├── api.go # HTTP 路由 & Handler
├── db.go # SQLite 数据库操作
├── auth.go # JWT 认证 & 密码管理
├── frp.go # frpc 管理核心逻辑
├── toml_parser.go # TOML 解析器
├── static/ # 前端静态资源
│ ├── index.html
│ ├── app.js
│ ├── style-1.css # 全局基础样式
│ ├── style-2.css # 登录页样式
── style-3.css # 主界面样式
├── bin/ # 内嵌 frpc 二进制 (多平台)
│ ├── style-1.css # 全局基础样式
│ ├── style-2.css # 登录页样式
── style-3.css # 主界面样式
└── style-4.css
├── bin/ # 内嵌 frpc 二进制 (多平台)
│ ├── frpc_windows_amd64.exe
│ ├── frpc_linux_amd64
── frpc_linux_arm64
── frpc_linux_arm64
│ └── frpc_linux_arm_hf
├── frpc.tmpl # frpc 配置模板
├── Dockerfile
└── go.mod
@@ -96,9 +100,9 @@ frpc-console/
### 数据存储
· 数据库文件:./frpc-console.db
· frpc 配置文件:./frpc.toml
· frpc 日志文件:./frpc.log
· 数据库文件:./frpc-console.db</br>
· frpc 配置文件:./frpc.toml</br>
· frpc 日志文件:./frpc.log</br>
---
@@ -123,17 +127,6 @@ go build -ldflags="-s -w" -o frpc-console .
前端使用 Vue 3 CDN + Naive UI,无需额外构建工具。修改 static/ 目录下的文件后,刷新浏览器即可预览效果。
---
### 📦 构建 Docker 镜像
```bash
# 构建 amd64 镜像
docker build -t frpc-console:amd64 .
# 多架构构建 (需要 buildx)
docker buildx build --platform linux/amd64,linux/arm64 -t frpc-console:latest --push .
```
---
@@ -149,7 +142,14 @@ docker buildx build --platform linux/amd64,linux/arm64 -t frpc-console:latest --
#### Q: frpc 启动失败怎么办?
检查 frpc.toml 配置是否正确,或查看 ./frpc.log 日志文件。
如果是首次启动,console 会自动生成一份符合官方规范的 `frps.toml` 配置文件,通常不需要额外操作
如果在使用过程中遇到启动失败,可以按以下步骤排查:
1. **检查配置是否正确** —— 在「全局配置」页面重新配置一次服务端参数,或导入已有的 `frpc.toml` 配置文件,console 会自动应用并尝试重启
2. **查看日志定位问题** —— 若上述操作后仍然失败,请查看 `./frpc.log` 日志文件,定位具体报错原因
> 日志文件的位置:与 `frpc-console` 二进制同级目录下的 `frpc.log`。Docker 部署时,可通过 `docker logs frpc-console` 查看容器输出。
#### Q: 支持哪些 frp 版本?
@@ -159,9 +159,10 @@ docker buildx build --platform linux/amd64,linux/arm64 -t frpc-console:latest --
|---|---|---|
| Linux | AMD64/x86-64 | 0.70.0 |
| Linux | ARM64/Aarch64 | 0.70.0 |
| Windows | AMD64/x86-64 | 0.69.0 |
| Linux | ARM_hf/ARMv7l | 0.70.0 |
| Windows | AMD64/x86-64 | 0.70.0 |
> 不是Windows不配高版本,是直到现在frp设计者那边0.70.0都没发Windows版本</br>(除非我单独下载下来make一个0.70.0的Windows,但是作者没放出来,肯定是有原因的)
> 行了行了,Windows 版和 Linux 版版本号已同步。不用再等了。
#### Q: 为什么不用 / 不推荐 Podux?
@@ -177,7 +178,7 @@ Podux 是个好项目,理念上和我们是一致的:用 Web 界面管理 fr
| 部署方式 | 单二进制 / Docker | 单二进制 / Docker |
| 多平台支持 | ✅ 原生交叉编译 | ✅ 原生交叉编译 |
> Podux 与其说是一个 frp 控制面板,不如说是一个“一站式 frp 管理器 + 可视化数据流面板 + 通道保活监测工具”。这种一站式本身没毛病,甚至功能实现非常到位。</br>但 podux的框架选型有点重,而且很明显细节稍显仓促。PocketBase 自带 WebUI 的情况下,Podux 还要再包一层 WebUI——相当于给数据库的 UI 又套了个 UI。更费解的是,这层 WebUI 只支持导入,不支持导出。这设计确实让人有点摸不着头脑</br>这也正是我们选择 SQLite + Vue CDN 的原因。
> Podux 与其说是一个 frp 控制面板,不如说是一个“一站式 frp 管理器 + 可视化数据流面板 + 通道保活监测工具”。这种一站式本身没毛病,甚至功能实现非常到位。</br>但 podux的框架选型有点重,而且很明显细节稍显仓促。PocketBase 自带 WebUI 的情况下,Podux 还要再包一层 WebUI——相当于给数据库的 UI 又套了个 UI。更费解的是,这层 WebUI 只支持导入,不支持导出。这设计确实让人有点摸不着头脑啦……</br>所以干脆换了一套轻量化工具自己上咯~
### Q: 为什么不直接用 frp 官方提供的 web 界面?
@@ -190,6 +191,53 @@ frpc-console 的目标是:
- **导入导出无缝迁移**
- **热加载无需重启**
### Q: 如果 frpc-console 进程挂了,frpc 本身会受影响吗?
**不会。**
这是 frp-console 系列工具与同类项目最核心的区别之一。我们称之为 **“阴阳模式”**。</br>
接下来,我们将结合中式哲学思想,阐述这个名称的由来:
#### 什么是“阴阳模式”?
以人的观察为出发点:
- **阴**:看不见的业务流(frpc 进程、toml 配置文件、隧道连接)
- **阳**:看得见的管理面板(Web 界面、API 服务)
大多数管理工具走的是 **“阳阴模式”**:面板是“大脑”,业务是“肢体”。大脑一旦停止工作,肢体也就瘫痪了。</br>
在这种模式下,管理面板与业务进程深度绑定,面板退出时业务进程也会随之终止。
**frpc-console 走的是“阴阳模式”:业务是根基,面板是工具。**
- **阴主导阳**:业务不依赖面板存活,面板只是用来观察和调整业务状态的手段
- **阳依附于阴**:面板的存在是为了服务业务,而不是反过来
#### 不同部署方式下的行为
**二进制部署:**
frpc-console 启动时,会以子进程的方式拉起 frpc,并为它创建一个独立的进程会话(`Setsid`)。这意味着 frpc 完全脱离父进程的生命周期控制。即使 SSH 断开导致 frpc-console 进程退出,frpc 也会被系统的 init 进程(PID 1)接管,继续在后台稳定运行。配置文件(`frpc.toml`)是持久化文件,不依赖 console 进程存活。面板可以随时挂、随时重启、随时升级,但隧道业务不受任何干扰。
**Docker 部署:**
容器使用 `--restart=always` 策略,frpc-console 进程意外退出时,Docker 守护进程会自动重启整个容器。重启后,console 重新读取持久化的 `frpc.toml`,重新拉起 frpc 子进程。数据目录(`/opt/frpc-console/data`)通过卷挂载持久化,容器重启不会丢失任何配置。Docker 模式的本质依然是“阳辅助阴”——`restart:always` 的目的是确保阴(业务)持续运行,而不是为了保住阳(面板)本身。
#### 为什么同类项目里很少见到这种设计?
因为大多数管理工具把“面板”和“业务”耦合在一起,认为面板是前提条件,业务是附属品。当然了,这确实是正向的、符合直觉的设计方向。但是有一个被很多人忽略的事实:**真正需要长期稳定运行的是隧道本身,而不是管理界面的进程。**
界面是用来观察和调整的,不是用来维持业务存活的。这是运维集群常用的“管理面与控制面分离”——只不过通常只在几千台服务器的集群管理里才会出现,很少有人会把它用在一个人用的 frp 管理工具上。
#### 核心原则
console 只做“配置的保管者”和“进程的启动者”,而不是“配置的持有者”或“进程的绑定者”。即使 console 完全离线,已经生成的 `frpc.toml` 依然存在,frpc 进程依然可以独立运行。这是 frp 本身的容灾能力在管理工具层面的自然延伸——**可视化框架只是工具,业务本身才是核心。**
> **管理面板可以丢,业务功能打死不能停。**
### Q: 支持 frp 的所有功能吗?
frpc-console 覆盖了 frp 最核心的 **TCP 隧道管理** 功能,包括 `tcpMux`、负载均衡、心跳配置等。如果你有更复杂的需求(比如 STCP、XTCP、P2P),欢迎提 issue,我们会评估是否加入。
@@ -204,28 +252,30 @@ frpc-console 遵循 **“够用就好”** 的原则:
2. **能用 SQLite 就不用 PostgreSQL,能用 Vue CDN 就不用 React 全家桶。**
3. **前端能做的事,后端不加额外复杂度。**
4. **删掉一个容器等于删掉所有垃圾,所以用 Docker 隔离是对的。**
5. **面板的存在应该是为了服务业务的,而不该是反过来主导业务的。**
---
## 📝 更新日志
### 1.0-Release (2026-07-24)
· 🎉 首次发布</br>
· ✨ 支持隧道增删改查</br>
· ✨ 支持 TOML 导入/导出</br>
· ✨ 首次启动 Web 注册</br>
· ✨ 深色磨砂玻璃 UI</br>
· ✨ 多平台 frpc 自动适配</br>
· 🐳 Docker 镜像支持
### .0-Release (正在修整,后续开发)
#### 相关更新日志请查看[update-logs.md](./update-logs.md)
---
## 📄 许可证
MIT License © 2026 lxh2875931338
MIT License © 2026 lxh2875931338XHLiang0
---
## 🙏 相关项目援引
### FRP 生态互补工具
· [MoonProxy](https://github.com/MoonProxyHQ/moonproxy-desktop) —— 基于 Tauri v2 + Vue 3 + Rust 构建的跨平台 FRP 桌面客户端(frpc GUI),面向 macOS 与 Windows,让内网穿透开箱即用,MIT协议开源。
### FRP 生态同类工具(暂无互引)
</br>
---
+115
View File
@@ -0,0 +1,115 @@
#!/bin/bash
# ============================================================
# frpc-console 部署入口(前置引导脚本)
# 此脚本固定在 main 分支,永不变化。
# 职责:引导用户选择通道,拉取对应分支的 deploy.sh 并执行
#
# 用法:
# curl -sSL https://git.whitetop.xyz/.../run-deploy.sh | sudo bash
# curl -sSL https://git.whitetop.xyz/.../run-deploy.sh | sudo bash -s -- --channel preview
# ============================================================
set -e
if [ -t 1 ]; then
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; CYAN='\033[0;36m'; MAGENTA='\033[0;35m'; NC='\033[0m'
else
RED=''; GREEN=''; YELLOW=''; BLUE=''; CYAN=''; MAGENTA=''; NC=''
fi
print_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_error() { echo -e "${RED}[✗]${NC} $1"; }
REPO_URL="https://git.whitetop.xyz/lxh2875931338/frpc-console.git"
WORK_DIR="/tmp/frpc-console-deploy"
CHANNEL=""
BRANCH=""
parse_args() {
for arg in "$@"; do
case $arg in
--channel)
shift; CHANNEL="$1"
;;
--channel=*)
CHANNEL="${arg#*=}"
;;
--help|-h)
echo "用法: curl .../run-deploy.sh | sudo bash -s -- [选项]"
echo ""
echo "选项:"
echo " --channel lts 使用 LTS 通道 (main 分支)"
echo " --channel preview 使用 Preview 通道 (test 分支)"
echo " --help, -h 显示帮助信息"
exit 0
;;
*)
print_error "未知选项: $arg"
echo "使用 --help 查看帮助"
exit 1
;;
esac
done
}
select_channel() {
if [ -n "$CHANNEL" ]; then
if [ "$CHANNEL" != "lts" ] && [ "$CHANNEL" != "preview" ]; then
print_error "无效通道: $CHANNEL (仅支持 lts / preview)"
exit 1
fi
BRANCH="$([ "$CHANNEL" = "preview" ] && echo "test" || echo "main")"
print_info "使用命令行参数: ${CHANNEL} 通道 (${BRANCH} 分支)"
return
fi
echo ""
echo -e "${CYAN}请选择部署通道:${NC}"
echo " 1. LTS (稳定版,生产推荐) [默认] → main 分支"
echo " 2. Preview (技术预览版,包含新特性) → test 分支"
echo ""
read -p "请选择 [1]: " CHANNEL_INPUT </dev/tty
CHANNEL_INPUT=${CHANNEL_INPUT:-1}
case $CHANNEL_INPUT in
1|"") CHANNEL="lts"; BRANCH="main" ;;
2) CHANNEL="preview"; BRANCH="test" ;;
*) print_error "无效选择"; exit 1 ;;
esac
print_info "已选择: ${CHANNEL} 通道 (${BRANCH} 分支)"
}
fetch_and_run() {
local deploy_url="https://git.whitetop.xyz/lxh2875931338/frpc-console/raw/${BRANCH}/deploy.sh"
echo ""
echo -e "${CYAN}▶ 从 ${BRANCH} 分支拉取 deploy.sh...${NC}"
rm -rf "$WORK_DIR"
mkdir -p "$WORK_DIR"
cd "$WORK_DIR"
if ! curl -sSL -o deploy.sh "$deploy_url"; then
print_error "无法下载 deploy.sh: $deploy_url"
exit 1
fi
chmod +x deploy.sh
echo -e "${GREEN}[✓] deploy.sh 已拉取${NC}"
echo ""
echo -e "${CYAN}▶ 执行部署脚本...${NC}"
echo ""
export DEPLOY_CHANNEL="$CHANNEL"
export DEPLOY_BRANCH="$BRANCH"
exec ./deploy.sh "$@"
}
main() {
clear 2>/dev/null || true
echo -e "${MAGENTA}════════════════════════════════════════════════════════${NC}"
echo -e "${MAGENTA} frpc-console 部署入口${NC}"
echo -e "${MAGENTA}════════════════════════════════════════════════════════${NC}"
echo ""
parse_args "$@"
select_channel
fetch_and_run "$@"
}
main "$@"
+112 -10
View File
@@ -9,6 +9,7 @@ import (
"os/exec"
"path/filepath"
"strings"
"time"
)
type Platform struct {
@@ -20,18 +21,89 @@ type Platform struct {
var platforms = []Platform{
{"windows", "amd64", "Windows x86-64", ".exe"},
{"windows", "386", "Windows x86", ".exe"},
{"linux", "amd64", "Linux x86-64", ""},
{"linux", "arm64", "Linux ARM64", ""},
{"linux", "armv7", "Linux ARMv7", ""},
{"linux", "arm", "Linux ARMv7l", ""},
}
const (
Version = "1.0.0"
BuildTime = "2026-07-24"
BuildTime = "2026-07-29"
Binary = "frpc-console"
)
// ============================================================
// 版本管理核心
// ============================================================
func readVersion() (semver string, ltsDate string) {
data, err := os.ReadFile("./version.ini")
if err != nil {
return "0.0.0", ""
}
lines := strings.Split(string(data), "\n")
var content string
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, ";") || strings.HasPrefix(line, "#") {
continue
}
content = line
break
}
parts := strings.Fields(content)
if len(parts) < 1 {
return "0.0.0", ""
}
semver = parts[0]
if len(parts) > 1 {
ltsDate = parts[1]
}
return semver, ltsDate
}
func getVersionType(semver string) string {
parts := strings.Split(semver, ".")
if len(parts) < 2 {
return "preview"
}
minor := parts[1]
if minor == "0" || minor == "5" {
return "lts"
}
return "preview"
}
func getFullVersion() string {
semver, ltsDate := readVersion()
vType := getVersionType(semver)
switch vType {
case "lts":
if ltsDate == "" {
ltsDate = time.Now().Format("20060102")
}
return semver + "-lts-" + ltsDate
default:
timestamp := time.Now().Format("20060102-150405")
return semver + "-preview-" + timestamp
}
}
func getImageTag() string {
semver, ltsDate := readVersion()
vType := getVersionType(semver)
switch vType {
case "lts":
if ltsDate == "" {
ltsDate = time.Now().Format("20060102")
}
return semver + "-lts-" + ltsDate
default:
return "preview-" + time.Now().Format("20060102-150405")
}
}
func main() {
if len(os.Args) > 1 {
target := os.Args[1]
@@ -45,6 +117,12 @@ func main() {
case "list":
listPlatforms()
return
case "version":
fmt.Println(getFullVersion())
return
case "image-tag":
fmt.Println(getImageTag())
return
}
for _, p := range platforms {
if target == p.OS+"/"+p.Arch {
@@ -53,8 +131,8 @@ func main() {
}
}
fmt.Println("❌ 不支持的平台:", target)
fmt.Println(" 可用: windows/amd64, windows/386, linux/amd64, linux/arm64, linux/armv7")
fmt.Println(" 或: all, list, clean")
fmt.Println(" 可用: windows/amd64, linux/amd64, linux/arm64, linux/arm")
fmt.Println(" 或: all, list, clean, version, image-tag")
return
}
interactiveMenu()
@@ -69,15 +147,19 @@ func listPlatforms() {
func interactiveMenu() {
fmt.Println("========================================")
fmt.Println(" frpc-console 多平台构建工具 v" + Version)
fmt.Println(" frpc-console 多平台构建工具")
fmt.Println("========================================")
fmt.Println()
fmt.Println(" 当前版本:", getFullVersion())
fmt.Println(" 镜像标签:", getImageTag())
fmt.Println()
for i, p := range platforms {
fmt.Printf(" %d. %s (%s/%s)\n", i+1, p.Name, p.OS, p.Arch)
}
fmt.Println(" a. 全部构建")
fmt.Println(" c. 清理构建产物")
fmt.Println(" v. 显示版本信息")
fmt.Println(" q. 退出")
fmt.Println()
@@ -97,6 +179,10 @@ func interactiveMenu() {
case "a":
buildAll()
return
case "v":
fmt.Println("版本:", getFullVersion())
fmt.Println("镜像标签:", getImageTag())
return
default:
var idx int
if n, err := fmt.Sscanf(input, "%d", &idx); n == 1 && err == nil && idx >= 1 && idx <= len(platforms) {
@@ -126,12 +212,22 @@ func build(p Platform, silent bool) {
return
}
outName := Binary + "-" + p.OS + "-" + p.Arch + p.Ext
fullVersion := getFullVersion()
imageTag := getImageTag()
outName := Binary + "-" + p.OS + "-" + p.Arch
if p.Arch == "arm" {
outName += "v7"
}
outName += p.Ext
outPath := filepath.Join(outDir, outName)
// 用 "go" 而不是硬编码路径,让系统去 PATH 里找
cmd := exec.Command("go", "build",
"-ldflags=-s -w -X main.version="+Version,
"-ldflags="+
"-s -w "+
"-X main.buildVersion="+fullVersion+" "+
"-X main.buildImageTag="+imageTag+" "+
"-X main.buildTime="+BuildTime,
"-o", outPath,
".",
)
@@ -140,6 +236,11 @@ func build(p Platform, silent bool) {
"GOARCH="+p.Arch,
"CGO_ENABLED=0",
)
if p.Arch == "arm" {
cmd.Env = append(cmd.Env, "GOARM=7")
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
@@ -150,6 +251,7 @@ func build(p Platform, silent bool) {
if !silent {
fmt.Printf("✅ 构建完成: %s\n", outPath)
fmt.Printf(" 版本: %s\n", fullVersion)
if info, err := os.Stat(outPath); err == nil {
size := float64(info.Size()) / 1024 / 1024
fmt.Printf(" 📦 %.2f MB\n", size)
+213 -15
View File
@@ -1,13 +1,12 @@
// app.js - 普通脚本(非模块)
const { createApp, ref, reactive, computed, onMounted } = Vue;
const { createApp, ref, reactive, computed, onMounted, nextTick, watch } = Vue;
// ============================================================
// 1. 基础 API
// ============================================================
const API_BASE = "/api";
function getToken() {
return localStorage.getItem("frpc_token") || "";
}
@@ -29,6 +28,13 @@ async function apiFetch(endpoint, options = {}) {
...options,
headers: { ...headers, ...(options.headers || {}) },
});
if (res.status === 401) {
clearAuthState();
window.dispatchEvent(new CustomEvent("auth:expired"));
return { code: 401, msg: "认证已过期,请重新登录" };
}
return res.json();
}
@@ -86,9 +92,9 @@ async function login(username, password) {
// 3. Config
// ============================================================
const defaultConfig = {
serverAddr: "frp.whitetop.xyz",
serverPort: 9358,
token: "",
serverAddr: "frp.example.com",
serverPort: 7000,
token: "CHANGE_ME",
logLevel: "info",
logMaxDays: 3,
tcpMux: true,
@@ -96,6 +102,7 @@ const defaultConfig = {
heartbeatInterval: 15,
heartbeatTimeout: 70,
poolCount: 8,
wireProtocolV2: false,
};
async function loadConfig() {
@@ -183,7 +190,26 @@ async function getFrpcStatus() {
}
// ============================================================
// 6. UI State
// 6. Logs
// ============================================================
async function fetchLogsApi() {
try {
const data = await apiFetch("/frpc/log");
if (data.code === 0) {
return {
lines: data.data.lines || [],
total: data.data.total || 0,
error: data.data.error || "",
};
}
return { lines: [], total: 0, error: "加载失败" };
} catch (e) {
return { lines: [], total: 0, error: "网络错误" };
}
}
// ============================================================
// 7. UI State
// ============================================================
const activeTab = ref("proxies");
const dialogVisible = ref(false);
@@ -197,6 +223,7 @@ const dialogForm = ref({
remotePort: 0,
});
const searchKeyword = ref("");
const showToken = ref(false);
function openAddDialog() {
dialogMode.value = "add";
@@ -222,7 +249,7 @@ function closeDialog() {
}
// ============================================================
// 7. Vue App
// 8. Vue App
// ============================================================
const app = createApp({
setup() {
@@ -251,7 +278,6 @@ const app = createApp({
const globalConfig = reactive({});
const proxies = ref([]);
const frpcRunning = ref(false);
const showDetail = ref(false);
// ---- 修改密码 ----
const passwordChange = reactive({
@@ -262,8 +288,92 @@ const app = createApp({
const passwordChangeError = ref("");
const passwordChangeSuccess = ref("");
// ---- 日志 ----
const logLines = ref([]);
const logTotal = ref(0);
const logError = ref("");
const logLastUpdate = ref("");
const logAutoScroll = ref(true);
let logTimer = null;
let logFetching = false;
// ---- Ping 延迟检测 ----
const pingLatency = ref(null);
let pingTimer = null;
const PING_INTERVAL_MS = 30000;
const PING_TIMEOUT_MS = 5000;
const pingStatusClass = computed(() => {
if (pingLatency.value === null) return "ping-fail";
if (pingLatency.value < 1000) return "ping-good";
if (pingLatency.value < 5000) return "ping-slow";
return "ping-fail";
});
const pingIcon = computed(() => {
if (pingLatency.value === null) {
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 256 256">
<path d="M0 0h256v256H0z" fill="none"/>
<g fill="currentColor">
<path d="m224.39 104.34-90.24 108.78a8 8 0 0 1-12.3 0L17.8 87.69a7.79 7.79 0 0 1 1.31-11.21A179.58 179.58 0 0 1 128 40a182 182 0 0 1 33.06 3a7.94 7.94 0 0 1 4.17 2.21L224 104Z" opacity=".2"/>
<path d="M229.66 98.34a8 8 0 0 1-11.32 11.32L200 91.31l-18.34 18.35a8 8 0 0 1-11.32-11.32L188.69 80l-18.35-18.34a8 8 0 0 1 11.32-11.32L200 68.69l18.34-18.35a8 8 0 0 1 11.32 11.32L211.31 80Zm-33.06 39.5a8 8 0 0 0-11.27 1L128 208L24.09 82.74A170.76 170.76 0 0 1 128 48c2.54 0 5.11.06 7.65.17a8 8 0 0 0 .7-16c-2.77-.12-5.58-.18-8.35-.18A186.67 186.67 0 0 0 14.28 70.1a15.93 15.93 0 0 0-6.17 10.81a15.65 15.65 0 0 0 3.54 11.89l104 125.43A15.93 15.93 0 0 0 128 224a15.93 15.93 0 0 0 12.31-5.77l57.34-69.12a8 8 0 0 0-1.05-11.27"/>
</g>
</svg>`;
}
if (pingLatency.value < 1000) {
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 25 24">
<path d="M0 0h25v24H0z" fill="none"/>
<path fill="currentColor" d="M2.046 6.725c6.192-4.967 15.05-4.967 21.243 0l.779.625l-11.4 14.25L1.265 7.35z"/>
</svg>`;
}
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
<path d="M0 0h24v24H0z" fill="none"/>
<path fill="none" stroke="currentColor" stroke-width="2" d="M21.996 7.505L12 20L2.004 7.505c5.827-4.673 14.165-4.673 19.992 0Z"/>
</svg>`;
});
async function doPing() {
if (!frpcRunning.value) {
pingLatency.value = null;
return;
}
const addr = globalConfig.serverAddr || "frp.example.com";
const start = performance.now();
try {
const res = await fetch(
`/api/ping?target=${encodeURIComponent(addr)}`,
{ signal: AbortSignal.timeout(PING_TIMEOUT_MS) },
);
if (!res.ok) throw new Error("Ping failed");
const end = performance.now();
pingLatency.value = Math.round(end - start);
} catch {
pingLatency.value = null;
}
}
function startPingPolling() {
if (pingTimer) return;
doPing();
pingTimer = setInterval(doPing, PING_INTERVAL_MS);
}
function stopPingPolling() {
if (pingTimer) {
clearInterval(pingTimer);
pingTimer = null;
}
}
// ---- 认证过期处理 ----
const handleAuthExpired = () => {
doLogout();
};
// ---- 初始化 ----
onMounted(() => {
window.addEventListener("auth:expired", handleAuthExpired);
const saved = loadAuthState();
if (saved.valid) {
token.value = saved.token;
@@ -279,6 +389,24 @@ const app = createApp({
}
});
// ---- Tab 切换监听日志轮询 ----
watch(activeTab, (newTab) => {
if (newTab === "logs") {
startLogPolling();
} else {
stopLogPolling();
}
});
watch(frpcRunning, (running) => {
if (!running) {
stopPingPolling();
pingLatency.value = null;
} else if (loggedIn.value) {
startPingPolling();
}
});
async function checkUsers() {
try {
const res = await fetch("/api/check/users");
@@ -312,6 +440,58 @@ const app = createApp({
frpcRunning.value = running;
}
// ---- 日志轮询 ----
async function fetchLogs() {
if (logFetching) return;
logFetching = true;
try {
const result = await fetchLogsApi();
if (result.code === 401) {
logFetching = false;
return;
}
logLines.value = result.lines;
logTotal.value = result.total;
logError.value = result.error;
logLastUpdate.value = new Date().toLocaleTimeString();
if (logAutoScroll.value) {
await nextTick();
const container = document.getElementById("logContainer");
if (container) {
container.scrollTop = container.scrollHeight;
}
}
} catch (e) {
logError.value = "网络错误";
} finally {
logFetching = false;
}
}
function startLogPolling() {
if (logTimer) return;
fetchLogs();
logTimer = setInterval(fetchLogs, 8000);
}
function stopLogPolling() {
if (logTimer) {
clearInterval(logTimer);
logTimer = null;
}
}
function refreshLogs() {
fetchLogs();
}
function scrollLogToBottom() {
const container = document.getElementById("logContainer");
if (container) {
container.scrollTop = container.scrollHeight;
}
}
// ---- 登录 ----
const doLogin = async () => {
if (!loginForm.username || !loginForm.password) {
@@ -368,9 +548,7 @@ const app = createApp({
});
const data = await res.json();
if (data.code === 0) {
// ✅ 注册成功,不再是首次启动
isFirstRun.value = false;
const token = data.data.token;
const expire = saveAuthState(token, registerForm.username);
token.value = token;
@@ -398,6 +576,8 @@ const app = createApp({
// ---- 退出 ----
const doLogout = () => {
if (expireTimer) clearInterval(expireTimer);
stopLogPolling();
stopPingPolling();
contentVisible.value = false;
loggedIn.value = false;
token.value = "";
@@ -407,8 +587,6 @@ const app = createApp({
loading.value = false;
transitioning.value = false;
clearAuthState();
// ✅ 重置注册相关状态
isFirstRun.value = false;
registerForm.username = "";
registerForm.password = "";
@@ -504,7 +682,7 @@ const app = createApp({
}
};
// ---- 导入导出(已移入 setup,可访问 loadAllData ----
// ---- 导入导出 ----
const triggerImport = () => {
document.getElementById("tomlFileInput").click();
};
@@ -559,9 +737,14 @@ const app = createApp({
// ---- 计算属性 ----
const filteredProxies = computed(() =>
filterProxies(proxies.value, searchKeyword.value)
filterProxies(proxies.value, searchKeyword.value),
);
const showDefaultTip = computed(() => {
const addr = globalConfig.serverAddr;
return !addr || addr === "frp.example.com" || addr.trim() === "";
});
// ---- 返回 ----
return {
loggedIn,
@@ -579,7 +762,6 @@ const app = createApp({
activeTab,
globalConfig,
showDetail,
saveConfig,
proxies,
@@ -608,6 +790,22 @@ const app = createApp({
passwordChangeError,
passwordChangeSuccess,
changePassword,
showDefaultTip,
logLines,
logTotal,
logError,
logLastUpdate,
logAutoScroll,
refreshLogs,
scrollLogToBottom,
showToken,
pingLatency,
pingStatusClass,
pingIcon,
};
},
});
+219 -122
View File
@@ -12,6 +12,7 @@
<link rel="stylesheet" href="/static/style-1.css" />
<link rel="stylesheet" href="/static/style-2.css" />
<link rel="stylesheet" href="/static/style-3.css" />
<link rel="stylesheet" href="/static/style-4.css" />
</head>
<body>
@@ -26,7 +27,7 @@
<!-- ====== 登录/注册页 ====== -->
<div v-if="!loggedIn" class="login-card">
<!-- Logo 区域(可替换) -->
<!-- Logo 区域 -->
<div class="login-logo">
<img src="/static/logo.svg" alt="frpc-console" class="logo-img" />
<span class="logo-text">frpc-console</span>
@@ -87,7 +88,7 @@
<!-- ====== 主界面 ====== -->
<div v-else class="main-panel" :class="{ visible: contentVisible }">
<!-- 顶部导航(含 Logo 小标) -->
<!-- 顶部导航 -->
<div class="top-bar">
<div class="top-left">
<img src="/static/logo.svg" alt="frpc-console" class="nav-logo" />
@@ -96,11 +97,15 @@
<span class="status-wrapper">
<span class="status-dot" :class="{ active: frpcRunning }"></span>
<span class="status-text">{{ frpcRunning ? 'frpc 运行中' : 'frpc 已停止' }}</span>
<!-- Ping 延迟显示 -->
<span class="ping-display" :class="pingStatusClass">
<span class="ping-icon" v-html="pingIcon"></span>
<span class="ping-value">{{ pingLatency !== null ? pingLatency + 'ms' : '--ms' }}</span>
</span>
</span>
</div>
</div>
<div class="top-right">
<span class="user-name">{{ loginForm.username }}</span>
<button class="logout-btn" @click="doLogout">退出</button>
</div>
</div>
@@ -111,103 +116,17 @@
@click="activeTab = 'proxies'">隧道列表</span>
<span class="tab-item" :class="{ active: activeTab === 'config' }"
@click="activeTab = 'config'">全局配置信息</span>
<span class="tab-item" :class="{ active: activeTab === 'logs' }"
@click="activeTab = 'logs'">运行日志</span>
<span class="tab-item" :class="{ active: activeTab === 'user' }"
@click="activeTab = 'user'">用户配置:{{loginForm.username }}</span>
</div>
<!-- 内容区 -->
<div class="content-area">
<!-- ====== 全局配置 ====== -->
<div v-if="activeTab === 'config'" class="tab-content">
<!-- 账户管理 -->
<div class="profile-section">
<div class="profile-header">
<span>👤 账户管理</span>
<span class="profile-username">{{ loginForm.username }}</span>
</div>
<div class="profile-form">
<div class="form-row">
<label>当前密码</label>
<input v-model="passwordChange.oldPassword" type="password" placeholder="输入当前密码" />
</div>
<div class="form-row">
<label>新密码</label>
<input v-model="passwordChange.newPassword" type="password"
placeholder="至少8位,含大小写/数字/特殊字符" />
</div>
<div class="form-row">
<label>确认新密码</label>
<input v-model="passwordChange.confirmPassword" type="password"
placeholder="再次输入新密码" />
</div>
<button class="save-btn" @click="changePassword">修改密码</button>
<p v-if="passwordChangeError" class="login-error">{{ passwordChangeError }}</p>
<p v-if="passwordChangeSuccess" class="login-success">{{ passwordChangeSuccess }}</p>
</div>
</div>
<!-- 配置卡片 -->
<div class="config-grid">
<div class="metric-card">
<div class="metric-label">TCP Multiplexing</div>
<div class="metric-value">
<span class="status-dot active"></span>
<span class="status-text active">已启用(固定)</span>
</div>
</div>
<div class="metric-card">
<div class="metric-label">连接池大小</div>
<div class="metric-value">
<span class="big-number">{{ globalConfig.poolCount || 8 }}</span>
<span class="unit"></span>
</div>
</div>
<div class="metric-card">
<div class="metric-label">心跳间隔 / 超时</div>
<div class="metric-value">
<span class="digit">{{ globalConfig.heartbeatInterval || 15 }}s</span>
<span class="sep">/</span>
<span class="digit">{{ globalConfig.heartbeatTimeout || 70 }}s</span>
</div>
</div>
</div>
<div class="detail-collapse" @click="showDetail = !showDetail">
<span>{{ showDetail ? '收起全部配置 ▲' : '展开全部配置 ▼' }}</span>
</div>
<div v-show="showDetail" class="detail-panel">
<div class="form-row"><label>Server Address</label><input
v-model="globalConfig.serverAddr" /></div>
<div class="form-row"><label>Server Port</label><input type="number"
v-model="globalConfig.serverPort" /></div>
<div class="form-row"><label>Token</label><input type="password"
v-model="globalConfig.token" /></div>
<div class="form-row">
<label>Log Level</label>
<select v-model="globalConfig.logLevel">
<option value="trace">trace</option>
<option value="debug">debug</option>
<option value="info">info</option>
<option value="warn">warn</option>
<option value="error">error</option>
</select>
</div>
<div class="form-row"><label>Log Max Days</label><input type="number"
v-model="globalConfig.logMaxDays" /></div>
<div class="form-row"><label>TCP Mux Keepalive</label><input type="number"
v-model="globalConfig.tcpMuxKeepalive" /></div>
<div class="form-row"><label>Heartbeat Interval</label><input type="number"
v-model="globalConfig.heartbeatInterval" /></div>
<div class="form-row"><label>Heartbeat Timeout</label><input type="number"
v-model="globalConfig.heartbeatTimeout" /></div>
<div class="form-row"><label>Pool Count</label><input type="number"
v-model="globalConfig.poolCount" /></div>
<button class="save-btn" @click="saveConfig">保存配置并热加载</button>
</div>
</div>
<!-- ====== 隧道列表 ====== -->
<div v-else-if="activeTab === 'proxies'" class="tab-content">
<div v-if="activeTab === 'proxies'" class="tab-content">
<div class="toolbar">
<div class="toolbar-left">
<button class="btn-import" @click="triggerImport">导入 TOML</button>
@@ -245,43 +164,221 @@
<div v-if="filteredProxies.length === 0" class="empty-state">暂无隧道,点击「新增隧道」添加</div>
</div>
</div>
</div>
</div>
</div>
<!-- ====== 弹窗 ====== -->
<Transition name="dialog">
<div v-if="dialogVisible" class="dialog-overlay" @click.self="dialogVisible = false">
<div class="dialog-card">
<h3>{{ dialogMode === 'add' ? '新增隧道' : '编辑隧道' }}</h3>
<div class="dialog-form">
<div class="form-row"><label>名称</label><input v-model="dialogForm.name" /></div>
<div class="form-row">
<label>类型</label>
<select v-model="dialogForm.type">
<option value="tcp">tcp</option>
<option value="udp">udp</option>
<option value="http">http</option>
<option value="https">https</option>
</select>
<!-- ====== 全局配置信息 ====== -->
<div v-if="activeTab === 'config'" class="tab-content config-tab-content">
<div class="config-page-header">
<h2>全局配置信息</h2>
<p class="config-subtitle">管理 frpc 连接参数与传输设置</p>
</div>
<div class="form-row"><label>本地 IP</label><input v-model="dialogForm.localIP" /></div>
<div class="form-row"><label>本地端口</label><input type="number" v-model="dialogForm.localPort" />
<div v-if="showDefaultTip" class="config-tip">
首次使用请修改「服务器地址」和「认证令牌」为您的真实 frps 配置
</div>
<div class="form-row"><label>远程端口</label><input type="number" v-model="dialogForm.remotePort" />
<!-- 卡片1: 服务器连接 -->
<div class="config-card">
<div class="config-card-header">
<span class="card-title">服务器连接</span>
</div>
<div class="config-card-body">
<div class="form-row">
<label>服务器地址</label>
<input v-model="globalConfig.serverAddr" placeholder="例如: frp.example.com" />
</div>
<div class="form-row">
<label>服务器端口</label>
<input type="number" v-model="globalConfig.serverPort" placeholder="7000" />
</div>
<div class="form-row" style="grid-column: 1 / -1;">
<label>认证令牌</label>
<div class="token-input-wrapper">
<input :type="showToken ? 'text' : 'password'" v-model="globalConfig.token"
placeholder="CHANGE_ME" />
<button class="token-toggle-btn" @click="showToken = !showToken">
{{ showToken ? '隐藏' : '显示' }}
</button>
</div>
</div>
</div>
</div>
<!-- 卡片2: 传输配置 -->
<div class="config-card">
<div class="config-card-header">
<span class="card-title">传输配置</span>
</div>
<div class="config-card-body">
<div class="form-row" style="grid-column: 1 / -1;">
<label>TCP 多路复用</label>
<div class="readonly-value">
<span class="status-dot active"></span>
<span class="status-text active">已强制开启</span>
<span class="hint-text">优化连接性能,减少延迟,frp 官方推荐开启</span>
</div>
</div>
<div class="form-row">
<label>保活间隔(秒)</label>
<input type="number" v-model="globalConfig.tcpMuxKeepalive" />
</div>
<div class="form-row">
<label>心跳间隔(秒)</label>
<input type="number" v-model="globalConfig.heartbeatInterval" />
</div>
<div class="form-row">
<label>心跳超时(秒)</label>
<input type="number" v-model="globalConfig.heartbeatTimeout" />
</div>
<div class="form-row">
<label>连接池大小(个)</label>
<input type="number" v-model="globalConfig.poolCount" />
</div>
<div class="form-row v2-switch-row">
<label>frp v2 隧道支持</label>
<div class="v2-switch-wrapper">
<label class="switch">
<input type="checkbox" v-model="globalConfig.wireProtocolV2" />
<span class="slider"></span>
</label>
</div>
<span class="hint-text v2-hint">
此功能为 frp 0.70.0 以上版本才能开启,若要打开必须搭配同版本 frpc 使用,否则此功能不生效
</span>
</div>
</div>
</div>
<!-- 卡片3: 日志配置 -->
<div class="config-card">
<div class="config-card-header">
<span class="card-title">日志配置</span>
</div>
<div class="config-card-body">
<div class="form-row">
<label>日志级别</label>
<select v-model="globalConfig.logLevel">
<option value="trace">trace</option>
<option value="debug">debug</option>
<option value="info">info</option>
<option value="warn">warn</option>
<option value="error">error</option>
</select>
</div>
<div class="form-row">
<label>日志保留天数(天)</label>
<input type="number" v-model="globalConfig.logMaxDays" />
</div>
</div>
</div>
<button class="save-config-btn" @click="saveConfig">保存配置并热加载</button>
</div>
<!-- ====== 运行日志 ====== -->
<div v-else-if="activeTab === 'logs'" class="tab-content log-tab-content">
<div class="log-toolbar">
<div class="log-toolbar-left">
<span class="log-info-badge">共 {{ logTotal }} 行</span>
<span v-if="logError" class="log-error-badge">{{ logError }}</span>
</div>
<div class="log-toolbar-right">
<label class="log-auto-scroll-label">
<input type="checkbox" v-model="logAutoScroll" />
自动滚动
</label>
<button class="log-btn" @click="refreshLogs">刷新</button>
<button class="log-btn" @click="scrollLogToBottom">↓ 滚动到底部</button>
</div>
</div>
<div class="log-terminal" id="logContainer">
<div v-if="logLines.length === 0 && !logError" class="log-empty">
暂无日志,frpc 尚未产生输出
</div>
<div v-else class="log-lines">
<div v-for="(line, idx) in logLines" :key="idx" class="log-line">{{ line }}</div>
</div>
</div>
<div class="log-footer">
<span>上次更新: {{ logLastUpdate || '--:--:--' }}</span>
<span class="log-polling-status">自动刷新中 (8s)</span>
</div>
</div>
<div class="dialog-actions">
<button class="btn-cancel" @click="dialogVisible = false">取消</button>
<button class="btn-confirm" @click="confirmDialog">确认</button>
<!-- ====== 用户配置 ====== -->
<div v-if="activeTab === 'user'" class="tab-content config-tab-content">
<div class="config-page-header">
<h2>用户配置:{{ loginForm.username }}</h2>
<p class="config-subtitle">修改当前账户的登录密码</p>
</div>
<div class="profile-section">
<div class="profile-header">
<span>账户管理</span>
<span class="profile-username">{{ loginForm.username }}</span>
</div>
<div class="profile-form">
<div class="form-row">
<label>当前密码</label>
<input v-model="passwordChange.oldPassword" type="password" placeholder="输入当前密码" />
</div>
<div class="form-row">
<label>新密码</label>
<input v-model="passwordChange.newPassword" type="password"
placeholder="至少8位,含大小写/数字/特殊字符" />
</div>
<div class="form-row">
<label>确认新密码</label>
<input v-model="passwordChange.confirmPassword" type="password"
placeholder="再次输入新密码" />
</div>
<button class="save-btn" @click="changePassword">修改密码</button>
<p v-if="passwordChangeError" class="login-error">{{ passwordChangeError }}</p>
<p v-if="passwordChangeSuccess" class="login-success">{{ passwordChangeSuccess }}</p>
</div>
</div>
</div>
</div>
</div>
</Transition>
</div> <!-- /content-area -->
<!-- ====== 弹窗 ====== -->
<Transition name="dialog">
<div v-if="dialogVisible" class="dialog-overlay" @click.self="dialogVisible = false">
<div class="dialog-card">
<h3>{{ dialogMode === 'add' ? '新增隧道' : '编辑隧道' }}</h3>
<div class="dialog-form">
<div class="form-row"><label>名称</label><input v-model="dialogForm.name" /></div>
<div class="form-row">
<label>类型</label>
<select v-model="dialogForm.type">
<option value="tcp">tcp</option>
<option value="udp">udp</option>
<option value="http">http</option>
<option value="https">https</option>
</select>
</div>
<div class="form-row"><label>本地 IP</label><input v-model="dialogForm.localIP" /></div>
<div class="form-row"><label>本地端口</label><input type="number" v-model="dialogForm.localPort" />
</div>
<div class="form-row"><label>远程端口</label><input type="number" v-model="dialogForm.remotePort" />
</div>
</div>
<div class="dialog-actions">
<button class="btn-cancel" @click="dialogVisible = false">取消</button>
<button class="btn-confirm" @click="confirmDialog">确认</button>
</div>
</div>
</div>
</Transition>
</div> <!-- /main-panel -->
</div> <!-- /app-container -->
<!-- 隐藏文件选择器 -->
<input type="file" id="tomlFileInput" accept=".toml" style="display:none" @change="handleImport" />
</div>
</div> <!-- /#app -->
<script src="/static/app.js"></script>
</body>
+151 -132
View File
@@ -1,4 +1,4 @@
/* ===== style-3.css - 主界面 ===== */
/* ===== style-3.css - 主界面核心 ===== */
/* ---------- 顶部导航 ---------- */
.top-bar {
@@ -145,130 +145,6 @@
height: 100%;
}
/* ---------- 全局配置页 ---------- */
.config-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
margin-bottom: 20px;
}
.metric-card {
background: var(--bg-metric);
border-radius: 16px;
padding: 16px 20px;
border: 1px solid var(--border-subtle);
}
.metric-label {
font-size: 12px;
color: var(--text-dim);
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 8px;
}
.metric-value {
display: flex;
align-items: center;
gap: 12px;
}
.big-number {
font-size: 28px;
font-weight: 600;
color: #fff;
}
.unit {
font-size: 14px;
color: var(--text-dim);
}
.digit {
font-family: 'JetBrains Mono', monospace;
font-size: 18px;
color: #fff;
}
.sep {
color: var(--text-dim);
}
/* ---------- 展开详情 ---------- */
.detail-collapse {
padding: 12px 0;
color: var(--text-dim);
font-size: 13px;
cursor: pointer;
user-select: none;
transition: color 0.3s;
}
.detail-collapse:hover {
color: var(--text-secondary);
}
.detail-panel {
background: rgba(255, 255, 255, 0.02);
border-radius: 12px;
padding: 16px 20px;
border: 1px solid var(--border-subtle);
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px 24px;
margin-bottom: 16px;
}
.detail-panel .form-row {
display: flex;
flex-direction: column;
gap: 4px;
}
.detail-panel .form-row label {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-dim);
}
.detail-panel .form-row input,
.detail-panel .form-row select {
padding: 8px 12px;
background: rgba(255, 255, 255, 0.04);
border: 1px solid var(--border-subtle);
border-radius: 8px;
color: #fff;
font-size: 14px;
outline: none;
transition: border-color 0.3s;
}
.detail-panel .form-row input:focus,
.detail-panel .form-row select:focus {
border-color: var(--primary-blue-border);
}
.save-btn {
grid-column: 1 / -1;
padding: 10px 24px;
background: linear-gradient(135deg, var(--primary-blue), #2a5adf);
border: none;
border-radius: 10px;
font-size: 14px;
font-weight: 600;
color: #0a0a0f;
cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s;
margin-top: 4px;
}
.save-btn:hover {
transform: scale(1.01);
box-shadow: 0 4px 16px var(--primary-blue-glow);
}
/* ---------- 账户管理区域 ---------- */
.profile-section {
background: rgba(255, 255, 255, 0.02);
@@ -329,13 +205,6 @@
border-color: var(--primary-blue-border);
}
.profile-form .save-btn {
grid-column: auto;
padding: 8px 20px;
margin-top: 0;
height: 40px;
}
.login-success {
color: #63e2b7;
font-size: 14px;
@@ -344,6 +213,57 @@
min-height: 24px;
}
/* ---------- 统一保存按钮 ---------- */
.save-btn,
.save-config-btn {
padding: 10px 24px;
background: linear-gradient(135deg, var(--primary-blue), #2a5adf);
border: none;
border-radius: 10px;
font-size: 14px;
font-weight: 600;
color: #0a0a0f;
cursor: pointer;
transition: filter 0.3s ease;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
/* 确保按钮本身不裁切阴影 */
isolation: isolate;
}
.save-btn:hover,
.save-config-btn:hover {
filter: brightness(1.25);
transform: none;
}
.save-btn:active,
.save-config-btn:active {
filter: brightness(0.9);
transform: scale(0.97);
}
/* 账户管理中的修改密码按钮(覆盖尺寸) */
.profile-form .save-btn {
grid-column: auto;
padding: 8px 20px;
margin-top: 0;
height: 40px;
font-size: 13px;
border-radius: 8px;
}
/* 保存配置按钮全宽(在全局配置页使用) */
.save-config-btn {
width: 100%;
margin-top: 8px;
padding: 12px;
font-size: 16px;
border-radius: 12px;
}
/* ---------- 隧道列表 ---------- */
.toolbar {
display: flex;
@@ -781,4 +701,103 @@ select:disabled {
.dialog-leave-from .dialog-card {
transform: scale(1) translateY(0);
opacity: 1;
}
/* ---------- 响应式调整 ---------- */
@media (max-width: 768px) {
.profile-form {
grid-template-columns: 1fr;
}
.proxy-list {
grid-template-columns: 1fr 1fr;
}
.toolbar {
flex-direction: column;
align-items: stretch;
}
.toolbar-right .search-input {
width: 100%;
}
}
@media (max-width: 480px) {
.proxy-list {
grid-template-columns: 1fr;
}
.top-left .nav-logo {
width: 36px;
height: 36px;
}
.brand-info .logo-text {
font-size: 18px;
}
.dialog-card {
padding: 20px;
}
}
/* ---------- Ping 延迟显示 ---------- */
.status-wrapper {
display: flex;
align-items: center;
gap: 12px;
}
.ping-display {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 12px;
font-weight: 500;
padding: 2px 8px 2px 4px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.04);
transition: background 0.3s;
}
.ping-display .ping-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
}
.ping-display .ping-icon svg {
width: 100%;
height: 100%;
}
/* 状态颜色 */
.ping-good .ping-icon {
color: #63e2b7;
}
.ping-good .ping-value {
color: #63e2b7;
}
.ping-slow .ping-icon {
color: #f0c040;
}
.ping-slow .ping-value {
color: #f0c040;
}
.ping-fail .ping-icon {
color: #f87171;
}
.ping-fail .ping-value {
color: #f87171;
}
/* 响应式调整 */
@media (max-width: 768px) {
.ping-display {
font-size: 11px;
padding: 1px 6px 1px 2px;
}
.ping-display .ping-icon {
width: 14px;
height: 14px;
}
}
+327
View File
@@ -0,0 +1,327 @@
/* ===== style-4.css - v1.5 新增样式 ===== */
/* ---------- 配置页面 ---------- */
.config-tab-content {
padding-bottom: 20px;
}
.config-page-header {
margin-bottom: 12px;
}
.config-page-header h2 {
font-size: 18px;
font-weight: 500;
color: var(--text-primary);
margin-bottom: 2px;
}
.config-subtitle {
font-size: 13px;
color: var(--text-dim);
}
/* 首次使用提示 */
.config-tip {
background: rgba(255, 200, 50, 0.08);
border: 1px solid rgba(255, 200, 50, 0.15);
border-radius: 10px;
padding: 10px 16px;
font-size: 13px;
color: #f0c040;
margin-bottom: 16px;
}
/* ---------- 配置卡片 ---------- */
.config-card {
background: rgba(255, 255, 255, 0.02);
border: 1px solid var(--border-subtle);
border-radius: 14px;
padding: 16px 20px;
margin-bottom: 14px;
}
.config-card-header {
display: flex;
align-items: center;
gap: 10px;
padding-bottom: 10px;
border-bottom: 1px solid var(--border-subtle);
margin-bottom: 14px;
}
.card-title {
font-size: 14px;
font-weight: 500;
color: var(--text-secondary);
}
.config-card-body {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px 24px;
}
.config-card-body .form-row {
display: flex;
flex-direction: column;
gap: 4px;
}
.config-card-body .form-row label {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-dim);
}
.config-card-body .form-row input,
.config-card-body .form-row select {
padding: 8px 12px;
background: rgba(255, 255, 255, 0.04);
border: 1px solid var(--border-subtle);
border-radius: 8px;
color: #fff;
font-size: 14px;
outline: none;
transition: border-color 0.3s;
width: 100%;
}
.config-card-body .form-row input:focus,
.config-card-body .form-row select:focus {
border-color: var(--primary-blue-border);
}
/* 数字输入框填满列宽 */
.config-card-body .form-row input[type="number"] {
width: 100%;
}
/* 只读行(TCP Mux */
.readonly-value {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
background: rgba(255, 255, 255, 0.02);
border-radius: 8px;
}
.readonly-value .status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #63e2b7;
box-shadow: 0 0 10px rgba(99, 226, 183, 0.3);
flex-shrink: 0;
}
.readonly-value .status-text.active {
color: #63e2b7;
font-size: 13px;
}
.readonly-value .hint-text {
font-size: 12px;
color: var(--text-dim);
margin-left: 8px;
}
/* Token 输入框 + 显示按钮 */
.token-input-wrapper {
display: flex;
gap: 8px;
}
.token-input-wrapper input {
flex: 1;
}
.token-toggle-btn {
padding: 8px 16px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid var(--border-subtle);
border-radius: 8px;
color: var(--text-secondary);
font-size: 12px;
cursor: pointer;
white-space: nowrap;
}
.token-toggle-btn:hover {
background: rgba(255, 255, 255, 0.1);
}
/* ---------- v2 协议开关(灰标禁用) ---------- */
.v2-switch-row {
grid-column: 1 / -1 !important;
padding-top: 4px;
border-top: 1px solid var(--border-subtle);
margin-top: 4px;
}
.v2-switch-wrapper {
display: flex;
align-items: center;
gap: 14px;
padding: 6px 0;
}
/* "即将推出" 徽章 */
.v2-badge {
font-size: 11px;
padding: 2px 12px;
background: rgba(255, 200, 50, 0.12);
border: 1px solid rgba(255, 200, 50, 0.15);
border-radius: 12px;
color: #f0c040;
letter-spacing: 0.5px;
font-weight: 500;
}
.v2-badge.v2-enabled {
background: rgba(99, 226, 183, 0.12);
border-color: rgba(99, 226, 183, 0.2);
color: #63e2b7;
}
.v2-hint {
font-size: 12px;
color: var(--text-dim);
line-height: 1.5;
padding: 2px 0 4px;
display: block;
}
/* ---------- 日志面板 ---------- */
.log-tab-content {
display: flex;
flex-direction: column;
height: 100%;
min-height: 400px;
}
.log-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 0 12px;
flex-shrink: 0;
flex-wrap: wrap;
gap: 10px;
}
.log-toolbar-left {
display: flex;
align-items: center;
gap: 14px;
}
.log-toolbar-right {
display: flex;
align-items: center;
gap: 10px;
}
.log-info-badge {
font-size: 13px;
color: var(--text-secondary);
}
.log-error-badge {
font-size: 13px;
color: #f87171;
}
.log-auto-scroll-label {
font-size: 13px;
color: var(--text-secondary);
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
}
.log-auto-scroll-label input[type="checkbox"] {
width: 16px;
height: 16px;
accent-color: var(--primary-blue);
cursor: pointer;
}
.log-btn {
padding: 6px 14px;
background: rgba(255, 255, 255, 0.04);
border: 1px solid var(--border-subtle);
border-radius: 8px;
color: var(--text-secondary);
font-size: 13px;
cursor: pointer;
transition: background 0.2s;
}
.log-btn:hover {
background: rgba(255, 255, 255, 0.08);
}
/* 终端样式(类似命令行) */
.log-terminal {
flex: 1;
background: rgba(0, 0, 0, 0.6);
border-radius: 12px;
border: 1px solid var(--border-subtle);
padding: 12px 16px;
overflow-y: auto;
font-family: 'JetBrains Mono', 'Consolas', monospace;
font-size: 13px;
line-height: 1.7;
min-height: 300px;
max-height: 500px;
}
.log-terminal::-webkit-scrollbar {
width: 6px;
}
.log-terminal::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.02);
border-radius: 4px;
}
.log-terminal::-webkit-scrollbar-thumb {
background: rgba(74, 124, 255, 0.25);
border-radius: 4px;
}
.log-terminal::-webkit-scrollbar-thumb:hover {
background: rgba(74, 124, 255, 0.4);
}
.log-lines {
display: flex;
flex-direction: column;
}
.log-line {
color: #c0c0c0;
white-space: pre-wrap;
word-break: break-all;
padding: 1px 0;
}
.log-empty {
color: var(--text-dim);
text-align: center;
padding: 40px 0;
}
/* 日志底部状态 */
.log-footer {
display: flex;
justify-content: space-between;
padding: 10px 4px 0;
font-size: 12px;
color: var(--text-dim);
flex-shrink: 0;
}
.log-polling-status {
color: var(--primary-blue);
}
/* ---------- 响应式调整 ---------- */
@media (max-width: 768px) {
.config-card-body {
grid-template-columns: 1fr;
}
.log-toolbar {
flex-direction: column;
align-items: stretch;
}
.log-toolbar-right {
flex-wrap: wrap;
}
.token-input-wrapper {
flex-wrap: wrap;
}
.v2-switch-wrapper {
flex-wrap: wrap;
}
}
+118
View File
@@ -0,0 +1,118 @@
## 📌 版本说明
| 版本类型 | 标记 | 适用场景 |
|----------|------|----------|
| LTS 正式版 | `-lts` | 生产环境,长期维护 |
| 技术预览版 | `-preview` | 功能前瞻,建议测试环境验证 |
## 🚀 2.4-lts (2026-07-30)
> **紧急修复版 —— 架构升级与部署流程重构**
>
> 本次版本为 **非正统 LTS 版本**(2.4 在语义版本中不属于 LTS 序列),因 `main` 分支在新架构迁移过程中出现编译阻塞,为快速恢复 LTS 通道可用性而发布。**2.5-lts 将回归正常语义版本规则。**
### 🔧 核心变更
- **部署架构重构** —— 引入 `run-deploy.sh` 独立入口,实现部署脚本与项目分支解耦
- **数据目录规范化** —— 所有运行时文件(数据库、配置、日志、PID)统一迁移至 `/app/data` 子目录,挂载点从 `/app` 收窄至 `/app/data`,彻底解决挂载覆盖二进制文件的问题
- **版本管理解耦** —— 二进制不再注入版本信息,版本由 `deploy.sh` 在部署时写入 `version.ini` 文件
- **PID 文件进程检测** —— frpc 状态检测从 `ps | grep` 改为基于 PID 文件,更加可靠
- **旧版本自动迁移** —— 检测到根目录存在旧数据文件时,自动迁移至 `data/` 子目录,并保留备份
### ✨ 功能完整
- Ping 延迟检测(顶部导航实时显示)
- 用户配置页独立(账户管理与全局配置分离)
- 401 统一拦截(认证过期自动跳转登录)
- 声明式数据库迁移引擎(基于 `db-history.go`
- frp v2 协议正式启用(`wireProtocol = "v2"`
### 📦 部署变更
| 变更项 | 旧方案 | 新方案 |
|--------|--------|--------|
| 挂载点 | `-v ${DEPLOY_DIR}:/app` | `-v ${DEPLOY_DIR}/data:/app/data` |
| 数据库路径 | `/app/frpc-console.db` | `/app/data/frpc-console.db` |
| 配置文件 | `/app/frpc.toml` | `/app/data/frpc.toml` |
| 版本文件 | 编译时注入 `-ldflags` | 部署时写入 `version.ini` |
### 🐛 修复
- 修复 `main` 分支因挂载覆盖导致二进制文件不可用的问题
- 修复 `ps | grep` 进程检测在容器环境不可靠的问题
- 修复旧版本升级时数据库路径不兼容的问题
---
## 🚀 2.3-preview (2026-07-28)
> **技术预览版** —— 在 LTS 稳定核心(2.0)基础上,集成 2.1 与 2.2 的新特性,并完成基础设施层的全面加固。
### ✨ 新增特性
- **Ping 延迟检测** —— 顶部导航实时显示 frpc 到 frps 的延迟,状态图标 + ms 值,直观反映网络质量(2.1)
- **用户配置页独立** —— 账户管理与全局配置分离,用户信息与 frpc 配置各自独立管理(2.1)
- **声明式数据库迁移引擎** —— 基于 `db-history.go` 的 Schema 版本声明,对比新旧差异自动决定迁移路径(2.2)
### 🔧 改进与优化
- **401 统一拦截** —— API 请求返回 401 时自动清除认证状态并跳转登录页,避免页面卡死(2.1)
- **数据库路径统一** —— 数据库文件固定为 `./frpc-console.db`Docker 部署时挂载整个 `/app` 目录,所有运行时文件(db / toml / log / pid)完整持久化
- **`deploy.sh` 部署逻辑重构** —— 备份 → 拉代码 → 停容器 → 构建 → 启动,顺序闭环;移除宿主机编译,全部交由 Docker 多阶段构建处理
- **Dockerfile 多阶段构建** —— 自动处理 `go.mod` 降级兼容,安装 `sqlite` 辅助工具,便于部署脚本验证数据库状态
- **前端加载状态管理** —— 新增 `authLoading` 状态,首次访问时先完成用户检查再渲染页面,彻底解决刷新后登录/注册页状态错乱的竞态问题
- **`schema_version` 兜底写入** —— `InitDB()` 末尾强制补写 Schema 版本,确保每次启动都能识别已有数据,彻底解决升级后反复跳转注册页的问题
- **`docker-compose.yml` 配套工具** —— 简化开发调试流程,支持快速重建容器
### 🐛 修复
- 修复 `ExportTomlHandler` 模板渲染时缺少 `WireProtocolLine` 字段的问题
- 修复 `deploy.sh` 升级时用空文件覆盖旧数据库的问题
- 修复 Docker 镜像中 `sqlite3` 包名错误导致 `deploy.sh` 无法验证数据库的问题
- 修复首次访问刷新时登录/注册页显示异常的前端竞态问题
### 📦 部署变更
- 挂载方式:`-v ${DEPLOY_DIR}:/app`(整个 `/app` 目录)
- 数据库位置:`/opt/frpc-console/frpc-console.db`
- 备份目录:`/tmp/frpc-console/db-backups`
- 容器内工具:`sqlite` 已预装,便于调试
---
## ✅ 2.0-lts (2026-07-27)
> **首个 LTS 正式版** —— 与 frps-console 2.0-lts 同步发布,共享版本号与 LTS 维护周期。
- 🚀 **frp v2 协议正式启用** —— `wireProtocol = "v2"` 配置项可用,实测稳定
- 🔒 **数据库迁移引擎完整实现** —— 版本驱动的增量迁移 + 迁移前自动全量备份 + 失败可回滚
- 🧩 **frps-console 同步发布** —— 同一套设计哲学,一个管理 frpc,一个管理 frps
---
## 🧪 1.5-release (2026-07-25) (non-LTS)
> 非长期支持版本,建议用于尝鲜测试,生产环境请使用 2.0-lts 及后续 LTS 版本。
- ✨ 全局配置页面卡片式重构(服务器连接 / 传输配置 / 日志配置)
- ✨ 新增运行日志面板(8 秒轮询,最大 200 行)
- ✨ frp v2 配置占位(UI 灰标禁用,为 2.0 铺路)
- 🔩 数据库 Schema 迁移框架(启动时自动补全缺失列)
- 🔐 默认配置脱敏(通用占位符,避免开箱即连他人服务器)
- 🎨 样式拆分与优化(style-3.css / style-4.css
---
## 🎉 1.0-release (2026-07-24) (non-LTS)
> 首次公开发布,核心功能全部就绪。
- 🎉 首次发布
- 📋 隧道全生命周期管理(增删改查 + 启用/禁用)
- 📦 TOML 导入/导出(无缝迁移现有 frpc 配置)
- 🔄 配置热加载(修改即生效,无需重启 frpc)
- 🔐 首次启动 Web 注册(无需命令行交互)
- 🖥️ 多平台支持(Windows / Linux / ARM 全平台)
- 🐳 容器化就绪(Docker 镜像,开箱即用)
- 🎨 深色磨砂玻璃 UI
+6
View File
@@ -0,0 +1,6 @@
; frpc-console 版本声明文件
; 格式: {语义版本号} [{LTS发布日期}]
; 示例:
; 2.4 # Preview 版本,无日期
; 2.5 20260729 # LTS 版本,带发布日期
2.4