CLOUD FLARE SERCURITY

export default {
  async fetch(request, env) {
   // return fetch("https://backend-api.hideproxy.io/api/v1/proxy/listCountry?domain=server1&provider=YUi9W%2B2bLuJaQkDlbmmt3I67z9KdrJxFtXjldEvWCweXiA%3D%3D&X-Signature&X-Timestamp")
    const url = new URL(request.url);

    // ===== Verify Signature =====

    const signature = request.headers.get("X-Signature");
    const timestamp = request.headers.get("X-Timestamp");
    const clientkey = request.headers.get("X-Client-Key");

    if (!signature || !timestamp) {
      return Response.json({
        success: false,
        message: "Missing Signature"
      }, { status: 401 });
    }

    // quá 5 phút
    if (Math.abs(Date.now() - Number(timestamp)) > 300000) {
      return Response.json({
        success: false,
        message: "Expired"
      }, { status: 401 });
    }

    // đọc body
    const body = await request.text();

    // hash body
    // const bodyHash = await sha256(body);

    const message =
      request.method + "\n" +
      url.pathname + "\n" +
      timestamp + "\n" +
      clientkey;

    const expected = await hmac(message, env.API_SECRET);

    // return Response.json({
    //   'env.API_SECRET': env.API_SECRET,
    //   'expected': expected
    // });

    if (!safeEqual(signature, expected)) {
      return Response.json({
        success: false,
        message: "Invalid Signature"
      }, { status: 401 });
    }

    // ===== Forward =====

    const headers = new Headers(request.headers);

    headers.set(
      "X-Internal-Key",
      env.INTERNAL_KEY
    );

    headers.delete("host");
    let init = {
      method: request.method,
      headers: headers
    };

    if (request.method !== "GET" && request.method !== "HEAD") {
      init.body = body;
    }
    let request_url = "https://backend-api.hideproxy.io" +url.pathname +url.search
    //  return Response.json({
    //     success: false,
    //     message: init
    //   }, { status: 200 });
    return fetch(request_url, init);

  }
}


//==============================

async function sha256(text) {

  const encoder = new TextEncoder();

  const hash = await crypto.subtle.digest(
    "SHA-256",
    encoder.encode(text)
  );

  return [...new Uint8Array(hash)]
    .map(x => x.toString(16).padStart(2, "0"))
    .join("");

}

async function hmac(message, secret) {

  const encoder = new TextEncoder();

  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(secret),
    {
      name: "HMAC",
      hash: "SHA-256"
    },
    false,
    ["sign"]
  );

  const sig = await crypto.subtle.sign(
    "HMAC",
    key,
    encoder.encode(message)
  );

  return [...new Uint8Array(sig)]
    .map(x => x.toString(16).padStart(2, "0"))
    .join("");

}

function safeEqual(a, b) {

  if (a.length !== b.length)
    return false;

  let result = 0;

  for (let i = 0; i < a.length; i++) {
    result |= a.charCodeAt(i) ^ b.charCodeAt(i);
  }

  return result === 0;

}

Nhận xét

Bài đăng phổ biến từ blog này

Các cách fix mongodb khi bị lỗi

Dạo này bận chạy deadline quá nên post link trễ