New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@plusauth/oidc-client-js

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@plusauth/oidc-client-js - npm Package Compare versions

Comparing version 1.2.4 to 1.2.5

4

dist/oidc-client.esm.js
/*!
* @plusauth/oidc-client-js v1.2.4
* @plusauth/oidc-client-js v1.2.5
* https://github.com/PlusAuth/oidc-client-js

@@ -719,3 +719,3 @@ * (c) 2023 @plusauth/oidc-client-js Contributors

if (currentValue[p] !== undefined) {
if (typeof currentValue[p] === 'object') {
if (typeof currentValue[p] === 'object' && currentValue[p].constructor.name === 'Object') {
previousValue[p] = merge(previousValue[p] || {}, currentValue[p]);

@@ -722,0 +722,0 @@ } else {

@@ -1,2 +0,2 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).PlusAuthOIDCClient={})}(this,function(e){"use strict";let t={USER_LOGOUT:"user_logout",USER_LOGIN:"user_login",SILENT_RENEW_SUCCESS:"silent_renew_success",SILENT_RENEW_ERROR:"silent_renew_error",SESSION_CHANGE:"session_change"};function i(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class s extends Error{constructor(e,t){super(`${e}${t&&` - ${t}`||""}`),i(this,"error",void 0),i(this,"error_description",void 0),this.name="OIDCClientError",this.error=e,this.error_description=t}}class n extends s{constructor(e,t,s,n){super(e,t),i(this,"state",void 0),i(this,"error_uri",void 0),this.name="AuthenticationError",this.state=s,this.error_uri=n}}class o extends s{constructor(e){super(e),this.name="InvalidJWTError",this.error_description=e}}class r extends o{constructor(e){super(e),this.name="InvalidIdTokenError"}}class a extends s{constructor(e){super(e),this.name="InteractionCancelled"}}class l{constructor(e=""){var t,i,s;t=this,s=void 0,(i="prefix")in t?Object.defineProperty(t,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[i]=s,this.prefix=e}}class h extends l{get(e){return new Promise(t=>{let i=window.localStorage.getItem(this.prefix+e);t(i?JSON.parse(i):null)})}set(e,t){return new Promise(i=>{window.localStorage.setItem(this.prefix+e,JSON.stringify(t)),i()})}del(e){return new Promise(t=>{window.localStorage.removeItem(this.prefix+e),t()})}clear(e){return new Promise(t=>{let i;let s=[];for(i=0;i<window.localStorage.length;i++){let e=window.localStorage.key(i);(null==e?void 0:e.substring(0,this.prefix.length))==this.prefix&&s.push(e)}for(i=0;i<s.length;i++)if(e)try{let t=JSON.parse(window.localStorage.getItem(s[i]));t.created_at<e&&window.localStorage.removeItem(s[i])}catch(e){}else window.localStorage.removeItem(s[i]);t()})}constructor(e="pa_oidc."){super(e)}}class c extends l{clear(e){return e?(this.map.forEach((t,i)=>{t.created_at<e&&this.map.delete(i)}),Promise.resolve()):Promise.resolve(this.map.clear())}del(e){return this.map.delete(e),Promise.resolve()}get(e){return Promise.resolve(this.map.get(e)||null)}set(e,t){return this.map.set(e,t),Promise.resolve()}constructor(...e){var t,i;super(...e),t=this,i=new Map,"map"in t?Object.defineProperty(t,"map",{value:i,enumerable:!0,configurable:!0,writable:!0}):t.map=i}}class d{once(e,t){function i(...s){this.off(e,i),t.apply(this,s)}return i.fn=t,this.on(e,i),this}on(e,t){return this.callbacks[`$${e}`]||(this.callbacks[`$${e}`]=[]),this.callbacks[`$${e}`].push(t),this}off(e,t){if(!e)return this.callbacks={},this;let i=this.callbacks[`$${e}`];if(!i)return this;if(!t)return delete this.callbacks[`$${e}`],this;for(let e=0;e<i.length;e++){let s=i[e];if(s===t||s.fn===t){i.splice(e,1);break}}return 0===i.length&&delete this.callbacks[`$${e}`],this}emit(e,...t){let i=this.callbacks[`$${e}`];if(i){i=i.slice(0);for(let e=0,s=i.length;e<s;++e)i[e].apply(this,t)}return this}constructor(){var e,t,i;e=this,i=void 0,(t="callbacks")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,this.callbacks={}}}function u(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class p{start(e,t){e<=0&&(e=1);let i=this.now()/1e3+e;if(this._expiration===i&&this._timerHandle)return;this.stop(),this._expiration=i;let s=5;e<5&&(s=e),this._timerHandle=setInterval(()=>{this._expiration<=this.now()/1e3&&(this.stop(),t())},1e3*s)}stop(){this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}constructor(e=()=>Date.now()){u(this,"now",void 0),u(this,"_timerHandle",void 0),u(this,"_expiration",void 0),this.now=e}}function w(){let e=window.document.createElement("iframe");return e.style.width="0",e.style.height="0",e.style.position="absolute",e.style.visibility="hidden",e.style.display="none",e.title="__pa_helper__hidden",e.ariaHidden="true",e}for(var _,f=[],m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g=0,v=m.length;g<v;++g)f[g]=m[g];function y(e,t=!0){if(!e)return"";let i=[];for(let t in e)e.hasOwnProperty(t)&&e[t]&&i.push(`${encodeURIComponent(t)}=${encodeURIComponent("object"==typeof e[t]?JSON.stringify(e[t]):e[t])}`);return`${t?"?":""}${i.join("&")}`}function S(e){let t=null,i=e.headers||{};return"POST"===e.method&&(i={"Content-Type":"form"===e.requestType?"application/x-www-form-urlencoded;charset=UTF-8":"application/json;charset=UTF-8",...i}),e.body&&(t="form"===e.requestType?y(e.body,!1):JSON.stringify(e.body)),new Promise((s,n)=>{fetch(e.url,{method:e.method,body:t,headers:i}).then(e=>s(e.json())).catch(n)})}let k="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function b(e){let t="",i=k.length,s=256-256%i;for(;e>0;){let n=function(e){let t=self.crypto||self.msCrypto,i=new Uint8Array(e);for(let s=0;s<e;s+=65536)t.getRandomValues(i.subarray(s,s+Math.min(e-s,65536)));return i}(Math.ceil(256*e/s));for(let o=0;o<n.length&&e>0;o++){let r=n[o];r<s&&(t+=k.charAt(r%i),e--)}}return t}let T=e=>decodeURIComponent(atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""));function E(e){try{let t=e.split(".");if(3!==t.length)throw Error("Wrong JWT format");return{header:JSON.parse(T(t[0])),payload:JSON.parse(T(t[1]))}}catch(e){throw new o("Failed to parse jwt")}}let I=["iss","aud","exp","nbf","iat","jti","azp","nonce","auth_time","at_hash","c_hash","acr","amr","sub_jwk","cnf","sip_from_tag","sip_date","sip_callid","sip_cseq_num","sip_via_branch","orig","dest","mky","events","toe","txn","rph","sid","vot","vtm","attest","origid","act","scope","client_id","may_act","jcard","at_use_nbr"];function O(...e){return e.reduce((e,t)=>(function e(t,i){for(let s in i)void 0!==i[s]&&("object"==typeof i[s]?t[s]=e(t[s]||{},i[s]):t[s]=i[s]);return t})(e||{},t),{})}let $=(e,t)=>t&&t.split(/\s+/g).filter(t=>t===e).length>0,x=(e,t)=>t&&t.split(" ").indexOf(e)>-1,R=(e,t=400,i=600)=>{let s=window.screenX+(window.innerWidth-t)/2,n=window.screenY+(window.innerHeight-i)/2;return window.open(e,"oidc-login-popup",`left=${s},top=${n},width=${t},height=${i},resizable,scrollbars=yes,status=1`)},P=`${performance.now()}:${1e9*Math.random()|0}`,C={};class A{CallOnce(e,t,i=3e3){if(!e)throw"empty lockname";if(!window.localStorage){t();return}let s=this.keyPrefix+e;localStorage.setItem(s,P),setTimeout(()=>{localStorage.getItem(s)==P&&t()},150),setTimeout(function(){localStorage.removeItem(s)},i)}BroadcastMessageToAllTabs(e,t){try{C[e](t)}catch(e){}if(!window.localStorage)return;let i={data:t,timeStamp:new Date().getTime()};localStorage.setItem(`${this.keyPrefix}event${e}`,JSON.stringify(i)),setTimeout(()=>{localStorage.removeItem(`${this.keyPrefix}event${e}`)},3e3)}OnBroadcastMessage(e,t){C[e]=t,window.localStorage&&window.addEventListener("storage",i=>{if(i.key!=`${this.keyPrefix}event${e}`||!i.newValue)return;let s=JSON.parse(i.newValue);t(s.data)})}constructor(e){var t,i,s;t=this,s=void 0,(i="keyPrefix")in t?Object.defineProperty(t,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[i]=s,this.keyPrefix=e}}function j(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class z extends d{async initialize(e=!0){return this.initialized?this:(this.__initializePromise||(this.__initializePromise=new Promise(async(i,n)=>{try{this.stateStore.init&&await this.stateStore.init(),this.authStore.init&&await this.authStore.init(),this.options.endpoints&&0!==Object.keys(this.options.endpoints).length||await this.fetchFromIssuer(),this.initialized=!0;try{!e||(null==window?void 0:window.frameElement)||await this.silentLogin()}catch(e){this.emit(t.SILENT_RENEW_ERROR,e),await this.authStore.clear()}i(this)}catch(e){n(e instanceof s?e:new s(e.message))}finally{this.__initializePromise=void 0}})),this.__initializePromise)}async login(e={},t={}){window.location.assign(await this.createAuthRequest(e,t))}async loginWithPopup(e={},i={}){let n=await this.createAuthRequest({response_mode:"fragment",...e,display:"popup",request_type:"p"}),{response:o,state:r}=await function(e,t){let i,n,o=t.popup;if(o?o.location.href=e:o=R(e),!o)throw Error("Could not open popup");return new Promise((e,r)=>{function l(){clearInterval(n),clearTimeout(i),window.removeEventListener("message",h)}function h(t){if(!t.data||"authorization_response"!==t.data.type)return;l(),o.close();let i=t.data.response||t.data;i.error?r(new s(i.error,i.error_description)):e(t.data)}i=setTimeout(()=>{l(),r(new s("Timed out"))},t.timeout||6e4),n=setInterval(function(){o.closed&&(l(),r(new a("user closed popup")))},300),window.addEventListener("message",h)})}(n,i),{authParams:l,localState:h}=r&&"string"!=typeof r?r:await this.loadState(r||o.state),c=await this.handleAuthResponse(o,l,h),d=await this.handleTokenResult(c,l,O(this.options,l));return d.session_state=o.session_state,this.synchronizer.BroadcastMessageToAllTabs(t.USER_LOGIN,d),h}async loginCallback(e=null==window?void 0:null===(_=window.location)||void 0===_?void 0:_.href){let i;if(!e)return Promise.reject(new s("Url must be passed to handle login redirect"));try{i=new URL(e)}catch(t){return Promise.reject(new s(`Invalid callback url passed: "${e}"`))}let o=function(e){let t={};e=e.trim().replace(/^(\?|#|&)/,"");let i=e.split("&");for(let e=0;e<i.length;e+=1){let s=i[e],n=s.split("="),o=decodeURIComponent(n.shift()),r=n.length>0?n.join("="):"";t[o]=decodeURIComponent(r)}return t}(i.search||i.hash),r=await this.loadState(o.state),{authParams:a,localState:l,request_type:h}=r;switch(e=e||window.location.href,h){case"s":(null==window?void 0:window.frameElement)&&e&&window.parent.postMessage({type:"authorization_response",response:o,state:r},`${location.protocol}//${location.host}`);return;case"p":window.opener&&e&&window.opener.postMessage({type:"authorization_response",response:o,state:r},`${location.protocol}//${location.host}`);return;default:if(o.error)return Promise.reject(new n(o.error,o.error_description));let c=await this.handleAuthResponse(o,a,l),d=await this.handleTokenResult(c,a,O(this.options,a));return d.session_state=o.session_state,this.synchronizer.BroadcastMessageToAllTabs(t.USER_LOGIN,d),l}}async logout(e={}){if(!e.localOnly){let t=await this.authStore.get("auth"),i=e.id_token_hint||(null==t?void 0:t.id_token_raw);window.location.assign(await this.createLogoutRequest({...e,id_token_hint:i}))}await this.authStore.clear()}async revokeToken(e,t="access_token",i={}){if(!this.options.endpoints.revocation_endpoint)return Promise.reject(new s('"revocation_endpoint" doesn\'t exist'));let n={client_id:i.client_id||this.options.client_id,client_secret:i.client_secret||this.options.client_secret,token_type_hint:t,token:e};return this.http({method:"POST",requestType:"form",url:this.options.endpoints.revocation_endpoint,body:n})}async silentLogin(e={},i={}){let o;await this.initialize(!1);let r={},a=await this.authStore.get("auth")||{},l=O({response_mode:"query",display:"page",prompt:"none"},this.options,e);if(l.silent_redirect_uri&&(l.redirect_uri=l.silent_redirect_uri),this.options.useRefreshToken&&(null==a?void 0:a.refresh_token))r.authParams=O((null==a?void 0:a.authParams)||{},r.authParams||{}),o=await this.exchangeRefreshToken({...l,refresh_token:a.refresh_token});else{var h;let e=await this.createAuthRequest({...l,request_type:"s"},i),{response:t,state:c}=await (h={timeout:l.silentRequestTimeout,eventOrigin:window.location.origin},new Promise((t,i)=>{let o=null,r=w(),a=setTimeout(()=>{i(new s("Timed out")),c()},1e3*(h.timeout||10)),l=e=>{if(e.origin!=h.eventOrigin||!e.data||"authorization_response"!==e.data.type)return;let s=e.source;s&&s.close();let o=e.data.response||e.data;o.error?i(new n(o.error,o.error_description,o.state,o.error_uri)):t(e.data),clearTimeout(a),c()},c=()=>{null!=o&&clearTimeout(o),window.document.body.contains(r)&&window.document.body.removeChild(r),window.removeEventListener("message",l,!1)},d=()=>setTimeout(()=>{i(new s("Could not complete silent authentication",e)),c()},300);window.addEventListener("message",l,!1),window.document.body.appendChild(r),r.setAttribute("src",e),r.onload=function(){o=d()}}));o=await this.handleAuthResponse(t,l,i),a.session_state=t.session_state,r=c}let c=await this.handleTokenResult(o,r.authParams,l);return c.session_state=a.session_state,this.synchronizer.BroadcastMessageToAllTabs(t.USER_LOGIN,c),r.localState}async getAccessToken(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.access_token}async getRefreshToken(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.refresh_token}async getIdToken(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.id_token}async getExpiresAt(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.expires_at}async getIdTokenRaw(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.id_token_raw}async getScopes(){var e,t;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:null===(t=e.scope)||void 0===t?void 0:t.split(" ")}async getUser(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.user}async isLoggedIn(e=!1){let t=!!await this.getUser();if(!t&&!e)try{return await this.silentLogin(),!0}catch(e){return!1}return t}async createAuthRequest(e={},t={}){var i,n;(null===(i=this.options.endpoints)||void 0===i?void 0:i.authorization_endpoint)||await this.initialize(!1);let o=Object.assign({},this.options,e);t.code_verifier=b(72);let r={client_id:o.client_id,state:b(10),scope:o.scope,audience:o.audience,redirect_uri:o.redirect_uri,response_mode:o.response_mode,response_type:o.response_type||"code",ui_locales:o.ui_locales,prompt:o.prompt,display:o.display,claims:o.claims,claims_locales:o.claims_locales,acr_values:o.acr_values,registration:o.registration,login_hint:o.login_hint,id_token_hint:o.id_token_hint,web_message_uri:o.web_message_uri,web_message_target:o.web_message_target,...o.extraParams&&o.extraParams};($("id_token",r.response_type)||x("openid",r.scope))&&(r.nonce=b(10)),$("code",r.response_type)&&(r.code_challenge=await ((n=t.code_verifier).length<43||n.length>128?Promise.reject(new s(`Invalid code length: ${n.length}`)):new Promise((e,t)=>{crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)).then(t=>e(function(e){let t=function(e){for(var t,i=e.length,s=i%3,n=[],o=0,r=i-s;o<r;o+=16383)n.push(function(e,t,i){for(var s,n=[],o=t;o<i;o+=3)n.push(f[(s=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]))>>18&63]+f[s>>12&63]+f[s>>6&63]+f[63&s]);return n.join("")}(e,o,o+16383>r?r:o+16383));return 1===s?n.push(f[(t=e[i-1])>>2]+f[t<<4&63]+"=="):2===s&&n.push(f[(t=(e[i-2]<<8)+e[i-1])>>10]+f[t>>4&63]+f[t<<2&63]+"="),n.join("")}(new Uint8Array(e));return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}(new Uint8Array(t))),function(e){return t(e)})})),r.code_challenge_method=o.code_challenge_method||"S256");let a=this.options.currentTimeInMillis&&this.options.currentTimeInMillis()||Date.now(),l=o.fragment?`#${o.fragment}`:"",h=y(r),c=`${this.options.endpoints.authorization_endpoint}${h}${l}`;return this.stateStore.clear(a-864e5),await this.stateStore.set(r.state,JSON.parse(JSON.stringify({created_at:a,authParams:r,localState:t,request_type:o.request_type}))),c}async createLogoutRequest(e={}){var t;(null===(t=this.options.endpoints)||void 0===t?void 0:t.end_session_endpoint)||await this.fetchFromIssuer();let i=O(this.options,e),s={id_token_hint:i.id_token_hint,post_logout_redirect_uri:i.post_logout_redirect_uri,...i.extraLogoutParams||{}};return`${this.options.endpoints.end_session_endpoint}${y(s)}`}async exchangeAuthorizationCode(e){var t;(null===(t=this.options.endpoints)||void 0===t?void 0:t.token_endpoint)||await this.fetchFromIssuer();let i=O(this.options,e),{extraTokenHeaders:s,extraTokenParams:n,...o}=i,r={...o,...n||{},grant_type:"authorization_code"};for(let e of["code","redirect_uri","code_verifier","client_id"])if(!r[e])return Promise.reject(Error(`"${e}" is required`));return this.http({url:`${this.options.endpoints.token_endpoint}`,method:"POST",requestType:"form",body:r,headers:s})}async exchangeRefreshToken(e){var t;(null===(t=this.options.endpoints)||void 0===t?void 0:t.token_endpoint)||await this.fetchFromIssuer();let{extraTokenHeaders:i,extraTokenParams:s,...n}=e,o={grant_type:"refresh_token",client_id:this.options.client_id,client_secret:this.options.client_secret,...n,...s||{}};for(let e of["refresh_token","client_id"])if(!o[e])return Promise.reject(Error(`"${e}" is required`));return this.http({url:`${this.options.endpoints.token_endpoint}`,method:"POST",requestType:"form",body:o,headers:i})}async fetchFromIssuer(){try{let e=`${this.options.issuer}/.well-known/openid-configuration`,t=await this.http({url:e,method:"GET",requestType:"json"});this.issuer_metadata=t;let i={};for(let e of Object.keys(this.issuer_metadata))(e.endsWith("_endpoint")||e.indexOf("_session")>-1||e.indexOf("_uri")>-1)&&(i[e]=this.issuer_metadata[e]);return this.options.endpoints=i,this.issuer_metadata}catch(e){throw new s("Loading metadata failed",e.message)}}async handleAuthResponse(e,t,i={}){return e.code?this.exchangeAuthorizationCode({redirect_uri:t.redirect_uri,client_id:t.client_id,code_verifier:i.code_verifier,grant_type:"authorization_code",code:e.code}):e}async handleTokenResult(e,t,i){let a;await this.initialize(!1);let l={};if(e.error)throw new n(e.error,e.error_description);if(e.id_token){if(a=await function(e,t,i){if(!t)throw new s("No nonce on state");try{let s=E(e);if(t!==s.payload.nonce)throw Error(`Invalid nonce in id_token: ${s.payload.nonce}`);if(function(e,t,i=!1){let{clockSkew:s,currentTimeInMillis:n,issuer:r,audience:a,client_id:l}=t;s||(s=0);let h=(n&&n()||Date.now())/1e3,c=E(e).payload;if(!c.iss)throw new o("Issuer (iss) was not provided");if(c.iss!==r)throw new o(`Invalid Issuer (iss) in token: ${c.iss}`);if(!c.aud)throw new o("Audience (aud) was not provided");if(Array.isArray(c.aud)?-1==c.aud.indexOf(i?l:a||l):c.aud!==(i?l:a||l))throw new o(`Invalid Audience (aud) in token: ${c.aud}`);if(c.azp&&c.azp!==l)throw new o(`Invalid Authorized Party (azp) in token: ${c.azp}`);let d=Math.ceil(h+s),u=Math.floor(h-s);if(!c.iat)throw new o("Issued At (iat) was not provided");if(d<Number(c.iat))throw new o(`Issued At (iat) is in the future: ${c.iat}`);if(c.nbf&&d<Number(c.nbf))throw new o(`Not Before time (nbf) is in the future: ${c.nbf}`);if(!c.exp)throw new o("Expiration Time (exp) was not provided");if(Number(c.exp)<u)throw new o(`Expiration Time (exp) is in the past: ${c.exp}`)}(e,i,!0),!s.payload.sub)throw Error("No Subject (sub) present in id_token");return s.payload}catch(e){throw new r(e.message)}}(e.id_token,t.nonce,i),i.idTokenValidator&&!await i.idTokenValidator(e.id_token))return Promise.reject(new r("Id Token validation failed"));Object.keys(a).forEach(e=>{I.includes(e)||(l[e]=a[e])})}if(e.access_token){var h;if(i.requestUserInfo&&(null===(h=this.options.endpoints)||void 0===h?void 0:h.userinfo_endpoint)){let t=await this.fetchUserInfo(e.access_token);t.error||(l={...l,...t})}}return{authParams:t,user:l,...e,id_token:a,id_token_raw:e.id_token,scope:e.scope||t.scope}}async loadState(e){let t=await this.stateStore.get(e);return t?(await this.stateStore.del(e),t):Promise.reject(new n(`State not found: ${e}`))}async fetchUserInfo(e){return this.http({method:"GET",url:`${this.options.endpoints.userinfo_endpoint}`,requestType:"json",headers:{Authorization:`Bearer ${e}`}})}monitorSession({sub:e,session_state:i}){let{client_id:s,endpoints:n}=this.options;if(!(null==n?void 0:n.check_session_iframe)){console.warn('"check_session_iframe" endpoint missing or session management is not supported by provider');return}if(!this.sessionCheckerFrame){let i=async i=>{if(i)this.emit(t.USER_LOGOUT);else{this.emit(t.SESSION_CHANGE);try{await this.silentLogin({},{});let i=await this.authStore.get("auth");if(i){var s;(null===(s=i.user)||void 0===s?void 0:s.sub)===e&&i.session_state&&this.sessionCheckerFrame.start(i.session_state)}else this.emit(t.USER_LOGOUT,null)}catch(e){this.emit(t.USER_LOGOUT);return}}};this.sessionCheckerFrame=function(e){let t,i;let{url:s,callback:n,client_id:o,checkInterval:r}=e,a=s.indexOf("/",s.indexOf("//")+2),l=s.substr(0,a),h=w(),c=()=>new Promise(e=>{window.document.body.appendChild(h),window.addEventListener("message",p,!1),h.onload=()=>{e(null)}}),d=e=>{c().then(()=>{if(e&&t!==e){u(),t=e;let s=()=>{h.contentWindow.postMessage(`${o} ${t}`,l)};s(),i=window.setInterval(s,r||2e3)}})},u=()=>{t=null,i&&(window.clearInterval(i),i=null)},p=e=>{e.origin===l&&e.source===h.contentWindow&&("error"===e.data?(u(),n(e.data)):"changed"===e.data&&(u(),n()))};return h.setAttribute("src",s),{stop:u,start:d}}({url:n.check_session_iframe,client_id:s,callback:i,checkInterval:this.options.checkSessionInterval})}this.sessionCheckerFrame.start(i)}async onUserLogin(e){let{expires_in:i,user:s,scope:n,access_token:o,id_token:r,refresh_token:a,session_state:l,id_token_raw:h}=e;if(await this.authStore.set("auth",e),this.user=s,this.scopes=null==n?void 0:n.split(" "),this.accessToken=o,this.idToken=r,this.idTokenRaw=h,this.refreshToken=a,this.emit(t.USER_LOGIN,e),!(null==window?void 0:window.frameElement)&&(this.options.checkSession&&this.monitorSession({sub:s.sub||s.id,session_state:l}),void 0!==i&&this.options.autoSilentRenew)){let e=Number(i)-this.options.secondsToRefreshAccessTokenBeforeExp;e>=0&&this._accessTokenExpireTimer.start(e,async()=>{this.synchronizer.CallOnce("silent-login",async()=>{try{await this.silentLogin(),this.emit(t.SILENT_RENEW_SUCCESS,null)}catch(e){this.emit(t.SILENT_RENEW_ERROR,e)}})})}}constructor(e){if(super(),j(this,"options",void 0),j(this,"user",void 0),j(this,"scopes",void 0),j(this,"accessToken",void 0),j(this,"refreshToken",void 0),j(this,"idToken",void 0),j(this,"idTokenRaw",void 0),j(this,"issuer_metadata",void 0),j(this,"http",void 0),j(this,"synchronizer",void 0),j(this,"stateStore",void 0),j(this,"authStore",void 0),j(this,"sessionCheckerFrame",void 0),j(this,"_accessTokenExpireTimer",void 0),j(this,"initialized",void 0),j(this,"__initializePromise",void 0),!function(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||""!==t.search||""!==t.hash)return!1;return!0}catch(e){return!1}}(e.issuer))throw new s('"issuer" must be a valid uri.');this.synchronizer=new A(btoa(e.issuer)),this.options=O({secondsToRefreshAccessTokenBeforeExp:60,autoSilentRenew:!0,checkSession:!0},e,{issuer:e.issuer.endsWith("/")?e.issuer.slice(0,-1):e.issuer}),this.http=this.options.httpClient||S,this.stateStore=this.options.stateStore||new h("pa_oidc.state."),this.authStore=this.options.authStore||new c,this.options.autoSilentRenew&&(this._accessTokenExpireTimer=new p),this.on(t.USER_LOGOUT,async()=>{this.user=void 0,this.scopes=void 0,this.accessToken=void 0,this.idToken=void 0,this.refreshToken=void 0,await this.authStore.clear()}),this.synchronizer.OnBroadcastMessage(t.USER_LOGIN,this.onUserLogin.bind(this))}}e.AuthenticationError=n,e.EventEmitter=d,e.Events=t,e.InMemoryStateStore=c,e.InteractionCancelled=a,e.InvalidIdTokenError=r,e.InvalidJWTError=o,e.LocalStorageStateStore=h,e.OIDCClient=z,e.OIDCClientError=s,e.StateStore=l,e.default=function(e){return new z(e).initialize()},Object.defineProperty(e,"__esModule",{value:!0})});
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).PlusAuthOIDCClient={})}(this,function(e){"use strict";let t={USER_LOGOUT:"user_logout",USER_LOGIN:"user_login",SILENT_RENEW_SUCCESS:"silent_renew_success",SILENT_RENEW_ERROR:"silent_renew_error",SESSION_CHANGE:"session_change"};function i(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class s extends Error{constructor(e,t){super(`${e}${t&&` - ${t}`||""}`),i(this,"error",void 0),i(this,"error_description",void 0),this.name="OIDCClientError",this.error=e,this.error_description=t}}class n extends s{constructor(e,t,s,n){super(e,t),i(this,"state",void 0),i(this,"error_uri",void 0),this.name="AuthenticationError",this.state=s,this.error_uri=n}}class o extends s{constructor(e){super(e),this.name="InvalidJWTError",this.error_description=e}}class r extends o{constructor(e){super(e),this.name="InvalidIdTokenError"}}class a extends s{constructor(e){super(e),this.name="InteractionCancelled"}}class l{constructor(e=""){var t,i,s;t=this,s=void 0,(i="prefix")in t?Object.defineProperty(t,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[i]=s,this.prefix=e}}class c extends l{get(e){return new Promise(t=>{let i=window.localStorage.getItem(this.prefix+e);t(i?JSON.parse(i):null)})}set(e,t){return new Promise(i=>{window.localStorage.setItem(this.prefix+e,JSON.stringify(t)),i()})}del(e){return new Promise(t=>{window.localStorage.removeItem(this.prefix+e),t()})}clear(e){return new Promise(t=>{let i;let s=[];for(i=0;i<window.localStorage.length;i++){let e=window.localStorage.key(i);(null==e?void 0:e.substring(0,this.prefix.length))==this.prefix&&s.push(e)}for(i=0;i<s.length;i++)if(e)try{let t=JSON.parse(window.localStorage.getItem(s[i]));t.created_at<e&&window.localStorage.removeItem(s[i])}catch(e){}else window.localStorage.removeItem(s[i]);t()})}constructor(e="pa_oidc."){super(e)}}class h extends l{clear(e){return e?(this.map.forEach((t,i)=>{t.created_at<e&&this.map.delete(i)}),Promise.resolve()):Promise.resolve(this.map.clear())}del(e){return this.map.delete(e),Promise.resolve()}get(e){return Promise.resolve(this.map.get(e)||null)}set(e,t){return this.map.set(e,t),Promise.resolve()}constructor(...e){var t,i;super(...e),t=this,i=new Map,"map"in t?Object.defineProperty(t,"map",{value:i,enumerable:!0,configurable:!0,writable:!0}):t.map=i}}class d{once(e,t){function i(...s){this.off(e,i),t.apply(this,s)}return i.fn=t,this.on(e,i),this}on(e,t){return this.callbacks[`$${e}`]||(this.callbacks[`$${e}`]=[]),this.callbacks[`$${e}`].push(t),this}off(e,t){if(!e)return this.callbacks={},this;let i=this.callbacks[`$${e}`];if(!i)return this;if(!t)return delete this.callbacks[`$${e}`],this;for(let e=0;e<i.length;e++){let s=i[e];if(s===t||s.fn===t){i.splice(e,1);break}}return 0===i.length&&delete this.callbacks[`$${e}`],this}emit(e,...t){let i=this.callbacks[`$${e}`];if(i){i=i.slice(0);for(let e=0,s=i.length;e<s;++e)i[e].apply(this,t)}return this}constructor(){var e,t,i;e=this,i=void 0,(t="callbacks")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,this.callbacks={}}}function u(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class p{start(e,t){e<=0&&(e=1);let i=this.now()/1e3+e;if(this._expiration===i&&this._timerHandle)return;this.stop(),this._expiration=i;let s=5;e<5&&(s=e),this._timerHandle=setInterval(()=>{this._expiration<=this.now()/1e3&&(this.stop(),t())},1e3*s)}stop(){this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}constructor(e=()=>Date.now()){u(this,"now",void 0),u(this,"_timerHandle",void 0),u(this,"_expiration",void 0),this.now=e}}function w(){let e=window.document.createElement("iframe");return e.style.width="0",e.style.height="0",e.style.position="absolute",e.style.visibility="hidden",e.style.display="none",e.title="__pa_helper__hidden",e.ariaHidden="true",e}for(var _,f=[],m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g=0,v=m.length;g<v;++g)f[g]=m[g];function y(e,t=!0){if(!e)return"";let i=[];for(let t in e)e.hasOwnProperty(t)&&e[t]&&i.push(`${encodeURIComponent(t)}=${encodeURIComponent("object"==typeof e[t]?JSON.stringify(e[t]):e[t])}`);return`${t?"?":""}${i.join("&")}`}function S(e){let t=null,i=e.headers||{};return"POST"===e.method&&(i={"Content-Type":"form"===e.requestType?"application/x-www-form-urlencoded;charset=UTF-8":"application/json;charset=UTF-8",...i}),e.body&&(t="form"===e.requestType?y(e.body,!1):JSON.stringify(e.body)),new Promise((s,n)=>{fetch(e.url,{method:e.method,body:t,headers:i}).then(e=>s(e.json())).catch(n)})}let k="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function b(e){let t="",i=k.length,s=256-256%i;for(;e>0;){let n=function(e){let t=self.crypto||self.msCrypto,i=new Uint8Array(e);for(let s=0;s<e;s+=65536)t.getRandomValues(i.subarray(s,s+Math.min(e-s,65536)));return i}(Math.ceil(256*e/s));for(let o=0;o<n.length&&e>0;o++){let r=n[o];r<s&&(t+=k.charAt(r%i),e--)}}return t}let T=e=>decodeURIComponent(atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""));function E(e){try{let t=e.split(".");if(3!==t.length)throw Error("Wrong JWT format");return{header:JSON.parse(T(t[0])),payload:JSON.parse(T(t[1]))}}catch(e){throw new o("Failed to parse jwt")}}let I=["iss","aud","exp","nbf","iat","jti","azp","nonce","auth_time","at_hash","c_hash","acr","amr","sub_jwk","cnf","sip_from_tag","sip_date","sip_callid","sip_cseq_num","sip_via_branch","orig","dest","mky","events","toe","txn","rph","sid","vot","vtm","attest","origid","act","scope","client_id","may_act","jcard","at_use_nbr"];function O(...e){return e.reduce((e,t)=>(function e(t,i){for(let s in i)void 0!==i[s]&&("object"==typeof i[s]&&"Object"===i[s].constructor.name?t[s]=e(t[s]||{},i[s]):t[s]=i[s]);return t})(e||{},t),{})}let $=(e,t)=>t&&t.split(/\s+/g).filter(t=>t===e).length>0,x=(e,t)=>t&&t.split(" ").indexOf(e)>-1,R=(e,t=400,i=600)=>{let s=window.screenX+(window.innerWidth-t)/2,n=window.screenY+(window.innerHeight-i)/2;return window.open(e,"oidc-login-popup",`left=${s},top=${n},width=${t},height=${i},resizable,scrollbars=yes,status=1`)},P=`${performance.now()}:${1e9*Math.random()|0}`,C={};class j{CallOnce(e,t,i=3e3){if(!e)throw"empty lockname";if(!window.localStorage){t();return}let s=this.keyPrefix+e;localStorage.setItem(s,P),setTimeout(()=>{localStorage.getItem(s)==P&&t()},150),setTimeout(function(){localStorage.removeItem(s)},i)}BroadcastMessageToAllTabs(e,t){try{C[e](t)}catch(e){}if(!window.localStorage)return;let i={data:t,timeStamp:new Date().getTime()};localStorage.setItem(`${this.keyPrefix}event${e}`,JSON.stringify(i)),setTimeout(()=>{localStorage.removeItem(`${this.keyPrefix}event${e}`)},3e3)}OnBroadcastMessage(e,t){C[e]=t,window.localStorage&&window.addEventListener("storage",i=>{if(i.key!=`${this.keyPrefix}event${e}`||!i.newValue)return;let s=JSON.parse(i.newValue);t(s.data)})}constructor(e){var t,i,s;t=this,s=void 0,(i="keyPrefix")in t?Object.defineProperty(t,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[i]=s,this.keyPrefix=e}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class z extends d{async initialize(e=!0){return this.initialized?this:(this.__initializePromise||(this.__initializePromise=new Promise(async(i,n)=>{try{this.stateStore.init&&await this.stateStore.init(),this.authStore.init&&await this.authStore.init(),this.options.endpoints&&0!==Object.keys(this.options.endpoints).length||await this.fetchFromIssuer(),this.initialized=!0;try{!e||(null==window?void 0:window.frameElement)||await this.silentLogin()}catch(e){this.emit(t.SILENT_RENEW_ERROR,e),await this.authStore.clear()}i(this)}catch(e){n(e instanceof s?e:new s(e.message))}finally{this.__initializePromise=void 0}})),this.__initializePromise)}async login(e={},t={}){window.location.assign(await this.createAuthRequest(e,t))}async loginWithPopup(e={},i={}){let n=await this.createAuthRequest({response_mode:"fragment",...e,display:"popup",request_type:"p"}),{response:o,state:r}=await function(e,t){let i,n,o=t.popup;if(o?o.location.href=e:o=R(e),!o)throw Error("Could not open popup");return new Promise((e,r)=>{function l(){clearInterval(n),clearTimeout(i),window.removeEventListener("message",c)}function c(t){if(!t.data||"authorization_response"!==t.data.type)return;l(),o.close();let i=t.data.response||t.data;i.error?r(new s(i.error,i.error_description)):e(t.data)}i=setTimeout(()=>{l(),r(new s("Timed out"))},t.timeout||6e4),n=setInterval(function(){o.closed&&(l(),r(new a("user closed popup")))},300),window.addEventListener("message",c)})}(n,i),{authParams:l,localState:c}=r&&"string"!=typeof r?r:await this.loadState(r||o.state),h=await this.handleAuthResponse(o,l,c),d=await this.handleTokenResult(h,l,O(this.options,l));return d.session_state=o.session_state,this.synchronizer.BroadcastMessageToAllTabs(t.USER_LOGIN,d),c}async loginCallback(e=null==window?void 0:null===(_=window.location)||void 0===_?void 0:_.href){let i;if(!e)return Promise.reject(new s("Url must be passed to handle login redirect"));try{i=new URL(e)}catch(t){return Promise.reject(new s(`Invalid callback url passed: "${e}"`))}let o=function(e){let t={};e=e.trim().replace(/^(\?|#|&)/,"");let i=e.split("&");for(let e=0;e<i.length;e+=1){let s=i[e],n=s.split("="),o=decodeURIComponent(n.shift()),r=n.length>0?n.join("="):"";t[o]=decodeURIComponent(r)}return t}(i.search||i.hash),r=await this.loadState(o.state),{authParams:a,localState:l,request_type:c}=r;switch(e=e||window.location.href,c){case"s":(null==window?void 0:window.frameElement)&&e&&window.parent.postMessage({type:"authorization_response",response:o,state:r},`${location.protocol}//${location.host}`);return;case"p":window.opener&&e&&window.opener.postMessage({type:"authorization_response",response:o,state:r},`${location.protocol}//${location.host}`);return;default:if(o.error)return Promise.reject(new n(o.error,o.error_description));let h=await this.handleAuthResponse(o,a,l),d=await this.handleTokenResult(h,a,O(this.options,a));return d.session_state=o.session_state,this.synchronizer.BroadcastMessageToAllTabs(t.USER_LOGIN,d),l}}async logout(e={}){if(!e.localOnly){let t=await this.authStore.get("auth"),i=e.id_token_hint||(null==t?void 0:t.id_token_raw);window.location.assign(await this.createLogoutRequest({...e,id_token_hint:i}))}await this.authStore.clear()}async revokeToken(e,t="access_token",i={}){if(!this.options.endpoints.revocation_endpoint)return Promise.reject(new s('"revocation_endpoint" doesn\'t exist'));let n={client_id:i.client_id||this.options.client_id,client_secret:i.client_secret||this.options.client_secret,token_type_hint:t,token:e};return this.http({method:"POST",requestType:"form",url:this.options.endpoints.revocation_endpoint,body:n})}async silentLogin(e={},i={}){let o;await this.initialize(!1);let r={},a=await this.authStore.get("auth")||{},l=O({response_mode:"query",display:"page",prompt:"none"},this.options,e);if(l.silent_redirect_uri&&(l.redirect_uri=l.silent_redirect_uri),this.options.useRefreshToken&&(null==a?void 0:a.refresh_token))r.authParams=O((null==a?void 0:a.authParams)||{},r.authParams||{}),o=await this.exchangeRefreshToken({...l,refresh_token:a.refresh_token});else{var c;let e=await this.createAuthRequest({...l,request_type:"s"},i),{response:t,state:h}=await (c={timeout:l.silentRequestTimeout,eventOrigin:window.location.origin},new Promise((t,i)=>{let o=null,r=w(),a=setTimeout(()=>{i(new s("Timed out")),h()},1e3*(c.timeout||10)),l=e=>{if(e.origin!=c.eventOrigin||!e.data||"authorization_response"!==e.data.type)return;let s=e.source;s&&s.close();let o=e.data.response||e.data;o.error?i(new n(o.error,o.error_description,o.state,o.error_uri)):t(e.data),clearTimeout(a),h()},h=()=>{null!=o&&clearTimeout(o),window.document.body.contains(r)&&window.document.body.removeChild(r),window.removeEventListener("message",l,!1)},d=()=>setTimeout(()=>{i(new s("Could not complete silent authentication",e)),h()},300);window.addEventListener("message",l,!1),window.document.body.appendChild(r),r.setAttribute("src",e),r.onload=function(){o=d()}}));o=await this.handleAuthResponse(t,l,i),a.session_state=t.session_state,r=h}let h=await this.handleTokenResult(o,r.authParams,l);return h.session_state=a.session_state,this.synchronizer.BroadcastMessageToAllTabs(t.USER_LOGIN,h),r.localState}async getAccessToken(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.access_token}async getRefreshToken(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.refresh_token}async getIdToken(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.id_token}async getExpiresAt(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.expires_at}async getIdTokenRaw(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.id_token_raw}async getScopes(){var e,t;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:null===(t=e.scope)||void 0===t?void 0:t.split(" ")}async getUser(){var e;return null===(e=await this.authStore.get("auth"))||void 0===e?void 0:e.user}async isLoggedIn(e=!1){let t=!!await this.getUser();if(!t&&!e)try{return await this.silentLogin(),!0}catch(e){return!1}return t}async createAuthRequest(e={},t={}){var i,n;(null===(i=this.options.endpoints)||void 0===i?void 0:i.authorization_endpoint)||await this.initialize(!1);let o=Object.assign({},this.options,e);t.code_verifier=b(72);let r={client_id:o.client_id,state:b(10),scope:o.scope,audience:o.audience,redirect_uri:o.redirect_uri,response_mode:o.response_mode,response_type:o.response_type||"code",ui_locales:o.ui_locales,prompt:o.prompt,display:o.display,claims:o.claims,claims_locales:o.claims_locales,acr_values:o.acr_values,registration:o.registration,login_hint:o.login_hint,id_token_hint:o.id_token_hint,web_message_uri:o.web_message_uri,web_message_target:o.web_message_target,...o.extraParams&&o.extraParams};($("id_token",r.response_type)||x("openid",r.scope))&&(r.nonce=b(10)),$("code",r.response_type)&&(r.code_challenge=await ((n=t.code_verifier).length<43||n.length>128?Promise.reject(new s(`Invalid code length: ${n.length}`)):new Promise((e,t)=>{crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)).then(t=>e(function(e){let t=function(e){for(var t,i=e.length,s=i%3,n=[],o=0,r=i-s;o<r;o+=16383)n.push(function(e,t,i){for(var s,n=[],o=t;o<i;o+=3)n.push(f[(s=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]))>>18&63]+f[s>>12&63]+f[s>>6&63]+f[63&s]);return n.join("")}(e,o,o+16383>r?r:o+16383));return 1===s?n.push(f[(t=e[i-1])>>2]+f[t<<4&63]+"=="):2===s&&n.push(f[(t=(e[i-2]<<8)+e[i-1])>>10]+f[t>>4&63]+f[t<<2&63]+"="),n.join("")}(new Uint8Array(e));return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}(new Uint8Array(t))),function(e){return t(e)})})),r.code_challenge_method=o.code_challenge_method||"S256");let a=this.options.currentTimeInMillis&&this.options.currentTimeInMillis()||Date.now(),l=o.fragment?`#${o.fragment}`:"",c=y(r),h=`${this.options.endpoints.authorization_endpoint}${c}${l}`;return this.stateStore.clear(a-864e5),await this.stateStore.set(r.state,JSON.parse(JSON.stringify({created_at:a,authParams:r,localState:t,request_type:o.request_type}))),h}async createLogoutRequest(e={}){var t;(null===(t=this.options.endpoints)||void 0===t?void 0:t.end_session_endpoint)||await this.fetchFromIssuer();let i=O(this.options,e),s={id_token_hint:i.id_token_hint,post_logout_redirect_uri:i.post_logout_redirect_uri,...i.extraLogoutParams||{}};return`${this.options.endpoints.end_session_endpoint}${y(s)}`}async exchangeAuthorizationCode(e){var t;(null===(t=this.options.endpoints)||void 0===t?void 0:t.token_endpoint)||await this.fetchFromIssuer();let i=O(this.options,e),{extraTokenHeaders:s,extraTokenParams:n,...o}=i,r={...o,...n||{},grant_type:"authorization_code"};for(let e of["code","redirect_uri","code_verifier","client_id"])if(!r[e])return Promise.reject(Error(`"${e}" is required`));return this.http({url:`${this.options.endpoints.token_endpoint}`,method:"POST",requestType:"form",body:r,headers:s})}async exchangeRefreshToken(e){var t;(null===(t=this.options.endpoints)||void 0===t?void 0:t.token_endpoint)||await this.fetchFromIssuer();let{extraTokenHeaders:i,extraTokenParams:s,...n}=e,o={grant_type:"refresh_token",client_id:this.options.client_id,client_secret:this.options.client_secret,...n,...s||{}};for(let e of["refresh_token","client_id"])if(!o[e])return Promise.reject(Error(`"${e}" is required`));return this.http({url:`${this.options.endpoints.token_endpoint}`,method:"POST",requestType:"form",body:o,headers:i})}async fetchFromIssuer(){try{let e=`${this.options.issuer}/.well-known/openid-configuration`,t=await this.http({url:e,method:"GET",requestType:"json"});this.issuer_metadata=t;let i={};for(let e of Object.keys(this.issuer_metadata))(e.endsWith("_endpoint")||e.indexOf("_session")>-1||e.indexOf("_uri")>-1)&&(i[e]=this.issuer_metadata[e]);return this.options.endpoints=i,this.issuer_metadata}catch(e){throw new s("Loading metadata failed",e.message)}}async handleAuthResponse(e,t,i={}){return e.code?this.exchangeAuthorizationCode({redirect_uri:t.redirect_uri,client_id:t.client_id,code_verifier:i.code_verifier,grant_type:"authorization_code",code:e.code}):e}async handleTokenResult(e,t,i){let a;await this.initialize(!1);let l={};if(e.error)throw new n(e.error,e.error_description);if(e.id_token){if(a=await function(e,t,i){if(!t)throw new s("No nonce on state");try{let s=E(e);if(t!==s.payload.nonce)throw Error(`Invalid nonce in id_token: ${s.payload.nonce}`);if(function(e,t,i=!1){let{clockSkew:s,currentTimeInMillis:n,issuer:r,audience:a,client_id:l}=t;s||(s=0);let c=(n&&n()||Date.now())/1e3,h=E(e).payload;if(!h.iss)throw new o("Issuer (iss) was not provided");if(h.iss!==r)throw new o(`Invalid Issuer (iss) in token: ${h.iss}`);if(!h.aud)throw new o("Audience (aud) was not provided");if(Array.isArray(h.aud)?-1==h.aud.indexOf(i?l:a||l):h.aud!==(i?l:a||l))throw new o(`Invalid Audience (aud) in token: ${h.aud}`);if(h.azp&&h.azp!==l)throw new o(`Invalid Authorized Party (azp) in token: ${h.azp}`);let d=Math.ceil(c+s),u=Math.floor(c-s);if(!h.iat)throw new o("Issued At (iat) was not provided");if(d<Number(h.iat))throw new o(`Issued At (iat) is in the future: ${h.iat}`);if(h.nbf&&d<Number(h.nbf))throw new o(`Not Before time (nbf) is in the future: ${h.nbf}`);if(!h.exp)throw new o("Expiration Time (exp) was not provided");if(Number(h.exp)<u)throw new o(`Expiration Time (exp) is in the past: ${h.exp}`)}(e,i,!0),!s.payload.sub)throw Error("No Subject (sub) present in id_token");return s.payload}catch(e){throw new r(e.message)}}(e.id_token,t.nonce,i),i.idTokenValidator&&!await i.idTokenValidator(e.id_token))return Promise.reject(new r("Id Token validation failed"));Object.keys(a).forEach(e=>{I.includes(e)||(l[e]=a[e])})}if(e.access_token){var c;if(i.requestUserInfo&&(null===(c=this.options.endpoints)||void 0===c?void 0:c.userinfo_endpoint)){let t=await this.fetchUserInfo(e.access_token);t.error||(l={...l,...t})}}return{authParams:t,user:l,...e,id_token:a,id_token_raw:e.id_token,scope:e.scope||t.scope}}async loadState(e){let t=await this.stateStore.get(e);return t?(await this.stateStore.del(e),t):Promise.reject(new n(`State not found: ${e}`))}async fetchUserInfo(e){return this.http({method:"GET",url:`${this.options.endpoints.userinfo_endpoint}`,requestType:"json",headers:{Authorization:`Bearer ${e}`}})}monitorSession({sub:e,session_state:i}){let{client_id:s,endpoints:n}=this.options;if(!(null==n?void 0:n.check_session_iframe)){console.warn('"check_session_iframe" endpoint missing or session management is not supported by provider');return}if(!this.sessionCheckerFrame){let i=async i=>{if(i)this.emit(t.USER_LOGOUT);else{this.emit(t.SESSION_CHANGE);try{await this.silentLogin({},{});let i=await this.authStore.get("auth");if(i){var s;(null===(s=i.user)||void 0===s?void 0:s.sub)===e&&i.session_state&&this.sessionCheckerFrame.start(i.session_state)}else this.emit(t.USER_LOGOUT,null)}catch(e){this.emit(t.USER_LOGOUT);return}}};this.sessionCheckerFrame=function(e){let t,i;let{url:s,callback:n,client_id:o,checkInterval:r}=e,a=s.indexOf("/",s.indexOf("//")+2),l=s.substr(0,a),c=w(),h=()=>new Promise(e=>{window.document.body.appendChild(c),window.addEventListener("message",p,!1),c.onload=()=>{e(null)}}),d=e=>{h().then(()=>{if(e&&t!==e){u(),t=e;let s=()=>{c.contentWindow.postMessage(`${o} ${t}`,l)};s(),i=window.setInterval(s,r||2e3)}})},u=()=>{t=null,i&&(window.clearInterval(i),i=null)},p=e=>{e.origin===l&&e.source===c.contentWindow&&("error"===e.data?(u(),n(e.data)):"changed"===e.data&&(u(),n()))};return c.setAttribute("src",s),{stop:u,start:d}}({url:n.check_session_iframe,client_id:s,callback:i,checkInterval:this.options.checkSessionInterval})}this.sessionCheckerFrame.start(i)}async onUserLogin(e){let{expires_in:i,user:s,scope:n,access_token:o,id_token:r,refresh_token:a,session_state:l,id_token_raw:c}=e;if(await this.authStore.set("auth",e),this.user=s,this.scopes=null==n?void 0:n.split(" "),this.accessToken=o,this.idToken=r,this.idTokenRaw=c,this.refreshToken=a,this.emit(t.USER_LOGIN,e),!(null==window?void 0:window.frameElement)&&(this.options.checkSession&&this.monitorSession({sub:s.sub||s.id,session_state:l}),void 0!==i&&this.options.autoSilentRenew)){let e=Number(i)-this.options.secondsToRefreshAccessTokenBeforeExp;e>=0&&this._accessTokenExpireTimer.start(e,async()=>{this.synchronizer.CallOnce("silent-login",async()=>{try{await this.silentLogin(),this.emit(t.SILENT_RENEW_SUCCESS,null)}catch(e){this.emit(t.SILENT_RENEW_ERROR,e)}})})}}constructor(e){if(super(),A(this,"options",void 0),A(this,"user",void 0),A(this,"scopes",void 0),A(this,"accessToken",void 0),A(this,"refreshToken",void 0),A(this,"idToken",void 0),A(this,"idTokenRaw",void 0),A(this,"issuer_metadata",void 0),A(this,"http",void 0),A(this,"synchronizer",void 0),A(this,"stateStore",void 0),A(this,"authStore",void 0),A(this,"sessionCheckerFrame",void 0),A(this,"_accessTokenExpireTimer",void 0),A(this,"initialized",void 0),A(this,"__initializePromise",void 0),!function(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||""!==t.search||""!==t.hash)return!1;return!0}catch(e){return!1}}(e.issuer))throw new s('"issuer" must be a valid uri.');this.synchronizer=new j(btoa(e.issuer)),this.options=O({secondsToRefreshAccessTokenBeforeExp:60,autoSilentRenew:!0,checkSession:!0},e,{issuer:e.issuer.endsWith("/")?e.issuer.slice(0,-1):e.issuer}),this.http=this.options.httpClient||S,this.stateStore=this.options.stateStore||new c("pa_oidc.state."),this.authStore=this.options.authStore||new h,this.options.autoSilentRenew&&(this._accessTokenExpireTimer=new p),this.on(t.USER_LOGOUT,async()=>{this.user=void 0,this.scopes=void 0,this.accessToken=void 0,this.idToken=void 0,this.refreshToken=void 0,await this.authStore.clear()}),this.synchronizer.OnBroadcastMessage(t.USER_LOGIN,this.onUserLogin.bind(this))}}e.AuthenticationError=n,e.EventEmitter=d,e.Events=t,e.InMemoryStateStore=h,e.InteractionCancelled=a,e.InvalidIdTokenError=r,e.InvalidJWTError=o,e.LocalStorageStateStore=c,e.OIDCClient=z,e.OIDCClientError=s,e.StateStore=l,e.default=function(e){return new z(e).initialize()},Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=oidc-client.min.js.map

@@ -114,3 +114,3 @@ declare const Events: {

interface IPlusAuthClientOptions extends Omit<AuthRequestOptions, 'request_type'>, Omit<LogoutRequestOptions, 'localOnly'> {
authStore?: StateStore;
authStore?: StateStore<any>;
/**

@@ -172,3 +172,3 @@ * Enable/disable automatic access token renewal. If enabled, access tokens will be refreshed by using silent

*/
stateStore?: StateStore<StateRecord>;
stateStore?: StateStore<any>;
/**

@@ -175,0 +175,0 @@ * If `true`, refresh tokens will be used for renewing access token. If `false`, authorization request will be

{
"name": "@plusauth/oidc-client-js",
"description": "OpenID Connect (OIDC) and OAuth2 library for browser based JavaScript applications.",
"version": "1.2.4",
"version": "1.2.5",
"homepage": "https://github.com/PlusAuth/oidc-client-js",

@@ -6,0 +6,0 @@ "license": "MIT",

@@ -54,3 +54,3 @@ ## @plusauth/oidc-client-js

```html
<script src="https://unpkg.com/@plusauth/oidc-client-js@1.2.2/dist/oidc-client.min.js"></script>
<script src="https://unpkg.com/@plusauth/oidc-client-js@1.2.3/dist/oidc-client.min.js"></script>
```

@@ -57,0 +57,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc