Cloudflare边缘计算(2)

错误更正

上次说到CF的worker可以做很多事,比如从第三方服务拿数据,再把数据写到Response中,我用了“重定向”这个词,其实不是很精确。

因为真正的重定向是这么写的:

const { pathname, search } = new URL(event.request.url)
const destinationURL = $HTTP_HOST + pathname + search
console.log('destinationURL:', destinationURL)
res = Response.redirect(destinationURL, 301)

Https协议的重改写

而上次用的其实是Fetch模式,那借用这个模式,还可以做一些其他的事情。比如我们都知道自Chrome 81版本以来,会强制将浏览器中的Http协议的媒体资源改写为https协议,如果你的云存储用Https安全链接比较贵,那么这时,边缘计算网络就可以帮到你了:

let response = await fetch(host + pathname + search)
const headers = { "cache-control": "public, max-age=14400" }
response = new Response(response.body, { ...response, headers }

它可以拦截Https请求,在返回http资源给网页,而这一切,Chrome浏览器将无从得知。

安全疑虑

当初Chrome团队决定将Http协议改写为Https协议时,是为了提高端对端的安全性。他们的解释是,Http协议的图片很容易通过攻击而被改写。比如你连上一个钓鱼用的WI-FI网络,攻击人可以通过请求拦截的形式修改任何的明文内容,而升级到Https则可避免这一点。

那在CloudFlare的边缘计算网络中将Https请求改写为Http时,会有安全问题吗?

我个人认为是比较安全的

浏览器 ––HTTPS–– 边缘计算网络 ––HTTP–– 原始目标

从连接模型上来看,浏览器到边缘网络是安全的Https协议,被攻击的可能性不大。从边缘网络到原始目标请求使用Http协议,这意味着安全工作交给了CloudFlare,如果CloudFlare所在的机房被攻击了,那么此方式才存在被人攻击的可能。

所以,对于数据安全很重要的网站而言,不应该使用此方式。而对媒体数据没那么敏感的网站(如本站)而言,也没有太大的安全威胁。

不过请注意,使用此方式将HTTPS协议重写,将大幅度降低国内访问这些资源的速度。

边缘缓存

我们不希望访问一些重复的资源时,边缘服务器反复发起请求到原始目标。将上面的代码改写为:

const host = "https://cdn.evink.cn"


async function handleRequest(event: FetchEvent) {
  const req = event.request

  const { pathname, search } = new URL(req.url)
  const cache = caches.default
  let response = await cache.match(req)

  try {
    if (!response) {
      response = await fetch(host + pathname + search)
      const headers = { "cache-control": "public, max-age=14400" }
      response = new Response(response.body, { ...response, headers })
      event.waitUntil(cache.put(event.request, response.clone()))
    }
    return response
  } catch (e) {
    return new Response(`error code:${e}`)
  }
}


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