From 972c7a664cd27be57011eb76c9762ee403b5025a Mon Sep 17 00:00:00 2001 From: netptop Date: Fri, 18 Sep 2020 22:05:26 -0400 Subject: [PATCH] fixed date issue. --- Proxy.js | 9 ++++++--- build/worker.js | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Proxy.js b/Proxy.js index d01e6c1..c7a955e 100644 --- a/Proxy.js +++ b/Proxy.js @@ -429,10 +429,13 @@ let Proxy = ({ProxyMiddleware, blockedSites, urlModify, httpprefix, serverName, const setCookieHeaders = proxyRes.headers['set-cookie'] || [] console.log(`1`) let datestr = '' + let datestrOriginHost = '' if (setCookieHeaders.length > 0) { - let date = new Date - date.setDate(date.getDate() + 1) // 一天之后过期 + let curDate = new Date() + let date = new Date(curDate.getTime() + 7200 * 1000) // 2 hours later datestr = date.toUTCString() + date = new Date(curDate.getTime() + 600 * 1000) // 10 mins later + datestrOriginHost = date.toUTCString() } console.log(`2, setCookieHeaders:${JSON.stringify(setCookieHeaders)}`) const modifiedSetCookieHeaders = setCookieHeaders @@ -453,7 +456,7 @@ let Proxy = ({ProxyMiddleware, blockedSites, urlModify, httpprefix, serverName, cookie_originalHost.name = 'ORIGINALHOST' cookie_originalHost.value = `${httpType}/${host}` cookie_originalHost.domain = `${serverName}` - cookie_originalHost.expiration_date = datestr + cookie_originalHost.expiration_date = datestrOriginHost cookie_originalHost.path = `/` cookie_originalHost.secure = false modifiedSetCookieHeaders.push(cookie_originalHost.toString()) diff --git a/build/worker.js b/build/worker.js index 480f36a..360cae4 100644 --- a/build/worker.js +++ b/build/worker.js @@ -25,7 +25,7 @@ var n=r(56),i=r(57),o=r(31);function a(){return u.TYPED_ARRAY_SUPPORT?2147483647 * * Copyright (c) 2014-present, Jon Schlinkert. * Licensed under the MIT License. - */const n=r(4),i=r(141),o=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),a=e=>"number"==typeof e||"string"==typeof e&&""!==e,s=e=>Number.isInteger(+e),u=e=>{let t=""+e,r=-1;if("-"===t[0]&&(t=t.slice(1)),"0"===t)return!1;for(;"0"===t[++r];);return r>0},c=(e,t,r)=>{if(t>0){let r="-"===e[0]?"-":"";r&&(e=e.slice(1)),e=r+e.padStart(r?t-1:t,"0")}return!1===r?String(e):e},l=(e,t)=>{let r="-"===e[0]?"-":"";for(r&&(e=e.slice(1),t--);e.length{if(r)return i(e,t,{wrap:!1,...n});let o=String.fromCharCode(e);return e===t?o:`[${o}-${String.fromCharCode(t)}]`},h=(e,t,r)=>{if(Array.isArray(e)){let t=!0===r.wrap,n=r.capture?"":"?:";return t?`(${n}${e.join("|")})`:e.join("|")}return i(e,t,r)},d=(...e)=>new RangeError("Invalid range arguments: "+n.inspect(...e)),p=(e,t,r)=>{if(!0===r.strictRanges)throw d([e,t]);return[]},g=(e,t,r=1,n={})=>{let i=Number(e),o=Number(t);if(!Number.isInteger(i)||!Number.isInteger(o)){if(!0===n.strictRanges)throw d([e,t]);return[]}0===i&&(i=0),0===o&&(o=0);let a=i>o,s=String(e),p=String(t),g=String(r);r=Math.max(Math.abs(r),1);let _=u(s)||u(p)||u(g),v=_?Math.max(s.length,p.length,g.length):0,b=!1===_&&!1===((e,t,r)=>"string"==typeof e||"string"==typeof t||!0===r.stringify)(e,t,n),y=n.transform||(e=>t=>!0===e?Number(t):String(t))(b);if(n.toRegex&&1===r)return f(l(e,v),l(t,v),!0,n);let m={negatives:[],positives:[]},w=[],x=0;for(;a?i>=o:i<=o;)!0===n.toRegex&&r>1?m[(E=i)<0?"negatives":"positives"].push(Math.abs(E)):w.push(c(y(i,x),v,b)),i=a?i-r:i+r,x++;var E;return!0===n.toRegex?r>1?((e,t)=>{e.negatives.sort((e,t)=>et?1:0),e.positives.sort((e,t)=>et?1:0);let r,n=t.capture?"":"?:",i="",o="";return e.positives.length&&(i=e.positives.join("|")),e.negatives.length&&(o=`-(${n}${e.negatives.join("|")})`),r=i&&o?`${i}|${o}`:i||o,t.wrap?`(${n}${r})`:r})(m,n):h(w,null,{wrap:!1,...n}):w},_=(e,t,r,n={})=>{if(null==t&&a(e))return[e];if(!a(e)||!a(t))return p(e,t,n);if("function"==typeof r)return _(e,t,1,{transform:r});if(o(r))return _(e,t,0,r);let i={...n};return!0===i.capture&&(i.wrap=!0),r=r||i.step||1,s(r)?s(e)&&s(t)?g(e,t,r,i):((e,t,r=1,n={})=>{if(!s(e)&&e.length>1||!s(t)&&t.length>1)return p(e,t,n);let i=n.transform||(e=>String.fromCharCode(e)),o=(""+e).charCodeAt(0),a=(""+t).charCodeAt(0),u=o>a,c=Math.min(o,a),l=Math.max(o,a);if(n.toRegex&&1===r)return f(c,l,!1,n);let d=[],g=0;for(;u?o>=a:o<=a;)d.push(i(o,g)),o=u?o-r:o+r,g++;return!0===n.toRegex?h(d,null,{wrap:!1,options:n}):d})(e,t,Math.max(Math.abs(r),1),i):null==r||o(r)?_(e,t,1,r):((e,t)=>{if(!0===t.strictRanges)throw new TypeError(`Expected step "${e}" to be a number`);return[]})(r,i)};e.exports=_},function(e,t,r){(function(e){e.env.cloudflare="true";var t=r(55);let{blockedSites:n,urlModify:i,httpprefix:o,serverName:a,port:s,locationReplaceMap302:u,regReplaceMap:c,siteSpecificReplace:l,pathReplace:f}=r(153),{middle2req:h,req2middleware:d,middle2res:p,res2middleware:g}=r(158);let _=a;addEventListener("fetch",e=>{var r;e.respondWith((r=e.request,new Promise(async(e,v)=>{let b=(new Date).toISOString(),y=d(r);try{y.url=y.url.replace("https://tutorial.cloudflareworkers.com","");let r=new RegExp(`http[s]?://${a}[0-9:]*`,"g");y.url=y.url.replace(r,""),r=new RegExp(`/http[s]?/${a}[0-9:]*?`,"g"),y.url=y.url.replace(r,""),console.log(`timestr:${b}, serverName:${a}, middle_req:${JSON.stringify(y)}`),""!==y.url&&"/"!==y.url||(y.url="/https/www.netptop.com"),console.log(`${b}: after modification, middle_req.url:${y.url}`);let v,m,w,{readable:x,writable:E}=new TransformStream,k=E.getWriter(),R=g({cf_res:new Response(x)});R.write=t=>{if(console.log("====> middle_res.send() being called."),!R.replied){console.log("sending response ..."),R.replied=!0;let t=p({middle_res:R,readable:x});console.log("cf_res:"+JSON.stringify(t)),e(t)}t&&(console.log("before getWriter"),console.log("after getWriter"),k.write(t),console.log("after write data"))},R.end=R.send=e=>{R.write(e),console.log("writable closed."),k.close()},t({ProxyMiddleware:({target:e,router:t,protocolRewrite:r,cookieDomainRewrite:n,onError:i,onProxyRes:o,onProxyReq:a,secure:s=!1,changeOrigin:u=!0,debug:c=!0,selfHandleResponse:l=!0})=>{v=a,m=o,w=t},blockedSites:n,urlModify:i,httpprefix:o,serverName:a,port:s,cookieDomainRewrite:_,locationReplaceMap302:u,regReplaceMap:c,siteSpecificReplace:l,pathReplace:f}),console.log("proxy called");const A=w(y);console.log("target:"+A);let S=d(new Request(A,{redirect:h.redirect,method:y.method}));console.log("calling onProxyReq..."),v(S,y,R),console.log("====> after onProxyReq, middle_proxyReq:"+JSON.stringify(S));const C=h(A,S);console.log("fetching: cf_proxyReq:"+JSON.stringify(C));let O=await fetch(C).catch(e=>{console.log("fetching error: "+JSON.stringify(e))}),T=g({cf_res:O});if(console.log("calling onProxyRes..."),m(T,y,R),console.log("after onProxyRes, cf_proxyRes.body:"+JSON.stringify(O.body)),R.write(null),null===O.body)return;let L=O.body.getReader();for(;;){let{done:e,value:t}=await L.read();if(t&&T.emit("data",t),e){T.emit("end");break}}}catch(e){console.log("error happened:"+e)}})))})}).call(this,r(0))},function(e,t,r){(function(t,n){const i=r(32),o=r(40),a=r(42),s=r(82),{logSave:u,logGet:c,logClear:l}=(r(101),r(110));r(111);function f(e){let t=e.reduce((e,t)=>e+t.length,0);if(!e.length)return null;let r=new Uint8Array(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}var h=e=>!e["content-type"]||-1!==e["content-type"].indexOf("text/")||-1!==e["content-type"].indexOf("javascript")||-1!==e["content-type"].indexOf("urlencoded")||-1!==e["content-type"].indexOf("json"),d=function({res:e,httpprefix:t,serverName:r}){try{e.setHeader("location",`${t}://${r}`)}catch(e){return void u("error: "+e)}e.status(302).send("")};let p=({req:e,serverName:t})=>{let r="",n="https";if(e.url.startsWith("/https/")){r=e.url.slice("/https/".length,e.url.length);let t=r.match(/[-a-z0-9A-Z]+\.[-a-z0-9A-Z.]+/g);r=t.length>0?t[0]:""}else if(e.url.startsWith("/http/")){r=e.url.slice("/http/".length,e.url.length);let t=r.match(/[-a-z0-9A-Z]+\.[-a-z0-9A-Z.]+/g);r=t.length>0?t[0]:"",n="http"}else if(e.headers.referer&&-1!==e.headers.referer.indexOf("https/")){let t=e.headers.referer.indexOf("https/")+6;r=e.headers.referer.slice(t,e.headers.referer.length);let n=r.indexOf("/");-1===n&&(n=r.length),r=r.slice(0,n),u(`============= host:${r}, req referer:${e.headers.referer}`)}else if(e.headers.referer&&-1!==e.headers.referer.indexOf("http/")){let t=e.headers.referer.indexOf("http/")+5;r=e.headers.referer.slice(t,e.headers.referer.length);let i=r.indexOf("/");-1===i&&(i=r.length),r=r.slice(0,i),n="http",u(`============= host:${r}, req referer:${e.headers.referer}`)}else if(e.headers.referer){var i=o(e.headers.referer);i.hostname?(r=i.hostname,n=i.protocol.replace(":","")):(r=e.headers.referer,n="https")}let s="";if(e.headers.cookie){e.headers.cookie.split(" ").map(e=>new a.Cookie(e)).map(e=>{"ORIGINALHOST"===e.name&&(s=e.value)})}return(""===r||r===t&&!["/index.html","/","/favicon.png"].includes(e.url))&&""!==s&&(n=s.split("/")[0],r=s.split("/")[1],u(`getHostFromReq, use ORIGINALHOST, ${n},${r}`)),u(`getHostFromReq, req.url:${e.url}, referer:${e.headers.referer}, host:${r}, httpType:${n}`),{host:r,httpType:n}};e.exports=({ProxyMiddleware:e,blockedSites:r,urlModify:o,httpprefix:g,serverName:_,port:v,cookieDomainRewrite:b,locationReplaceMap302:y,regReplaceMap:m,siteSpecificReplace:w,pathReplace:x})=>{var E=({res:e,serverName:t,httpprefix:r,host:n,httpType:i})=>{let o=e.getHeaders().location;if("301"==e.statusCode||"302"==e.statusCode||"303"==e.statusCode||"307"==e.statusCode||"308"==e.statusCode){o=y({location:o,serverName:t,httpprefix:r,host:n,httpType:i}),u("after replacement, location="+o);try{e.setHeader("location",o)}catch(e){return u("error: "+e),!1}}return!0};let k=({req:e,res:r,body:n,gbFlag:o})=>{let a,{host:l,httpType:f}=p({req:e,serverName:_});if(!1!==E({res:r,serverName:_,httpprefix:g,host:l,httpType:f})){for(let e in m)a=new RegExp(e,"g"),n=n.replace(a,m[e]);if(u("##### host:"+l),l&&(n=x({host:l,httpType:f,body:n})),u("2"),u("3"),a=new RegExp(`/${f}/${l}/${f}/${l}/`,"g"),n=n.replace(a,`/${f}/${l}/`),u("4"),Object.keys(w).forEach(t=>{e.url&&(-1!==e.url.indexOf(t)||e.headers.referer&&-1!==e.headers.referer.indexOf(t))&&(keys=Object.keys(w[t]),keys.forEach(e=>{a=new RegExp(e,"g"),n=n.replace(a,w[t][e])}))}),u("5"),o&&(n=s.encode(n,"gbk")),"string"==typeof n&&n.startsWith(`${g}://${_}`)&&-1!==n.indexOf("googlevideo.com")){console.log("============== redirect googlevideo.com");try{r.setHeader("location",n)}catch(e){return void u("error: "+e)}r.statusCode="302"}if(u("5 after replacment,displayed string, body.length:"+n.length),"true"===t.env.cloudflare){let e=new TextEncoder;n=e.encode(n),u("6 cloudflare, after encoding, uint8array, body.length:"+n.length)}else n=i.gzipSync(n);u("7");try{r.setHeader("content-encoding","gzip"),u(`handleRespond: res.statusCode:${r.statusCode}, res.headers:${JSON.stringify(r.getHeaders())}`),"true"===e.headers.debugflag&&(r.removeHeader("content-encoding"),r.setHeader("content-type","text/plain"),n=c()),r.end(n)}catch(e){u("error: "+e)}}};return e({target:"https://www.google.com",router:e=>{let t=new RegExp(`/http[s]?/${_}.*?/`,"g");e.url=e.url.replace(t,"/");let{host:r,httpType:n}=p({req:e,serverName:_}),i=`${n}://${r}`;return u(`router, target:${i}, req.url:${e.url}`),i},protocolRewrite:!0,cookieDomainRewrite:b,secure:!1,changeOrigin:!0,debug:!0,onError:(e,t,r)=>{console.log("onerror: "+JSON.stringify(e));try{(e.code&&("ECONNREFUSED"===e.code||"EHOSTUNREACH"===e.code||"EPROTO"===e.code||"ECONNRESET"===e.code||"ENOTFOUND"===e.code)||e.reason&&-1===e.reason.indexOf("Expected"))&&d({res:r,httpprefix:g,serverName:_})}catch(e){u("error of sending 404: "+e)}},selfHandleResponse:!0,onProxyRes:(e,r,o)=>{let{host:l,httpType:v}=p({req:r,serverName:_});u(`proxyRes.status:${e.statusCode} proxyRes.headers:${JSON.stringify(e.headers)}`);let b=[],y=0;e.on("data",(function(i){if(y+=i.length,b.push(i),y>=25e5&&!0!==h(e.headers)){let i;i="true"===t.env.cloudflare?f(b):n.concat(b);let a=r.headers["X-Forwarded-For"]||r.headers["x-forwarded-for"],s=e.headers["content-type"],u=e.headers["content-length"];u>=155e6||l.indexOf("googlevideo"),console.log(`route:${a}, content-type:${s},bulk length:${y}, content-length:${u}, ${l}`),b=[],y=0,o.write(i)}})),e.on("end",(function(){let a;if(console.log("on end 1, bodyList.length:"+b.length),"true"===t.env.cloudflare){if(a=f(b),!a)return E({res:o,serverName:_,httpprefix:g,host:l,httpType:v}),void o.end(a)}else a=n.concat(b);console.log("on end 2, body.length:"+a.length);let p=!1;if("gzip"===e.headers["content-encoding"]||"br"===e.headers["content-encoding"]){let n;try{"true"===t.env.cloudflare?(console.log("cloudflare environment"),n=a):(console.log("node environment"),"br"===e.headers["content-encoding"]?(n=i.brotliDecompressSync(a),u("zlib.brotli...")):(n=i.gunzipSync(a),u("zlib.gunzip...")))}catch(e){return void console.log("error2:"+e)}if(console.log("on end 3"),!0===h(e.headers)){if(console.log("on end 4"),!n)return void d({res:o,httpprefix:g,serverName:_});u("utf-8 text, gunzipped.length:"+n.length);let i=n;"true"===t.env.cloudflare?(a=(new TextDecoder).decode(n),u("after decode, displayed string, body.length:"+a.length)):a=n.toString("utf-8");let c=a.slice(0,1e3);-1===c.indexOf('="text/html; charset=gb')&&-1===c.indexOf(' charset="gb')&&-1===c.indexOf("='text/html; charset=gb")||(u("gb2312 found..."),a=s.decode(i,"gbk"),p=!0);r.headers["X-Forwarded-For"]||r.headers["x-forwarded-for"];200===e.statusCode&&e.headers["content-type"]&&e.headers["content-type"].indexOf("text/html"),200===e.statusCode&&-1!==r.url.indexOf("/sw.js")&&o.setHeader("service-worker-allowed","/"),k({req:r,res:o,body:a,gbFlag:p})}else{console.log("on end 5");let t=r.headers["X-Forwarded-For"]||r.headers["x-forwarded-for"],n=e.headers["content-type"],i=e.headers["content-length"];console.log(`end,route:${t}, content-type:${n},gzip length:${y}, content-length:${i}, ${l}`);try{o.end(a)}catch(e){console.log("error:"+e)}}}else if(301===e.statusCode||302===e.statusCode||307===e.statusCode||308===e.statusCode||!0===h(e.headers)){u("utf-8 text...");let e=a;a="true"===t.env.cloudflare?(new TextDecoder).decode(a):a.toString("utf-8"),-1===a.indexOf('="text/html; charset=gb')&&-1===a.indexOf(' charset="gb')&&-1===a.indexOf("='text/html; charset=gb")||(u("gb2312 found..."),a=s.decode(e,"gbk"),p=!0),k({req:r,res:o,body:a,gbFlag:p})}else{u("3========>"+c());let n=r.headers["X-Forwarded-For"]||r.headers["x-forwarded-for"],i=e.headers["content-type"],s=e.headers["content-length"];console.log(`end,route:${n}, content-type:${i},length:${y}, content-length:${s}, ${l}`),"true"===t.env.cloudflare?o.end(Uint8Array.from(a)):o.end(a)}}));const m=e.headers["set-cookie"]||[];console.log("1");let w="";if(m.length>0){let e=new Date;e.setDate(e.getDate()+1),w=e.toUTCString()}console.log("2, setCookieHeaders:"+JSON.stringify(m));const x=m.map(e=>new a.Cookie(e)).map(e=>(u("cookie:"+JSON.stringify(e)),e.path&&"/"===e.path[0]&&(e.domain=""+_,e.expiration_date=w,e.path=`/${v}/${l}${e.path}`),e.secure=!1,e)).map(e=>e.toString());console.log("3");let R=new a.Cookie;if(R.name="ORIGINALHOST",R.value=`${v}/${l}`,R.domain=""+_,R.expiration_date=w,R.path="/",R.secure=!1,x.push(R.toString()),console.log("4"),e.headers["set-cookie"]=x,Object.keys(e.headers).forEach((function(t){if("content-security-policy"===t||"x-frame-options"===t||"content-length"===t&&!0===h(e.headers))u("skip header:"+t);else try{"content-encoding"===t&&!0===h(e.headers)?o.setHeader(t,"gzip"):o.setHeader(t,e.headers[t])}catch(e){return void u("error:"+e)}})),o.statusCode=e.statusCode,u(`res.status:${o.statusCode} res.url:${o.url}, res.headers:${JSON.stringify(o.getHeaders())}`),404!==o.statusCode);else try{o.headers&&o.headers["content-length"]&&delete o.headers["content-length"],d({res:o,httpprefix:g,serverName:_})}catch(e){u("error: "+e)}},onProxyReq:(e,t,n)=>{let i=new RegExp(`/http[s]?/${_}[0-9:]*?`,"g");t.url=t.url.replace(i,""),0===t.url.length&&(t.url="/");let a=t.headers["X-Forwarded-For"]||t.headers["x-forwarded-for"],{host:s,httpType:c}=p({req:t,serverName:_});for(let e=0;e3)return void n.status(404).send("{}");l(),t.headers.host=s,t.headers.referer=s,"origin"in t.headers&&(t.headers.origin=s),e.path=e.url=o({httpType:c,host:s,url:t.url});t.url.replace(`/${c}/${s}`,"");u(`httpType:${c}, host:${s}, req.url:${t.url}, req.headers:${JSON.stringify(t.headers)}`),Object.keys(t.headers).forEach((function(r){if(-1===s.indexOf("twitter.com")&&0===r.indexOf("x-")||0===r.indexOf("sec-fetch")||0===r.indexOf("cf-"))return u(`remove key=${r},`),e.removeHeader(r),void("sec-fetch-mode"===r&&e.setHeader("sec-fetch-mode","cors"));u(`set key=${r},`),e.setHeader(r,t.headers[r])})),e.setHeader("Accept-Encoding","gzip"),e.setHeader("referer",s),console.log("host="+s),-1!==s.indexOf("youtube.com")&&e.setHeader("User-Agent","Mozilla/5.0 (Linux; Android 6.0.1; Lenovo-A6020l36 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.93 Mobile Safari/537.36"),u(`req host:${s}, req.url:${t.url}, proxyReq.query:${e.query} proxyReq.path:${e.path}, proxyReq.url:${e.url} proxyReq headers:${JSON.stringify(e.getHeaders())}`),""!==s&&s||(u("------------------ sending status 404"),d({res:n,httpprefix:g,serverName:_}),n.end())}})}}).call(this,r(0),r(2).Buffer)},function(e,t,r){"use strict";t.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=c(e),a=n[0],s=n[1],u=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,f=s>0?a-4:a;for(r=0;r>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],a=0,s=r-i;as?s:a+16383));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,l=-7,f=r?i-1:0,h=r?-1:1,d=e[t+f];for(f+=h,o=d&(1<<-l)-1,d>>=-l,l+=s;l>0;o=256*o+e[t+f],f+=h,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=h,l-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),o-=c}return(d?-1:1)*a*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var a,s,u,c=8*o-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?h/u:h*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,i),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,c-=8);e[r+d-p]|=128*g}},function(e,t){},function(e,t,r){"use strict";var n=r(15).Buffer,i=r(60);e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var t,r,i,o=n.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=o,i=s,t.copy(r,i),s+=a.data.length,a=a.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(e.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t){},function(e,t,r){(function(e){var n=void 0!==e&&e||"undefined"!=typeof self&&self||window,i=Function.prototype.apply;function o(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new o(i.call(setTimeout,n,arguments),clearTimeout)},t.setInterval=function(){return new o(i.call(setInterval,n,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(n,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},r(62),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,r(1))},function(e,t,r){(function(e,t){!function(e,r){"use strict";if(!e.setImmediate){var n,i,o,a,s,u=1,c={},l=!1,f=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,"[object process]"==={}.toString.call(e.process)?n=function(e){t.nextTick((function(){p(e)}))}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,r=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=r,t}}()?e.MessageChannel?((o=new MessageChannel).port1.onmessage=function(e){p(e.data)},n=function(e){o.port2.postMessage(e)}):f&&"onreadystatechange"in f.createElement("script")?(i=f.documentElement,n=function(e){var t=f.createElement("script");t.onreadystatechange=function(){p(e),t.onreadystatechange=null,i.removeChild(t),t=null},i.appendChild(t)}):n=function(e){setTimeout(p,0,e)}:(a="setImmediate$"+Math.random()+"$",s=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(a)&&p(+t.data.slice(a.length))},e.addEventListener?e.addEventListener("message",s,!1):e.attachEvent("onmessage",s),n=function(t){e.postMessage(a+t,"*")}),h.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),r=0;rt.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=e,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}l.prototype.close=function(){this.write_in_progress?this.pending_close=!0:(this.pending_close=!1,i(this.init_done,"close before init"),i(this.mode<=t.UNZIP),this.mode===t.DEFLATE||this.mode===t.GZIP||this.mode===t.DEFLATERAW?a.deflateEnd(this.strm):this.mode!==t.INFLATE&&this.mode!==t.GUNZIP&&this.mode!==t.INFLATERAW&&this.mode!==t.UNZIP||s.inflateEnd(this.strm),this.mode=t.NONE,this.dictionary=null)},l.prototype.write=function(e,t,r,n,i,o,a){return this._write(!0,e,t,r,n,i,o,a)},l.prototype.writeSync=function(e,t,r,n,i,o,a){return this._write(!1,e,t,r,n,i,o,a)},l.prototype._write=function(r,o,a,s,u,c,l,f){if(i.equal(arguments.length,8),i(this.init_done,"write before init"),i(this.mode!==t.NONE,"already finalized"),i.equal(!1,this.write_in_progress,"write already in progress"),i.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,i.equal(!1,void 0===o,"must provide flush value"),this.write_in_progress=!0,o!==t.Z_NO_FLUSH&&o!==t.Z_PARTIAL_FLUSH&&o!==t.Z_SYNC_FLUSH&&o!==t.Z_FULL_FLUSH&&o!==t.Z_FINISH&&o!==t.Z_BLOCK)throw new Error("Invalid flush value");if(null==a&&(a=e.alloc(0),u=0,s=0),this.strm.avail_in=u,this.strm.input=a,this.strm.next_in=s,this.strm.avail_out=f,this.strm.output=c,this.strm.next_out=l,this.flush=o,!r)return this._process(),this._checkError()?this._afterSync():void 0;var h=this;return n.nextTick((function(){h._process(),h._after()})),this},l.prototype._afterSync=function(){var e=this.strm.avail_out,t=this.strm.avail_in;return this.write_in_progress=!1,[t,e]},l.prototype._process=function(){var e=null;switch(this.mode){case t.DEFLATE:case t.GZIP:case t.DEFLATERAW:this.err=a.deflate(this.strm,this.flush);break;case t.UNZIP:switch(this.strm.avail_in>0&&(e=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(null===e)break;if(31!==this.strm.input[e]){this.mode=t.INFLATE;break}if(this.gzip_id_bytes_read=1,e++,1===this.strm.avail_in)break;case 1:if(null===e)break;139===this.strm.input[e]?(this.gzip_id_bytes_read=2,this.mode=t.GUNZIP):this.mode=t.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case t.INFLATE:case t.GUNZIP:case t.INFLATERAW:for(this.err=s.inflate(this.strm,this.flush),this.err===t.Z_NEED_DICT&&this.dictionary&&(this.err=s.inflateSetDictionary(this.strm,this.dictionary),this.err===t.Z_OK?this.err=s.inflate(this.strm,this.flush):this.err===t.Z_DATA_ERROR&&(this.err=t.Z_NEED_DICT));this.strm.avail_in>0&&this.mode===t.GUNZIP&&this.err===t.Z_STREAM_END&&0!==this.strm.next_in[0];)this.reset(),this.err=s.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}},l.prototype._checkError=function(){switch(this.err){case t.Z_OK:case t.Z_BUF_ERROR:if(0!==this.strm.avail_out&&this.flush===t.Z_FINISH)return this._error("unexpected end of file"),!1;break;case t.Z_STREAM_END:break;case t.Z_NEED_DICT:return null==this.dictionary?this._error("Missing dictionary"):this._error("Bad dictionary"),!1;default:return this._error("Zlib error"),!1}return!0},l.prototype._after=function(){if(this._checkError()){var e=this.strm.avail_out,t=this.strm.avail_in;this.write_in_progress=!1,this.callback(t,e),this.pending_close&&this.close()}},l.prototype._error=function(e){this.strm.msg&&(e=this.strm.msg),this.onerror(e,this.err),this.write_in_progress=!1,this.pending_close&&this.close()},l.prototype.init=function(e,r,n,o,a){i(4===arguments.length||5===arguments.length,"init(windowBits, level, memLevel, strategy, [dictionary])"),i(e>=8&&e<=15,"invalid windowBits"),i(r>=-1&&r<=9,"invalid compression level"),i(n>=1&&n<=9,"invalid memlevel"),i(o===t.Z_FILTERED||o===t.Z_HUFFMAN_ONLY||o===t.Z_RLE||o===t.Z_FIXED||o===t.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(r,e,n,o,a),this._setDictionary()},l.prototype.params=function(){throw new Error("deflateParams Not supported")},l.prototype.reset=function(){this._reset(),this._setDictionary()},l.prototype._init=function(e,r,n,i,u){switch(this.level=e,this.windowBits=r,this.memLevel=n,this.strategy=i,this.flush=t.Z_NO_FLUSH,this.err=t.Z_OK,this.mode!==t.GZIP&&this.mode!==t.GUNZIP||(this.windowBits+=16),this.mode===t.UNZIP&&(this.windowBits+=32),this.mode!==t.DEFLATERAW&&this.mode!==t.INFLATERAW||(this.windowBits=-1*this.windowBits),this.strm=new o,this.mode){case t.DEFLATE:case t.GZIP:case t.DEFLATERAW:this.err=a.deflateInit2(this.strm,this.level,t.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case t.INFLATE:case t.GUNZIP:case t.INFLATERAW:case t.UNZIP:this.err=s.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}this.err!==t.Z_OK&&this._error("Init error"),this.dictionary=u,this.write_in_progress=!1,this.init_done=!0},l.prototype._setDictionary=function(){if(null!=this.dictionary){switch(this.err=t.Z_OK,this.mode){case t.DEFLATE:case t.DEFLATERAW:this.err=a.deflateSetDictionary(this.strm,this.dictionary)}this.err!==t.Z_OK&&this._error("Failed to set dictionary")}},l.prototype._reset=function(){switch(this.err=t.Z_OK,this.mode){case t.DEFLATE:case t.DEFLATERAW:case t.GZIP:this.err=a.deflateReset(this.strm);break;case t.INFLATE:case t.INFLATERAW:case t.GUNZIP:this.err=s.inflateReset(this.strm)}this.err!==t.Z_OK&&this._error("Failed to reset stream")},t.Zlib=l}).call(this,r(2).Buffer,r(0))},function(e,t,r){"use strict"; + */const n=r(4),i=r(141),o=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),a=e=>"number"==typeof e||"string"==typeof e&&""!==e,s=e=>Number.isInteger(+e),u=e=>{let t=""+e,r=-1;if("-"===t[0]&&(t=t.slice(1)),"0"===t)return!1;for(;"0"===t[++r];);return r>0},c=(e,t,r)=>{if(t>0){let r="-"===e[0]?"-":"";r&&(e=e.slice(1)),e=r+e.padStart(r?t-1:t,"0")}return!1===r?String(e):e},l=(e,t)=>{let r="-"===e[0]?"-":"";for(r&&(e=e.slice(1),t--);e.length{if(r)return i(e,t,{wrap:!1,...n});let o=String.fromCharCode(e);return e===t?o:`[${o}-${String.fromCharCode(t)}]`},h=(e,t,r)=>{if(Array.isArray(e)){let t=!0===r.wrap,n=r.capture?"":"?:";return t?`(${n}${e.join("|")})`:e.join("|")}return i(e,t,r)},d=(...e)=>new RangeError("Invalid range arguments: "+n.inspect(...e)),p=(e,t,r)=>{if(!0===r.strictRanges)throw d([e,t]);return[]},g=(e,t,r=1,n={})=>{let i=Number(e),o=Number(t);if(!Number.isInteger(i)||!Number.isInteger(o)){if(!0===n.strictRanges)throw d([e,t]);return[]}0===i&&(i=0),0===o&&(o=0);let a=i>o,s=String(e),p=String(t),g=String(r);r=Math.max(Math.abs(r),1);let _=u(s)||u(p)||u(g),v=_?Math.max(s.length,p.length,g.length):0,b=!1===_&&!1===((e,t,r)=>"string"==typeof e||"string"==typeof t||!0===r.stringify)(e,t,n),y=n.transform||(e=>t=>!0===e?Number(t):String(t))(b);if(n.toRegex&&1===r)return f(l(e,v),l(t,v),!0,n);let m={negatives:[],positives:[]},w=[],x=0;for(;a?i>=o:i<=o;)!0===n.toRegex&&r>1?m[(E=i)<0?"negatives":"positives"].push(Math.abs(E)):w.push(c(y(i,x),v,b)),i=a?i-r:i+r,x++;var E;return!0===n.toRegex?r>1?((e,t)=>{e.negatives.sort((e,t)=>et?1:0),e.positives.sort((e,t)=>et?1:0);let r,n=t.capture?"":"?:",i="",o="";return e.positives.length&&(i=e.positives.join("|")),e.negatives.length&&(o=`-(${n}${e.negatives.join("|")})`),r=i&&o?`${i}|${o}`:i||o,t.wrap?`(${n}${r})`:r})(m,n):h(w,null,{wrap:!1,...n}):w},_=(e,t,r,n={})=>{if(null==t&&a(e))return[e];if(!a(e)||!a(t))return p(e,t,n);if("function"==typeof r)return _(e,t,1,{transform:r});if(o(r))return _(e,t,0,r);let i={...n};return!0===i.capture&&(i.wrap=!0),r=r||i.step||1,s(r)?s(e)&&s(t)?g(e,t,r,i):((e,t,r=1,n={})=>{if(!s(e)&&e.length>1||!s(t)&&t.length>1)return p(e,t,n);let i=n.transform||(e=>String.fromCharCode(e)),o=(""+e).charCodeAt(0),a=(""+t).charCodeAt(0),u=o>a,c=Math.min(o,a),l=Math.max(o,a);if(n.toRegex&&1===r)return f(c,l,!1,n);let d=[],g=0;for(;u?o>=a:o<=a;)d.push(i(o,g)),o=u?o-r:o+r,g++;return!0===n.toRegex?h(d,null,{wrap:!1,options:n}):d})(e,t,Math.max(Math.abs(r),1),i):null==r||o(r)?_(e,t,1,r):((e,t)=>{if(!0===t.strictRanges)throw new TypeError(`Expected step "${e}" to be a number`);return[]})(r,i)};e.exports=_},function(e,t,r){(function(e){e.env.cloudflare="true";var t=r(55);let{blockedSites:n,urlModify:i,httpprefix:o,serverName:a,port:s,locationReplaceMap302:u,regReplaceMap:c,siteSpecificReplace:l,pathReplace:f}=r(153),{middle2req:h,req2middleware:d,middle2res:p,res2middleware:g}=r(158);let _=a;addEventListener("fetch",e=>{var r;e.respondWith((r=e.request,new Promise(async(e,v)=>{let b=(new Date).toISOString(),y=d(r);try{y.url=y.url.replace("https://tutorial.cloudflareworkers.com","");let r=new RegExp(`http[s]?://${a}[0-9:]*`,"g");y.url=y.url.replace(r,""),r=new RegExp(`/http[s]?/${a}[0-9:]*?`,"g"),y.url=y.url.replace(r,""),console.log(`timestr:${b}, serverName:${a}, middle_req:${JSON.stringify(y)}`),""!==y.url&&"/"!==y.url||(y.url="/https/www.netptop.com"),console.log(`${b}: after modification, middle_req.url:${y.url}`);let v,m,w,{readable:x,writable:E}=new TransformStream,k=E.getWriter(),R=g({cf_res:new Response(x)});R.write=t=>{if(console.log("====> middle_res.send() being called."),!R.replied){console.log("sending response ..."),R.replied=!0;let t=p({middle_res:R,readable:x});console.log("cf_res:"+JSON.stringify(t)),e(t)}t&&(console.log("before getWriter"),console.log("after getWriter"),k.write(t),console.log("after write data"))},R.end=R.send=e=>{R.write(e),console.log("writable closed."),k.close()},t({ProxyMiddleware:({target:e,router:t,protocolRewrite:r,cookieDomainRewrite:n,onError:i,onProxyRes:o,onProxyReq:a,secure:s=!1,changeOrigin:u=!0,debug:c=!0,selfHandleResponse:l=!0})=>{v=a,m=o,w=t},blockedSites:n,urlModify:i,httpprefix:o,serverName:a,port:s,cookieDomainRewrite:_,locationReplaceMap302:u,regReplaceMap:c,siteSpecificReplace:l,pathReplace:f}),console.log("proxy called");const A=w(y);console.log("target:"+A);let S=d(new Request(A,{redirect:h.redirect,method:y.method}));console.log("calling onProxyReq..."),v(S,y,R),console.log("====> after onProxyReq, middle_proxyReq:"+JSON.stringify(S));const C=h(A,S);console.log("fetching: cf_proxyReq:"+JSON.stringify(C));let O=await fetch(C).catch(e=>{console.log("fetching error: "+JSON.stringify(e))}),T=g({cf_res:O});if(console.log("calling onProxyRes..."),m(T,y,R),console.log("after onProxyRes, cf_proxyRes.body:"+JSON.stringify(O.body)),R.write(null),null===O.body)return;let L=O.body.getReader();for(;;){let{done:e,value:t}=await L.read();if(t&&T.emit("data",t),e){T.emit("end");break}}}catch(e){console.log("error happened:"+e)}})))})}).call(this,r(0))},function(e,t,r){(function(t,n){const i=r(32),o=r(40),a=r(42),s=r(82),{logSave:u,logGet:c,logClear:l}=(r(101),r(110));r(111);function f(e){let t=e.reduce((e,t)=>e+t.length,0);if(!e.length)return null;let r=new Uint8Array(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}var h=e=>!e["content-type"]||-1!==e["content-type"].indexOf("text/")||-1!==e["content-type"].indexOf("javascript")||-1!==e["content-type"].indexOf("urlencoded")||-1!==e["content-type"].indexOf("json"),d=function({res:e,httpprefix:t,serverName:r}){try{e.setHeader("location",`${t}://${r}`)}catch(e){return void u("error: "+e)}e.status(302).send("")};let p=({req:e,serverName:t})=>{let r="",n="https";if(e.url.startsWith("/https/")){r=e.url.slice("/https/".length,e.url.length);let t=r.match(/[-a-z0-9A-Z]+\.[-a-z0-9A-Z.]+/g);r=t.length>0?t[0]:""}else if(e.url.startsWith("/http/")){r=e.url.slice("/http/".length,e.url.length);let t=r.match(/[-a-z0-9A-Z]+\.[-a-z0-9A-Z.]+/g);r=t.length>0?t[0]:"",n="http"}else if(e.headers.referer&&-1!==e.headers.referer.indexOf("https/")){let t=e.headers.referer.indexOf("https/")+6;r=e.headers.referer.slice(t,e.headers.referer.length);let n=r.indexOf("/");-1===n&&(n=r.length),r=r.slice(0,n),u(`============= host:${r}, req referer:${e.headers.referer}`)}else if(e.headers.referer&&-1!==e.headers.referer.indexOf("http/")){let t=e.headers.referer.indexOf("http/")+5;r=e.headers.referer.slice(t,e.headers.referer.length);let i=r.indexOf("/");-1===i&&(i=r.length),r=r.slice(0,i),n="http",u(`============= host:${r}, req referer:${e.headers.referer}`)}else if(e.headers.referer){var i=o(e.headers.referer);i.hostname?(r=i.hostname,n=i.protocol.replace(":","")):(r=e.headers.referer,n="https")}let s="";if(e.headers.cookie){e.headers.cookie.split(" ").map(e=>new a.Cookie(e)).map(e=>{"ORIGINALHOST"===e.name&&(s=e.value)})}return(""===r||r===t&&!["/index.html","/","/favicon.png"].includes(e.url))&&""!==s&&(n=s.split("/")[0],r=s.split("/")[1],u(`getHostFromReq, use ORIGINALHOST, ${n},${r}`)),u(`getHostFromReq, req.url:${e.url}, referer:${e.headers.referer}, host:${r}, httpType:${n}`),{host:r,httpType:n}};e.exports=({ProxyMiddleware:e,blockedSites:r,urlModify:o,httpprefix:g,serverName:_,port:v,cookieDomainRewrite:b,locationReplaceMap302:y,regReplaceMap:m,siteSpecificReplace:w,pathReplace:x})=>{var E=({res:e,serverName:t,httpprefix:r,host:n,httpType:i})=>{let o=e.getHeaders().location;if("301"==e.statusCode||"302"==e.statusCode||"303"==e.statusCode||"307"==e.statusCode||"308"==e.statusCode){o=y({location:o,serverName:t,httpprefix:r,host:n,httpType:i}),u("after replacement, location="+o);try{e.setHeader("location",o)}catch(e){return u("error: "+e),!1}}return!0};let k=({req:e,res:r,body:n,gbFlag:o})=>{let a,{host:l,httpType:f}=p({req:e,serverName:_});if(!1!==E({res:r,serverName:_,httpprefix:g,host:l,httpType:f})){for(let e in m)a=new RegExp(e,"g"),n=n.replace(a,m[e]);if(u("##### host:"+l),l&&(n=x({host:l,httpType:f,body:n})),u("2"),u("3"),a=new RegExp(`/${f}/${l}/${f}/${l}/`,"g"),n=n.replace(a,`/${f}/${l}/`),u("4"),Object.keys(w).forEach(t=>{e.url&&(-1!==e.url.indexOf(t)||e.headers.referer&&-1!==e.headers.referer.indexOf(t))&&(keys=Object.keys(w[t]),keys.forEach(e=>{a=new RegExp(e,"g"),n=n.replace(a,w[t][e])}))}),u("5"),o&&(n=s.encode(n,"gbk")),"string"==typeof n&&n.startsWith(`${g}://${_}`)&&-1!==n.indexOf("googlevideo.com")){console.log("============== redirect googlevideo.com");try{r.setHeader("location",n)}catch(e){return void u("error: "+e)}r.statusCode="302"}if(u("5 after replacment,displayed string, body.length:"+n.length),"true"===t.env.cloudflare){let e=new TextEncoder;n=e.encode(n),u("6 cloudflare, after encoding, uint8array, body.length:"+n.length)}else n=i.gzipSync(n);u("7");try{r.setHeader("content-encoding","gzip"),u(`handleRespond: res.statusCode:${r.statusCode}, res.headers:${JSON.stringify(r.getHeaders())}`),"true"===e.headers.debugflag&&(r.removeHeader("content-encoding"),r.setHeader("content-type","text/plain"),n=c()),r.end(n)}catch(e){u("error: "+e)}}};return e({target:"https://www.google.com",router:e=>{let t=new RegExp(`/http[s]?/${_}.*?/`,"g");e.url=e.url.replace(t,"/");let{host:r,httpType:n}=p({req:e,serverName:_}),i=`${n}://${r}`;return u(`router, target:${i}, req.url:${e.url}`),i},protocolRewrite:!0,cookieDomainRewrite:b,secure:!1,changeOrigin:!0,debug:!0,onError:(e,t,r)=>{console.log("onerror: "+JSON.stringify(e));try{(e.code&&("ECONNREFUSED"===e.code||"EHOSTUNREACH"===e.code||"EPROTO"===e.code||"ECONNRESET"===e.code||"ENOTFOUND"===e.code)||e.reason&&-1===e.reason.indexOf("Expected"))&&d({res:r,httpprefix:g,serverName:_})}catch(e){u("error of sending 404: "+e)}},selfHandleResponse:!0,onProxyRes:(e,r,o)=>{let{host:l,httpType:v}=p({req:r,serverName:_});u(`proxyRes.status:${e.statusCode} proxyRes.headers:${JSON.stringify(e.headers)}`);let b=[],y=0;e.on("data",(function(i){if(y+=i.length,b.push(i),y>=25e5&&!0!==h(e.headers)){let i;i="true"===t.env.cloudflare?f(b):n.concat(b);let a=r.headers["X-Forwarded-For"]||r.headers["x-forwarded-for"],s=e.headers["content-type"],u=e.headers["content-length"];u>=155e6||l.indexOf("googlevideo"),console.log(`route:${a}, content-type:${s},bulk length:${y}, content-length:${u}, ${l}`),b=[],y=0,o.write(i)}})),e.on("end",(function(){let a;if(console.log("on end 1, bodyList.length:"+b.length),"true"===t.env.cloudflare){if(a=f(b),!a)return E({res:o,serverName:_,httpprefix:g,host:l,httpType:v}),void o.end(a)}else a=n.concat(b);console.log("on end 2, body.length:"+a.length);let p=!1;if("gzip"===e.headers["content-encoding"]||"br"===e.headers["content-encoding"]){let n;try{"true"===t.env.cloudflare?(console.log("cloudflare environment"),n=a):(console.log("node environment"),"br"===e.headers["content-encoding"]?(n=i.brotliDecompressSync(a),u("zlib.brotli...")):(n=i.gunzipSync(a),u("zlib.gunzip...")))}catch(e){return void console.log("error2:"+e)}if(console.log("on end 3"),!0===h(e.headers)){if(console.log("on end 4"),!n)return void d({res:o,httpprefix:g,serverName:_});u("utf-8 text, gunzipped.length:"+n.length);let i=n;"true"===t.env.cloudflare?(a=(new TextDecoder).decode(n),u("after decode, displayed string, body.length:"+a.length)):a=n.toString("utf-8");let c=a.slice(0,1e3);-1===c.indexOf('="text/html; charset=gb')&&-1===c.indexOf(' charset="gb')&&-1===c.indexOf("='text/html; charset=gb")||(u("gb2312 found..."),a=s.decode(i,"gbk"),p=!0);r.headers["X-Forwarded-For"]||r.headers["x-forwarded-for"];200===e.statusCode&&e.headers["content-type"]&&e.headers["content-type"].indexOf("text/html"),200===e.statusCode&&-1!==r.url.indexOf("/sw.js")&&o.setHeader("service-worker-allowed","/"),k({req:r,res:o,body:a,gbFlag:p})}else{console.log("on end 5");let t=r.headers["X-Forwarded-For"]||r.headers["x-forwarded-for"],n=e.headers["content-type"],i=e.headers["content-length"];console.log(`end,route:${t}, content-type:${n},gzip length:${y}, content-length:${i}, ${l}`);try{o.end(a)}catch(e){console.log("error:"+e)}}}else if(301===e.statusCode||302===e.statusCode||307===e.statusCode||308===e.statusCode||!0===h(e.headers)){u("utf-8 text...");let e=a;a="true"===t.env.cloudflare?(new TextDecoder).decode(a):a.toString("utf-8"),-1===a.indexOf('="text/html; charset=gb')&&-1===a.indexOf(' charset="gb')&&-1===a.indexOf("='text/html; charset=gb")||(u("gb2312 found..."),a=s.decode(e,"gbk"),p=!0),k({req:r,res:o,body:a,gbFlag:p})}else{u("3========>"+c());let n=r.headers["X-Forwarded-For"]||r.headers["x-forwarded-for"],i=e.headers["content-type"],s=e.headers["content-length"];console.log(`end,route:${n}, content-type:${i},length:${y}, content-length:${s}, ${l}`),"true"===t.env.cloudflare?o.end(Uint8Array.from(a)):o.end(a)}}));const m=e.headers["set-cookie"]||[];console.log("1");let w="",x="";if(m.length>0){let e=new Date,t=new Date(e.getTime()+72e5);w=t.toUTCString(),t=new Date(e.getTime()+6e5),x=t.toUTCString()}console.log("2, setCookieHeaders:"+JSON.stringify(m));const R=m.map(e=>new a.Cookie(e)).map(e=>(u("cookie:"+JSON.stringify(e)),e.path&&"/"===e.path[0]&&(e.domain=""+_,e.expiration_date=w,e.path=`/${v}/${l}${e.path}`),e.secure=!1,e)).map(e=>e.toString());console.log("3");let A=new a.Cookie;if(A.name="ORIGINALHOST",A.value=`${v}/${l}`,A.domain=""+_,A.expiration_date=x,A.path="/",A.secure=!1,R.push(A.toString()),console.log("4"),e.headers["set-cookie"]=R,Object.keys(e.headers).forEach((function(t){if("content-security-policy"===t||"x-frame-options"===t||"content-length"===t&&!0===h(e.headers))u("skip header:"+t);else try{"content-encoding"===t&&!0===h(e.headers)?o.setHeader(t,"gzip"):o.setHeader(t,e.headers[t])}catch(e){return void u("error:"+e)}})),o.statusCode=e.statusCode,u(`res.status:${o.statusCode} res.url:${o.url}, res.headers:${JSON.stringify(o.getHeaders())}`),404!==o.statusCode);else try{o.headers&&o.headers["content-length"]&&delete o.headers["content-length"],d({res:o,httpprefix:g,serverName:_})}catch(e){u("error: "+e)}},onProxyReq:(e,t,n)=>{let i=new RegExp(`/http[s]?/${_}[0-9:]*?`,"g");t.url=t.url.replace(i,""),0===t.url.length&&(t.url="/");let a=t.headers["X-Forwarded-For"]||t.headers["x-forwarded-for"],{host:s,httpType:c}=p({req:t,serverName:_});for(let e=0;e3)return void n.status(404).send("{}");l(),t.headers.host=s,t.headers.referer=s,"origin"in t.headers&&(t.headers.origin=s),e.path=e.url=o({httpType:c,host:s,url:t.url});t.url.replace(`/${c}/${s}`,"");u(`httpType:${c}, host:${s}, req.url:${t.url}, req.headers:${JSON.stringify(t.headers)}`),Object.keys(t.headers).forEach((function(r){if(-1===s.indexOf("twitter.com")&&0===r.indexOf("x-")||0===r.indexOf("sec-fetch")||0===r.indexOf("cf-"))return u(`remove key=${r},`),e.removeHeader(r),void("sec-fetch-mode"===r&&e.setHeader("sec-fetch-mode","cors"));u(`set key=${r},`),e.setHeader(r,t.headers[r])})),e.setHeader("Accept-Encoding","gzip"),e.setHeader("referer",s),console.log("host="+s),-1!==s.indexOf("youtube.com")&&e.setHeader("User-Agent","Mozilla/5.0 (Linux; Android 6.0.1; Lenovo-A6020l36 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.93 Mobile Safari/537.36"),u(`req host:${s}, req.url:${t.url}, proxyReq.query:${e.query} proxyReq.path:${e.path}, proxyReq.url:${e.url} proxyReq headers:${JSON.stringify(e.getHeaders())}`),""!==s&&s||(u("------------------ sending status 404"),d({res:n,httpprefix:g,serverName:_}),n.end())}})}}).call(this,r(0),r(2).Buffer)},function(e,t,r){"use strict";t.byteLength=function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=c(e),a=n[0],s=n[1],u=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,f=s>0?a-4:a;for(r=0;r>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],a=0,s=r-i;as?s:a+16383));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,l=-7,f=r?i-1:0,h=r?-1:1,d=e[t+f];for(f+=h,o=d&(1<<-l)-1,d>>=-l,l+=s;l>0;o=256*o+e[t+f],f+=h,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=h,l-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),o-=c}return(d?-1:1)*a*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var a,s,u,c=8*o-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?h/u:h*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,i),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,c-=8);e[r+d-p]|=128*g}},function(e,t){},function(e,t,r){"use strict";var n=r(15).Buffer,i=r(60);e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var t,r,i,o=n.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=o,i=s,t.copy(r,i),s+=a.data.length,a=a.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(e.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},function(e,t){},function(e,t,r){(function(e){var n=void 0!==e&&e||"undefined"!=typeof self&&self||window,i=Function.prototype.apply;function o(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new o(i.call(setTimeout,n,arguments),clearTimeout)},t.setInterval=function(){return new o(i.call(setInterval,n,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(n,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},r(62),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,r(1))},function(e,t,r){(function(e,t){!function(e,r){"use strict";if(!e.setImmediate){var n,i,o,a,s,u=1,c={},l=!1,f=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,"[object process]"==={}.toString.call(e.process)?n=function(e){t.nextTick((function(){p(e)}))}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,r=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=r,t}}()?e.MessageChannel?((o=new MessageChannel).port1.onmessage=function(e){p(e.data)},n=function(e){o.port2.postMessage(e)}):f&&"onreadystatechange"in f.createElement("script")?(i=f.documentElement,n=function(e){var t=f.createElement("script");t.onreadystatechange=function(){p(e),t.onreadystatechange=null,i.removeChild(t),t=null},i.appendChild(t)}):n=function(e){setTimeout(p,0,e)}:(a="setImmediate$"+Math.random()+"$",s=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(a)&&p(+t.data.slice(a.length))},e.addEventListener?e.addEventListener("message",s,!1):e.attachEvent("onmessage",s),n=function(t){e.postMessage(a+t,"*")}),h.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),r=0;rt.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=e,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}l.prototype.close=function(){this.write_in_progress?this.pending_close=!0:(this.pending_close=!1,i(this.init_done,"close before init"),i(this.mode<=t.UNZIP),this.mode===t.DEFLATE||this.mode===t.GZIP||this.mode===t.DEFLATERAW?a.deflateEnd(this.strm):this.mode!==t.INFLATE&&this.mode!==t.GUNZIP&&this.mode!==t.INFLATERAW&&this.mode!==t.UNZIP||s.inflateEnd(this.strm),this.mode=t.NONE,this.dictionary=null)},l.prototype.write=function(e,t,r,n,i,o,a){return this._write(!0,e,t,r,n,i,o,a)},l.prototype.writeSync=function(e,t,r,n,i,o,a){return this._write(!1,e,t,r,n,i,o,a)},l.prototype._write=function(r,o,a,s,u,c,l,f){if(i.equal(arguments.length,8),i(this.init_done,"write before init"),i(this.mode!==t.NONE,"already finalized"),i.equal(!1,this.write_in_progress,"write already in progress"),i.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,i.equal(!1,void 0===o,"must provide flush value"),this.write_in_progress=!0,o!==t.Z_NO_FLUSH&&o!==t.Z_PARTIAL_FLUSH&&o!==t.Z_SYNC_FLUSH&&o!==t.Z_FULL_FLUSH&&o!==t.Z_FINISH&&o!==t.Z_BLOCK)throw new Error("Invalid flush value");if(null==a&&(a=e.alloc(0),u=0,s=0),this.strm.avail_in=u,this.strm.input=a,this.strm.next_in=s,this.strm.avail_out=f,this.strm.output=c,this.strm.next_out=l,this.flush=o,!r)return this._process(),this._checkError()?this._afterSync():void 0;var h=this;return n.nextTick((function(){h._process(),h._after()})),this},l.prototype._afterSync=function(){var e=this.strm.avail_out,t=this.strm.avail_in;return this.write_in_progress=!1,[t,e]},l.prototype._process=function(){var e=null;switch(this.mode){case t.DEFLATE:case t.GZIP:case t.DEFLATERAW:this.err=a.deflate(this.strm,this.flush);break;case t.UNZIP:switch(this.strm.avail_in>0&&(e=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(null===e)break;if(31!==this.strm.input[e]){this.mode=t.INFLATE;break}if(this.gzip_id_bytes_read=1,e++,1===this.strm.avail_in)break;case 1:if(null===e)break;139===this.strm.input[e]?(this.gzip_id_bytes_read=2,this.mode=t.GUNZIP):this.mode=t.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case t.INFLATE:case t.GUNZIP:case t.INFLATERAW:for(this.err=s.inflate(this.strm,this.flush),this.err===t.Z_NEED_DICT&&this.dictionary&&(this.err=s.inflateSetDictionary(this.strm,this.dictionary),this.err===t.Z_OK?this.err=s.inflate(this.strm,this.flush):this.err===t.Z_DATA_ERROR&&(this.err=t.Z_NEED_DICT));this.strm.avail_in>0&&this.mode===t.GUNZIP&&this.err===t.Z_STREAM_END&&0!==this.strm.next_in[0];)this.reset(),this.err=s.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}},l.prototype._checkError=function(){switch(this.err){case t.Z_OK:case t.Z_BUF_ERROR:if(0!==this.strm.avail_out&&this.flush===t.Z_FINISH)return this._error("unexpected end of file"),!1;break;case t.Z_STREAM_END:break;case t.Z_NEED_DICT:return null==this.dictionary?this._error("Missing dictionary"):this._error("Bad dictionary"),!1;default:return this._error("Zlib error"),!1}return!0},l.prototype._after=function(){if(this._checkError()){var e=this.strm.avail_out,t=this.strm.avail_in;this.write_in_progress=!1,this.callback(t,e),this.pending_close&&this.close()}},l.prototype._error=function(e){this.strm.msg&&(e=this.strm.msg),this.onerror(e,this.err),this.write_in_progress=!1,this.pending_close&&this.close()},l.prototype.init=function(e,r,n,o,a){i(4===arguments.length||5===arguments.length,"init(windowBits, level, memLevel, strategy, [dictionary])"),i(e>=8&&e<=15,"invalid windowBits"),i(r>=-1&&r<=9,"invalid compression level"),i(n>=1&&n<=9,"invalid memlevel"),i(o===t.Z_FILTERED||o===t.Z_HUFFMAN_ONLY||o===t.Z_RLE||o===t.Z_FIXED||o===t.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(r,e,n,o,a),this._setDictionary()},l.prototype.params=function(){throw new Error("deflateParams Not supported")},l.prototype.reset=function(){this._reset(),this._setDictionary()},l.prototype._init=function(e,r,n,i,u){switch(this.level=e,this.windowBits=r,this.memLevel=n,this.strategy=i,this.flush=t.Z_NO_FLUSH,this.err=t.Z_OK,this.mode!==t.GZIP&&this.mode!==t.GUNZIP||(this.windowBits+=16),this.mode===t.UNZIP&&(this.windowBits+=32),this.mode!==t.DEFLATERAW&&this.mode!==t.INFLATERAW||(this.windowBits=-1*this.windowBits),this.strm=new o,this.mode){case t.DEFLATE:case t.GZIP:case t.DEFLATERAW:this.err=a.deflateInit2(this.strm,this.level,t.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case t.INFLATE:case t.GUNZIP:case t.INFLATERAW:case t.UNZIP:this.err=s.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}this.err!==t.Z_OK&&this._error("Init error"),this.dictionary=u,this.write_in_progress=!1,this.init_done=!0},l.prototype._setDictionary=function(){if(null!=this.dictionary){switch(this.err=t.Z_OK,this.mode){case t.DEFLATE:case t.DEFLATERAW:this.err=a.deflateSetDictionary(this.strm,this.dictionary)}this.err!==t.Z_OK&&this._error("Failed to set dictionary")}},l.prototype._reset=function(){switch(this.err=t.Z_OK,this.mode){case t.DEFLATE:case t.DEFLATERAW:case t.GZIP:this.err=a.deflateReset(this.strm);break;case t.INFLATE:case t.INFLATERAW:case t.GUNZIP:this.err=s.inflateReset(this.strm)}this.err!==t.Z_OK&&this._error("Failed to reset stream")},t.Zlib=l}).call(this,r(2).Buffer,r(0))},function(e,t,r){"use strict"; /* object-assign (c) Sindre Sorhus