UNPKG

@devino.solutions/upup

Version:
3 lines (2 loc) 7.29 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@aws-sdk/client-s3"),t=require("@aws-sdk/s3-request-presigner"),n=require("crypto"),r=require("@azure/identity"),o=require("@azure/storage-blob");let s;const i=new Uint8Array(16);function a(){if(!s&&(s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!s))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return s(i)}const c=[];for(let e=0;e<256;++e)c.push((e+256).toString(16).slice(1));var p,d,u,l={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function R(e,t,n){if(l.randomUUID&&!t&&!e)return l.randomUUID();const r=(e=e||{}).random||(e.rng||a)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(let e=0;e<16;++e)t[n+e]=r[e];return t}return function(e,t=0){return c[e[t+0]]+c[e[t+1]]+c[e[t+2]]+c[e[t+3]]+"-"+c[e[t+4]]+c[e[t+5]]+"-"+c[e[t+6]]+c[e[t+7]]+"-"+c[e[t+8]]+c[e[t+9]]+"-"+c[e[t+10]]+c[e[t+11]]+c[e[t+12]]+c[e[t+13]]+c[e[t+14]]+c[e[t+15]]}(r)}!function(e){e.INTERNAL="INTERNAL",e.GOOGLE_DRIVE="GOOGLE_DRIVE",e.ONE_DRIVE="ONE_DRIVE",e.LINK="LINK",e.CAMERA="CAMERA"}(p||(p={})),exports.UpupProvider=void 0,(d=exports.UpupProvider||(exports.UpupProvider={})).AWS="aws",d.Azure="azure",d.BackBlaze="backblaze",d.DigitalOcean="digitalocean",function(e){e.PERMISSION_ERROR="PERMISSION_ERROR",e.EXPIRED_URL="EXPIRED_URL",e.FILE_VALIDATION_ERROR="FILE_VALIDATION_ERROR",e.PRESIGNED_URL_ERROR="PRESIGNED_URL_ERROR",e.SIGNED_URL_ERROR="SIGNED_URL_ERROR",e.CORS_CONFIG_ERROR="CORS_CONFIG_ERROR",e.TEMPORARY_CREDENTIALS_ERROR="TEMPORARY_CREDENTIALS_ERROR",e.UNKNOWN_UPLOAD_ERROR="UNKNOWN_UPLOAD_ERROR"}(u||(u={}));class E extends Error{constructor(e,t,n,r){void 0===t&&(t=u.UNKNOWN_UPLOAD_ERROR),void 0===n&&(n=!1),super(e),this.type=t,this.retryable=n,this.status=r,this.DEFAULT_ERROR_STATUS_CODE=500,this.name="UploadError",this.status=r||this.DEFAULT_ERROR_STATUS_CODE}}const O=10485760;function w(e){const t=["name","type","size"].filter(t=>!e[t]);if(t.length>0)throw new E("Missing required file param: "+t.join(", "),u.FILE_VALIDATION_ERROR,!1,400);const{type:n,accept:r="*",size:o,maxFileSize:s=O}=e;if(!function(e,t){const n=t.type;if(!e||!n)return!1;const[r,o]=n.split("/");if(!r||!o)return!1;const s=e.split(",").map(e=>e.trim());return s.includes("*")||s.some(e=>{if(e.includes("/*")){const[t]=e.split("/");return n.startsWith(t)}return e.toLowerCase()===n.toLowerCase()})||!1}(r,e))throw new E(`File type ${n} not allowed. Accepted types: ${r}`,u.FILE_VALIDATION_ERROR,!1,400);if(o>s)throw new E(`File size: ${o} exceeds maximum limit of ${s/1048576}MB`,u.FILE_VALIDATION_ERROR,!1,413)}async function g(n,r,o,s){void 0===s&&(s=259200);try{const i=new e.S3Client(n);return await t.getSignedUrl(i,new e.GetObjectCommand({Bucket:o,Key:r}),{expiresIn:s})}catch(e){throw new E(e.message,u.SIGNED_URL_ERROR,!1)}}function A(e,t){return n.createHmac("sha256",e).update(t).digest()}function m(e){return n.createHash("sha256").update(e).digest("hex")}const U=3600;exports.azureGenerateSasUrl=async function(e){let{fileParams:t,containerName:n,credentials:s,expiresIn:i=3600}=e;try{w(t);const e=new r.ClientSecretCredential(s.tenantId,s.clientId,s.clientSecret),a=new o.BlobServiceClient(`https://${s.storageAccount}.blob.core.windows.net`,e),c=await async function(e,t){void 0===t&&(t=3600);try{const n=new Date,r=new Date(n);return r.setMinutes(n.getMinutes()+t/60),await e.getUserDelegationKey(n,r)}catch(e){throw new E(e.message,u.TEMPORARY_CREDENTIALS_ERROR,!1,500)}}(a),{name:p,type:d}=t,l=`${R()}-${p}`,O=a.getContainerClient(n).getBlobClient(l),g=o.generateBlobSASQueryParameters({containerName:n,blobName:l,permissions:o.BlobSASPermissions.parse("racw"),startsOn:new Date,expiresOn:new Date(Date.now()+1e3*i),protocol:o.SASProtocol.Https,contentType:d},c,s.storageAccount).toString();return{key:l,publicUrl:O.url,uploadUrl:`${O.url}?${g}`,expiresIn:i}}catch(e){if(e instanceof E)throw e;throw new E(e.message,u.PRESIGNED_URL_ERROR,!1,500)}},exports.s3GeneratePresignedUrl=async function(r){let{fileParams:o,bucketName:s,s3ClientConfig:i,expiresIn:a=U,origin:c,provider:p}=r;const{name:d,type:l,size:O}=o;try{w(o),await async function(e,t,r,o){const s={[exports.UpupProvider.AWS]:`https://${t}.s3.${r.region}.amazonaws.com/?cors`,[exports.UpupProvider.BackBlaze]:`${r.endpoint}/${t}/?cors=null`,[exports.UpupProvider.DigitalOcean]:`https://${t}.${r.region}.digitaloceanspaces.com/?cors`,[exports.UpupProvider.Azure]:""}[o],i=`<?xml version="1.0" encoding="UTF-8"?><CORSConfiguration>\n <CORSRule>\n <ID>Allow S3 Operations from my site: ${e}</ID>\n <AllowedOrigin>${e}</AllowedOrigin>\n <AllowedHeader>*</AllowedHeader>\n <AllowedMethod>HEAD</AllowedMethod>\n <AllowedMethod>PUT</AllowedMethod>\n <AllowedMethod>GET</AllowedMethod>\n <AllowedMethod>POST</AllowedMethod>\n <ExposeHeader>ETag</ExposeHeader>\n <MaxAgeSeconds>3600</MaxAgeSeconds>\n </CORSRule>\n</CORSConfiguration>`,a=function(e,t,r,o){let{region:s,credentials:{accessKeyId:i,secretAccessKey:a},endpoint:c}=r;const p=function(e,t,n){let{endpoint:r,region:o}=n;switch(t){case exports.UpupProvider.AWS:return`${e}.s3.${o}.amazonaws.com`;case exports.UpupProvider.BackBlaze:return r.split("https://")[1];case exports.UpupProvider.DigitalOcean:return`${e}.${o}.digitaloceanspaces.com`;default:return""}}(t,o,{endpoint:c,region:s}),d=(u=e,n.createHash("md5").update(u).digest("base64"));var u;const l=(new Date).toISOString().replace(/[:-]|\.\d{3}/g,""),R=l.slice(0,8),E={[exports.UpupProvider.AWS]:"/",[exports.UpupProvider.BackBlaze]:`/${t}/`,[exports.UpupProvider.DigitalOcean]:"/",[exports.UpupProvider.Azure]:""}[o],O={[exports.UpupProvider.AWS]:"cors=",[exports.UpupProvider.BackBlaze]:"cors=null",[exports.UpupProvider.DigitalOcean]:"cors=",[exports.UpupProvider.Azure]:""}[o],w=m(e),g="content-md5;content-type;host;x-amz-content-sha256;x-amz-date",U="AWS4-HMAC-SHA256",S=`${R}/${s}/s3/aws4_request`,_=[U,l,S,m(["PUT",E,O,`content-md5:${d}\ncontent-type:application/xml\nhost:${p}\nx-amz-content-sha256:${w}\nx-amz-date:${l}\n`,g,w].join("\n"))].join("\n"),I=function(e,t,n,r){const o=A("AWS4"+e,t),s=A(o,n),i=A(s,"s3");return A(i,"aws4_request")}(a,R,s);return{"Content-Type":"application/xml","Content-MD5":d,Authorization:U+" "+`Credential=${i}/${S}, `+`SignedHeaders=${g}, Signature=`+n.createHmac("sha256",I).update(_).digest("hex"),"x-amz-content-sha256":w,"x-amz-date":l,Host:p}}(i,t,r,o),c=await fetch(s,{method:"PUT",body:i,headers:a});if(!c.ok){const e=await c.text();throw new E(e,u.CORS_CONFIG_ERROR,!1,c.status)}return await c.text()}(c,s,i,p);const r=new e.S3Client(i),U=`${R()}-${d}`,S=new e.PutObjectCommand({Bucket:s,Key:U,ContentType:l,ContentLength:O}),_=await t.getSignedUrl(r,S,{expiresIn:a,signableHeaders:new Set(["content-type","content-length"])});return{key:U,publicUrl:await g(i,U,s),uploadUrl:_,expiresIn:a}}catch(e){if(e instanceof E)throw e;const{message:t,errorType:n}=function(e){return{message:(e||{}).Message||e.message,errorType:(e||{}).Code||u.PRESIGNED_URL_ERROR}}(e);throw new E(t,n,!1,500)}},exports.s3GenerateSignedUrl=g; //# sourceMappingURL=node.node.js.map