修复wss连接、一些未知错误

This commit is contained in:
2026-03-28 18:58:52 +08:00
parent b66ba41431
commit 3d391415c6
8 changed files with 179 additions and 97 deletions

View File

@@ -5,9 +5,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
"net"
"net/http"
"net/url"
"strings"
"time"
@@ -68,17 +66,10 @@ type realtimeBackplane interface {
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" {
return true
}
parsed, err := url.Parse(origin)
if err != nil {
return false
}
return originHostMatchesRequest(parsed.Host, r)
// Device sessions are authenticated before upgrade. Keeping origin
// permissive avoids false negatives behind reverse proxies or custom
// domains where Host/Forwarded headers are rewritten.
return true
},
}
@@ -307,62 +298,3 @@ func (c *Client) writePump() {
}
}
}
func originHostMatchesRequest(originHost string, r *http.Request) bool {
requestHosts := []string{
strings.TrimSpace(r.Host),
strings.TrimSpace(r.Header.Get("X-Forwarded-Host")),
}
originName, err := normalizeHost(originHost)
if err != nil {
return false
}
for _, host := range requestHosts {
if host == "" {
continue
}
requestName, err := normalizeHost(host)
if err != nil {
continue
}
if requestName == originName {
return true
}
}
return false
}
func normalizeHost(host string) (string, error) {
host = strings.TrimSpace(host)
if host == "" {
return "", fmt.Errorf("empty host")
}
if strings.Contains(host, "://") {
parsed, err := url.Parse(host)
if err != nil {
return "", err
}
host = parsed.Host
}
name, _, err := net.SplitHostPort(host)
if err == nil {
host = name
} else if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = strings.TrimPrefix(strings.TrimSuffix(host, "]"), "[")
}
host = strings.ToLower(strings.TrimSpace(host))
switch host {
case "127.0.0.1", "::1":
return "localhost", nil
default:
return host, nil
}
}