From 7da616ce4c3052b4efd3f2d12e6d690fcfc11fce Mon Sep 17 00:00:00 2001 From: Akizon77 Date: Mon, 8 Jun 2026 20:45:00 +0800 Subject: [PATCH] feat(security): add configurable CORS and origin checks Add settings for allowed CORS origins and WebSocket origin validation so deployments can restrict cross-origin access instead of using a global wildcard policy. Move CORS handling into the security middleware and update report cache usage to use the dedicated report package. --- cmd/server.go | 30 +---- pkg/config/settings.go | 30 +++-- utils/notifier/traffic.go | 4 +- utils/pingSchedule.go | 4 +- utils/renewal/renewal.go | 4 +- .../connections.go} | 15 ++- web/{api => }/agent/v2_events.go | 15 ++- web/api/AuthSensitive.go | 111 ++++++++++++++++++ web/api/Common.go | 93 --------------- web/api/WebSocket.go | 61 ++++++++++ web/api/admin/client.go | 6 +- web/api/admin/exec.go | 15 ++- web/api/admin/update/user.go | 8 ++ web/api/client/report.go | 39 +++--- web/api/client/report_v2.go | 33 +++--- web/api/public/latestRecord.go | 3 +- web/api/public/mjpeg.go | 2 +- web/api/terminal/establish.go | 11 +- web/api/terminal/request.go | 15 +-- web/api/ws.go | 25 ++-- .../safeConn.go => connection/safe_conn.go} | 2 +- web/nezha/compat.go | 16 +-- web/report/cache.go | 84 +++++++++++++ web/router/router.go | 8 +- {pkg => web}/rpc/jsonrpc/JsonRpc.go | 16 +-- {pkg => web}/rpc/jsonrpc/common.go | 12 +- {pkg => web}/rpc/jsonrpc/common.record.go | 0 web/security/cors.go | 74 ++++++++++++ web/security/origin.go | 84 +++++++++++++ web/ws/origin.go | 25 ---- web/ws/upgrade.go | 25 ---- 31 files changed, 550 insertions(+), 320 deletions(-) rename web/{ws/existingConnection.go => agent/connections.go} (88%) rename web/{api => }/agent/v2_events.go (93%) create mode 100644 web/api/AuthSensitive.go create mode 100644 web/api/WebSocket.go rename web/{ws/safeConn.go => connection/safe_conn.go} (98%) create mode 100644 web/report/cache.go rename {pkg => web}/rpc/jsonrpc/JsonRpc.go (95%) rename {pkg => web}/rpc/jsonrpc/common.go (98%) rename {pkg => web}/rpc/jsonrpc/common.record.go (100%) create mode 100644 web/security/cors.go create mode 100644 web/security/origin.go delete mode 100644 web/ws/origin.go delete mode 100644 web/ws/upgrade.go diff --git a/cmd/server.go b/cmd/server.go index fd1855c..1f12127 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -32,14 +32,12 @@ import ( "github.com/komari-monitor/komari/utils/notifier" "github.com/komari-monitor/komari/web/nezha" "github.com/komari-monitor/komari/web/oauth" + report_cache "github.com/komari-monitor/komari/web/report" "github.com/komari-monitor/komari/web/router" + "github.com/komari-monitor/komari/web/security" "github.com/spf13/cobra" ) -var ( - DynamicCorsEnabled bool = false -) - var ServerCmd = &cobra.Command{ Use: "server", Short: "Start the server", @@ -126,13 +124,7 @@ func RunServer() { r.Use(logutil.GinLogger()) r.Use(logutil.GinRecovery()) - // 动态 CORS 中间件 - - DynamicCorsEnabled = conf.AllowCors config.Subscribe(func(event config.ConfigEvent) { - if ok, t := config.IsChangedT[bool](event, config.AllowCorsKey); ok { - DynamicCorsEnabled = t - } if event.IsChanged(config.GeoIpProviderKey) { go geoip.InitGeoIp() } @@ -142,21 +134,7 @@ func RunServer() { } }) - r.Use(func(c *gin.Context) { - if DynamicCorsEnabled { - c.Header("Access-Control-Allow-Origin", "*") - c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS") - c.Header("Access-Control-Allow-Headers", "Origin, Content-Length, Content-Type, Authorization, Accept, X-CSRF-Token, X-Requested-With, Set-Cookie") - c.Header("Access-Control-Expose-Headers", "Content-Length, Authorization, Set-Cookie") - c.Header("Access-Control-Allow-Credentials", "true") - c.Header("Access-Control-Max-Age", "43200") // 12 hours - if c.Request.Method == "OPTIONS" { - c.AbortWithStatus(204) - return - } - } - c.Next() - }) + r.Use(security.CorsMiddleware(conf.AllowCors, conf.CorsAllowedOrigins)) r.Use(api.IdentityMiddleware()) r.Use(api.PrivateSiteMiddleware()) @@ -238,7 +216,7 @@ func cleanupScheduledData() { func minuteScheduledWork() { cfg, _ := config.GetManyAs[config.Settings]() - api.SaveClientReportToDB() + report_cache.SaveClientReportToDB() if !cfg.RecordEnabled { records.DeleteAll() tasks.DeleteAllPingRecords() diff --git a/pkg/config/settings.go b/pkg/config/settings.go index 74f447d..d7d8bc0 100644 --- a/pkg/config/settings.go +++ b/pkg/config/settings.go @@ -3,18 +3,21 @@ package config import "time" type Settings struct { - ID uint `json:"id,omitempty"` // 1 - Sitename string `json:"sitename" default:"Komari"` // 站点名称,默认 "Komari" - Description string `json:"description" default:"A simple server monitor tool."` // 站点描述 - AllowCors bool `json:"allow_cors" default:"false"` // 是否允许跨域,默认 false - Theme string `json:"theme" default:"default"` // 主题名称,默认 'default' - PrivateSite bool `json:"private_site" default:"false"` // 是否为私有站点,默认 false - ApiKey string `json:"api_key" default:""` // API 密钥,默认空字符串 - AutoDiscoveryKey string `json:"auto_discovery_key" default:""` // 自动发现密钥 - ScriptDomain string `json:"script_domain" default:""` // 自定义脚本域名 - SendIpAddrToGuest bool `json:"send_ip_addr_to_guest" default:"false"` // 是否向访客页面发送 IP 地址,默认 false - EulaAccepted bool `json:"eula_accepted" default:"false"` - BaseScriptsURLKey string `json:"base_scripts_url" default:""` + ID uint `json:"id,omitempty"` // 1 + Sitename string `json:"sitename" default:"Komari"` // 站点名称,默认 "Komari" + Description string `json:"description" default:"A simple server monitor tool."` // 站点描述 + AllowCors bool `json:"allow_cors" default:"false"` // 是否允许跨域,默认 false + CorsAllowedOrigins string `json:"cors_allowed_origins" default:""` // API 跨域允许列表 + WsOriginCheckEnabled bool `json:"ws_origin_check_enabled" default:"true"` // 是否校验 WebSocket Origin + WsAllowedOrigins string `json:"ws_allowed_origins" default:""` // WebSocket Origin 允许列表 + Theme string `json:"theme" default:"default"` // 主题名称,默认 'default' + PrivateSite bool `json:"private_site" default:"false"` // 是否为私有站点,默认 false + ApiKey string `json:"api_key" default:""` // API 密钥,默认空字符串 + AutoDiscoveryKey string `json:"auto_discovery_key" default:""` // 自动发现密钥 + ScriptDomain string `json:"script_domain" default:""` // 自定义脚本域名 + SendIpAddrToGuest bool `json:"send_ip_addr_to_guest" default:"false"` // 是否向访客页面发送 IP 地址,默认 false + EulaAccepted bool `json:"eula_accepted" default:"false"` + BaseScriptsURLKey string `json:"base_scripts_url" default:""` // GeoIP 配置 GeoIpEnabled bool `json:"geo_ip_enabled" default:"true"` GeoIpProvider string `json:"geo_ip_provider" default:"ipinfo"` // empty, mmdb, ip-api, geojs @@ -48,6 +51,9 @@ const ( SitenameKey = "sitename" DescriptionKey = "description" AllowCorsKey = "allow_cors" + CorsAllowedOriginsKey = "cors_allowed_origins" + WsOriginCheckEnabledKey = "ws_origin_check_enabled" + WsAllowedOriginsKey = "ws_allowed_origins" ThemeKey = "theme" PrivateSiteKey = "private_site" ApiKeyKey = "api_key" diff --git a/utils/notifier/traffic.go b/utils/notifier/traffic.go index 05b7497..0daf9ee 100644 --- a/utils/notifier/traffic.go +++ b/utils/notifier/traffic.go @@ -11,7 +11,7 @@ import ( "github.com/komari-monitor/komari/database/models" "github.com/komari-monitor/komari/pkg/config" "github.com/komari-monitor/komari/utils/messageSender" - "github.com/komari-monitor/komari/web/ws" + agent_runtime "github.com/komari-monitor/komari/web/agent" cache "github.com/patrickmn/go-cache" ) @@ -23,7 +23,7 @@ var trafficCache = cache.New(30*24*time.Hour, time.Hour) // 30天缓存,1小 // 由外部协程每分钟调用一次 func CheckTraffic() { // 获取最新上报与客户端配置 - reports := ws.GetLatestReport() + reports := agent_runtime.GetLatestReport() if len(reports) == 0 { return } diff --git a/utils/pingSchedule.go b/utils/pingSchedule.go index 17b82da..8bdb0dc 100644 --- a/utils/pingSchedule.go +++ b/utils/pingSchedule.go @@ -9,7 +9,7 @@ import ( "github.com/komari-monitor/komari/database/models" "github.com/komari-monitor/komari/pkg/corn" v2 "github.com/komari-monitor/komari/protocol/v2" - agent_api "github.com/komari-monitor/komari/web/api/agent" + agent_runtime "github.com/komari-monitor/komari/web/agent" ) // PingTaskManager 管理定时器和任务 @@ -78,7 +78,7 @@ func executePingTask(ctx context.Context, task models.PingTask) { // Context is still active, continue. } - agent_api.DispatchPing(clientUUID, message, v2.PingParams{TaskID: task.Id, Type: task.Type, Target: task.Target}) + agent_runtime.DispatchPing(clientUUID, message, v2.PingParams{TaskID: task.Id, Type: task.Type, Target: task.Target}) } } diff --git a/utils/renewal/renewal.go b/utils/renewal/renewal.go index c98c47f..04a2ae3 100644 --- a/utils/renewal/renewal.go +++ b/utils/renewal/renewal.go @@ -9,7 +9,7 @@ import ( "github.com/komari-monitor/komari/database/models" messageevent "github.com/komari-monitor/komari/database/models/messageEvent" "github.com/komari-monitor/komari/utils/messageSender" - "github.com/komari-monitor/komari/web/ws" + agent_runtime "github.com/komari-monitor/komari/web/agent" ) func CheckAndAutoRenewal(client models.Client) { @@ -24,7 +24,7 @@ func CheckAndAutoRenewal(client models.Client) { return } // 不在线则不续费 - if _, ok := ws.GetConnectedClients()[client.UUID]; !ok { + if _, ok := agent_runtime.GetConnectedClients()[client.UUID]; !ok { return } diff --git a/web/ws/existingConnection.go b/web/agent/connections.go similarity index 88% rename from web/ws/existingConnection.go rename to web/agent/connections.go index 285eadd..50aa1f4 100644 --- a/web/ws/existingConnection.go +++ b/web/agent/connections.go @@ -1,17 +1,16 @@ -package ws +package agent import ( "sync" "time" - "github.com/gorilla/websocket" v1 "github.com/komari-monitor/komari/protocol/v1" + "github.com/komari-monitor/komari/web/connection" ) var ( - connectedClients = make(map[string]*SafeConn) + connectedClients = make(map[string]*connection.SafeConn) connectedClientV2 = make(map[string]bool) - ConnectedUsers = []*websocket.Conn{} latestReport = make(map[string]*v1.Report) // presenceOnly stores online state for non-WebSocket agents (e.g., Nezha gRPC) // value keeps connectionID and a soft expiration to avoid flicker @@ -22,17 +21,17 @@ var ( mu = sync.RWMutex{} ) -func GetConnectedClients() map[string]*SafeConn { +func GetConnectedClients() map[string]*connection.SafeConn { mu.RLock() defer mu.RUnlock() - clientsCopy := make(map[string]*SafeConn) + clientsCopy := make(map[string]*connection.SafeConn) for k, v := range connectedClients { clientsCopy[k] = v } return clientsCopy } -func SetConnectedClients(uuid string, conn *SafeConn) { +func SetConnectedClients(uuid string, conn *connection.SafeConn) { mu.Lock() defer mu.Unlock() connectedClients[uuid] = conn @@ -50,7 +49,7 @@ func IsV2Client(uuid string) bool { return connectedClientV2[uuid] } -func DeleteClientConditionally(uuid string, connToRemove *SafeConn) { +func DeleteClientConditionally(uuid string, connToRemove *connection.SafeConn) { mu.Lock() defer mu.Unlock() diff --git a/web/api/agent/v2_events.go b/web/agent/v2_events.go similarity index 93% rename from web/api/agent/v2_events.go rename to web/agent/v2_events.go index 23d9c79..2a42207 100644 --- a/web/api/agent/v2_events.go +++ b/web/agent/v2_events.go @@ -9,7 +9,6 @@ import ( "time" v2 "github.com/komari-monitor/komari/protocol/v2" - "github.com/komari-monitor/komari/web/ws" ) const ( @@ -38,11 +37,11 @@ func getV2EventQueueLocked(uuid string) *v2EventQueue { } func DispatchV2Event(uuid, method string, params any) bool { - if conn := ws.GetConnectedClients()[uuid]; conn != nil { + if conn := GetConnectedClients()[uuid]; conn != nil { payload := v2.Request{JSONRPC: v2.Version, Method: method, Params: params} return conn.WriteJSON(payload) == nil } - if !ws.IsV2Client(uuid) { + if !IsV2Client(uuid) { return false } EnqueueV2Event(uuid, method, params) @@ -50,14 +49,14 @@ func DispatchV2Event(uuid, method string, params any) bool { } func DispatchPing(uuid string, legacy any, params v2.PingParams) bool { - if conn := ws.GetConnectedClients()[uuid]; conn != nil { + if conn := GetConnectedClients()[uuid]; conn != nil { payload := legacy - if ws.IsV2Client(uuid) { + if IsV2Client(uuid) { payload = v2.Request{JSONRPC: v2.Version, Method: v2.MethodAgentPing, Params: params} } return conn.WriteJSON(payload) == nil } - if !ws.IsV2Client(uuid) { + if !IsV2Client(uuid) { return false } EnqueueV2Event(uuid, v2.MethodAgentPing, params) @@ -65,10 +64,10 @@ func DispatchPing(uuid string, legacy any, params v2.PingParams) bool { } func IsAgentOnline(uuid string) bool { - if ws.GetConnectedClients()[uuid] != nil { + if GetConnectedClients()[uuid] != nil { return true } - return ws.IsV2Client(uuid) + return IsV2Client(uuid) } func EnqueueV2Event(uuid, method string, params any) v2.Event { diff --git a/web/api/AuthSensitive.go b/web/api/AuthSensitive.go new file mode 100644 index 0000000..04e365e --- /dev/null +++ b/web/api/AuthSensitive.go @@ -0,0 +1,111 @@ +package api + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/komari-monitor/komari/database/accounts" +) + +func RequireSensitive2FA() gin.HandlerFunc { + return func(c *gin.Context) { + if err := VerifySensitive2FA(c); err != nil { + RespondError(c, http.StatusUnauthorized, err.Error()) + c.Abort() + return + } + c.Next() + } +} + +func VerifySensitive2FA(c *gin.Context) error { + if _, ok := c.Get("api_key"); ok { + return nil + } + uuid, ok := c.Get("uuid") + if !ok { + return err2FARequired() + } + uuidString, ok := uuid.(string) + if !ok || uuidString == "" { + return err2FARequired() + } + user, err := accounts.GetUserByUUID(uuidString) + if err != nil { + return err + } + if user.TwoFactor == "" { + return nil + } + code := get2FACode(c) + if code == "" { + return err2FARequired() + } + valid, err := accounts.Verify2Fa(uuidString, code) + if err != nil { + return err + } + if !valid { + return err2FAInvalid() + } + return nil +} + +func get2FACode(c *gin.Context) string { + if code, ok := c.Get("2fa_code"); ok { + if codeString, ok := code.(string); ok && codeString != "" { + return codeString + } + } + if code := c.GetHeader("X-2FA-Code"); code != "" { + return code + } + if code := c.GetHeader("X-Two-Factor-Code"); code != "" { + return code + } + for _, key := range []string{"2fa_code", "two_factor_code", "otp"} { + if code := c.Query(key); code != "" { + return code + } + } + if c.Request.Body == nil || c.Request.Method == http.MethodGet { + return "" + } + bodyBytes, err := io.ReadAll(c.Request.Body) + if err != nil { + return "" + } + c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes)) + if len(bodyBytes) == 0 { + return "" + } + var body map[string]interface{} + if err := json.Unmarshal(bodyBytes, &body); err != nil { + return "" + } + for _, key := range []string{"2fa_code", "two_factor_code", "otp"} { + if value, ok := body[key].(string); ok && value != "" { + return value + } + } + return "" +} + +func err2FARequired() error { + return &sensitive2FAError{"2FA code is required"} +} + +func err2FAInvalid() error { + return &sensitive2FAError{"Invalid 2FA code"} +} + +type sensitive2FAError struct { + message string +} + +func (e *sensitive2FAError) Error() string { + return e.message +} diff --git a/web/api/Common.go b/web/api/Common.go index 7764858..3bcb413 100644 --- a/web/api/Common.go +++ b/web/api/Common.go @@ -1,104 +1,11 @@ package api import ( - "log" "net/http" - "time" "github.com/gin-gonic/gin" - "github.com/komari-monitor/komari/protocol/v1" - "github.com/patrickmn/go-cache" - - "strconv" - - "github.com/komari-monitor/komari/database/dbcore" - "github.com/komari-monitor/komari/database/models" - "github.com/komari-monitor/komari/utils" ) -var ( - Records = cache.New(1*time.Minute, 1*time.Minute) -) - -func SaveClientReportToDB() error { - lastMinute := time.Now().Add(-time.Minute).Unix() - var records []models.Record - var gpuRecords []models.GPURecord - - // 遍历所有客户端记录 - for uuid, x := range Records.Items() { - if uuid == "" { - continue - } - - reports, ok := x.Object.([]v1.Report) - if !ok { - log.Printf("Invalid report type for UUID %s", uuid) - continue - } - - // 过滤一分钟前的记录 - var filtered []v1.Report - for _, r := range reports { - if r.UpdatedAt.Unix() >= lastMinute { - filtered = append(filtered, r) - } - } - - // 更新缓存 - Records.Set(uuid, filtered, cache.DefaultExpiration) - - // 计算平均报告并添加到记录列表 - if len(filtered) > 0 { - r := utils.AverageReport(uuid, time.Now(), filtered, 0.3) - records = append(records, r) - - // 使用与其他数据相同的聚合逻辑处理GPU数据 - gpuAggregated := utils.AverageGPUReports(uuid, time.Now(), filtered, 0.3) - gpuRecords = append(gpuRecords, gpuAggregated...) - } - } - - // 批量插入数据库前去重(client与time共同构成唯一键) - db := dbcore.GetDBInstance() - - if len(records) > 0 { - unique := make(map[string]models.Record) - for _, rec := range records { - key := rec.Client + "_" + strconv.FormatInt(rec.Time.ToTime().Unix(), 10) - unique[key] = rec - } - var deduped []models.Record - for _, rec := range unique { - deduped = append(deduped, rec) - } - if err := db.Model(&models.Record{}).Create(&deduped).Error; err != nil { - log.Printf("Failed to save records to database: %v", err) - return err - } - } - - // 批量插入GPU记录 - if len(gpuRecords) > 0 { - // GPU记录也需要去重,防止重复插入 - gpuUnique := make(map[string]models.GPURecord) - for _, rec := range gpuRecords { - key := rec.Client + "_" + strconv.Itoa(rec.DeviceIndex) + "_" + strconv.FormatInt(rec.Time.ToTime().Unix(), 10) - gpuUnique[key] = rec - } - var gpuDeduped []models.GPURecord - for _, rec := range gpuUnique { - gpuDeduped = append(gpuDeduped, rec) - } - if err := db.Model(&models.GPURecord{}).Create(&gpuDeduped).Error; err != nil { - log.Printf("Failed to save GPU records to database: %v", err) - return err - } - } - - return nil -} - type Response struct { Status string `json:"status"` Message string `json:"message"` diff --git a/web/api/WebSocket.go b/web/api/WebSocket.go new file mode 100644 index 0000000..c296bc9 --- /dev/null +++ b/web/api/WebSocket.go @@ -0,0 +1,61 @@ +package api + +import ( + "fmt" + "net/http" + "os" + "strings" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + "github.com/komari-monitor/komari/pkg/config" + "github.com/komari-monitor/komari/web/security" +) + +type WebSocketUpgradeOption func(*websocket.Upgrader) + +func IsWebSocketUpgrade(c *gin.Context) bool { + return websocket.IsWebSocketUpgrade(c.Request) +} + +func EnableWebSocketCompression(upgrader *websocket.Upgrader) { + upgrader.EnableCompression = true +} + +func UpgradeWebSocket(c *gin.Context, options ...WebSocketUpgradeOption) (*websocket.Conn, error) { + if !IsWebSocketUpgrade(c) { + return nil, fmt.Errorf("require websocket upgrade") + } + upgrader := websocket.Upgrader{ + CheckOrigin: CheckWebSocketOrigin, + } + for _, option := range options { + option(&upgrader) + } + return upgrader.Upgrade(c.Writer, c.Request, nil) +} + +func CheckWebSocketOrigin(r *http.Request) bool { + origin := r.Header.Get("Origin") + if strings.EqualFold(os.Getenv("KOMARI_WS_DISABLE_ORIGIN"), "true") { + return true + } + if security.IsAPIKeyRequest(r) { + return true + } + if origin == "" && r.URL.Query().Get("token") != "" { + return true + } + enabled, _ := config.GetAs[bool](config.WsOriginCheckEnabledKey, true) + if !enabled { + return true + } + if origin == "" { + return false + } + if security.OriginMatchesHost(origin, r.Host) { + return true + } + allowlist, _ := config.GetAs[string](config.WsAllowedOriginsKey, "") + return security.OriginInAllowlist(origin, allowlist) +} diff --git a/web/api/admin/client.go b/web/api/admin/client.go index eff0b5a..6a32f59 100644 --- a/web/api/admin/client.go +++ b/web/api/admin/client.go @@ -7,7 +7,7 @@ import ( "github.com/komari-monitor/komari/database/auditlog" "github.com/komari-monitor/komari/database/clients" "github.com/komari-monitor/komari/database/records" - "github.com/komari-monitor/komari/web/ws" + agent_runtime "github.com/komari-monitor/komari/web/agent" ) func AddClient(c *gin.Context) { @@ -68,8 +68,8 @@ func RemoveClient(c *gin.Context) { user_uuid, _ := c.Get("uuid") auditlog.Log(c.ClientIP(), user_uuid.(string), "delete client:"+uuid, "warn") c.JSON(200, gin.H{"status": "success"}) - ws.DeleteConnectedClients(uuid) - ws.DeleteLatestReport(uuid) + agent_runtime.DeleteConnectedClients(uuid) + agent_runtime.DeleteLatestReport(uuid) } func ClearRecord(c *gin.Context) { diff --git a/web/api/admin/exec.go b/web/api/admin/exec.go index 40b3d35..93a2ab0 100644 --- a/web/api/admin/exec.go +++ b/web/api/admin/exec.go @@ -12,9 +12,8 @@ import ( "github.com/komari-monitor/komari/database/tasks" v2 "github.com/komari-monitor/komari/protocol/v2" "github.com/komari-monitor/komari/utils" + agent_runtime "github.com/komari-monitor/komari/web/agent" "github.com/komari-monitor/komari/web/api" - agent_api "github.com/komari-monitor/komari/web/api/agent" - "github.com/komari-monitor/komari/web/ws" ) // 接受数据类型: @@ -36,7 +35,7 @@ func Exec(c *gin.Context) { api.RespondError(c, 400, "Command cannot be empty") return } - // for uuid := range ws.GetConnectedClients() { + // for uuid := range agent_runtime.GetConnectedClients() { // if contain(req.Clients, uuid) { // onlineClients = append(onlineClients, uuid) // } @@ -46,9 +45,9 @@ func Exec(c *gin.Context) { // // } // } for _, uuid := range req.Clients { - if client := ws.GetConnectedClients()[uuid]; client != nil { + if client := agent_runtime.GetConnectedClients()[uuid]; client != nil { onlineClients = append(onlineClients, uuid) - } else if agent_api.IsAgentOnline(uuid) { + } else if agent_runtime.IsAgentOnline(uuid) { queuedClients = append(queuedClients, uuid) } else { offlineClients = append(offlineClients, uuid) @@ -72,10 +71,10 @@ func Exec(c *gin.Context) { TaskId string `json:"task_id"` }{Message: "exec", Command: req.Command, TaskId: taskId} payload, _ := json.Marshal(legacy) - if ws.IsV2Client(uuid) { + if agent_runtime.IsV2Client(uuid) { payload, _ = json.Marshal(v2.Request{JSONRPC: v2.Version, Method: v2.MethodAgentExec, Params: v2.ExecParams{TaskID: taskId, Command: req.Command}}) } - client := ws.GetConnectedClients()[uuid] + client := agent_runtime.GetConnectedClients()[uuid] if client != nil { if err := client.WriteMessage(websocket.TextMessage, payload); err != nil { api.RespondError(c, 400, "Client connection is broke: "+uuid) @@ -87,7 +86,7 @@ func Exec(c *gin.Context) { } } for _, uuid := range queuedClients { - agent_api.DispatchV2Event(uuid, v2.MethodAgentExec, v2.ExecParams{TaskID: taskId, Command: req.Command}) + agent_runtime.DispatchV2Event(uuid, v2.MethodAgentExec, v2.ExecParams{TaskID: taskId, Command: req.Command}) } uuid, _ := c.Get("uuid") auditlog.Log(c.ClientIP(), uuid.(string), "REC, task id: "+taskId, "warn") diff --git a/web/api/admin/update/user.go b/web/api/admin/update/user.go index bab6daa..a91b92e 100644 --- a/web/api/admin/update/user.go +++ b/web/api/admin/update/user.go @@ -13,6 +13,7 @@ func UpdateUser(c *gin.Context) { Name *string `json:"username"` Password *string `json:"password"` SsoType *string `json:"sso_type"` + TwoFa string `json:"2fa_code"` } if err := c.ShouldBindJSON(&req); err != nil { api.RespondError(c, 400, "Invalid or missing request body: "+err.Error()) @@ -30,6 +31,13 @@ func UpdateUser(c *gin.Context) { api.RespondError(c, 400, "Password must be at least 6 characters long") return } + if req.Password != nil { + c.Set("2fa_code", req.TwoFa) + if err := api.VerifySensitive2FA(c); err != nil { + api.RespondError(c, 401, err.Error()) + return + } + } if err := accounts.UpdateUser(req.Uuid, req.Name, req.Password, req.SsoType); err != nil { api.RespondError(c, 500, "Failed to update user: "+err.Error()) return diff --git a/web/api/client/report.go b/web/api/client/report.go index d51d158..61badc9 100644 --- a/web/api/client/report.go +++ b/web/api/client/report.go @@ -18,8 +18,10 @@ import ( "github.com/komari-monitor/komari/database/tasks" v1 "github.com/komari-monitor/komari/protocol/v1" "github.com/komari-monitor/komari/utils/notifier" + agent_runtime "github.com/komari-monitor/komari/web/agent" "github.com/komari-monitor/komari/web/api" - "github.com/komari-monitor/komari/web/ws" + "github.com/komari-monitor/komari/web/connection" + report_cache "github.com/komari-monitor/komari/web/report" "github.com/patrickmn/go-cache" ) @@ -56,14 +58,14 @@ func refreshPostPresence(uuid string) { entry.timer = time.AfterFunc(readWait, func() { postPresenceExpired(uuid, entry.connID, gen) }) - ws.KeepAlivePresence(uuid, entry.connID, readWait) + agent_runtime.KeepAlivePresence(uuid, entry.connID, readWait) return } // 新 POST 会话:生成 connID,标记在线,启动超时定时器 connID := time.Now().UnixNano() - ws.KeepAlivePresence(uuid, connID, readWait) - ws.SetClientProtocolVersion(uuid, 1) + agent_runtime.KeepAlivePresence(uuid, connID, readWait) + agent_runtime.SetClientProtocolVersion(uuid, 1) go notifier.OnlineNotification(uuid, connID) defaultGeneration := uint64(0) @@ -93,7 +95,7 @@ func postPresenceExpired(uuid string, connID int64, gen uint64) { delete(postPresenceStates, uuid) postPresenceMu.Unlock() - ws.SetPresence(uuid, connID, false) + agent_runtime.SetPresence(uuid, connID, false) notifier.OfflineNotification(uuid, connID) } @@ -140,7 +142,7 @@ func UploadReport(c *gin.Context) { } // Update report with method and token - ws.SetLatestReport(uuid, &report) + agent_runtime.SetLatestReport(uuid, &report) // POST 上报后标记节点在线,超时未收到新 POST 则触发离线 refreshPostPresence(uuid) @@ -151,22 +153,17 @@ func UploadReport(c *gin.Context) { func WebSocketReport(c *gin.Context) { // 升级ws - if !websocket.IsWebSocketUpgrade(c.Request) { + if !api.IsWebSocketUpgrade(c) { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Require WebSocket upgrade"}) return } - upgrader := websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { - return true // 被控 - }, - } // Upgrade the HTTP connection to a WebSocket connection - unsafeConn, err := upgrader.Upgrade(c.Writer, c.Request, nil) + unsafeConn, err := api.UpgradeWebSocket(c) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Failed to upgrade to WebSocket." + err.Error()}) return } - conn := ws.NewSafeConn(unsafeConn) + conn := connection.NewSafeConn(unsafeConn) defer conn.Close() _, message, err := conn.ReadMessage() @@ -202,17 +199,17 @@ func WebSocketReport(c *gin.Context) { } // 接受新连接,并处理旧连接 - if oldConn, exists := ws.GetConnectedClients()[uuid]; exists { + if oldConn, exists := agent_runtime.GetConnectedClients()[uuid]; exists { log.Printf("Client %s is reconnecting. Closing the old connection.", uuid) // 强制关闭旧连接。这将导致旧连接的 ReadMessage() 循环出错退出。 go oldConn.Close() } - ws.SetConnectedClients(uuid, conn) + agent_runtime.SetConnectedClients(uuid, conn) log.Printf("Client %s is reconnect success, connID: %d", uuid, conn.ID) go notifier.OnlineNotification(uuid, conn.ID) defer func() { - ws.DeleteClientConditionally(uuid, conn) + agent_runtime.DeleteClientConditionally(uuid, conn) notifier.OfflineNotification(uuid, conn.ID) }() @@ -234,7 +231,7 @@ func WebSocketReport(c *gin.Context) { } // 将消息处理逻辑提取到一个函数中,方便复用 -func processMessage(conn *ws.SafeConn, message []byte, uuid string) { +func processMessage(conn *connection.SafeConn, message []byte, uuid string) { type MessageType struct { Type string `json:"type"` } @@ -259,7 +256,7 @@ func processMessage(conn *ws.SafeConn, message []byte, uuid string) { conn.WriteJSON(gin.H{"status": "error", "error": fmt.Sprintf("%v", err)}) return } - ws.SetLatestReport(uuid, &report) + agent_runtime.SetLatestReport(uuid, &report) case "ping_result": var reqBody struct { PingTaskID uint `json:"task_id"` @@ -286,7 +283,7 @@ func processMessage(conn *ws.SafeConn, message []byte, uuid string) { } func SaveClientReport(uuid string, report v1.Report) error { - reports, _ := api.Records.Get(uuid) + reports, _ := report_cache.Records.Get(uuid) if reports == nil { reports = []v1.Report{} } @@ -294,7 +291,7 @@ func SaveClientReport(uuid string, report v1.Report) error { report.CPU.Usage = 0.01 } reports = append(reports.([]v1.Report), report) - api.Records.Set(uuid, reports, cache.DefaultExpiration) + report_cache.Records.Set(uuid, reports, cache.DefaultExpiration) return nil } diff --git a/web/api/client/report_v2.go b/web/api/client/report_v2.go index 02c5b62..23c5167 100644 --- a/web/api/client/report_v2.go +++ b/web/api/client/report_v2.go @@ -17,8 +17,9 @@ import ( "github.com/komari-monitor/komari/database/tasks" v2 "github.com/komari-monitor/komari/protocol/v2" "github.com/komari-monitor/komari/utils/notifier" - agent_api "github.com/komari-monitor/komari/web/api/agent" - "github.com/komari-monitor/komari/web/ws" + agent_runtime "github.com/komari-monitor/komari/web/agent" + "github.com/komari-monitor/komari/web/api" + "github.com/komari-monitor/komari/web/connection" ) func readMaybeCompressedBody(r *http.Request) ([]byte, error) { @@ -58,12 +59,12 @@ func handleV2RPC(uuid string, req v2.Request, allowWait bool) v2.Response { if err := SaveClientReport(uuid, report); err != nil { return v2.Error(req.ID, -32000, "failed to save report", err.Error()) } - ws.SetLatestReport(uuid, &report) + agent_runtime.SetLatestReport(uuid, &report) refreshPostPresence(uuid) - ws.SetClientProtocolVersion(uuid, 2) + agent_runtime.SetClientProtocolVersion(uuid, 2) return v2.Success(req.ID, gin.H{ "status": "success", - "events": agent_api.TakeV2Events(uuid, params.AckEventIDs, 8), + "events": agent_runtime.TakeV2Events(uuid, params.AckEventIDs, 8), }) case v2.MethodAgentBasicInfo: var params v2.BasicInfoParams @@ -102,13 +103,13 @@ func handleV2RPC(uuid string, req v2.Request, allowWait bool) v2.Response { return v2.Error(req.ID, -32602, "invalid pull params", err.Error()) } refreshPostPresence(uuid) - ws.SetClientProtocolVersion(uuid, 2) + agent_runtime.SetClientProtocolVersion(uuid, 2) timeout := 0 * time.Second if allowWait { timeout = 25 * time.Second } return v2.Success(req.ID, gin.H{ - "events": agent_api.WaitV2Events(uuid, params.AckEventIDs, timeout), + "events": agent_runtime.WaitV2Events(uuid, params.AckEventIDs, timeout), }) default: return v2.Error(req.ID, -32601, "method not found", req.Method) @@ -140,20 +141,16 @@ func UploadV2RPC(c *gin.Context) { } func WebSocketV2RPC(c *gin.Context) { - if !websocket.IsWebSocketUpgrade(c.Request) { + if !api.IsWebSocketUpgrade(c) { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Require WebSocket upgrade"}) return } - upgrader := websocket.Upgrader{ - EnableCompression: true, - CheckOrigin: func(r *http.Request) bool { return true }, - } - unsafeConn, err := upgrader.Upgrade(c.Writer, c.Request, nil) + unsafeConn, err := api.UpgradeWebSocket(c, api.EnableWebSocketCompression) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Failed to upgrade to WebSocket." + err.Error()}) return } - conn := ws.NewSafeConn(unsafeConn) + conn := connection.NewSafeConn(unsafeConn) defer conn.Close() uuid, ok := clientUUIDFromContext(c) @@ -161,14 +158,14 @@ func WebSocketV2RPC(c *gin.Context) { conn.WriteJSON(v2.Error(nil, -32001, "invalid token", nil)) return } - if oldConn, exists := ws.GetConnectedClients()[uuid]; exists { + if oldConn, exists := agent_runtime.GetConnectedClients()[uuid]; exists { go oldConn.Close() } - ws.SetConnectedClients(uuid, conn) - ws.SetClientProtocolVersion(uuid, 2) + agent_runtime.SetConnectedClients(uuid, conn) + agent_runtime.SetClientProtocolVersion(uuid, 2) go notifierOnline(uuid, conn.ID) defer func() { - ws.DeleteClientConditionally(uuid, conn) + agent_runtime.DeleteClientConditionally(uuid, conn) notifierOffline(uuid, conn.ID) }() diff --git a/web/api/public/latestRecord.go b/web/api/public/latestRecord.go index 7645c27..60e8b69 100644 --- a/web/api/public/latestRecord.go +++ b/web/api/public/latestRecord.go @@ -6,6 +6,7 @@ import ( "github.com/komari-monitor/komari/database/dbcore" "github.com/komari-monitor/komari/database/models" "github.com/komari-monitor/komari/web/api" + report_cache "github.com/komari-monitor/komari/web/report" ) func GetClientRecentRecords(c *gin.Context) { @@ -40,6 +41,6 @@ func GetClientRecentRecords(c *gin.Context) { } } - records, _ := api.Records.Get(uuid) + records, _ := report_cache.Records.Get(uuid) api.RespondSuccess(c, records) } diff --git a/web/api/public/mjpeg.go b/web/api/public/mjpeg.go index 9d47850..83f78c0 100644 --- a/web/api/public/mjpeg.go +++ b/web/api/public/mjpeg.go @@ -23,7 +23,7 @@ import ( "github.com/gin-gonic/gin" "github.com/komari-monitor/komari/database/models" conf "github.com/komari-monitor/komari/pkg/config" - jsonRpc "github.com/komari-monitor/komari/pkg/rpc/jsonrpc" + jsonRpc "github.com/komari-monitor/komari/web/rpc/jsonrpc" "golang.org/x/image/font" "golang.org/x/image/font/basicfont" "golang.org/x/image/font/opentype" diff --git a/web/api/terminal/establish.go b/web/api/terminal/establish.go index 154365c..f9b5dfd 100644 --- a/web/api/terminal/establish.go +++ b/web/api/terminal/establish.go @@ -4,7 +4,7 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" + "github.com/komari-monitor/komari/web/api" ) func EstablishConnection(c *gin.Context) { @@ -15,16 +15,11 @@ func EstablishConnection(c *gin.Context) { return } // Upgrade the connection to WebSocket - if !websocket.IsWebSocketUpgrade(c.Request) { + if !api.IsWebSocketUpgrade(c) { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Require WebSocket upgrade"}) return } - upgrader := websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { - return true // 被控 - }, - } - conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) + conn, err := api.UpgradeWebSocket(c) if err != nil { TerminalSessionsMutex.Lock() if session.Browser != nil { diff --git a/web/api/terminal/request.go b/web/api/terminal/request.go index 268377d..db8b82f 100644 --- a/web/api/terminal/request.go +++ b/web/api/terminal/request.go @@ -6,10 +6,10 @@ import ( "time" "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" "github.com/komari-monitor/komari/database/clients" "github.com/komari-monitor/komari/utils" - "github.com/komari-monitor/komari/web/ws" + agent_runtime "github.com/komari-monitor/komari/web/agent" + "github.com/komari-monitor/komari/web/api" ) func RequestTerminal(c *gin.Context) { @@ -24,14 +24,11 @@ func RequestTerminal(c *gin.Context) { return } // 建立ws - if !websocket.IsWebSocketUpgrade(c.Request) { + if !api.IsWebSocketUpgrade(c) { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "Require WebSocket upgrade"}) return } - upgrader := websocket.Upgrader{ - CheckOrigin: ws.CheckOrigin, - } - conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) + conn, err := api.UpgradeWebSocket(c) if err != nil { return } @@ -60,7 +57,7 @@ func RequestTerminal(c *gin.Context) { return nil }) - if ws.GetConnectedClients()[uuid] == nil { + if agent_runtime.GetConnectedClients()[uuid] == nil { conn.WriteMessage(1, []byte("Client offline!\n被控端离线!\n")) conn.Close() TerminalSessionsMutex.Lock() @@ -68,7 +65,7 @@ func RequestTerminal(c *gin.Context) { TerminalSessionsMutex.Unlock() return } - err = ws.GetConnectedClients()[uuid].WriteJSON(gin.H{ + err = agent_runtime.GetConnectedClients()[uuid].WriteJSON(gin.H{ "message": "terminal", "request_id": id, }) diff --git a/web/api/ws.go b/web/api/ws.go index 00ec273..adc6427 100644 --- a/web/api/ws.go +++ b/web/api/ws.go @@ -5,32 +5,21 @@ import ( "strings" "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" - "github.com/komari-monitor/komari/protocol/v1" "github.com/komari-monitor/komari/database/accounts" "github.com/komari-monitor/komari/database/dbcore" "github.com/komari-monitor/komari/database/models" - "github.com/komari-monitor/komari/pkg/config" - "github.com/komari-monitor/komari/web/ws" + "github.com/komari-monitor/komari/protocol/v1" + agent_runtime "github.com/komari-monitor/komari/web/agent" ) func GetClients(c *gin.Context) { // 升级到ws - if !websocket.IsWebSocketUpgrade(c.Request) { + if !IsWebSocketUpgrade(c) { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Require WebSocket upgrade"}) return } - AllowCors, _ := config.GetAs[bool](config.AllowCorsKey, false) - upgrader := websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { - if AllowCors { - return true - } - return ws.CheckOrigin(r) - }, - } // Upgrade the HTTP connection to a WebSocket connection - conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) + conn, err := UpgradeWebSocket(c) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Failed to upgrade to WebSocket." + err.Error()}) return @@ -63,7 +52,7 @@ func GetClients(c *gin.Context) { // 请求 for { var resp struct { - Online []string `json:"online"` // 已建立连接的客户端uuid列表 + Online []string `json:"online"` // 已建立连接的客户端uuid列表 Data map[string]v1.Report `json:"data"` // 最后上报的数据 } @@ -88,7 +77,7 @@ func GetClients(c *gin.Context) { } // 在线客户端uuid列表(WebSocket 与非 WebSocket) - for _, key := range ws.GetAllOnlineUUIDs() { + for _, key := range agent_runtime.GetAllOnlineUUIDs() { if !isLogin && hiddenMap[key] { continue } @@ -99,7 +88,7 @@ func GetClients(c *gin.Context) { } //过往节点数据信息 - for key, report := range ws.GetLatestReport() { + for key, report := range agent_runtime.GetLatestReport() { if !isLogin && hiddenMap[key] { continue } diff --git a/web/ws/safeConn.go b/web/connection/safe_conn.go similarity index 98% rename from web/ws/safeConn.go rename to web/connection/safe_conn.go index 1d28630..3d7aa12 100644 --- a/web/ws/safeConn.go +++ b/web/connection/safe_conn.go @@ -1,4 +1,4 @@ -package ws +package connection import ( "sync" diff --git a/web/nezha/compat.go b/web/nezha/compat.go index 625b031..900827c 100644 --- a/web/nezha/compat.go +++ b/web/nezha/compat.go @@ -18,8 +18,8 @@ import ( v1 "github.com/komari-monitor/komari/protocol/v1" "github.com/komari-monitor/komari/utils/geoip" "github.com/komari-monitor/komari/utils/notifier" + agent_runtime "github.com/komari-monitor/komari/web/agent" apiClient "github.com/komari-monitor/komari/web/api/client" - "github.com/komari-monitor/komari/web/ws" "github.com/komari-monitor/komari/web/nezha/proto" "google.golang.org/grpc" @@ -187,10 +187,10 @@ func (s *nezhaCompatServer) ReportSystemState(stream proto.NezhaService_ReportSy } // presence start connID := time.Now().UnixNano() - ws.SetPresence(uuid, connID, true) + agent_runtime.SetPresence(uuid, connID, true) go notifier.OnlineNotification(uuid, connID) defer func() { - ws.SetPresence(uuid, connID, false) + agent_runtime.SetPresence(uuid, connID, false) notifier.OfflineNotification(uuid, connID) }() for { @@ -202,7 +202,7 @@ func (s *nezhaCompatServer) ReportSystemState(stream proto.NezhaService_ReportSy return err } // refresh presence TTL on every frame - ws.KeepAlivePresence(uuid, connID, 30*time.Second) + agent_runtime.KeepAlivePresence(uuid, connID, 30*time.Second) if err := ingestState(uuid, st); err != nil { // still ack to avoid client stuck; log error log.Printf("Nezha ingest state error: %v", err) @@ -223,8 +223,8 @@ func (s *nezhaCompatServer) RequestTask(stream proto.NezhaService_RequestTaskSer ticker := time.NewTicker(10 * time.Second) defer ticker.Stop() connID := time.Now().UnixNano() - ws.SetPresence(uuid, connID, true) - defer ws.SetPresence(uuid, connID, false) + agent_runtime.SetPresence(uuid, connID, true) + defer agent_runtime.SetPresence(uuid, connID, false) // receive results in background recvErr := make(chan error, 1) go func() { @@ -239,7 +239,7 @@ func (s *nezhaCompatServer) RequestTask(stream proto.NezhaService_RequestTaskSer return } // refresh presence TTL when result received - ws.KeepAlivePresence(uuid, connID, 30*time.Second) + agent_runtime.KeepAlivePresence(uuid, connID, 30*time.Second) } }() // send heartbeat tasks periodically @@ -354,7 +354,7 @@ func ingestState(uuid string, st *proto.State) error { UpdatedAt: time.Now(), } // 更新实时缓存供前端使用 - ws.SetLatestReport(uuid, &rep) + agent_runtime.SetLatestReport(uuid, &rep) // 写入内存缓存,入库交由定时聚合任务处理 return apiClient.SaveClientReport(uuid, rep) } diff --git a/web/report/cache.go b/web/report/cache.go new file mode 100644 index 0000000..019b066 --- /dev/null +++ b/web/report/cache.go @@ -0,0 +1,84 @@ +package report + +import ( + "log" + "strconv" + "time" + + "github.com/komari-monitor/komari/database/dbcore" + "github.com/komari-monitor/komari/database/models" + "github.com/komari-monitor/komari/protocol/v1" + "github.com/komari-monitor/komari/utils" + "github.com/patrickmn/go-cache" +) + +var Records = cache.New(1*time.Minute, 1*time.Minute) + +func SaveClientReportToDB() error { + lastMinute := time.Now().Add(-time.Minute).Unix() + var records []models.Record + var gpuRecords []models.GPURecord + + for uuid, x := range Records.Items() { + if uuid == "" { + continue + } + + reports, ok := x.Object.([]v1.Report) + if !ok { + log.Printf("Invalid report type for UUID %s", uuid) + continue + } + + var filtered []v1.Report + for _, r := range reports { + if r.UpdatedAt.Unix() >= lastMinute { + filtered = append(filtered, r) + } + } + + Records.Set(uuid, filtered, cache.DefaultExpiration) + + if len(filtered) > 0 { + r := utils.AverageReport(uuid, time.Now(), filtered, 0.3) + records = append(records, r) + gpuRecords = append(gpuRecords, utils.AverageGPUReports(uuid, time.Now(), filtered, 0.3)...) + } + } + + db := dbcore.GetDBInstance() + + if len(records) > 0 { + unique := make(map[string]models.Record) + for _, rec := range records { + key := rec.Client + "_" + strconv.FormatInt(rec.Time.ToTime().Unix(), 10) + unique[key] = rec + } + var deduped []models.Record + for _, rec := range unique { + deduped = append(deduped, rec) + } + if err := db.Model(&models.Record{}).Create(&deduped).Error; err != nil { + log.Printf("Failed to save records to database: %v", err) + return err + } + } + + if len(gpuRecords) > 0 { + gpuUnique := make(map[string]models.GPURecord) + for _, rec := range gpuRecords { + key := rec.Client + "_" + strconv.Itoa(rec.DeviceIndex) + "_" + strconv.FormatInt(rec.Time.ToTime().Unix(), 10) + gpuUnique[key] = rec + } + var gpuDeduped []models.GPURecord + for _, rec := range gpuUnique { + gpuDeduped = append(gpuDeduped, rec) + } + if err := db.Model(&models.GPURecord{}).Create(&gpuDeduped).Error; err != nil { + log.Printf("Failed to save GPU records to database: %v", err) + return err + } + } + + return nil +} diff --git a/web/router/router.go b/web/router/router.go index aeafeb3..2c0bee5 100644 --- a/web/router/router.go +++ b/web/router/router.go @@ -2,7 +2,6 @@ package router import ( "github.com/gin-gonic/gin" - jsonRpc "github.com/komari-monitor/komari/pkg/rpc/jsonrpc" "github.com/komari-monitor/komari/web/api" "github.com/komari-monitor/komari/web/api/admin" "github.com/komari-monitor/komari/web/api/admin/clipboard" @@ -14,6 +13,7 @@ import ( public_api "github.com/komari-monitor/komari/web/api/public" "github.com/komari-monitor/komari/web/api/terminal" "github.com/komari-monitor/komari/web/public" + jsonRpc "github.com/komari-monitor/komari/web/rpc/jsonrpc" ) // Register binds all HTTP, WebSocket, JSON-RPC and static frontend routes. @@ -76,7 +76,7 @@ func Register(r *gin.Engine) { taskGroup := adminAuthrized.Group("/task") { taskGroup.GET("/all", admin.GetTasks) - taskGroup.POST("/exec", admin.Exec) + taskGroup.POST("/exec", api.RequireSensitive2FA(), admin.Exec) taskGroup.GET("/:task_id", admin.GetTaskById) taskGroup.GET("/:task_id/result", admin.GetTaskResultsByTaskId) taskGroup.GET("/:task_id/result/:uuid", admin.GetSpecificTaskResult) @@ -120,7 +120,7 @@ func Register(r *gin.Engine) { clientGroup.GET("/:uuid/token", admin.GetClientToken) clientGroup.POST("/order", admin.OrderWeight) // client terminal - clientGroup.GET("/:uuid/terminal", terminal.RequestTerminal) + clientGroup.GET("/:uuid/terminal", api.RequireSensitive2FA(), terminal.RequestTerminal) } // records @@ -145,7 +145,7 @@ func Register(r *gin.Engine) { { two_factorGroup.GET("/generate", admin.Generate2FA) two_factorGroup.POST("/enable", admin.Enable2FA) - two_factorGroup.POST("/disable", admin.Disable2FA) + two_factorGroup.POST("/disable", api.RequireSensitive2FA(), admin.Disable2FA) } adminAuthrized.GET("/logs", log_api.GetLogs) diff --git a/pkg/rpc/jsonrpc/JsonRpc.go b/web/rpc/jsonrpc/JsonRpc.go similarity index 95% rename from pkg/rpc/jsonrpc/JsonRpc.go rename to web/rpc/jsonrpc/JsonRpc.go index 7bdb4f7..a3ba0ed 100644 --- a/pkg/rpc/jsonrpc/JsonRpc.go +++ b/web/rpc/jsonrpc/JsonRpc.go @@ -15,7 +15,8 @@ import ( "github.com/komari-monitor/komari/database/clients" "github.com/komari-monitor/komari/pkg/config" "github.com/komari-monitor/komari/pkg/rpc" - "github.com/komari-monitor/komari/web/ws" + "github.com/komari-monitor/komari/web/api" + "github.com/komari-monitor/komari/web/connection" ) // OnInternalRequest 内部调用 RPC 方法,支持权限控制 @@ -63,21 +64,14 @@ func OnInternalRequest(ctx context.Context, group string, method string, params // Json Rpc2 over websocket, /api/rpc2 func OnRpcRequest(c *gin.Context) { - AllowCors, _ := config.GetAs[bool](config.AllowCorsKey) - // GET -> WebSocket if c.Request.Method == http.MethodGet { - _conn, err := ws.UpgradeRequest(c, func(r *http.Request) bool { - if AllowCors { - return true - } - return ws.CheckOrigin(r) - }) - conn := ws.NewSafeConn(_conn) + _conn, err := api.UpgradeWebSocket(c) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "Failed to upgrade to WebSocket." + err.Error()}) return } + conn := connection.NewSafeConn(_conn) permissionGroup := detectPermissionGroup(c) meta := buildContextMeta(c, permissionGroup) defer conn.Close() @@ -213,7 +207,7 @@ func buildContextMeta(c *gin.Context, permissionGroup string) *rpc.ContextMeta { } // dispatchByPermissionWithMeta 与原函数类似,但会携带 meta 上下文给 handler -func dispatchByPermissionWithMeta(conn *ws.SafeConn, permissionGroup string, meta *rpc.ContextMeta, req *rpc.JsonRpcRequest) { +func dispatchByPermissionWithMeta(conn *connection.SafeConn, permissionGroup string, meta *rpc.ContextMeta, req *rpc.JsonRpcRequest) { fc := strings.Split(req.Method, ":") if len(fc) == 1 { fc[0] = "common" diff --git a/pkg/rpc/jsonrpc/common.go b/web/rpc/jsonrpc/common.go similarity index 98% rename from pkg/rpc/jsonrpc/common.go rename to web/rpc/jsonrpc/common.go index 42db6c6..188fcbd 100644 --- a/pkg/rpc/jsonrpc/common.go +++ b/web/rpc/jsonrpc/common.go @@ -8,7 +8,6 @@ import ( "strings" "time" - "github.com/komari-monitor/komari/protocol/v1" "github.com/komari-monitor/komari/database" "github.com/komari-monitor/komari/database/clients" "github.com/komari-monitor/komari/database/dbcore" @@ -16,9 +15,10 @@ import ( "github.com/komari-monitor/komari/database/tasks" "github.com/komari-monitor/komari/pkg/config" "github.com/komari-monitor/komari/pkg/rpc" + "github.com/komari-monitor/komari/protocol/v1" "github.com/komari-monitor/komari/utils" - "github.com/komari-monitor/komari/web/api" - "github.com/komari-monitor/komari/web/ws" + agent_runtime "github.com/komari-monitor/komari/web/agent" + report_cache "github.com/komari-monitor/komari/web/report" cache "github.com/patrickmn/go-cache" ) @@ -285,8 +285,8 @@ func getNodesLatestStatus(ctx context.Context, req *rpc.JsonRpcRequest) (any, *r req.BindParams(¶ms) meta := rpc.MetaFromContext(ctx) - latest := ws.GetLatestReport() // map[string]*v1.Report (copy) - onlineUUIDs := ws.GetAllOnlineUUIDs() + latest := agent_runtime.GetLatestReport() // map[string]*v1.Report (copy) + onlineUUIDs := agent_runtime.GetAllOnlineUUIDs() onlineSet := make(map[string]bool, len(onlineUUIDs)) for _, uuid := range onlineUUIDs { onlineSet[uuid] = true @@ -487,7 +487,7 @@ func getNodeRecentStatus(ctx context.Context, req *rpc.JsonRpcRequest) (any, *rp } } - raw, _ := api.Records.Get(params.UUID) + raw, _ := report_cache.Records.Get(params.UUID) reports, _ := raw.([]v1.Report) // 扁平化为 { count, records: [] } diff --git a/pkg/rpc/jsonrpc/common.record.go b/web/rpc/jsonrpc/common.record.go similarity index 100% rename from pkg/rpc/jsonrpc/common.record.go rename to web/rpc/jsonrpc/common.record.go diff --git a/web/security/cors.go b/web/security/cors.go new file mode 100644 index 0000000..3f6f7b2 --- /dev/null +++ b/web/security/cors.go @@ -0,0 +1,74 @@ +package security + +import ( + "net/http" + "sync" + + "github.com/gin-gonic/gin" + "github.com/komari-monitor/komari/pkg/config" +) + +func CorsMiddleware(initialEnabled bool, initialAllowedOrigins string) gin.HandlerFunc { + var mu sync.RWMutex + enabled := initialEnabled + allowedOrigins := initialAllowedOrigins + + config.Subscribe(func(event config.ConfigEvent) { + mu.Lock() + defer mu.Unlock() + if ok, t := config.IsChangedT[bool](event, config.AllowCorsKey); ok { + enabled = t + } + if ok, t := config.IsChangedT[string](event, config.CorsAllowedOriginsKey); ok { + allowedOrigins = t + } + }) + + return func(c *gin.Context) { + mu.RLock() + corsEnabled := enabled + corsAllowedOrigins := allowedOrigins + mu.RUnlock() + + if !corsEnabled { + c.Next() + return + } + + origin := c.GetHeader("Origin") + allowOrigin := "" + if origin != "" && (IsAPIKeyRequest(c.Request) || + OriginMatchesHost(origin, c.Request.Host) || + OriginInAllowlist(origin, corsAllowedOrigins)) { + allowOrigin = origin + } + + authorizationPreflight := origin != "" && allowOrigin == "" && IsAuthorizationPreflight(c.Request) + if authorizationPreflight { + allowOrigin = origin + } + + if allowOrigin != "" { + c.Header("Access-Control-Allow-Origin", allowOrigin) + c.Header("Vary", "Origin") + c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS") + c.Header("Access-Control-Allow-Headers", "Origin, Content-Length, Content-Type, Authorization, Accept, X-CSRF-Token, X-Requested-With, Set-Cookie, X-2FA-Code, X-Two-Factor-Code") + c.Header("Access-Control-Expose-Headers", "Content-Length, Authorization, Set-Cookie") + if !authorizationPreflight { + c.Header("Access-Control-Allow-Credentials", "true") + } + c.Header("Access-Control-Max-Age", "43200") // 12 hours + } + + if c.Request.Method == http.MethodOptions { + if allowOrigin != "" { + c.AbortWithStatus(http.StatusNoContent) + } else { + c.AbortWithStatus(http.StatusForbidden) + } + return + } + + c.Next() + } +} diff --git a/web/security/origin.go b/web/security/origin.go new file mode 100644 index 0000000..9ea9f7a --- /dev/null +++ b/web/security/origin.go @@ -0,0 +1,84 @@ +package security + +import ( + "net/http" + "net/url" + "strings" + + "github.com/komari-monitor/komari/pkg/config" +) + +func SplitAllowlist(raw string) []string { + parts := strings.FieldsFunc(raw, func(r rune) bool { + return r == ',' || r == '\n' || r == '\r' + }) + entries := make([]string, 0, len(parts)) + for _, part := range parts { + entry := strings.TrimSpace(part) + if entry != "" { + entries = append(entries, entry) + } + } + return entries +} + +func HasAllowlist(raw string) bool { + return len(SplitAllowlist(raw)) > 0 +} + +func OriginMatchesHost(origin, host string) bool { + _, originHost, ok := normalizeOrigin(origin) + return ok && strings.EqualFold(originHost, host) +} + +func OriginInAllowlist(origin, rawAllowlist string) bool { + normalizedOrigin, originHost, ok := normalizeOrigin(origin) + if !ok { + return false + } + for _, entry := range SplitAllowlist(rawAllowlist) { + if entry == "*" { + return true + } + if strings.Contains(entry, "://") { + normalizedEntry, _, ok := normalizeOrigin(entry) + if ok && strings.EqualFold(normalizedEntry, normalizedOrigin) { + return true + } + continue + } + if strings.EqualFold(entry, originHost) { + return true + } + } + return false +} + +func IsAPIKeyRequest(r *http.Request) bool { + apiKeyConfig, err := config.GetAs[string](config.ApiKeyKey, "") + if err != nil || apiKeyConfig == "" || len(apiKeyConfig) < 12 { + return false + } + return r.Header.Get("Authorization") == "Bearer "+apiKeyConfig +} + +func IsAuthorizationPreflight(r *http.Request) bool { + if r.Method != http.MethodOptions { + return false + } + for _, header := range strings.Split(r.Header.Get("Access-Control-Request-Headers"), ",") { + if strings.EqualFold(strings.TrimSpace(header), "authorization") { + return true + } + } + return false +} + +func normalizeOrigin(raw string) (string, string, bool) { + parsed, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || parsed.Scheme == "" || parsed.Host == "" { + return "", "", false + } + host := strings.ToLower(parsed.Host) + return strings.ToLower(parsed.Scheme) + "://" + host, host, true +} diff --git a/web/ws/origin.go b/web/ws/origin.go deleted file mode 100644 index 9a7c707..0000000 --- a/web/ws/origin.go +++ /dev/null @@ -1,25 +0,0 @@ -package ws - -import ( - "net/http" - "net/url" - "os" - "strings" -) - -func CheckOrigin(r *http.Request) bool { - origin := r.Header.Get("Origin") - // 显式关闭校验 - if strings.EqualFold(os.Getenv("KOMARI_WS_DISABLE_ORIGIN"), "true") { - return true - } - if origin == "" { - return false - } - host := r.Host - originUrl, err := url.Parse(origin) - if err != nil { - return false - } - return originUrl.Host == host -} diff --git a/web/ws/upgrade.go b/web/ws/upgrade.go deleted file mode 100644 index 9dde9c7..0000000 --- a/web/ws/upgrade.go +++ /dev/null @@ -1,25 +0,0 @@ -package ws - -import ( - "fmt" - "net/http" - - "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" -) - -func UpgradeRequest(c *gin.Context, checkOrigin func(r *http.Request) bool) (*websocket.Conn, error) { - // 升级到ws - if !websocket.IsWebSocketUpgrade(c.Request) { - return nil, fmt.Errorf("require websocket upgrade") - } - upgrader := websocket.Upgrader{ - CheckOrigin: checkOrigin, - } - // Upgrade the HTTP connection to a WebSocket connection - conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) - if err != nil { - return nil, err - } - return conn, nil -}