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 2.0.0-rc.4 to 2.0.0-rc.5

2

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

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

var oidc=(()=>{var Ge=Object.create;var re=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var Ue=a=>re(a,"__esModule",{value:!0});var Ie=(a=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(a,{get:(e,t)=>(typeof require!="undefined"?require:e)[t]}):a)(function(a){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+a+'" is not supported')});var z=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),tt=(a,e)=>{for(var t in e)re(a,t,{get:e[t],enumerable:!0})},Ee=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Xe(e))!et.call(a,i)&&(t||i!=="default")&&re(a,i,{get:()=>e[i],enumerable:!(r=Ye(e,i))||r.enumerable});return a},ie=(a,e)=>Ee(Ue(re(a!=null?Ge(Ze(a)):{},"default",!e&&a&&a.__esModule?{get:()=>a.default,enumerable:!0}:{value:a,enumerable:!0})),a),rt=(a=>(e,t)=>a&&a.get(e)||(t=Ee(Ue({}),e,1),a&&a.set(e,t),t))(typeof WeakMap!="undefined"?new WeakMap:0);var Te=z(()=>{});var $=z((se,Ae)=>{(function(a,e){typeof se=="object"?Ae.exports=se=e():typeof define=="function"&&define.amd?define([],e):a.CryptoJS=e()})(se,function(){var a=a||function(e,t){var r;if(typeof window!="undefined"&&window.crypto&&(r=window.crypto),typeof self!="undefined"&&self.crypto&&(r=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(r=globalThis.crypto),!r&&typeof window!="undefined"&&window.msCrypto&&(r=window.msCrypto),!r&&typeof global!="undefined"&&global.crypto&&(r=global.crypto),!r&&typeof Ie=="function")try{r=Te()}catch{}var i=function(){if(r){if(typeof r.getRandomValues=="function")try{return r.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof r.randomBytes=="function")try{return r.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},s=Object.create||function(){function o(){}return function(g){var S;return o.prototype=g,S=new o,o.prototype=null,S}}(),n={},c=n.lib={},d=c.Base=function(){return{extend:function(o){var g=s(this);return o&&g.mixIn(o),(!g.hasOwnProperty("init")||this.init===g.init)&&(g.init=function(){g.$super.init.apply(this,arguments)}),g.init.prototype=g,g.$super=this,g},create:function(){var o=this.extend();return o.init.apply(o,arguments),o},init:function(){},mixIn:function(o){for(var g in o)o.hasOwnProperty(g)&&(this[g]=o[g]);o.hasOwnProperty("toString")&&(this.toString=o.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),u=c.WordArray=d.extend({init:function(o,g){o=this.words=o||[],g!=t?this.sigBytes=g:this.sigBytes=o.length*4},toString:function(o){return(o||_).stringify(this)},concat:function(o){var g=this.words,S=o.words,m=this.sigBytes,y=o.sigBytes;if(this.clamp(),m%4)for(var v=0;v<y;v++){var P=S[v>>>2]>>>24-v%4*8&255;g[m+v>>>2]|=P<<24-(m+v)%4*8}else for(var R=0;R<y;R+=4)g[m+R>>>2]=S[R>>>2];return this.sigBytes+=y,this},clamp:function(){var o=this.words,g=this.sigBytes;o[g>>>2]&=4294967295<<32-g%4*8,o.length=e.ceil(g/4)},clone:function(){var o=d.clone.call(this);return o.words=this.words.slice(0),o},random:function(o){for(var g=[],S=0;S<o;S+=4)g.push(i());return new u.init(g,o)}}),f=n.enc={},_=f.Hex={stringify:function(o){for(var g=o.words,S=o.sigBytes,m=[],y=0;y<S;y++){var v=g[y>>>2]>>>24-y%4*8&255;m.push((v>>>4).toString(16)),m.push((v&15).toString(16))}return m.join("")},parse:function(o){for(var g=o.length,S=[],m=0;m<g;m+=2)S[m>>>3]|=parseInt(o.substr(m,2),16)<<24-m%8*4;return new u.init(S,g/2)}},h=f.Latin1={stringify:function(o){for(var g=o.words,S=o.sigBytes,m=[],y=0;y<S;y++){var v=g[y>>>2]>>>24-y%4*8&255;m.push(String.fromCharCode(v))}return m.join("")},parse:function(o){for(var g=o.length,S=[],m=0;m<g;m++)S[m>>>2]|=(o.charCodeAt(m)&255)<<24-m%4*8;return new u.init(S,g)}},p=f.Utf8={stringify:function(o){try{return decodeURIComponent(escape(h.stringify(o)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(o){return h.parse(unescape(encodeURIComponent(o)))}},w=c.BufferedBlockAlgorithm=d.extend({reset:function(){this._data=new u.init,this._nDataBytes=0},_append:function(o){typeof o=="string"&&(o=p.parse(o)),this._data.concat(o),this._nDataBytes+=o.sigBytes},_process:function(o){var g,S=this._data,m=S.words,y=S.sigBytes,v=this.blockSize,P=v*4,R=y/P;o?R=e.ceil(R):R=e.max((R|0)-this._minBufferSize,0);var E=R*v,N=e.min(E*4,y);if(E){for(var W=0;W<E;W+=v)this._doProcessBlock(m,W);g=m.splice(0,E),S.sigBytes-=N}return new u.init(g,N)},clone:function(){var o=d.clone.call(this);return o._data=this._data.clone(),o},_minBufferSize:0}),b=c.Hasher=w.extend({cfg:d.extend(),init:function(o){this.cfg=this.cfg.extend(o),this.reset()},reset:function(){w.reset.call(this),this._doReset()},update:function(o){return this._append(o),this._process(),this},finalize:function(o){o&&this._append(o);var g=this._doFinalize();return g},blockSize:512/32,_createHelper:function(o){return function(g,S){return new o.init(S).finalize(g)}},_createHmacHelper:function(o){return function(g,S){return new k.HMAC.init(o,S).finalize(g)}}}),k=n.algo={};return n}(Math);return a})});var Oe=z((ne,Me)=>{(function(a,e){typeof ne=="object"?Me.exports=ne=e($()):typeof define=="function"&&define.amd?define(["./core"],e):e(a.CryptoJS)})(ne,function(a){return function(e){var t=a,r=t.lib,i=r.WordArray,s=r.Hasher,n=t.algo,c=[],d=[];(function(){function _(b){for(var k=e.sqrt(b),o=2;o<=k;o++)if(!(b%o))return!1;return!0}function h(b){return(b-(b|0))*4294967296|0}for(var p=2,w=0;w<64;)_(p)&&(w<8&&(c[w]=h(e.pow(p,1/2))),d[w]=h(e.pow(p,1/3)),w++),p++})();var u=[],f=n.SHA256=s.extend({_doReset:function(){this._hash=new i.init(c.slice(0))},_doProcessBlock:function(_,h){for(var p=this._hash.words,w=p[0],b=p[1],k=p[2],o=p[3],g=p[4],S=p[5],m=p[6],y=p[7],v=0;v<64;v++){if(v<16)u[v]=_[h+v]|0;else{var P=u[v-15],R=(P<<25|P>>>7)^(P<<14|P>>>18)^P>>>3,E=u[v-2],N=(E<<15|E>>>17)^(E<<13|E>>>19)^E>>>10;u[v]=R+u[v-7]+N+u[v-16]}var W=g&S^~g&m,pe=w&b^w&k^b&k,he=(w<<30|w>>>2)^(w<<19|w>>>13)^(w<<10|w>>>22),Qe=(g<<26|g>>>6)^(g<<21|g>>>11)^(g<<7|g>>>25),Ce=y+Qe+W+d[v]+u[v],Ve=he+pe;y=m,m=S,S=g,g=o+Ce|0,o=k,k=b,b=w,w=Ce+Ve|0}p[0]=p[0]+w|0,p[1]=p[1]+b|0,p[2]=p[2]+k|0,p[3]=p[3]+o|0,p[4]=p[4]+g|0,p[5]=p[5]+S|0,p[6]=p[6]+m|0,p[7]=p[7]+y|0},_doFinalize:function(){var _=this._data,h=_.words,p=this._nDataBytes*8,w=_.sigBytes*8;return h[w>>>5]|=128<<24-w%32,h[(w+64>>>9<<4)+14]=e.floor(p/4294967296),h[(w+64>>>9<<4)+15]=p,_.sigBytes=h.length*4,this._process(),this._hash},clone:function(){var _=s.clone.call(this);return _._hash=this._hash.clone(),_}});t.SHA256=s._createHelper(f),t.HmacSHA256=s._createHmacHelper(f)}(Math),a.SHA256})});var Ne=z((oe,qe)=>{(function(a,e){typeof oe=="object"?qe.exports=oe=e($()):typeof define=="function"&&define.amd?define(["./core"],e):e(a.CryptoJS)})(oe,function(a){return function(){var e=a,t=e.lib,r=t.WordArray,i=e.enc,s=i.Base64={stringify:function(c){var d=c.words,u=c.sigBytes,f=this._map;c.clamp();for(var _=[],h=0;h<u;h+=3)for(var p=d[h>>>2]>>>24-h%4*8&255,w=d[h+1>>>2]>>>24-(h+1)%4*8&255,b=d[h+2>>>2]>>>24-(h+2)%4*8&255,k=p<<16|w<<8|b,o=0;o<4&&h+o*.75<u;o++)_.push(f.charAt(k>>>6*(3-o)&63));var g=f.charAt(64);if(g)for(;_.length%4;)_.push(g);return _.join("")},parse:function(c){var d=c.length,u=this._map,f=this._reverseMap;if(!f){f=this._reverseMap=[];for(var _=0;_<u.length;_++)f[u.charCodeAt(_)]=_}var h=u.charAt(64);if(h){var p=c.indexOf(h);p!==-1&&(d=p)}return n(c,d,f)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};function n(c,d,u){for(var f=[],_=0,h=0;h<d;h++)if(h%4){var p=u[c.charCodeAt(h-1)]<<h%4*2,w=u[c.charCodeAt(h)]>>>6-h%4*2,b=p|w;f[_>>>2]|=b<<24-_%4*8,_++}return r.create(f,_)}}(),a.enc.Base64})});var Le=z((ae,We)=>{(function(a,e){typeof ae=="object"?We.exports=ae=e($()):typeof define=="function"&&define.amd?define(["./core"],e):e(a.CryptoJS)})(ae,function(a){return a.enc.Utf8})});var kt={};tt(kt,{AccessTokenEvents:()=>Q,CheckSessionIFrame:()=>V,ErrorResponse:()=>U,InMemoryWebStorage:()=>j,Log:()=>L,Logger:()=>l,MetadataService:()=>G,OidcClient:()=>le,OidcClientSettingsStore:()=>B,SessionMonitor:()=>Z,SigninResponse:()=>K,SigninState:()=>O,SignoutResponse:()=>X,State:()=>I,User:()=>q,UserManager:()=>Ke,UserManagerSettingsStore:()=>te,Version:()=>$e,WebStorageStateStore:()=>H});var je=ie($()),Fe=ie(Oe()),fe=ie(Ne()),He=ie(Le());var it={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},A,M,L=(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))(L||{});(r=>{function a(){A=3,M=it}r.reset=a;function e(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");A=i}r.setLevel=e;function t(i){M=i}r.setLogger=t})(L||(L={}));var l=class{constructor(e){this._name=e}debug(...e){A>=4&&M.debug(l._format(this._name,this._method),...e)}info(...e){A>=3&&M.info(l._format(this._name,this._method),...e)}warn(...e){A>=2&&M.warn(l._format(this._name,this._method),...e)}error(...e){A>=1&&M.error(l._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 _format(e,t){let r=`[${e}]`;return t?r+` ${t}:`:r}static debug(e,...t){A>=4&&M.debug(l._format(e),...t)}static info(e,...t){A>=3&&M.info(l._format(e),...t)}static warn(e,...t){A>=2&&M.warn(l._format(e),...t)}static error(e,...t){A>=1&&M.error(l._format(e),...t)}};L.reset();var st="10000000-1000-4000-8000-100000000000",C=class{static _randomWord(){return je.default.lib.WordArray.random(1).words[0]}static generateUUIDv4(){return st.replace(/[018]/g,t=>(+t^C._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return C.generateUUIDv4()+C.generateUUIDv4()+C.generateUUIDv4()}static generateCodeChallenge(e){try{let t=(0,Fe.default)(e);return fe.default.stringify(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw l.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){let r=He.default.parse([e,t].join(":"));return fe.default.stringify(r)}};var T=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)}};function _e(a){this.message=a}_e.prototype=new Error,_e.prototype.name="InvalidCharacterError";var Be=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(a){var e=String(a).replace(/=+$/,"");if(e.length%4==1)throw new _e("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,r,i=0,s=0,n="";r=e.charAt(s++);~r&&(t=i%4?64*t+r:r,i++%4)?n+=String.fromCharCode(255&t>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return n};function nt(a){var e=a.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(Be(t).replace(/(.)/g,function(r,i){var s=i.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch{return Be(e)}}function ce(a){this.message=a}function ot(a,e){if(typeof a!="string")throw new ce("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(nt(a.split(".")[t]))}catch(r){throw new ce("Invalid token specified: "+r.message)}}ce.prototype=new Error,ce.prototype.name="InvalidTokenError";var Je=ot;var J=class{static decode(e){try{return Je(e)}catch(t){throw l.error("JwtUtils.decode",t),t}}};var de=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 x=class extends T{constructor(){super(...arguments);this._logger=new l(`Timer('${this._name}')`);this._timerHandle=null;this._expiration=0;this._callback=()=>{let e=this._expiration-x.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=x.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){let t=this._logger.create("init");e=Math.max(Math.floor(e),1);let r=x.getEpochTime()+e;if(this.expiration===r&&this._timerHandle){t.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),t.debug("using duration",e),this._expiration=r;let 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)}};var D=class{static readParams(e,t="query"){let i=new URL(e)[t==="fragment"?"hash":"search"];return new URLSearchParams(i.slice(1))}};var Q=class{constructor(e){this._logger=new l("AccessTokenEvents");this._expiringTimer=new x("Access token expiring");this._expiredTimer=new x("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 V=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=r.indexOf("/",r.indexOf("//")+2);this._frame_origin=r.substr(0,n),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=r}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 U=class extends Error{constructor(e,t){super(e.error_description||e.error||"");this.form=t;this.name="ErrorResponse";var r,i,s;if(!e.error)throw l.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=(r=e.error_description)!=null?r:null,this.error_uri=(i=e.error_uri)!=null?i:null,this.state=e.userState,this.session_state=(s=e.session_state)!=null?s:null}};var j=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 F=class{constructor(e=[],t=null){this._jwtHandler=t;this._logger=new l("JsonService");this._contentTypes=[];this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async getJson(e,t){let r=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};t&&(r.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t);let s;try{r.debug("url:",e),s=await fetch(e,{method:"GET",headers:i})}catch(d){throw r.error("Network Error"),d}r.debug("HTTP response received, status",s.status);let n=s.headers.get("Content-Type");if(n&&!this._contentTypes.find(d=>n.startsWith(d))&&r.throw(new Error(`Invalid response Content-Type: ${n!=null?n:"undefined"}, from URL: ${e}`)),s.ok&&this._jwtHandler&&(n==null?void 0:n.startsWith("application/jwt")))return await this._jwtHandler(await s.text());let c;try{c=await s.json()}catch(d){throw r.error("Error parsing JSON response",d),s.ok?d:new Error(`${s.statusText} (${s.status})`)}if(!s.ok)throw r.error("Error from server:",c),c.error?new U(c):new Error(`${s.statusText} (${s.status}): ${JSON.stringify(c)}`);return c}async postForm(e,t,r){let i=this._logger.create("postForm"),s={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};r!==void 0&&(s.Authorization="Basic "+r);let n;try{i.debug("url:",e),n=await fetch(e,{method:"POST",headers:s,body:t})}catch(f){throw i.error("Network error"),f}i.debug("HTTP response received, status",n.status);let c=n.headers.get("Content-Type");if(c&&!this._contentTypes.find(f=>c.startsWith(f)))throw new Error(`Invalid response Content-Type: ${c!=null?c:"undefined"}, from URL: ${e}`);let d=await n.text(),u={};if(d)try{u=JSON.parse(d)}catch(f){throw i.error("Error parsing JSON response",f),n.ok?f:new Error(`${n.statusText} (${n.status})`)}if(!n.ok)throw i.error("Error from server:",u),u.error?new U(u,t):new Error(`${n.statusText} (${n.status}): ${JSON.stringify(u)}`);return u}};var at=".well-known/openid-configuration",G=class{constructor(e){this._settings=e;this._logger=new l("MetadataService");this._jsonService=new F(["application/jwk-set+json"]);this._metadataUrl=null;this._signingKeys=null;this._metadata=null;this._settings.metadataUrl?this._metadataUrl=this._settings.metadataUrl:this._settings.authority&&(this._metadataUrl=this._settings.authority,this._metadataUrl.endsWith("/")||(this._metadataUrl+="/"),this._metadataUrl+=at),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)}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);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 H=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new l("WebStorageStateStore");this._store=t,this._prefix=e}set(e,t){return this._logger.create(`set('${e}')`),e=this._prefix+e,this._store.setItem(e,t),Promise.resolve()}get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;let t=this._store.getItem(e);return Promise.resolve(t)}remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;let t=this._store.getItem(e);return this._store.removeItem(e),Promise.resolve(t)}getAllKeys(){this._logger.create("getAllKeys");let e=[];for(let t=0;t<this._store.length;t++){let r=this._store.key(t);r&&r.indexOf(this._prefix)===0&&e.push(r.substr(this._prefix.length))}return Promise.resolve(e)}};var ct="code",dt="openid",lt="client_secret_post",gt="query",ut=60*15,pt=60*5,B=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:i,metadataSeed:s,client_id:n,client_secret:c,response_type:d=ct,scope:u=dt,redirect_uri:f,post_logout_redirect_uri:_,client_authentication:h=lt,prompt:p,display:w,max_age:b,ui_locales:k,acr_values:o,resource:g,response_mode:S=gt,filterProtocolClaims:m=!0,loadUserInfo:y=!1,staleStateAgeInSeconds:v=ut,clockSkewInSeconds:P=pt,userInfoJwtIssuer:R="OP",mergeClaims:E=!1,stateStore:N,extraQueryParams:W={},extraTokenParams:pe={}}){if(this.authority=e,this.metadataUrl=t,this.metadata=r,this.metadataSeed=s,this.signingKeys=i,this.client_id=n,this.client_secret=c,this.response_type=d,this.scope=u,this.redirect_uri=f,this.post_logout_redirect_uri=_,this.client_authentication=h,this.prompt=p,this.display=w,this.max_age=b,this.ui_locales=k,this.acr_values=o,this.resource=g,this.response_mode=S,this.filterProtocolClaims=!!m,this.loadUserInfo=!!y,this.staleStateAgeInSeconds=v,this.clockSkewInSeconds=P,this.userInfoJwtIssuer=R,this.mergeClaims=!!E,N)this.stateStore=N;else{let he=typeof window!="undefined"?window.localStorage:new j;this.stateStore=new H({store:he})}this.extraQueryParams=W,this.extraTokenParams=pe}};var me=class{constructor(e){this._metadataService=e;this._logger=new l("UserInfoService");this._getClaimsFromJwt=async e=>{let t=this._logger.create("_getClaimsFromJwt");try{let r=J.decode(e);return t.debug("JWT decoding successful"),r}catch(r){throw t.error("Error parsing JWT response"),r}};this._jsonService=new F(void 0,this._getClaimsFromJwt)}async getClaims(e){let t=this._logger.create("getClaims");if(!e)throw this._logger.error("getClaims: No token passed"),new Error("A token is required");let r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);let i=await this._jsonService.getJson(r,e);return t.debug("got claims",i),i}};var Y=class{constructor(e,t){this._settings=e;this._metadataService=t;this._logger=new l("TokenClient");this._jsonService=new F}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")),s.code_verifier||n.throw(new Error("A code_verifier is required"));let c=new URLSearchParams({grant_type:e,redirect_uri:t});for(let[_,h]of Object.entries(s))h!=null&&c.set(_,h);let d;switch(this._settings.client_authentication){case"client_secret_basic":if(!i)throw n.throw(new Error("A client_secret is required")),null;d=C.generateBasicAuth(r,i);break;case"client_secret_post":c.append("client_id",r),i&&c.append("client_secret",i);break}let u=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");let f=await this._jsonService.postForm(u,c,d);return n.debug("got response"),f}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,...i}){let s=this._logger.create("exchangeRefreshToken");t||s.throw(new Error("A client_id is required")),i.refresh_token||s.throw(new Error("A refresh_token is required"));let n=new URLSearchParams({grant_type:e});for(let[f,_]of Object.entries(i))_!=null&&n.set(f,_);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw s.throw(new Error("A client_secret is required")),null;c=C.generateBasicAuth(t,r);break;case"client_secret_post":n.append("client_id",t),r&&n.append("client_secret",r);break}let d=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");let u=await this._jsonService.postForm(d,n,c);return s.debug("got response"),u}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,c]of Object.entries(e))c!=null&&i.set(n,c);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,i),t.debug("got response")}};var ht=["iss","aud","exp","nbf","iat","jti","auth_time","nonce","acr","amr","azp","at_hash"],we=class{constructor(e,t){this._settings=e;this._metadataService=t;this._logger=new l("ResponseValidator");this._userInfoService=new me(this._metadataService);this._tokenClient=new Y(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),r.debug("claims processed")}async validateRefreshResponse(e,t){var i;let r=this._logger.create("validateRefreshResponse");e.userState=t.data,(i=e.scope)!=null||(e.scope=t.scope),e.isOpenId&&this._validateIdTokenAttributes(e,t.id_token),r.debug("tokens validated"),await this._processClaims(e),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 U(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,(i=e.scope)!=null||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new U(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response")),!t.code_verifier&&e.code&&r.throw(new Error("Unexpected code in response"))}async _processClaims(e,t=!1){let r=this._logger.create("_processClaims");if(!e.isOpenId){r.debug("response is not OIDC, skipping claims processing");return}if(r.debug("response is OIDC, processing claims",e.profile),e.profile=this._filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token){r.debug("not loading user info");return}r.debug("loading user info");let i=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),i.sub!==e.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._mergeClaims(e.profile,this._filterProtocolClaims(i)),r.debug("_processClaims: user info claims received, updated profile:",e.profile)}_mergeClaims(e,t){let r={...e};for(let[i,s]of Object.entries(t))for(let n of Array.isArray(s)?s:[s]){let c=r[i];c?Array.isArray(c)?c.includes(n)||c.push(n):r[i]!==n&&(typeof n=="object"&&this._settings.mergeClaims?r[i]=this._mergeClaims(c,n):r[i]=[c,n]):r[i]=n}return r}_filterProtocolClaims(e){let t={...e};if(this._settings.filterProtocolClaims)for(let r of ht)delete t[r];return t}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=J.decode((s=e.id_token)!=null?s:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),t){let n=J.decode(t);n.sub!==i.sub&&r.throw(new Error("sub in id_token does not match current sub")),n.auth_time&&n.auth_time!==i.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),n.azp&&n.azp!==i.azp&&r.throw(new Error("azp in id_token does not match original azp")),!n.azp&&i.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}};var I=class{constructor(e){this.id=e.id||C.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=x.getEpochTime(),this.request_type=e.request_type}toStorageString(){return new l("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})}static fromStorageString(e){return l.debug("State.fromStorageString"),new I(JSON.parse(e))}static async clearStaleState(e,t){let r=x.getEpochTime()-t,i=await e.getAllKeys();l.debug("State.clearStaleState","got keys",i);for(let s=0;s<i.length;s++){let n=i[s],c=await e.get(n),d=!1;if(c)try{let u=I.fromStorageString(c);l.debug("State.clearStaleState","got item from key: ",n,u.created),u.created<=r&&(d=!0)}catch(u){l.error("State.clearStaleState","Error parsing state for key",n,u),d=!0}else l.debug("State.clearStaleState","no item in storage for key: ",n),d=!0;d&&(l.debug("State.clearStaleState","removed item for key: ",n),e.remove(n))}}};var O=class extends I{constructor(e){super(e);e.code_verifier===!0?this.code_verifier=C.generateCodeVerifier():e.code_verifier&&(this.code_verifier=e.code_verifier),this.code_verifier&&(this.code_challenge=C.generateCodeChallenge(this.code_verifier)),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}toStorageString(){return new l("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,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.debug("SigninState.fromStorageString");let t=JSON.parse(e);return new O(t)}};var Se=class{constructor({url:e,authority:t,client_id:r,redirect_uri:i,response_type:s,scope:n,state_data:c,response_mode:d,request_type:u,client_secret:f,skipUserInfo:_,extraQueryParams:h,extraTokenParams:p,...w}){this._logger=new l("SigninRequest");if(!e)throw this._logger.error("ctor: No url passed"),new Error("url");if(!r)throw this._logger.error("ctor: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("ctor: No redirect_uri passed"),new Error("redirect_uri");if(!s)throw this._logger.error("ctor: No response_type passed"),new Error("response_type");if(!n)throw this._logger.error("ctor: No scope passed"),new Error("scope");if(!t)throw this._logger.error("ctor: No authority passed"),new Error("authority");this.state=new O({data:c,request_type:u,code_verifier:!0,client_id:r,authority:t,redirect_uri:i,response_mode:d,client_secret:f,scope:n,extraTokenParams:p,skipUserInfo:_});let b=new URL(e);b.searchParams.append("client_id",r),b.searchParams.append("redirect_uri",i),b.searchParams.append("response_type",s),b.searchParams.append("scope",n),b.searchParams.append("state",this.state.id),this.state.code_challenge&&(b.searchParams.append("code_challenge",this.state.code_challenge),b.searchParams.append("code_challenge_method","S256"));for(let[k,o]of Object.entries({response_mode:d,...w,...h}))o!=null&&b.searchParams.append(k,o.toString());this.url=b.href}};var ft="openid",K=class{constructor(e){this.access_token="";this.token_type="";this.profile={};this.state=e.get("state"),this.session_state=e.get("session_state"),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-x.getEpochTime()}set expires_in(e){typeof e=="string"&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+x.getEpochTime())}get isOpenId(){var e;return((e=this.scope)==null?void 0:e.split(" ").includes(ft))||!!this.id_token}};var be=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:i,extraQueryParams:s,request_type:n}){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),i&&(c.searchParams.append("post_logout_redirect_uri",i),t&&(this.state=new I({data:t,request_type:n}),c.searchParams.append("state",this.state.id)));for(let[d,u]of Object.entries({...s}))u!=null&&c.searchParams.append(d,u.toString());this.url=c.href}};var X=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 le=class{constructor(e){this._logger=new l("OidcClient");this.settings=new B(e),this.metadataService=new G(this.settings),this._validator=new we(this.settings,this.metadataService),this._tokenClient=new Y(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:i,id_token_hint:s,login_hint:n,skipUserInfo:c,response_type:d=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:f=this.settings.redirect_uri,prompt:_=this.settings.prompt,display:h=this.settings.display,max_age:p=this.settings.max_age,ui_locales:w=this.settings.ui_locales,acr_values:b=this.settings.acr_values,resource:k=this.settings.resource,response_mode:o=this.settings.response_mode,extraQueryParams:g=this.settings.extraQueryParams,extraTokenParams:S=this.settings.extraTokenParams}){let m=this._logger.create("createSigninRequest");if(d!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");let y=await this.metadataService.getAuthorizationEndpoint();m.debug("Received authorization endpoint",y);let v=new Se({url:y,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:f,response_type:d,scope:u,state_data:e,prompt:_,display:h,max_age:p,ui_locales:w,id_token_hint:s,login_hint:n,acr_values:b,resource:k,request:t,request_uri:r,extraQueryParams:g,extraTokenParams:S,request_type:i,response_mode:o,client_secret:this.settings.client_secret,skipUserInfo:c}),P=v.state;return await this.settings.stateStore.set(P.id,P.toStorageString()),v}async readSigninResponseState(e,t=!1){let r=this._logger.create("readSigninResponseState"),i=new K(D.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: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 useRefreshToken(e){let t=this._logger.create("useRefreshToken"),r=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token}),i=new K(new URLSearchParams);return Object.assign(i,r),t.debug("validating response",i),await this._validator.validateRefreshResponse(i,e),i}async createSignoutRequest({state:e,id_token_hint:t,request_type:r,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){let n=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw n.throw(new Error("No end session endpoint")),null;n.debug("createSignoutRequest: Received end session endpoint",c);let d=new be({url:c,id_token_hint:t,post_logout_redirect_uri:i,state_data:e,extraQueryParams:s,request_type:r}),u=d.state;return u&&(n.debug("Signout request has state to persist"),await this.settings.stateStore.set(u.id,u.toStorageString())),d}async readSignoutResponseState(e,t=!1){let r=this._logger.create("readSignoutResponseState"),i=new X(D.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 U(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:I.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"),I.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 Z=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,this._sid=e.profile.sid,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,this._sid=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,c=this._userManager.settings.stopCheckSessionOnError,d=new V(this._callback,s,i,n,c);await d.load(),this._checkSessionIFrame=d,d.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._sid=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&&r.sid?{sub:r.sub,sid:r.sid}: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),t.sid===this._sid?e.debug("same sub still logged in at OP, restarting check session iframe; session_state",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("No user manager passed to SessionMonitor"),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&&t.sid?{sub:t.sub,sid:t.sid}:null};this._start(r)}}}};var q=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}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-x.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+x.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.debug("User.fromStorageString"),new q(JSON.parse(e))}};var De="oidc-client",ee=class{constructor(){this._abort=new T("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 c=d=>{let u=d.data;if(!(d.origin!==window.location.origin||(u==null?void 0:u.source)!==De)){try{let f=D.readParams(u.url,e.response_mode).get("state");if(f||t.warn("no state found in response url"),d.source!==this._window&&f!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}s(u)}};window.addEventListener("message",c,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",c,!1)),this._disposeHandlers.add(this._abort.addHandler(d=>{this._dispose(),n(d)}))});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){e.postMessage({source:De,url:t,keepOpen:r},window.location.origin)}};var _t=10,ge=class extends ee{constructor({silentRequestTimeoutInSeconds:e=_t}){super();this._logger=new l("IFrameWindow");this._timeoutInSeconds=e,this._frame=window.document.createElement("iframe"),this._window=this._frame.contentWindow,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",window.document.body.appendChild(this._frame),this._window=this._frame.contentWindow}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);let t=setTimeout(()=>this._abort.raise(new Error("IFrame timed out without a response")),this._timeoutInSeconds*1e3);return this._disposeHandlers.add(()=>clearTimeout(t)),await super.navigate(e)}close(){this._frame&&(this._frame.parentNode&&this._frame.parentNode.removeChild(this._frame),this._abort.raise(new Error("IFrame removed from DOM")),this._frame=null),this._window=null}static notifyParent(e){return super._notifyParent(window.parent,e)}};var ve=class{constructor(e){this._settings=e;this._logger=new l("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new ge({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),ge.notifyParent(e)}};var mt=500,wt={location:!1,toolbar:!1,height:640},St="_blank",ue=class extends ee{constructor({popupWindowTarget:e=St,popupWindowFeatures:t={}}){super();this._logger=new l("PopupWindow");let r=de.center({...wt,...t});this._window=window.open(void 0,e,de.serialize(r))}async navigate(e){var r;(r=this._window)==null||r.focus();let t=setInterval(()=>{(!this._window||this._window.closed)&&this._abort.raise(new Error("Popup closed by user"))},mt);return this._disposeHandlers.add(()=>clearInterval(t)),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)}};var ye=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 ue({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,t=!1){this._logger.create("callback"),ue.notifyOpener(e,t)}};var ke=class{constructor(e){this._settings=e;this._logger=new l("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod}){let t=window.location[e].bind(window.location);return{navigate:r=>t(r.url),close:()=>this._logger.warn("close: cannot close the current window")}}};var bt=60,vt=2,te=class extends B{constructor(e){let{popup_redirect_uri:t,popup_post_logout_redirect_uri:r,popupWindowFeatures:i,popupWindowTarget:s,redirectMethod:n="assign",silent_redirect_uri:c,silentRequestTimeoutInSeconds:d,automaticSilentRenew:u=!0,validateSubOnSilentRenew:f=!0,includeIdTokenInSilentRenew:_=!1,monitorSession:h=!1,monitorAnonymousSession:p=!1,checkSessionIntervalInSeconds:w=vt,query_status_response_type:b,stopCheckSessionOnError:k=!0,revokeTokenTypes:o=["access_token","refresh_token"],revokeTokensOnSignout:g=!1,accessTokenExpiringNotificationTimeInSeconds:S=bt,userStore:m}=e;super(e);if(this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=i,this.popupWindowTarget=s,this.redirectMethod=n,this.silent_redirect_uri=c,this.silentRequestTimeoutInSeconds=d,this.automaticSilentRenew=u,this.validateSubOnSilentRenew=f,this.includeIdTokenInSilentRenew=_,this.monitorSession=h,this.monitorAnonymousSession=p,this.checkSessionIntervalInSeconds=w,this.stopCheckSessionOnError=k,b?this.query_status_response_type=b:this.query_status_response_type="code",this.revokeTokenTypes=o,this.revokeTokensOnSignout=g,this.accessTokenExpiringNotificationTimeInSeconds=S,m)this.userStore=m;else{let y=typeof window!="undefined"?window.sessionStorage:new j;this.userStore=new H({store:y})}}};var xe=class extends Q{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds});this._logger=new l("UserManagerEvents");this._userLoaded=new T("User loaded");this._userUnloaded=new T("User unloaded");this._silentRenewError=new T("Silent renew error");this._userSignedIn=new T("User signed in");this._userSignedOut=new T("User signed out");this._userSessionChanged=new T("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()}};var Pe=class{constructor(e){this._userManager=e;this._logger=new l("SilentRenewService");this._isStarted=!1;this._tokenExpiring=async()=>{let e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){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);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}};var Re=class{constructor(e){this.id=void 0;this.created=void 0;this.request_type=void 0;this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.scope=e.scope,this.data=e.state}toStorageString(){throw new Error("This method was called in error - refresh requests do not store persistent state.")}};var Ke=class{constructor(e){this._logger=new l("UserManager");this.settings=new te(e),this._client=new le(e),this._redirectNavigator=new ke(this.settings),this._popupNavigator=new ye(this.settings),this._iframeNavigator=new ve(this.settings),this._events=new xe(this.settings),this._silentRenewService=new Pe(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new Z(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 signinPopup(e={}){let t=this._logger.create("signinPopup"),{popupWindowFeatures:r,popupWindowTarget:i,...s}=e,n=this.settings.popup_redirect_uri||this.settings.redirect_uri;n||t.throw(new Error("No popup_redirect_uri or redirect_uri configured"));let c=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:i}),d=await this._signin({request_type:"si:p",redirect_uri:n,display:"popup",...s},c);return d&&(d.profile&&d.profile.sub?t.info("success, signed in subject",d.profile.sub):t.info("no subject")),d}async signinPopupCallback(e=window.location.href,t=!1){let r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,t),r.info("success")}async signinSilent(e={}){var u;let t=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:r,...i}=e,s=await this._loadUser();if(s==null?void 0:s.refresh_token){t.debug("using refresh token");let f=new Re(s);return await this._useRefreshToken(f)}let n=this.settings.silent_redirect_uri||this.settings.redirect_uri;n||t.throw(new Error("No silent_redirect_uri configured"));let c;s&&this.settings.validateSubOnSilentRenew&&(t.debug("subject prior to silent renew:",s.profile.sub),c=s.profile.sub);let d=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},d,c),s&&(((u=s.profile)==null?void 0:u.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),r=new q({...e,...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;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||this.settings.redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));let n=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),c=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...i},n);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,sid:d.profile.sid}):(t.info("success, user not authenticated"),null)}catch(d){if(this.settings.monitorAnonymousSession&&d instanceof U)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})}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);r.debug("got signin response");let s=new q(i);if(t){if(t!==s.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin: ",s.profile.sub),new U({...i,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(s),r.debug("user stored"),this._events.load(s),s}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||this.settings.post_logout_redirect_uri,c=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},c),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){let r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,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 c=await this._client.createSignoutRequest(e);return r.debug("got signout request"),await t.navigate({url:c.url,state:(i=c.state)==null?void 0:i.id})}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 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"),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 ze="2.0.0-rc.4";var $e=ze;return rt(kt);})();
var oidc=(()=>{var et=Object.create;var se=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var Ae=c=>se(c,"__esModule",{value:!0});var Me=(c=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(c,{get:(e,t)=>(typeof require!="undefined"?require:e)[t]}):c)(function(c){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+c+'" is not supported')});var Q=(c,e)=>()=>(e||c((e={exports:{}}).exports,e),e.exports),nt=(c,e)=>{for(var t in e)se(c,t,{get:e[t],enumerable:!0})},Oe=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rt(e))!st.call(c,i)&&(t||i!=="default")&&se(c,i,{get:()=>e[i],enumerable:!(r=tt(e,i))||r.enumerable});return c},ne=(c,e)=>Oe(Ae(se(c!=null?et(it(c)):{},"default",!e&&c&&c.__esModule?{get:()=>c.default,enumerable:!0}:{value:c,enumerable:!0})),c),ot=(c=>(e,t)=>c&&c.get(e)||(t=Oe(Ae({}),e,1),c&&c.set(e,t),t))(typeof WeakMap!="undefined"?new WeakMap:0);var qe=Q(()=>{});var V=Q((oe,Ne)=>{(function(c,e){typeof oe=="object"?Ne.exports=oe=e():typeof define=="function"&&define.amd?define([],e):c.CryptoJS=e()})(oe,function(){var c=c||function(e,t){var r;if(typeof window!="undefined"&&window.crypto&&(r=window.crypto),typeof self!="undefined"&&self.crypto&&(r=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(r=globalThis.crypto),!r&&typeof window!="undefined"&&window.msCrypto&&(r=window.msCrypto),!r&&typeof global!="undefined"&&global.crypto&&(r=global.crypto),!r&&typeof Me=="function")try{r=qe()}catch{}var i=function(){if(r){if(typeof r.getRandomValues=="function")try{return r.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof r.randomBytes=="function")try{return r.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},s=Object.create||function(){function a(){}return function(g){var S;return a.prototype=g,S=new a,a.prototype=null,S}}(),n={},o=n.lib={},l=o.Base=function(){return{extend:function(a){var g=s(this);return a&&g.mixIn(a),(!g.hasOwnProperty("init")||this.init===g.init)&&(g.init=function(){g.$super.init.apply(this,arguments)}),g.init.prototype=g,g.$super=this,g},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var g in a)a.hasOwnProperty(g)&&(this[g]=a[g]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),u=o.WordArray=l.extend({init:function(a,g){a=this.words=a||[],g!=t?this.sigBytes=g:this.sigBytes=a.length*4},toString:function(a){return(a||m).stringify(this)},concat:function(a){var g=this.words,S=a.words,_=this.sigBytes,y=a.sigBytes;if(this.clamp(),_%4)for(var b=0;b<y;b++){var P=S[b>>>2]>>>24-b%4*8&255;g[_+b>>>2]|=P<<24-(_+b)%4*8}else for(var R=0;R<y;R+=4)g[_+R>>>2]=S[R>>>2];return this.sigBytes+=y,this},clamp:function(){var a=this.words,g=this.sigBytes;a[g>>>2]&=4294967295<<32-g%4*8,a.length=e.ceil(g/4)},clone:function(){var a=l.clone.call(this);return a.words=this.words.slice(0),a},random:function(a){for(var g=[],S=0;S<a;S+=4)g.push(i());return new u.init(g,a)}}),f=n.enc={},m=f.Hex={stringify:function(a){for(var g=a.words,S=a.sigBytes,_=[],y=0;y<S;y++){var b=g[y>>>2]>>>24-y%4*8&255;_.push((b>>>4).toString(16)),_.push((b&15).toString(16))}return _.join("")},parse:function(a){for(var g=a.length,S=[],_=0;_<g;_+=2)S[_>>>3]|=parseInt(a.substr(_,2),16)<<24-_%8*4;return new u.init(S,g/2)}},h=f.Latin1={stringify:function(a){for(var g=a.words,S=a.sigBytes,_=[],y=0;y<S;y++){var b=g[y>>>2]>>>24-y%4*8&255;_.push(String.fromCharCode(b))}return _.join("")},parse:function(a){for(var g=a.length,S=[],_=0;_<g;_++)S[_>>>2]|=(a.charCodeAt(_)&255)<<24-_%4*8;return new u.init(S,g)}},p=f.Utf8={stringify:function(a){try{return decodeURIComponent(escape(h.stringify(a)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(a){return h.parse(unescape(encodeURIComponent(a)))}},w=o.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new u.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 g,S=this._data,_=S.words,y=S.sigBytes,b=this.blockSize,P=b*4,R=y/P;a?R=e.ceil(R):R=e.max((R|0)-this._minBufferSize,0);var E=R*b,W=e.min(E*4,y);if(E){for(var L=0;L<E;L+=b)this._doProcessBlock(_,L);g=_.splice(0,E),S.sigBytes-=W}return new u.init(g,W)},clone:function(){var a=l.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),v=o.Hasher=w.extend({cfg:l.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){w.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var g=this._doFinalize();return g},blockSize:512/32,_createHelper:function(a){return function(g,S){return new a.init(S).finalize(g)}},_createHmacHelper:function(a){return function(g,S){return new k.HMAC.init(a,S).finalize(g)}}}),k=n.algo={};return n}(Math);return c})});var Le=Q((ae,We)=>{(function(c,e){typeof ae=="object"?We.exports=ae=e(V()):typeof define=="function"&&define.amd?define(["./core"],e):e(c.CryptoJS)})(ae,function(c){return function(e){var t=c,r=t.lib,i=r.WordArray,s=r.Hasher,n=t.algo,o=[],l=[];(function(){function m(v){for(var k=e.sqrt(v),a=2;a<=k;a++)if(!(v%a))return!1;return!0}function h(v){return(v-(v|0))*4294967296|0}for(var p=2,w=0;w<64;)m(p)&&(w<8&&(o[w]=h(e.pow(p,1/2))),l[w]=h(e.pow(p,1/3)),w++),p++})();var u=[],f=n.SHA256=s.extend({_doReset:function(){this._hash=new i.init(o.slice(0))},_doProcessBlock:function(m,h){for(var p=this._hash.words,w=p[0],v=p[1],k=p[2],a=p[3],g=p[4],S=p[5],_=p[6],y=p[7],b=0;b<64;b++){if(b<16)u[b]=m[h+b]|0;else{var P=u[b-15],R=(P<<25|P>>>7)^(P<<14|P>>>18)^P>>>3,E=u[b-2],W=(E<<15|E>>>17)^(E<<13|E>>>19)^E>>>10;u[b]=R+u[b-7]+W+u[b-16]}var L=g&S^~g&_,he=w&v^w&k^v&k,me=(w<<30|w>>>2)^(w<<19|w>>>13)^(w<<10|w>>>22),Xe=(g<<26|g>>>6)^(g<<21|g>>>11)^(g<<7|g>>>25),Te=y+Xe+L+l[b]+u[b],Ze=me+he;y=_,_=S,S=g,g=a+Te|0,a=k,k=v,v=w,w=Te+Ze|0}p[0]=p[0]+w|0,p[1]=p[1]+v|0,p[2]=p[2]+k|0,p[3]=p[3]+a|0,p[4]=p[4]+g|0,p[5]=p[5]+S|0,p[6]=p[6]+_|0,p[7]=p[7]+y|0},_doFinalize:function(){var m=this._data,h=m.words,p=this._nDataBytes*8,w=m.sigBytes*8;return h[w>>>5]|=128<<24-w%32,h[(w+64>>>9<<4)+14]=e.floor(p/4294967296),h[(w+64>>>9<<4)+15]=p,m.sigBytes=h.length*4,this._process(),this._hash},clone:function(){var m=s.clone.call(this);return m._hash=this._hash.clone(),m}});t.SHA256=s._createHelper(f),t.HmacSHA256=s._createHmacHelper(f)}(Math),c.SHA256})});var je=Q((ce,Fe)=>{(function(c,e){typeof ce=="object"?Fe.exports=ce=e(V()):typeof define=="function"&&define.amd?define(["./core"],e):e(c.CryptoJS)})(ce,function(c){return function(){var e=c,t=e.lib,r=t.WordArray,i=e.enc,s=i.Base64={stringify:function(o){var l=o.words,u=o.sigBytes,f=this._map;o.clamp();for(var m=[],h=0;h<u;h+=3)for(var p=l[h>>>2]>>>24-h%4*8&255,w=l[h+1>>>2]>>>24-(h+1)%4*8&255,v=l[h+2>>>2]>>>24-(h+2)%4*8&255,k=p<<16|w<<8|v,a=0;a<4&&h+a*.75<u;a++)m.push(f.charAt(k>>>6*(3-a)&63));var g=f.charAt(64);if(g)for(;m.length%4;)m.push(g);return m.join("")},parse:function(o){var l=o.length,u=this._map,f=this._reverseMap;if(!f){f=this._reverseMap=[];for(var m=0;m<u.length;m++)f[u.charCodeAt(m)]=m}var h=u.charAt(64);if(h){var p=o.indexOf(h);p!==-1&&(l=p)}return n(o,l,f)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};function n(o,l,u){for(var f=[],m=0,h=0;h<l;h++)if(h%4){var p=u[o.charCodeAt(h-1)]<<h%4*2,w=u[o.charCodeAt(h)]>>>6-h%4*2,v=p|w;f[m>>>2]|=v<<24-m%4*8,m++}return r.create(f,m)}}(),c.enc.Base64})});var Be=Q((le,He)=>{(function(c,e){typeof le=="object"?He.exports=le=e(V()):typeof define=="function"&&define.amd?define(["./core"],e):e(c.CryptoJS)})(le,function(c){return c.enc.Utf8})});var kt={};nt(kt,{AccessTokenEvents:()=>G,CheckSessionIFrame:()=>Y,ErrorResponse:()=>C,ErrorTimeout:()=>O,InMemoryWebStorage:()=>j,Log:()=>F,Logger:()=>d,MetadataService:()=>X,OidcClient:()=>ue,OidcClientSettingsStore:()=>J,SessionMonitor:()=>te,SigninResponse:()=>z,SigninState:()=>q,SignoutResponse:()=>ee,State:()=>U,User:()=>N,UserManager:()=>Ve,UserManagerSettingsStore:()=>ie,Version:()=>Ye,WebStorageStateStore:()=>B});var Je=ne(V()),De=ne(Le()),fe=ne(je()),Ke=ne(Be());var at={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},A,M,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 c(){A=3,M=at}r.reset=c;function e(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");A=i}r.setLevel=e;function t(i){M=i}r.setLogger=t})(F||(F={}));var d=class{constructor(e){this._name=e}debug(...e){A>=4&&M.debug(d._format(this._name,this._method),...e)}info(...e){A>=3&&M.info(d._format(this._name,this._method),...e)}warn(...e){A>=2&&M.warn(d._format(this._name,this._method),...e)}error(...e){A>=1&&M.error(d._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 _format(e,t){let r=`[${e}]`;return t?r+` ${t}:`:r}static debug(e,...t){A>=4&&M.debug(d._format(e),...t)}static info(e,...t){A>=3&&M.info(d._format(e),...t)}static warn(e,...t){A>=2&&M.warn(d._format(e),...t)}static error(e,...t){A>=1&&M.error(d._format(e),...t)}};F.reset();var ct="10000000-1000-4000-8000-100000000000",I=class{static _randomWord(){return Je.default.lib.WordArray.random(1).words[0]}static generateUUIDv4(){return ct.replace(/[018]/g,t=>(+t^I._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return I.generateUUIDv4()+I.generateUUIDv4()+I.generateUUIDv4()}static generateCodeChallenge(e){try{let t=(0,De.default)(e);return fe.default.stringify(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw d.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){let r=Ke.default.parse([e,t].join(":"));return fe.default.stringify(r)}};var T=class{constructor(e){this._name=e;this._logger=new d(`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)}};function _e(c){this.message=c}_e.prototype=new Error,_e.prototype.name="InvalidCharacterError";var ze=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(c){var e=String(c).replace(/=+$/,"");if(e.length%4==1)throw new _e("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,r,i=0,s=0,n="";r=e.charAt(s++);~r&&(t=i%4?64*t+r:r,i++%4)?n+=String.fromCharCode(255&t>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return n};function lt(c){var e=c.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(ze(t).replace(/(.)/g,function(r,i){var s=i.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch{return ze(e)}}function de(c){this.message=c}function dt(c,e){if(typeof c!="string")throw new de("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(lt(c.split(".")[t]))}catch(r){throw new de("Invalid token specified: "+r.message)}}de.prototype=new Error,de.prototype.name="InvalidTokenError";var $e=dt;var D=class{static decode(e){try{return $e(e)}catch(t){throw d.error("JwtUtils.decode",t),t}}};var ge=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 x=class extends T{constructor(){super(...arguments);this._logger=new d(`Timer('${this._name}')`);this._timerHandle=null;this._expiration=0;this._callback=()=>{let e=this._expiration-x.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=x.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){let t=this._logger.create("init");e=Math.max(Math.floor(e),1);let r=x.getEpochTime()+e;if(this.expiration===r&&this._timerHandle){t.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),t.debug("using duration",e),this._expiration=r;let 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)}};var K=class{static readParams(e,t="query"){let i=new URL(e)[t==="fragment"?"hash":"search"];return new URLSearchParams(i.slice(1))}};var C=class extends Error{constructor(e,t){super(e.error_description||e.error||"");this.form=t;this.name="ErrorResponse";var r,i,s;if(!e.error)throw d.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=(r=e.error_description)!=null?r:null,this.error_uri=(i=e.error_uri)!=null?i:null,this.state=e.userState,this.session_state=(s=e.session_state)!=null?s:null}};var O=class extends Error{constructor(e){super(e);this.name="ErrorTimeout"}};var G=class{constructor(e){this._logger=new d("AccessTokenEvents");this._expiringTimer=new x("Access token expiring");this._expiredTimer=new x("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 Y=class{constructor(e,t,r,i,s){this._callback=e;this._client_id=t;this._intervalInSeconds=i;this._stopOnError=s;this._logger=new d("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=r.indexOf("/",r.indexOf("//")+2);this._frame_origin=r.substr(0,n),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=r}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 j=class{constructor(){this._logger=new d("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 H=class{constructor(e=[],t=null){this._jwtHandler=t;this._logger=new d("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 O("Network timed out"):o}finally{clearTimeout(n)}}async getJson(e,{token:t}={}){let r=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};t&&(r.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t);let s;try{r.debug("url:",e),s=await this.fetchWithTimeout(e,{method:"GET",headers:i})}catch(l){throw r.error("Network Error"),l}r.debug("HTTP response received, status",s.status);let n=s.headers.get("Content-Type");if(n&&!this._contentTypes.find(l=>n.startsWith(l))&&r.throw(new Error(`Invalid response Content-Type: ${n!=null?n:"undefined"}, from URL: ${e}`)),s.ok&&this._jwtHandler&&(n==null?void 0:n.startsWith("application/jwt")))return await this._jwtHandler(await s.text());let o;try{o=await s.json()}catch(l){throw r.error("Error parsing JSON response",l),s.ok?l:new Error(`${s.statusText} (${s.status})`)}if(!s.ok)throw r.error("Error from server:",o),o.error?new C(o):new Error(`${s.statusText} (${s.status}): ${JSON.stringify(o)}`);return o}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:i}){let s=this._logger.create("postForm"),n={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};r!==void 0&&(n.Authorization="Basic "+r);let o;try{s.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"POST",headers:n,body:t,timeoutInSeconds:i})}catch(m){throw s.error("Network error"),m}s.debug("HTTP response received, status",o.status);let l=o.headers.get("Content-Type");if(l&&!this._contentTypes.find(m=>l.startsWith(m)))throw new Error(`Invalid response Content-Type: ${l!=null?l:"undefined"}, from URL: ${e}`);let u=await o.text(),f={};if(u)try{f=JSON.parse(u)}catch(m){throw s.error("Error parsing JSON response",m),o.ok?m:new Error(`${o.statusText} (${o.status})`)}if(!o.ok)throw s.error("Error from server:",f),f.error?new C(f,t):new Error(`${o.statusText} (${o.status}): ${JSON.stringify(f)}`);return f}};var X=class{constructor(e){this._settings=e;this._logger=new d("MetadataService");this._jsonService=new H(["application/jwk-set+json"]);this._signingKeys=null;this._metadata=null;this._metadataUrl=this._settings.metadataUrl,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)}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);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 B=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new d("WebStorageStateStore");this._store=t,this._prefix=e}set(e,t){return this._logger.create(`set('${e}')`),e=this._prefix+e,this._store.setItem(e,t),Promise.resolve()}get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;let t=this._store.getItem(e);return Promise.resolve(t)}remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;let t=this._store.getItem(e);return this._store.removeItem(e),Promise.resolve(t)}getAllKeys(){this._logger.create("getAllKeys");let e=[];for(let t=0;t<this._store.length;t++){let r=this._store.key(t);r&&r.indexOf(this._prefix)===0&&e.push(r.substr(this._prefix.length))}return Promise.resolve(e)}};var gt="code",ut="openid",pt="client_secret_post",ht="query",mt=60*15,ft=60*5,J=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:i,metadataSeed:s,client_id:n,client_secret:o,response_type:l=gt,scope:u=ut,redirect_uri:f,post_logout_redirect_uri:m,client_authentication:h=pt,prompt:p,display:w,max_age:v,ui_locales:k,acr_values:a,resource:g,response_mode:S=ht,filterProtocolClaims:_=!0,loadUserInfo:y=!1,staleStateAgeInSeconds:b=mt,clockSkewInSeconds:P=ft,userInfoJwtIssuer:R="OP",mergeClaims:E=!1,stateStore:W,extraQueryParams:L={},extraTokenParams:he={}}){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=l,this.scope=u,this.redirect_uri=f,this.post_logout_redirect_uri=m,this.client_authentication=h,this.prompt=p,this.display=w,this.max_age=v,this.ui_locales=k,this.acr_values=a,this.resource=g,this.response_mode=S,this.filterProtocolClaims=!!_,this.loadUserInfo=!!y,this.staleStateAgeInSeconds=b,this.clockSkewInSeconds=P,this.userInfoJwtIssuer=R,this.mergeClaims=!!E,W)this.stateStore=W;else{let me=typeof window!="undefined"?window.localStorage:new j;this.stateStore=new B({store:me})}this.extraQueryParams=L,this.extraTokenParams=he}};var we=class{constructor(e){this._metadataService=e;this._logger=new d("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 H(void 0,this._getClaimsFromJwt)}async getClaims(e){let t=this._logger.create("getClaims");if(!e)throw this._logger.error("getClaims: No token passed"),new Error("A token is required");let r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);let i=await this._jsonService.getJson(r,{token:e});return t.debug("got claims",i),i}};var Z=class{constructor(e,t){this._settings=e;this._metadataService=t;this._logger=new d("TokenClient");this._jsonService=new H}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")),s.code_verifier||n.throw(new Error("A code_verifier is required"));let o=new URLSearchParams({grant_type:e,redirect_uri:t});for(let[m,h]of Object.entries(s))h!=null&&o.set(m,h);let l;switch(this._settings.client_authentication){case"client_secret_basic":if(!i)throw n.throw(new Error("A client_secret is required")),null;l=I.generateBasicAuth(r,i);break;case"client_secret_post":o.append("client_id",r),i&&o.append("client_secret",i);break}let u=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");let f=await this._jsonService.postForm(u,{body:o,basicAuth:l});return n.debug("got response"),f}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[m,h]of Object.entries(s))h!=null&&o.set(m,h);let l;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw n.throw(new Error("A client_secret is required")),null;l=I.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break}let u=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");let f=await this._jsonService.postForm(u,{body:o,basicAuth:l,timeoutInSeconds:i});return n.debug("got response"),f}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 _t=["iss","aud","exp","nbf","iat","jti","auth_time","nonce","acr","amr","azp","at_hash"],Se=class{constructor(e,t){this._settings=e;this._metadataService=t;this._logger=new d("ResponseValidator");this._userInfoService=new we(this._metadataService);this._tokenClient=new Z(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),r.debug("claims processed")}async validateRefreshResponse(e,t){var i;let r=this._logger.create("validateRefreshResponse");e.userState=t.data,(i=e.scope)!=null||(e.scope=t.scope),e.isOpenId&&this._validateIdTokenAttributes(e,t.id_token),r.debug("tokens validated"),await this._processClaims(e),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 C(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,(i=e.scope)!=null||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new C(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response")),!t.code_verifier&&e.code&&r.throw(new Error("Unexpected code in response"))}async _processClaims(e,t=!1){let r=this._logger.create("_processClaims");if(!e.isOpenId){r.debug("response is not OIDC, skipping claims processing");return}if(r.debug("response is OIDC, processing claims",e.profile),e.profile=this._filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token){r.debug("not loading user info");return}r.debug("loading user info");let i=await this._userInfoService.getClaims(e.access_token);r.debug("user info claims received from user info endpoint"),i.sub!==e.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._mergeClaims(e.profile,this._filterProtocolClaims(i)),r.debug("_processClaims: user info claims received, updated profile:",e.profile)}_mergeClaims(e,t){let r={...e};for(let[i,s]of Object.entries(t))for(let n of Array.isArray(s)?s:[s]){let o=r[i];o?Array.isArray(o)?o.includes(n)||o.push(n):r[i]!==n&&(typeof n=="object"&&this._settings.mergeClaims?r[i]=this._mergeClaims(o,n):r[i]=[o,n]):r[i]=n}return r}_filterProtocolClaims(e){let t={...e};if(this._settings.filterProtocolClaims)for(let r of _t)delete t[r];return t}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);n.sub!==i.sub&&r.throw(new Error("sub in id_token does not match current sub")),n.auth_time&&n.auth_time!==i.auth_time&&r.throw(new Error("auth_time in id_token does not match original auth_time")),n.azp&&n.azp!==i.azp&&r.throw(new Error("azp in id_token does not match original azp")),!n.azp&&i.azp&&r.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}};var U=class{constructor(e){this.id=e.id||I.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=x.getEpochTime(),this.request_type=e.request_type}toStorageString(){return new d("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type})}static fromStorageString(e){return d.debug("State.fromStorageString"),new U(JSON.parse(e))}static async clearStaleState(e,t){let r=x.getEpochTime()-t,i=await e.getAllKeys();d.debug("State.clearStaleState","got keys",i);for(let s=0;s<i.length;s++){let n=i[s],o=await e.get(n),l=!1;if(o)try{let u=U.fromStorageString(o);d.debug("State.clearStaleState","got item from key: ",n,u.created),u.created<=r&&(l=!0)}catch(u){d.error("State.clearStaleState","Error parsing state for key",n,u),l=!0}else d.debug("State.clearStaleState","no item in storage for key: ",n),l=!0;l&&(d.debug("State.clearStaleState","removed item for key: ",n),e.remove(n))}}};var q=class extends U{constructor(e){super(e);e.code_verifier===!0?this.code_verifier=I.generateCodeVerifier():e.code_verifier&&(this.code_verifier=e.code_verifier),this.code_verifier&&(this.code_challenge=I.generateCodeChallenge(this.code_verifier)),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}toStorageString(){return new d("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,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){d.debug("SigninState.fromStorageString");let t=JSON.parse(e);return new q(t)}};var be=class{constructor({url:e,authority:t,client_id:r,redirect_uri:i,response_type:s,scope:n,state_data:o,response_mode:l,request_type:u,client_secret:f,skipUserInfo:m,extraQueryParams:h,extraTokenParams:p,...w}){this._logger=new d("SigninRequest");if(!e)throw this._logger.error("ctor: No url passed"),new Error("url");if(!r)throw this._logger.error("ctor: No client_id passed"),new Error("client_id");if(!i)throw this._logger.error("ctor: No redirect_uri passed"),new Error("redirect_uri");if(!s)throw this._logger.error("ctor: No response_type passed"),new Error("response_type");if(!n)throw this._logger.error("ctor: No scope passed"),new Error("scope");if(!t)throw this._logger.error("ctor: No authority passed"),new Error("authority");this.state=new q({data:o,request_type:u,code_verifier:!0,client_id:r,authority:t,redirect_uri:i,response_mode:l,client_secret:f,scope:n,extraTokenParams:p,skipUserInfo:m});let v=new URL(e);v.searchParams.append("client_id",r),v.searchParams.append("redirect_uri",i),v.searchParams.append("response_type",s),v.searchParams.append("scope",n),v.searchParams.append("state",this.state.id),this.state.code_challenge&&(v.searchParams.append("code_challenge",this.state.code_challenge),v.searchParams.append("code_challenge_method","S256"));for(let[k,a]of Object.entries({response_mode:l,...w,...h}))a!=null&&v.searchParams.append(k,a.toString());this.url=v.href}};var wt="openid",z=class{constructor(e){this.access_token="";this.token_type="";this.profile={};this.state=e.get("state"),this.session_state=e.get("session_state"),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-x.getEpochTime()}set expires_in(e){typeof e=="string"&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+x.getEpochTime())}get isOpenId(){var e;return((e=this.scope)==null?void 0:e.split(" ").includes(wt))||!!this.id_token}};var ve=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:i,extraQueryParams:s,request_type:n}){this._logger=new d("SignoutRequest");if(!e)throw this._logger.error("ctor: No url passed"),new Error("url");let o=new URL(e);r&&o.searchParams.append("id_token_hint",r),i&&(o.searchParams.append("post_logout_redirect_uri",i),t&&(this.state=new U({data:t,request_type:n}),o.searchParams.append("state",this.state.id)));for(let[l,u]of Object.entries({...s}))u!=null&&o.searchParams.append(l,u.toString());this.url=o.href}};var ee=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 ue=class{constructor(e){this._logger=new d("OidcClient");this.settings=new J(e),this.metadataService=new X(this.settings),this._validator=new Se(this.settings,this.metadataService),this._tokenClient=new Z(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,response_type:l=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:f=this.settings.redirect_uri,prompt:m=this.settings.prompt,display:h=this.settings.display,max_age:p=this.settings.max_age,ui_locales:w=this.settings.ui_locales,acr_values:v=this.settings.acr_values,resource:k=this.settings.resource,response_mode:a=this.settings.response_mode,extraQueryParams:g=this.settings.extraQueryParams,extraTokenParams:S=this.settings.extraTokenParams}){let _=this._logger.create("createSigninRequest");if(l!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");let y=await this.metadataService.getAuthorizationEndpoint();_.debug("Received authorization endpoint",y);let b=new be({url:y,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:f,response_type:l,scope:u,state_data:e,prompt:m,display:h,max_age:p,ui_locales:w,id_token_hint:s,login_hint:n,acr_values:v,resource:k,request:t,request_uri:r,extraQueryParams:g,extraTokenParams:S,request_type:i,response_mode:a,client_secret:this.settings.client_secret,skipUserInfo:o}),P=b.state;return await this.settings.stateStore.set(P.id,P.toStorageString()),b}async readSigninResponseState(e,t=!1){let r=this._logger.create("readSigninResponseState"),i=new z(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:q.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 useRefreshToken({state:e,timeoutInSeconds:t}){let r=this._logger.create("useRefreshToken"),i=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,timeoutInSeconds:t}),s=new z(new URLSearchParams);return Object.assign(s,i),r.debug("validating response",s),await this._validator.validateRefreshResponse(s,e),s}async createSignoutRequest({state:e,id_token_hint:t,request_type:r,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){let n=this._logger.create("createSignoutRequest"),o=await this.metadataService.getEndSessionEndpoint();if(!o)throw n.throw(new Error("No end session endpoint")),null;n.debug("createSignoutRequest: Received end session endpoint",o);let l=new ve({url:o,id_token_hint:t,post_logout_redirect_uri:i,state_data:e,extraQueryParams:s,request_type:r}),u=l.state;return u&&(n.debug("Signout request has state to persist"),await this.settings.stateStore.set(u.id,u.toStorageString())),l}async readSignoutResponseState(e,t=!1){let r=this._logger.create("readSignoutResponseState"),i=new ee(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 C(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:U.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"),U.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 te=class{constructor(e){this._userManager=e;this._logger=new d("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,this._sid=e.profile.sid,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,this._sid=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,l=new Y(this._callback,s,i,n,o);await l.load(),this._checkSessionIFrame=l,l.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._sid=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&&r.sid?{sub:r.sub,sid:r.sid}: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),t.sid===this._sid?e.debug("same sub still logged in at OP, restarting check session iframe; session_state",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("No user manager passed to SessionMonitor"),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&&t.sid?{sub:t.sub,sid:t.sid}:null};this._start(r)}}}};var N=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}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-x.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+x.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 d("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 d.debug("User.fromStorageString"),new N(JSON.parse(e))}};var Qe="oidc-client",re=class{constructor(){this._abort=new T("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=l=>{let u=l.data;if(!(l.origin!==window.location.origin||(u==null?void 0:u.source)!==Qe)){try{let f=K.readParams(u.url,e.response_mode).get("state");if(f||t.warn("no state found in response url"),l.source!==this._window&&f!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}s(u)}};window.addEventListener("message",o,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",o,!1)),this._disposeHandlers.add(this._abort.addHandler(l=>{this._dispose(),n(l)}))});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){e.postMessage({source:Qe,url:t,keepOpen:r},window.location.origin)}};var ye={location:!1,toolbar:!1,height:640},ke="_blank",St=60,bt=2,xe=10,ie=class extends J{constructor(e){let{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:r=e.post_logout_redirect_uri,popupWindowFeatures:i=ye,popupWindowTarget:s=ke,redirectMethod:n="assign",silent_redirect_uri:o=e.redirect_uri,silentRequestTimeoutInSeconds:l=xe,automaticSilentRenew:u=!0,validateSubOnSilentRenew:f=!0,includeIdTokenInSilentRenew:m=!1,monitorSession:h=!1,monitorAnonymousSession:p=!1,checkSessionIntervalInSeconds:w=bt,query_status_response_type:v="code",stopCheckSessionOnError:k=!0,revokeTokenTypes:a=["access_token","refresh_token"],revokeTokensOnSignout:g=!1,accessTokenExpiringNotificationTimeInSeconds:S=St,userStore:_}=e;super(e);if(this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=i,this.popupWindowTarget=s,this.redirectMethod=n,this.silent_redirect_uri=o,this.silentRequestTimeoutInSeconds=l,this.automaticSilentRenew=u,this.validateSubOnSilentRenew=f,this.includeIdTokenInSilentRenew=m,this.monitorSession=h,this.monitorAnonymousSession=p,this.checkSessionIntervalInSeconds=w,this.stopCheckSessionOnError=k,this.query_status_response_type=v,this.revokeTokenTypes=a,this.revokeTokensOnSignout=g,this.accessTokenExpiringNotificationTimeInSeconds=S,_)this.userStore=_;else{let y=typeof window!="undefined"?window.sessionStorage:new j;this.userStore=new B({store:y})}}};var $=class extends re{constructor({silentRequestTimeoutInSeconds:e=xe}){super();this._logger=new d("IFrameWindow");this._timeoutInSeconds=e,this._frame=$.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){let 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",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);let t=setTimeout(()=>this._abort.raise(new O("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 i;let r=t.target;(i=r.parentNode)==null||i.removeChild(r),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){return super._notifyParent(window.parent,e)}};var Pe=class{constructor(e){this._settings=e;this._logger=new d("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new $({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),$.notifyParent(e)}};var vt=500,pe=class extends re{constructor({popupWindowTarget:e=ke,popupWindowFeatures:t={}}){super();this._logger=new d("PopupWindow");let r=ge.center({...ye,...t});this._window=window.open(void 0,e,ge.serialize(r))}async navigate(e){var r;(r=this._window)==null||r.focus();let t=setInterval(()=>{(!this._window||this._window.closed)&&this._abort.raise(new Error("Popup closed by user"))},vt);return this._disposeHandlers.add(()=>clearInterval(t)),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)}};var Re=class{constructor(e){this._settings=e;this._logger=new d("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget}){return new pe({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,t=!1){this._logger.create("callback"),pe.notifyOpener(e,t)}};var Ie=class{constructor(e){this._settings=e;this._logger=new d("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod}){this._logger.create("prepare");let t=window.location[e].bind(window.location),r;return{navigate:async i=>{this._logger.create("navigate");let s=new Promise((n,o)=>{r=o,window.addEventListener("unload",()=>n(null))});return t(i.url),await s},close:()=>{this._logger.create("close"),r==null||r(new Error("Redirect aborted")),window.stop()}}}};var Ce=class extends G{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds});this._logger=new d("UserManagerEvents");this._userLoaded=new T("User loaded");this._userUnloaded=new T("User unloaded");this._silentRenewError=new T("Silent renew error");this._userSignedIn=new T("User signed in");this._userSignedOut=new T("User signed out");this._userSessionChanged=new T("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()}};var Ue=class{constructor(e){this._userManager=e;this._logger=new d("SilentRenewService");this._isStarted=!1;this._retryTimer=new x("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 O){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 Ee=class{constructor(e){this.id=void 0;this.created=void 0;this.request_type=void 0;this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.scope=e.scope,this.data=e.state}toStorageString(){throw new Error("This method was called in error - refresh requests do not store persistent state.")}};var Ve=class{constructor(e){this._logger=new d("UserManager");this.settings=new ie(e),this._client=new ue(e),this._redirectNavigator=new Ie(this.settings),this._popupNavigator=new Re(this.settings),this._iframeNavigator=new Pe(this.settings),this._events=new Ce(this.settings),this._silentRenewService=new Ue(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new te(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 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}),l=await this._signin({request_type:"si:p",redirect_uri:n,display:"popup",...s},o);return l&&(l.profile&&l.profile.sub?t.info("success, signed in subject",l.profile.sub):t.info("no subject")),l}async signinPopupCallback(e=window.location.href,t=!1){let r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,t),r.info("success")}async signinSilent(e={}){var u;let t=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:r,...i}=e,s=await this._loadUser();if(s==null?void 0:s.refresh_token){t.debug("using refresh token");let f=new Ee(s);return await this._useRefreshToken(f)}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 l=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},l,o),s&&(((u=s.profile)==null?void 0:u.sub)?t.info("success, signed in subject",s.profile.sub):t.info("no subject")),s}async _useRefreshToken(e){let t=await this._client.useRefreshToken({state:e,timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds}),r=new N({...e,...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;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._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),o=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...i},n);try{let l=await this._client.processSigninResponse(o.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 C)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,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})}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);r.debug("got signin response");let s=new N(i);if(t){if(t!==s.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin: ",s.profile.sub),new C({...i,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(s),r.debug("user stored"),this._events.load(s),s}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,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})}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 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"),N.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 Ge="2.0.0-rc.5";var Ye=Ge;return ot(kt);})();
//# sourceMappingURL=oidc-client-ts.min.js.map

@@ -21,3 +21,3 @@ /**

*/
export declare type AccessTokenCallback = (...ev: unknown[]) => void;
export declare type AccessTokenCallback = (...ev: unknown[]) => (Promise<void> | void);

@@ -150,2 +150,13 @@ /**

/**
* Error class thrown in case of network timeouts (e.g IFrame time out).
*
* @public
*/
export declare class ErrorTimeout extends Error {
/** Marker to detect class: "ErrorTimeout" */
readonly name: string;
constructor(message?: string);
}
/**
* @internal

@@ -183,2 +194,3 @@ */

refresh_token: string;
timeoutInSeconds?: number;
}

@@ -240,2 +252,3 @@

constructor({ silentRequestTimeoutInSeconds, }: IFrameWindowParams);
private static createHiddenIframe;
navigate(params: NavigateParams): Promise<NavigateResponse>;

@@ -457,3 +470,3 @@ close(): void;

processSigninResponse(url: string): Promise<SigninResponse>;
useRefreshToken(state: RefreshState): Promise<SigninResponse>;
useRefreshToken({ state, timeoutInSeconds, }: UseRefreshTokenArgs): Promise<SigninResponse>;
createSignoutRequest({ state, id_token_hint, request_type, post_logout_redirect_uri, extraQueryParams, }?: CreateSignoutRequestArgs): Promise<SignoutRequest>;

@@ -552,3 +565,3 @@ readSignoutResponseState(url: string, removeState?: boolean): Promise<{

readonly authority: string;
readonly metadataUrl: string | undefined;
readonly metadataUrl: string;
readonly metadata: Partial<OidcMetadata> | undefined;

@@ -1029,2 +1042,3 @@ readonly metadataSeed: Partial<OidcMetadata> | undefined;

private _isStarted;
private readonly _retryTimer;
constructor(_userManager: UserManager);

@@ -1076,3 +1090,3 @@ start(): Promise<void>;

exchangeCode({ grant_type, redirect_uri, client_id, client_secret, ...args }: ExchangeCodeArgs): Promise<Record<string, unknown>>;
exchangeRefreshToken({ grant_type, client_id, client_secret, ...args }: ExchangeRefreshTokenArgs): Promise<Record<string, unknown>>;
exchangeRefreshToken({ grant_type, client_id, client_secret, timeoutInSeconds, ...args }: ExchangeRefreshTokenArgs): Promise<Record<string, unknown>>;
/**

@@ -1141,2 +1155,10 @@ * Revoke an access or refresh token.

/**
* @public
*/
export declare interface UseRefreshTokenArgs {
state: RefreshState;
timeoutInSeconds?: number;
}
/**
* @internal

@@ -1401,9 +1423,9 @@ */

export declare class UserManagerSettingsStore extends OidcClientSettingsStore {
readonly popup_redirect_uri: string | undefined;
readonly popup_redirect_uri: string;
readonly popup_post_logout_redirect_uri: string | undefined;
readonly popupWindowFeatures: PopupWindowFeatures | undefined;
readonly popupWindowTarget: string | undefined;
readonly popupWindowFeatures: PopupWindowFeatures;
readonly popupWindowTarget: string;
readonly redirectMethod: "replace" | "assign";
readonly silent_redirect_uri: string | undefined;
readonly silentRequestTimeoutInSeconds: number | undefined;
readonly silent_redirect_uri: string;
readonly silentRequestTimeoutInSeconds: number;
readonly automaticSilentRenew: boolean;

@@ -1415,3 +1437,3 @@ readonly validateSubOnSilentRenew: boolean;

readonly checkSessionIntervalInSeconds: number;
readonly query_status_response_type: string | undefined;
readonly query_status_response_type: string;
readonly stopCheckSessionOnError: boolean;

@@ -1418,0 +1440,0 @@ readonly revokeTokenTypes: ("access_token" | "refresh_token")[];

{
"name": "oidc-client-ts",
"version": "2.0.0-rc.4",
"version": "2.0.0-rc.5",
"description": "OpenID Connect (OIDC) & OAuth2 client library",

@@ -5,0 +5,0 @@ "repository": {

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 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