Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: improve code quality in proxy_ws and human packages

Mario3a0b829150f2
diff --git a/internal/handlers/proxy_ws.go b/internal/handlers/proxy_ws.go
index d12c47ae..416df93f 100644
--- a/internal/handlers/proxy_ws.go
+++ b/internal/handlers/proxy_ws.go
@@ -1,19 +1,22 @@
package handlers
import (
+ "bufio"
+ "fmt"
"io"
"log/slog"
"net"
"net/http"
+ "net/textproto"
"strings"
)
// ProxyWebSocket does a raw TCP tunnel for WebSocket connections.
-// This is the simplest approach — no frame parsing, just bidirectional copy.
+// Uses proper HTTP request construction for standards compliance.
func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
-
- wsTarget := strings.Replace(targetURL, "http://", "", 1)
- wsTarget = strings.Replace(wsTarget, "https://", "", 1)
+ // Parse target URL
+ wsTarget := strings.TrimPrefix(targetURL, "http://")
+ wsTarget = strings.TrimPrefix(wsTarget, "https://")
host := wsTarget
path := "/"
@@ -22,6 +25,7 @@ func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
path = wsTarget[idx:]
}
+ // Connect to backend
backend, err := net.Dial("tcp", host)
if err != nil {
http.Error(w, "backend unavailable", http.StatusBadGateway)
@@ -30,6 +34,7 @@ func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
}
defer func() { _ = backend.Close() }()
+ // Hijack client connection
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "server doesn't support hijacking", http.StatusInternalServerError)
@@ -42,18 +47,44 @@ func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
}
defer func() { _ = client.Close() }()
- reqLine := r.Method + " " + path + " HTTP/1.1\r\n"
- _, _ = backend.Write([]byte(reqLine))
- _, _ = backend.Write([]byte("Host: " + host + "\r\n"))
- for k, vv := range r.Header {
- for _, v := range vv {
- _, _ = backend.Write([]byte(k + ": " + v + "\r\n"))
+ // Write properly formatted HTTP request to backend
+ writer := bufio.NewWriter(backend)
+
+ // Request line
+ _, _ = fmt.Fprintf(writer, "%s %s HTTP/1.1\r\n", r.Method, path)
+
+ // Host header (required for HTTP/1.1)
+ _, _ = fmt.Fprintf(writer, "Host: %s\r\n", host)
+
+ // Copy other headers (using canonical header format)
+ for name, values := range r.Header {
+ // textproto.CanonicalMIMEHeaderKey ensures proper header formatting
+ canonicalName := textproto.CanonicalMIMEHeaderKey(name)
+ for _, value := range values {
+ _, _ = fmt.Fprintf(writer, "%s: %s\r\n", canonicalName, value)
}
}
- _, _ = backend.Write([]byte("\r\n"))
+ // End of headers
+ _, _ = fmt.Fprintf(writer, "\r\n")
+
+ // Flush the buffered request
+ if err := writer.Flush(); err != nil {
+ slog.Error("ws proxy: failed to write request", "err", err)
+ return
+ }
+
+ // Bidirectional copy between client and backend
done := make(chan struct{}, 2)
- go func() { _, _ = io.Copy(client, backend); done <- struct{}{} }()
- go func() { _, _ = io.Copy(backend, client); done <- struct{}{} }()
+ go func() {
+ _, _ = io.Copy(client, backend)
+ done <- struct{}{}
+ }()
+ go func() {
+ _, _ = io.Copy(backend, client)
+ done <- struct{}{}
+ }()
+
+ // Wait for one direction to complete
<-done
}
diff --git a/internal/human/human.go b/internal/human/human.go
index ad5f199f..30199d85 100644
--- a/internal/human/human.go
+++ b/internal/human/human.go
@@ -19,6 +19,19 @@ func SetHumanRandSeed(seed int64) {
humanRand = rand.New(rand.NewSource(seed))
}
+// Config allows injecting a custom random source for testing
+type Config struct {
+ Rand *rand.Rand
+}
+
+// getRand returns the configured random source or the global default
+func (c *Config) getRand() *rand.Rand {
+ if c != nil && c.Rand != nil {
+ return c.Rand
+ }
+ return humanRand
+}
+
func MouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {
distance := math.Sqrt((toX-fromX)*(toX-fromX) + (toY-fromY)*(toY-fromY))
baseDuration := 100 + (distance/2000)*200
@@ -144,6 +157,12 @@ func ClickElement(ctx context.Context, nodeID cdp.NodeID) error {
}
func Type(text string, fast bool) []chromedp.Action {
+ return TypeWithConfig(text, fast, nil)
+}
+
+// TypeWithConfig generates typing actions with optional custom random source
+func TypeWithConfig(text string, fast bool, cfg *Config) []chromedp.Action {
+ rng := cfg.getRand()
actions := []chromedp.Action{}
baseDelay := 80
@@ -154,22 +173,22 @@ func Type(text string, fast bool) []chromedp.Action {
chars := []rune(text)
for i, char := range chars {
actions = append(actions, chromedp.KeyEvent(string(char)))
- delay := baseDelay + humanRand.Intn(baseDelay/2)
- if humanRand.Float64() < 0.05 {
- delay += humanRand.Intn(500)
+ delay := baseDelay + rng.Intn(baseDelay/2)
+ if rng.Float64() < 0.05 {
+ delay += rng.Intn(500)
}
if i > 0 && chars[i-1] == char {
delay = delay / 2
}
actions = append(actions, chromedp.Sleep(time.Duration(delay)*time.Millisecond))
- if humanRand.Float64() < 0.03 && i < len(chars)-1 {
- wrongChar := rune('a' + humanRand.Intn(26))
+ if rng.Float64() < 0.03 && i < len(chars)-1 {
+ wrongChar := rune('a' + rng.Intn(26))
actions = append(actions,
chromedp.KeyEvent(string(wrongChar)),
- chromedp.Sleep(time.Duration(50+humanRand.Intn(100))*time.Millisecond),
+ chromedp.Sleep(time.Duration(50+rng.Intn(100))*time.Millisecond),
chromedp.KeyEvent("\b"),
- chromedp.Sleep(time.Duration(30+humanRand.Intn(70))*time.Millisecond),
+ chromedp.Sleep(time.Duration(30+rng.Intn(70))*time.Millisecond),
)
}
}
diff --git a/internal/human/human_test.go b/internal/human/human_test.go
index 0a83433c..54b4e274 100644
--- a/internal/human/human_test.go
+++ b/internal/human/human_test.go
@@ -2,6 +2,7 @@ package human
import (
"context"
+ "math/rand"
"testing"
"github.com/chromedp/chromedp"
@@ -53,3 +54,26 @@ func TestClick(t *testing.T) {
ctx, _ := chromedp.NewContext(context.Background())
_ = Click(ctx, 50, 50)
}
+
+func TestTypeWithConfig(t *testing.T) {
+ // Test with fixed seed for reproducibility
+ cfg := &Config{
+ Rand: rand.New(rand.NewSource(12345)),
+ }
+
+ // Generate actions twice with same config - should be identical
+ actions1 := TypeWithConfig("hello", false, cfg)
+
+ // Reset the rand source to same seed
+ cfg.Rand = rand.New(rand.NewSource(12345))
+ actions2 := TypeWithConfig("hello", false, cfg)
+
+ if len(actions1) != len(actions2) {
+ t.Errorf("expected same number of actions with same seed, got %d and %d", len(actions1), len(actions2))
+ }
+
+ // Verify at least some actions were generated
+ if len(actions1) < 10 {
+ t.Errorf("expected at least 10 actions, got %d", len(actions1))
+ }
+}