Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

oidc-client-ts

Package Overview
Dependencies
Maintainers
2
Versions
37
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

oidc-client-ts - npm Package Compare versions

Comparing version 3.0.0-rc.0 to 3.0.0-rc.1

2

dist/browser/oidc-client-ts.min.js

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

"use strict";var oidc=(()=>{var Se=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var We=(a,e)=>{for(var t in e)Se(a,t,{get:e[t],enumerable:!0})},Le=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Me(e))!Ne.call(a,i)&&i!==t&&Se(a,i,{get:()=>e[i],enumerable:!(r=qe(e,i))||r.enumerable});return a};var je=a=>Le(Se({},"__esModule",{value:!0}),a);var rt={};We(rt,{AccessTokenEvents:()=>z,CheckSessionIFrame:()=>B,ErrorResponse:()=>_,ErrorTimeout:()=>P,InMemoryWebStorage:()=>T,Log:()=>F,Logger:()=>l,MetadataService:()=>Q,OidcClient:()=>re,OidcClientSettingsStore:()=>C,SessionMonitor:()=>X,SigninResponse:()=>q,SigninState:()=>O,SignoutResponse:()=>G,State:()=>y,User:()=>M,UserManager:()=>ve,UserManagerSettingsStore:()=>Z,Version:()=>Ie,WebStorageStateStore:()=>A});var He={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},k,x,F=(s=>(s[s.NONE=0]="NONE",s[s.ERROR=1]="ERROR",s[s.WARN=2]="WARN",s[s.INFO=3]="INFO",s[s.DEBUG=4]="DEBUG",s))(F||{});(r=>{function a(){k=3,x=He}r.reset=a;function e(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");k=i}r.setLevel=e;function t(i){x=i}r.setLogger=t})(F||(F={}));var l=class a{constructor(e){this._name=e}debug(...e){k>=4&&x.debug(a._format(this._name,this._method),...e)}info(...e){k>=3&&x.info(a._format(this._name,this._method),...e)}warn(...e){k>=2&&x.warn(a._format(this._name,this._method),...e)}error(...e){k>=1&&x.error(a._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){let t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){let r=new a(`${e}.${t}`);return r.debug("begin"),r}static _format(e,t){let r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(e,...t){k>=4&&x.debug(a._format(e),...t)}static info(e,...t){k>=3&&x.info(a._format(e),...t)}static warn(e,...t){k>=2&&x.warn(a._format(e),...t)}static error(e,...t){k>=1&&x.error(a._format(e),...t)}};F.reset();var Fe="10000000-1000-4000-8000-100000000000",xe=a=>btoa([...new Uint8Array(a)].map(e=>String.fromCharCode(e)).join("")),w=class a{static _randomWord(){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return Fe.replace(/[018]/g,t=>(+t^a._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return a.generateUUIDv4()+a.generateUUIDv4()+a.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{let r=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",r);return xe(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw l.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){let i=new TextEncoder().encode([e,t].join(":"));return xe(i)}};var S=class{constructor(e){this._name=e;this._logger=new l(`Event('${this._name}')`);this._callbacks=[]}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){let t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}raise(...e){this._logger.debug("raise:",...e);for(let t of this._callbacks)t(...e)}};var J=class extends Error{};J.prototype.name="InvalidTokenError";function Je(a){return decodeURIComponent(atob(a).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function De(a){let e=a.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return Je(e)}catch{return atob(e)}}function Pe(a,e){if(typeof a!="string")throw new J("Invalid token specified: must be a string");e||(e={});let t=e.header===!0?0:1,r=a.split(".")[t];if(typeof r!="string")throw new J(`Invalid token specified: missing part #${t+1}`);let i;try{i=De(r)}catch(s){throw new J(`Invalid token specified: invalid base64 for part #${t+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new J(`Invalid token specified: invalid json for part #${t+1} (${s.message})`)}}var D=class{static decode(e){try{return Pe(e)}catch(t){throw l.error("JwtUtils.decode",t),t}}};var ee=class{static center({...e}){var t,r,i;return e.width==null&&(e.width=(t=[800,720,600,480].find(s=>s<=window.outerWidth/1.618))!=null?t:360),(r=e.left)!=null||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),e.height!=null&&((i=e.top)!=null||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,t])=>t!=null).map(([t,r])=>`${t}=${typeof r!="boolean"?r:r?"yes":"no"}`).join(",")}};var m=class a extends S{constructor(){super(...arguments);this._logger=new l(`Timer('${this._name}')`);this._timerHandle=null;this._expiration=0;this._callback=()=>{let t=this._expiration-a.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=a.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){let r=this._logger.create("init");t=Math.max(Math.floor(t),1);let i=a.getEpochTime()+t;if(this.expiration===i&&this._timerHandle){r.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),r.debug("using duration",t),this._expiration=i;let s=Math.min(t,5);this._timerHandle=setInterval(this._callback,s*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}};var K=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");let i=new URL(e,"http://127.0.0.1")[t==="fragment"?"hash":"search"];return new URLSearchParams(i.slice(1))}},te=";";var _=class extends Error{constructor(t,r){var i,s,n;super(t.error_description||t.error||"");this.form=r;this.name="ErrorResponse";if(!t.error)throw l.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=t.error,this.error_description=(i=t.error_description)!=null?i:null,this.error_uri=(s=t.error_uri)!=null?s:null,this.state=t.userState,this.session_state=(n=t.session_state)!=null?n:null,this.url_state=t.url_state}};var P=class extends Error{constructor(t){super(t);this.name="ErrorTimeout"}};var z=class{constructor(e){this._logger=new l("AccessTokenEvents");this._expiringTimer=new m("Access token expiring");this._expiredTimer=new m("Access token expired");this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}load(e){let t=this._logger.create("load");if(e.access_token&&e.expires_in!==void 0){let r=e.expires_in;if(t.debug("access token present, remaining duration:",r),r>0){let s=r-this._expiringNotificationTimeInSeconds;s<=0&&(s=1),t.debug("registering expiring timer, raising in",s,"seconds"),this._expiringTimer.init(s)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();let i=r+1;t.debug("registering expired timer, raising in",i,"seconds"),this._expiredTimer.init(i)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}};var B=class{constructor(e,t,r,i,s){this._callback=e;this._client_id=t;this._intervalInSeconds=i;this._stopOnError=s;this._logger=new l("CheckSessionIFrame");this._timer=null;this._session_state=null;this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data==="error"?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):e.data==="changed"?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};let n=new URL(r);this._frame_origin=n.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=n.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;let t=()=>{!this._frame.contentWindow||!this._session_state||this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,this._intervalInSeconds*1e3)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}};var T=class{constructor(){this._logger=new l("InMemoryWebStorage");this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}};var U=class{constructor(e=[],t=null,r={}){this._jwtHandler=t;this._extraHeaders=r;this._logger=new l("JsonService");this._contentTypes=[];this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){let{timeoutInSeconds:r,...i}=t;if(!r)return await fetch(e,i);let s=new AbortController,n=setTimeout(()=>s.abort(),r*1e3);try{return await fetch(e,{...t,signal:s.signal})}catch(o){throw o instanceof DOMException&&o.name==="AbortError"?new P("Network timed out"):o}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:r}={}){let i=this._logger.create("getJson"),s={Accept:this._contentTypes.join(", ")};t&&(i.debug("token passed, setting Authorization header"),s.Authorization="Bearer "+t),this.appendExtraHeaders(s);let n;try{i.debug("url:",e),n=await this.fetchWithTimeout(e,{method:"GET",headers:s,credentials:r})}catch(d){throw i.error("Network Error"),d}i.debug("HTTP response received, status",n.status);let o=n.headers.get("Content-Type");if(o&&!this._contentTypes.find(d=>o.startsWith(d))&&i.throw(new Error(`Invalid response Content-Type: ${o!=null?o:"undefined"}, from URL: ${e}`)),n.ok&&this._jwtHandler&&(o!=null&&o.startsWith("application/jwt")))return await this._jwtHandler(await n.text());let c;try{c=await n.json()}catch(d){throw i.error("Error parsing JSON response",d),n.ok?d:new Error(`${n.statusText} (${n.status})`)}if(!n.ok)throw i.error("Error from server:",c),c.error?new _(c):new Error(`${n.statusText} (${n.status}): ${JSON.stringify(c)}`);return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:i,initCredentials:s}){let n=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};r!==void 0&&(o.Authorization="Basic "+r),this.appendExtraHeaders(o);let c;try{n.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:i,credentials:s})}catch(p){throw n.error("Network error"),p}n.debug("HTTP response received, status",c.status);let d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(p=>d.startsWith(p)))throw new Error(`Invalid response Content-Type: ${d!=null?d:"undefined"}, from URL: ${e}`);let g=await c.text(),u={};if(g)try{u=JSON.parse(g)}catch(p){throw n.error("Error parsing JSON response",p),c.ok?p:new Error(`${c.statusText} (${c.status})`)}if(!c.ok)throw n.error("Error from server:",u),u.error?new _(u,t):new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`);return u}appendExtraHeaders(e){let t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),i=["authorization","accept","content-type"];r.length!==0&&r.forEach(s=>{if(i.includes(s.toLocaleLowerCase())){t.warn("Protected header could not be overridden",s,i);return}let n=typeof this._extraHeaders[s]=="function"?this._extraHeaders[s]():this._extraHeaders[s];n&&n!==""&&(e[s]=n)})}};var Q=class{constructor(e){this._settings=e;this._logger=new l("MetadataService");this._signingKeys=null;this._metadata=null;this._metadataUrl=this._settings.metadataUrl,this._jsonService=new U(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){let e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);let t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,t),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){let r=this._logger.create(`_getMetadataProperty('${e}')`),i=await this.getMetadata();if(r.debug("resolved"),i[e]===void 0){if(t===!0){r.warn("Metadata does not contain optional property");return}r.throw(new Error("Metadata does not contain property "+e))}return i[e]}async getSigningKeys(){let e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;let t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);let r=await this._jsonService.getJson(t);if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}};var A=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new l("WebStorageStateStore");this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;let t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");let e=await this._store.length,t=[];for(let r=0;r<e;r++){let i=await this._store.key(r);i&&i.indexOf(this._prefix)===0&&t.push(i.substr(this._prefix.length))}return t}};var Ke="code",$e="openid",ze="client_secret_post",Be=60*15,C=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:i,metadataSeed:s,client_id:n,client_secret:o,response_type:c=Ke,scope:d=$e,redirect_uri:g,post_logout_redirect_uri:u,client_authentication:p=ze,prompt:f,display:N,max_age:W,ui_locales:L,acr_values:j,resource:H,response_mode:v,filterProtocolClaims:h=!0,loadUserInfo:R=!1,staleStateAgeInSeconds:I=Be,mergeClaimsStrategy:b={array:"replace"},disablePKCE:$=!1,stateStore:E,revokeTokenAdditionalContentTypes:fe,fetchRequestCredentials:ke,refreshTokenAllowedScope:Ee,extraQueryParams:Te={},extraTokenParams:Ue={},extraHeaders:Ae={}}){if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=r,this.metadataSeed=s,this.signingKeys=i,this.client_id=n,this.client_secret=o,this.response_type=c,this.scope=d,this.redirect_uri=g,this.post_logout_redirect_uri=u,this.client_authentication=p,this.prompt=f,this.display=N,this.max_age=W,this.ui_locales=L,this.acr_values=j,this.resource=H,this.response_mode=v,this.filterProtocolClaims=h!=null?h:!0,this.loadUserInfo=!!R,this.staleStateAgeInSeconds=I,this.mergeClaimsStrategy=b,this.disablePKCE=!!$,this.revokeTokenAdditionalContentTypes=fe,this.fetchRequestCredentials=ke||"same-origin",E)this.stateStore=E;else{let Oe=typeof window!="undefined"?window.localStorage:new T;this.stateStore=new A({store:Oe})}this.refreshTokenAllowedScope=Ee,this.extraQueryParams=Te,this.extraTokenParams=Ue,this.extraHeaders=Ae}};var ne=class{constructor(e,t){this._settings=e;this._metadataService=t;this._logger=new l("UserInfoService");this._getClaimsFromJwt=async e=>{let t=this._logger.create("_getClaimsFromJwt");try{let r=D.decode(e);return t.debug("JWT decoding successful"),r}catch(r){throw t.error("Error parsing JWT response"),r}};this._jsonService=new U(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){let t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));let r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);let i=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials});return t.debug("got claims",i),i}};var V=class{constructor(e,t){this._settings=e;this._metadataService=t;this._logger=new l("TokenClient");this._jsonService=new U(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:i=this._settings.client_secret,...s}){let n=this._logger.create("exchangeCode");r||n.throw(new Error("A client_id is required")),t||n.throw(new Error("A redirect_uri is required")),s.code||n.throw(new Error("A code is required"));let o=new URLSearchParams({grant_type:e,redirect_uri:t});for(let[u,p]of Object.entries(s))p!=null&&o.set(u,p);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!i)throw n.throw(new Error("A client_secret is required")),null;c=w.generateBasicAuth(r,i);break;case"client_secret_post":o.append("client_id",r),i&&o.append("client_secret",i);break}let d=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");let g=await this._jsonService.postForm(d,{body:o,basicAuth:c,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),g}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:i=this._settings.scope,...s}){let n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));let o=new URLSearchParams({grant_type:e,scope:i});for(let[u,p]of Object.entries(s))p!=null&&o.set(u,p);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw n.throw(new Error("A client_secret is required")),null;c=w.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break}let d=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");let g=await this._jsonService.postForm(d,{body:o,basicAuth:c,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),g}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:i,...s}){let n=this._logger.create("exchangeRefreshToken");t||n.throw(new Error("A client_id is required")),s.refresh_token||n.throw(new Error("A refresh_token is required"));let o=new URLSearchParams({grant_type:e});for(let[u,p]of Object.entries(s))Array.isArray(p)?p.forEach(f=>o.append(u,f)):p!=null&&o.set(u,p);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw n.throw(new Error("A client_secret is required")),null;c=w.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break}let d=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");let g=await this._jsonService.postForm(d,{body:o,basicAuth:c,timeoutInSeconds:i,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),g}async revoke(e){var s;let t=this._logger.create("revoke");e.token||t.throw(new Error("A token is required"));let r=await this._metadataService.getRevocationEndpoint(!1);t.debug(`got revocation endpoint, revoking ${(s=e.token_type_hint)!=null?s:"default token type"}`);let i=new URLSearchParams;for(let[n,o]of Object.entries(e))o!=null&&i.set(n,o);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:i}),t.debug("got response")}};var oe=class{constructor(e,t,r){this._settings=e;this._metadataService=t;this._claimsService=r;this._logger=new l("ResponseValidator");this._userInfoService=new ne(this._settings,this._metadataService);this._tokenClient=new V(this._settings,this._metadataService)}async validateSigninResponse(e,t){let r=this._logger.create("validateSigninResponse");this._processSigninState(e,t),r.debug("state processed"),await this._processCode(e,t),r.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t==null?void 0:t.skipUserInfo,e.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(e,t){let r=this._logger.create("validateCredentialsResponse");e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),r.debug("claims processed")}async validateRefreshResponse(e,t){var s,n;let r=this._logger.create("validateRefreshResponse");e.userState=t.data,(s=e.session_state)!=null||(e.session_state=t.session_state),(n=e.scope)!=null||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);let i=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,i),r.debug("claims processed")}validateSignoutResponse(e,t){let r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new _(e)}_processSigninState(e,t){var i;let r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,(i=e.scope)!=null||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new _(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){let i=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token){i.debug("not loading user info");return}i.debug("loading user info");let s=await this._userInfoService.getClaims(e.access_token);i.debug("user info claims received from user info endpoint"),r&&s.sub!==e.profile.sub&&i.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),i.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t){let r=this._logger.create("_processCode");if(e.code){r.debug("Validating code");let i=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,...t.extraTokenParams});Object.assign(e,i)}else r.debug("No code to process")}_validateIdTokenAttributes(e,t){var s;let r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");let i=D.decode((s=e.id_token)!=null?s:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),t){let n=D.decode(t);i.sub!==n.sub&&r.throw(new Error("sub in id_token does not match current sub")),i.auth_time&&i.auth_time!==n.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),i.azp&&i.azp!==n.azp&&r.throw(new Error("azp in id_token does not match original azp")),!i.azp&&n.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}};var y=class a{constructor(e){this.id=e.id||w.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=m.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new l("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(e){return l.createStatic("State","fromStorageString"),Promise.resolve(new a(JSON.parse(e)))}static async clearStaleState(e,t){let r=l.createStatic("State","clearStaleState"),i=m.getEpochTime()-t,s=await e.getAllKeys();r.debug("got keys",s);for(let n=0;n<s.length;n++){let o=s[n],c=await e.get(o),d=!1;if(c)try{let g=await a.fromStorageString(c);r.debug("got item from key:",o,g.created),g.created<=i&&(d=!0)}catch(g){r.error("Error parsing state for key:",o,g),d=!0}else r.debug("no item in storage for key:",o),d=!0;d&&(r.debug("removed item for key:",o),e.remove(o))}}};var O=class a extends y{constructor(t){super(t);this.code_verifier=t.code_verifier,this.code_challenge=t.code_challenge,this.authority=t.authority,this.client_id=t.client_id,this.redirect_uri=t.redirect_uri,this.scope=t.scope,this.client_secret=t.client_secret,this.extraTokenParams=t.extraTokenParams,this.response_mode=t.response_mode,this.skipUserInfo=t.skipUserInfo}static async create(t){let r=t.code_verifier===!0?w.generateCodeVerifier():t.code_verifier||void 0,i=r?await w.generateCodeChallenge(r):void 0;return new a({...t,code_verifier:r,code_challenge:i})}toStorageString(){return new l("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){l.createStatic("SigninState","fromStorageString");let r=JSON.parse(t);return a.create(r)}};var ce=class ce{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:t,client_id:r,redirect_uri:i,response_type:s,scope:n,state_data:o,response_mode:c,request_type:d,client_secret:g,nonce:u,url_state:p,resource:f,skipUserInfo:N,extraQueryParams:W,extraTokenParams:L,disablePKCE:j,...H}){if(!e)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!s)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!n)throw this._logger.error("create: No scope passed"),new Error("scope");if(!t)throw this._logger.error("create: No authority passed"),new Error("authority");let v=await O.create({data:o,request_type:d,url_state:p,code_verifier:!j,client_id:r,authority:t,redirect_uri:i,response_mode:c,client_secret:g,scope:n,extraTokenParams:L,skipUserInfo:N}),h=new URL(e);h.searchParams.append("client_id",r),h.searchParams.append("redirect_uri",i),h.searchParams.append("response_type",s),h.searchParams.append("scope",n),u&&h.searchParams.append("nonce",u);let R=v.id;p&&(R=`${R}${te}${p}`),h.searchParams.append("state",R),v.code_challenge&&(h.searchParams.append("code_challenge",v.code_challenge),h.searchParams.append("code_challenge_method","S256")),f&&(Array.isArray(f)?f:[f]).forEach(b=>h.searchParams.append("resource",b));for(let[I,b]of Object.entries({response_mode:c,...H,...W}))b!=null&&h.searchParams.append(I,b.toString());return new ce({url:h.href,state:v})}};ce._logger=new l("SigninRequest");var ae=ce;var Qe="openid",q=class{constructor(e){this.access_token="";this.token_type="";this.profile={};if(this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){let t=decodeURIComponent(this.state).split(te);this.state=t[0],t.length>1&&(this.url_state=t.slice(1).join(te))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-m.getEpochTime()}set expires_in(e){typeof e=="string"&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+m.getEpochTime())}get isOpenId(){var e;return((e=this.scope)==null?void 0:e.split(" ").includes(Qe))||!!this.id_token}};var le=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:i,extraQueryParams:s,request_type:n,client_id:o}){this._logger=new l("SignoutRequest");if(!e)throw this._logger.error("ctor: No url passed"),new Error("url");let c=new URL(e);r&&c.searchParams.append("id_token_hint",r),o&&c.searchParams.append("client_id",o),i&&(c.searchParams.append("post_logout_redirect_uri",i),t&&(this.state=new y({data:t,request_type:n}),c.searchParams.append("state",this.state.id)));for(let[d,g]of Object.entries({...s}))g!=null&&c.searchParams.append(d,g.toString());this.url=c.href}};var G=class{constructor(e){this.state=e.get("state"),this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}};var Ve=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],Ge=["sub","iss","aud","exp","iat"],de=class{constructor(e){this._settings=e;this._logger=new l("ClaimsService")}filterProtocolClaims(e){let t={...e};if(this._settings.filterProtocolClaims){let r;Array.isArray(this._settings.filterProtocolClaims)?r=this._settings.filterProtocolClaims:r=Ve;for(let i of r)Ge.includes(i)||delete t[i]}return t}mergeClaims(e,t){let r={...e};for(let[i,s]of Object.entries(t))if(r[i]!==s)if(Array.isArray(r[i])||Array.isArray(s))if(this._settings.mergeClaimsStrategy.array=="replace")r[i]=s;else{let n=Array.isArray(r[i])?r[i]:[r[i]];for(let o of Array.isArray(s)?s:[s])n.includes(o)||n.push(o);r[i]=n}else typeof r[i]=="object"&&typeof s=="object"?r[i]=this.mergeClaims(r[i],s):r[i]=s;return r}};var re=class{constructor(e,t){this._logger=new l("OidcClient");this.settings=e instanceof C?e:new C(e),this.metadataService=t!=null?t:new Q(this.settings),this._claimsService=new de(this.settings),this._validator=new oe(this.settings,this.metadataService,this._claimsService),this._tokenClient=new V(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:i,id_token_hint:s,login_hint:n,skipUserInfo:o,nonce:c,url_state:d,response_type:g=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:p=this.settings.redirect_uri,prompt:f=this.settings.prompt,display:N=this.settings.display,max_age:W=this.settings.max_age,ui_locales:L=this.settings.ui_locales,acr_values:j=this.settings.acr_values,resource:H=this.settings.resource,response_mode:v=this.settings.response_mode,extraQueryParams:h=this.settings.extraQueryParams,extraTokenParams:R=this.settings.extraTokenParams}){let I=this._logger.create("createSigninRequest");if(g!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");let b=await this.metadataService.getAuthorizationEndpoint();I.debug("Received authorization endpoint",b);let $=await ae.create({url:b,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:p,response_type:g,scope:u,state_data:e,url_state:d,prompt:f,display:N,max_age:W,ui_locales:L,id_token_hint:s,login_hint:n,acr_values:j,resource:H,request:t,request_uri:r,extraQueryParams:h,extraTokenParams:R,request_type:i,response_mode:v,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:c,disablePKCE:this.settings.disablePKCE});await this.clearStaleState();let E=$.state;return await this.settings.stateStore.set(E.id,E.toStorageString()),$}async readSigninResponseState(e,t=!1){let r=this._logger.create("readSigninResponseState"),i=new q(K.readParams(e,this.settings.response_mode));if(!i.state)throw r.throw(new Error("No state in response")),null;let s=await this.settings.stateStore[t?"remove":"get"](i.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await O.fromStorageString(s),response:i}}async processSigninResponse(e){let t=this._logger.create("processSigninResponse"),{state:r,response:i}=await this.readSigninResponseState(e,!0);return t.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(i,r),i}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:i={}}){let s=await this._tokenClient.exchangeCredentials({username:e,password:t,...i}),n=new q(new URLSearchParams);return Object.assign(n,s),await this._validator.validateCredentialsResponse(n,r),n}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:i,extraTokenParams:s}){var g;let n=this._logger.create("useRefreshToken"),o;if(this.settings.refreshTokenAllowedScope===void 0)o=e.scope;else{let u=this.settings.refreshTokenAllowedScope.split(" ");o=(((g=e.scope)==null?void 0:g.split(" "))||[]).filter(f=>u.includes(f)).join(" ")}let c=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:o,redirect_uri:t,resource:r,timeoutInSeconds:i,...s}),d=new q(new URLSearchParams);return Object.assign(d,c),n.debug("validating response",d),await this._validator.validateRefreshResponse(d,{...e,scope:o}),d}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:i,post_logout_redirect_uri:s=this.settings.post_logout_redirect_uri,extraQueryParams:n=this.settings.extraQueryParams}={}){let o=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw o.throw(new Error("No end session endpoint")),null;o.debug("Received end session endpoint",c),!r&&s&&!t&&(r=this.settings.client_id);let d=new le({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:s,state_data:e,extraQueryParams:n,request_type:i});await this.clearStaleState();let g=d.state;return g&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(g.id,g.toStorageString())),d}async readSignoutResponseState(e,t=!1){let r=this._logger.create("readSignoutResponseState"),i=new G(K.readParams(e,this.settings.response_mode));if(!i.state){if(r.debug("No state in response"),i.error)throw r.warn("Response was error:",i.error),new _(i);return{state:void 0,response:i}}let s=await this.settings.stateStore[t?"remove":"get"](i.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await y.fromStorageString(s),response:i}}async processSignoutResponse(e){let t=this._logger.create("processSignoutResponse"),{state:r,response:i}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(i,r)):t.debug("No state from storage; skipping response validation"),i}clearStaleState(){return this._logger.create("clearStaleState"),y.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}};var X=class{constructor(e){this._userManager=e;this._logger=new l("SessionMonitor");this._start=async e=>{let t=e.session_state;if(!t)return;let r=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,r.debug("session_state",t,", anonymous user")),this._checkSessionIFrame){this._checkSessionIFrame.start(t);return}try{let i=await this._userManager.metadataService.getCheckSessionIframe();if(i){r.debug("initializing check session iframe");let s=this._userManager.settings.client_id,n=this._userManager.settings.checkSessionIntervalInSeconds,o=this._userManager.settings.stopCheckSessionOnError,c=new B(this._callback,s,i,n,o);await c.load(),this._checkSessionIFrame=c,c.start(t)}else r.warn("no check session iframe found in the metadata")}catch(i){r.error("Error from getCheckSessionIframe:",i instanceof Error?i.message:i)}};this._stop=()=>{let e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){let t=setInterval(async()=>{clearInterval(t);try{let r=await this._userManager.querySessionStatus();if(r){let i={session_state:r.session_state,profile:r.sub?{sub:r.sub}:null};this._start(i)}}catch(r){e.error("error from querySessionStatus",r instanceof Error?r.message:r)}},1e3)}};this._callback=async()=>{let e=this._logger.create("_callback");try{let t=await this._userManager.querySessionStatus(),r=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(r=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),r?this._sub?this._userManager.events._raiseUserSignedOut():this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),this._userManager.events._raiseUserSignedOut())}};e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(t=>{this._logger.error(t)})}async _init(){this._logger.create("_init");let e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){let t=await this._userManager.querySessionStatus();if(t){let r={session_state:t.session_state,profile:t.sub?{sub:t.sub}:null};this._start(r)}}}};var M=class a{constructor(e){var t;this.id_token=e.id_token,this.session_state=(t=e.session_state)!=null?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-m.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+m.getEpochTime())}get expired(){let e=this.expires_in;if(e!==void 0)return e<=0}get scopes(){var e,t;return(t=(e=this.scope)==null?void 0:e.split(" "))!=null?t:[]}toStorageString(){return new l("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(e){return l.createStatic("User","fromStorageString"),new a(JSON.parse(e))}};var Re="oidc-client",Y=class{constructor(){this._abort=new S("Window navigation aborted");this._disposeHandlers=new Set;this._window=null}async navigate(e){let t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);let{url:r,keepOpen:i}=await new Promise((s,n)=>{let o=c=>{var u;let d=c.data,g=(u=e.scriptOrigin)!=null?u:window.location.origin;if(!(c.origin!==g||(d==null?void 0:d.source)!==Re)){try{let p=K.readParams(d.url,e.response_mode).get("state");if(p||t.warn("no state found in response url"),c.source!==this._window&&p!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}s(d)}};window.addEventListener("message",o,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",o,!1)),this._disposeHandlers.add(this._abort.addHandler(c=>{this._dispose(),n(c)}))});return t.debug("got response from window"),this._dispose(),i||this.close(),{url:r}}_dispose(){this._logger.create("_dispose");for(let e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,r=!1,i=window.location.origin){e.postMessage({source:Re,url:t,keepOpen:r},i)}};var be={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},we="_blank",Xe=60,Ye=2,ye=10,Z=class extends C{constructor(t){let{popup_redirect_uri:r=t.redirect_uri,popup_post_logout_redirect_uri:i=t.post_logout_redirect_uri,popupWindowFeatures:s=be,popupWindowTarget:n=we,redirectMethod:o="assign",redirectTarget:c="self",iframeNotifyParentOrigin:d=t.iframeNotifyParentOrigin,iframeScriptOrigin:g=t.iframeScriptOrigin,silent_redirect_uri:u=t.redirect_uri,silentRequestTimeoutInSeconds:p=ye,automaticSilentRenew:f=!0,validateSubOnSilentRenew:N=!0,includeIdTokenInSilentRenew:W=!1,monitorSession:L=!1,monitorAnonymousSession:j=!1,checkSessionIntervalInSeconds:H=Ye,query_status_response_type:v="code",stopCheckSessionOnError:h=!0,revokeTokenTypes:R=["access_token","refresh_token"],revokeTokensOnSignout:I=!1,includeIdTokenInSilentSignout:b=!1,accessTokenExpiringNotificationTimeInSeconds:$=Xe,userStore:E}=t;super(t);if(this.popup_redirect_uri=r,this.popup_post_logout_redirect_uri=i,this.popupWindowFeatures=s,this.popupWindowTarget=n,this.redirectMethod=o,this.redirectTarget=c,this.iframeNotifyParentOrigin=d,this.iframeScriptOrigin=g,this.silent_redirect_uri=u,this.silentRequestTimeoutInSeconds=p,this.automaticSilentRenew=f,this.validateSubOnSilentRenew=N,this.includeIdTokenInSilentRenew=W,this.monitorSession=L,this.monitorAnonymousSession=j,this.checkSessionIntervalInSeconds=H,this.stopCheckSessionOnError=h,this.query_status_response_type=v,this.revokeTokenTypes=R,this.revokeTokensOnSignout=I,this.includeIdTokenInSilentSignout=b,this.accessTokenExpiringNotificationTimeInSeconds=$,E)this.userStore=E;else{let fe=typeof window!="undefined"?window.sessionStorage:new T;this.userStore=new A({store:fe})}}};var ie=class a extends Y{constructor({silentRequestTimeoutInSeconds:t=ye}){super();this._logger=new l("IFrameWindow");this._timeoutInSeconds=t,this._frame=a.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){let t=window.document.createElement("iframe");return t.style.visibility="hidden",t.style.position="fixed",t.style.left="-1000px",t.style.top="0",t.width="0",t.height="0",window.document.body.appendChild(t),t}async navigate(t){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);let r=setTimeout(()=>this._abort.raise(new P("IFrame timed out without a response")),this._timeoutInSeconds*1e3);return this._disposeHandlers.add(()=>clearTimeout(r)),await super.navigate(t)}close(){var t;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",r=>{var s;let i=r.target;(s=i.parentNode)==null||s.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))},!0),(t=this._frame.contentWindow)==null||t.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(t,r){return super._notifyParent(window.parent,t,!1,r)}};var ge=class{constructor(e){this._settings=e;this._logger=new l("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new ie({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),ie.notifyParent(e,this._settings.iframeNotifyParentOrigin)}};var Ze=500,et=1e3,se=class extends Y{constructor({popupWindowTarget:t=we,popupWindowFeatures:r={}}){super();this._logger=new l("PopupWindow");let i=ee.center({...be,...r});this._window=window.open(void 0,t,ee.serialize(i)),r.closePopupWindowAfterInSeconds&&r.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{if(!this._window||typeof this._window.closed!="boolean"||this._window.closed){this._abort.raise(new Error("Popup blocked by user"));return}this.close()},r.closePopupWindowAfterInSeconds*et)}async navigate(t){var i;(i=this._window)==null||i.focus();let r=setInterval(()=>{(!this._window||this._window.closed)&&this._abort.raise(new Error("Popup closed by user"))},Ze);return this._disposeHandlers.add(()=>clearInterval(r)),await super.navigate(t)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(t,r){if(!window.opener)throw new Error("No window.opener. Can't complete notification.");return super._notifyParent(window.opener,t,r)}};var pe=class{constructor(e){this._settings=e;this._logger=new l("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget}){return new se({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),se.notifyOpener(e,t)}};var ue=class{constructor(e){this._settings=e;this._logger=new l("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let r=window.self;t==="top"&&(r=(n=window.top)!=null?n:window.self);let i=r.location[e].bind(r.location),s;return{navigate:async o=>{this._logger.create("navigate");let c=new Promise((d,g)=>{s=g});return i(o.url),await c},close:()=>{this._logger.create("close"),s==null||s(new Error("Redirect aborted")),r.stop()}}}async callback(){}};var he=class extends z{constructor(t){super({expiringNotificationTimeInSeconds:t.accessTokenExpiringNotificationTimeInSeconds});this._logger=new l("UserManagerEvents");this._userLoaded=new S("User loaded");this._userUnloaded=new S("User unloaded");this._silentRenewError=new S("Silent renew error");this._userSignedIn=new S("User signed in");this._userSignedOut=new S("User signed out");this._userSessionChanged=new S("User session changed")}load(t,r=!0){super.load(t),r&&this._userLoaded.raise(t)}unload(){super.unload(),this._userUnloaded.raise()}addUserLoaded(t){return this._userLoaded.addHandler(t)}removeUserLoaded(t){return this._userLoaded.removeHandler(t)}addUserUnloaded(t){return this._userUnloaded.addHandler(t)}removeUserUnloaded(t){return this._userUnloaded.removeHandler(t)}addSilentRenewError(t){return this._silentRenewError.addHandler(t)}removeSilentRenewError(t){return this._silentRenewError.removeHandler(t)}_raiseSilentRenewError(t){this._silentRenewError.raise(t)}addUserSignedIn(t){return this._userSignedIn.addHandler(t)}removeUserSignedIn(t){this._userSignedIn.removeHandler(t)}_raiseUserSignedIn(){this._userSignedIn.raise()}addUserSignedOut(t){return this._userSignedOut.addHandler(t)}removeUserSignedOut(t){this._userSignedOut.removeHandler(t)}_raiseUserSignedOut(){this._userSignedOut.raise()}addUserSessionChanged(t){return this._userSessionChanged.addHandler(t)}removeUserSessionChanged(t){this._userSessionChanged.removeHandler(t)}_raiseUserSessionChanged(){this._userSessionChanged.raise()}};var me=class{constructor(e){this._userManager=e;this._logger=new l("SilentRenewService");this._isStarted=!1;this._retryTimer=new m("Retry Silent Renew");this._tokenExpiring=async()=>{let e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof P){e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),this._retryTimer.init(5);return}e.error("Error from signinSilent:",t),this._userManager.events._raiseSilentRenewError(t)}}}async start(){let e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}};var _e=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}};var ve=class{constructor(e,t,r,i){this._logger=new l("UserManager");this.settings=new Z(e),this._client=new re(e),this._redirectNavigator=t!=null?t:new ue(this.settings),this._popupNavigator=r!=null?r:new pe(this.settings),this._iframeNavigator=i!=null?i:new ge(this.settings),this._events=new he(this.settings),this._silentRenewService=new me(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new X(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(){let e=this._logger.create("getUser"),t=await this._loadUser();return t?(e.info("user loaded"),this._events.load(t,!1),t):(e.info("user not found in storage"),null)}async removeUser(){let e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),this._events.unload()}async signinRedirect(e={}){this._logger.create("signinRedirect");let{redirectMethod:t,...r}=e,i=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:"si:r",...r},i)}async signinRedirectCallback(e=window.location.href){let t=this._logger.create("signinRedirectCallback"),r=await this._signinEnd(e);return r.profile&&r.profile.sub?t.info("success, signed in subject",r.profile.sub):t.info("no subject"),r}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:r=!1}){let i=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r,extraTokenParams:this.settings.extraTokenParams});i.debug("got signin response");let n=await this._buildUser(s);return n.profile&&n.profile.sub?i.info("success, signed in subject",n.profile.sub):i.info("no subject"),n}async signinPopup(e={}){let t=this._logger.create("signinPopup"),{popupWindowFeatures:r,popupWindowTarget:i,...s}=e,n=this.settings.popup_redirect_uri;n||t.throw(new Error("No popup_redirect_uri configured"));let o=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:i}),c=await this._signin({request_type:"si:p",redirect_uri:n,display:"popup",...s},o);return c&&(c.profile&&c.profile.sub?t.info("success, signed in subject",c.profile.sub):t.info("no subject")),c}async signinPopupCallback(e=window.location.href,t=!1){let r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async signinSilent(e={}){var d;let t=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:r,...i}=e,s=await this._loadUser();if(s!=null&&s.refresh_token){t.debug("using refresh token");let g=new _e(s);return await this._useRefreshToken({state:g,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:r})}let n=this.settings.silent_redirect_uri;n||t.throw(new Error("No silent_redirect_uri configured"));let o;s&&this.settings.validateSubOnSilentRenew&&(t.debug("subject prior to silent renew:",s.profile.sub),o=s.profile.sub);let c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});return s=await this._signin({request_type:"si:s",redirect_uri:n,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?s==null?void 0:s.id_token:void 0,...i},c,o),s&&((d=s.profile)!=null&&d.sub?t.info("success, signed in subject",s.profile.sub):t.info("no subject")),s}async _useRefreshToken(e){let t=await this._client.useRefreshToken({...e,timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds}),r=new M({...e.state,...t});return await this.storeUser(r),this._events.load(r),r}async signinSilentCallback(e=window.location.href){let t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){let{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":return await this.signinPopupCallback(e);case"si:s":return await this.signinSilentCallback(e);default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){let{state:r}=await this._client.readSignoutResponseState(e);if(r)switch(r.request_type){case"so:r":await this.signoutRedirectCallback(e);break;case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){let t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:r,...i}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));let n=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),c=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?n==null?void 0:n.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...i},o);try{let d=await this._client.processSigninResponse(c.url);return t.debug("got signin response"),d.session_state&&d.profile.sub?(t.info("success for subject",d.profile.sub),{session_state:d.session_state,sub:d.profile.sub}):(t.info("success, user not authenticated"),null)}catch(d){if(this.settings.monitorAnonymousSession&&d instanceof _)switch(d.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:d.session_state}}throw d}}async _signin(e,t,r){let i=await this._signinStart(e,t);return await this._signinEnd(i.url,r)}async _signinStart(e,t){let r=this._logger.create("_signinStart");try{let i=await this._client.createSigninRequest(e);return r.debug("got signin request"),await t.navigate({url:i.url,state:i.state.id,response_mode:i.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(i){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),i}}async _signinEnd(e,t){let r=this._logger.create("_signinEnd"),i=await this._client.processSigninResponse(e);return r.debug("got signin response"),await this._buildUser(i,t)}async _buildUser(e,t){let r=this._logger.create("_buildUser"),i=new M(e);if(t){if(t!==i.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin:",i.profile.sub),new _({...e,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(i),r.debug("user stored"),this._events.load(i),i}async signoutRedirect(e={}){let t=this._logger.create("signoutRedirect"),{redirectMethod:r,...i}=e,s=await this._redirectNavigator.prepare({redirectMethod:r});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...i},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){let t=this._logger.create("signoutRedirectCallback"),r=await this._signoutEnd(e);return t.info("success"),r}async signoutPopup(e={}){let t=this._logger.create("signoutPopup"),{popupWindowFeatures:r,popupWindowTarget:i,...s}=e,n=this.settings.popup_post_logout_redirect_uri,o=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:i});await this._signout({request_type:"so:p",post_logout_redirect_uri:n,state:n==null?void 0:{},...s},o),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){let r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async _signout(e,t){let r=await this._signoutStart(e,t);return await this._signoutEnd(r.url)}async _signoutStart(e={},t){var i;let r=this._logger.create("_signoutStart");try{let s=await this._loadUser();r.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);let n=e.id_token_hint||s&&s.id_token;n&&(r.debug("setting id_token_hint in signout request"),e.id_token_hint=n),await this.removeUser(),r.debug("user removed, creating signout request");let o=await this._client.createSignoutRequest(e);return r.debug("got signout request"),await t.navigate({url:o.url,state:(i=o.state)==null?void 0:i.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),s}}async _signoutEnd(e){let t=this._logger.create("_signoutEnd"),r=await this._client.processSignoutResponse(e);return t.debug("got signout response"),r}async signoutSilent(e={}){var c;let t=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:r,...i}=e,s=this.settings.includeIdTokenInSilentSignout?(c=await this._loadUser())==null?void 0:c.id_token:void 0,n=this.settings.popup_post_logout_redirect_uri,o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});await this._signout({request_type:"so:s",post_logout_redirect_uri:n,id_token_hint:s,...i},o),t.info("success")}async signoutSilentCallback(e=window.location.href){let t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){let t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){let r=this._logger.create("_revokeInternal");if(!e)return;let i=t.filter(s=>typeof e[s]=="string");if(!i.length){r.debug("no need to revoke due to no token(s)");return}for(let s of i)await this._client.revokeToken(e[s],s),r.info(`${s} revoked successfully`),s!=="access_token"&&(e[s]=null);await this.storeUser(e),r.debug("user stored"),this._events.load(e)}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){let e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),M.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){let t=this._logger.create("storeUser");if(e){t.debug("storing user");let r=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,r)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey)}async clearStaleState(){await this._client.clearStaleState()}};var Ce="3.0.0-rc.0";var Ie=Ce;return je(rt);})();
"use strict";var oidc=(()=>{var fe=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var We=(a,e)=>{for(var t in e)fe(a,t,{get:e[t],enumerable:!0})},Le=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Me(e))!Ne.call(a,i)&&i!==t&&fe(a,i,{get:()=>e[i],enumerable:!(r=qe(e,i))||r.enumerable});return a};var je=a=>Le(fe({},"__esModule",{value:!0}),a);var rt={};We(rt,{AccessTokenEvents:()=>z,CheckSessionIFrame:()=>B,ErrorResponse:()=>_,ErrorTimeout:()=>P,InMemoryWebStorage:()=>E,Log:()=>J,Logger:()=>l,MetadataService:()=>Q,OidcClient:()=>re,OidcClientSettingsStore:()=>C,SessionMonitor:()=>X,SigninResponse:()=>O,SigninState:()=>A,SignoutResponse:()=>G,State:()=>y,User:()=>q,UserManager:()=>ye,UserManagerSettingsStore:()=>Z,Version:()=>Ce,WebStorageStateStore:()=>U});var He={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},k,x,J=(s=>(s[s.NONE=0]="NONE",s[s.ERROR=1]="ERROR",s[s.WARN=2]="WARN",s[s.INFO=3]="INFO",s[s.DEBUG=4]="DEBUG",s))(J||{});(r=>{function a(){k=3,x=He}r.reset=a;function e(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");k=i}r.setLevel=e;function t(i){x=i}r.setLogger=t})(J||(J={}));var l=class a{constructor(e){this._name=e}debug(...e){k>=4&&x.debug(a._format(this._name,this._method),...e)}info(...e){k>=3&&x.info(a._format(this._name,this._method),...e)}warn(...e){k>=2&&x.warn(a._format(this._name,this._method),...e)}error(...e){k>=1&&x.error(a._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){let t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){let r=new a(`${e}.${t}`);return r.debug("begin"),r}static _format(e,t){let r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(e,...t){k>=4&&x.debug(a._format(e),...t)}static info(e,...t){k>=3&&x.info(a._format(e),...t)}static warn(e,...t){k>=2&&x.warn(a._format(e),...t)}static error(e,...t){k>=1&&x.error(a._format(e),...t)}};J.reset();var Fe="10000000-1000-4000-8000-100000000000",ke=a=>btoa([...new Uint8Array(a)].map(e=>String.fromCharCode(e)).join("")),b=class a{static _randomWord(){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return Fe.replace(/[018]/g,t=>(+t^a._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return a.generateUUIDv4()+a.generateUUIDv4()+a.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{let r=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",r);return ke(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw l.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){let i=new TextEncoder().encode([e,t].join(":"));return ke(i)}};var S=class{constructor(e){this._name=e;this._logger=new l(`Event('${this._name}')`);this._callbacks=[]}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){let t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(let t of this._callbacks)await t(...e)}};var D=class extends Error{};D.prototype.name="InvalidTokenError";function Je(a){return decodeURIComponent(atob(a).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function De(a){let e=a.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return Je(e)}catch{return atob(e)}}function xe(a,e){if(typeof a!="string")throw new D("Invalid token specified: must be a string");e||(e={});let t=e.header===!0?0:1,r=a.split(".")[t];if(typeof r!="string")throw new D(`Invalid token specified: missing part #${t+1}`);let i;try{i=De(r)}catch(s){throw new D(`Invalid token specified: invalid base64 for part #${t+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new D(`Invalid token specified: invalid json for part #${t+1} (${s.message})`)}}var K=class{static decode(e){try{return xe(e)}catch(t){throw l.error("JwtUtils.decode",t),t}}};var ee=class{static center({...e}){var t,r,i;return e.width==null&&(e.width=(t=[800,720,600,480].find(s=>s<=window.outerWidth/1.618))!=null?t:360),(r=e.left)!=null||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),e.height!=null&&((i=e.top)!=null||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,t])=>t!=null).map(([t,r])=>`${t}=${typeof r!="boolean"?r:r?"yes":"no"}`).join(",")}};var m=class a extends S{constructor(){super(...arguments);this._logger=new l(`Timer('${this._name}')`);this._timerHandle=null;this._expiration=0;this._callback=()=>{let t=this._expiration-a.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=a.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){let r=this._logger.create("init");t=Math.max(Math.floor(t),1);let i=a.getEpochTime()+t;if(this.expiration===i&&this._timerHandle){r.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),r.debug("using duration",t),this._expiration=i;let s=Math.min(t,5);this._timerHandle=setInterval(this._callback,s*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}};var $=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");let i=new URL(e,"http://127.0.0.1")[t==="fragment"?"hash":"search"];return new URLSearchParams(i.slice(1))}},te=";";var _=class extends Error{constructor(t,r){var i,s,n;super(t.error_description||t.error||"");this.form=r;this.name="ErrorResponse";if(!t.error)throw l.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=t.error,this.error_description=(i=t.error_description)!=null?i:null,this.error_uri=(s=t.error_uri)!=null?s:null,this.state=t.userState,this.session_state=(n=t.session_state)!=null?n:null,this.url_state=t.url_state}};var P=class extends Error{constructor(t){super(t);this.name="ErrorTimeout"}};var z=class{constructor(e){this._logger=new l("AccessTokenEvents");this._expiringTimer=new m("Access token expiring");this._expiredTimer=new m("Access token expired");this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}load(e){let t=this._logger.create("load");if(e.access_token&&e.expires_in!==void 0){let r=e.expires_in;if(t.debug("access token present, remaining duration:",r),r>0){let s=r-this._expiringNotificationTimeInSeconds;s<=0&&(s=1),t.debug("registering expiring timer, raising in",s,"seconds"),this._expiringTimer.init(s)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();let i=r+1;t.debug("registering expired timer, raising in",i,"seconds"),this._expiredTimer.init(i)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}};var B=class{constructor(e,t,r,i,s){this._callback=e;this._client_id=t;this._intervalInSeconds=i;this._stopOnError=s;this._logger=new l("CheckSessionIFrame");this._timer=null;this._session_state=null;this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data==="error"?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):e.data==="changed"?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};let n=new URL(r);this._frame_origin=n.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=n.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;let t=()=>{!this._frame.contentWindow||!this._session_state||this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,this._intervalInSeconds*1e3)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}};var E=class{constructor(){this._logger=new l("InMemoryWebStorage");this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}};var T=class{constructor(e=[],t=null,r={}){this._jwtHandler=t;this._extraHeaders=r;this._logger=new l("JsonService");this._contentTypes=[];this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){let{timeoutInSeconds:r,...i}=t;if(!r)return await fetch(e,i);let s=new AbortController,n=setTimeout(()=>s.abort(),r*1e3);try{return await fetch(e,{...t,signal:s.signal})}catch(o){throw o instanceof DOMException&&o.name==="AbortError"?new P("Network timed out"):o}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:r}={}){let i=this._logger.create("getJson"),s={Accept:this._contentTypes.join(", ")};t&&(i.debug("token passed, setting Authorization header"),s.Authorization="Bearer "+t),this.appendExtraHeaders(s);let n;try{i.debug("url:",e),n=await this.fetchWithTimeout(e,{method:"GET",headers:s,credentials:r})}catch(d){throw i.error("Network Error"),d}i.debug("HTTP response received, status",n.status);let o=n.headers.get("Content-Type");if(o&&!this._contentTypes.find(d=>o.startsWith(d))&&i.throw(new Error(`Invalid response Content-Type: ${o!=null?o:"undefined"}, from URL: ${e}`)),n.ok&&this._jwtHandler&&(o!=null&&o.startsWith("application/jwt")))return await this._jwtHandler(await n.text());let c;try{c=await n.json()}catch(d){throw i.error("Error parsing JSON response",d),n.ok?d:new Error(`${n.statusText} (${n.status})`)}if(!n.ok)throw i.error("Error from server:",c),c.error?new _(c):new Error(`${n.statusText} (${n.status}): ${JSON.stringify(c)}`);return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:i,initCredentials:s}){let n=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};r!==void 0&&(o.Authorization="Basic "+r),this.appendExtraHeaders(o);let c;try{n.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:i,credentials:s})}catch(p){throw n.error("Network error"),p}n.debug("HTTP response received, status",c.status);let d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find(p=>d.startsWith(p)))throw new Error(`Invalid response Content-Type: ${d!=null?d:"undefined"}, from URL: ${e}`);let g=await c.text(),u={};if(g)try{u=JSON.parse(g)}catch(p){throw n.error("Error parsing JSON response",p),c.ok?p:new Error(`${c.statusText} (${c.status})`)}if(!c.ok)throw n.error("Error from server:",u),u.error?new _(u,t):new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`);return u}appendExtraHeaders(e){let t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),i=["authorization","accept","content-type"];r.length!==0&&r.forEach(s=>{if(i.includes(s.toLocaleLowerCase())){t.warn("Protected header could not be overridden",s,i);return}let n=typeof this._extraHeaders[s]=="function"?this._extraHeaders[s]():this._extraHeaders[s];n&&n!==""&&(e[s]=n)})}};var Q=class{constructor(e){this._settings=e;this._logger=new l("MetadataService");this._signingKeys=null;this._metadata=null;this._metadataUrl=this._settings.metadataUrl,this._jsonService=new T(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){let e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);let t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,t),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){let r=this._logger.create(`_getMetadataProperty('${e}')`),i=await this.getMetadata();if(r.debug("resolved"),i[e]===void 0){if(t===!0){r.warn("Metadata does not contain optional property");return}r.throw(new Error("Metadata does not contain property "+e))}return i[e]}async getSigningKeys(){let e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;let t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);let r=await this._jsonService.getJson(t);if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}};var U=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new l("WebStorageStateStore");this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;let t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");let e=await this._store.length,t=[];for(let r=0;r<e;r++){let i=await this._store.key(r);i&&i.indexOf(this._prefix)===0&&t.push(i.substr(this._prefix.length))}return t}};var Ke="code",$e="openid",ze="client_secret_post",Be=60*15,C=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:i,metadataSeed:s,client_id:n,client_secret:o,response_type:c=Ke,scope:d=$e,redirect_uri:g,post_logout_redirect_uri:u,client_authentication:p=ze,prompt:f,display:M,max_age:N,ui_locales:W,acr_values:L,resource:j,response_mode:v,filterProtocolClaims:h=!0,loadUserInfo:R=!1,staleStateAgeInSeconds:I=Be,mergeClaimsStrategy:w={array:"replace"},disablePKCE:H=!1,stateStore:F,revokeTokenAdditionalContentTypes:Ie,fetchRequestCredentials:ve,refreshTokenAllowedScope:Ee,extraQueryParams:Te={},extraTokenParams:Ue={},extraHeaders:Ae={}}){if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=r,this.metadataSeed=s,this.signingKeys=i,this.client_id=n,this.client_secret=o,this.response_type=c,this.scope=d,this.redirect_uri=g,this.post_logout_redirect_uri=u,this.client_authentication=p,this.prompt=f,this.display=M,this.max_age=N,this.ui_locales=W,this.acr_values=L,this.resource=j,this.response_mode=v,this.filterProtocolClaims=h!=null?h:!0,this.loadUserInfo=!!R,this.staleStateAgeInSeconds=I,this.mergeClaimsStrategy=w,this.disablePKCE=!!H,this.revokeTokenAdditionalContentTypes=Ie,this.fetchRequestCredentials=ve||"same-origin",F)this.stateStore=F;else{let Oe=typeof window!="undefined"?window.localStorage:new E;this.stateStore=new U({store:Oe})}this.refreshTokenAllowedScope=Ee,this.extraQueryParams=Te,this.extraTokenParams=Ue,this.extraHeaders=Ae}};var ne=class{constructor(e,t){this._settings=e;this._metadataService=t;this._logger=new l("UserInfoService");this._getClaimsFromJwt=async e=>{let t=this._logger.create("_getClaimsFromJwt");try{let r=K.decode(e);return t.debug("JWT decoding successful"),r}catch(r){throw t.error("Error parsing JWT response"),r}};this._jsonService=new T(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){let t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));let r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);let i=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials});return t.debug("got claims",i),i}};var V=class{constructor(e,t){this._settings=e;this._metadataService=t;this._logger=new l("TokenClient");this._jsonService=new T(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:i=this._settings.client_secret,...s}){let n=this._logger.create("exchangeCode");r||n.throw(new Error("A client_id is required")),t||n.throw(new Error("A redirect_uri is required")),s.code||n.throw(new Error("A code is required"));let o=new URLSearchParams({grant_type:e,redirect_uri:t});for(let[u,p]of Object.entries(s))p!=null&&o.set(u,p);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!i)throw n.throw(new Error("A client_secret is required")),null;c=b.generateBasicAuth(r,i);break;case"client_secret_post":o.append("client_id",r),i&&o.append("client_secret",i);break}let d=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");let g=await this._jsonService.postForm(d,{body:o,basicAuth:c,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),g}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:i=this._settings.scope,...s}){let n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));let o=new URLSearchParams({grant_type:e,scope:i});for(let[u,p]of Object.entries(s))p!=null&&o.set(u,p);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw n.throw(new Error("A client_secret is required")),null;c=b.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break}let d=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");let g=await this._jsonService.postForm(d,{body:o,basicAuth:c,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),g}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:i,...s}){let n=this._logger.create("exchangeRefreshToken");t||n.throw(new Error("A client_id is required")),s.refresh_token||n.throw(new Error("A refresh_token is required"));let o=new URLSearchParams({grant_type:e});for(let[u,p]of Object.entries(s))Array.isArray(p)?p.forEach(f=>o.append(u,f)):p!=null&&o.set(u,p);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw n.throw(new Error("A client_secret is required")),null;c=b.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break}let d=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");let g=await this._jsonService.postForm(d,{body:o,basicAuth:c,timeoutInSeconds:i,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),g}async revoke(e){var s;let t=this._logger.create("revoke");e.token||t.throw(new Error("A token is required"));let r=await this._metadataService.getRevocationEndpoint(!1);t.debug(`got revocation endpoint, revoking ${(s=e.token_type_hint)!=null?s:"default token type"}`);let i=new URLSearchParams;for(let[n,o]of Object.entries(e))o!=null&&i.set(n,o);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(r,{body:i}),t.debug("got response")}};var oe=class{constructor(e,t,r){this._settings=e;this._metadataService=t;this._claimsService=r;this._logger=new l("ResponseValidator");this._userInfoService=new ne(this._settings,this._metadataService);this._tokenClient=new V(this._settings,this._metadataService)}async validateSigninResponse(e,t){let r=this._logger.create("validateSigninResponse");this._processSigninState(e,t),r.debug("state processed"),await this._processCode(e,t),r.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t==null?void 0:t.skipUserInfo,e.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(e,t){let r=this._logger.create("validateCredentialsResponse");e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),r.debug("claims processed")}async validateRefreshResponse(e,t){var s,n;let r=this._logger.create("validateRefreshResponse");e.userState=t.data,(s=e.session_state)!=null||(e.session_state=t.session_state),(n=e.scope)!=null||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);let i=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,i),r.debug("claims processed")}validateSignoutResponse(e,t){let r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new _(e)}_processSigninState(e,t){var i;let r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,(i=e.scope)!=null||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new _(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){let i=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token){i.debug("not loading user info");return}i.debug("loading user info");let s=await this._userInfoService.getClaims(e.access_token);i.debug("user info claims received from user info endpoint"),r&&s.sub!==e.profile.sub&&i.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),i.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t){let r=this._logger.create("_processCode");if(e.code){r.debug("Validating code");let i=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,...t.extraTokenParams});Object.assign(e,i)}else r.debug("No code to process")}_validateIdTokenAttributes(e,t){var s;let r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");let i=K.decode((s=e.id_token)!=null?s:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),t){let n=K.decode(t);i.sub!==n.sub&&r.throw(new Error("sub in id_token does not match current sub")),i.auth_time&&i.auth_time!==n.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),i.azp&&i.azp!==n.azp&&r.throw(new Error("azp in id_token does not match original azp")),!i.azp&&n.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}};var y=class a{constructor(e){this.id=e.id||b.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=m.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new l("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(e){return l.createStatic("State","fromStorageString"),Promise.resolve(new a(JSON.parse(e)))}static async clearStaleState(e,t){let r=l.createStatic("State","clearStaleState"),i=m.getEpochTime()-t,s=await e.getAllKeys();r.debug("got keys",s);for(let n=0;n<s.length;n++){let o=s[n],c=await e.get(o),d=!1;if(c)try{let g=await a.fromStorageString(c);r.debug("got item from key:",o,g.created),g.created<=i&&(d=!0)}catch(g){r.error("Error parsing state for key:",o,g),d=!0}else r.debug("no item in storage for key:",o),d=!0;d&&(r.debug("removed item for key:",o),e.remove(o))}}};var A=class a extends y{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(e){let t=e.code_verifier===!0?b.generateCodeVerifier():e.code_verifier||void 0,r=t?await b.generateCodeChallenge(t):void 0;return new a({...e,code_verifier:t,code_challenge:r})}toStorageString(){return new l("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(e){l.createStatic("SigninState","fromStorageString");let t=JSON.parse(e);return a.create(t)}};var ce=class ce{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:t,client_id:r,redirect_uri:i,response_type:s,scope:n,state_data:o,response_mode:c,request_type:d,client_secret:g,nonce:u,url_state:p,resource:f,skipUserInfo:M,extraQueryParams:N,extraTokenParams:W,disablePKCE:L,...j}){if(!e)throw this._logger.error("create: No url passed"),new Error("url");if(!r)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!s)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!n)throw this._logger.error("create: No scope passed"),new Error("scope");if(!t)throw this._logger.error("create: No authority passed"),new Error("authority");let v=await A.create({data:o,request_type:d,url_state:p,code_verifier:!L,client_id:r,authority:t,redirect_uri:i,response_mode:c,client_secret:g,scope:n,extraTokenParams:W,skipUserInfo:M}),h=new URL(e);h.searchParams.append("client_id",r),h.searchParams.append("redirect_uri",i),h.searchParams.append("response_type",s),h.searchParams.append("scope",n),u&&h.searchParams.append("nonce",u);let R=v.id;p&&(R=`${R}${te}${p}`),h.searchParams.append("state",R),v.code_challenge&&(h.searchParams.append("code_challenge",v.code_challenge),h.searchParams.append("code_challenge_method","S256")),f&&(Array.isArray(f)?f:[f]).forEach(w=>h.searchParams.append("resource",w));for(let[I,w]of Object.entries({response_mode:c,...j,...N}))w!=null&&h.searchParams.append(I,w.toString());return new ce({url:h.href,state:v})}};ce._logger=new l("SigninRequest");var ae=ce;var Qe="openid",O=class{constructor(e){this.access_token="";this.token_type="";this.profile={};if(this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){let t=decodeURIComponent(this.state).split(te);this.state=t[0],t.length>1&&(this.url_state=t.slice(1).join(te))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-m.getEpochTime()}set expires_in(e){typeof e=="string"&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+m.getEpochTime())}get isOpenId(){var e;return((e=this.scope)==null?void 0:e.split(" ").includes(Qe))||!!this.id_token}};var le=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:i,extraQueryParams:s,request_type:n,client_id:o}){this._logger=new l("SignoutRequest");if(!e)throw this._logger.error("ctor: No url passed"),new Error("url");let c=new URL(e);r&&c.searchParams.append("id_token_hint",r),o&&c.searchParams.append("client_id",o),i&&(c.searchParams.append("post_logout_redirect_uri",i),t&&(this.state=new y({data:t,request_type:n}),c.searchParams.append("state",this.state.id)));for(let[d,g]of Object.entries({...s}))g!=null&&c.searchParams.append(d,g.toString());this.url=c.href}};var G=class{constructor(e){this.state=e.get("state"),this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}};var Ve=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],Ge=["sub","iss","aud","exp","iat"],de=class{constructor(e){this._settings=e;this._logger=new l("ClaimsService")}filterProtocolClaims(e){let t={...e};if(this._settings.filterProtocolClaims){let r;Array.isArray(this._settings.filterProtocolClaims)?r=this._settings.filterProtocolClaims:r=Ve;for(let i of r)Ge.includes(i)||delete t[i]}return t}mergeClaims(e,t){let r={...e};for(let[i,s]of Object.entries(t))if(r[i]!==s)if(Array.isArray(r[i])||Array.isArray(s))if(this._settings.mergeClaimsStrategy.array=="replace")r[i]=s;else{let n=Array.isArray(r[i])?r[i]:[r[i]];for(let o of Array.isArray(s)?s:[s])n.includes(o)||n.push(o);r[i]=n}else typeof r[i]=="object"&&typeof s=="object"?r[i]=this.mergeClaims(r[i],s):r[i]=s;return r}};var re=class{constructor(e,t){this._logger=new l("OidcClient");this.settings=e instanceof C?e:new C(e),this.metadataService=t!=null?t:new Q(this.settings),this._claimsService=new de(this.settings),this._validator=new oe(this.settings,this.metadataService,this._claimsService),this._tokenClient=new V(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:i,id_token_hint:s,login_hint:n,skipUserInfo:o,nonce:c,url_state:d,response_type:g=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:p=this.settings.redirect_uri,prompt:f=this.settings.prompt,display:M=this.settings.display,max_age:N=this.settings.max_age,ui_locales:W=this.settings.ui_locales,acr_values:L=this.settings.acr_values,resource:j=this.settings.resource,response_mode:v=this.settings.response_mode,extraQueryParams:h=this.settings.extraQueryParams,extraTokenParams:R=this.settings.extraTokenParams}){let I=this._logger.create("createSigninRequest");if(g!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");let w=await this.metadataService.getAuthorizationEndpoint();I.debug("Received authorization endpoint",w);let H=await ae.create({url:w,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:p,response_type:g,scope:u,state_data:e,url_state:d,prompt:f,display:M,max_age:N,ui_locales:W,id_token_hint:s,login_hint:n,acr_values:L,resource:j,request:t,request_uri:r,extraQueryParams:h,extraTokenParams:R,request_type:i,response_mode:v,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:c,disablePKCE:this.settings.disablePKCE});await this.clearStaleState();let F=H.state;return await this.settings.stateStore.set(F.id,F.toStorageString()),H}async readSigninResponseState(e,t=!1){let r=this._logger.create("readSigninResponseState"),i=new O($.readParams(e,this.settings.response_mode));if(!i.state)throw r.throw(new Error("No state in response")),null;let s=await this.settings.stateStore[t?"remove":"get"](i.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await A.fromStorageString(s),response:i}}async processSigninResponse(e){let t=this._logger.create("processSigninResponse"),{state:r,response:i}=await this.readSigninResponseState(e,!0);return t.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(i,r),i}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:i={}}){let s=await this._tokenClient.exchangeCredentials({username:e,password:t,...i}),n=new O(new URLSearchParams);return Object.assign(n,s),await this._validator.validateCredentialsResponse(n,r),n}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:i,extraTokenParams:s}){var g;let n=this._logger.create("useRefreshToken"),o;if(this.settings.refreshTokenAllowedScope===void 0)o=e.scope;else{let u=this.settings.refreshTokenAllowedScope.split(" ");o=(((g=e.scope)==null?void 0:g.split(" "))||[]).filter(f=>u.includes(f)).join(" ")}let c=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:o,redirect_uri:t,resource:r,timeoutInSeconds:i,...s}),d=new O(new URLSearchParams);return Object.assign(d,c),n.debug("validating response",d),await this._validator.validateRefreshResponse(d,{...e,scope:o}),d}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:i,post_logout_redirect_uri:s=this.settings.post_logout_redirect_uri,extraQueryParams:n=this.settings.extraQueryParams}={}){let o=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw o.throw(new Error("No end session endpoint")),null;o.debug("Received end session endpoint",c),!r&&s&&!t&&(r=this.settings.client_id);let d=new le({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:s,state_data:e,extraQueryParams:n,request_type:i});await this.clearStaleState();let g=d.state;return g&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(g.id,g.toStorageString())),d}async readSignoutResponseState(e,t=!1){let r=this._logger.create("readSignoutResponseState"),i=new G($.readParams(e,this.settings.response_mode));if(!i.state){if(r.debug("No state in response"),i.error)throw r.warn("Response was error:",i.error),new _(i);return{state:void 0,response:i}}let s=await this.settings.stateStore[t?"remove":"get"](i.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await y.fromStorageString(s),response:i}}async processSignoutResponse(e){let t=this._logger.create("processSignoutResponse"),{state:r,response:i}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(i,r)):t.debug("No state from storage; skipping response validation"),i}clearStaleState(){return this._logger.create("clearStaleState"),y.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}};var X=class{constructor(e){this._userManager=e;this._logger=new l("SessionMonitor");this._start=async e=>{let t=e.session_state;if(!t)return;let r=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,r.debug("session_state",t,", anonymous user")),this._checkSessionIFrame){this._checkSessionIFrame.start(t);return}try{let i=await this._userManager.metadataService.getCheckSessionIframe();if(i){r.debug("initializing check session iframe");let s=this._userManager.settings.client_id,n=this._userManager.settings.checkSessionIntervalInSeconds,o=this._userManager.settings.stopCheckSessionOnError,c=new B(this._callback,s,i,n,o);await c.load(),this._checkSessionIFrame=c,c.start(t)}else r.warn("no check session iframe found in the metadata")}catch(i){r.error("Error from getCheckSessionIframe:",i instanceof Error?i.message:i)}};this._stop=()=>{let e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){let t=setInterval(async()=>{clearInterval(t);try{let r=await this._userManager.querySessionStatus();if(r){let i={session_state:r.session_state,profile:r.sub?{sub:r.sub}:null};this._start(i)}}catch(r){e.error("error from querySessionStatus",r instanceof Error?r.message:r)}},1e3)}};this._callback=async()=>{let e=this._logger.create("_callback");try{let t=await this._userManager.querySessionStatus(),r=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(r=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),r?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}};e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(t=>{this._logger.error(t)})}async _init(){this._logger.create("_init");let e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){let t=await this._userManager.querySessionStatus();if(t){let r={session_state:t.session_state,profile:t.sub?{sub:t.sub}:null};this._start(r)}}}};var q=class a{constructor(e){var t;this.id_token=e.id_token,this.session_state=(t=e.session_state)!=null?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-m.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+m.getEpochTime())}get expired(){let e=this.expires_in;if(e!==void 0)return e<=0}get scopes(){var e,t;return(t=(e=this.scope)==null?void 0:e.split(" "))!=null?t:[]}toStorageString(){return new l("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(e){return l.createStatic("User","fromStorageString"),new a(JSON.parse(e))}};var Pe="oidc-client",Y=class{constructor(){this._abort=new S("Window navigation aborted");this._disposeHandlers=new Set;this._window=null}async navigate(e){let t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);let{url:r,keepOpen:i}=await new Promise((s,n)=>{let o=c=>{var u;let d=c.data,g=(u=e.scriptOrigin)!=null?u:window.location.origin;if(!(c.origin!==g||(d==null?void 0:d.source)!==Pe)){try{let p=$.readParams(d.url,e.response_mode).get("state");if(p||t.warn("no state found in response url"),c.source!==this._window&&p!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}s(d)}};window.addEventListener("message",o,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",o,!1)),this._disposeHandlers.add(this._abort.addHandler(c=>{this._dispose(),n(c)}))});return t.debug("got response from window"),this._dispose(),i||this.close(),{url:r}}_dispose(){this._logger.create("_dispose");for(let e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,r=!1,i=window.location.origin){e.postMessage({source:Pe,url:t,keepOpen:r},i)}};var Se={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},we="_blank",Xe=60,Ye=2,be=10,Z=class extends C{constructor(e){let{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:r=e.post_logout_redirect_uri,popupWindowFeatures:i=Se,popupWindowTarget:s=we,redirectMethod:n="assign",redirectTarget:o="self",iframeNotifyParentOrigin:c=e.iframeNotifyParentOrigin,iframeScriptOrigin:d=e.iframeScriptOrigin,silent_redirect_uri:g=e.redirect_uri,silentRequestTimeoutInSeconds:u=be,automaticSilentRenew:p=!0,validateSubOnSilentRenew:f=!0,includeIdTokenInSilentRenew:M=!1,monitorSession:N=!1,monitorAnonymousSession:W=!1,checkSessionIntervalInSeconds:L=Ye,query_status_response_type:j="code",stopCheckSessionOnError:v=!0,revokeTokenTypes:h=["access_token","refresh_token"],revokeTokensOnSignout:R=!1,includeIdTokenInSilentSignout:I=!1,accessTokenExpiringNotificationTimeInSeconds:w=Xe,userStore:H}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=i,this.popupWindowTarget=s,this.redirectMethod=n,this.redirectTarget=o,this.iframeNotifyParentOrigin=c,this.iframeScriptOrigin=d,this.silent_redirect_uri=g,this.silentRequestTimeoutInSeconds=u,this.automaticSilentRenew=p,this.validateSubOnSilentRenew=f,this.includeIdTokenInSilentRenew=M,this.monitorSession=N,this.monitorAnonymousSession=W,this.checkSessionIntervalInSeconds=L,this.stopCheckSessionOnError=v,this.query_status_response_type=j,this.revokeTokenTypes=h,this.revokeTokensOnSignout=R,this.includeIdTokenInSilentSignout=I,this.accessTokenExpiringNotificationTimeInSeconds=w,H)this.userStore=H;else{let F=typeof window!="undefined"?window.sessionStorage:new E;this.userStore=new U({store:F})}}};var ie=class a extends Y{constructor({silentRequestTimeoutInSeconds:t=be}){super();this._logger=new l("IFrameWindow");this._timeoutInSeconds=t,this._frame=a.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){let t=window.document.createElement("iframe");return t.style.visibility="hidden",t.style.position="fixed",t.style.left="-1000px",t.style.top="0",t.width="0",t.height="0",window.document.body.appendChild(t),t}async navigate(t){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);let r=setTimeout(()=>void this._abort.raise(new P("IFrame timed out without a response")),this._timeoutInSeconds*1e3);return this._disposeHandlers.add(()=>clearTimeout(r)),await super.navigate(t)}close(){var t;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",r=>{var s;let i=r.target;(s=i.parentNode)==null||s.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))},!0),(t=this._frame.contentWindow)==null||t.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(t,r){return super._notifyParent(window.parent,t,!1,r)}};var ge=class{constructor(e){this._settings=e;this._logger=new l("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new ie({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),ie.notifyParent(e,this._settings.iframeNotifyParentOrigin)}};var Ze=500,et=1e3,se=class extends Y{constructor({popupWindowTarget:t=we,popupWindowFeatures:r={}}){super();this._logger=new l("PopupWindow");let i=ee.center({...Se,...r});this._window=window.open(void 0,t,ee.serialize(i)),r.closePopupWindowAfterInSeconds&&r.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{if(!this._window||typeof this._window.closed!="boolean"||this._window.closed){this._abort.raise(new Error("Popup blocked by user"));return}this.close()},r.closePopupWindowAfterInSeconds*et)}async navigate(t){var i;(i=this._window)==null||i.focus();let r=setInterval(()=>{(!this._window||this._window.closed)&&this._abort.raise(new Error("Popup closed by user"))},Ze);return this._disposeHandlers.add(()=>clearInterval(r)),await super.navigate(t)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(t,r){if(!window.opener)throw new Error("No window.opener. Can't complete notification.");return super._notifyParent(window.opener,t,r)}};var pe=class{constructor(e){this._settings=e;this._logger=new l("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget}){return new se({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),se.notifyOpener(e,t)}};var ue=class{constructor(e){this._settings=e;this._logger=new l("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let r=window.self;t==="top"&&(r=(n=window.top)!=null?n:window.self);let i=r.location[e].bind(r.location),s;return{navigate:async o=>{this._logger.create("navigate");let c=new Promise((d,g)=>{s=g});return i(o.url),await c},close:()=>{this._logger.create("close"),s==null||s(new Error("Redirect aborted")),r.stop()}}}async callback(){}};var he=class extends z{constructor(t){super({expiringNotificationTimeInSeconds:t.accessTokenExpiringNotificationTimeInSeconds});this._logger=new l("UserManagerEvents");this._userLoaded=new S("User loaded");this._userUnloaded=new S("User unloaded");this._silentRenewError=new S("Silent renew error");this._userSignedIn=new S("User signed in");this._userSignedOut=new S("User signed out");this._userSessionChanged=new S("User session changed")}async load(t,r=!0){super.load(t),r&&await this._userLoaded.raise(t)}async unload(){super.unload(),await this._userUnloaded.raise()}addUserLoaded(t){return this._userLoaded.addHandler(t)}removeUserLoaded(t){return this._userLoaded.removeHandler(t)}addUserUnloaded(t){return this._userUnloaded.addHandler(t)}removeUserUnloaded(t){return this._userUnloaded.removeHandler(t)}addSilentRenewError(t){return this._silentRenewError.addHandler(t)}removeSilentRenewError(t){return this._silentRenewError.removeHandler(t)}async _raiseSilentRenewError(t){await this._silentRenewError.raise(t)}addUserSignedIn(t){return this._userSignedIn.addHandler(t)}removeUserSignedIn(t){this._userSignedIn.removeHandler(t)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(t){return this._userSignedOut.addHandler(t)}removeUserSignedOut(t){this._userSignedOut.removeHandler(t)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(t){return this._userSessionChanged.addHandler(t)}removeUserSessionChanged(t){this._userSessionChanged.removeHandler(t)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}};var me=class{constructor(e){this._userManager=e;this._logger=new l("SilentRenewService");this._isStarted=!1;this._retryTimer=new m("Retry Silent Renew");this._tokenExpiring=async()=>{let e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof P){e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),this._retryTimer.init(5);return}e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){let e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}};var _e=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}};var ye=class{constructor(e,t,r,i){this._logger=new l("UserManager");this.settings=new Z(e),this._client=new re(e),this._redirectNavigator=t!=null?t:new ue(this.settings),this._popupNavigator=r!=null?r:new pe(this.settings),this._iframeNavigator=i!=null?i:new ge(this.settings),this._events=new he(this.settings),this._silentRenewService=new me(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new X(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(){let e=this._logger.create("getUser"),t=await this._loadUser();return t?(e.info("user loaded"),await this._events.load(t,!1),t):(e.info("user not found in storage"),null)}async removeUser(){let e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){this._logger.create("signinRedirect");let{redirectMethod:t,...r}=e,i=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:"si:r",...r},i)}async signinRedirectCallback(e=window.location.href){let t=this._logger.create("signinRedirectCallback"),r=await this._signinEnd(e);return r.profile&&r.profile.sub?t.info("success, signed in subject",r.profile.sub):t.info("no subject"),r}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:r=!1}){let i=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r,extraTokenParams:this.settings.extraTokenParams});i.debug("got signin response");let n=await this._buildUser(s);return n.profile&&n.profile.sub?i.info("success, signed in subject",n.profile.sub):i.info("no subject"),n}async signinPopup(e={}){let t=this._logger.create("signinPopup"),{popupWindowFeatures:r,popupWindowTarget:i,...s}=e,n=this.settings.popup_redirect_uri;n||t.throw(new Error("No popup_redirect_uri configured"));let o=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:i}),c=await this._signin({request_type:"si:p",redirect_uri:n,display:"popup",...s},o);return c&&(c.profile&&c.profile.sub?t.info("success, signed in subject",c.profile.sub):t.info("no subject")),c}async signinPopupCallback(e=window.location.href,t=!1){let r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async signinSilent(e={}){var d;let t=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:r,...i}=e,s=await this._loadUser();if(s!=null&&s.refresh_token){t.debug("using refresh token");let g=new _e(s);return await this._useRefreshToken({state:g,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:r})}let n=this.settings.silent_redirect_uri;n||t.throw(new Error("No silent_redirect_uri configured"));let o;s&&this.settings.validateSubOnSilentRenew&&(t.debug("subject prior to silent renew:",s.profile.sub),o=s.profile.sub);let c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});return s=await this._signin({request_type:"si:s",redirect_uri:n,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?s==null?void 0:s.id_token:void 0,...i},c,o),s&&((d=s.profile)!=null&&d.sub?t.info("success, signed in subject",s.profile.sub):t.info("no subject")),s}async _useRefreshToken(e){let t=await this._client.useRefreshToken({...e,timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds}),r=new q({...e.state,...t});return await this.storeUser(r),await this._events.load(r),r}async signinSilentCallback(e=window.location.href){let t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){let{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":return await this.signinPopupCallback(e);case"si:s":return await this.signinSilentCallback(e);default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){let{state:r}=await this._client.readSignoutResponseState(e);if(r)switch(r.request_type){case"so:r":await this.signoutRedirectCallback(e);break;case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){let t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:r,...i}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));let n=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),c=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?n==null?void 0:n.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...i},o);try{let d=await this._client.processSigninResponse(c.url);return t.debug("got signin response"),d.session_state&&d.profile.sub?(t.info("success for subject",d.profile.sub),{session_state:d.session_state,sub:d.profile.sub}):(t.info("success, user not authenticated"),null)}catch(d){if(this.settings.monitorAnonymousSession&&d instanceof _)switch(d.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:d.session_state}}throw d}}async _signin(e,t,r){let i=await this._signinStart(e,t);return await this._signinEnd(i.url,r)}async _signinStart(e,t){let r=this._logger.create("_signinStart");try{let i=await this._client.createSigninRequest(e);return r.debug("got signin request"),await t.navigate({url:i.url,state:i.state.id,response_mode:i.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(i){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),i}}async _signinEnd(e,t){let r=this._logger.create("_signinEnd"),i=await this._client.processSigninResponse(e);return r.debug("got signin response"),await this._buildUser(i,t)}async _buildUser(e,t){let r=this._logger.create("_buildUser"),i=new q(e);if(t){if(t!==i.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin:",i.profile.sub),new _({...e,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(i),r.debug("user stored"),await this._events.load(i),i}async signoutRedirect(e={}){let t=this._logger.create("signoutRedirect"),{redirectMethod:r,...i}=e,s=await this._redirectNavigator.prepare({redirectMethod:r});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...i},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){let t=this._logger.create("signoutRedirectCallback"),r=await this._signoutEnd(e);return t.info("success"),r}async signoutPopup(e={}){let t=this._logger.create("signoutPopup"),{popupWindowFeatures:r,popupWindowTarget:i,...s}=e,n=this.settings.popup_post_logout_redirect_uri,o=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:i});await this._signout({request_type:"so:p",post_logout_redirect_uri:n,state:n==null?void 0:{},...s},o),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){let r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async _signout(e,t){let r=await this._signoutStart(e,t);return await this._signoutEnd(r.url)}async _signoutStart(e={},t){var i;let r=this._logger.create("_signoutStart");try{let s=await this._loadUser();r.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);let n=e.id_token_hint||s&&s.id_token;n&&(r.debug("setting id_token_hint in signout request"),e.id_token_hint=n),await this.removeUser(),r.debug("user removed, creating signout request");let o=await this._client.createSignoutRequest(e);return r.debug("got signout request"),await t.navigate({url:o.url,state:(i=o.state)==null?void 0:i.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),s}}async _signoutEnd(e){let t=this._logger.create("_signoutEnd"),r=await this._client.processSignoutResponse(e);return t.debug("got signout response"),r}async signoutSilent(e={}){var c;let t=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:r,...i}=e,s=this.settings.includeIdTokenInSilentSignout?(c=await this._loadUser())==null?void 0:c.id_token:void 0,n=this.settings.popup_post_logout_redirect_uri,o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r});await this._signout({request_type:"so:s",post_logout_redirect_uri:n,id_token_hint:s,...i},o),t.info("success")}async signoutSilentCallback(e=window.location.href){let t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){let t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){let r=this._logger.create("_revokeInternal");if(!e)return;let i=t.filter(s=>typeof e[s]=="string");if(!i.length){r.debug("no need to revoke due to no token(s)");return}for(let s of i)await this._client.revokeToken(e[s],s),r.info(`${s} revoked successfully`),s!=="access_token"&&(e[s]=null);await this.storeUser(e),r.debug("user stored"),await this._events.load(e)}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){let e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),q.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){let t=this._logger.create("storeUser");if(e){t.debug("storing user");let r=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,r)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey)}async clearStaleState(){await this._client.clearStaleState()}};var Re="3.0.0-rc.1";var Ce=Re;return je(rt);})();
//# sourceMappingURL=oidc-client-ts.min.js.map
{
"type": "module",
"version": "3.0.0-rc.0"
"version": "3.0.0-rc.1"
}

@@ -8,5 +8,5 @@ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.

"packageName": "@microsoft/api-extractor",
"packageVersion": "7.38.5"
"packageVersion": "7.39.1"
}
]
}
{
"name": "oidc-client-ts",
"version": "3.0.0-rc.0",
"version": "3.0.0-rc.1",
"description": "OpenID Connect (OIDC) & OAuth2 client library",
"repository": {
"type": "git",
"url": "git+https://github.com:authts/oidc-client-ts.git"
"url": "git+https://github.com/authts/oidc-client-ts.git"
},

@@ -62,3 +62,3 @@ "homepage": "https://github.com/authts/oidc-client-ts#readme",

"typedoc": "^0.25.0",
"typescript": "~5.0.4",
"typescript": "~5.3.3",
"yn": "^5.0.0"

@@ -65,0 +65,0 @@ },

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

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