package websocket
import (
"bytes"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"golang.org/x/net/html"
)
// URL attributes that may carry a path-absolute reference and therefore need
// the proxy path prefix when the document is served through the port proxy.
// Source: https://html.spec.whatwg.org/multipage/indices.html#attributes-3
var rewritableURLAttrs = map[string]bool{
"href": true,
"src": true,
"action": true,
"formaction": true,
"cite": true,
"data": true,
"poster": true,
"background": true,
"manifest": true,
}
// styleTagName is the HTML element name we treat as a raw-text CSS body so we
// can pipe its contents through `rewriteCSSFragment`.
const styleTagName = "style"
// scriptTagName is a raw-text element per the HTML spec — its contents are
// not HTML-escaped. The golang.org/x/net/html tokenizer correctly returns the
// raw bytes in `Token.Data`, but `Token.String()` blindly HTML-escapes any
// text token's `Data`, which corrupts inline JS containing characters like
// `&` (e.g. `x & 1`, `a && b`, JSON with `&` in strings). We therefore emit
// ``
// runtimeShim returns the runtime shim script tag with the given proxy prefix
// baked in. %q produces a JS-safe double-quoted string literal (slashes and
// alphanumerics need no escaping, which matches every prefix we emit).
func runtimeShim(prefix string) string {
return fmt.Sprintf(runtimeShimTemplate, prefix)
}
// urlInCSSPattern matches `url(...)` invocations in CSS where the argument is
// a path-absolute URL we want to rewrite. The argument can be optionally
// wrapped in single or double quotes and may be surrounded by whitespace.
//
// url(/foo)
// url('/foo')
// url("/foo")
//
// Network-relative (`//host/foo`) and absolute (`http://...`) are left alone.
var urlInCSSPattern = regexp.MustCompile(`url\(\s*(['"]?)(/[^/'"][^'")]*)`)
// importInCSSPattern matches `@import "/foo";` style root-absolute imports.
var importInCSSPattern = regexp.MustCompile(`@import\s+(['"])(/[^/'"][^'"]*)['"]`)
// rewriteProxyResponse mutates an `http.Response` from agentctl in place,
// rewriting root-absolute URLs to be prefixed by `proxyPrefix` so the iframe's
// asset/XHR/import requests come back through the same port proxy instead of
// hitting the host page's origin. Returns nil and leaves the response untouched
// for content types we don't rewrite (everything except HTML and CSS today).
//
// `proxyPrefix` is the public URL path that fronts this proxy on the gateway,
// e.g. "/port-proxy//" (no trailing slash). It is prepended to
// matched URLs that start with a single "/" — see `rewriteAbsolutePath`.
func rewriteProxyResponse(resp *http.Response, proxyPrefix string) error {
ct := strings.ToLower(resp.Header.Get("Content-Type"))
var rewrite func([]byte, string) []byte
switch {
case strings.Contains(ct, "text/html"):
rewrite = rewriteHTMLURLs
case strings.Contains(ct, "text/css"):
rewrite = rewriteCSSURLs
default:
return nil
}
body, err := io.ReadAll(resp.Body)
closeErr := resp.Body.Close()
if err != nil {
return err
}
if closeErr != nil {
return closeErr
}
modified := rewrite(body, proxyPrefix)
resp.Body = io.NopCloser(bytes.NewReader(modified))
resp.Header.Del("Content-Encoding")
resp.Header.Set("Content-Length", strconv.Itoa(len(modified)))
resp.ContentLength = int64(len(modified))
return nil
}
// rewriteAbsolutePath turns a path-absolute URL ("/foo") into a proxied path
// ("/foo"). Returns the input unchanged for non-rewritable cases:
// empty strings, network-relative URLs (`//host`), schemes (`http:`, `data:`,
// `mailto:`, etc.), or relative paths (`foo`, `./foo`, `../foo`).
func rewriteAbsolutePath(rawURL, prefix string) string {
if len(rawURL) < 1 || rawURL[0] != '/' {
return rawURL
}
if len(rawURL) >= 2 && rawURL[1] == '/' {
return rawURL // network-relative
}
return prefix + rawURL
}
// htmlRewriteState tracks per-document position during a single
// `rewriteHTMLURLs` pass. Pulled out to its own type so each token-handling
// case stays short and the top-level loop's cyclomatic complexity stays under
// the lint budget.
type htmlRewriteState struct {
out *bytes.Buffer
prefix string
shim string
inStyle bool
inScript bool
shimInjected bool
}
// onStartTag emits the (URL-rewritten) start tag and updates raw-text
// element tracking. Also injects the runtime shim immediately after ``.
func (s *htmlRewriteState) onStartTag(token html.Token) {
rewriteTokenURLs(&token, s.prefix)
s.out.WriteString(token.String())
if !s.shimInjected && token.Data == headTagName {
s.out.WriteString(s.shim)
s.shimInjected = true
}
switch token.Data {
case styleTagName:
s.inStyle = true
case scriptTagName:
s.inScript = true
}
}
// onEndTag clears raw-text element tracking, then writes the end tag.
func (s *htmlRewriteState) onEndTag(token html.Token) {
switch token.Data {
case styleTagName:
s.inStyle = false
case scriptTagName:
s.inScript = false
}
s.out.WriteString(token.String())
}
// onTextToken writes text content with the right escaping for the current
// element context: rewrite CSS URLs inside `