package gateway import ( "bytes" "fmt" "io" "log/slog" "net/http" "net/http/httputil" "net/url" "regexp" "strconv" "strings" ) var ( htmlAttrRegex = regexp.MustCompile(`(?i)(href|src|action|data-src|data-url)="(/[^"]*)"`) ) func rewriteHTMLResponse(resp *http.Response, toolID, prefix string) error { contentType := strings.ToLower(resp.Header.Get("Content-Type")) // NEVER buffer streaming responses — SSE, chunked, binary, etc. // Only rewrite actual text/html pages. if !strings.Contains(contentType, "text/html") { return nil } // Also skip event-streams even if they somehow claim text/html if strings.Contains(contentType, "event-stream") { return nil } bodyBytes, err := io.ReadAll(resp.Body) if err != nil { return err } resp.Body.Close() htmlStr := string(bodyBytes) // Rewrite attributes htmlStr = htmlAttrRegex.ReplaceAllStringFunc(htmlStr, func(match string) string { parts := htmlAttrRegex.FindStringSubmatch(match) if len(parts) == 3 { attr := parts[1] path := parts[2] if strings.HasPrefix(path, prefix) || strings.HasPrefix(path, "http") || strings.HasPrefix(path, "//") || strings.HasPrefix(path, "data:") { return match } return fmt.Sprintf(`%s="%s%s"`, attr, prefix, path) } return match }) // Inject JS shim right after or at top if no head shim := fmt.Sprintf(``, prefix) headIdx := strings.Index(strings.ToLower(htmlStr), "") if headIdx != -1 { htmlStr = htmlStr[:headIdx+6] + shim + htmlStr[headIdx+6:] } else { htmlStr = shim + htmlStr } newBody := []byte(htmlStr) resp.Body = io.NopCloser(bytes.NewReader(newBody)) resp.ContentLength = int64(len(newBody)) resp.Header.Set("Content-Length", strconv.Itoa(len(newBody))) return nil } // toolProxy creates a new ReverseProxy for a given tool port. func toolProxy(pm *ProcessManager, toolID string, port int) *httputil.ReverseProxy { target, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port)) proxy := httputil.NewSingleHostReverseProxy(target) prefix := fmt.Sprintf("/tool/%s", toolID) // FlushInterval=-1 means flush every write immediately. // This is required for SSE (text/event-stream) and chunked responses // to reach the browser in real-time instead of being buffered. proxy.FlushInterval = -1 // Customize Director: strip prefix, set correct headers proxy.Director = func(req *http.Request) { if pm != nil && !pm.IsRunning(toolID) { slog.Info("auto-launching tool on demand", "tool", toolID) _ = pm.EnsureRunning(req.Context(), toolID) } req.URL.Scheme = target.Scheme req.URL.Host = target.Host req.URL.Path = strings.TrimPrefix(req.URL.Path, prefix) if req.URL.Path == "" { req.URL.Path = "/" } req.Host = target.Host // Force re-fetch so we can rewrite HTML (prevents 304 Not Modified) req.Header.Del("If-None-Match") req.Header.Del("If-Modified-Since") // Forward real client IP if clientIP := req.Header.Get("X-Real-IP"); clientIP == "" { req.Header.Set("X-Real-IP", req.RemoteAddr) } req.Header.Set("X-Forwarded-Prefix", prefix) } proxy.ModifyResponse = func(resp *http.Response) error { // Rewrite redirect Location headers if loc := resp.Header.Get("Location"); loc != "" { if strings.HasPrefix(loc, "/") && !strings.HasPrefix(loc, prefix) { resp.Header.Set("Location", prefix+loc) } } return rewriteHTMLResponse(resp, toolID, prefix) } proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { slog.Error("tool proxy forwarding error", "tool", toolID, "path", r.URL.Path, "err", err) http.Error(w, fmt.Sprintf("Tool %s proxy error: %v", toolID, err), http.StatusBadGateway) } return proxy }