- 增加信令访问令牌、HTTPS 校验、限流及跨网段中继连接修复 - 同步三端媒体 v2 协议,实现 AES-GCM、防重放和乱序分片重组,升级 Rust ABI 6 - 修复文件鉴权、权限协商及剪贴板越权,完善上传校验和串流超时处理 - 增加跨端回归测试及部署文档,在 AGENTS.md 记录真机与真实跨网段待验收项目
87 lines
2.0 KiB
Go
87 lines
2.0 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type quota struct {
|
|
tokens float64
|
|
updated time.Time
|
|
watches int
|
|
}
|
|
|
|
// Secure protects discovery, registration and relay with the same private-network
|
|
// credential. It is not a per-device identity or multi-tenant authorization system.
|
|
func Secure(next http.Handler, token string) http.Handler {
|
|
expected := sha256.Sum256([]byte(token))
|
|
var mu sync.Mutex
|
|
clients := make(map[string]*quota)
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
if err != nil {
|
|
host = r.RemoteAddr
|
|
}
|
|
now := time.Now()
|
|
mu.Lock()
|
|
q := clients[host]
|
|
if q == nil {
|
|
for key, old := range clients {
|
|
if now.Sub(old.updated) > 5*time.Minute && old.watches == 0 {
|
|
delete(clients, key)
|
|
}
|
|
}
|
|
if len(clients) >= 4096 {
|
|
mu.Unlock()
|
|
http.Error(w, "server busy", 503)
|
|
return
|
|
}
|
|
q = "a{tokens: 400, updated: now}
|
|
clients[host] = q
|
|
}
|
|
q.tokens += now.Sub(q.updated).Seconds() * 200
|
|
if q.tokens > 400 {
|
|
q.tokens = 400
|
|
}
|
|
q.updated = now
|
|
if q.tokens < 1 {
|
|
mu.Unlock()
|
|
w.Header().Set("Retry-After", "1")
|
|
http.Error(w, "rate limited", 429)
|
|
return
|
|
}
|
|
q.tokens--
|
|
mu.Unlock()
|
|
if r.URL.Path == "/healthz" && r.Method == http.MethodGet {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
if token != "" {
|
|
auth := r.Header.Get("Authorization")
|
|
actual := sha256.Sum256([]byte(strings.TrimPrefix(auth, "Bearer ")))
|
|
if !strings.HasPrefix(auth, "Bearer ") || subtle.ConstantTimeCompare(actual[:], expected[:]) != 1 {
|
|
w.Header().Set("WWW-Authenticate", "Bearer")
|
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
}
|
|
if r.URL.Path == "/watch" {
|
|
mu.Lock()
|
|
if q.watches >= 4 {
|
|
mu.Unlock()
|
|
http.Error(w, "too many watches", 429)
|
|
return
|
|
}
|
|
q.watches++
|
|
mu.Unlock()
|
|
defer func() { mu.Lock(); q.watches--; mu.Unlock() }()
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|