Cloudflare Worker 代理 腾讯云对象存储

目前Worker的.dev域名基本残废,需要一个自己的域名.

这篇博客的目的是利用Worker充当对象存储的网关,主要适合以下条件:

1.没有域名备案,对象存储无法绑定未备案域名

2.希望保护源站,避免被打

创建Worker后填入以下代码:

export default {
  async fetch(request, env) {
    return await handleRequest(request)
  }
}

const status_access_denied = "Access Denied"
const status_internal_error = "Internal Error"


//这里需要填入自己的ID,KEY,源站地址
const tencent_secret_id = "************"
const tencent_secret_key = "***********"
const tencent_cos_index = "https://******.cos.ap-chengdu.myqcloud.com"

async function handleRequest(request) {
  const {searchParams, pathname} = new URL(request.url)

  if(pathname == "/"){
    return new Response(`{\"message\":\"${status_access_denied}\", \"status\":\"500\"}`, { status: 500 });
  }

  const KeyTime = await key_time(300)
  const SignKey = await hmac_sha1(tencent_secret_key, KeyTime)
  const HttpString = await http_string("get", pathname, "", "")
  const StringToSign = "sha1" + "\n" + KeyTime + "\n" + await sha1(HttpString)  + "\n"
  const Signature = await hmac_sha1(SignKey, StringToSign)

  const SignedURL = await signed_url(tencent_cos_index + pathname, tencent_secret_id, KeyTime, "", "", Signature)

  try {
    // 发送网络请求并获取响应
    const response = await fetch(SignedURL);

    // 过滤和处理返回的信息
    if (response.ok) {
      // 响应成功
      return new Response(await response.body)
    } else {
      // 响应失败
      throw new Error(`{\"message":\"${stat}\", "status":"${response.status}"}`);
    }
  } catch (error) {
    // 处理错误
    return new Response(error.message, { status: 500 });
  }
}

async function key_time(TimeDelay){
  let current_time = Math.floor(Date.now() / 1000);
  let expire_time = current_time + TimeDelay

  return current_time + ";" + expire_time
}

async function hmac_sha1(SecretKey, KeyTime){
  // 定义要进行 HMAC-SHA1 计算的数据和密钥
  const data = KeyTime;
  const key = SecretKey;

  // 将密钥转换为 Uint8Array 格式
  const keyData = new TextEncoder().encode(key);

  // 导入 SubtleCrypto API
  const crypto = self.crypto.subtle;

  // 定义要使用的算法和密钥
  const algorithm = { name: 'HMAC', hash: 'SHA-1' };
  const cryptoKey = await crypto.importKey('raw', keyData, algorithm, false, ['sign']);

  // 计算 HMAC-SHA1 的结果
  const signatureBuffer = await crypto.sign(algorithm, cryptoKey, new TextEncoder().encode(data));

  // 将结果转换为十六进制字符串
  const signature = Array.from(new Uint8Array(signatureBuffer)).map(byte => byte.toString(16).padStart(2, '0')).join('');

  return signature
}

async function http_string(Method, URI, Parameters, Headers){
  return Method + "\n" + URI + "\n" + Parameters + "\n" + Headers + "\n"
}

async function sha1(HttpString){
  const dataBuffer = new TextEncoder().encode(HttpString);
  
  // 导入 SubtleCrypto API
  const crypto = self.crypto.subtle;

  // 定义要使用的算法
  const algorithm = { name: 'SHA-1' };

  // 计算 SHA-1 哈希值
  return crypto.digest(algorithm, dataBuffer)
    .then(hashBuffer => {
      // 将哈希值转换为十六进制字符串
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');

      // 返回哈希值
      return hashHex;
    })
    .catch(error => {
      // 处理错误
      console.error(error);
      return "Failed"
    });
}

async function signed_url(URL, SecretId, KeyTime, HeaderList, UrlParamList, Signature){
  return URL 
    + "?"
    + "q-sign-algorithm=" + "sha1" 
    + "&q-ak=" + SecretId
    + "&q-sign-time=" + KeyTime
    + "&q-key-time=" + KeyTime
    + "&q-header-list=" + HeaderList
    + "&q-url-param-list=" + UrlParamList
    + "&q-signature=" + Signature
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值