mirror of
https://github.com/komari-monitor/komari.git
synced 2026-11-24 09:05:49 +00:00
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.
This commit is contained in:
1 parent
9d914e70b9
commit
7da616ce4c
31 files changed
+550
-320
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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"`
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,213 +0,0 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
v2 "github.com/komari-monitor/komari/protocol/v2"
|
||||
"github.com/komari-monitor/komari/web/ws"
|
||||
)
|
||||
|
||||
const (
|
||||
v2EventQueueLimit = 128
|
||||
v2EventTTL = 5 * time.Minute
|
||||
v2PingEventTTL = 3 * time.Second
|
||||
)
|
||||
|
||||
type v2EventQueue struct {
|
||||
events []v2.Event
|
||||
signal chan struct{}
|
||||
}
|
||||
|
||||
var (
|
||||
v2EventMu sync.Mutex
|
||||
v2EventQueues = make(map[string]*v2EventQueue)
|
||||
)
|
||||
|
||||
func getV2EventQueueLocked(uuid string) *v2EventQueue {
|
||||
q := v2EventQueues[uuid]
|
||||
if q == nil {
|
||||
q = &v2EventQueue{signal: make(chan struct{})}
|
||||
v2EventQueues[uuid] = q
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func DispatchV2Event(uuid, method string, params any) bool {
|
||||
if conn := ws.GetConnectedClients()[uuid]; conn != nil {
|
||||
payload := v2.Request{JSONRPC: v2.Version, Method: method, Params: params}
|
||||
return conn.WriteJSON(payload) == nil
|
||||
}
|
||||
if !ws.IsV2Client(uuid) {
|
||||
return false
|
||||
}
|
||||
EnqueueV2Event(uuid, method, params)
|
||||
return true
|
||||
}
|
||||
|
||||
func DispatchPing(uuid string, legacy any, params v2.PingParams) bool {
|
||||
if conn := ws.GetConnectedClients()[uuid]; conn != nil {
|
||||
payload := legacy
|
||||
if ws.IsV2Client(uuid) {
|
||||
payload = v2.Request{JSONRPC: v2.Version, Method: v2.MethodAgentPing, Params: params}
|
||||
}
|
||||
return conn.WriteJSON(payload) == nil
|
||||
}
|
||||
if !ws.IsV2Client(uuid) {
|
||||
return false
|
||||
}
|
||||
EnqueueV2Event(uuid, v2.MethodAgentPing, params)
|
||||
return true
|
||||
}
|
||||
|
||||
func IsAgentOnline(uuid string) bool {
|
||||
if ws.GetConnectedClients()[uuid] != nil {
|
||||
return true
|
||||
}
|
||||
return ws.IsV2Client(uuid)
|
||||
}
|
||||
|
||||
func EnqueueV2Event(uuid, method string, params any) v2.Event {
|
||||
now := time.Now()
|
||||
ttl := v2EventTTL
|
||||
if method == v2.MethodAgentPing {
|
||||
ttl = v2PingEventTTL
|
||||
}
|
||||
event := v2.Event{
|
||||
ID: newV2EventID(),
|
||||
Method: method,
|
||||
Params: params,
|
||||
CreatedAt: now.Format(time.RFC3339Nano),
|
||||
ExpiresAt: now.Add(ttl).Format(time.RFC3339Nano),
|
||||
}
|
||||
|
||||
v2EventMu.Lock()
|
||||
q := getV2EventQueueLocked(uuid)
|
||||
pruneExpiredV2EventsLocked(q)
|
||||
coalesceV2EventLocked(q, event)
|
||||
q.events = append(q.events, event)
|
||||
if len(q.events) > v2EventQueueLimit {
|
||||
q.events = q.events[len(q.events)-v2EventQueueLimit:]
|
||||
}
|
||||
close(q.signal)
|
||||
q.signal = make(chan struct{})
|
||||
v2EventMu.Unlock()
|
||||
|
||||
return event
|
||||
}
|
||||
|
||||
func newV2EventID() string {
|
||||
var b [8]byte
|
||||
if _, err := rand.Read(b[:]); err == nil {
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
return fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
}
|
||||
|
||||
func coalesceV2EventLocked(q *v2EventQueue, event v2.Event) {
|
||||
key := v2EventCoalesceKey(event)
|
||||
if key == "" {
|
||||
return
|
||||
}
|
||||
filtered := q.events[:0]
|
||||
for _, existing := range q.events {
|
||||
if v2EventCoalesceKey(existing) != key {
|
||||
filtered = append(filtered, existing)
|
||||
}
|
||||
}
|
||||
q.events = filtered
|
||||
}
|
||||
|
||||
func v2EventCoalesceKey(event v2.Event) string {
|
||||
if event.Method != v2.MethodAgentPing {
|
||||
return ""
|
||||
}
|
||||
var params v2.PingParams
|
||||
if err := bindV2EventParams(event.Params, ¶ms); err != nil || params.TaskID == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%s:%d", event.Method, params.TaskID)
|
||||
}
|
||||
|
||||
func bindV2EventParams(raw any, target any) error {
|
||||
b, err := json.Marshal(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(b, target)
|
||||
}
|
||||
|
||||
func ackV2EventsLocked(q *v2EventQueue, ackIDs []string) {
|
||||
if len(ackIDs) == 0 || len(q.events) == 0 {
|
||||
return
|
||||
}
|
||||
acked := make(map[string]struct{}, len(ackIDs))
|
||||
for _, id := range ackIDs {
|
||||
acked[id] = struct{}{}
|
||||
}
|
||||
filtered := q.events[:0]
|
||||
for _, event := range q.events {
|
||||
if _, ok := acked[event.ID]; !ok {
|
||||
filtered = append(filtered, event)
|
||||
}
|
||||
}
|
||||
q.events = filtered
|
||||
}
|
||||
|
||||
func pruneExpiredV2EventsLocked(q *v2EventQueue) {
|
||||
if len(q.events) == 0 {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
filtered := q.events[:0]
|
||||
for _, event := range q.events {
|
||||
if event.ExpiresAt == "" {
|
||||
filtered = append(filtered, event)
|
||||
continue
|
||||
}
|
||||
expiresAt, err := time.Parse(time.RFC3339Nano, event.ExpiresAt)
|
||||
if err != nil || expiresAt.After(now) {
|
||||
filtered = append(filtered, event)
|
||||
}
|
||||
}
|
||||
q.events = filtered
|
||||
}
|
||||
|
||||
func TakeV2Events(uuid string, ackIDs []string, limit int) []v2.Event {
|
||||
v2EventMu.Lock()
|
||||
defer v2EventMu.Unlock()
|
||||
|
||||
q := getV2EventQueueLocked(uuid)
|
||||
ackV2EventsLocked(q, ackIDs)
|
||||
pruneExpiredV2EventsLocked(q)
|
||||
if limit <= 0 || limit > len(q.events) {
|
||||
limit = len(q.events)
|
||||
}
|
||||
events := make([]v2.Event, limit)
|
||||
copy(events, q.events[:limit])
|
||||
return events
|
||||
}
|
||||
|
||||
func WaitV2Events(uuid string, ackIDs []string, timeout time.Duration) []v2.Event {
|
||||
events := TakeV2Events(uuid, ackIDs, v2EventQueueLimit)
|
||||
if len(events) > 0 || timeout <= 0 {
|
||||
return events
|
||||
}
|
||||
|
||||
v2EventMu.Lock()
|
||||
q := getV2EventQueueLocked(uuid)
|
||||
signal := q.signal
|
||||
v2EventMu.Unlock()
|
||||
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-signal:
|
||||
case <-timer.C:
|
||||
}
|
||||
return TakeV2Events(uuid, nil, v2EventQueueLimit)
|
||||
}
|
||||
+18
-21
@@ -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
|
||||
}
|
||||
+15
-18
@@ -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)
|
||||
}()
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
+7
-18
@@ -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
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user