diff --git a/proxy/rewriter.go b/proxy/rewriter.go index 21556f8..e6da60a 100644 --- a/proxy/rewriter.go +++ b/proxy/rewriter.go @@ -52,7 +52,7 @@ func (r *ContentRewriter) rewriteNode(n *html.Node) { } script.AppendChild(&html.Node{ Type: html.TextNode, - Data: `(function(){var t="/p/` + r.token + `";var o=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(m,u){if(typeof u==="string"&&u.startsWith("/")){arguments[1]=t+u}return o.apply(this,arguments)};var f=window.fetch;window.fetch=function(u,opt){if(typeof u==="string"&&u.startsWith("/")){u=t+u}return f.call(this,u,opt)};var U=window.URL;window.URL=function(u,base){if(typeof u==="string"&&u.startsWith("/")){u=t+u}return new U(u,base)};Object.defineProperty(window.location,"pathname",{get:function(){var p=window.location.href.split(window.location.host)[1]||"/";return p.startsWith(t)?p.substring(t.length):p}});var oa=Element.prototype.setAttribute;Element.prototype.setAttribute=function(n,v){if((n==="href"||n==="src"||n==="action")&&typeof v==="string"&&v.startsWith("/")){v=t+v}return oa.call(this,n,v)}})();`, + Data: `(function(){var t="/p/` + r.token + `";function r(u){if(typeof u!=="string")return u;if(u.startsWith(t))return u;if(u.startsWith("/")){return t+u}return u}var o=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(m,u){arguments[1]=r(u);return o.apply(this,arguments)};var f=window.fetch;window.fetch=function(u,opt){return f.call(this,r(u),opt)}})();`, }) script.NextSibling = n.FirstChild n.FirstChild.PrevSibling = script @@ -142,7 +142,8 @@ func (r *ContentRewriter) rewriteURL(urlStr string) string { return urlStr } - if strings.HasPrefix(urlStr, "/p/"+r.token+"/") { + // 防止重复添加 token + if strings.HasPrefix(urlStr, "/p/"+r.token) { return urlStr } @@ -161,7 +162,6 @@ func (r *ContentRewriter) rewriteURL(urlStr string) string { if !u.IsAbs() { resolved := r.baseURL.ResolveReference(u) - // 同域相对路径,只保留路径部分 if resolved.Host == r.baseURL.Host { proxyPath := resolved.Path if resolved.RawQuery != "" { @@ -172,11 +172,9 @@ func (r *ContentRewriter) rewriteURL(urlStr string) string { } return "/p/" + r.token + proxyPath } - // 跨域相对路径(罕见),保留完整 URL return "/p/" + r.token + "/" + resolved.String() } - // 同域绝对 URL,只保留路径 if u.Host == r.baseURL.Host { proxyPath := u.Path if u.RawQuery != "" { @@ -188,7 +186,6 @@ func (r *ContentRewriter) rewriteURL(urlStr string) string { return "/p/" + r.token + proxyPath } - // 跨域绝对 URL,保留完整 URL return "/p/" + r.token + "/" + u.String() } @@ -313,6 +310,11 @@ func (r *ContentRewriter) simpleRewriteHTML(body []byte) []byte { {`action="` + baseStr, `action="/p/` + r.token}, {`href='` + baseStr, `href='/p/` + r.token}, {`src='` + baseStr, `src='/p/` + r.token}, + {`href="/`, `href="/p/` + r.token + `/`}, + {`src="/`, `src="/p/` + r.token + `/`}, + {`action="/`, `action="/p/` + r.token + `/`}, + {`href='/`, `href='/p/` + r.token + `/`}, + {`src='/`, `src='/p/` + r.token + `/`}, } for _, rep := range replacements {