优化客服云权限安全与访客IP解析

This commit is contained in:
yml2213
2026-08-31 13:43:45 +08:00
parent 523a306d5e
commit bdf67395ab
24 changed files with 365 additions and 48 deletions
+31 -1
View File
@@ -24,10 +24,40 @@ func processDraftContacts(tenantID, customerID, sessionID uint, text string) {
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
CheckOrigin: checkOrigin,
Subprotocols: []string{"kefu-v1", "kefu-visitor-v1"},
}
var (
originMu sync.RWMutex
allowedOrigins = []string{"*"}
)
// SetAllowedOrigins configures the origins accepted during WebSocket upgrade.
func SetAllowedOrigins(origins []string) {
originMu.Lock()
defer originMu.Unlock()
allowedOrigins = append([]string(nil), origins...)
if len(allowedOrigins) == 0 {
allowedOrigins = []string{"*"}
}
}
func checkOrigin(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
originMu.RLock()
defer originMu.RUnlock()
for _, allowed := range allowedOrigins {
if allowed == "*" || allowed == origin {
return true
}
}
return false
}
type Client struct {
Conn *websocket.Conn
UserID uint
+16
View File
@@ -1,10 +1,26 @@
package ws
import (
"net/http/httptest"
"testing"
"time"
)
func TestCheckOriginUsesConfiguredAllowlist(t *testing.T) {
SetAllowedOrigins([]string{"https://portal.example"})
defer SetAllowedOrigins([]string{"*"})
allowed := httptest.NewRequest("GET", "/api/ws", nil)
allowed.Header.Set("Origin", "https://portal.example")
if !checkOrigin(allowed) {
t.Fatal("白名单来源应允许 WebSocket 升级")
}
denied := httptest.NewRequest("GET", "/api/ws", nil)
denied.Header.Set("Origin", "https://evil.example")
if checkOrigin(denied) {
t.Fatal("非白名单来源不应允许 WebSocket 升级")
}
}
func TestBroadcastToSessionRestrictsRecipients(t *testing.T) {
hub := NewHub()
go hub.Run()