// To use this code example you need an API key from Virus Total.
// See https://www.virustotal.com/gui/my-apikey
const VT_API_KEY = "";
const BACKEND_PRIMARY = "origin_0";
const BACKEND_VT = "origin_1";
const BACKEND_VT_MOCK = "origin_2";
const MOCK_RESPONSE = '{"data":{"attributes":{"reputation":100, "last_analysis_stats": { "malicious": 50 }}}}';

// !! When using credentials in Fiddle code please be aware that
// !! all fiddles are publicly accessible

async function handleRequest(event) {
  const req = event.request;
  const reqBody = await req.arrayBuffer();
    
  let url = new URL(req.url);

  // If the path is /upload and the Method POST, sha-256 hash the file and test with VT
  if (url.pathname == "/upload" && ["POST", "PUT"].includes(req.method)) {
    const reqmethod = req.method;
    const reqheaders = await req.headers;
    const sha256_hash = await hash(reqBody);
    
    console.log("SHA-256: " + sha256_hash);

    const vtUrl = VT_API_KEY ? "https://www.virustotal.com/api/v3/files/" + sha256_hash : "https://http-me.glitch.me/?header=content-type:application/json&base64=" + btoa(MOCK_RESPONSE);
    console.log(vtUrl);
    const response = await fetch(vtUrl, {
        backend: VT_API_KEY ? BACKEND_VT : BACKEND_VT_MOCK,
        cacheOverride: new CacheOverride("pass"),
        headers: new Headers({ "x-apikey": VT_API_KEY }),
      }
    );
    if (!response.ok) {
      req.headers.set('Virus-Scan-Result', `Invalid response from VT API: ${response.status}`);
    } else {
      const myJson = await response.json(); //extract JSON from the http response
      let reputation = await myJson.data.attributes.reputation;
      let malicious = await myJson.data.attributes.last_analysis_stats.malicious;
      req.headers.set('Virus-Scan-Result', `reputation=${reputation}; malicious=${malicious}`);
    }
  }
  
  // Forward the original request to origin
  return fetch(req, {
    backend: BACKEND_PRIMARY,
    body: reqBody
  });
}

function hash(arrayBuff) {
  return crypto.subtle.digest("SHA-256", arrayBuff).then((hashBuffer) => {
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray
      .map((bytes) => bytes.toString(16).padStart(2, "0"))
      .join("");
    return hashHex;
  });
}

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