modern-aws-tools
Version:
modern aws tools
215 lines (206 loc) • 7.61 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => main_default,
s3Upload: () => s3Upload
});
module.exports = __toCommonJS(main_exports);
// src/shared/base64.ts
var utoa = (str) => {
return btoa(decodeURIComponent(encodeURIComponent(str)));
};
// src/shared/getDate.ts
var getDate = () => {
const date = /* @__PURE__ */ new Date();
const nowYear = date.getUTCFullYear().toString();
let nowMonth = (date.getUTCMonth() + 1).toString();
let nowDate = date.getUTCDate().toString();
if (+nowMonth >= 1 && +nowMonth <= 9) {
nowMonth = "0" + nowMonth;
}
if (+nowDate >= 0 && +nowDate <= 9) {
nowDate = "0" + nowDate;
}
return nowYear + nowMonth + nowDate;
};
var getDate_default = getDate;
// src/shared/getExactDate.ts
var getExactDate = () => {
const date = /* @__PURE__ */ new Date();
date.setTime(date.getTime() + 1 * 60 * 60 * 1e3);
const nowYear = date.getFullYear();
let nowMonth = (date.getMonth() + 1).toString();
let nowDate = date.getDate().toString();
let hour = date.getHours().toString();
let minu = date.getMinutes().toString();
let sec = date.getSeconds().toString();
if (+hour < 10)
hour = "0" + hour;
if (+minu < 10)
minu = "0" + minu;
if (+sec < 10)
sec = "0" + sec;
if (+nowMonth >= 1 && +nowMonth <= 9) {
nowMonth = "0" + nowMonth;
}
if (+nowDate >= 0 && +nowDate <= 9) {
nowDate = "0" + nowDate;
}
return nowYear + "-" + nowMonth + "-" + nowDate + "T" + hour + ":" + minu + ":" + sec + "Z";
};
var getExactDate_default = getExactDate;
// src/shared/sign.ts
var import_crypto_js = __toESM(require("crypto-js"));
var sign = (key, region, service, msg) => {
const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10).replace(/-/g, "");
const kDate = import_crypto_js.default.HmacSHA256(date, "AWS4" + key);
const kRegion = import_crypto_js.default.HmacSHA256(region, kDate);
const kService = import_crypto_js.default.HmacSHA256(service, kRegion);
const kSigning = import_crypto_js.default.HmacSHA256("aws4_request", kService);
return import_crypto_js.default.HmacSHA256(msg, kSigning);
};
var sign_default = sign;
// src/shared/uuid.ts
var UUID = (len, radix) => {
const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
const uuid = [];
let i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++)
uuid[i] = chars[0 | Math.random() * radix];
} else {
let r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
uuid[14] = "4";
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[i === 19 ? r & 3 | 8 : r];
}
}
}
return uuid.join("");
};
// src/s3/upload.ts
var s3Upload = async (req) => {
try {
return new Promise((resolve, reject) => {
const finalKey = `${req.prefix ? req.prefix + "/" : ""}${UUID().toString()}.${(/* @__PURE__ */ new Date()).getTime()}.${req.key.split(".")[req.key.split(".").length > 1 ? req.key.split(".").length - 1 : 0]}`;
const form = s3_upload_form(req, req.finalKey || finalKey);
const data = new FormData();
data.append("acl", form["acl"]);
data.append("key", form["key"]);
data.append("Content-Type", req.file.type);
data.append("policy", form["policy"]);
data.append("success_action_status", form["success_action_status"]);
data.append("x-amz-algorithm", form["x-amz-algorithm"]);
data.append("x-amz-credential", form["x-amz-credential"]);
data.append("x-amz-date", form["x-amz-date"]);
data.append("x-amz-signature", form["x-amz-signature"]);
data.append("x-amz-meta-tag", form["x-amz-meta-tag"]);
data.append("x-amz-meta-uuid", form["x-amz-meta-uuid"]);
data.append(
"x-amz-server-side-encryption",
form["x-amz-server-side-encryption"]
);
data.append("x-amz-security-token", form["x-amz-security-token"]);
data.append("file", req.file);
fetch(form.action, {
body: data,
method: "POST"
}).then((e) => {
console.log(e);
resolve({
msg: e,
host: req.host,
key: req.finalKey || finalKey
});
}).catch((err) => reject(err));
});
} catch (error) {
console.log(error);
}
};
var s3_upload_form = (req, finalKey) => {
const form = {
acl: "public-read",
success_action_status: "201",
"x-amz-algorithm": "AWS4-HMAC-SHA256",
"x-amz-credential": req.credential.accessKeyId + "/" + getDate_default() + "/" + req.region + "/s3/aws4_request",
"x-amz-date": getDate_default() + "T000000Z",
"x-amz-meta-tag": "",
"x-amz-meta-uuid": 14365123651274,
"x-amz-server-side-encryption": "AES256",
"x-amz-security-token": req.credential.sessionToken
};
const policy = {
conditions: [
{ bucket: req.bucket },
{ acl: "public-read" },
["content-length-range", 32, 5368709120],
{ success_action_status: form["success_action_status"] },
{ "x-amz-algorithm": form["x-amz-algorithm"] },
{ "x-amz-credential": form["x-amz-credential"] },
{ "x-amz-date": form["x-amz-date"] },
{ "x-amz-meta-uuid": "14365123651274" },
{ "x-amz-server-side-encryption": "AES256" },
{
"x-amz-security-token": form["x-amz-security-token"]
},
["starts-with", "$Content-Type", ""],
["starts-with", "$x-amz-meta-tag", ""],
["starts-with", "$key", `${req.prefix ? req.prefix + "/" : ""}`]
],
expiration: req.credential.expiration ? req.credential.expiration : getExactDate_default()
};
form["action"] = "https://" + req.bucket + ".s3." + req.region + ".amazonaws.com/";
form["key"] = finalKey;
policy["conditions"].push({ key: finalKey });
form["policy"] = utoa(JSON.stringify(policy));
console.log(form["policy"]);
form["x-amz-signature"] = sign_default(
req.credential.secretAccessKey,
req.region,
"s3",
form["policy"]
);
return form;
};
// src/main.ts
var modernAWSTools = {
s3Upload
};
var main_default = modernAWSTools;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
s3Upload
});