Spaces:
Running
Running
| export default { | |
| async fetch(request, env) { | |
| const url = new URL(request.url); | |
| // 只处理 /proxy 路径 | |
| if (url.pathname !== "/proxy") { | |
| return new Response("Not Found", { status: 404 }); | |
| } | |
| // 可选认证:如果传递了凭据则验证,但不强制要求也不阻止请求 | |
| const auth = request.headers.get("Authorization"); | |
| if (auth && auth.startsWith("Basic ")) { | |
| const expected = btoa(`${env.PROXY_USER}:${env.PROXY_PASS}`); | |
| if (auth.slice(6) !== expected) { | |
| console.log(`[Auth] Invalid credentials provided`); | |
| } | |
| } | |
| // 获取目标 URL | |
| const target = url.searchParams.get("target_url"); | |
| if (!target) { | |
| return new Response("Missing target_url parameter", { status: 400 }); | |
| } | |
| try { | |
| // 构建转发头,过滤 host(Worker网关的host,不是目标的) | |
| const headers = new Headers(); | |
| for (const [key, value] of request.headers) { | |
| const lower = key.toLowerCase(); | |
| if (lower !== "host") { | |
| headers.set(key, value); | |
| } | |
| } | |
| // 转发请求,不跟随重定向(与原版行为一致) | |
| const body = ["GET", "HEAD"].includes(request.method) ? null : request.body; | |
| const resp = await fetch(target, { | |
| method: request.method, | |
| headers: headers, | |
| body: body, | |
| redirect: "manual", | |
| }); | |
| // 构建响应头,去掉 hop-by-hop 头 | |
| const respHeaders = new Headers(); | |
| for (const [key, value] of resp.headers) { | |
| const lower = key.toLowerCase(); | |
| if (lower !== "transfer-encoding" && lower !== "connection") { | |
| respHeaders.set(key, value); | |
| } | |
| } | |
| // 流式返回响应体 | |
| return new Response(resp.body, { | |
| status: resp.status, | |
| headers: respHeaders, | |
| }); | |
| } catch (e) { | |
| return new Response(`Proxy Error: ${e.message}`, { status: 500 }); | |
| } | |
| }, | |
| }; | |