返回官网

CloudFlare的 worker代码备录

狒狒 2024-9-11 技术札记 79 次
let rHostUrl = ''

//主函数
async function fetchAndApply(request) {
      
 
  const region = request.headers.get('cf-ipcountry') || '';
  const ipAddress = request.headers.get('cf-connecting-ip') || '';
  const userAgent = request.headers.get('user-agent') || ''; 
  const uaPlatform = request.headers.get('sec-ch-ua-platform') || ''; 
  const referer = request.headers.get('Referer') || '';
  const language = request.headers.get('Accept-Language') || '';
  const fetchDest = request.headers.get('sec-fetch-dest') || '';
  const browser = request.headers.get('sec-ch-ua') || '';
  const asn  = (request.cf || {}).asn ||'';
  const colos  = (request.cf || {}).colos ||'';
  const country  = (request.cf || {}).country ||'';
  const city  = (request.cf || {}).city ||'';
  const continent  = (request.cf || {}).continent ||'';
  const httpProtocol  = (request.cf || {}).httpProtocol ||'';
  const tlsCipher  = (request.cf || {}).tlsCipher ||'';
  const tlsClientAuth  = (request.cf || {}).tlsClientAuth ||'';
  const tlsVersion  = (request.cf || {}).tlsVersion ||'';
  const regionCode  = (request.cf || {}).regionCode ||'';
  const latitude  = (request.cf || {}).latitude ||'';
  const longitude  = (request.cf || {}).longitude ||'';


  // console.log(asn);
  // console.log(colos);
  // console.log(country);
  // console.log(city);
  // console.log(continent);
  // console.log(httpProtocol);
  // console.log(tlsCipher);
  // console.log(tlsClientAuth);
  // console.log(tlsVersion);
  // console.log(regionCode);
  // console.log(latitude);
  // console.log(longitude);

  const coordinates = latitude+','+longitude;

  let basicUrl = '';  
  basicUrl = request.url;  
  
  const requestURL = new URL(request.url);
  const baseURL = new URL(request.url);
  let  upstreamURL = new URL(basicUrl); 
  let results = null;

  // console.log(requestURL);

  // const userAgent = "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)"; 
  // let checkUserAgent = userAgent.indexOf("externalhit_uatext.php");

  // return new Response(requestURL.protocol+'//'+'lpsiteserver.'+requestURL.host+'/eetest/',{status:404,}, );
  // if(userAgent == 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)' || checkUserAgent!==-1){  
    
  //   const baseResponse = await fetch(upstreamURL.protocol+'//lpsiteserver.'+requestURL.host+'/');
  //   return new Response(    baseResponse.body, { status: 404, },   ); 
  // }
   
  // for (var i = 0; i < BlackASNlist.length; i++) {
  //   if (asn == BlackASNlist[i]){
  //       return new Response(   'asn Access denied: It is not available in your region.',   {status: 404,},  );
  //   }
  // } 
  // const contentType = request.headers.get("content-type") || "";  
// request.headers.forEach()
// console.log(request.headers.keys())
  // const region = 'JP'
  const deviceStr = uaPlatform.replace(/"/g,'') || '';
  if(region==null || region==''){   
 
     // 使用 IP 地址获取国家和ISP信息
     const response = await fetch(`https://ipinfo.io/${ipAddress}/json`)
     const ipInfo = await response.json()
     console.log(ipInfo);
     // 获取ISP信息
     const isp = ipInfo.org
     const city = ipInfo.city
     const country = ipInfo.country
     const city_region = ipInfo.region
     const loc= ipInfo.loc
     const timezone= ipInfo.timezone
     const hostname= ipInfo.hostname
 
     const region = country
    //  console.log(isp)
    //  console.log(country)
    //  console.log(city)
    //  console.log(city_region)
    //  console.log(loc)
    //  console.log(timezone)
    //  console.log(hostname)
  }
   
  // console.log(ipAddress);
  // console.log(region);
  // console.log(language);
  // console.log(fetchDest);
  // console.log(uaPlatform);
  // console.log(referer);
  // console.log(userAgent);
  // console.log(browser);
  // console.log(request.url);
  // console.log(deviceStr);
  var arrayData = {'ip':ipAddress,'coordinates':coordinates,'region':region,'language':language,'fetchDest':fetchDest,'deviceStr':deviceStr,'referer':referer,'userAgent':userAgent,'browser':browser,'url':request.url}
  
  let jsonStr = JSON.stringify(arrayData);
  var encodedJsonStr = encodeURIComponent(jsonStr);

  // console.log(encodedJsonStr);

  // var jsonData = ipAddress+':::'+region+':::'+language+':::'+fetchDest+':::'+deviceStr+':::'+referer+':::'+userAgent+':::'+browser+':::'+request.url
  // var baseStr = base64_encode(jsonData)
  // console.log(baseStr)
  //request.headers.set("user-agent", "mirror");
  
  // request.headers.forEach(function(v,index){
  //     console.log(index+': '+v)
  // }); 
   
 //if(rHostUrl ==''){
    // rHostUrl = requestURL.protocol+'//'+requestURL.host+'/js/worker.js';
//获取规避规则
  rHostUrl = '/api/domainWorkerJson?signSalt=d252df29edb659a08ea6143c7c9c9b48&host='+encodedJsonStr;
  //return new Response(   userAgent+'  '+region+' '+rHostUrl+'  asn Access denied: It is not available in your region.',   {status: 403,},  );
  console.log(rHostUrl);
  const resp = await fetch(rHostUrl) ; 
  // console.log(resp)    
  results = await gatherResponse(resp);    
  
  // const contentType = request.headers.get("content-type") || ""; 
  // console.log('contentType: '+contentType)   
  // if(!results.isPoxy){
  console.log(request.url);    
  // return new fetch(request);
  //  return new Response( 'Access denied: Your IP address is blocked.', { status: 403,},);  
  // } 
  //&& requestURL.host in results
  //[requestURL.host]
 
//  return new Response (upstreamURL.protocol+'//'+results.basic.upstream,{status:404});
 

  if(results.basic){
    //upstreamURL.protocol+'//'++'/eetest/'
    
    basicUrl = results.basic.upstream;
    console.log(basicUrl);
   
    upstreamURL = new URL(basicUrl);   
    
    let safePage =  results.basic.safePage;
    if(safePage){ 
        if(requestURL.pathname != '/'){
            if(requestURL.pathname.indexOf(upstreamURL.pathname)>0){
                let re = new RegExp(upstreamURL.pathname, 'g')
                requestURL.pathname = requestURL.pathname.replace(re, '');  
                requestURL.pathname = upstreamURL.pathname ;
                //+ requestURL.pathname;
                //  console.log(requestURL.href)
                //  console.log(upstreamURL.href)
            }else{
                console.log('requestURL.pathname!="/"');
                requestURL.protocol = upstreamURL.protocol;
                requestURL.host = upstreamURL.host;
                //判断是不是wp-
                // if(requestURL.pathname.indexOf('wp-content')===-1 && requestURL.pathname.indexOf('wp-includes')===-1){
                  // requestURL.pathname = upstreamURL.pathname;// + requestURL.pathname;
                // }
            }
            let newRequest = new Request(requestURL)
            let response = await fetch(newRequest)
            let body = await response.text();
            let proxyUrl = new RegExp(requestURL.host, 'g');
            let newBody = body.replace(proxyUrl,baseURL.host);
            // console.log(newBody);
            return new Response(newBody, response);
            // return response

        }else{
            
            console.log(baseURL.host);
            requestURL.href = upstreamURL.href
            console.log(requestURL.href);
            let response = await fetch(requestURL.href);
            // console.log(response);
            let body = await response.text();
            // console.log(requestURL.host);
            let proxyUrl = new RegExp(requestURL.host, 'g');
          
            // 替换 body 中的字符串
            let newBody = body.replace(proxyUrl,baseURL.host);
            // console.log(newBody);
            return new Response(newBody, response);
        
        } 
      
    }
 
  } 
  // return new Response( '  Access denied: Your IP address is blocked', { status: 403,},);
  // return new Response( upstreamURL+'       '+rHostUrl+'   '+jsonStr+' Access denied: Your IP address is blocked.', { status: 403,},); 
  // return new Response( rHostUrl+'  Access denied: Your IP address is blocked', { status: 403,},);
  //  console.log(results)
  if(results){
    var rConfig = results;
    // console.log(results) 
    // console.log(requestURL.host) 
    // console.log(results[requestURL.host].routes)    
    // console.log(rConfig.firewall)
   
    //根据屏蔽的国家返回错误
    if (region !== '' ) {
      
      if(rConfig.firewall){
        if(rConfig.firewall.blockedRegion.includes(region.toUpperCase())){
          return new Response(
            'C Access denied: It is not available in your region.',
            {status: 403,},
          );
        }
      }
      
    } 
     
    //根据IP地址
    if (ipAddress !== '') {
      if(rConfig.firewall && rConfig.firewall.blockedIPAddress.includes(ipAddress)){
        return new Response(
          'P Access denied: Your IP address is blocked',
          {status: 403,},
        );
      }      
    } 
      
    // console.log(region)    
    //手机端访问地址
    if (userAgent && isMobile(userAgent) === true) {
      upstreamURL = new URL(rConfig.basic.mobileRedirect);
    } else if (region && rConfig.routes) {
      
      if(region.toUpperCase() in rConfig.routes){
        upstreamURL = new URL(rConfig.routes[region.toUpperCase()]); 
      }    
      // return new Response( upstreamURL+' Access denied: Your IP address is blocked.', { status: 403,},);   
      // console.log(upstreamURL) 
    } else { 
      if(rConfig.basic){
        upstreamURL = new URL(rConfig.basic.upstream);      
      } 
    }
  
    // console.log(region.toUpperCase())
    // console.log(rConfig.routes)      
    // console.log(deviceStr);
    // console.log(rConfig.device);
    //特定设备指向地址
    if(rConfig.device){  
       
      if(deviceStr && deviceStr in rConfig.device){ 
        if(rConfig.device[deviceStr]){
          upstreamURL = new URL(rConfig.device[deviceStr]); 
          // console.log(upstreamURL) 
        } 
      }  
    }
   
    //特定的语言指向地址
    if(rConfig.language){   
      var sLanguage =   language.split(',')
      sLanguage.forEach(function(v,index){
            // console.log(index+': '+v)
            if(v && v in rConfig.language){ 
              if(rConfig.language[v]){
                // console.log(rConfig.language[v])
                upstreamURL = new URL(rConfig.language[v]); 
                // console.log(upstreamURL) 
              } 
            }  
        }) 
    }
   
    //特定的IP指向地址
    if(rConfig.ip){        
      if(ipAddress && ipAddress in rConfig.ip){ 
        if(rConfig.ip[ipAddress]){
          // console.log(rConfig.ip[ipAddress])
          upstreamURL = new URL(rConfig.ip[ipAddress]); 
          // console.log(upstreamURL)   
        } 
      }  
    }  
       

    //特定的UserAgent指向地址
    if(rConfig.userAgent){    
      // console.log(userAgent);      
      var userAgentData = Object.keys(rConfig.userAgent);  
      userAgentData.forEach(function(v,index){
           console.log(index+': '+v)
          if (userAgent.includes(v)) {
            console.log(userAgent.includes(v))
            console.log(rConfig.userAgent[v])
            // if(rConfig.userAgent[v]){
            //   upstreamURL = new URL(rConfig.userAgent[v]); 
            // } 
            //
          } 
        })   
    }  
    // console.log(upstreamURL) 
    // console.log(basicUrl) 
   
   
    if(upstreamURL==null){ 
      if(basicUrl){
        return await fetch(basicUrl);
      }
      // return await fetch(request.url);
      return new Response( ' Access denied: Your IP address is blocked', { status: 403,},);          
    }
    
   
  }else{
    if(basicUrl){
      return await fetch(basicUrl);
    }    
   // console.log(false);
   return new Response( 'Access denied: Your IP address is blocked', { status: 403,},);
  }
 
//假如源站url有路径就都加一起
  requestURL.protocol = upstreamURL.protocol;
  requestURL.host = upstreamURL.host;

// console.log(requestURL.pathname);
// console.log('##########################################');
// console.log(upstreamURL.protocol);
// console.log(upstreamURL.host);
// console.log(upstreamURL.pathname);
// console.log(upstreamURL.href);
// console.log('##########################################');

// console.log(requestURL.protocol);
// console.log(requestURL.host);
// console.log(requestURL.pathname);
// console.log(requestURL.href);
// console.log('##########################################');

 

 if(requestURL.pathname != '/'){
      if(requestURL.pathname.indexOf(upstreamURL.pathname)>0){
          let re = new RegExp(upstreamURL.pathname, 'g')
          requestURL.pathname = requestURL.pathname.replace(re, '');  
          requestURL.pathname = upstreamURL.pathname ;
          //+ requestURL.pathname;
          //  console.log(requestURL.href)
          //  console.log(upstreamURL.href)
      }else{
          console.log('requestURL.pathname!="/"');
          //判断是不是wp-
          if(requestURL.pathname.indexOf('wp-content')===-1 && requestURL.pathname.indexOf('wp-includes')===-1){
            requestURL.pathname = upstreamURL.pathname;// + requestURL.pathname;
          }
      }
}else{
  // console.log('requestURL.pathname="/"');
  // console.log(baseURL.host);
  requestURL.href = upstreamURL.href
   
  let response = await fetch(requestURL.href);
  let body = await response.text();
  // console.log(requestURL.host);
  let proxyUrl = new RegExp(requestURL.host, 'g');

  // 替换 body 中的字符串
  let newBody = body.replace(proxyUrl,baseURL.host);
  // console.log(newBody);
  return new Response(newBody, response);



//  requestURL.href = upstreamURL.href      
//  console.log(requestURL.pathname)
//  console.log(requestURL.href)
//  const newUrlResponse = await fetch(requestURL);
//  return new Response( newUrlResponse, { status: 403,},); 

//有请求主体的跟没有请求主体的
  let newRequest; 
  if (request.method === 'GET' || request.method === 'HEAD') {
    newRequest = new Request(requestURL, {
      cf: {
        cacheEverything: rConfig.optimization.cacheEverything,
        cacheTtl: rConfig.optimization.cacheTtl,
        mirage: rConfig.optimization.mirage,
        polish: rConfig.optimization.polish,
        minify: rConfig.optimization.minify,
        scrapeShield: true,
      },
      method: request.method,
      headers: request.headers,
    });
  } else {
    const requestBody = await request.text();
    
    newRequest = new Request(requestURL, {
      cf: {
        cacheEverything: rConfig.optimization.cacheEverything,
        cacheTtl: rConfig.optimization.cacheTtl,
        mirage: rConfig.optimization.mirage,
        polish: rConfig.optimization.polish,
        minify: rConfig.optimization.minify,
        scrapeShield:true,
      },
      method: request.method,
      headers: request.headers,
      body: requestBody,
    });
  }

  const fetchedResponse = await fetch(newRequest);
  const modifiedResponseHeaders = new Headers(fetchedResponse.headers);
  
  if (modifiedResponseHeaders.has('x-pjax-url')) {
    const pjaxURL = new URL(modifiedResponseHeaders.get('x-pjax-url'));
    pjaxURL.protocol = requestURL.protocol;
    pjaxURL.host = requestURL.host;
    pjaxURL.pathname = pjaxURL.path.replace(requestURL.pathname, '/'); 
    modifiedResponseHeaders.set(
      'x-pjax-url',
      pjaxURL.href,
    );
  }  


  const requestBodyNew = await request.text();
  console.log(requestBodyNew);
    
    // newRequest = new Request(requestURL, {
    //   cf: {
    //     cacheEverything: rConfig.optimization.cacheEverything,
    //     cacheTtl: rConfig.optimization.cacheTtl,
    //     mirage: rConfig.optimization.mirage,
    //     polish: rConfig.optimization.polish,
    //     minify: rConfig.optimization.minify,
    //     scrapeShield:true,
    //   },
    //   method: request.method,
    //   headers: request.headers,
    //   body: requestBodyNew,
    // });
    
  // let response = await fetch(newRequest)
  // return response // 返回新URL的响应
  // return new Response( requestURL.href, { status: 403,},); 
  return new Response(
    fetchedResponse.body, 
    {
      headers: modifiedResponseHeaders,
      status: fetchedResponse.status,
      statusText: fetchedResponse.statusText,        
    },
  );
}

/**
 * 获取远程JSON信息
 * @param {*} response 
 * @returns 
 */
async function gatherResponse(response) {
  const { headers } = response;
  const contentType = headers.get("content-type") || ""; 
  // console.log(contentType)
  if (contentType.includes("application/json")) {
    return await response.json();
  }
  return response.text();
}

//检查是不是手机
async function isMobile(userAgent) {
  const agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
  return agents.any((agent) => userAgent.indexOf(agent) > 0);
  //return true

 
const BlackASNlist = [
  46868,20448,30584,394143,396319,396503,397282,397685,3644,39690,14061,39690,393406,394362,62567,
  16276,200487,62468,62468,56851,62468,8075,8068,8070,792,18837,7160,14919,3457,46558,3457,4192,
  31898,63295,11479,14506,37963,37963,136907,131444,265443,206798,206204,61348,55990,55933,16509,
  14618,45090,63949,26496,54290,13335,394536,395747,132892,202623,51167,7005,30103,14061,46015,
  136170,61317,7489,30560,14327,30437,3921,1294,43515,36040,30041,3464,29771,328170,43569,45144,
  55720,55720,131316,135387,55720,45152,45352,132597,45352,49532,19437,20454,20150,7005,53824,
  32244,54290,19969,40819,6188,18229,11798,53013,58182,9439,44427,53013,54115,32934,6939,55081,
  63023,25820,25820,36114,56046,4808,17622,138421,9929,4808,15169,32934,14618,13238,16550,19527,
  22859,26910,36039,36040,36384,36385,36492,394507,394639,394699,395973,396982,20001
]
/**
 * 主执行
 */
// eslint-disable-next-line no-restricted-globals
addEventListener('fetch', (event) => {
  event.respondWith(fetchAndApply(event.request));
});

发表评论

Copyright © 2016 DEWEBSTUDIO