import { Router } from "@fastly/expressly";
import {HmacSHA1} from "crypto-js";
import {Base64} from 'crypto-js/enc-base64';

const router = new Router();
const secret = "iqFPeN2uZ0Lm5IrsKaOFKR";

router.get("(.*)", async (req, res) => {
  let token;
  if(req.headers.has("Cookie")&&(req.headers("Cookie").startWith("token="))){
      token = req.headers("Cookie").substring(5);  
  }
  if(req.query.has("token")){
      token = req.query.get("token");
  }

  if(token!=""){
      let expiryTime;
      let suppliedSig;
      let expectedSig;

      // Extract expire time and signature from token
      const regex = /^(\d+)_(\w+)$/;
      const match = token.match(regex);

      /// Verify the token of request object
      if (match) {
          const expiryTime = match[1];
          const suppliedSig = match[2];
       
          var CryptoJS = require("crypto-js");
          const hmac = HmacSHA1(
                `${req.path}${expiryTime}${req.headers.get("User-Agent")}`,
                secret
            );
          expectedSig = btoa("0x"+ hmac.toString());

          if(suppliedSig == expectedSig){
            let currentTime = new Date().getTime() / 1000;
            if (currentTime > expiryTime) {
                console.log("Token has expired");
                res.sendStatus(410);
            }else{
                console.log("Token is good");
                res.send(await fetch(
                  req, { backend: "origin_0" }
                  ));
            }
          }
         
      }else{
          console.log("Invalid token format");
          res.sendStatus(403);
      }
  }else{
      console.log("Missing 'token' query param or cookie");
      res.sendStatus(403);
  }
});

router.listen();