File Explorer

/var/runtime/node_modules/@aws-sdk/cloudfront-signer/dist-cjs

This explorer reads the filesystem of the server it runs on, so /workspace/user isn't present here. Browsing and the terminal still work against this server's own disk from /.

0 dirs
1 file
index.js8.8 KB · 309 lines
"use strict";var __defProp = Object.defineProperty;var __getOwnPropDesc = Object.getOwnPropertyDescriptor;var __getOwnPropNames = Object.getOwnPropertyNames;var __hasOwnProp = Object.prototype.hasOwnProperty;var __name = (target, value) => __defProp(target, "name", { value, configurable: true });var __export = (target, all) => {  for (var name in all)    __defProp(target, name, { get: all[name], enumerable: true });};var __copyProps = (to, from, except, desc) => {  if (from && typeof from === "object" || typeof from === "function") {    for (let key of __getOwnPropNames(from))      if (!__hasOwnProp.call(to, key) && key !== except)        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });  }  return to;};var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.tsvar index_exports = {};__export(index_exports, {  getSignedCookies: () => getSignedCookies,  getSignedUrl: () => getSignedUrl});module.exports = __toCommonJS(index_exports); // src/sign.tsvar import_crypto = require("crypto");function getSignedUrl({  dateLessThan,  dateGreaterThan,  url,  keyPairId,  privateKey,  ipAddress,  policy,  passphrase}) {  const cloudfrontSignBuilder = new CloudfrontSignBuilder({    keyPairId,    privateKey,    passphrase  });  if (!url && !policy) {    throw new Error("@aws-sdk/cloudfront-signer: Please provide 'url' or 'policy'.");  }  if (policy) {    cloudfrontSignBuilder.setCustomPolicy(policy);  } else {    cloudfrontSignBuilder.setPolicyParameters({      url,      dateLessThan,      dateGreaterThan,      ipAddress    });  }  let baseUrl;  if (url) {    baseUrl = url;  } else if (policy) {    const resources = getPolicyResources(policy);    if (!resources[0]) {      throw new Error(        "@aws-sdk/cloudfront-signer: No URL provided and unable to determine URL from first policy statement resource."      );    }    baseUrl = resources[0].replace("*://", "https://");  }  const startFlag = baseUrl.includes("?") ? "&" : "?";  const params = Object.entries(cloudfrontSignBuilder.createCloudfrontAttribute()).filter(([, value]) => value !== void 0).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");  const urlString = baseUrl + startFlag + params;  return getResource(urlString);}__name(getSignedUrl, "getSignedUrl");function getSignedCookies({  ipAddress,  url,  privateKey,  keyPairId,  dateLessThan,  dateGreaterThan,  policy,  passphrase}) {  const cloudfrontSignBuilder = new CloudfrontSignBuilder({    keyPairId,    privateKey,    passphrase  });  if (policy) {    cloudfrontSignBuilder.setCustomPolicy(policy);  } else {    cloudfrontSignBuilder.setPolicyParameters({      url,      dateLessThan,      dateGreaterThan,      ipAddress    });  }  const cloudfrontCookieAttributes = cloudfrontSignBuilder.createCloudfrontAttribute();  const cookies = {    "CloudFront-Key-Pair-Id": cloudfrontCookieAttributes["Key-Pair-Id"],    "CloudFront-Signature": cloudfrontCookieAttributes["Signature"]  };  if (cloudfrontCookieAttributes["Expires"]) {    cookies["CloudFront-Expires"] = cloudfrontCookieAttributes["Expires"];  }  if (cloudfrontCookieAttributes["Policy"]) {    cookies["CloudFront-Policy"] = cloudfrontCookieAttributes["Policy"];  }  return cookies;}__name(getSignedCookies, "getSignedCookies");function getPolicyResources(policy) {  const parsedPolicy = typeof policy === "string" ? JSON.parse(policy) : policy;  return (parsedPolicy?.Statement ?? []).map((s) => s.Resource);}__name(getPolicyResources, "getPolicyResources");function getResource(urlString) {  const protocol = urlString.slice(0, urlString.indexOf("//"));  switch (protocol) {    case "http:":    case "https:":    case "ws:":    case "wss:":      return urlString;    case "rtmp:":      const url = new URL(urlString);      const origin = `${protocol}//${url.hostname}`;      return urlString.substring(origin.length).replace(/(?::\d+)?\//, "");    default:      throw new Error("Invalid URI scheme. Scheme must be one of http, https, or rtmp");  }}__name(getResource, "getResource");var CloudfrontSignBuilder = class {  static {    __name(this, "CloudfrontSignBuilder");  }  keyPairId;  privateKey;  passphrase;  policy;  customPolicy = false;  dateLessThan;  constructor({ privateKey, keyPairId, passphrase }) {    this.keyPairId = keyPairId;    this.privateKey = privateKey;    this.policy = "";    this.passphrase = passphrase;  }  buildPolicy(args) {    const policy = {      Statement: [        {          Resource: args.resource,          Condition: {            DateLessThan: {              "AWS:EpochTime": args.dateLessThan            }          }        }      ]    };    if (args.dateGreaterThan) {      policy.Statement[0].Condition["DateGreaterThan"] = {        "AWS:EpochTime": args.dateGreaterThan      };    }    if (args.ipAddress) {      const cidr = this.parseCIDR(args.ipAddress);      policy.Statement[0].Condition["IpAddress"] = {        "AWS:SourceIp": cidr      };    }    return policy;  }  normalizeBase64(str) {    const replacements = {      "+": "-",      "=": "_",      "/": "~"    };    return str.replace(/[+=/]/g, function(match) {      return replacements[match];    });  }  encodeToBase64(str) {    return this.normalizeBase64(Buffer.from(str).toString("base64"));  }  validateIP(ipStr) {    const octets = ipStr.split(".");    if (octets.length !== 4) {      throw new Error(`IP does not contain four octets.`);    }    const isValid = octets.every((octet) => {      const num = Number(octet);      return Number.isInteger(num) && num >= 0 && num <= 255;    });    if (!isValid) {      throw new Error("invalid IP octets");    }  }  validateMask(maskStr) {    const mask = Number(maskStr);    const isValid = Number.isInteger(mask) && mask >= 0 && mask <= 32;    if (!isValid) {      throw new Error("invalid mask");    }  }  parseCIDR(cidrStr) {    try {      const cidrParts = cidrStr.split("/");      if (cidrParts.some((part) => part.length === 0)) {        throw new Error("missing ip or mask part of CIDR");      }      this.validateIP(cidrParts[0]);      let mask = "32";      if (cidrParts.length === 2) {        this.validateMask(cidrParts[1]);        mask = cidrParts[1];      }      return `${cidrParts[0]}/${mask}`;    } catch (error) {      const errMessage = `IP address "${cidrStr}" is invalid`;      if (error instanceof Error) {        throw new Error(`${errMessage} due to ${error.message}.`);      } else {        throw new Error(`${errMessage}.`);      }    }  }  epochTime(date) {    return Math.round(date.getTime() / 1e3);  }  parseDate(date) {    if (!date) {      return void 0;    }    const parsedDate = new Date(date);    return isNaN(parsedDate.getTime()) ? void 0 : this.epochTime(parsedDate);  }  parseDateWindow(expiration, start) {    const dateLessThan = this.parseDate(expiration);    if (!dateLessThan) {      throw new Error("dateLessThan is invalid. Ensure the date value is compatible with the Date constructor.");    }    return {      dateLessThan,      dateGreaterThan: this.parseDate(start)    };  }  signData(data, privateKey, passphrase) {    const sign = (0, import_crypto.createSign)("RSA-SHA1");    sign.update(data);    return sign.sign({ key: privateKey, passphrase }, "base64");  }  signPolicy(policy, privateKey, passphrase) {    return this.normalizeBase64(this.signData(policy, privateKey, passphrase));  }  setCustomPolicy(policy) {    this.customPolicy = true;    this.policy = policy;  }  setPolicyParameters({    url,    dateLessThan,    dateGreaterThan,    ipAddress  }) {    if (!url || !dateLessThan) {      return false;    }    const resource = getResource(url);    const parsedDates = this.parseDateWindow(dateLessThan, dateGreaterThan);    this.dateLessThan = parsedDates.dateLessThan;    this.customPolicy = Boolean(parsedDates.dateGreaterThan) || Boolean(ipAddress);    this.policy = JSON.stringify(      this.buildPolicy({        resource,        ipAddress,        dateLessThan: parsedDates.dateLessThan,        dateGreaterThan: parsedDates.dateGreaterThan      })    );  }  createCloudfrontAttribute() {    if (!Boolean(this.policy)) {      throw new Error("Invalid policy");    }    const signature = this.signPolicy(this.policy, this.privateKey, this.passphrase);    return {      Expires: this.customPolicy ? void 0 : this.dateLessThan,      Policy: this.customPolicy ? this.encodeToBase64(this.policy) : void 0,      "Key-Pair-Id": this.keyPairId,      Signature: signature    };  }};// Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = {  getSignedUrl,  getSignedCookies});