File size: 9,330 Bytes
902615d
 
 
 
 
 
 
 
 
 
 
 
 
201d0dc
902615d
ab75e5d
902615d
 
 
 
 
 
 
cacb4da
902615d
023c0e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
902615d
 
 
 
 
 
 
 
 
 
 
 
f58bc9f
902615d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
023c0e3
902615d
 
 
 
 
 
 
 
 
2d130a8
902615d
 
 
 
 
 
 
 
 
2d130a8
902615d
2d130a8
902615d
 
 
 
 
 
 
 
 
 
 
2d130a8
902615d
2d130a8
902615d
 
 
 
 
 
 
 
 
 
 
2d130a8
902615d
2d130a8
902615d
 
 
 
 
 
 
 
 
 
 
 
2d130a8
902615d
2d130a8
902615d
 
 
 
 
 
 
 
 
 
 
2d130a8
902615d
2d130a8
902615d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d130a8
902615d
 
2d130a8
902615d
 
 
 
 
 
feb5851
902615d
 
 
 
 
 
 
 
 
 
 
f58bc9f
902615d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b58a08
 
902615d
 
 
 
 
 
 
 
 
 
 
2d130a8
902615d
 
369fabc
 
 
 
55c3b2a
369fabc
ace0cc9
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
/**
* Respond to the request
*/
async function handleRequest(event) {
  const { request } = event;
  //请求头部、返回对象
  let reqHeaders = new Headers(request.headers),
      outBody, outStatus = 200, outStatusText = 'OK', outCt = null, outHeaders = new Headers({
          "x-url": request.url,
          "Access-Control-Allow-Origin": reqHeaders.get('Origin'),
          "Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
          "Access-Control-Allow-Headers": reqHeaders.get('Access-Control-Allow-Headers') || "Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Requested-With, Token, x-access-token, Notion-Version"
      });
    let url = request.url;
    //取域名第一个斜杠后的所有信息为代理链接
    url = decodeURIComponent(request.url.replace("http://x-undefined-2-proxy-server.hf.space/", ""));
    let refer = reqHeaders.get("Referer")
    let cookie = reqHeaders.get("Cookie")
  try {
      //需要忽略的代理
      if (request.method == "OPTIONS" && reqHeaders.has('access-control-request-headers')) {
          //输出提示
          return new Response(null, PREFLIGHT_INIT)
      }
      //阻断
      //补上前缀 http://
      url = url.replace(/https:(\/+)*/,'https://').replace(/http:(\/+)*/, 'http://')
      if (url.indexOf("://") == -1) {
          if(refer){
              refer = refer.replace("https://x-undefined-2-proxy-server.hf.space/", "")
              let xref = refer.substr(0, refer.indexOf('/', 10)+1)
              url = xref + url;
          }
      }
      let domain = url.substr(0, url.indexOf('/', 10)+1);
      if(refer){
          refer = refer.replace("https://x-undefined-2-proxy-server.hf.space/", "")
          domain = refer.substr(0, refer.indexOf('/', 10)+1)
          // url = domain + url
      }
      outHeaders.set("xxx_url", url)
      outHeaders.set("xxx_domain", domain)

    //构建 fetch 参数
    let fp = {
        method: request.method,
        headers: {}
    }

    //保留头部其它信息
    let he = reqHeaders.entries();
    for (let h of he) {
        if (!['content-length'].includes(h[0])) {
            fp.headers[h[0]] = h[1];
        }
    }
    // 是否带 body
    if (["POST", "PUT", "PATCH", "DELETE"].indexOf(request.method) >= 0) {
        const ct = (reqHeaders.get('content-type') || "").toLowerCase();
        if (ct.includes('application/json')) {
            let requestJSON = await request.json()
            console.log(typeof requestJSON)
            fp.body = JSON.stringify(requestJSON);
        } else if (ct.includes('application/text') || ct.includes('text/html')) {
            fp.body = await request.text();
        } else if (ct.includes('form')) {
            fp.body = await request.formData();
        } else {
            fp.body = await request.blob();
        }
    }
    console.log("parsed url:", url, domain);
    // 发起 fetch
    let fr = (await fetch(new URL(url), fp));
    outCt = fr.headers.get('content-type');
    if(outCt && (outCt.includes('application/text') || outCt.includes('text/html'))) {
        try {
            // 添加base
            let newFr = new HTMLRewriter()
            .on("head", {
            element(element) {
                element.prepend(`<base href="https://x-undefined-2-proxy-server.hf.space/${url}" />`, {
                html: true
                })
            },
            })
            .on("link", {
                element(element) {
                    let href = element.getAttribute("href")
                    if(href){
                        if(href.indexOf("https://") == 0){
                            element.setAttribute("href", "https://x-undefined-2-proxy-server.hf.space/"+href);
                        } else if(href[0] == '/') {
                            element.setAttribute("href", "https://x-undefined-2-proxy-server.hf.space/"+domain.substr(0, domain.lastIndexOf('/'))+href);
                        } else {
                            element.setAttribute("href", request.url+href);
                        }
                    }
                },
            })
            .on("script", {
                element(element) {
                    let href = element.getAttribute("src")
                    if(href){
                        if(href.indexOf("https://") == 0){
                            element.setAttribute("src", "https://x-undefined-2-proxy-server.hf.space/"+href);
                        } else if(href[0] == '/') {
                            element.setAttribute("src", "https://x-undefined-2-proxy-server.hf.space/"+domain.substr(0, domain.lastIndexOf('/'))+href);
                        } else {
                            element.setAttribute("src", request.url+href);
                        }
                    }
                },
            })
            .on("img", {
                element(element) {
                    let href = element.getAttribute("src")
                    if(href){
                        if(href.indexOf("https://") == 0){
                            element.setAttribute("src", "https://x-undefined-2-proxy-server.hf.space/"+href);
                        } else if(href[0] == '/') {
                            element.setAttribute("src", "https://x-undefined-2-proxy-server.hf.space/"+domain.substr(0, domain.lastIndexOf('/'))+href);
                        } else if(href.indexOf("data:image") == 0){
                        } else {
                            element.setAttribute("src", request.url+href);
                        }
                    }
                },
            })
            .on("form", {
                element(element) {
                    let href = element.getAttribute("action")
                    if(href){
                        if(href.indexOf("https://") == 0){
                            element.setAttribute("action", "https://x-undefined-2-proxy-server.hf.space/"+href);
                        } else if(href[0] == '/') {
                            element.setAttribute("action", "https://x-undefined-2-proxy-server.hf.space/"+domain.substr(0, domain.lastIndexOf('/'))+href);
                        } else {
                            element.setAttribute("action", request.url+href);
                        }
                    }
                },
            })
            .on("a", {
                element(element) {
                    let href = element.getAttribute("href")
                    if(href){
                        if(href.indexOf("https://") == 0){
                            element.setAttribute("href", "https://x-undefined-2-proxy-server.hf.space/"+href);
                        } else if(href[0] == '/') {
                            element.setAttribute("href", "https://x-undefined-2-proxy-server.hf.space/"+domain.substr(0, domain.lastIndexOf('/'))+href);
                        } else {
                            element.setAttribute("href", request.url+href);
                        }
                    }
                },
            })
            .transform(fr)
            outHeaders.set("error", "noerror");
            fr = newFr
        } catch(e) {
            outHeaders.set("error", e);
        }
    }

    for (const [key, value] of fr.headers.entries()) {
        if(key =="Content-Security-Policy" || key =="content-security-policy"){ 
            outHeaders.set(key, value.replaceAll("github.githubassets.com", "x-undefined-2-proxy-server.hf.space github.githubassets.com").replaceAll("script-src .*?;", "script-src 'self' 'unsafe-inline';"));
        }
    }
    outHeaders.set("Access-Control-Allow-Origin", "x-undefined-2-proxy-server.hf.space")
    outHeaders.set("Access-Control-Allow-Methods", "*")
    outHeaders.set("Access-Control-Allow-Credentials", "true")

    outStatus = fr.status;
    outStatusText = fr.statusText;
    outBody = fr.body;
    console.log(fr.body);
    outBody = injectOutBody(url, outBody)
  } catch (err) {
    outHeaders.set("hasError", err);
      outCt = "application/json";
      outBody = JSON.stringify({
          code: -1,
          msg: JSON.stringify(err.stack) || err
      });
  } finally {
    outHeaders.set("x_Url_ext", request.url)
    outHeaders.set("x_Refer", refer)
  }

  //设置类型
  if (outCt && outCt != "") {
      outHeaders.set("content-type", outCt);
  }

  let response = new Response(outBody, {
      status: outStatus,
      statusText: outStatusText,
      headers: outHeaders
  })

  return response;

  // return new Response('OK', { status: 200 })
}

/**
* 阻断器
*/
const blocker = {
  keys: [".m3u8", ".ts", ".acc", ".m4s", "photocall.tv", "googlevideo.com"
],
  check: function (url) {
      url = url.toLowerCase();
      let len = blocker.keys.filter(x => url.includes(x)).length;
      return len != 0;
  }
}

const injectOutBody = (url, body)=>{
    // if(url.includes("huggingface.co") && url.endsWith("index.js")) {
    //     let domain = url.substr(0, url.indexOf("/", 9))
    //     console.log(body)
    //     return body.text();//.replace(/href: \"(.*?)\"/ig, "href:\"https://x-undefined-2-proxy-server.hf.space/"+domain+"$1\"")
    // }
    return body;
}

export default{
  async fetch(request, event){
    return handleRequest({request});
  }
}