fix: server-side HTML URL rewriting to bypass CSP blocking
Build and Push to GHCR / build-and-push (push) Has been cancelled

JS injection fails on sites with strict Content-Security-Policy
(e.g. GitHub). Add golang.org/x/net/html-based server-side rewriting
of URL attributes (href/src/action/etc.) and CSS url() values before
response is sent. Keep JS injection as fallback for dynamic content.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <[email protected]>
This commit is contained in:
Agent
2026-05-24 17:44:35 +08:00
co-authored by HAPI
parent f03eacaf20
commit f13f294d04
5 changed files with 144 additions and 3 deletions
+5 -1
View File
@@ -53,7 +53,7 @@ func DynamicProxy(targetURL string) http.Handler {
resp.Header.Set("Location", rewriteURL(loc, tokenPrefix))
}
// 对 HTML 响应注入 JS 脚本,重写链接
// 对 HTML 响应做服务端 URL 重写 + 注入 JS 兜底
contentType := resp.Header.Get("Content-Type")
if strings.Contains(contentType, "text/html") && resp.Body != nil {
body, err := io.ReadAll(resp.Body)
@@ -62,7 +62,11 @@ func DynamicProxy(targetURL string) http.Handler {
}
resp.Body.Close()
// 1. 服务端重写所有已知 URL 属性(应对 CSP 禁止内联脚本的情况)
body = rewriteHTMLBody(body, tokenPrefix)
// 2. 注入 JS 处理动态添加的内容(无 CSP 时生效)
body = injectTokenPrefixScript(body, tokenPrefix)
resp.Body = io.NopCloser(bytes.NewReader(body))
resp.ContentLength = int64(len(body))
resp.Header.Set("Content-Length", fmt.Sprintf("%d", len(body)))