fix: rewrite proxy links with token prefix and correct login redirect
Build and Push to GHCR / build-and-push (push) Has been cancelled

- Add ModifyResponse to DynamicProxy to inject token-prefix JS and
  rewrite Location headers, same as GitHub proxy already did.
- Improve injectTokenPrefixScript to rewrite href/src/action on page
  load and watch for dynamically added elements via MutationObserver.
- Replace hardcoded ../ login redirect with pathname-based calculation
  so it works regardless of admin_path config.

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

Co-Authored-By: HAPI <[email protected]>
This commit is contained in:
Agent
2026-05-24 17:27:38 +08:00
co-authored by HAPI
parent d6623fc150
commit f03eacaf20
3 changed files with 58 additions and 5 deletions
+42
View File
@@ -1,11 +1,16 @@
package proxy
import (
"bytes"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"mirror-proxy/internal/auth"
)
// DynamicProxy 创建指向任意目标 URL 的反向代理
@@ -23,11 +28,48 @@ func DynamicProxy(targetURL string) http.Handler {
req.URL.Host = target.Host
req.Host = target.Host
req.Header.Set("Host", target.Host)
// 删除 Accept-Encoding,防止响应被压缩,便于修改 HTML
req.Header.Del("Accept-Encoding")
if req.Header.Get("User-Agent") == "" {
req.Header.Set("User-Agent", "MirrorProxy/1.0")
}
req.Header.Del("X-Forwarded-For")
},
ModifyResponse: func(resp *http.Response) error {
// 从请求上下文中获取 token 前缀
tokenPrefix := ""
if resp.Request != nil {
if prefix, ok := resp.Request.Context().Value(auth.TokenPrefixContextKey).(string); ok {
tokenPrefix = prefix
}
}
if tokenPrefix == "" {
return nil
}
// 重写 Location header
if loc := resp.Header.Get("Location"); loc != "" {
resp.Header.Set("Location", rewriteURL(loc, tokenPrefix))
}
// 对 HTML 响应注入 JS 脚本,重写链接
contentType := resp.Header.Get("Content-Type")
if strings.Contains(contentType, "text/html") && resp.Body != nil {
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
resp.Body.Close()
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)))
}
return nil
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusBadGateway)
+12 -3
View File
@@ -104,11 +104,21 @@ func rewriteURL(u string, prefix string) string {
return u
}
// injectTokenPrefixScript 在 HTML 中注入 JS 脚本,拦截链接点击自动补全 token 前缀
// injectTokenPrefixScript 在 HTML 中注入 JS 脚本,重写所有链接使其包含 token 前缀
func injectTokenPrefixScript(body []byte, prefix string) []byte {
script := []byte(`<script>` +
`(function(){` +
`var p='` + prefix + `';` +
`function rw(v){return v&&v.startsWith('/')&&!v.startsWith(p+'/')&&v!==p?p+v:v};` +
`function fix(root){` +
`root.querySelectorAll&&root.querySelectorAll('a[href]').forEach(function(a){a.href=rw(a.getAttribute('href'))});` +
`root.querySelectorAll&&root.querySelectorAll('form[action]').forEach(function(f){f.action=rw(f.getAttribute('action'))});` +
`root.querySelectorAll&&root.querySelectorAll('[src]').forEach(function(el){var s=el.getAttribute('src');if(s&&s.startsWith('/')&&!s.startsWith(p+'/'))el.setAttribute('src',p+s)});` +
`}` +
`fix(document);` +
`if(window.MutationObserver){` +
`new MutationObserver(function(ms){ms.forEach(function(m){m.addedNodes.forEach(function(n){if(n.nodeType===1)fix(n)})})}).observe(document.documentElement||document.body,{childList:true,subtree:true});` +
`}` +
`document.addEventListener('click',function(e){` +
`var a=e.target.closest('a');` +
`if(!a)return;` +
@@ -135,14 +145,13 @@ func injectTokenPrefixScript(body []byte, prefix string) []byte {
}
// 或者在 <body> 标签后插入
if idx := bytes.Index(body, []byte("<body")); idx != -1 {
// 找到 <body> 标签的结束位置
endIdx := bytes.Index(body[idx:], []byte(">"))
if endIdx != -1 {
pos := idx + endIdx + 1
return append(body[:pos], append(script, body[pos:]...)...)
}
}
// fallback:在文档开头插入
// fallback:在文档开头插入
return append(script, body...)
}
+4 -2
View File
@@ -109,7 +109,8 @@
try {
const res = await fetch('/api/auth/me', { credentials: 'same-origin' });
if (res.ok) {
window.location.href = '../';
const adminRoot = window.location.pathname.replace(/\/login\/?$/, '/');
window.location.href = adminRoot;
}
} catch (e) {}
}
@@ -138,7 +139,8 @@
});
if (res.ok) {
window.location.href = '../';
const adminRoot = window.location.pathname.replace(/\/login\/?$/, '/');
window.location.href = adminRoot;
} else {
const data = await res.json().catch(() => ({}));
errorEl.textContent = data.error || '用户名或密码错误';