Files
marqdo/plugins/web/internal/ws/connect.go
T
cflmyandCursor 86b183e2d7 fix(web): harden WebSocket and net host boundaries
- WS handshake: same-origin CheckOrigin instead of allow-all
- route_ws require_auth/需要登录: broadcast/room need a session by default,
  explicit opt-out for public feeds; unauthenticated handshakes get 401
- WS limits: 1 MiB per message, 256 replies per connect; transport errors
  return {ok:false, error} instead of an empty success; empty rooms GC'd
- net host: enforce the 8 MiB response cap while reading (incl. error and
  SSE error paths) so a peer cannot exhaust memory
- url_encode: %20 for space (URL segment semantics, not form +)
- docs: sync 网页 (route_ws 需要登录, connect caps) and CHANGELOG
- tests: gold expectations, live fixture opt-out, hub GC, ws auth gate

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 15:14:35 +08:00

97 lines
2.4 KiB
Go

package ws
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
)
const (
maxMessageBytes = 1 << 20
maxMessages = 256
)
// Connect dials url, sends one text message, collects text replies until close or timeout.
// Mirrors Rust ws::connect; errors are returned as {ok:false, error}.
func Connect(url, message string, headers map[string]any, timeoutSec uint64) map[string]any {
if !(strings.HasPrefix(url, "ws://") || strings.HasPrefix(url, "wss://")) {
return map[string]any{"ok": false, "error": "ws url must start with ws:// or wss://"}
}
if timeoutSec < 1 {
timeoutSec = 1
}
timeout := time.Duration(timeoutSec) * time.Second
hdr := http.Header{}
for k, v := range headersFromValue(headers) {
hdr.Set(k, v)
}
dialer := websocket.Dialer{HandshakeTimeout: timeout}
conn, _, err := dialer.Dial(url, hdr)
if err != nil {
return map[string]any{"ok": false, "error": fmt.Sprintf("ws connect: %v", err)}
}
defer conn.Close()
conn.SetReadLimit(maxMessageBytes)
if err := conn.SetWriteDeadline(time.Now().Add(timeout)); err != nil {
return map[string]any{"ok": false, "error": fmt.Sprintf("ws send: %v", err)}
}
if err := conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
return map[string]any{"ok": false, "error": fmt.Sprintf("ws send: %v", err)}
}
var messages []string
deadline := time.Now().Add(timeout)
for {
if err := conn.SetReadDeadline(deadline); err != nil {
break
}
mt, data, err := conn.ReadMessage()
if err != nil {
if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
break
}
return map[string]any{"ok": false, "error": fmt.Sprintf("ws receive: %v", err)}
}
if mt == websocket.TextMessage {
if len(messages) == maxMessages {
return map[string]any{"ok": false, "error": "ws receive: too many messages"}
}
messages = append(messages, string(data))
}
if mt == websocket.CloseMessage {
break
}
}
return map[string]any{"ok": true, "messages": toAnyList(messages)}
}
func headersFromValue(headers map[string]any) map[string]string {
out := map[string]string{}
if headers == nil {
return out
}
for k, v := range headers {
switch t := v.(type) {
case string:
out[k] = t
case nil:
out[k] = ""
default:
out[k] = fmt.Sprint(t)
}
}
return out
}
func toAnyList(ss []string) []any {
out := make([]any, len(ss))
for i, s := range ss {
out[i] = s
}
return out
}