/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@bunq-community/bunq-js-client@1.1.2/dist/BunqJSClient.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const axios_1=require("axios"),Logger_1=require("./Helpers/Logger"),ErrorCodes_1=require("./Helpers/ErrorCodes"),Rsa_1=require("./Crypto/Rsa"),Aes_1=require("./Crypto/Aes"),ApiAdapter_1=require("./ApiAdapter"),Session_1=require("./Session"),LocalstorageStore_1=require("./Stores/LocalstorageStore"),index_1=require("./Api/index"),FIVE_MINUTES_MS=3e5;class BunqJSClient{constructor(e=!1,s=Logger_1.default){if(this.apiKey=!1,this.keepAlive=!0,this.fetchingNewSession=!1,this.errorCodes=ErrorCodes_1.default,this.expiryTimerCallback=()=>{if(!1===this.keepAlive)return this.clearExpiryTimer(),!1;this.getUsers(!0).then((e=>{this.logger.debug("Triggered session refresh")})).catch((e=>{this.logger.error(e)})),this.setExpiryTimer(!0)},!1===e){if("undefined"==typeof navigator)throw new Error("No custom storageInterface was defined in the constructor!");this.storageInterface=LocalstorageStore_1.default()}else this.storageInterface=e;this.logger=s,this.Session=new Session_1.default(this.storageInterface,this.logger),this.ApiAdapter=new ApiAdapter_1.default(this.Session,this.logger,this),this.api=index_1.default(this)}async run(e,s=[],i="SANDBOX",t=!1,r=2048,o=!1){this.logger.debug("bunqJSClient run"),this.apiKey=e,await this.Session.setup(this.apiKey,s,i,t,r,o),this.setExpiryTimer(),await this.ApiAdapter.setup()}setKeepAlive(e){this.keepAlive=e}setRequestProxies(e){this.ApiAdapter.RequestLimitFactory.setEnabledProxies(e)}async install(){if(!1===this.Session.verifyInstallation()){if(!this.Session.publicKey)throw new Error("No public key is set yet, make sure you setup an encryption key with BunqJSClient->run()");const e=await this.api.installation.add();this.Session.serverPublicKeyPem=e.serverPublicKey,this.Session.serverPublicKey=await Rsa_1.publicKeyFromPem(e.serverPublicKey),this.Session.installToken=e.token.token,this.Session.installUpdated=new Date(e.token.updated),this.Session.installCreated=new Date(e.token.created),await this.Session.storeSession()}return!0}async registerDevice(e="My Device",s=2048,i=!1){if(!1===this.Session.verifyDeviceInstallation())try{const s=await this.api.deviceRegistration.add({description:e,permitted_ips:this.Session.allowedIps});this.Session.deviceId=s,await this.Session.storeSession()}catch(e){if(!e.response)throw e;throw 400===e.response.status&&(this.Session.serverPublicKeyPem=null,this.Session.serverPublicKey=null,this.Session.installToken=null,this.Session.installUpdated=null,this.Session.installCreated=null,await this.Session.setupKeypair(!0,s,i),await this.Session.storeSession()),e}return!0}async registerSession(){if(!1===this.Session.verifySessionInstallation()){try{this.fetchingNewSession=this.generateSession(),await this.fetchingNewSession}catch(e){throw this.fetchingNewSession=!1,e}this.fetchingNewSession=!1}return!0}async generateSession(){let e=null;try{this.logger.debug(" === Attempting to fetch session"),e=await this.api.sessionServer.add()}catch(e){if(e.response&&e.response.data.Error){const s=e.response.data.Error[0].error_description;if(this.logger.error("bunq API error: "+s),"Authentication token already has a user session."===s)throw{errorCode:this.errorCodes.INSTALLATION_HAS_SESSION,error:e}}throw e}this.logger.debug("response.token.created:"+e.token.created);const s=new Date(e.token.created+" UTC");let i,t=this.getUserType(e.user_info);return!1===t.isOAuth?(i=t.info.session_timeout,this.logger.debug("Received userInfoParsed.info.session_timeout from api: "+t.info.session_timeout),this.Session.isOAuthKey=!1,this.Session.userInfo=e.user_info):i=this.parseOauthUser(t),i*=1e3,s.setTime(s.getTime()+i),this.Session.sessionExpiryTime=s,this.Session.sessionTimeout=i,this.Session.sessionId=e.id,this.Session.sessionToken=e.token.token,this.Session.sessionTokenId=e.token.id,this.logger.debug("calculated expireDate: "+s+" current date: "+new Date),await this.Session.storeSession(),this.setExpiryTimer(),!0}async changeEncryptionKey(e){if(!Aes_1.validateKey(e))throw new Error("Invalid EAS key given! Invalid characters or length (16,24,32 length)");return this.Session.encryptionKey=e,this.Session.storeSession()}parseOauthUser(e){const s=this.getUserType(e.info.requested_by_user),i=this.getUserType(e.info.granted_by_user),t=s.info.session_timeout;return this.logger.debug("Received requestedByUserParsed.info.session_timeout from api: "+s.info.session_timeout),i.info.id||(i.info.id=e.info.id),this.Session.isOAuthKey=!0,this.Session.userInfo.UserApiKey=e.info,t}async createCredentials(){const e=this.ApiAdapter.RequestLimitFactory.create("/credential-password-ip-request","POST");return(await e.run((async e=>this.ApiAdapter.post("https://api.tinker.bunq.com/v1/credential-password-ip-request",{},{},{disableVerification:!0,disableSigning:!0,skipSessionCheck:!0})))).Response[0].UserCredentialPasswordIpRequest}async checkCredentialStatus(e){const s=this.ApiAdapter.RequestLimitFactory.create("/credential-password-ip-request","GET");return(await s.run((async s=>this.ApiAdapter.get(`https://api.tinker.bunq.com/v1/credential-password-ip-request/${e}`,{},{disableVerification:!0,disableSigning:!0,skipSessionCheck:!0})))).Response[0].UserCredentialPasswordIpRequest}async exchangeOAuthToken(e,s,i,t,r=!1,o=!1,n="authorization_code"){const a=this.formatOAuthKeyExchangeUrl(e,s,i,t,o,n),h=(await axios_1.default({method:"POST",url:a})).data;if(r&&r!==h.state)throw new Error("Given state does not match token exchange state!");return h.access_token}formatOAuthAuthorizationRequestUrl(e,s,i=!1,t=!1){return`${t?"https://oauth.sandbox.bunq.com":"https://oauth.bunq.com"}/auth?response_type=code&client_id=${e}&redirect_uri=${s}`+(i?`&state=${i}`:"")}formatOAuthKeyExchangeUrl(e,s,i,t,r=!1,o="authorization_code"){return`${r?"https://api-oauth.sandbox.bunq.com":"https://api.oauth.bunq.com"}/v1/token?grant_type=${o}&code=${t}&client_id=${e}&client_secret=${s}&redirect_uri=${i}`}setExpiryTimer(e=!1,s=!1){if("undefined"!=typeof process&&"true"===process.env.ENV_CI&&!0!==s)return!1;if(!1===this.keepAlive)return this.clearExpiryTimer(),!1;if(this.Session.sessionExpiryTime){const e=this.calculateSessionExpiry()-15e3;this.clearExpiryTimer(),this.Session.sessionExpiryTimeChecker=setTimeout(this.expiryTimerCallback,e)}}clearExpiryTimer(){null!==this.Session.sessionExpiryTimeChecker&&clearTimeout(this.Session.sessionExpiryTimeChecker)}calculateSessionExpiry(e=!1){if(e)return!this.Session.sessionTimeout||this.Session.sessionTimeout>3e5?3e5:this.Session.sessionTimeout;const s=new Date;return this.Session.sessionExpiryTime.getTime()-s.getTime()}async destroySession(){if(this.Session.verifyInstallation()&&this.Session.verifyDeviceInstallation()&&this.Session.verifySessionInstallation())try{await this.api.sessionServer.delete()}catch(e){}this.clearExpiryTimer(),await this.Session.destroySession()}async destroyApiSession(e=!1){this.clearExpiryTimer(),await this.Session.destroyApiSession(e)}async getUser(e,s=!1){if(s){const e=await this.api.user.list(),s=this.getUserType(e);s.isOAuth?this.parseOauthUser(s):this.Session.userInfo[s.type]=s.info}return this.Session.userInfo[e]}async getUsers(e=!1){if(e){const e=await this.api.user.list(),s=this.getUserType(e);s.isOAuth?this.parseOauthUser(s):this.Session.userInfo[s.type]=s.info}return this.Session.userInfo}getUserType(e){if(void 0!==e.UserCompany)return{info:e.UserCompany,type:"UserCompany",isOAuth:!1};if(void 0!==e.UserPerson)return{info:e.UserPerson,type:"UserPerson",isOAuth:!1};if(void 0!==e.UserLight)return{info:e.UserLight,type:"UserLight",isOAuth:!1};if(void 0!==e.UserApiKey)return{info:e.UserApiKey,type:"UserApiKey",isOAuth:!0};throw new Error("No supported account type found! (Not one of UserLight, UserPerson, UserApiKey or UserCompany)")}}exports.default=BunqJSClient;
//# sourceMappingURL=/sm/1e73fa992175e4da3094bd079a24e92ac73554f9d6018015ef9dbd90acb4fa38.map