169 lines
5.0 KiB
Go
169 lines
5.0 KiB
Go
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 <head> or at top if no head
|
|
shim := fmt.Sprintf(`<script>
|
|
(function(){
|
|
var _P = '%s';
|
|
function _fix(u) {
|
|
if (typeof u !== 'string') return u;
|
|
if (u.startsWith('/') && !u.startsWith(_P) && !u.startsWith('//')) return _P + u;
|
|
return u;
|
|
}
|
|
// Patch fetch
|
|
var _fetch = window.fetch;
|
|
window.fetch = function(input, init) {
|
|
if (typeof input === 'string') input = _fix(input);
|
|
else if (input instanceof Request) {
|
|
try { input = new Request(_fix(input.url), input); } catch(e) {}
|
|
}
|
|
return _fetch.call(this, input, init);
|
|
};
|
|
// Patch XHR
|
|
var _open = XMLHttpRequest.prototype.open;
|
|
XMLHttpRequest.prototype.open = function(method, url) {
|
|
var args = Array.prototype.slice.call(arguments);
|
|
args[1] = _fix(url);
|
|
return _open.apply(this, args);
|
|
};
|
|
// Patch history
|
|
var _push = history.pushState;
|
|
history.pushState = function(state, title, url) {
|
|
return _push.call(this, state, title, url ? _fix(url) : url);
|
|
};
|
|
var _replace = history.replaceState;
|
|
history.replaceState = function(state, title, url) {
|
|
return _replace.call(this, state, title, url ? _fix(url) : url);
|
|
};
|
|
// Patch EventSource (used for SSE streams)
|
|
var _ES = window.EventSource;
|
|
window.EventSource = function(url, cfg) {
|
|
return new _ES(_fix(url), cfg);
|
|
};
|
|
window.EventSource.prototype = _ES.prototype;
|
|
window.EventSource.CONNECTING = _ES.CONNECTING;
|
|
window.EventSource.OPEN = _ES.OPEN;
|
|
window.EventSource.CLOSED = _ES.CLOSED;
|
|
})();
|
|
</script>`, prefix)
|
|
|
|
headIdx := strings.Index(strings.ToLower(htmlStr), "<head>")
|
|
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
|
|
}
|