(function(j,U){typeof exports=="object"&&typeof module<"u"?U(exports):typeof define=="function"&&define.amd?define(["exports"],U):(j=typeof globalThis<"u"?globalThis:j||self,U(j.uirisfrontsecurity={}))})(this,function(j){"use strict";var U=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function L(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ie(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var s=function i(){return this instanceof i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};s.prototype=t.prototype}else s={};return Object.defineProperty(s,"__esModule",{value:!0}),Object.keys(e).forEach(function(i){var r=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(s,i,r.get?r:{enumerable:!0,get:function(){return e[i]}})}),s}function xe(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var le={exports:{}};const Ue=Ie(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));(function(e,t){(function(s,i){e.exports=i()})(U,function(){var s=s||function(i,r){var n;if(typeof window<"u"&&window.crypto&&(n=window.crypto),typeof self<"u"&&self.crypto&&(n=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(n=globalThis.crypto),!n&&typeof window<"u"&&window.msCrypto&&(n=window.msCrypto),!n&&typeof U<"u"&&U.crypto&&(n=U.crypto),!n&&typeof xe=="function")try{n=Ue}catch{}var o=function(){if(n){if(typeof n.getRandomValues=="function")try{return n.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof n.randomBytes=="function")try{return n.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},c=Object.create||function(){function a(){}return function(d){var _;return a.prototype=d,_=new a,a.prototype=null,_}}(),l={},h=l.lib={},u=h.Base=function(){return{extend:function(a){var d=c(this);return a&&d.mixIn(a),(!d.hasOwnProperty("init")||this.init===d.init)&&(d.init=function(){d.$super.init.apply(this,arguments)}),d.init.prototype=d,d.$super=this,d},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var d in a)a.hasOwnProperty(d)&&(this[d]=a[d]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),g=h.WordArray=u.extend({init:function(a,d){a=this.words=a||[],d!=r?this.sigBytes=d:this.sigBytes=a.length*4},toString:function(a){return(a||m).stringify(this)},concat:function(a){var d=this.words,_=a.words,w=this.sigBytes,y=a.sigBytes;if(this.clamp(),w%4)for(var k=0;k>>2]>>>24-k%4*8&255;d[w+k>>>2]|=R<<24-(w+k)%4*8}else for(var T=0;T>>2]=_[T>>>2];return this.sigBytes+=y,this},clamp:function(){var a=this.words,d=this.sigBytes;a[d>>>2]&=4294967295<<32-d%4*8,a.length=i.ceil(d/4)},clone:function(){var a=u.clone.call(this);return a.words=this.words.slice(0),a},random:function(a){for(var d=[],_=0;_>>2]>>>24-y%4*8&255;w.push((k>>>4).toString(16)),w.push((k&15).toString(16))}return w.join("")},parse:function(a){for(var d=a.length,_=[],w=0;w>>3]|=parseInt(a.substr(w,2),16)<<24-w%8*4;return new g.init(_,d/2)}},b=S.Latin1={stringify:function(a){for(var d=a.words,_=a.sigBytes,w=[],y=0;y<_;y++){var k=d[y>>>2]>>>24-y%4*8&255;w.push(String.fromCharCode(k))}return w.join("")},parse:function(a){for(var d=a.length,_=[],w=0;w>>2]|=(a.charCodeAt(w)&255)<<24-w%4*8;return new g.init(_,d)}},p=S.Utf8={stringify:function(a){try{return decodeURIComponent(escape(b.stringify(a)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(a){return b.parse(unescape(encodeURIComponent(a)))}},v=h.BufferedBlockAlgorithm=u.extend({reset:function(){this._data=new g.init,this._nDataBytes=0},_append:function(a){typeof a=="string"&&(a=p.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(a){var d,_=this._data,w=_.words,y=_.sigBytes,k=this.blockSize,R=k*4,T=y/R;a?T=i.ceil(T):T=i.max((T|0)-this._minBufferSize,0);var A=T*k,x=i.min(A*4,y);if(A){for(var H=0;H>>7)^(T<<14|T>>>18)^T>>>3,x=g[R-2],H=(x<<15|x>>>17)^(x<<13|x>>>19)^x>>>10;g[R]=A+g[R-7]+H+g[R-16]}var B=_&w^~_&y,re=v&E^v&a^E&a,ne=(v<<30|v>>>2)^(v<<19|v>>>13)^(v<<10|v>>>22),oe=(_<<26|_>>>6)^(_<<21|_>>>11)^(_<<7|_>>>25),z=k+oe+B+u[R]+g[R],ae=ne+re;k=y,y=w,w=_,_=d+z|0,d=a,a=E,E=v,v=z+ae|0}p[0]=p[0]+v|0,p[1]=p[1]+E|0,p[2]=p[2]+a|0,p[3]=p[3]+d|0,p[4]=p[4]+_|0,p[5]=p[5]+w|0,p[6]=p[6]+y|0,p[7]=p[7]+k|0},_doFinalize:function(){var m=this._data,b=m.words,p=this._nDataBytes*8,v=m.sigBytes*8;return b[v>>>5]|=128<<24-v%32,b[(v+64>>>9<<4)+14]=i.floor(p/4294967296),b[(v+64>>>9<<4)+15]=p,m.sigBytes=b.length*4,this._process(),this._hash},clone:function(){var m=c.clone.call(this);return m._hash=this._hash.clone(),m}});r.SHA256=c._createHelper(S),r.HmacSHA256=c._createHmacHelper(S)}(Math),s.SHA256})})(de);var Pe=de.exports;const Oe=L(Pe);var he={exports:{}};(function(e,t){(function(s,i){e.exports=i(D)})(U,function(s){return function(){var i=s,r=i.lib,n=r.WordArray,o=i.enc;o.Base64={stringify:function(l){var h=l.words,u=l.sigBytes,g=this._map;l.clamp();for(var S=[],m=0;m>>2]>>>24-m%4*8&255,p=h[m+1>>>2]>>>24-(m+1)%4*8&255,v=h[m+2>>>2]>>>24-(m+2)%4*8&255,E=b<<16|p<<8|v,a=0;a<4&&m+a*.75>>6*(3-a)&63));var d=g.charAt(64);if(d)for(;S.length%4;)S.push(d);return S.join("")},parse:function(l){var h=l.length,u=this._map,g=this._reverseMap;if(!g){g=this._reverseMap=[];for(var S=0;S>>6-m%4*2,v=b|p;g[S>>>2]|=v<<24-S%4*8,S++}return n.create(g,S)}}(),s.enc.Base64})})(he);var Ae=he.exports;const ge=L(Ae);var ue={exports:{}};(function(e,t){(function(s,i){e.exports=i(D)})(U,function(s){return s.enc.Utf8})})(ue);var Me=ue.exports;const Ne=L(Me);function K(e){this.message=e}K.prototype=new Error,K.prototype.name="InvalidCharacterError";var _e=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new K("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,r=0,n=0,o="";i=t.charAt(n++);~i&&(s=r%4?64*s+i:i,r++%4)?o+=String.fromCharCode(255&s>>(-2*r&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return o};function qe(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(s){return decodeURIComponent(_e(s).replace(/(.)/g,function(i,r){var n=r.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}(t)}catch{return _e(t)}}function $(e){this.message=e}function J(e,t){if(typeof e!="string")throw new $("Invalid token specified");var s=(t=t||{}).header===!0?0:1;try{return JSON.parse(qe(e.split(".")[s]))}catch(i){throw new $("Invalid token specified: "+i.message)}}$.prototype=new Error,$.prototype.name="InvalidTokenError";var He={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},C,P,N=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(N||{});(e=>{function t(){C=3,P=He}e.reset=t;function s(r){if(!(0<=r&&r<=4))throw new Error("Invalid log level");C=r}e.setLevel=s;function i(r){P=r}e.setLogger=i})(N||(N={}));var f=class{constructor(e){this._name=e}debug(...e){C>=4&&P.debug(f._format(this._name,this._method),...e)}info(...e){C>=3&&P.info(f._format(this._name,this._method),...e)}warn(...e){C>=2&&P.warn(f._format(this._name,this._method),...e)}error(...e){C>=1&&P.error(f._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const s=new f(`${e}.${t}`);return s.debug("begin"),s}static _format(e,t){const s=`[${e}]`;return t?`${s} ${t}:`:s}static debug(e,...t){C>=4&&P.debug(f._format(e),...t)}static info(e,...t){C>=3&&P.info(f._format(e),...t)}static warn(e,...t){C>=2&&P.warn(f._format(e),...t)}static error(e,...t){C>=1&&P.error(f._format(e),...t)}};N.reset();var je="10000000-1000-4000-8000-100000000000",O=class{static _randomWord(){return Ce.lib.WordArray.random(1).words[0]}static generateUUIDv4(){return je.replace(/[018]/g,t=>(+t^O._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return O.generateUUIDv4()+O.generateUUIDv4()+O.generateUUIDv4()}static generateCodeChallenge(e){try{const t=Oe(e);return ge.stringify(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw f.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const s=Ne.parse([e,t].join(":"));return ge.stringify(s)}},M=class{constructor(t){this._name=t,this._logger=new f(`Event('${this._name}')`),this._callbacks=[]}addHandler(t){return this._callbacks.push(t),()=>this.removeHandler(t)}removeHandler(t){const s=this._callbacks.lastIndexOf(t);s>=0&&this._callbacks.splice(s,1)}raise(...t){this._logger.debug("raise:",...t);for(const s of this._callbacks)s(...t)}},V=class{static decode(e){try{return J(e)}catch(t){throw f.error("JwtUtils.decode",t),t}}},pe=class{static center({...e}){var t,s,i;return e.width==null&&(e.width=(t=[800,720,600,480].find(r=>r<=window.outerWidth/1.618))!=null?t:360),(s=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,s])=>`${t}=${typeof s!="boolean"?s:s?"yes":"no"}`).join(",")}},I=class extends M{constructor(){super(...arguments),this._logger=new f(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-I.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=I.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const s=I.getEpochTime()+e;if(this.expiration===s&&this._timerHandle){t.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),t.debug("using duration",e),this._expiration=s;const i=Math.min(e,5);this._timerHandle=setInterval(this._callback,i*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},Q=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const i=new URL(e,"http://127.0.0.1")[t==="fragment"?"hash":"search"];return new URLSearchParams(i.slice(1))}},G=";",q=class extends Error{constructor(e,t){var s,i,r;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw f.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=(s=e.error_description)!=null?s:null,this.error_uri=(i=e.error_uri)!=null?i:null,this.state=e.userState,this.session_state=(r=e.session_state)!=null?r:null,this.url_state=e.url_state}},X=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},We=class{constructor(e){this._logger=new f("AccessTokenEvents"),this._expiringTimer=new I("Access token expiring"),this._expiredTimer=new I("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}load(e){const t=this._logger.create("load");if(e.access_token&&e.expires_in!==void 0){const s=e.expires_in;if(t.debug("access token present, remaining duration:",s),s>0){let r=s-this._expiringNotificationTimeInSeconds;r<=0&&(r=1),t.debug("registering expiring timer, raising in",r,"seconds"),this._expiringTimer.init(r)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const i=s+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)}},Be=class{constructor(e,t,s,i,r){this._callback=e,this._client_id=t,this._intervalInSeconds=i,this._stopOnError=r,this._logger=new f("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=o=>{o.origin===this._frame_origin&&o.source===this._frame.contentWindow&&(o.data==="error"?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):o.data==="changed"?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(o.data+" message from check session op iframe"))};const n=new URL(s);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;const 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)}},fe=class{constructor(){this._logger=new f("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]}},Y=class{constructor(e=[],t=null,s={}){this._jwtHandler=t,this._extraHeaders=s,this._logger=new f("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:s,...i}=t;if(!s)return await fetch(e,i);const r=new AbortController,n=setTimeout(()=>r.abort(),s*1e3);try{return await fetch(e,{...t,signal:r.signal})}catch(o){throw o instanceof DOMException&&o.name==="AbortError"?new X("Network timed out"):o}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:s}={}){const i=this._logger.create("getJson"),r={Accept:this._contentTypes.join(", ")};t&&(i.debug("token passed, setting Authorization header"),r.Authorization="Bearer "+t),this.appendExtraHeaders(r);let n;try{i.debug("url:",e),n=await this.fetchWithTimeout(e,{method:"GET",headers:r,credentials:s})}catch(l){throw i.error("Network Error"),l}i.debug("HTTP response received, status",n.status);const o=n.headers.get("Content-Type");if(o&&!this._contentTypes.find(l=>o.startsWith(l))&&i.throw(new Error(`Invalid response Content-Type: ${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(l){throw i.error("Error parsing JSON response",l),n.ok?l:new Error(`${n.statusText} (${n.status})`)}if(!n.ok)throw i.error("Error from server:",c),c.error?new q(c):new Error(`${n.statusText} (${n.status}): ${JSON.stringify(c)}`);return c}async postForm(e,{body:t,basicAuth:s,timeoutInSeconds:i,initCredentials:r}){const n=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};s!==void 0&&(o.Authorization="Basic "+s),this.appendExtraHeaders(o);let c;try{n.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:i,credentials:r})}catch(g){throw n.error("Network error"),g}n.debug("HTTP response received, status",c.status);const l=c.headers.get("Content-Type");if(l&&!this._contentTypes.find(g=>l.startsWith(g)))throw new Error(`Invalid response Content-Type: ${l??"undefined"}, from URL: ${e}`);const h=await c.text();let u={};if(h)try{u=JSON.parse(h)}catch(g){throw n.error("Error parsing JSON response",g),c.ok?g:new Error(`${c.statusText} (${c.status})`)}if(!c.ok)throw n.error("Error from server:",u),u.error?new q(u,t):new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`);return u}appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),s=Object.keys(this._extraHeaders),i=["authorization","accept","content-type"];s.length!==0&&s.forEach(r=>{if(i.includes(r.toLocaleLowerCase())){t.warn("Protected header could not be overridden",r,i);return}const n=typeof this._extraHeaders[r]=="function"?this._extraHeaders[r]():this._extraHeaders[r];n&&n!==""&&(e[r]=n)})}},Le=class{constructor(e){this._settings=e,this._logger=new f("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new Y(["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(){const 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);const 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){const s=this._logger.create(`_getMetadataProperty('${e}')`),i=await this.getMetadata();if(s.debug("resolved"),i[e]===void 0){if(t===!0){s.warn("Metadata does not contain optional property");return}s.throw(new Error("Metadata does not contain property "+e))}return i[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const s=await this._jsonService.getJson(t);if(e.debug("got key set",s),!Array.isArray(s.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=s.keys,this._signingKeys}},Z=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new f("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;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let s=0;s{const i=this._logger.create("_getClaimsFromJwt");try{const r=V.decode(s);return i.debug("JWT decoding successful"),r}catch(r){throw i.error("Error parsing JWT response"),r}},this._jsonService=new Y(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const s=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",s);const i=await this._jsonService.getJson(s,{token:e,credentials:this._settings.fetchRequestCredentials});return t.debug("got claims",i),i}},we=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new f("TokenClient"),this._jsonService=new Y(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:s=this._settings.client_id,client_secret:i=this._settings.client_secret,...r}){const n=this._logger.create("exchangeCode");s||n.throw(new Error("A client_id is required")),t||n.throw(new Error("A redirect_uri is required")),r.code||n.throw(new Error("A code is required"));const o=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[u,g]of Object.entries(r))g!=null&&o.set(u,g);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=O.generateBasicAuth(s,i);break;case"client_secret_post":o.append("client_id",s),i&&o.append("client_secret",i);break}const l=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(l,{body:o,basicAuth:c,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,scope:i=this._settings.scope,...r}){const n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e,scope:i});for(const[u,g]of Object.entries(r))g!=null&&o.set(u,g);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;c=O.generateBasicAuth(t,s);break;case"client_secret_post":o.append("client_id",t),s&&o.append("client_secret",s);break}const l=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(l,{body:o,basicAuth:c,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,timeoutInSeconds:i,...r}){const n=this._logger.create("exchangeRefreshToken");t||n.throw(new Error("A client_id is required")),r.refresh_token||n.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:e});for(const[u,g]of Object.entries(r))Array.isArray(g)?g.forEach(S=>o.append(u,S)):g!=null&&o.set(u,g);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;c=O.generateBasicAuth(t,s);break;case"client_secret_post":o.append("client_id",t),s&&o.append("client_secret",s);break}const l=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const h=await this._jsonService.postForm(l,{body:o,basicAuth:c,timeoutInSeconds:i,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),h}async revoke(e){var t;const s=this._logger.create("revoke");e.token||s.throw(new Error("A token is required"));const i=await this._metadataService.getRevocationEndpoint(!1);s.debug(`got revocation endpoint, revoking ${(t=e.token_type_hint)!=null?t:"default token type"}`);const r=new URLSearchParams;for(const[n,o]of Object.entries(e))o!=null&&r.set(n,o);r.set("client_id",this._settings.client_id),this._settings.client_secret&&r.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(i,{body:r}),s.debug("got response")}},Qe=class{constructor(e,t,s){this._settings=e,this._metadataService=t,this._claimsService=s,this._logger=new f("ResponseValidator"),this._userInfoService=new Ve(this._settings,this._metadataService),this._tokenClient=new we(this._settings,this._metadataService)}async validateSigninResponse(e,t){const s=this._logger.create("validateSigninResponse");this._processSigninState(e,t),s.debug("state processed"),await this._processCode(e,t),s.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,t==null?void 0:t.skipUserInfo,e.isOpenId),s.debug("claims processed")}async validateCredentialsResponse(e,t){const s=this._logger.create("validateCredentialsResponse");e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),s.debug("claims processed")}async validateRefreshResponse(e,t){var s,i;const r=this._logger.create("validateRefreshResponse");e.userState=t.data,(s=e.session_state)!=null||(e.session_state=t.session_state),(i=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);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),r.debug("claims processed")}validateSignoutResponse(e,t){const s=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&s.throw(new Error("State does not match")),s.debug("state validated"),e.userState=t.data,e.error)throw s.warn("Response was error",e.error),new q(e)}_processSigninState(e,t){var s;const i=this._logger.create("_processSigninState");if(t.id!==e.state&&i.throw(new Error("State does not match")),t.client_id||i.throw(new Error("No client_id on state")),t.authority||i.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&i.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&i.throw(new Error("client_id mismatch on settings vs. signin state")),i.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,(s=e.scope)!=null||(e.scope=t.scope),e.error)throw i.warn("Response was error",e.error),new q(e);t.code_verifier&&!e.code&&i.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,s=!0){const 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");const r=await this._userInfoService.getClaims(e.access_token);i.debug("user info claims received from user info endpoint"),s&&r.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(r)),i.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t){const s=this._logger.create("_processCode");if(e.code){s.debug("Validating code");const 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 s.debug("No code to process")}_validateIdTokenAttributes(e,t){var s;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const r=V.decode((s=e.id_token)!=null?s:"");if(r.sub||i.throw(new Error("ID Token is missing a subject claim")),t){const n=V.decode(t);r.sub!==n.sub&&i.throw(new Error("sub in id_token does not match current sub")),r.auth_time&&r.auth_time!==n.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),r.azp&&r.azp!==n.azp&&i.throw(new Error("azp in id_token does not match original azp")),!r.azp&&n.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=r}},W=class{constructor(e){this.id=e.id||O.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=I.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new f("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 f.createStatic("State","fromStorageString"),new W(JSON.parse(e))}static async clearStaleState(e,t){const s=f.createStatic("State","clearStaleState"),i=I.getEpochTime()-t,r=await e.getAllKeys();s.debug("got keys",r);for(let n=0;na.searchParams.append("resource",w));for(const[_,w]of Object.entries({response_mode:c,...E,...b}))w!=null&&a.searchParams.append(_,w.toString());this.url=a.href}},Xe="openid",se=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const t=decodeURIComponent(this.state).split(G);this.state=t[0],t.length>1&&(this.url_state=t.slice(1).join(G))}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-I.getEpochTime()}set expires_in(e){typeof e=="string"&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+I.getEpochTime())}get isOpenId(){var e;return((e=this.scope)==null?void 0:e.split(" ").includes(Xe))||!!this.id_token}},Ye=class{constructor({url:e,state_data:t,id_token_hint:s,post_logout_redirect_uri:i,extraQueryParams:r,request_type:n,client_id:o}){if(this._logger=new f("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);s&&c.searchParams.append("id_token_hint",s),o&&c.searchParams.append("client_id",o),i&&(c.searchParams.append("post_logout_redirect_uri",i),t&&(this.state=new W({data:t,request_type:n}),c.searchParams.append("state",this.state.id)));for(const[l,h]of Object.entries({...r}))h!=null&&c.searchParams.append(l,h.toString());this.url=c.href}},Ze=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")}},et=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],tt=["sub","iss","aud","exp","iat"],st=class{constructor(e){this._settings=e,this._logger=new f("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let s;Array.isArray(this._settings.filterProtocolClaims)?s=this._settings.filterProtocolClaims:s=et;for(const i of s)tt.includes(i)||delete t[i]}return t}mergeClaims(e,t){const s={...e};for(const[i,r]of Object.entries(t))for(const n of Array.isArray(r)?r:[r]){const o=s[i];o===void 0?s[i]=n:Array.isArray(o)?o.includes(n)||o.push(n):s[i]!==n&&(typeof n=="object"&&this._settings.mergeClaims?s[i]=this.mergeClaims(o,n):s[i]=[o,n])}return s}},it=class{constructor(e,t){this._logger=new f("OidcClient"),this.settings=e instanceof ee?e:new ee(e),this.metadataService=t??new Le(this.settings),this._claimsService=new st(this.settings),this._validator=new Qe(this.settings,this.metadataService,this._claimsService),this._tokenClient=new we(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:s,request_type:i,id_token_hint:r,login_hint:n,skipUserInfo:o,nonce:c,url_state:l,response_type:h=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:g=this.settings.redirect_uri,prompt:S=this.settings.prompt,display:m=this.settings.display,max_age:b=this.settings.max_age,ui_locales:p=this.settings.ui_locales,acr_values:v=this.settings.acr_values,resource:E=this.settings.resource,response_mode:a=this.settings.response_mode,extraQueryParams:d=this.settings.extraQueryParams,extraTokenParams:_=this.settings.extraTokenParams}){const w=this._logger.create("createSigninRequest");if(h!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const y=await this.metadataService.getAuthorizationEndpoint();w.debug("Received authorization endpoint",y);const k=new Ge({url:y,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:g,response_type:h,scope:u,state_data:e,url_state:l,prompt:S,display:m,max_age:b,ui_locales:p,id_token_hint:r,login_hint:n,acr_values:v,resource:E,request:t,request_uri:s,extraQueryParams:d,extraTokenParams:_,request_type:i,response_mode:a,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:c,disablePKCE:this.settings.disablePKCE});await this.clearStaleState();const R=k.state;return await this.settings.stateStore.set(R.id,R.toStorageString()),k}async readSigninResponseState(e,t=!1){const s=this._logger.create("readSigninResponseState"),i=new se(Q.readParams(e,this.settings.response_mode));if(!i.state)throw s.throw(new Error("No state in response")),null;const r=await this.settings.stateStore[t?"remove":"get"](i.state);if(!r)throw s.throw(new Error("No matching state found in storage")),null;return{state:te.fromStorageString(r),response:i}}async processSigninResponse(e){const t=this._logger.create("processSigninResponse"),{state:s,response:i}=await this.readSigninResponseState(e,!0);return t.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(i,s),i}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:s=!1,extraTokenParams:i={}}){const r=await this._tokenClient.exchangeCredentials({username:e,password:t,...i}),n=new se(new URLSearchParams);return Object.assign(n,r),await this._validator.validateCredentialsResponse(n,s),n}async useRefreshToken({state:e,timeoutInSeconds:t}){var s;const i=this._logger.create("useRefreshToken");let r;if(this.settings.refreshTokenAllowedScope===void 0)r=e.scope;else{const c=this.settings.refreshTokenAllowedScope.split(" ");r=(((s=e.scope)==null?void 0:s.split(" "))||[]).filter(h=>c.includes(h)).join(" ")}const n=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,resource:e.resource,scope:r,timeoutInSeconds:t}),o=new se(new URLSearchParams);return Object.assign(o,n),i.debug("validating response",o),await this._validator.validateRefreshResponse(o,{...e,scope:r}),o}async createSignoutRequest({state:e,id_token_hint:t,client_id:s,request_type:i,post_logout_redirect_uri:r=this.settings.post_logout_redirect_uri,extraQueryParams:n=this.settings.extraQueryParams}={}){const 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),!s&&r&&!t&&(s=this.settings.client_id);const l=new Ye({url:c,id_token_hint:t,client_id:s,post_logout_redirect_uri:r,state_data:e,extraQueryParams:n,request_type:i});await this.clearStaleState();const h=l.state;return h&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(h.id,h.toStorageString())),l}async readSignoutResponseState(e,t=!1){const s=this._logger.create("readSignoutResponseState"),i=new Ze(Q.readParams(e,this.settings.response_mode));if(!i.state){if(s.debug("No state in response"),i.error)throw s.warn("Response was error:",i.error),new q(i);return{state:void 0,response:i}}const r=await this.settings.stateStore[t?"remove":"get"](i.state);if(!r)throw s.throw(new Error("No matching state found in storage")),null;return{state:W.fromStorageString(r),response:i}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:s,response:i}=await this.readSignoutResponseState(e,!0);return s?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(i,s)):t.debug("No state from storage; skipping response validation"),i}clearStaleState(){return this._logger.create("clearStaleState"),W.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})}},rt=class{constructor(e){this._userManager=e,this._logger=new f("SessionMonitor"),this._start=async t=>{const s=t.session_state;if(!s)return;const i=this._logger.create("_start");if(t.profile?(this._sub=t.profile.sub,this._sid=t.profile.sid,i.debug("session_state",s,", sub",this._sub)):(this._sub=void 0,this._sid=void 0,i.debug("session_state",s,", anonymous user")),this._checkSessionIFrame){this._checkSessionIFrame.start(s);return}try{const r=await this._userManager.metadataService.getCheckSessionIframe();if(r){i.debug("initializing check session iframe");const n=this._userManager.settings.client_id,o=this._userManager.settings.checkSessionIntervalInSeconds,c=this._userManager.settings.stopCheckSessionOnError,l=new Be(this._callback,n,r,o,c);await l.load(),this._checkSessionIFrame=l,l.start(s)}else i.warn("no check session iframe found in the metadata")}catch(r){i.error("Error from getCheckSessionIframe:",r instanceof Error?r.message:r)}},this._stop=()=>{const t=this._logger.create("_stop");if(this._sub=void 0,this._sid=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const s=setInterval(async()=>{clearInterval(s);try{const i=await this._userManager.querySessionStatus();if(i){const r={session_state:i.session_state,profile:i.sub&&i.sid?{sub:i.sub,sid:i.sid}:null};this._start(r)}}catch(i){t.error("error from querySessionStatus",i instanceof Error?i.message:i)}},1e3)}},this._callback=async()=>{const t=this._logger.create("_callback");try{const s=await this._userManager.querySessionStatus();let i=!0;s&&this._checkSessionIFrame?s.sub===this._sub?(i=!1,this._checkSessionIFrame.start(s.session_state),s.sid===this._sid?t.debug("same sub still logged in at OP, restarting check session iframe; session_state",s.session_state):(t.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",s.session_state),this._userManager.events._raiseUserSessionChanged())):t.debug("different subject signed into OP",s.sub):t.debug("subject no longer signed into OP"),i?this._sub?this._userManager.events._raiseUserSignedOut():this._userManager.events._raiseUserSignedIn():t.debug("no change in session detected, no event to raise")}catch(s){this._sub&&(t.debug("Error calling queryCurrentSigninSession; raising signed out event",s),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");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const t=await this._userManager.querySessionStatus();if(t){const s={session_state:t.session_state,profile:t.sub&&t.sid?{sub:t.sub,sid:t.sid}:null};this._start(s)}}}},F=class{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-I.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+I.getEpochTime())}get expired(){const 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 f("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 f.createStatic("User","fromStorageString"),new F(JSON.parse(e))}},me="oidc-client",ve=class{constructor(){this._abort=new M("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const 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);const{url:s,keepOpen:i}=await new Promise((r,n)=>{const o=c=>{var l;const h=c.data,u=(l=e.scriptOrigin)!=null?l:window.location.origin;if(!(c.origin!==u||(h==null?void 0:h.source)!==me)){try{const g=Q.readParams(h.url,e.response_mode).get("state");if(g||t.warn("no state found in response url"),c.source!==this._window&&g!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}r(h)}};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:s}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,s=!1,i=window.location.origin){e.postMessage({source:me,url:t,keepOpen:s},i)}},Se={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},ye="_blank",nt=60,ot=2,be=10,at=class extends ee{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:s=e.post_logout_redirect_uri,popupWindowFeatures:i=Se,popupWindowTarget:r=ye,redirectMethod:n="assign",redirectTarget:o="self",iframeNotifyParentOrigin:c=e.iframeNotifyParentOrigin,iframeScriptOrigin:l=e.iframeScriptOrigin,silent_redirect_uri:h=e.redirect_uri,silentRequestTimeoutInSeconds:u=be,automaticSilentRenew:g=!0,validateSubOnSilentRenew:S=!0,includeIdTokenInSilentRenew:m=!1,monitorSession:b=!1,monitorAnonymousSession:p=!1,checkSessionIntervalInSeconds:v=ot,query_status_response_type:E="code",stopCheckSessionOnError:a=!0,revokeTokenTypes:d=["access_token","refresh_token"],revokeTokensOnSignout:_=!1,includeIdTokenInSilentSignout:w=!1,accessTokenExpiringNotificationTimeInSeconds:y=nt,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=s,this.popupWindowFeatures=i,this.popupWindowTarget=r,this.redirectMethod=n,this.redirectTarget=o,this.iframeNotifyParentOrigin=c,this.iframeScriptOrigin=l,this.silent_redirect_uri=h,this.silentRequestTimeoutInSeconds=u,this.automaticSilentRenew=g,this.validateSubOnSilentRenew=S,this.includeIdTokenInSilentRenew=m,this.monitorSession=b,this.monitorAnonymousSession=p,this.checkSessionIntervalInSeconds=v,this.stopCheckSessionOnError=a,this.query_status_response_type=E,this.revokeTokenTypes=d,this.revokeTokensOnSignout=_,this.includeIdTokenInSilentSignout=w,this.accessTokenExpiringNotificationTimeInSeconds=y,k)this.userStore=k;else{const R=typeof window<"u"?window.sessionStorage:new fe;this.userStore=new Z({store:R})}}},ie=class extends ve{constructor({silentRequestTimeoutInSeconds:e=be}){super(),this._logger=new f("IFrameWindow"),this._timeoutInSeconds=e,this._frame=ie.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>this._abort.raise(new X("IFrame timed out without a response")),this._timeoutInSeconds*1e3);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",t=>{var s;const i=t.target;(s=i.parentNode)==null||s.removeChild(i),this._abort.raise(new Error("IFrame removed from DOM"))},!0),(e=this._frame.contentWindow)==null||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},ct=class{constructor(e){this._settings=e,this._logger=new f("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)}},lt=500,dt=1e3,ke=class extends ve{constructor({popupWindowTarget:e=ye,popupWindowFeatures:t={}}){super(),this._logger=new f("PopupWindow");const s=pe.center({...Se,...t});this._window=window.open(void 0,e,pe.serialize(s)),t.closePopupWindowAfterInSeconds&&t.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()},t.closePopupWindowAfterInSeconds*dt)}async navigate(e){var t;(t=this._window)==null||t.focus();const s=setInterval(()=>{(!this._window||this._window.closed)&&this._abort.raise(new Error("Popup closed by user"))},lt);return this._disposeHandlers.add(()=>clearInterval(s)),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){if(!window.opener)throw new Error("No window.opener. Can't complete notification.");return super._notifyParent(window.opener,e,t)}},ht=class{constructor(e){this._settings=e,this._logger=new f("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget}){return new ke({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),ke.notifyOpener(e,t)}},gt=class{constructor(e){this._settings=e,this._logger=new f("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var s;this._logger.create("prepare");let i=window.self;t==="top"&&(i=(s=window.top)!=null?s:window.self);const r=i.location[e].bind(i.location);let n;return{navigate:async o=>{this._logger.create("navigate");const c=new Promise((l,h)=>{n=h});return r(o.url),await c},close:()=>{this._logger.create("close"),n==null||n(new Error("Redirect aborted")),i.stop()}}}async callback(){}},ut=class extends We{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new f("UserManagerEvents"),this._userLoaded=new M("User loaded"),this._userUnloaded=new M("User unloaded"),this._silentRenewError=new M("Silent renew error"),this._userSignedIn=new M("User signed in"),this._userSignedOut=new M("User signed out"),this._userSessionChanged=new M("User session changed")}load(e,t=!0){super.load(e),t&&this._userLoaded.raise(e)}unload(){super.unload(),this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}_raiseSilentRenewError(e){this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}_raiseUserSignedIn(){this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}_raiseUserSignedOut(){this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}_raiseUserSessionChanged(){this._userSessionChanged.raise()}},_t=class{constructor(e){this._userManager=e,this._logger=new f("SilentRenewService"),this._isStarted=!1,this._retryTimer=new I("Retry Silent Renew"),this._tokenExpiring=async()=>{const t=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),t.debug("silent token renewal successful")}catch(s){if(s instanceof X){t.warn("ErrorTimeout from signinSilent:",s,"retry in 5s"),this._retryTimer.init(5);return}t.error("Error from signinSilent:",s),this._userManager.events._raiseSilentRenewError(s)}}}async start(){const 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)}},pt=class{constructor(e,t){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.resource=t,this.data=e.state}},ft=class{constructor(e,t,s,i){this._logger=new f("UserManager"),this.settings=new at(e),this._client=new it(e),this._redirectNavigator=t??new gt(this.settings),this._popupNavigator=s??new ht(this.settings),this._iframeNavigator=i??new ct(this.settings),this._events=new ut(this.settings),this._silentRenewService=new _t(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new rt(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(){const 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(){const 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");const{redirectMethod:t,...s}=e,i=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:"si:r",...s},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),s=await this._signinEnd(e);return s.profile&&s.profile.sub?t.info("success, signed in subject",s.profile.sub):t.info("no subject"),s}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:s=!1}){const i=this._logger.create("signinResourceOwnerCredential"),r=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:s,extraTokenParams:this.settings.extraTokenParams});i.debug("got signin response");const n=await this._buildUser(r);return n.profile&&n.profile.sub?i.info("success, signed in subject",n.profile.sub):i.info("no subject"),n}async signinPopup(e={}){const t=this._logger.create("signinPopup"),{popupWindowFeatures:s,popupWindowTarget:i,...r}=e,n=this.settings.popup_redirect_uri;n||t.throw(new Error("No popup_redirect_uri configured"));const o=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i}),c=await this._signin({request_type:"si:p",redirect_uri:n,display:"popup",...r},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){const s=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),s.info("success")}async signinSilent(e={}){var t;const s=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:i,resource:r,...n}=e;let o=await this._loadUser();if(o!=null&&o.refresh_token){s.debug("using refresh token");const u=new pt(o,r);return await this._useRefreshToken(u)}const c=this.settings.silent_redirect_uri;c||s.throw(new Error("No silent_redirect_uri configured"));let l;o&&this.settings.validateSubOnSilentRenew&&(s.debug("subject prior to silent renew:",o.profile.sub),l=o.profile.sub);const h=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i});return o=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?o==null?void 0:o.id_token:void 0,...n},h,l),o&&((t=o.profile)!=null&&t.sub?s.info("success, signed in subject",o.profile.sub):s.info("no subject")),o}async _useRefreshToken(e){const t=await this._client.useRefreshToken({state:e,timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds}),s=new F({...e,...t});return await this.storeUser(s),this._events.load(s),s}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{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){const{state:s}=await this._client.readSignoutResponseState(e);if(s)switch(s.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={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:s,...i}=e,r=this.settings.silent_redirect_uri;r||t.throw(new Error("No silent_redirect_uri configured"));const n=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s}),c=await this._signinStart({request_type:"si:s",redirect_uri:r,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{const l=await this._client.processSigninResponse(c.url);return t.debug("got signin response"),l.session_state&&l.profile.sub?(t.info("success for subject",l.profile.sub),{session_state:l.session_state,sub:l.profile.sub,sid:l.profile.sid}):(t.info("success, user not authenticated"),null)}catch(l){if(this.settings.monitorAnonymousSession&&l instanceof q)switch(l.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:l.session_state}}throw l}}async _signin(e,t,s){const i=await this._signinStart(e,t);return await this._signinEnd(i.url,s)}async _signinStart(e,t){const s=this._logger.create("_signinStart");try{const i=await this._client.createSigninRequest(e);return s.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 s.debug("error after preparing navigator, closing navigator window"),t.close(),i}}async _signinEnd(e,t){const s=this._logger.create("_signinEnd"),i=await this._client.processSigninResponse(e);return s.debug("got signin response"),await this._buildUser(i,t)}async _buildUser(e,t){const s=this._logger.create("_buildUser"),i=new F(e);if(t){if(t!==i.profile.sub)throw s.debug("current user does not match user returned from signin. sub from signin:",i.profile.sub),new q({...e,error:"login_required"});s.debug("current user matches user returned from signin")}return await this.storeUser(i),s.debug("user stored"),this._events.load(i),i}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:s,...i}=e,r=await this._redirectNavigator.prepare({redirectMethod:s});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...i},r),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),s=await this._signoutEnd(e);return t.info("success"),s}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:s,popupWindowTarget:i,...r}=e,n=this.settings.popup_post_logout_redirect_uri,o=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i});await this._signout({request_type:"so:p",post_logout_redirect_uri:n,state:n==null?void 0:{},...r},o),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const s=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),s.info("success")}async _signout(e,t){const s=await this._signoutStart(e,t);return await this._signoutEnd(s.url)}async _signoutStart(e={},t){var s;const i=this._logger.create("_signoutStart");try{const r=await this._loadUser();i.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(r);const n=e.id_token_hint||r&&r.id_token;n&&(i.debug("setting id_token_hint in signout request"),e.id_token_hint=n),await this.removeUser(),i.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return i.debug("got signout request"),await t.navigate({url:o.url,state:(s=o.state)==null?void 0:s.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(r){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),r}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),s=await this._client.processSignoutResponse(e);return t.debug("got signout response"),s}async signoutSilent(e={}){var t;const s=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:i,...r}=e,n=this.settings.includeIdTokenInSilentSignout?(t=await this._loadUser())==null?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,c=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:i});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:n,...r},c),s.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const s=this._logger.create("_revokeInternal");if(!e)return;const i=t.filter(r=>typeof e[r]=="string");if(!i.length){s.debug("no need to revoke due to no token(s)");return}for(const r of i)await this._client.revokeToken(e[r],r),s.info(`${r} revoked successfully`),r!=="access_token"&&(e[r]=null);await this.storeUser(e),s.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(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),F.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const s=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,s)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey)}async clearStaleState(){await this._client.clearStaleState()}};const wt="code",mt="openid profile",Ee=60,Re=600,vt=2,Te=class ce{constructor({authorizationServer:t,clientId:s,redirectUri:i,silentRedirectUri:r,postLogoutRedirectUri:n,scopes:o,automaticRenewIfActivity:c=!0,logLevel:l=N.ERROR,automaticReSignInIfSilentRenewError:h=!0,defaultExtraQueryParamsOnSignInRenew:u={},defaultStateOnSignInRenew:g={}}){if(!t)throw Error("The authorizationServer is mandatory for SecurityManager construction");if(!s)throw Error("The clientId is mandatory for SecurityManager construction");if(!i)throw Error("The redirectUri is mandatory for SecurityManager construction");if(!r)throw Error("The silentRedirectUri is mandatory for SecurityManager construction");if(!n)throw Error("The postLogoutRedirectUri is mandatory for SecurityManager construction");this.authorizationServer=t,this.clientId=s,this.redirectUri=i,this.silentRedirectUri=r,this.postLogoutRedirectUri=n,this.scopes=mt,o&&(this.scopes=this.scopes.concat(..." "+o.trim())),this.automaticRenewIfActivity=c,this.automaticReSignInIfSilentRenewError=h,this.checkSessionTimestamp=void 0,this.checkSessionCooldownPeriod=Re,this.isUtilisateurActif=!1,this.defaultExtraQueryParamsOnSignInRenew=u,this.defaultStateOnSignInRenew=g,this.userLoaded=null,this.userUnloaded=null,this.userManager=new ft({userStore:new Z({store:window.sessionStorage}),authority:this.authorizationServer,client_id:this.clientId,redirect_uri:this.redirectUri,silent_redirect_uri:this.silentRedirectUri,post_logout_redirect_uri:this.postLogoutRedirectUri,response_type:wt,scope:this.scopes,loadUserInfo:!1,automaticSilentRenew:!1,validateSubOnSilentRenew:!1,includeIdTokenInSilentRenew:!0,accessTokenExpiringNotificationTimeInSeconds:Ee,revokeTokensOnSignout:!0}),N.setLogger(console),N.setLevel(l),this.logger=new f("logger"),this.setEvents(),this.automaticRenewIfActivity&&(window.addEventListener("keydown",this.manageUserActivity.bind(this)),window.addEventListener("click",this.manageUserActivity.bind(this)))}async manageUserActivity(){this.isUtilisateurActif=!0;const t=new Date().getTime();if(this.logger.debug("SecurityManager.manageUserActivity()","Détection activité utilisateur"),!this.checkSessionTimestamp||this.checkSessionTimestamp+this.checkSessionCooldownPeriod*1e3{this.logger.debug("EVENT/addUserLoaded event",t)}),this.userManager.events.addUserUnloaded((...t)=>{this.logger.debug("EVENT/addUserUnloaded event",t)}),this.userManager.events.addAccessTokenExpiring(async(...t)=>{this.logger.debug("EVENT/addAccessTokenExpiring",t),this.isUtilisateurActif&&await this.signInSilent(!0)}),this.userManager.events.addAccessTokenExpired((...t)=>{this.logger.debug("EVENT/addAccessTokenExpired",t)}),this.userManager.events.addSilentRenewError((...t)=>{this.logger.debug("EVENT/addSilentRenewError",t),this.automaticReSignInIfSilentRenewError?this.signIn({extraQueryParams:this.defaultExtraQueryParamsOnSignInRenew,state:this.defaultStateOnSignInRenew,prompt:void 0}):dispatchEvent(new Event(ce.EVENT_SILENT_RENEW_ERROR))})}async signIn({extraQueryParams:t={},state:s={},prompt:i}){(await this.isUserAnonymous()||await this.isUserExpired()||i==="login")&&(s.routeToReach||(s.routeToReach=window.location.href),await this.userManager.signinRedirect({extraQueryParams:t,state:s,prompt:i}))}async isUserAnonymous(){return!await this.getUser()}async isUserExpired(){const t=await this.getUser();return!!(t&&Number(t.expires_in)<=Ee)}async signInSilent(t=void 0){try{this.isUtilisateurActif=!1,await this.userManager.signinSilent({silentRequestTimeoutInSeconds:vt})}catch(s){this.logger.warn("SecurityManager/signInSilent() error",s),t??this.automaticReSignInIfSilentRenewError?await this.signIn({extraQueryParams:this.defaultExtraQueryParamsOnSignInRenew,state:this.defaultStateOnSignInRenew,prompt:void 0}):dispatchEvent(new Event(ce.EVENT_SILENT_RENEW_ERROR))}}async signOut(){await this.userManager.signoutRedirect()}async getUser(){return await this.userManager.getUser()}async getAccessToken(t=!1){let s=await this.getUser();if((t||this.automaticRenewIfActivity&&await this.isUserExpired())&&(await this.signInSilent(),s=await this.getUser()),s)return s.access_token}async getDecodedAccessToken(){return J(String(await this.getAccessToken()))}async getIdToken(){const t=await this.getUser();return t==null?void 0:t.id_token}async getDecodedIdToken(){return J(String(await this.getIdToken()))}async getInfosUtilisateurConnecte(){const t={uid:"",suId:"",nom:"",prenom:"",email:"",collaborateurPermanent:!1,collaborateurMagasin:!1,collaborateurPartenaire:!1,login:"",loginUnique:"",loginIBMi:"",matriculeRH:"",centraleConnexion:{code:"",libelle:""},magasinConnexion:{codeMagasin:"",codeLieuFonction:"",raisonSociale:""},partenaireConnexion:{code:""},groups:[]},s=await this.getDecodedAccessToken();t.uid=s.uid,t.suId=s.sub,t.login=s.login,t.nom=s.family_name,t.prenom=s.given_name,t.email=s.mail,t.loginIBMi=s.suLoginIBMi,t.loginUnique=s.suLoginUnique,t.matriculeRH=s.matricule,t.collaborateurPermanent=s.isUserCentrale,t.collaborateurMagasin=s.isUserPdv,t.collaborateurPartenaire=s.isUserPartner,t.collaborateurPermanent?(t.centraleConnexion.code=s.code_centrale,t.centraleConnexion.libelle=s.organisation):t.collaborateurMagasin?(t.magasinConnexion.codeMagasin=s.code_magasin,t.magasinConnexion.codeLieuFonction=s.code_associe,t.magasinConnexion.raisonSociale=s.organisation):t.collaborateurPartenaire&&(t.partenaireConnexion.code=s.organisation);for(const i in s)i.endsWith(".groups")&&t.groups.push(s[i]);return t}};Te.EVENT_SILENT_RENEW_ERROR="uirisfrontsecurity/silentRenewError";let St=Te;j.SecurityManager=St,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"})});