From 4aa49266e64dcd608b86943bee2465a300bf4dd1 Mon Sep 17 00:00:00 2001
From: wcwq98 <85041970+wcwq98@users.noreply.github.com>
Date: Mon, 23 Dec 2024 14:59:08 +0800
Subject: [PATCH 1/3] Add files via upload
---
web/config.toml | 10 ++
web/go.mod | 39 +++++
web/go.sum | 89 +++++++++++
web/main.go | 298 +++++++++++++++++++++++++++++++++++
web/static/app.js | 134 ++++++++++++++++
web/templates/index.html | 330 +++++++++++++++++++++++++++++++++++++++
web/templates/login.html | 133 ++++++++++++++++
7 files changed, 1033 insertions(+)
create mode 100644 web/config.toml
create mode 100644 web/go.mod
create mode 100644 web/go.sum
create mode 100644 web/main.go
create mode 100644 web/static/app.js
create mode 100644 web/templates/index.html
create mode 100644 web/templates/login.html
diff --git a/web/config.toml b/web/config.toml
new file mode 100644
index 0000000..30e1a04
--- /dev/null
+++ b/web/config.toml
@@ -0,0 +1,10 @@
+[auth]
+password = "你的密码"
+
+[server]
+port = 8080
+
+[https]
+enabled = true
+cert_file = "./cert.pem"
+key_file = "./private.key"
diff --git a/web/go.mod b/web/go.mod
new file mode 100644
index 0000000..dc8d407
--- /dev/null
+++ b/web/go.mod
@@ -0,0 +1,39 @@
+module realm
+
+go 1.23.4
+
+require github.com/BurntSushi/toml v1.4.0
+
+require (
+ github.com/bytedance/sonic v1.11.6 // indirect
+ github.com/bytedance/sonic/loader v0.1.1 // indirect
+ github.com/cloudwego/base64x v0.1.4 // indirect
+ github.com/cloudwego/iasm v0.2.0 // indirect
+ github.com/gabriel-vasile/mimetype v1.4.3 // indirect
+ github.com/gin-contrib/sessions v1.0.1 // indirect
+ github.com/gin-contrib/sse v0.1.0 // indirect
+ github.com/gin-gonic/gin v1.10.0 // indirect
+ github.com/go-playground/locales v0.14.1 // indirect
+ github.com/go-playground/universal-translator v0.18.1 // indirect
+ github.com/go-playground/validator/v10 v10.20.0 // indirect
+ github.com/goccy/go-json v0.10.2 // indirect
+ github.com/gorilla/context v1.1.2 // indirect
+ github.com/gorilla/securecookie v1.1.2 // indirect
+ github.com/gorilla/sessions v1.2.2 // indirect
+ github.com/json-iterator/go v1.1.12 // indirect
+ github.com/klauspost/cpuid/v2 v2.2.7 // indirect
+ github.com/leodido/go-urn v1.4.0 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
+ github.com/modern-go/reflect2 v1.0.2 // indirect
+ github.com/pelletier/go-toml/v2 v2.2.2 // indirect
+ github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
+ github.com/ugorji/go/codec v1.2.12 // indirect
+ golang.org/x/arch v0.8.0 // indirect
+ golang.org/x/crypto v0.23.0 // indirect
+ golang.org/x/net v0.25.0 // indirect
+ golang.org/x/sys v0.20.0 // indirect
+ golang.org/x/text v0.15.0 // indirect
+ google.golang.org/protobuf v1.34.1 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/web/go.sum b/web/go.sum
new file mode 100644
index 0000000..641fecd
--- /dev/null
+++ b/web/go.sum
@@ -0,0 +1,89 @@
+github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
+github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
+github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
+github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
+github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
+github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
+github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
+github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
+github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
+github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
+github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
+github.com/gin-contrib/sessions v1.0.1 h1:3hsJyNs7v7N8OtelFmYXFrulAf6zSR7nW/putcPEHxI=
+github.com/gin-contrib/sessions v1.0.1/go.mod h1:ouxSFM24/OgIud5MJYQJLpy6AwxQ5EYO9yLhbtObGkM=
+github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
+github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
+github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
+github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
+github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
+github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
+github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
+github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
+github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
+github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
+github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
+github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
+github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
+github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
+github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
+github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
+github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
+github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
+github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
+github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
+github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
+github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
+github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
+github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
+github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
+github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
+golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
+golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
+golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
+golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
+golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
+golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
+golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
+golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
+golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
+google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
+google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
+rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
diff --git a/web/main.go b/web/main.go
new file mode 100644
index 0000000..26a3b69
--- /dev/null
+++ b/web/main.go
@@ -0,0 +1,298 @@
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "log"
+ "net/http"
+ "os/exec"
+ "sync"
+
+ "github.com/BurntSushi/toml"
+ "github.com/gin-contrib/sessions"
+ "github.com/gin-contrib/sessions/cookie"
+ "github.com/gin-gonic/gin"
+)
+
+type ForwardingRule struct {
+ Listen string `toml:"listen"`
+ Remote string `toml:"remote"`
+}
+
+type Config struct {
+ Network struct {
+ NoTCP bool `toml:"no_tcp"`
+ UseUDP bool `toml:"use_udp"`
+ } `toml:"network"`
+ Endpoints []ForwardingRule `toml:"endpoints"`
+}
+
+type PanelConfig struct {
+ Auth struct {
+ Password string `toml:"password"`
+ } `toml:"auth"`
+ Server struct {
+ Port int `toml:"port"`
+ } `toml:"server"`
+ HTTPS struct {
+ Enabled bool `toml:"enabled"`
+ CertFile string `toml:"cert_file"`
+ KeyFile string `toml:"key_file"`
+ } `toml:"https"`
+}
+
+var (
+ rules []ForwardingRule
+ mu sync.Mutex
+ config Config
+ panelConfig PanelConfig
+)
+
+func LoadConfig() error {
+ data, err := ioutil.ReadFile("/root/.realm/config.toml")
+ if err != nil {
+ return err
+ }
+
+ if _, err := toml.Decode(string(data), &config); err != nil {
+ return err
+ }
+
+ rules = config.Endpoints
+ return nil
+}
+
+func LoadPanelConfig() error {
+ data, err := ioutil.ReadFile("./config.toml")
+ if err != nil {
+ return err
+ }
+
+ if _, err := toml.Decode(string(data), &panelConfig); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func SaveRules() error {
+ mu.Lock()
+ defer mu.Unlock()
+
+ config.Endpoints = rules
+ data, err := toml.Marshal(config)
+ if err != nil {
+ return err
+ }
+
+ return ioutil.WriteFile("/root/.realm/config.toml", data, 0644)
+}
+
+// 认证中间件
+func AuthRequired() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ session := sessions.Default(c)
+ user := session.Get("user")
+ if user == nil {
+ c.Redirect(http.StatusFound, "/login")
+ c.Abort()
+ return
+ }
+ c.Next()
+ }
+}
+
+func main() {
+ if err := LoadConfig(); err != nil {
+ log.Fatalf("无法加载 realm 配置: %v", err)
+ }
+
+ if err := LoadPanelConfig(); err != nil {
+ log.Fatalf("无法加载面板配置: %v", err)
+ }
+
+ r := gin.Default()
+
+ // 设置 session
+ store := cookie.NewStore([]byte("secret"))
+ r.Use(sessions.Sessions("realm_session", store))
+
+ // 静态文件
+ r.Static("/static", "./static")
+
+ // 登录页面
+ r.GET("/login", func(c *gin.Context) {
+ session := sessions.Default(c)
+ if session.Get("user") != nil {
+ c.Redirect(http.StatusFound, "/")
+ return
+ }
+ c.File("./templates/login.html")
+ })
+
+ // 登录处理
+ r.POST("/login", func(c *gin.Context) {
+ var loginData struct {
+ Password string `json:"password"`
+ }
+
+ if err := c.ShouldBindJSON(&loginData); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求"})
+ return
+ }
+
+ if loginData.Password == panelConfig.Auth.Password {
+ session := sessions.Default(c)
+ session.Set("user", true)
+ session.Options(sessions.Options{
+ MaxAge: 3600 * 24, // 24小时
+ })
+ if err := session.Save(); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Session保存失败"})
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"message": "登录成功"})
+ } else {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"})
+ }
+ })
+
+ // 登出
+ r.POST("/logout", AuthRequired(), func(c *gin.Context) {
+ session := sessions.Default(c)
+ session.Clear()
+ session.Save()
+ c.JSON(http.StatusOK, gin.H{"message": "登出成功"})
+ })
+
+ // 需要认证的路由
+ authorized := r.Group("/")
+ authorized.Use(AuthRequired())
+ {
+ // 主页
+ authorized.GET("/", func(c *gin.Context) {
+ c.File("./templates/index.html")
+ })
+
+ // 获取转发规则
+ authorized.GET("/get_rules", func(c *gin.Context) {
+ mu.Lock()
+ defer mu.Unlock()
+ c.JSON(200, rules)
+ })
+
+ // 添加转发规则
+ authorized.POST("/add_rule", func(c *gin.Context) {
+ var input struct {
+ Listen string `json:"listen"`
+ Remote string `json:"remote"`
+ }
+
+ if err := c.ShouldBindJSON(&input); err != nil {
+ c.JSON(400, gin.H{"error": "Invalid input"})
+ return
+ }
+
+ mu.Lock()
+ rules = append(rules, ForwardingRule{
+ Listen: input.Listen,
+ Remote: input.Remote,
+ })
+ mu.Unlock()
+
+ if err := SaveRules(); err != nil {
+ c.JSON(500, gin.H{"error": "Failed to save rules"})
+ return
+ }
+
+ c.JSON(201, input)
+ })
+
+ // 删除转发规则
+ authorized.DELETE("/delete_rule", func(c *gin.Context) {
+ listen := c.Query("listen")
+
+ mu.Lock()
+ for i, rule := range rules {
+ if rule.Listen == listen {
+ rules = append(rules[:i], rules[i+1:]...)
+ break
+ }
+ }
+ mu.Unlock()
+
+ if err := SaveRules(); err != nil {
+ c.JSON(500, gin.H{"error": "Failed to save rules"})
+ return
+ }
+
+ c.Status(200)
+ })
+
+ // 启动服务
+ authorized.POST("/start_service", func(c *gin.Context) {
+ cmd := exec.Command("systemctl", "start", "realm")
+ if err := cmd.Run(); err != nil {
+ c.JSON(500, gin.H{"error": "Failed to start service"})
+ return
+ }
+
+ c.JSON(200, gin.H{"message": "Service started successfully"})
+ })
+
+ // 停止服务
+ authorized.POST("/stop_service", func(c *gin.Context) {
+ cmd := exec.Command("systemctl", "stop", "realm")
+ if err := cmd.Run(); err != nil {
+ c.JSON(500, gin.H{"error": "Failed to stop service"})
+ return
+ }
+
+ c.JSON(200, gin.H{"message": "Service stopped successfully"})
+ })
+
+ // 检查服务状态
+ authorized.GET("/check_status", func(c *gin.Context) {
+ cmd := exec.Command("systemctl", "is-active", "--quiet", "realm")
+ err := cmd.Run()
+
+ var status string
+ if err != nil {
+ if exitError, ok := err.(*exec.ExitError); ok {
+ if exitError.ExitCode() == 3 {
+ status = "未启用"
+ } else {
+ status = "未知状态"
+ }
+ } else {
+ status = "检查失败"
+ }
+ } else {
+ status = "启用"
+ }
+
+ c.JSON(200, gin.H{"status": status})
+ })
+ }
+
+ port := panelConfig.Server.Port
+ if port == 0 {
+ port = 8081 // 默认端口
+ }
+
+ if panelConfig.HTTPS.Enabled {
+ if panelConfig.HTTPS.CertFile == "" || panelConfig.HTTPS.KeyFile == "" {
+ log.Println("警告:HTTPS 已启用,但证书或密钥文件路径未指定。将使用 HTTP 继续。")
+ log.Printf("服务器正在使用 HTTP 运行,端口:%d\n", port)
+ r.Run(fmt.Sprintf(":%d", port))
+ } else {
+ log.Printf("服务器正在使用 HTTPS 运行,端口:%d\n", port)
+ r.RunTLS(fmt.Sprintf(":%d", port), panelConfig.HTTPS.CertFile, panelConfig.HTTPS.KeyFile)
+ }
+ } else {
+ log.Println("警告:未启用 HTTPS,将使用 HTTP 继续。")
+ log.Printf("服务器正在使用 HTTP 运行,端口:%d\n", port)
+ r.Run(fmt.Sprintf(":%d", port))
+ }
+}
+
diff --git a/web/static/app.js b/web/static/app.js
new file mode 100644
index 0000000..bd200f7
--- /dev/null
+++ b/web/static/app.js
@@ -0,0 +1,134 @@
+document.addEventListener('DOMContentLoaded', () => {
+ const outputDiv = document.getElementById('output');
+ const startButton = document.getElementById('startButton');
+ const stopButton = document.getElementById('stopButton');
+ const addRuleButton = document.getElementById('addRuleButton');
+ const localPortInput = document.getElementById('localPort');
+ const remoteIPInput = document.getElementById('remoteIP');
+ const remotePortInput = document.getElementById('remotePort');
+
+ async function fetchForwardingRules() {
+ try {
+ const response = await fetch('/get_rules');
+ if (!response.ok) {
+ throw new Error('获取规则失败:' + response.statusText);
+ }
+ const rules = await response.json();
+ const tbody = document.querySelector('#forwardingTable tbody');
+ tbody.innerHTML = '';
+
+ rules.forEach((rule, index) => {
+ const [, localPort] = rule.Listen.split(':');
+ const lastColonIndex = rule.Remote.lastIndexOf(':');
+ const remoteIP = rule.Remote.substring(0, lastColonIndex);
+ const remotePort = rule.Remote.substring(lastColonIndex + 1);
+
+ const row = document.createElement('tr');
+ row.innerHTML = `
+
${index + 1} |
+ ${localPort} |
+ ${remoteIP} |
+ ${remotePort} |
+ |
+ `;
+ tbody.appendChild(row);
+ });
+
+ // 为删除按钮添加事件监听
+ const deleteButtons = document.querySelectorAll('.delete-btn');
+ deleteButtons.forEach(button => {
+ button.addEventListener('click', function() {
+ const listenAddress = this.getAttribute('data-listen');
+ deleteRule(listenAddress);
+ });
+ });
+ } catch (error) {
+ console.error('请求失败:', error);
+ outputDiv.textContent = '获取转发规则失败';
+ }
+ }
+
+ async function deleteRule(listenAddress) {
+ try {
+ const response = await fetch(`/delete_rule?listen=${encodeURIComponent(listenAddress)}`, {
+ method: 'DELETE'
+ });
+ if (!response.ok) {
+ throw new Error('删除规则失败:' + response.statusText);
+ }
+ fetchForwardingRules(); // 重新获取规则列表
+ } catch (error) {
+ console.error('删除规则失败:', error);
+ outputDiv.textContent = '删除规则失败';
+ }
+ }
+
+ async function addRule() {
+ const localPort = localPortInput.value;
+ const remoteIP = remoteIPInput.value;
+ const remotePort = remotePortInput.value;
+
+ if (!localPort || !remoteIP || !remotePort) {
+ outputDiv.textContent = '请填写所有字段';
+ return;
+ }
+
+ try {
+ const response = await fetch('/add_rule', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ localPort,
+ remoteIP,
+ remotePort
+ })
+ });
+ if (!response.ok) {
+ throw new Error('添加规则失败:' + response.statusText);
+ }
+ fetchForwardingRules(); // 重新获取规则列表
+ } catch (error) {
+ console.error('添加规则失败:', error);
+ outputDiv.textContent = '添加规则失败';
+ }
+ }
+
+ startButton.addEventListener('click', async () => {
+ try {
+ const response = await fetch('/start_service', {
+ method: 'POST'
+ });
+ if (!response.ok) {
+ throw new Error('启动服务失败:' + response.statusText);
+ }
+ const result = await response.json();
+ outputDiv.textContent = result.output;
+ } catch (error) {
+ console.error('启动服务失败:', error);
+ outputDiv.textContent = '启动服务失败';
+ }
+ });
+
+ stopButton.addEventListener('click', async () => {
+ try {
+ const response = await fetch('/stop_service', {
+ method: 'POST'
+ });
+ if (!response.ok) {
+ throw new Error('停止服务失败:' + response.statusText);
+ }
+ const result = await response.json();
+ outputDiv.textContent = result.output;
+ } catch (error) {
+ console.error('停止服务失败:', error);
+ outputDiv.textContent = '停止服务失败';
+ }
+ });
+
+ addRuleButton.addEventListener('click', addRule);
+
+ // 初始化时获取规则列表
+ fetchForwardingRules();
+});
diff --git a/web/templates/index.html b/web/templates/index.html
new file mode 100644
index 0000000..3f1def9
--- /dev/null
+++ b/web/templates/index.html
@@ -0,0 +1,330 @@
+
+
+
+
+
+ Realm 转发管理面板
+
+
+
+
+
+
Realm 转发管理面板
+
+
+
+
+
+
当前转发规则
+
+
+
+ 序号 |
+ 中转端口 |
+ 落地鸡 IP |
+ 目标端口 |
+ 操作 |
+
+
+
+
+
+
+
+
添加转发规则
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/web/templates/login.html b/web/templates/login.html
new file mode 100644
index 0000000..98734bf
--- /dev/null
+++ b/web/templates/login.html
@@ -0,0 +1,133 @@
+
+
+
+
+
+ Realm 转发管理面板 - 登录
+
+
+
+
+
+
+
+
+
From 73e3c632d9ef03e5907485faf26b6f6613e366d0 Mon Sep 17 00:00:00 2001
From: wcwq98 <85041970+wcwq98@users.noreply.github.com>
Date: Mon, 23 Dec 2024 17:18:37 +0800
Subject: [PATCH 2/3] Update config.toml
---
web/config.toml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/web/config.toml b/web/config.toml
index 30e1a04..a3f9f18 100644
--- a/web/config.toml
+++ b/web/config.toml
@@ -6,5 +6,5 @@ port = 8080
[https]
enabled = true
-cert_file = "./cert.pem"
-key_file = "./private.key"
+cert_file = "./certificate/cert.pem"
+key_file = "./certificate/private.key"
From b7a3db2cd9b4b24d4437fc4f495a29c2dfcdd334 Mon Sep 17 00:00:00 2001
From: wcwq98 <85041970+wcwq98@users.noreply.github.com>
Date: Sat, 28 Dec 2024 22:47:31 +0800
Subject: [PATCH 3/3] Add files via upload
---
realm.sh | 345 +++++++++++++++++++++++++++++----------
web/config.toml | 7 +-
web/go.mod | 4 -
web/go.sum | 8 -
web/main.go | 142 ++++++++++------
web/templates/index.html | 58 ++++++-
6 files changed, 401 insertions(+), 163 deletions(-)
diff --git a/realm.sh b/realm.sh
index f5fec22..f8ed010 100644
--- a/realm.sh
+++ b/realm.sh
@@ -48,8 +48,6 @@ EOF
exit 0
fi
-
-
# 更新realm状态
update_realm_status() {
if [ -f "/root/realm/realm" ]; then
@@ -64,75 +62,96 @@ update_realm_status() {
# 检查realm服务状态
check_realm_service_status() {
if systemctl is-active --quiet realm; then
- echo -e "${green}启用${plain}"
+ realm_service_status="启用"
+ realm_service_status_color=$green
else
- echo -e "${red}未启用${plain}"
+ realm_service_status="未启用"
+ realm_service_status_color=$red
+ fi
+}
+
+# 更新面板状态
+update_panel_status() {
+ if [ -f "/root/realm/web/realm_web" ]; then
+ panel_status="已安装"
+ panel_status_color=$green
+ else
+ panel_status="未安装"
+ panel_status_color=$red
+ fi
+}
+
+# 检查面板服务状态
+check_panel_service_status() {
+ if systemctl is-active --quiet realm-panel; then
+ panel_service_status="启用"
+ panel_service_status_color=$green
+ else
+ panel_service_status="未启用"
+ panel_service_status_color=$red
fi
}
# 更新脚本
Update_Shell() {
echo -e "当前脚本版本为 [ ${sh_ver} ],开始检测最新版本..."
-
- # 获取最新版本号
sh_new_ver=$(wget --no-check-certificate -qO- "https://raw.githubusercontent.com/wcwq98/realm/main/realm.sh" | grep 'sh_ver="' | awk -F "=" '{print $NF}' | sed 's/\"//g' | head -1)
if [[ -z ${sh_new_ver} ]]; then
echo -e "${red}检测最新版本失败!请检查网络或稍后再试。${plain}"
return 1
fi
-
+
if [[ ${sh_new_ver} == ${sh_ver} ]]; then
echo -e "当前已是最新版本 [ ${sh_new_ver} ]!"
return 0
fi
-
- # 提示用户是否更新
+
echo -e "发现新版本 [ ${sh_new_ver} ],是否更新?[Y/n]"
read -p "(默认: y): " yn
- yn=${yn:-y} # 默认值为 'y'
+ yn=${yn:-y}
if [[ ${yn} =~ ^[Yy]$ ]]; then
- # 下载最新脚本
wget -N --no-check-certificate https://raw.githubusercontent.com/wcwq98/realm/main/realm.sh -O realm.sh
if [[ $? -ne 0 ]]; then
echo -e "${red}下载脚本失败,请检查网络连接!${plain}"
return 1
fi
-
chmod +x realm.sh
echo -e "脚本已更新为最新版本 [ ${sh_new_ver} ]!"
-
- # 自动重启更新后的脚本
- echo "正在重新启动脚本..."
exec bash realm.sh
else
echo -e "已取消更新。"
fi
}
+# 检查依赖
+check_dependencies() {
+ echo "正在检查当前环境依赖"
+ local dependencies=("wget" "tar" "systemctl" "sed" "grep")
-# 初始化realm状态
-update_realm_status() {
- if [ -f "/root/realm/realm" ]; then
- realm_status="已安装"
- realm_status_color=$green
- else
- realm_status="未安装"
- realm_status_color=$red
- fi
-}
+ for dep in "${dependencies[@]}"; do
+ if ! command -v "$dep" &> /dev/null; then
+ echo "正在安装 $dep..."
+ if [ -x "$(command -v apt-get)" ]; then
+ apt-get update && apt-get install -y "$dep"
+ elif [ -x "$(command -v yum)" ]; then
+ yum install -y "$dep"
+ else
+ echo "无法安装 $dep。请手动安装后重试。"
+ exit 1
+ fi
+ fi
+ done
-# 检查realm服务状态
-check_realm_service_status() {
- if systemctl is-active --quiet realm; then
- echo -e "${green}启用${plain}"
- else
- echo -e "${red}未启用${plain}"
- fi
+ echo "所有依赖已满足。"
}
# 显示菜单的函数
show_menu() {
clear
+ update_realm_status
+ check_realm_service_status
+ update_panel_status
+ check_panel_service_status
echo "欢迎使用realm一键转发脚本"
echo "================="
echo "1. 部署环境"
@@ -145,11 +164,13 @@ show_menu() {
echo "8. 检测更新"
echo "9. 一键卸载"
echo "10. 更新脚本"
+ echo "11. 面板管理"
echo "0. 退出脚本"
echo "================="
echo -e "realm 状态:${realm_status_color}${realm_status}${plain}"
- echo -n "realm 转发状态:"
- check_realm_service_status
+ echo -e "realm 转发状态:${realm_service_status_color}${realm_service_status}${plain}"
+ echo -e "面板状态:${panel_status_color}${panel_status}${plain}"
+ echo -e "面板服务状态:${panel_service_status_color}${panel_service_status}${plain}"
}
# 部署环境的函数
@@ -198,11 +219,9 @@ deploy_realm() {
tar -xvf "/root/realm/realm-${_version}.tar.gz" -C /root/realm/
chmod +x /root/realm/realm
-# 创建 config.toml 模板
+ # 创建 config.toml 模板
mkdir -p /root/.realm
cat < "$CONFIG_PATH"
-
-
[network]
no_tcp = false #是否关闭tcp转发
use_udp = true #是否开启udp转发
@@ -215,7 +234,6 @@ use_udp = true #是否开启udp转发
[[endpoints]]
listen = "0.0.0.0:1234"
remote = "0.0.0.0:5678"
-
EOF
echo "[Unit]
@@ -255,6 +273,7 @@ uninstall_realm() {
if [[ $delete_config == "Y" || $delete_config == "y" ]]; then
rm -rf /root/realm
+ rm -rf /root/.realm
echo "配置文件已删除。"
else
echo "配置文件保留。"
@@ -266,15 +285,17 @@ uninstall_realm() {
# 删除转发规则的函数
delete_forward() {
echo "当前转发规则:"
- local IFS=$'\n'
- local lines=($(grep -n 'remote =' /root/realm/config.toml))
+ local lines=($(grep -n 'remote =' /root/.realm/config.toml | grep -v '#' | awk -F: '{print $1}'))
if [ ${#lines[@]} -eq 0 ]; then
echo "没有发现任何转发规则。"
return
fi
local index=1
- for line in "${lines[@]}"; do
- echo "${index}. $(echo $line | cut -d '"' -f 2)"
+ for line_num in "${lines[@]}"; do
+ listen_line=$((line_num - 1))
+ listen_port=$(sed -n "${listen_line}p" /root/.realm/config.toml | cut -d '"' -f 2)
+ remote_port=$(sed -n "${line_num}p" /root/.realm/config.toml | cut -d '"' -f 2)
+ echo "${index}. 本地监听: ${listen_port} --> 远程目标: ${remote_port}"
let index+=1
done
@@ -295,13 +316,20 @@ delete_forward() {
return
fi
- local chosen_line=${lines[$((choice-1))]}
- local line_number=$(echo $chosen_line | cut -d ':' -f 1)
+ local line_number=${lines[$((choice-1))]}
+ # 找到 [[endpoints]] 的起始行
local start_line=$line_number
- local end_line=$(($line_number + 2))
+ while [ $start_line -ge 1 ]; do
+ local line_content=$(sed -n "${start_line}p" /root/.realm/config.toml)
+ if [[ $line_content =~ $$\[endpoints$$\] ]]; then
+ break
+ fi
+ ((start_line--))
+ done
- sed -i "${start_line},${end_line}d" /root/realm/config.toml
+ # 删除从 start_line 开始的 3 行
+ sed -i "${start_line},$(($start_line+3))d" /root/.realm/config.toml
echo "转发规则已删除。"
}
@@ -312,9 +340,10 @@ add_forward() {
read -e -p "请输入落地鸡的IP: " ip
read -e -p "请输入本地中转鸡的端口(port1): " port1
read -e -p "请输入落地鸡端口(port2): " port2
- echo "[[endpoints]]
+ echo "
+[[endpoints]]
listen = \"0.0.0.0:$port1\"
-remote = \"$ip:$port2\"" >> /root/realm/config.toml
+remote = \"$ip:$port2\"" >> /root/.realm/config.toml
read -e -p "是否继续添加转发规则(Y/N)? " answer
if [[ $answer != "Y" && $answer != "y" ]]; then
@@ -331,9 +360,10 @@ add_port_range_forward() {
read -e -p "请输入落地鸡端口: " remote_port
for ((port=$start_port; port<=$end_port; port++)); do
- echo "[[endpoints]]
+ echo "
+[[endpoints]]
listen = \"0.0.0.0:$port\"
-remote = \"$ip:$remote_port\"" >> /root/realm/config.toml
+remote = \"$ip:$remote_port\"" >> /root/.realm/config.toml
done
echo "端口段转发规则已添加。"
@@ -346,30 +376,23 @@ start_service() {
systemctl restart realm.service
systemctl enable realm.service
echo "realm服务已启动并设置为开机自启。"
- update_realm_status
-
- # 检查服务状态
- if ! systemctl is-active --quiet realm; then
- echo "请检查是否存在config.toml或config.toml配置是否正确"
- fi
+ check_realm_service_status
}
+
# 停止服务
stop_service() {
- systemctl stop realm
- echo "realm服务已停止。"
- update_realm_status
+ systemctl stop realm.service
+ systemctl disable realm.service
+ echo "realm服务已停止并已禁用开机自启。"
+ check_realm_service_status
}
# 重启服务
restart_service() {
- systemctl restart realm
+ systemctl daemon-reload
+ systemctl restart realm.service
echo "realm服务已重启。"
- update_realm_status
-
- # 检查服务状态
- if ! systemctl is-active --quiet realm; then
- echo "请检查是否存在config.toml或config.toml配置是否正确"
- fi
+ check_realm_service_status
}
# 更新realm
@@ -407,26 +430,174 @@ update_realm() {
update_realm_status
}
-# 初始化realm状态
-update_realm_status
+# 面板管理函数
+panel_management() {
+ clear
+ echo "==========================="
+ echo "Realm 面板管理"
+ echo "==========================="
+ echo "1. 启动面板"
+ echo "2. 暂停面板"
+ echo "3. 安装面板"
+ echo "4. 卸载面板"
+ echo "5. 修改面板配置"
+ echo "0. 返回主菜单"
+ echo "==========================="
+ read -p "请选择操作 [0-5]: " panel_choice
-# 主循环
-while true; do
- show_menu
- read -p "请选择一个选项: " choice
- case $choice in
- 1) deploy_realm ;;
- 2) add_forward ;;
- 3) add_port_range_forward ;;
- 4) delete_forward ;;
- 5) start_service ;;
- 6) stop_service ;;
- 7) restart_service ;;
- 8) update_realm ;;
- 9) uninstall_realm ;;
- 10) Update_Shell ;;
- 0) echo "退出脚本。"; exit 0 ;;
- *) echo "无效选项: $choice" ;;
+ case $panel_choice in
+ 1) start_panel ;;
+ 2) stop_panel ;;
+ 3) install_panel ;;
+ 4) uninstall_panel ;;
+ 5) modify_panel_config ;;
+ 0) return ;;
+ *) echo "无效的选择" ;;
esac
- read -p "按任意键继续..." key
-done
+}
+
+install_panel() {
+ echo "开始安装 Realm 面板..."
+
+ # 检测系统架构
+ arch=$(uname -m)
+ case "$arch" in
+ x86_64)
+ panel_file="realm-panel-linux-amd64.tar.gz"
+ ;;
+ aarch64|arm64)
+ panel_file="realm-panel-linux-arm64.tar.gz"
+ ;;
+ *)
+ echo "不支持的系统架构: $arch"
+ return 1
+ ;;
+ esac
+
+ cd /root/realm
+
+ # 从 GitHub 下载面板文件
+ echo "正在从 GitHub 下载面板文件..."
+ echo "检测到系统架构: $arch,将下载: $panel_file"
+
+ # 下载面板文件
+ download_url="https://github.com/wcwq98/realm/releases/download/v2.0/${panel_file}"
+ if ! wget -O "${panel_file}" "$download_url"; then
+ echo "下载失败,请检查网络连接或稍后再试。"
+ return 1
+ fi
+
+ # 解压并设置权限
+ tar -xvf "${panel_file}" -C /root/realm/
+
+ # 重命名文件夹
+ if [ -d "realm-panel-linux-amd64" ]; then
+ mv realm-panel-linux-amd64 web
+ elif [ -d "realm-panel-linux-arm64" ]; then
+ mv realm-panel-linux-arm64 web
+ else
+ echo "未找到解压后的文件夹。"
+ return 1
+ fi
+
+ cd web
+ # 设置权限
+ chmod +rwx realm-web-amd64
+
+ # 重命名文件
+ if [ -f "realm-web-amd64" ]; then
+ mv realm-web-amd64 realm_web
+ elif [ -f "realm-web-arm64" ]; then
+ mv realm-web-arm64 realm_web
+ else
+ echo "未找到解压后的文件。"
+ return 1
+ fi
+
+
+ # 创建服务文件
+ echo "[Unit]
+Description=Realm Web Panel
+After=network.target
+
+[Service]
+Type=simple
+User=root
+WorkingDirectory=/root/realm/web
+ExecStart=/root/realm/web/realm_web
+Restart=on-failure
+
+[Install]
+WantedBy=multi-user.target" > /etc/systemd/system/realm-panel.service
+
+ # 重新加载 systemd 并启动服务
+ systemctl daemon-reload
+ systemctl enable realm-panel
+ systemctl start realm-panel
+
+ update_panel_status
+ echo "Realm 面板安装完成。"
+}
+
+# 启动面板
+start_panel() {
+ systemctl start realm-panel
+ echo "面板服务已启动。"
+ check_panel_service_status
+}
+
+# 停止面板
+stop_panel() {
+ systemctl stop realm-panel
+ echo "面板服务已停止。"
+ check_panel_service_status
+}
+
+# 卸载面板
+uninstall_panel() {
+ systemctl stop realm-panel
+ systemctl disable realm-panel
+ rm -f /etc/systemd/system/realm-panel.service
+ systemctl daemon-reload
+
+ rm -f /root/realm/realm_web
+ echo "面板已被卸载。"
+
+ update_panel_status
+}
+
+# 修改面板配置
+modify_panel_config() {
+ echo "修改面板配置..."
+ # 在此添加修改配置的具体逻辑
+ echo "配置已修改。"
+}
+
+# 主程序
+main() {
+ check_dependencies
+ init_env
+
+ while true; do
+ show_menu
+ read -p "请输入选项 [0-11]: " choice
+
+ case $choice in
+ 1) deploy_realm ;;
+ 2) add_forward ;;
+ 3) add_port_range_forward ;;
+ 4) delete_forward ;;
+ 5) start_service ;;
+ 6) stop_service ;;
+ 7) restart_service ;;
+ 8) update_realm ;;
+ 9) uninstall_realm ;;
+ 10) Update_Shell ;;
+ 11) panel_management ;;
+ 0) exit 0 ;;
+ *) echo "无效的选项,请重新输入。" ;;
+ esac
+ done
+}
+
+main
diff --git a/web/config.toml b/web/config.toml
index a3f9f18..eff1efd 100644
--- a/web/config.toml
+++ b/web/config.toml
@@ -1,10 +1,11 @@
[auth]
-password = "你的密码"
+password = "123456" # 面板密码
[server]
-port = 8080
+port = 8081 # 面板端口
[https]
-enabled = true
+enabled = false #是否开启HTTPS
cert_file = "./certificate/cert.pem"
key_file = "./certificate/private.key"
+
diff --git a/web/go.mod b/web/go.mod
index dc8d407..3af0670 100644
--- a/web/go.mod
+++ b/web/go.mod
@@ -10,16 +10,12 @@ require (
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
- github.com/gin-contrib/sessions v1.0.1 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.10.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
- github.com/gorilla/context v1.1.2 // indirect
- github.com/gorilla/securecookie v1.1.2 // indirect
- github.com/gorilla/sessions v1.2.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
diff --git a/web/go.sum b/web/go.sum
index 641fecd..e6bbf9f 100644
--- a/web/go.sum
+++ b/web/go.sum
@@ -12,8 +12,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
-github.com/gin-contrib/sessions v1.0.1 h1:3hsJyNs7v7N8OtelFmYXFrulAf6zSR7nW/putcPEHxI=
-github.com/gin-contrib/sessions v1.0.1/go.mod h1:ouxSFM24/OgIud5MJYQJLpy6AwxQ5EYO9yLhbtObGkM=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
@@ -27,12 +25,6 @@ github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaC
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
-github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
-github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
-github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
-github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
-github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
-github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
diff --git a/web/main.go b/web/main.go
index 26a3b69..f125c3f 100644
--- a/web/main.go
+++ b/web/main.go
@@ -1,6 +1,7 @@
package main
import (
+ "bytes"
"fmt"
"io/ioutil"
"log"
@@ -15,8 +16,8 @@ import (
)
type ForwardingRule struct {
- Listen string `toml:"listen"`
- Remote string `toml:"remote"`
+ Listen string `toml:"listen" json:"listen"`
+ Remote string `toml:"remote" json:"remote"`
}
type Config struct {
@@ -42,10 +43,10 @@ type PanelConfig struct {
}
var (
- rules []ForwardingRule
mu sync.Mutex
config Config
panelConfig PanelConfig
+ httpsWarningShown = false
)
func LoadConfig() error {
@@ -58,7 +59,6 @@ func LoadConfig() error {
return err
}
- rules = config.Endpoints
return nil
}
@@ -75,20 +75,34 @@ func LoadPanelConfig() error {
return nil
}
-func SaveRules() error {
+func SaveConfig() error {
mu.Lock()
defer mu.Unlock()
- config.Endpoints = rules
- data, err := toml.Marshal(config)
- if err != nil {
+ var buf bytes.Buffer
+ encoder := toml.NewEncoder(&buf)
+
+ // 编码 network 部分
+ if err := encoder.Encode(map[string]interface{}{"network": config.Network}); err != nil {
return err
}
- return ioutil.WriteFile("/root/.realm/config.toml", data, 0644)
+ // 只有在有规则时才添加 endpoints 部分
+ if len(config.Endpoints) > 0 {
+ buf.WriteString("\n")
+ for _, endpoint := range config.Endpoints {
+ buf.WriteString("[[endpoints]]\n")
+ if err := encoder.Encode(endpoint); err != nil {
+ return err
+ }
+ buf.WriteString("\n")
+ }
+ }
+
+ // 写入文件
+ return ioutil.WriteFile("/root/.realm/config.toml", buf.Bytes(), 0644)
}
-// 认证中间件
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
@@ -102,6 +116,21 @@ func AuthRequired() gin.HandlerFunc {
}
}
+func HTTPSRedirect() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ if panelConfig.HTTPS.Enabled && c.Request.TLS == nil {
+ target := "https://" + c.Request.Host + c.Request.URL.Path
+ if c.Request.URL.RawQuery != "" {
+ target += "?" + c.Request.URL.RawQuery
+ }
+ c.Redirect(http.StatusMovedPermanently, target)
+ c.Abort()
+ return
+ }
+ c.Next()
+ }
+}
+
func main() {
if err := LoadConfig(); err != nil {
log.Fatalf("无法加载 realm 配置: %v", err)
@@ -113,14 +142,12 @@ func main() {
r := gin.Default()
- // 设置 session
store := cookie.NewStore([]byte("secret"))
r.Use(sessions.Sessions("realm_session", store))
+ r.Use(HTTPSRedirect())
- // 静态文件
r.Static("/static", "./static")
- // 登录页面
r.GET("/login", func(c *gin.Context) {
session := sessions.Default(c)
if session.Get("user") != nil {
@@ -130,7 +157,6 @@ func main() {
c.File("./templates/login.html")
})
- // 登录处理
r.POST("/login", func(c *gin.Context) {
var loginData struct {
Password string `json:"password"`
@@ -157,101 +183,90 @@ func main() {
}
})
- // 登出
- r.POST("/logout", AuthRequired(), func(c *gin.Context) {
- session := sessions.Default(c)
- session.Clear()
- session.Save()
- c.JSON(http.StatusOK, gin.H{"message": "登出成功"})
- })
-
- // 需要认证的路由
authorized := r.Group("/")
authorized.Use(AuthRequired())
{
- // 主页
authorized.GET("/", func(c *gin.Context) {
+ if !panelConfig.HTTPS.Enabled && !httpsWarningShown {
+ c.Header("X-HTTPS-Warning", "当前未启用HTTPS,强烈建议启用HTTPS")
+ httpsWarningShown = true
+ }
c.File("./templates/index.html")
})
- // 获取转发规则
authorized.GET("/get_rules", func(c *gin.Context) {
mu.Lock()
- defer mu.Unlock()
+ rules := config.Endpoints
+ mu.Unlock()
c.JSON(200, rules)
})
- // 添加转发规则
authorized.POST("/add_rule", func(c *gin.Context) {
- var input struct {
- Listen string `json:"listen"`
- Remote string `json:"remote"`
- }
+ var input ForwardingRule
if err := c.ShouldBindJSON(&input); err != nil {
- c.JSON(400, gin.H{"error": "Invalid input"})
+ c.JSON(400, gin.H{"error": "无效的输入"})
return
}
mu.Lock()
- rules = append(rules, ForwardingRule{
- Listen: input.Listen,
- Remote: input.Remote,
- })
+ config.Endpoints = append(config.Endpoints, input)
mu.Unlock()
- if err := SaveRules(); err != nil {
- c.JSON(500, gin.H{"error": "Failed to save rules"})
+ if err := SaveConfig(); err != nil {
+ c.JSON(500, gin.H{"error": "保存配置失败"})
return
}
c.JSON(201, input)
})
- // 删除转发规则
authorized.DELETE("/delete_rule", func(c *gin.Context) {
listen := c.Query("listen")
mu.Lock()
- for i, rule := range rules {
+ found := false
+ for i, rule := range config.Endpoints {
if rule.Listen == listen {
- rules = append(rules[:i], rules[i+1:]...)
+ config.Endpoints = append(config.Endpoints[:i], config.Endpoints[i+1:]...)
+ found = true
break
}
}
mu.Unlock()
- if err := SaveRules(); err != nil {
- c.JSON(500, gin.H{"error": "Failed to save rules"})
+ if err := SaveConfig(); err != nil {
+ c.JSON(500, gin.H{"error": "保存转发规则失败"})
return
}
- c.Status(200)
+ if found {
+ c.JSON(200, gin.H{"message": "保存转发规则成功"})
+ } else {
+ c.JSON(404, gin.H{"error": "未找到转发规则"})
+ }
})
- // 启动服务
authorized.POST("/start_service", func(c *gin.Context) {
cmd := exec.Command("systemctl", "start", "realm")
if err := cmd.Run(); err != nil {
- c.JSON(500, gin.H{"error": "Failed to start service"})
+ c.JSON(500, gin.H{"error": "服务启动失败"})
return
}
- c.JSON(200, gin.H{"message": "Service started successfully"})
+ c.JSON(200, gin.H{"message": "服务启动成功"})
})
- // 停止服务
authorized.POST("/stop_service", func(c *gin.Context) {
cmd := exec.Command("systemctl", "stop", "realm")
if err := cmd.Run(); err != nil {
- c.JSON(500, gin.H{"error": "Failed to stop service"})
+ c.JSON(500, gin.H{"error": "服务停止失败"})
return
}
- c.JSON(200, gin.H{"message": "Service stopped successfully"})
+ c.JSON(200, gin.H{"message": "服务停止成功"})
})
- // 检查服务状态
authorized.GET("/check_status", func(c *gin.Context) {
cmd := exec.Command("systemctl", "is-active", "--quiet", "realm")
err := cmd.Run()
@@ -273,6 +288,13 @@ func main() {
c.JSON(200, gin.H{"status": status})
})
+
+ authorized.POST("/logout", func(c *gin.Context) {
+ session := sessions.Default(c)
+ session.Clear()
+ session.Save()
+ c.JSON(http.StatusOK, gin.H{"message": "登出成功"})
+ })
}
port := panelConfig.Server.Port
@@ -287,10 +309,24 @@ func main() {
r.Run(fmt.Sprintf(":%d", port))
} else {
log.Printf("服务器正在使用 HTTPS 运行,端口:%d\n", port)
- r.RunTLS(fmt.Sprintf(":%d", port), panelConfig.HTTPS.CertFile, panelConfig.HTTPS.KeyFile)
+ go func() {
+ log.Printf("HTTP 服务器正在运行,端口:8082,用于重定向到 HTTPS\n")
+ if err := http.ListenAndServe(":8082", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ target := "https://" + r.Host + r.URL.Path
+ if r.URL.RawQuery != "" {
+ target += "?" + r.URL.RawQuery
+ }
+ http.Redirect(w, r, target, http.StatusMovedPermanently)
+ })); err != nil {
+ log.Fatalf("HTTP 服务器错误: %v", err)
+ }
+ }()
+ if err := r.RunTLS(fmt.Sprintf(":%d", port), panelConfig.HTTPS.CertFile, panelConfig.HTTPS.KeyFile); err != nil {
+ log.Fatalf("HTTPS 服务器错误: %v", err)
+ }
}
} else {
- log.Println("警告:未启用 HTTPS,将使用 HTTP 继续。")
+ log.Println("警告:未启用 HTTPS,强烈建议启用 HTTPS。")
log.Printf("服务器正在使用 HTTP 运行,端口:%d\n", port)
r.Run(fmt.Sprintf(":%d", port))
}
diff --git a/web/templates/index.html b/web/templates/index.html
index 3f1def9..3cfa20b 100644
--- a/web/templates/index.html
+++ b/web/templates/index.html
@@ -118,6 +118,7 @@