@lemoncloud/lemon-web-core
Version:
Core Web-based Library for signing request at LEMONCLOUD
29 lines (27 loc) • 29.2 kB
JavaScript
import Ce from 'crypto-js/hmac-sha256.js';
import Ie from 'crypto-js/enc-base64.js';
import { format } from 'util';
import { jwtDecode } from 'jwt-decode';
import Pe from 'axios';
import b from 'aws-sdk/global.js';
import Ee from 'crypto-js/sha256.js';
import $e from 'crypto-js/enc-hex.js';
var ke=Object.defineProperty,Se=Object.defineProperties;var Te=Object.getOwnPropertyDescriptors;var te=Object.getOwnPropertySymbols;var we=Object.prototype.hasOwnProperty,xe=Object.prototype.propertyIsEnumerable;var re=(n,e,t)=>e in n?ke(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t,g=(n,e)=>{for(var t in e||(e={}))we.call(e,t)&&re(n,t,e[t]);if(te)for(var t of te(e))xe.call(e,t)&&re(n,t,e[t]);return n},v=(n,e)=>Se(n,Te(e));var i=(n,e,t)=>new Promise((r,s)=>{var o=a=>{try{h(t.next(a));}catch(y){s(y);}},c=a=>{try{h(t.throw(a));}catch(y){s(y);}},h=a=>a.done?r(a.value):Promise.resolve(a.value).then(o,c);h((t=t.apply(n,e)).next());});var _={},G=class{constructor(){}setItem(e,t){return _[e]=t,_[e]}getItem(e){return Object.prototype.hasOwnProperty.call(_,e)?_[e]:void 0}removeItem(e){return delete _[e]}clear(){return _={},_}},H=class{constructor(){try{this.storage=window.localStorage,this.storage.setItem(".test-value",1),this.storage.removeItem(".test-value");}catch(e){this.storage=new G;}}setItem(e,t){this.storage.setItem(e,t);}getItem(e){return this.storage.getItem(e)}removeItem(e){this.storage.removeItem(e);}};var Ae=n=>new Promise(e=>setTimeout(()=>e(),n)),se=n=>typeof n!="object"?!n:Object.keys(n).length===0,Ye=(n,e,t)=>(...r)=>i(void 0,null,function*(){let s=0;do{try{return yield n(...r)}catch(o){if(s===e)return Promise.reject(o)}yield Ae(t);}while(s++<e)}),P=(n,e)=>{let t=Ce(n,e);return Ie.stringify(t)},Y=(n,e=new Date().toISOString(),t=navigator.userAgent)=>{let r=n.authId||"",s=n.accountId||"",o=n.identityId||"",c="";let h=[e,s,o,c,t].join("&");let a=P(P(P(h,r),s),o);return a},K=n=>n.toLowerCase().split("_").map((e,t)=>t>0?e.charAt(0).toUpperCase()+e.slice(1):e).join(""),Xe=(n,e=new Date().toISOString(),t=navigator.userAgent)=>{let r=n.authId||"",s=n.accountId||"",o=n.identityId||"",c=n.identityToken||"";let h=[e,s,o,c,t].join("&");let a=P(P(P(h,r),s),o);return a};var ve={Black:0,Red:1,Green:2,Yellow:3,Blue:4,Magenta:5,Cyan:6,Grey:7,White:9},_e={Black:"Black",Red:"IndianRed",Green:"LimeGreen",Yellow:"Orange",Blue:"RoyalBlue",Magenta:"Orchid",Cyan:"SkyBlue",Grey:"DimGrey",White:"White"},N=class{constructor(){this.colorSet=this.getColorSet(),this.logColors={DEBUG:this.colorSet.Blue,INFO:this.colorSet.Green,WARN:this.colorSet.Yellow,ERROR:this.colorSet.Red,DEFAULT:this.colorSet.Black};}formatMessage(e,t){let r=this.checkErrorInstance(t);return format(e,...r)}getColorAsType(e){return this.logColors[e]}getColorByName(e="Grey"){return this.colorSet[e]}isBrowser(){return typeof window!="undefined"&&typeof window.document!="undefined"}isNode(){return typeof process!="undefined"&&process.versions!=null&&process.versions.node!=null}checkErrorInstance(e){return this.isNode()?e:e.map(t=>t instanceof Error?{error:t.message,stack:t.stack}:t)}getColorSet(){return this.isBrowser()?_e:ve}};var be=(s=>(s.DEBUG="DEBUG",s.WARN="WARN",s.INFO="INFO",s.ERROR="ERROR",s))(be||{}),A=class{constructor(e="LEMON",t={}){this.options={showTimestamp:true,showLogType:true};this.utils=new N,this.namespace=e,this.options=g(g({},this.options),t),this.isNode=this.utils.isNode(),this.isBrowser=this.utils.isBrowser();}log(e,...t){let r=this.utils.formatMessage(e,t);this.writeLog("DEBUG",r);}debug(e,...t){let r=this.utils.formatMessage(e,t);this.writeLog("DEBUG",r);}warn(e,...t){let r=this.utils.formatMessage(e,t);this.writeLog("WARN",r);}info(e,...t){let r=this.utils.formatMessage(e,t);this.writeLog("INFO",r);}error(e,...t){let r=this.utils.formatMessage(e,t);this.writeLog("ERROR",r);}writeLog(e,t){let r=this.getFormat(e),s=this.createLogMessage(e,t,r);if(this.isNode){console.log(s);return}this.logOnBrowser(e,s,r);}createLogMessage(e,t,r,s=true){let o=e==="INFO"||e==="WARN"?" ":"",{showTimestamp:c,showLogType:h}=this.options,{timestampFormat:a,typeFormat:y,textFormat:k,namespaceFormat:S}=r;this.isBrowser&&s&&(a="%c",y="%c",S="%c",k=": %c");let T=c?`${a}${this.createTimestamp(new Date)} `:`${a}`,I=h?`${y}[${e}]${o} `:`${y}`,L=`${S}${this.namespace}`,W=`${k}${t}`;return `${T}${I}${L}${W}`}logOnBrowser(e,t,r){let{timestampFormat:s,typeFormat:o,namespaceFormat:c,textFormat:h}=r;e==="ERROR"?console.error(t,s,o,c,h):console.log(t,s,o,c,h);}getFormat(e){return this.isNode?this.getNodeFormat(e):this.getBrowserFormat(e)}getNodeFormat(e){let t=this.utils.getColorByName("White"),r=this.utils.getColorAsType(e),o="\x1B[3"+this.utils.getColorByName("Grey")+"m",c="\x1B[3"+r+";22m",h="\x1B[3"+t+";1m";return {timestampFormat:o,typeFormat:c,textFormat:"\x1B[0m: ",namespaceFormat:h}}getBrowserFormat(e){let t=this.utils.getColorByName("Black"),r=this.utils.getColorAsType(e),o="color:"+this.utils.getColorByName("Grey"),c="color:"+r,h="color:"+t+"; font-weight: bold";return {timestampFormat:o,typeFormat:c,textFormat:": ",namespaceFormat:h}}createTimestamp(e){let t=T=>T<10?"0":"",r=e||new Date,[s,o,c,h,a,y]=[r.getFullYear(),r.getMonth()+1,r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds()],k=`${t(s)}${s}-${t(o)}${o}-${t(c)}${c}`,S=`${t(h)}${h}:${t(a)}${a}:${t(y)}${y}`;return `${k} ${S}`}};var C="use_x_lemon_identity_key",w="use_x_lemon_language_key",F="region",E=class{constructor(e){this.config=e;this.prefix="lemon";this.storage=new H;this.prefix=`@${e.project}`,this.storage=this.config.storage||new H;}updatePrefix(e){this.prefix=`@${e}`;}setItem(e,t){return i(this,null,function*(){return yield this.storage.setItem(`${this.prefix}.${e}`,t)})}getItem(e){return i(this,null,function*(){return yield this.storage.getItem(`${this.prefix}.${e}`)})}calculateTokenExpiration(e,t){var o;if(e)return new Date(e).getTime()-3e5;if(t)try{let c=((o=this.extractJWT(t))==null?void 0:o.exp)||null;if(c)return c*1e3-3e5}catch(c){console.warn("Failed to parse JWT expiration:",c);}return console.warn("No server expiration found, using fallback duration"),new Date().getTime()+9e5}calculateTokenIssuedTime(e){var t;if(e)try{let r=((t=this.extractJWT(e))==null?void 0:t.iat)||null;if(r)return r*1e3}catch(r){return console.warn("Failed to parse JWT expiration:",r),""}return ""}extractJWT(e){try{return jwtDecode(e)}catch(t){return null}}};var U=class extends E{constructor(t){super(t);this.config=t;this.credentialKeys=["account_id","auth_id","identity_id","identity_pool_id","identity_token","access_key_id","secret_key","session_token","expired_time","issued_time","kms_arn"];}initLemonConfig(){return i(this,null,function*(){yield this.setItem(C,"true"),yield this.setItem(F,this.config.region||"ap-northeast-2");})}getAllItems(){return i(this,null,function*(){return yield this.credentialKeys.reduce((t,r)=>i(this,null,function*(){let s=yield t.then();return s[`${this.prefix}.${r}`]=yield this.storage.getItem(`${this.prefix}.${r}`),Promise.resolve(s)}),Promise.resolve({}))})}hasCachedToken(){return i(this,null,function*(){let t=yield this.storage.getItem(`${this.prefix}.expired_time`),r=yield this.storage.getItem(`${this.prefix}.access_key_id`),s=yield this.storage.getItem(`${this.prefix}.secret_key`),o=yield this.storage.getItem(`${this.prefix}.identity_token`);return !!r&&!!s&&!!t&&!!o})}shouldRefreshToken(){return i(this,null,function*(){let t=+(yield this.storage.getItem(`${this.prefix}.expired_time`)),r=new Date().getTime(),s=!t||t<=0,o=r>=t;return s||o})}getCachedCredentials(){return i(this,null,function*(){let t=yield this.storage.getItem(`${this.prefix}.access_key_id`),r=yield this.storage.getItem(`${this.prefix}.secret_key`),s=yield this.storage.getItem(`${this.prefix}.session_token`);return {AccessKeyId:t,SecretKey:r,SessionToken:s}})}getCachedOAuthToken(){return i(this,null,function*(){let t=yield this.credentialKeys.reduce((c,h)=>i(this,null,function*(){let a=yield c.then();return a[K(h)]=yield this.storage.getItem(`${this.prefix}.${h}`),Promise.resolve(a)}),Promise.resolve({})),r=yield this.storage.getItem(`${this.prefix}.access_key_id`),s=yield this.storage.getItem(`${this.prefix}.secret_key`),o=yield this.storage.getItem(`${this.prefix}.session_token`);return t.credential={AccessKeyId:r,SecretKey:s,SessionToken:o},delete t.accessKeyId,delete t.secretKey,delete t.sessionToken,delete t.expiredTime,delete t.kmsArn,t})}saveOAuthToken(t){return i(this,null,function*(){let{accountId:r,authId:s,credential:o,identityId:c,identityPoolId:h,identityToken:a}=t,{AccessKeyId:y,SecretKey:k,SessionToken:S,Expiration:T}=o;this.storage.setItem(`${this.prefix}.account_id`,r||""),this.storage.setItem(`${this.prefix}.auth_id`,s||""),this.storage.setItem(`${this.prefix}.identity_id`,c||""),this.storage.setItem(`${this.prefix}.identity_token`,a||""),this.storage.setItem(`${this.prefix}.identity_pool_id`,h||""),this.storage.setItem(`${this.prefix}.access_key_id`,y||""),this.storage.setItem(`${this.prefix}.secret_key`,k||""),this.storage.setItem(`${this.prefix}.session_token`,S||"");let I=this.calculateTokenExpiration(T,a);this.storage.setItem(`${this.prefix}.expired_time`,I.toString());let L=this.calculateTokenIssuedTime(a);L&&this.storage.setItem(`${this.prefix}.issued_time`,L.toString());})}clearOAuthToken(){return i(this,null,function*(){yield Promise.all(this.credentialKeys.map(t=>this.storage.removeItem(`${this.prefix}.${t}`)));})}saveKMS(t){return i(this,null,function*(){let r=t.arn;this.storage.setItem(`${this.prefix}.kms_arn`,r||"");})}};var M=class extends E{constructor(t){super(t);this.config=t;this.credentialKeys=["account_id","auth_id","identity_id","identity_token","access_token","host_key","expired_time","issued_time","client_id"];}getAllItems(){return i(this,null,function*(){return yield this.credentialKeys.reduce((t,r)=>i(this,null,function*(){let s=yield t;return s[`${this.prefix}.${r}`]=yield this.storage.getItem(`${this.prefix}.${r}`),Promise.resolve(s)}),Promise.resolve({}))})}hasCachedToken(){return i(this,null,function*(){let t=yield this.storage.getItem(`${this.prefix}.expired_time`),r=yield this.storage.getItem(`${this.prefix}.identity_token`),s=yield this.storage.getItem(`${this.prefix}.access_token`),o=yield this.storage.getItem(`${this.prefix}.host_key`);return !!r&&!!s&&!!o&&!!t})}shouldRefreshToken(){return i(this,null,function*(){let t=+(yield this.storage.getItem(`${this.prefix}.expired_time`)),r=new Date().getTime(),s=!t||t<=0,o=r>=t;return s||o})}getCachedOAuthToken(){return i(this,null,function*(){let t=yield this.credentialKeys.reduce((s,o)=>i(this,null,function*(){let c=yield s;return c[K(o)]=yield this.storage.getItem(`${this.prefix}.${o}`),Promise.resolve(c)}),Promise.resolve({})),r=yield this.storage.getItem(`${this.prefix}.host_key`);return t.credential={HostKey:r},delete t.hostKey,delete t.expiredTime,t})}saveOAuthToken(t){return i(this,null,function*(){let{accountId:r,authId:s,credential:o,identityId:c,identityToken:h,accessToken:a}=t,{hostKey:y,clientId:k,Expiration:S}=o;this.storage.setItem(`${this.prefix}.account_id`,r||""),this.storage.setItem(`${this.prefix}.auth_id`,s||""),this.storage.setItem(`${this.prefix}.identity_id`,c||""),this.storage.setItem(`${this.prefix}.identity_token`,h||""),this.storage.setItem(`${this.prefix}.host_key`,y||""),this.storage.setItem(`${this.prefix}.access_token`,a||""),this.storage.setItem(`${this.prefix}.client_id`,k||"default");let T=this.calculateTokenExpiration(S,h);this.storage.setItem(`${this.prefix}.expired_time`,T.toString());let I=this.calculateTokenIssuedTime(h);I&&this.storage.setItem(`${this.prefix}.issued_time`,I.toString());})}clearOAuthToken(){return i(this,null,function*(){yield Promise.all(this.credentialKeys.map(t=>this.storage.removeItem(`${this.prefix}.${t}`)));})}};var R=class{constructor(e,t){this.config={headers:{"Content-Type":"application/json"},method:"get"};if(!e.method)throw new Error("method should be defined!");if(!e.baseURL)throw new Error("baseURL should be defined!");this.config=g(g({},this.config),e),this.axiosInstance=t||Pe.create(e);}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}setMethod(e){return this.config.method=e,this}addHeaders(e={}){return this.config.headers=g(g({},this.config.headers),e),this}addAxiosRequestConfig(e){return this.config=g(g({},this.config),e),this}execute(){return i(this,null,function*(){try{return yield this.axiosInstance.request(this.config)}catch(e){throw e}})}};var Be=Ee,Oe=$e,We=Ce,X={};X.newClient=function(n){let e="AWS4-HMAC-SHA256",t="aws4_request",r="AWS4",s="x-amz-date",o="x-amz-security-token",c="host",h="Authorization";function a(d){return Be(d)}function y(d){return d.toString(Oe)}function k(d,m){return We(m,d)}function S(d,m,l,p,u){return d+`
`+I(m)+`
`+W(l)+`
`+ne(p)+`
`+j(p)+`
`+y(a(u))}function T(d){return y(a(d))}function I(d){return L(d)}function L(d,m=false){let l=[];for(let p=0;p<d.length;p++){let u=d.charAt(p);u>="A"&&u<="Z"||u>="a"&&u<="z"||u>="0"&&u<="9"||u=="_"||u=="-"||u=="~"||u=="."?l.push(u):u=="*"?l.push("%2A"):u=="!"?l.push("%21"):u=="("?l.push("%28"):u==")"?l.push("%29"):u=="/"?l.push(m?"%2F":u):l.push(encodeURIComponent(u));}return l.join("").toString()}function W(d){if(Object.keys(d).length<1)return "";let m=[];for(let p in d)Object.prototype.hasOwnProperty.call(d,p)&&m.push(p);m.sort();let l="";for(let p=0;p<m.length;p++)l+=m[p]+"="+ie(d[m[p]])+"&";return l.substr(0,l.length-1)}function ie(d){return encodeURIComponent(d).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A").replace(/%20/g,"%20")}function ne(d){let m="",l=[];for(let p in d)Object.prototype.hasOwnProperty.call(d,p)&&l.push(p);l.sort();for(let p=0;p<l.length;p++)m+=l[p].toLowerCase()+":"+d[l[p]]+`
`;return m}function j(d){let m=[];for(let l in d)Object.prototype.hasOwnProperty.call(d,l)&&m.push(l.toLowerCase());return m.sort(),m.join(";")}function ae(d,m,l){return e+`
`+d+`
`+m+`
`+l}function ce(d,m,l){return d.substr(0,8)+"/"+m+"/"+l+"/"+t}function de(d,m,l,p){return k(k(k(k(r+d,m.substr(0,8)),l),p),t)}function he(d,m){return y(k(d,m))}function ge(d,m,l,p){return e+" Credential="+d+"/"+m+", SignedHeaders="+j(l)+", Signature="+p}let f={};if(n.accessKey===void 0||n.secretKey===void 0)return f;f.host=n.host,f.accessKey=n.accessKey,f.secretKey=n.secretKey,f.sessionToken=n.sessionToken,f.serviceName=n.serviceName||"execute-api",f.region=n.region||"ap-northeast-2",f.defaultAcceptType=n.defaultAcceptType||"application/json",f.defaultContentType=n.defaultContentType||"application/json";let J=n.endpoint,Z=/(^https?:\/\/[^/]+)/g.exec(J)[1],ue=J.substring(Z.length);return f.endpoint=Z,f.pathComponent=ue,f.signRequest=function(d){let m=d.method.toUpperCase(),l=f.pathComponent+d.path,p=d.queryParams||{},u=d.headers||{};u["Content-Type"]===void 0&&(u["Content-Type"]=f.defaultContentType),u.Accept===void 0&&(u.Accept=f.defaultAcceptType);let x=d.body||{};d.body===void 0||m==="GET"?x="":x=x&&typeof x=="object"?JSON.stringify(x):x,(x===""||x===void 0||x===null)&&delete u["Content-Type"];let q=new Date().toISOString().replace(/\.\d{3}Z$/,"Z").replace(/[:-]|\.\d{3}/g,"");u[s]=q,u[c]=f.host;let le=S(m,l,p,u,x),me=T(le),Q=ce(q,f.region,f.serviceName),pe=ae(q,Q,me),fe=de(f.secretKey,q,f.region,f.serviceName),ye=he(fe,pe);u[h]=ge(f.accessKey,Q,u,ye),f.sessionToken!==void 0&&f.sessionToken!==""&&(u[o]=f.sessionToken),delete u[c];let V=f.endpoint+l,ee=W(p);return ee!==""&&(V+="?"+ee),u["Content-Type"]===void 0&&(u["Content-Type"]=f.defaultContentType),{headers:u,url:V}},f};var B=class{constructor(e,t,r){this.tokenStorage=e;this.config={headers:{"Content-Type":"application/json"},method:"get"};if(!e)throw new Error("tokenStorage should be defined!");if(!t.method)throw new Error("method should be defined!");if(!t.baseURL)throw new Error("baseURL should be defined!");this.config=g(g({},this.config),t),this.axiosInstance=r||Pe.create(this.config),this.logger=new A("AWSHttpBuilder");}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}setMethod(e){return this.config.method=e,this}addHeaders(e={}){return this.config.headers=g(g({},this.config.headers),e),this}addAxiosRequestConfig(e){return this.config=g(g({},this.config),e),this}execute(){return i(this,null,function*(){var e;try{let t=yield this.getSignedClient(this.config.baseURL),r={method:((e=this.config.method)==null?void 0:e.toLowerCase())||"get",params:this.config.params,body:this.config.data},s=yield this.getSignedHeader(t,r);return this.addHeaders(s),yield this.axiosInstance.request(this.config)}catch(t){throw t}})}getSignedClient(e){return i(this,null,function*(){if(!e)throw new Error("@endpoint (string) is required!");let t=yield this.tokenStorage.getItem(F),s=b.config&&b.config.credentials&&X.newClient({accessKey:b.config.credentials.accessKeyId,secretKey:b.config.credentials.secretAccessKey,sessionToken:b.config.credentials.sessionToken,region:t||"ap-northeast-2",endpoint:e,host:this.extractHostname(e)});return s||this.logger.warn("signedClient is missing. Request without signing.."),yield s})}getSignedHeader(e,t){return i(this,null,function*(){if(!e)return {};let{method:r,path:s,params:o,body:c}=t,h=e.signRequest({method:r,path:s||"",headers:{},queryParams:o||{},body:c||{}}),a=h&&h.headers;if(se(a))return this.logger.warn("signedClient is missing => Request without signing"),this.config.headers;let k=yield this.addXLemonIdentityToHeader(a);return yield this.addXLemonLanguageToHeader(k)})}addXLemonIdentityToHeader(e){return i(this,null,function*(){let t=yield this.tokenStorage.getItem(C);if(!t||t==="false")return g(g({},e),this.config.headers);let r=yield this.tokenStorage.getItem("identity_token");return v(g(g({},e),this.config.headers),{"x-lemon-identity":r})})}addXLemonLanguageToHeader(e){return i(this,null,function*(){let[t,r]=yield Promise.all([this.tokenStorage.getItem(w),this.tokenStorage.getItem((yield this.tokenStorage.getItem(w))||"")]);return g(g(g({},e),this.config.headers),t&&r&&{"x-lemon-language":r})})}extractHostname(e){let t;return e.indexOf("//")>-1?t=e.split("/")[2]:t=e.split("/")[0],t=t.split(":")[0],t=t.split("?")[0],t}};var O=class{constructor(e,t){this.tokenStorage=e;this.config={headers:{"Content-Type":"application/json"},method:"get"};if(!e)throw new Error("tokenStorage should be defined!");if(!t.method)throw new Error("method should be defined!");if(!t.baseURL)throw new Error("baseURL should be defined!");this.config=g(g({},this.config),t),this.axiosInstance=Pe.create(this.config);}setHeaders(e){return this.config.headers=e,this}setParams(e){return this.config.params=e,this}setBody(e){return this.config.data=e,this}setMethod(e){return this.config.method=e,this}addHeaders(e={}){return this.config.headers=g(g({},this.config.headers),e),this}addAxiosRequestConfig(e){return this.config=g(g({},this.config),e),this}execute(){return i(this,null,function*(){try{return yield this.addCodeParams(),yield this.addBearerTokenToHeader(),yield this.addXLemonIdentityToHeader(),yield this.addXLemonLanguageToHeader(),yield this.axiosInstance.request(this.config)}catch(e){throw e}})}addCodeParams(){return i(this,null,function*(){let e=(yield this.tokenStorage.getItem("host_key"))||"";if(!e)return;let t=(yield this.tokenStorage.getItem("client_id"))||"default",r=this.config.params||{};this.setParams(v(g({},r),{code:e,clientId:t}));})}addBearerTokenToHeader(){return i(this,null,function*(){let e=(yield this.tokenStorage.getItem("identity_token"))||"";e&&this.addHeaders({Authorization:`Bearer ${e}`});})}addXLemonIdentityToHeader(){return i(this,null,function*(){let e=yield this.tokenStorage.getItem(C);if(!e||e==="false")return;let t=yield this.tokenStorage.getItem("identity_token");this.addHeaders({"x-lemon-identity":t});})}addXLemonLanguageToHeader(){return i(this,null,function*(){let e=yield this.tokenStorage.getItem(w);if(!e)return;let t=yield this.tokenStorage.getItem(e);t&&this.addHeaders({"x-lemon-language":t});})}};var D=class{constructor(e){this.config=e;this.logger=new A("AWSCore"),this.tokenStorage=new U(this.config),this.sharedAxiosInstance=Pe.create();}getSharedAxiosInstance(){return this.sharedAxiosInstance}init(){return i(this,null,function*(){if(yield this.tokenStorage.initLemonConfig(),!(yield this.tokenStorage.hasCachedToken()))return this.logger.warn("initialized without token!"),"no-token";if((yield this.tokenStorage.shouldRefreshToken())&&(yield this.refreshCachedToken()))return yield this.getCurrentCredentials(),this.logger.info("initialized and refreshed token!"),"refreshed";if(!(yield this.tokenStorage.hasCachedToken()))return this.logger.warn("initialized without token!"),"no-token";let s=yield this.tokenStorage.getCachedCredentials();return this.createAWSCredentials(s),this.logger.info("initialized with token!"),"build"})}getTokenStorage(){return this.tokenStorage}buildRequest(e){return new R(e,this.sharedAxiosInstance)}request(c,h){return i(this,arguments,function*(e,t,r={},s,o){let a=new R({method:e,baseURL:t,params:r});return s&&a.setBody(s),o&&a.addAxiosRequestConfig(o),yield a.execute()})}buildSignedRequest(e){return new B(this.tokenStorage,e,this.sharedAxiosInstance)}signedRequest(c,h){return i(this,arguments,function*(e,t,r={},s,o){let a=new B(this.tokenStorage,{method:e,baseURL:t,params:r});return s&&a.setBody(s),o&&a.addAxiosRequestConfig(o),yield a.execute()})}getSavedToken(){return this.tokenStorage.getAllItems()}isAuthenticated(){return i(this,null,function*(){try{return (yield this.tokenStorage.hasCachedToken())?(yield this.tokenStorage.shouldRefreshToken())?(this.logger.info("return isAuthenticated after refresh token"),(yield this.refreshCachedToken())!==null):new Promise(r=>{try{let s=b.config.credentials;if(!s){r(!1);return}s.get(o=>{o&&this.logger.error("get AWSConfig.credentials error: ",o),r(!o);});}catch(s){this.logger.error("isAuthenticated error: ",s),r(!1);}}):!1}catch(e){return this.logger.error("isAuthenticated error:",e),false}})}buildCredentialsByToken(e){return i(this,null,function*(){this.logger.log("buildCredentialsByToken()..."),yield this.buildAWSCredentialsByToken(e);let t=b.config.credentials;if(!t)throw new Error("Failed to build AWS credentials");return t})}buildCredentialsByStorage(){return i(this,null,function*(){this.logger.log("buildCredentialsByStorage()..."),yield this.buildAWSCredentialsByStorage();let e=b.config.credentials;if(!e)throw new Error("Failed to build AWS credentials from storage");return e})}saveKMS(e){return i(this,null,function*(){return this.logger.log("saveKMS()..."),yield this.tokenStorage.saveKMS(e)})}refreshCachedToken(e="",t=""){return i(this,null,function*(){try{let r=yield this.tokenStorage.getCachedOAuthToken();if(!r.authId)throw new Error("authId is required for token refresh");let s=yield this.tokenStorage.getCachedCredentials();this.createAWSCredentials(s);let o={authId:r.authId,accountId:r.accountId,identityId:r.identityId,identityToken:r.identityToken},c=new Date().toISOString(),h=Y(o,c),a={current:c,signature:h};e&&e.length>0&&(a=v(g({},a),{domain:e}));let y=yield this.signedRequest("POST",t||`${this.config.oAuthEndpoint}/oauth/${r.authId}/refresh`,{token:1},g({},a)),k=y.data.Token||y.data,S=g({identityToken:k.identityToken||r.identityToken,identityPoolId:r.identityPoolId},k);return this.logger.info("success to refresh token"),yield this.buildCredentialsByToken(S)}catch(r){return this.logger.error("token refresh failed:",r),null}})}changeUserSite(e,t){return i(this,null,function*(){var T;if(!e||!e.siteId||!e.userId)throw new Error("@changeSiteBody required");let r=yield this.tokenStorage.getCachedOAuthToken(),s=`${e.userId}@${e.siteId}`,o=yield this.getTokenSignature(),{authId:c,current:h,signature:a,originToken:y}=o;if(!c)throw new Error("authId is required for token refresh");let k=yield this.signedRequest("POST",t||`${this.config.oAuthEndpoint}/oauth/${c}/refresh`,{token:1},{current:h,signature:a,target:s}),S=v(g({},k.data),{identityToken:((T=k.data)==null?void 0:T.identityToken)||y.identityToken,identityPoolId:r.identityPoolId});return this.logger.info("success to change user site"),yield this.buildCredentialsByToken(S)})}logout(){return i(this,null,function*(){b.config.credentials=null,yield this.tokenStorage.clearOAuthToken();})}setUseXLemonIdentity(e){return i(this,null,function*(){yield this.tokenStorage.setItem(C,`${e}`);})}setUseXLemonLanguage(e,t){return i(this,null,function*(){if(!e){yield this.tokenStorage.setItem(w,"");return}t&&(yield this.tokenStorage.setItem(w,t));})}getTokenSignature(){return i(this,null,function*(){let e=yield this.tokenStorage.getCachedOAuthToken(),t={authId:e.authId,accountId:e.accountId,identityId:e.identityId,identityToken:e.identityToken},r=new Date().toISOString(),s=Y(t,r);return {authId:t.authId,current:r,signature:s,originToken:e}})}getCredentials(){return i(this,null,function*(){return (yield this.tokenStorage.hasCachedToken())?(yield this.tokenStorage.shouldRefreshToken())&&(this.logger.info("should refresh token!"),!(yield this.refreshCachedToken()))?null:yield this.getCurrentCredentials():(this.logger.info("has no cached token!"),null)})}buildAWSCredentialsByStorage(){return i(this,null,function*(){this.logger.log("buildAWSCredentialsByStorage()...");let e=yield this.tokenStorage.getCachedCredentials(),{AccessKeyId:t,SecretKey:r}=e;if(!t)throw new Error(".AccessKeyId (string) is required!");if(!r)throw new Error(".SecretKey (string) is required!");this.createAWSCredentials(e);})}getCurrentCredentials(){return new Promise((e,t)=>{let r=b.config.credentials;if(!r){t(new Error("No AWS credentials configured"));return}r.get(s=>{s?(this.logger.error("Error on getCurrentCredentials: ",s),t(s)):(this.logger.info("success to get AWS credentials"),e(r));});})}buildAWSCredentialsByToken(e){return i(this,null,function*(){let{credential:t}=e,{AccessKeyId:r,SecretKey:s}=t;if(!r)throw new Error(".AccessKeyId (string) is required!");if(!s)throw new Error(".SecretKey (string) is required!");return yield this.tokenStorage.saveOAuthToken(e),this.createAWSCredentials(t)})}createAWSCredentials(e){let{AccessKeyId:t,SecretKey:r,SessionToken:s}=e;b.config.credentials=new b.Credentials(t,r,s);}};var z=class{constructor(e){this.config=e;this.logger=new A("AzureCore"),this.tokenStorage=new M(this.config),this.sharedAxiosInstance=Pe.create();}init(){return i(this,null,function*(){return (yield this.tokenStorage.hasCachedToken())?((yield this.tokenStorage.shouldRefreshToken())&&this.logger.info("initialized and refreshed token!"),this.logger.info("initialized with token!"),"has-token"):(this.logger.warn("initialized without token!"),"no-token")})}getTokenStorage(){return this.tokenStorage}getSharedAxiosInstance(){return this.sharedAxiosInstance}buildRequest(e){return new R(e,this.sharedAxiosInstance)}request(c,h){return i(this,arguments,function*(e,t,r={},s,o){let a=new R({method:e,baseURL:t,params:r});return s&&a.setBody(s),o&&a.addAxiosRequestConfig(o),yield a.execute()})}buildSignedRequest(e){return new O(this.tokenStorage,e)}signedRequest(c,h){return i(this,arguments,function*(e,t,r={},s,o){let a=new O(this.tokenStorage,{method:e,baseURL:t,params:r});return s&&a.setBody(s),o&&a.addAxiosRequestConfig(o),yield a.execute()})}getSavedToken(){return this.tokenStorage.getAllItems()}isAuthenticated(){return i(this,null,function*(){return (yield this.tokenStorage.hasCachedToken())?((yield this.tokenStorage.shouldRefreshToken())&&this.logger.info("should refresh token!"),true):false})}saveOAuthToken(e){return i(this,null,function*(){return yield this.tokenStorage.saveOAuthToken(e)})}logout(){return i(this,null,function*(){yield this.tokenStorage.clearOAuthToken();})}setUseXLemonIdentity(e){return i(this,null,function*(){yield this.tokenStorage.setItem(C,`${e}`);})}setUseXLemonLanguage(e,t){return i(this,null,function*(){if(!e){yield this.tokenStorage.setItem(w,"");return}t&&(yield this.tokenStorage.setItem(w,t));})}};var Ue={aws:D,azure:z},oe=class{static create(e){let{cloud:t}=e,r=Ue[t];if(!r)throw new Error("Unsupported cloud provider");return new r(e)}};//! INFO: lemon-account-api
//! algorithm: sha256, encoding: base64
//! build payload to sign......
//! make signature with auth-id
//! returns signature..........
//! code from: https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
//! '*' '+' '!' 같은 특수 문자가 들어갈 경우 인증 에러 발생할 수 있음.
export { B as AWSHttpRequestBuilder, U as AWSStorageService, D as AWSWebCore, O as AzureHttpRequestBuilder, M as AzureStorageService, z as AzureWebCore, _e as BROWSER_COLORS, R as HttpRequestBuilder, H as LocalStorageService, be as LogType, N as LoggerHelperService, A as LoggerService, ve as NODE_COLORS, F as REGION_KEY, E as TokenStorageService, C as USE_X_LEMON_IDENTITY_KEY, w as USE_X_LEMON_LANGUAGE_KEY, oe as WebCoreFactory, Y as calcSignature, Xe as calcTestSignature, K as convertCamelCaseFromSnake, Ae as createAsyncDelay, P as hmac, se as isEmptyObject, X as sigV4Client, Ye as withRetries };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map