1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
| addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)); });
const ORIGIN_HOST = "6.xinhaojin.top";
async function handleRequest(request) { const url = new URL(request.url); const pathname = url.pathname; if (pathname === '/') { return new Response( `🚀 IPv6 代理服务\n\n` + `使用方法:https://4.xinhaojin.top/<端口>/<路径>\n\n` + `示例:\n` + `https://4.xinhaojin.top/911/ → http://6.xinhaojin.top:911/\n` + `https://4.xinhaojin.top/912/admin → http://6.xinhaojin.top:912/admin\n` + `https://4.xinhaojin.top/8080/static/ → http://6.xinhaojin.top:8080/static/\n\n` + `当前支持任意端口号访问 IPv6-only 服务`, { status: 200, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-cache' } } ); } let match = pathname.match(/^\/(\d+)(?:\/(.*))?$/); let port = null; let restPath = ''; if (match) { port = match[1]; restPath = match[2] || ''; } else { const referer = request.headers.get('referer'); if (referer) { const refererMatch = referer.match(/\/\/(?:\d+\.)?4\.xinhaojin\.top\/(\d+)\//); if (refererMatch) { port = refererMatch[1]; restPath = pathname.slice(1); console.log(`Recovered port ${port} from Referer for path: ${pathname}`); } } if (!port) { const cookieHeader = request.headers.get('cookie'); if (cookieHeader) { const cookieMatch = cookieHeader.match(/XPORT=(\d+)/); if (cookieMatch) { port = cookieMatch[1]; restPath = pathname.slice(1); console.log(`Recovered port ${port} from Cookie for path: ${pathname}`); } } } if (!port) { return new Response( `❌ 无法确定目标端口\n\n` + `请求路径:${pathname}\n` + `此路径不包含端口号,且无法从引用页面确定目标端口。\n\n` + `请确保:\n` + `1. 从包含端口号的页面链接访问资源\n` + `2. 或者使用完整路径:/<端口>${pathname}\n\n` + `示例:\n` + `https://4.xinhaojin.top/911${pathname}`, { status: 400, headers: { 'Content-Type': 'text/plain; charset=utf-8' } } ); } } const target = `http://${ORIGIN_HOST}:${port}/${restPath}${url.search}`; console.log(`Proxying: ${url.pathname} -> ${target} (port: ${port})`); const reqHeaders = new Headers(request.headers); reqHeaders.set("Host", ORIGIN_HOST); reqHeaders.set("X-Forwarded-Host", url.hostname); reqHeaders.set("X-Forwarded-Proto", "https"); reqHeaders.delete("cf-connecting-ip"); reqHeaders.delete("cf-ipcountry"); reqHeaders.delete("cf-ray"); reqHeaders.delete("cf-visitor");
const fetchInit = { method: request.method, headers: reqHeaders, redirect: "manual", body: ["GET", "HEAD"].includes(request.method) ? undefined : request.body };
let res; try { res = await fetch(target, fetchInit); } catch (e) { return new Response( `❌ 上游服务连接失败\n\n` + `错误信息:${e.message}\n` + `目标地址:${target}\n` + `恢复的端口:${port}\n\n` + `可能的原因:\n` + `• 端口 ${port} 没有服务在运行\n` + `• 目标服务器 ${ORIGIN_HOST} 无法访问\n` + `• 网络连接问题`, { status: 502, headers: { 'Content-Type': 'text/plain; charset=utf-8' } } ); }
const newHeaders = new Headers(); for (const [k, v] of res.headers) { if (k.toLowerCase() === "location" && v) { try { const locationUrl = new URL(v, target); if (locationUrl.hostname === ORIGIN_HOST) { const redirectPort = locationUrl.port || '80'; const newLocation = `/${redirectPort}${locationUrl.pathname}${locationUrl.search}`; newHeaders.set("Location", newLocation); continue; } } catch (e) { } } if (k.toLowerCase() === "set-cookie") { let modifiedCookie = v; if (!/Path=\/.*\//i.test(modifiedCookie)) { modifiedCookie = modifiedCookie.replace(/; Path=[^;]*/i, `; Path=/`); } newHeaders.append("Set-Cookie", modifiedCookie); continue; } const hopByHop = new Set([ "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers", "transfer-encoding", "upgrade" ]); if (!hopByHop.has(k.toLowerCase())) { newHeaders.set(k, v); } }
newHeaders.append("Set-Cookie", `XPORT=${port}; Path=/; Max-Age=3600; SameSite=Lax`);
const contentType = res.headers.get("content-type") || ""; if (contentType.includes("text/html")) { let html = await res.text(); html = html.replace( /(href|src|action)=["'](\/[^"']*)["']/gi, (match, attr, path) => { if (path.match(/^\/\d+\//) || path.startsWith('//') || path.startsWith('http://') || path.startsWith('https://')) { return match; } return `${attr}="/${port}${path}"`; } ); html = html.replace( /url\(["']?(\/[^"')]*)["']?\)/gi, (match, urlPath) => { if (urlPath.match(/^\/\d+\//) || urlPath.startsWith('//') || urlPath.startsWith('http://') || urlPath.startsWith('https://')) { return match; } return `url("/${port}${urlPath}")`; } ); const clientScript = ` <script> // 增强的客户端路径重写 (function() { const currentPort = "${port}"; const basePath = "/" + currentPort; console.log('Path Rewrite Agent loaded for port:', currentPort); // 设置文档基础URI const baseElement = document.createElement('base'); baseElement.href = basePath + '/'; document.head.appendChild(baseElement); // 重写路径函数 function rewritePath(url) { if (!url || typeof url !== 'string') return url; // 跳过已重写的URL和外部URL if (url.startsWith(basePath) || url.startsWith('//') || url.startsWith('http://') || url.startsWith('https://') || !url.startsWith('/')) { return url; } const newUrl = basePath + url; console.log('Rewriting path:', url, '->', newUrl); return newUrl; } // 重写现有DOM元素 function rewriteExistingElements() { console.log('Rewriting existing DOM elements...'); // 重写所有链接 document.querySelectorAll('a[href]').forEach(link => { const href = link.getAttribute('href'); if (href && href.startsWith('/') && !href.startsWith(basePath)) { link.setAttribute('href', rewritePath(href)); } }); // 重写所有表单 document.querySelectorAll('form[action]').forEach(form => { const action = form.getAttribute('action'); if (action && action.startsWith('/') && !action.startsWith(basePath)) { form.setAttribute('action', rewritePath(action)); } }); // 重写所有资源 const resourceSelectors = [ 'img[src]', 'script[src]', 'link[href]', 'iframe[src]', 'embed[src]', 'object[data]', 'source[src]', 'track[src]', 'audio[src]', 'video[src]' ]; resourceSelectors.forEach(selector => { document.querySelectorAll(selector).forEach(el => { const src = el.getAttribute('src'); const href = el.getAttribute('href'); const data = el.getAttribute('data'); if (src && src.startsWith('/') && !src.startsWith(basePath)) { el.setAttribute('src', rewritePath(src)); } if (href && el.tagName.toLowerCase() === 'link' && href.startsWith('/') && !href.startsWith(basePath)) { el.setAttribute('href', rewritePath(href)); } if (data && data.startsWith('/') && !data.startsWith(basePath)) { el.setAttribute('data', rewritePath(data)); } }); }); } // 拦截fetch请求 const originalFetch = window.fetch; window.fetch = function(...args) { if (typeof args[0] === 'string') { const newUrl = rewritePath(args[0]); if (newUrl !== args[0]) { console.log('Intercepted fetch:', args[0], '->', newUrl); args[0] = newUrl; } } else if (args[0] instanceof Request) { const newUrl = rewritePath(args[0].url); if (newUrl !== args[0].url) { console.log('Intercepted Request:', args[0].url, '->', newUrl); args[0] = new Request(newUrl, args[0]); } } return originalFetch.apply(this, args); }; // 拦截XMLHttpRequest const originalOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url, ...rest) { if (typeof url === 'string') { const newUrl = rewritePath(url); if (newUrl !== url) { console.log('Intercepted XHR:', url, '->', newUrl); url = newUrl; } } return originalOpen.call(this, method, url, ...rest); }; // 拦截动态创建的元素 const originalCreateElement = document.createElement; document.createElement = function(tagName) { const element = originalCreateElement.call(this, tagName); const rewriteAttributes = ['src', 'href', 'action', 'data']; const originalSetAttribute = element.setAttribute; element.setAttribute = function(name, value) { if (rewriteAttributes.includes(name) && value && value.startsWith('/') && !value.startsWith(basePath)) { value = rewritePath(value); } return originalSetAttribute.call(this, name, value); }; return element; }; // 监听DOM变化 const observer = new MutationObserver(function(mutations) { let shouldRewrite = false; mutations.forEach(function(mutation) { if (mutation.addedNodes.length) { shouldRewrite = true; } }); if (shouldRewrite) { setTimeout(rewriteExistingElements, 100); } }); observer.observe(document.body, { childList: true, subtree: true }); // 初始重写 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function() { setTimeout(rewriteExistingElements, 100); }); } else { setTimeout(rewriteExistingElements, 100); } })(); </script> `; if (html.includes('</head>')) { html = html.replace('</head>', clientScript + '</head>'); } else if (html.includes('<head>')) { html = html.replace('<head>', '<head>' + clientScript); } else { html = clientScript + html; } const bodyBytes = new TextEncoder().encode(html); newHeaders.set("content-length", String(bodyBytes.length)); return new Response(bodyBytes, { status: res.status, statusText: res.statusText, headers: newHeaders }); }
return new Response(res.body, { status: res.status, statusText: res.statusText, headers: newHeaders }); }
|