[TOC]

一、Cloudflare Workers 代理

1、功能

直链下载加速。
如:GitHub repo 克隆、GitHub release 下载、wget 下载。
如:Hugging Face 模型下载、OpenAI API 访问。
反盗链绕过。
如:绕过 Pixiv 图片直链反盗链。
开启跨域。
如:绕过他人提供的 API 的跨域限制。

2、代码

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})
const specialCases = {
  "*": {
    "Origin": "DELETE",
    "Referer": "DELETE"
  }
}
function handleSpecialCases(request) {
  const url = new URL(request.url);
  const rules = specialCases[url.hostname] || specialCases["*"];
  for (const [key, value] of Object.entries(rules)) {
    switch (value) {
      case "KEEP":
        break;
      case "DELETE":
        request.headers.delete(key);
        break;
      default:
        request.headers.set(key, value);
        break;
    }
  }
}
async function handleRequest(request) {
  const url = new URL(request.url);
  if (url.pathname === "/") {
    return new Response("Please enter the link after the /")
  };
  const actualUrlStr = url.pathname.replace("/", "") + url.search + url.hash;
  const actualUrl = new URL(actualUrlStr);
  const modifiedRequest = new Request(actualUrl, {
    headers: request.headers,
    method: request.method,
    body: request.body,
    redirect: 'follow'
  });
  handleSpecialCases(modifiedRequest);
  const response = await fetch(modifiedRequest);
  const modifiedResponse = new Response(response.body, response);
  modifiedResponse.headers.set('Access-Control-Allow-Origin', '*');
  return modifiedResponse;
} 
代码来源:https://www.bilibili.com/read/cv34109631/

3、用法

原始链接:https://www.example.com/example.zip
反代链接:https://绑定的Worker域名/https://www.example.com/example.zip

4、反盗链特判

specialCases 处理一些网站的反盗链规则。规则的配置格式如下所示:

<域名>: {
"Origin": <Origin规则>,
"Referer": <Referer规则>
}

其中,Origin 规则和 Referer 规则的取值可以为:
DELETE: 删除该请求头
KEEP: 保持请求头不变
自定义: 将请求头更改为指定的值
例如 Pixiv 的图片直链 CDN 限制了 Referer 来源是:https://www.pixiv.net/ 那么可以配置以下规则:

const specialCases = {
  "i.pximg.net": {
    "Origin": "DELETE",
    "Referer": "https://www.pixiv.net/"
  },
  "i-cf.pximg.net": {
    "Origin": "DELETE",
    "Referer": "https://www.pixiv.net/"
  },
  "*": {
    "Origin": "DELETE",
    "Referer": "DELETE"
  }
}

需要注意的是,* 规则代表未匹配的其他所有站点,建议保持不变。

5、问题

二级页面会跳出代理

6、页面加密

/**
 * @param {string} USERNAME User name to access the page
 * @param {string} PASSWORD Password to access the page
 * @param {string} REALM A name of an area (a page or a group of pages) to protect.
 * Some browsers may show "Enter user name and password to access REALM"
 */
const USERNAME = 'demouser'
const PASSWORD = 'demopassword'
const REALM = 'Secure Area'

addEventListener('fetch', (event) => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const authorization = request.headers.get('authorization')
  if (!request.headers.has('authorization')) {
    return getUnauthorizedResponse(
      'Provide User Name and Password to access this page.',
    )
  }
  const credentials = parseCredentials(authorization)
  if (credentials[0] !== USERNAME || credentials[1] !== PASSWORD) {
    return getUnauthorizedResponse(
      'The User Name and Password combination you have entered is invalid.',
    )
  }
  return await fetch(request)
}

/**
 * Break down base64 encoded authorization string into plain-text username and password
 * @param {string} authorization
 * @returns {string[]}
 */
function parseCredentials(authorization) {- [一、Cloudflare Workers 代理](#一cloudflare-workers-代理)
  - [1、功能](#1功能)
  - [2、代码](#2代码)
  - [3、用法](#3用法)
  - [4、反盗链特判](#4反盗链特判)
  - [5、问题](#5问题)
  - [6、页面加密](#6页面加密)

  const parts = authorization.split(' ')
  const plainAuth = atob(parts[1])
  const credentials = plainAuth.split(':')
  return credentials
}

/**
 * Helper funtion to generate Response object
 * @param {string} message
 * @returns {Response}
 */
function getUnauthorizedResponse(message) {
  let response = new Response(message, {
    status: 401,
  })
  response.headers.set('WWW-Authenticate', `Basic realm="${REALM}"`)
  return response
}
代码来源:https://www.maxivanov.io/how-to-password-protect-your-website-with-cloudflare-workers/