@uva-fnwi/datanose-core 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +151 -0
- package/dist/Auth.helpers.d.ts +38 -0
- package/dist/Auth.helpers.test.d.ts +1 -0
- package/dist/Auth.reducer.d.ts +15 -0
- package/dist/Auth.reducer.test.d.ts +1 -0
- package/dist/Auth.selectors.d.ts +5 -0
- package/dist/Auth.selectors.test.d.ts +1 -0
- package/dist/Auth.state.d.ts +10 -0
- package/dist/Auth.types.d.ts +60 -0
- package/dist/AuthContext.d.ts +15 -0
- package/dist/AuthProvider.d.ts +12 -0
- package/dist/AuthService.d.ts +20 -0
- package/dist/core.es.js +3161 -0
- package/dist/core.umd.js +6 -0
- package/dist/index.d.ts +8 -0
- package/dist/useAuth.d.ts +5 -0
- package/package.json +73 -0
package/dist/core.umd.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
(function(I,N){typeof exports=="object"&&typeof module<"u"?N(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],N):(I=typeof globalThis<"u"?globalThis:I||self,N(I.DataNoseCore={},I.React))})(this,(function(I,N){"use strict";var de=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function te(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function tt(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var r=function s(){var i=!1;try{i=this instanceof s}catch{}return i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(s){var i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(r,s,i.get?i:{enumerable:!0,get:function(){return e[s]}})}),r}function rt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var re={exports:{}};const st=tt(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var it=re.exports,Ie;function se(){return Ie||(Ie=1,(function(e,t){(function(r,s){e.exports=s()})(it,function(){var r=r||(function(s,i){var n;if(typeof window<"u"&&window.crypto&&(n=window.crypto),typeof self<"u"&&self.crypto&&(n=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(n=globalThis.crypto),!n&&typeof window<"u"&&window.msCrypto&&(n=window.msCrypto),!n&&typeof de<"u"&&de.crypto&&(n=de.crypto),!n&&typeof rt=="function")try{n=st}catch{}var o=function(){if(n){if(typeof n.getRandomValues=="function")try{return n.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof n.randomBytes=="function")try{return n.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},l=Object.create||(function(){function a(){}return function(d){var f;return a.prototype=d,f=new a,a.prototype=null,f}})(),u={},g=u.lib={},_=g.Base=(function(){return{extend:function(a){var d=l(this);return a&&d.mixIn(a),(!d.hasOwnProperty("init")||this.init===d.init)&&(d.init=function(){d.$super.init.apply(this,arguments)}),d.init.prototype=d,d.$super=this,d},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var d in a)a.hasOwnProperty(d)&&(this[d]=a[d]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),h=g.WordArray=_.extend({init:function(a,d){a=this.words=a||[],d!=i?this.sigBytes=d:this.sigBytes=a.length*4},toString:function(a){return(a||w).stringify(this)},concat:function(a){var d=this.words,f=a.words,v=this.sigBytes,E=a.sigBytes;if(this.clamp(),v%4)for(var T=0;T<E;T++){var x=f[T>>>2]>>>24-T%4*8&255;d[v+T>>>2]|=x<<24-(v+T)%4*8}else for(var C=0;C<E;C+=4)d[v+C>>>2]=f[C>>>2];return this.sigBytes+=E,this},clamp:function(){var a=this.words,d=this.sigBytes;a[d>>>2]&=4294967295<<32-d%4*8,a.length=s.ceil(d/4)},clone:function(){var a=_.clone.call(this);return a.words=this.words.slice(0),a},random:function(a){for(var d=[],f=0;f<a;f+=4)d.push(o());return new h.init(d,a)}}),b=u.enc={},w=b.Hex={stringify:function(a){for(var d=a.words,f=a.sigBytes,v=[],E=0;E<f;E++){var T=d[E>>>2]>>>24-E%4*8&255;v.push((T>>>4).toString(16)),v.push((T&15).toString(16))}return v.join("")},parse:function(a){for(var d=a.length,f=[],v=0;v<d;v+=2)f[v>>>3]|=parseInt(a.substr(v,2),16)<<24-v%8*4;return new h.init(f,d/2)}},k=b.Latin1={stringify:function(a){for(var d=a.words,f=a.sigBytes,v=[],E=0;E<f;E++){var T=d[E>>>2]>>>24-E%4*8&255;v.push(String.fromCharCode(T))}return v.join("")},parse:function(a){for(var d=a.length,f=[],v=0;v<d;v++)f[v>>>2]|=(a.charCodeAt(v)&255)<<24-v%4*8;return new h.init(f,d)}},p=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(k.stringify(a)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(a){return k.parse(unescape(encodeURIComponent(a)))}},S=g.BufferedBlockAlgorithm=_.extend({reset:function(){this._data=new h.init,this._nDataBytes=0},_append:function(a){typeof a=="string"&&(a=p.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(a){var d,f=this._data,v=f.words,E=f.sigBytes,T=this.blockSize,x=T*4,C=E/x;a?C=s.ceil(C):C=s.max((C|0)-this._minBufferSize,0);var M=C*T,P=s.min(M*4,E);if(M){for(var q=0;q<M;q+=T)this._doProcessBlock(v,q);d=v.splice(0,M),f.sigBytes-=P}return new h.init(d,P)},clone:function(){var a=_.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0});g.Hasher=S.extend({cfg:_.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){S.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var d=this._doFinalize();return d},blockSize:16,_createHelper:function(a){return function(d,f){return new a.init(f).finalize(d)}},_createHmacHelper:function(a){return function(d,f){return new R.HMAC.init(a,f).finalize(d)}}});var R=u.algo={};return u})(Math);return r})})(re)),re.exports}var nt=se();const ot=te(nt);var ie={exports:{}},at=ie.exports,Ce;function ct(){return Ce||(Ce=1,(function(e,t){(function(r,s){e.exports=s(se())})(at,function(r){return(function(s){var i=r,n=i.lib,o=n.WordArray,l=n.Hasher,u=i.algo,g=[],_=[];(function(){function w(R){for(var a=s.sqrt(R),d=2;d<=a;d++)if(!(R%d))return!1;return!0}function k(R){return(R-(R|0))*4294967296|0}for(var p=2,S=0;S<64;)w(p)&&(S<8&&(g[S]=k(s.pow(p,1/2))),_[S]=k(s.pow(p,1/3)),S++),p++})();var h=[],b=u.SHA256=l.extend({_doReset:function(){this._hash=new o.init(g.slice(0))},_doProcessBlock:function(w,k){for(var p=this._hash.words,S=p[0],R=p[1],a=p[2],d=p[3],f=p[4],v=p[5],E=p[6],T=p[7],x=0;x<64;x++){if(x<16)h[x]=w[k+x]|0;else{var C=h[x-15],M=(C<<25|C>>>7)^(C<<14|C>>>18)^C>>>3,P=h[x-2],q=(P<<15|P>>>17)^(P<<13|P>>>19)^P>>>10;h[x]=M+h[x-7]+q+h[x-16]}var B=f&v^~f&E,ee=S&R^S&a^R&a,z=(S<<30|S>>>2)^(S<<19|S>>>13)^(S<<10|S>>>22),Y=(f<<26|f>>>6)^(f<<21|f>>>11)^(f<<7|f>>>25),$=T+Y+B+_[x]+h[x],V=z+ee;T=E,E=v,v=f,f=d+$|0,d=a,a=R,R=S,S=$+V|0}p[0]=p[0]+S|0,p[1]=p[1]+R|0,p[2]=p[2]+a|0,p[3]=p[3]+d|0,p[4]=p[4]+f|0,p[5]=p[5]+v|0,p[6]=p[6]+E|0,p[7]=p[7]+T|0},_doFinalize:function(){var w=this._data,k=w.words,p=this._nDataBytes*8,S=w.sigBytes*8;return k[S>>>5]|=128<<24-S%32,k[(S+64>>>9<<4)+14]=s.floor(p/4294967296),k[(S+64>>>9<<4)+15]=p,w.sigBytes=k.length*4,this._process(),this._hash},clone:function(){var w=l.clone.call(this);return w._hash=this._hash.clone(),w}});i.SHA256=l._createHelper(b),i.HmacSHA256=l._createHmacHelper(b)})(Math),r.SHA256})})(ie)),ie.exports}var lt=ct();const ut=te(lt);var ne={exports:{}},dt=ne.exports,Ue;function ht(){return Ue||(Ue=1,(function(e,t){(function(r,s){e.exports=s(se())})(dt,function(r){return(function(){var s=r,i=s.lib,n=i.WordArray,o=s.enc;o.Base64={stringify:function(u){var g=u.words,_=u.sigBytes,h=this._map;u.clamp();for(var b=[],w=0;w<_;w+=3)for(var k=g[w>>>2]>>>24-w%4*8&255,p=g[w+1>>>2]>>>24-(w+1)%4*8&255,S=g[w+2>>>2]>>>24-(w+2)%4*8&255,R=k<<16|p<<8|S,a=0;a<4&&w+a*.75<_;a++)b.push(h.charAt(R>>>6*(3-a)&63));var d=h.charAt(64);if(d)for(;b.length%4;)b.push(d);return b.join("")},parse:function(u){var g=u.length,_=this._map,h=this._reverseMap;if(!h){h=this._reverseMap=[];for(var b=0;b<_.length;b++)h[_.charCodeAt(b)]=b}var w=_.charAt(64);if(w){var k=u.indexOf(w);k!==-1&&(g=k)}return l(u,g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};function l(u,g,_){for(var h=[],b=0,w=0;w<g;w++)if(w%4){var k=_[u.charCodeAt(w-1)]<<w%4*2,p=_[u.charCodeAt(w)]>>>6-w%4*2,S=k|p;h[b>>>2]|=S<<24-b%4*8,b++}return n.create(h,b)}})(),r.enc.Base64})})(ne)),ne.exports}var gt=ht();const Ae=te(gt);var oe={exports:{}},_t=oe.exports,Oe;function ft(){return Oe||(Oe=1,(function(e,t){(function(r,s){e.exports=s(se())})(_t,function(r){return r.enc.Utf8})})(oe)),oe.exports}var pt=ft();const wt=te(pt);function he(e){this.message=e}he.prototype=new Error,he.prototype.name="InvalidCharacterError";var Pe=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new he("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,s,i=0,n=0,o="";s=t.charAt(n++);~s&&(r=i%4?64*r+s:s,i++%4)?o+=String.fromCharCode(255&r>>(-2*i&6)):0)s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);return o};function vt(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return(function(r){return decodeURIComponent(Pe(r).replace(/(.)/g,(function(s,i){var n=i.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))})(t)}catch{return Pe(t)}}function ae(e){this.message=e}function mt(e,t){if(typeof e!="string")throw new ae("Invalid token specified");var r=(t=t||{}).header===!0?0:1;try{return JSON.parse(vt(e.split(".")[r]))}catch(s){throw new ae("Invalid token specified: "+s.message)}}ae.prototype=new Error,ae.prototype.name="InvalidTokenError";var St={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},L,H,ce=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(ce||{});(e=>{function t(){L=3,H=St}e.reset=t;function r(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");L=i}e.setLevel=r;function s(i){H=i}e.setLogger=s})(ce||(ce={}));var m=class{constructor(e){this._name=e}debug(...e){L>=4&&H.debug(m._format(this._name,this._method),...e)}info(...e){L>=3&&H.info(m._format(this._name,this._method),...e)}warn(...e){L>=2&&H.warn(m._format(this._name,this._method),...e)}error(...e){L>=1&&H.error(m._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const r=new m(`${e}.${t}`);return r.debug("begin"),r}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(e,...t){L>=4&&H.debug(m._format(e),...t)}static info(e,...t){L>=3&&H.info(m._format(e),...t)}static warn(e,...t){L>=2&&H.warn(m._format(e),...t)}static error(e,...t){L>=1&&H.error(m._format(e),...t)}};ce.reset();var yt="10000000-1000-4000-8000-100000000000",D=class{static _randomWord(){return ot.lib.WordArray.random(1).words[0]}static generateUUIDv4(){return yt.replace(/[018]/g,t=>(+t^D._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return D.generateUUIDv4()+D.generateUUIDv4()+D.generateUUIDv4()}static generateCodeChallenge(e){try{const t=ut(e);return Ae.stringify(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw m.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const r=wt.parse([e,t].join(":"));return Ae.stringify(r)}},W=class{constructor(e){this._name=e,this._logger=new m(`Event('${this._name}')`),this._callbacks=[]}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)t(...e)}},ge=class{static decode(e){try{return mt(e)}catch(t){throw m.error("JwtUtils.decode",t),t}}},Ne=class{static center({...e}){var t,r,s;return e.width==null&&(e.width=(t=[800,720,600,480].find(i=>i<=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&&((s=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(",")}},j=class extends W{constructor(){super(...arguments),this._logger=new m(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-j.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=j.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const r=j.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;const s=Math.min(e,5);this._timerHandle=setInterval(this._callback,s*1e3)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},_e=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const s=new URL(e,"http://127.0.0.1")[t==="fragment"?"hash":"search"];return new URLSearchParams(s.slice(1))}},fe=";",F=class extends Error{constructor(e,t){var r,s,i;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw m.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=(s=e.error_uri)!=null?s:null,this.state=e.userState,this.session_state=(i=e.session_state)!=null?i:null,this.url_state=e.url_state}},pe=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},bt=class{constructor(e){this._logger=new m("AccessTokenEvents"),this._expiringTimer=new j("Access token expiring"),this._expiredTimer=new j("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}load(e){const t=this._logger.create("load");if(e.access_token&&e.expires_in!==void 0){const r=e.expires_in;if(t.debug("access token present, remaining duration:",r),r>0){let i=r-this._expiringNotificationTimeInSeconds;i<=0&&(i=1),t.debug("registering expiring timer, raising in",i,"seconds"),this._expiringTimer.init(i)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const s=r+1;t.debug("registering expired timer, raising in",s,"seconds"),this._expiredTimer.init(s)}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)}},kt=class{constructor(e,t,r,s,i){this._callback=e,this._client_id=t,this._intervalInSeconds=s,this._stopOnError=i,this._logger=new m("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=o=>{o.origin===this._frame_origin&&o.source===this._frame.contentWindow&&(o.data==="error"?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):o.data==="changed"?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(o.data+" message from check session op iframe"))};const n=new URL(r);this._frame_origin=n.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=n.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{!this._frame.contentWindow||!this._session_state||this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,this._intervalInSeconds*1e3)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},je=class{constructor(){this._logger=new m("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]}},we=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new m("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...s}=t;if(!r)return await fetch(e,s);const i=new AbortController,n=setTimeout(()=>i.abort(),r*1e3);try{return await fetch(e,{...t,signal:i.signal})}catch(o){throw o instanceof DOMException&&o.name==="AbortError"?new pe("Network timed out"):o}finally{clearTimeout(n)}}async getJson(e,{token:t,credentials:r}={}){const s=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};t&&(s.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this.appendExtraHeaders(i);let n;try{s.debug("url:",e),n=await this.fetchWithTimeout(e,{method:"GET",headers:i,credentials:r})}catch(u){throw s.error("Network Error"),u}s.debug("HTTP response received, status",n.status);const o=n.headers.get("Content-Type");if(o&&!this._contentTypes.find(u=>o.startsWith(u))&&s.throw(new Error(`Invalid response Content-Type: ${o??"undefined"}, from URL: ${e}`)),n.ok&&this._jwtHandler&&o?.startsWith("application/jwt"))return await this._jwtHandler(await n.text());let l;try{l=await n.json()}catch(u){throw s.error("Error parsing JSON response",u),n.ok?u:new Error(`${n.statusText} (${n.status})`)}if(!n.ok)throw s.error("Error from server:",l),l.error?new F(l):new Error(`${n.statusText} (${n.status}): ${JSON.stringify(l)}`);return l}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:s,initCredentials:i}){const n=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};r!==void 0&&(o.Authorization="Basic "+r),this.appendExtraHeaders(o);let l;try{n.debug("url:",e),l=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:s,credentials:i})}catch(h){throw n.error("Network error"),h}n.debug("HTTP response received, status",l.status);const u=l.headers.get("Content-Type");if(u&&!this._contentTypes.find(h=>u.startsWith(h)))throw new Error(`Invalid response Content-Type: ${u??"undefined"}, from URL: ${e}`);const g=await l.text();let _={};if(g)try{_=JSON.parse(g)}catch(h){throw n.error("Error parsing JSON response",h),l.ok?h:new Error(`${l.statusText} (${l.status})`)}if(!l.ok)throw n.error("Error from server:",_),_.error?new F(_,t):new Error(`${l.statusText} (${l.status}): ${JSON.stringify(_)}`);return _}appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),s=["authorization","accept","content-type"];r.length!==0&&r.forEach(i=>{if(s.includes(i.toLocaleLowerCase())){t.warn("Protected header could not be overridden",i,s);return}const n=typeof this._extraHeaders[i]=="function"?this._extraHeaders[i]():this._extraHeaders[i];n&&n!==""&&(e[i]=n)})}},Et=class{constructor(e){this._settings=e,this._logger=new m("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new we(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,t),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const r=this._logger.create(`_getMetadataProperty('${e}')`),s=await this.getMetadata();if(r.debug("resolved"),s[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 s[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const 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}},ve=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new m("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return this._logger.create(`get('${e}')`),e=this._prefix+e,await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let r=0;r<e;r++){const s=await this._store.key(r);s&&s.indexOf(this._prefix)===0&&t.push(s.substr(this._prefix.length))}return t}},Tt="code",Rt="openid",xt="client_secret_post",It="query",Ct=900,Ut=300,me=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:s,metadataSeed:i,client_id:n,client_secret:o,response_type:l=Tt,scope:u=Rt,redirect_uri:g,post_logout_redirect_uri:_,client_authentication:h=xt,prompt:b,display:w,max_age:k,ui_locales:p,acr_values:S,resource:R,response_mode:a=It,filterProtocolClaims:d=!0,loadUserInfo:f=!1,staleStateAgeInSeconds:v=Ct,clockSkewInSeconds:E=Ut,userInfoJwtIssuer:T="OP",mergeClaims:x=!1,disablePKCE:C=!1,stateStore:M,refreshTokenCredentials:P,revokeTokenAdditionalContentTypes:q,fetchRequestCredentials:B,refreshTokenAllowedScope:ee,extraQueryParams:z={},extraTokenParams:Y={},extraHeaders:$={}}){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=i,this.signingKeys=s,this.client_id=n,this.client_secret=o,this.response_type=l,this.scope=u,this.redirect_uri=g,this.post_logout_redirect_uri=_,this.client_authentication=h,this.prompt=b,this.display=w,this.max_age=k,this.ui_locales=p,this.acr_values=S,this.resource=R,this.response_mode=a,this.filterProtocolClaims=d??!0,this.loadUserInfo=!!f,this.staleStateAgeInSeconds=v,this.clockSkewInSeconds=E,this.userInfoJwtIssuer=T,this.mergeClaims=!!x,this.disablePKCE=!!C,this.revokeTokenAdditionalContentTypes=q,B&&P&&console.warn("Both fetchRequestCredentials and refreshTokenCredentials is set. Only fetchRequestCredentials will be used."),this.fetchRequestCredentials=B||P||"same-origin",M)this.stateStore=M;else{const V=typeof window<"u"?window.localStorage:new je;this.stateStore=new ve({store:V})}this.refreshTokenAllowedScope=ee,this.extraQueryParams=z,this.extraTokenParams=Y,this.extraHeaders=$}},At=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new m("UserInfoService"),this._getClaimsFromJwt=async r=>{const s=this._logger.create("_getClaimsFromJwt");try{const i=ge.decode(r);return s.debug("JWT decoding successful"),i}catch(i){throw s.error("Error parsing JWT response"),i}},this._jsonService=new we(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const s=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials});return t.debug("got claims",s),s}},Me=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new m("TokenClient"),this._jsonService=new we(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:s=this._settings.client_secret,...i}){const 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")),i.code||n.throw(new Error("A code is required"));const o=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[_,h]of Object.entries(i))h!=null&&o.set(_,h);let l;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw n.throw(new Error("A client_secret is required")),null;l=D.generateBasicAuth(r,s);break;case"client_secret_post":o.append("client_id",r),s&&o.append("client_secret",s);break}const u=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const g=await this._jsonService.postForm(u,{body:o,basicAuth:l,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),g}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:s=this._settings.scope,...i}){const n=this._logger.create("exchangeCredentials");t||n.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e,scope:s});for(const[_,h]of Object.entries(i))h!=null&&o.set(_,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=D.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break}const u=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const g=await this._jsonService.postForm(u,{body:o,basicAuth:l,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),g}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:s,...i}){const n=this._logger.create("exchangeRefreshToken");t||n.throw(new Error("A client_id is required")),i.refresh_token||n.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:e});for(const[_,h]of Object.entries(i))Array.isArray(h)?h.forEach(b=>o.append(_,b)):h!=null&&o.set(_,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=D.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r);break}const u=await this._metadataService.getTokenEndpoint(!1);n.debug("got token endpoint");const g=await this._jsonService.postForm(u,{body:o,basicAuth:l,timeoutInSeconds:s,initCredentials:this._settings.fetchRequestCredentials});return n.debug("got response"),g}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const s=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${(t=e.token_type_hint)!=null?t:"default token type"}`);const i=new URLSearchParams;for(const[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(s,{body:i}),r.debug("got response")}},Ot=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new m("ResponseValidator"),this._userInfoService=new At(this._settings,this._metadataService),this._tokenClient=new Me(this._settings,this._metadataService)}async validateSigninResponse(e,t){const 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?.skipUserInfo,e.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse");e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),r.debug("claims processed")}async validateRefreshResponse(e,t){var r,s;const i=this._logger.create("validateRefreshResponse");e.userState=t.data,(r=e.session_state)!=null||(e.session_state=t.session_state),(s=e.scope)!=null||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),i.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),i.debug("claims processed")}validateSignoutResponse(e,t){const 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 F(e)}_processSigninState(e,t){var r;const s=this._logger.create("_processSigninState");if(t.id!==e.state&&s.throw(new Error("State does not match")),t.client_id||s.throw(new Error("No client_id on state")),t.authority||s.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&s.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&s.throw(new Error("client_id mismatch on settings vs. signin state")),s.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,(r=e.scope)!=null||(e.scope=t.scope),e.error)throw s.warn("Response was error",e.error),new F(e);t.code_verifier&&!e.code&&s.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const s=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token){s.debug("not loading user info");return}s.debug("loading user info");const i=await this._userInfoService.getClaims(e.access_token);s.debug("user info claims received from user info endpoint"),r&&i.sub!==e.profile.sub&&s.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(i)),s.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t){const r=this._logger.create("_processCode");if(e.code){r.debug("Validating code");const s=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,s)}else r.debug("No code to process")}_validateIdTokenAttributes(e,t){var r;const s=this._logger.create("_validateIdTokenAttributes");s.debug("decoding ID Token JWT");const i=ge.decode((r=e.id_token)!=null?r:"");if(i.sub||s.throw(new Error("ID Token is missing a subject claim")),t){const n=ge.decode(t);i.sub!==n.sub&&s.throw(new Error("sub in id_token does not match current sub")),i.auth_time&&i.auth_time!==n.auth_time&&s.throw(new Error("auth_time in id_token does not match original auth_time")),i.azp&&i.azp!==n.azp&&s.throw(new Error("azp in id_token does not match original azp")),!i.azp&&n.azp&&s.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}},J=class{constructor(e){this.id=e.id||D.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=j.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new m("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(e){return m.createStatic("State","fromStorageString"),new J(JSON.parse(e))}static async clearStaleState(e,t){const r=m.createStatic("State","clearStaleState"),s=j.getEpochTime()-t,i=await e.getAllKeys();r.debug("got keys",i);for(let n=0;n<i.length;n++){const o=i[n],l=await e.get(o);let u=!1;if(l)try{const g=J.fromStorageString(l);r.debug("got item from key:",o,g.created),g.created<=s&&(u=!0)}catch(g){r.error("Error parsing state for key:",o,g),u=!0}else r.debug("no item in storage for key:",o),u=!0;u&&(r.debug("removed item for key:",o),e.remove(o))}}},Se=class extends J{constructor(e){super(e),e.code_verifier===!0?this.code_verifier=D.generateCodeVerifier():e.code_verifier&&(this.code_verifier=e.code_verifier),this.code_verifier&&(this.code_challenge=D.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 m("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(e){m.createStatic("SigninState","fromStorageString");const t=JSON.parse(e);return new Se(t)}},Pt=class{constructor({url:e,authority:t,client_id:r,redirect_uri:s,response_type:i,scope:n,state_data:o,response_mode:l,request_type:u,client_secret:g,nonce:_,url_state:h,resource:b,skipUserInfo:w,extraQueryParams:k,extraTokenParams:p,disablePKCE:S,...R}){if(this._logger=new m("SigninRequest"),!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(!s)throw this._logger.error("ctor: No redirect_uri passed"),new Error("redirect_uri");if(!i)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 Se({data:o,request_type:u,url_state:h,code_verifier:!S,client_id:r,authority:t,redirect_uri:s,response_mode:l,client_secret:g,scope:n,extraTokenParams:p,skipUserInfo:w});const a=new URL(e);a.searchParams.append("client_id",r),a.searchParams.append("redirect_uri",s),a.searchParams.append("response_type",i),a.searchParams.append("scope",n),_&&a.searchParams.append("nonce",_);let d=this.state.id;h&&(d=`${d}${fe}${h}`),a.searchParams.append("state",d),this.state.code_challenge&&(a.searchParams.append("code_challenge",this.state.code_challenge),a.searchParams.append("code_challenge_method","S256")),b&&(Array.isArray(b)?b:[b]).forEach(v=>a.searchParams.append("resource",v));for(const[f,v]of Object.entries({response_mode:l,...R,...k}))v!=null&&a.searchParams.append(f,v.toString());this.url=a.href}},Nt="openid",ye=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const t=decodeURIComponent(this.state).split(fe);this.state=t[0],t.length>1&&(this.url_state=t.slice(1).join(fe))}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-j.getEpochTime()}set expires_in(e){typeof e=="string"&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+j.getEpochTime())}get isOpenId(){var e;return((e=this.scope)==null?void 0:e.split(" ").includes(Nt))||!!this.id_token}},jt=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:s,extraQueryParams:i,request_type:n,client_id:o}){if(this._logger=new m("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const l=new URL(e);r&&l.searchParams.append("id_token_hint",r),o&&l.searchParams.append("client_id",o),s&&(l.searchParams.append("post_logout_redirect_uri",s),t&&(this.state=new J({data:t,request_type:n}),l.searchParams.append("state",this.state.id)));for(const[u,g]of Object.entries({...i}))g!=null&&l.searchParams.append(u,g.toString());this.url=l.href}},Mt=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")}},qt=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],Lt=["sub","iss","aud","exp","iat"],Ht=class{constructor(e){this._settings=e,this._logger=new m("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let r;Array.isArray(this._settings.filterProtocolClaims)?r=this._settings.filterProtocolClaims:r=qt;for(const s of r)Lt.includes(s)||delete t[s]}return t}mergeClaims(e,t){const r={...e};for(const[s,i]of Object.entries(t))for(const n of Array.isArray(i)?i:[i]){const o=r[s];o===void 0?r[s]=n:Array.isArray(o)?o.includes(n)||o.push(n):r[s]!==n&&(typeof n=="object"&&this._settings.mergeClaims?r[s]=this.mergeClaims(o,n):r[s]=[o,n])}return r}},Dt=class{constructor(e,t){this._logger=new m("OidcClient"),this.settings=e instanceof me?e:new me(e),this.metadataService=t??new Et(this.settings),this._claimsService=new Ht(this.settings),this._validator=new Ot(this.settings,this.metadataService,this._claimsService),this._tokenClient=new Me(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:s,id_token_hint:i,login_hint:n,skipUserInfo:o,nonce:l,url_state:u,response_type:g=this.settings.response_type,scope:_=this.settings.scope,redirect_uri:h=this.settings.redirect_uri,prompt:b=this.settings.prompt,display:w=this.settings.display,max_age:k=this.settings.max_age,ui_locales:p=this.settings.ui_locales,acr_values:S=this.settings.acr_values,resource:R=this.settings.resource,response_mode:a=this.settings.response_mode,extraQueryParams:d=this.settings.extraQueryParams,extraTokenParams:f=this.settings.extraTokenParams}){const v=this._logger.create("createSigninRequest");if(g!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const E=await this.metadataService.getAuthorizationEndpoint();v.debug("Received authorization endpoint",E);const T=new Pt({url:E,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:h,response_type:g,scope:_,state_data:e,url_state:u,prompt:b,display:w,max_age:k,ui_locales:p,id_token_hint:i,login_hint:n,acr_values:S,resource:R,request:t,request_uri:r,extraQueryParams:d,extraTokenParams:f,request_type:s,response_mode:a,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:l,disablePKCE:this.settings.disablePKCE});await this.clearStaleState();const x=T.state;return await this.settings.stateStore.set(x.id,x.toStorageString()),T}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),s=new ye(_e.readParams(e,this.settings.response_mode));if(!s.state)throw r.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[t?"remove":"get"](s.state);if(!i)throw r.throw(new Error("No matching state found in storage")),null;return{state:Se.fromStorageString(i),response:s}}async processSigninResponse(e){const t=this._logger.create("processSigninResponse"),{state:r,response:s}=await this.readSigninResponseState(e,!0);return t.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(s,r),s}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:s={}}){const i=await this._tokenClient.exchangeCredentials({username:e,password:t,...s}),n=new ye(new URLSearchParams);return Object.assign(n,i),await this._validator.validateCredentialsResponse(n,r),n}async useRefreshToken({state:e,timeoutInSeconds:t,extraTokenParams:r}){var s;const i=this._logger.create("useRefreshToken");let n;if(this.settings.refreshTokenAllowedScope===void 0)n=e.scope;else{const u=this.settings.refreshTokenAllowedScope.split(" ");n=(((s=e.scope)==null?void 0:s.split(" "))||[]).filter(_=>u.includes(_)).join(" ")}const o=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,resource:e.resource,scope:n,timeoutInSeconds:t,...r}),l=new ye(new URLSearchParams);return Object.assign(l,o),i.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:n}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:s,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:n=this.settings.extraQueryParams}={}){const o=this._logger.create("createSignoutRequest"),l=await this.metadataService.getEndSessionEndpoint();if(!l)throw o.throw(new Error("No end session endpoint")),null;o.debug("Received end session endpoint",l),!r&&i&&!t&&(r=this.settings.client_id);const u=new jt({url:l,id_token_hint:t,client_id:r,post_logout_redirect_uri:i,state_data:e,extraQueryParams:n,request_type:s});await this.clearStaleState();const g=u.state;return g&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(g.id,g.toStorageString())),u}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),s=new Mt(_e.readParams(e,this.settings.response_mode));if(!s.state){if(r.debug("No state in response"),s.error)throw r.warn("Response was error:",s.error),new F(s);return{state:void 0,response:s}}const i=await this.settings.stateStore[t?"remove":"get"](s.state);if(!i)throw r.throw(new Error("No matching state found in storage")),null;return{state:J.fromStorageString(i),response:s}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:s}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(s,r)):t.debug("No state from storage; skipping response validation"),s}clearStaleState(){return this._logger.create("clearStaleState"),J.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})}},Wt=class{constructor(e){this._userManager=e,this._logger=new m("SessionMonitor"),this._start=async t=>{const r=t.session_state;if(!r)return;const s=this._logger.create("_start");if(t.profile?(this._sub=t.profile.sub,this._sid=t.profile.sid,s.debug("session_state",r,", sub",this._sub)):(this._sub=void 0,this._sid=void 0,s.debug("session_state",r,", anonymous user")),this._checkSessionIFrame){this._checkSessionIFrame.start(r);return}try{const i=await this._userManager.metadataService.getCheckSessionIframe();if(i){s.debug("initializing check session iframe");const n=this._userManager.settings.client_id,o=this._userManager.settings.checkSessionIntervalInSeconds,l=this._userManager.settings.stopCheckSessionOnError,u=new kt(this._callback,n,i,o,l);await u.load(),this._checkSessionIFrame=u,u.start(r)}else s.warn("no check session iframe found in the metadata")}catch(i){s.error("Error from getCheckSessionIframe:",i instanceof Error?i.message:i)}},this._stop=()=>{const t=this._logger.create("_stop");if(this._sub=void 0,this._sid=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const r=setInterval(async()=>{clearInterval(r);try{const s=await this._userManager.querySessionStatus();if(s){const i={session_state:s.session_state,profile:s.sub&&s.sid?{sub:s.sub,sid:s.sid}:null};this._start(i)}}catch(s){t.error("error from querySessionStatus",s instanceof Error?s.message:s)}},1e3)}},this._callback=async()=>{const t=this._logger.create("_callback");try{const r=await this._userManager.querySessionStatus();let s=!0;r&&this._checkSessionIFrame?r.sub===this._sub?(s=!1,this._checkSessionIFrame.start(r.session_state),r.sid===this._sid?t.debug("same sub still logged in at OP, restarting check session iframe; session_state",r.session_state):(t.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",r.session_state),this._userManager.events._raiseUserSessionChanged())):t.debug("different subject signed into OP",r.sub):t.debug("subject no longer signed into OP"),s?this._sub?this._userManager.events._raiseUserSignedOut():this._userManager.events._raiseUserSignedIn():t.debug("no change in session detected, no event to raise")}catch(r){this._sub&&(t.debug("Error calling queryCurrentSigninSession; raising signed out event",r),this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(t=>{this._logger.error(t)})}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const t=await this._userManager.querySessionStatus();if(t){const r={session_state:t.session_state,profile:t.sub&&t.sid?{sub:t.sub,sid:t.sid}:null};this._start(r)}}}},K=class{constructor(e){var t;this.id_token=e.id_token,this.session_state=(t=e.session_state)!=null?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-j.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+j.getEpochTime())}get expired(){const e=this.expires_in;if(e!==void 0)return e<=0}get scopes(){var e,t;return(t=(e=this.scope)==null?void 0:e.split(" "))!=null?t:[]}toStorageString(){return new m("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 m.createStatic("User","fromStorageString"),new K(JSON.parse(e))}},qe="oidc-client",Le=class{constructor(){this._abort=new W("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:r,keepOpen:s}=await new Promise((i,n)=>{const o=l=>{var u;const g=l.data,_=(u=e.scriptOrigin)!=null?u:window.location.origin;if(!(l.origin!==_||g?.source!==qe)){try{const h=_e.readParams(g.url,e.response_mode).get("state");if(h||t.warn("no state found in response url"),l.source!==this._window&&h!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}i(g)}};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(),s||this.close(),{url:r}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,r=!1,s=window.location.origin){e.postMessage({source:qe,url:t,keepOpen:r},s)}},He={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},De="_blank",Bt=60,Ft=2,We=10,zt=class extends me{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:r=e.post_logout_redirect_uri,popupWindowFeatures:s=He,popupWindowTarget:i=De,redirectMethod:n="assign",redirectTarget:o="self",iframeNotifyParentOrigin:l=e.iframeNotifyParentOrigin,iframeScriptOrigin:u=e.iframeScriptOrigin,silent_redirect_uri:g=e.redirect_uri,silentRequestTimeoutInSeconds:_=We,automaticSilentRenew:h=!0,validateSubOnSilentRenew:b=!0,includeIdTokenInSilentRenew:w=!1,monitorSession:k=!1,monitorAnonymousSession:p=!1,checkSessionIntervalInSeconds:S=Ft,query_status_response_type:R="code",stopCheckSessionOnError:a=!0,revokeTokenTypes:d=["access_token","refresh_token"],revokeTokensOnSignout:f=!1,includeIdTokenInSilentSignout:v=!1,accessTokenExpiringNotificationTimeInSeconds:E=Bt,userStore:T}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=s,this.popupWindowTarget=i,this.redirectMethod=n,this.redirectTarget=o,this.iframeNotifyParentOrigin=l,this.iframeScriptOrigin=u,this.silent_redirect_uri=g,this.silentRequestTimeoutInSeconds=_,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=b,this.includeIdTokenInSilentRenew=w,this.monitorSession=k,this.monitorAnonymousSession=p,this.checkSessionIntervalInSeconds=S,this.stopCheckSessionOnError=a,this.query_status_response_type=R,this.revokeTokenTypes=d,this.revokeTokensOnSignout=f,this.includeIdTokenInSilentSignout=v,this.accessTokenExpiringNotificationTimeInSeconds=E,T)this.userStore=T;else{const x=typeof window<"u"?window.sessionStorage:new je;this.userStore=new ve({store:x})}}},be=class extends Le{constructor({silentRequestTimeoutInSeconds:e=We}){super(),this._logger=new m("IFrameWindow"),this._timeoutInSeconds=e,this._frame=be.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout(()=>this._abort.raise(new pe("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 r;const s=t.target;(r=s.parentNode)==null||r.removeChild(s),this._abort.raise(new Error("IFrame removed from DOM"))},!0),(e=this._frame.contentWindow)==null||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},$t=class{constructor(e){this._settings=e,this._logger=new m("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new be({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),be.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},Jt=500,Kt=1e3,Be=class extends Le{constructor({popupWindowTarget:e=De,popupWindowFeatures:t={}}){super(),this._logger=new m("PopupWindow");const r=Ne.center({...He,...t});this._window=window.open(void 0,e,Ne.serialize(r)),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{if(!this._window||typeof this._window.closed!="boolean"||this._window.closed){this._abort.raise(new Error("Popup blocked by user"));return}this.close()},t.closePopupWindowAfterInSeconds*Kt)}async navigate(e){var t;(t=this._window)==null||t.focus();const r=setInterval(()=>{(!this._window||this._window.closed)&&this._abort.raise(new Error("Popup closed by user"))},Jt);return this._disposeHandlers.add(()=>clearInterval(r)),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)}},Gt=class{constructor(e){this._settings=e,this._logger=new m("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget}){return new Be({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Be.notifyOpener(e,t)}},Yt=class{constructor(e){this._settings=e,this._logger=new m("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var r;this._logger.create("prepare");let s=window.self;t==="top"&&(s=(r=window.top)!=null?r:window.self);const i=s.location[e].bind(s.location);let n;return{navigate:async o=>{this._logger.create("navigate");const l=new Promise((u,g)=>{n=g});return i(o.url),await l},close:()=>{this._logger.create("close"),n?.(new Error("Redirect aborted")),s.stop()}}}async callback(){}},Vt=class extends bt{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new m("UserManagerEvents"),this._userLoaded=new W("User loaded"),this._userUnloaded=new W("User unloaded"),this._silentRenewError=new W("Silent renew error"),this._userSignedIn=new W("User signed in"),this._userSignedOut=new W("User signed out"),this._userSessionChanged=new W("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()}},Xt=class{constructor(e){this._userManager=e,this._logger=new m("SilentRenewService"),this._isStarted=!1,this._retryTimer=new j("Retry Silent Renew"),this._tokenExpiring=async()=>{const t=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),t.debug("silent token renewal successful")}catch(r){if(r instanceof pe){t.warn("ErrorTimeout from signinSilent:",r,"retry in 5s"),this._retryTimer.init(5);return}t.error("Error from signinSilent:",r),this._userManager.events._raiseSilentRenewError(r)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Zt=class{constructor(e,t){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.resource=t,this.data=e.state}},Qt=class{constructor(e,t,r,s){this._logger=new m("UserManager"),this.settings=new zt(e),this._client=new Dt(e),this._redirectNavigator=t??new Yt(this.settings),this._popupNavigator=r??new Gt(this.settings),this._iframeNavigator=s??new $t(this.settings),this._events=new Vt(this.settings),this._silentRenewService=new Xt(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new Wt(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(){const e=this._logger.create("getUser"),t=await this._loadUser();return t?(e.info("user loaded"),this._events.load(t,!1),t):(e.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),this._events.unload()}async signinRedirect(e={}){this._logger.create("signinRedirect");const{redirectMethod:t,...r}=e,s=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:"si:r",...r},s)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),r=await this._signinEnd(e);return r.profile&&r.profile.sub?t.info("success, signed in subject",r.profile.sub):t.info("no subject"),r}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:r=!1}){const s=this._logger.create("signinResourceOwnerCredential"),i=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r,extraTokenParams:this.settings.extraTokenParams});s.debug("got signin response");const n=await this._buildUser(i);return n.profile&&n.profile.sub?s.info("success, signed in subject",n.profile.sub):s.info("no subject"),n}async signinPopup(e={}){const t=this._logger.create("signinPopup"),{popupWindowFeatures:r,popupWindowTarget:s,...i}=e,n=this.settings.popup_redirect_uri;n||t.throw(new Error("No popup_redirect_uri configured"));const o=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:s}),l=await this._signin({request_type:"si:p",redirect_uri:n,display:"popup",...i},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){const r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async signinSilent(e={}){var t;const r=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,resource:i,...n}=e;let o=await this._loadUser();if(o?.refresh_token){r.debug("using refresh token");const _=new Zt(o,i);return await this._useRefreshToken({state:_,extraTokenParams:n.extraTokenParams})}const l=this.settings.silent_redirect_uri;l||r.throw(new Error("No silent_redirect_uri configured"));let u;o&&this.settings.validateSubOnSilentRenew&&(r.debug("subject prior to silent renew:",o.profile.sub),u=o.profile.sub);const g=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return o=await this._signin({request_type:"si:s",redirect_uri:l,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?o?.id_token:void 0,...n},g,u),o&&((t=o.profile)!=null&&t.sub?r.info("success, signed in subject",o.profile.sub):r.info("no subject")),o}async _useRefreshToken(e){const t=await this._client.useRefreshToken({...e,timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds}),r=new K({...e.state,...t});return await this.storeUser(r),this._events.load(r),r}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":return await this.signinPopupCallback(e);case"si:s":return await this.signinSilentCallback(e);default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:r}=await this._client.readSignoutResponseState(e);if(r)switch(r.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:r,...s}=e,i=this.settings.silent_redirect_uri;i||t.throw(new Error("No silent_redirect_uri configured"));const n=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),l=await this._signinStart({request_type:"si:s",redirect_uri:i,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?n?.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},o);try{const u=await this._client.processSigninResponse(l.url);return t.debug("got signin response"),u.session_state&&u.profile.sub?(t.info("success for subject",u.profile.sub),{session_state:u.session_state,sub:u.profile.sub,sid:u.profile.sid}):(t.info("success, user not authenticated"),null)}catch(u){if(this.settings.monitorAnonymousSession&&u instanceof F)switch(u.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:u.session_state}}throw u}}async _signin(e,t,r){const s=await this._signinStart(e,t);return await this._signinEnd(s.url,r)}async _signinStart(e,t){const r=this._logger.create("_signinStart");try{const s=await this._client.createSigninRequest(e);return r.debug("got signin request"),await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),s}}async _signinEnd(e,t){const r=this._logger.create("_signinEnd"),s=await this._client.processSigninResponse(e);return r.debug("got signin response"),await this._buildUser(s,t)}async _buildUser(e,t){const r=this._logger.create("_buildUser"),s=new K(e);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 F({...e,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={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:r,...s}=e,i=await this._redirectNavigator.prepare({redirectMethod:r});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},i),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),r=await this._signoutEnd(e);return t.info("success"),r}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:r,popupWindowTarget:s,...i}=e,n=this.settings.popup_post_logout_redirect_uri,o=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:n,state:n==null?void 0:{},...i},o),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async _signout(e,t){const r=await this._signoutStart(e,t);return await this._signoutEnd(r.url)}async _signoutStart(e={},t){var r;const s=this._logger.create("_signoutStart");try{const i=await this._loadUser();s.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(i);const n=e.id_token_hint||i&&i.id_token;n&&(s.debug("setting id_token_hint in signout request"),e.id_token_hint=n),await this.removeUser(),s.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return s.debug("got signout request"),await t.navigate({url:o.url,state:(r=o.state)==null?void 0:r.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(i){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),i}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),r=await this._client.processSignoutResponse(e);return t.debug("got signout response"),r}async signoutSilent(e={}){var t;const r=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:s,...i}=e,n=this.settings.includeIdTokenInSilentSignout?(t=await this._loadUser())==null?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:n,...i},l),r.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const r=this._logger.create("_revokeInternal");if(!e)return;const s=t.filter(i=>typeof e[i]=="string");if(!s.length){r.debug("no need to revoke due to no token(s)");return}for(const i of s)await this._client.revokeToken(e[i],i),r.info(`${i} revoked successfully`),i!=="access_token"&&(e[i]=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(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),K.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const 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()}};const ke=e=>{const t=e?.split(".")[1];if(!t)return null;const r=t.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(window.atob(r).split("").map(function(i){return"%"+("00"+i.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(s)},Fe=e=>e===null?!1:!!e.access_token&&!e.expired,ze=()=>{try{return window.location!==window.parent.location}catch{return!0}},$e=()=>{if(!ze()||!document.referrer)return!1;try{const{host:e}=new URL(document.referrer);return[/^uvadlo-.*\.instructure\.com$/,/^uvadlo-.*\.test\.instructure\.com$/,/^canvas\.instructure\.com$/].some(t=>t.test(e))}catch{return!1}},Ee=e=>{const t=ke(e);if(!t)throw new Error("Error while logging in");const r=new K({access_token:e,token_type:"Bearer",profile:{iss:t.iss??"",sub:"",aud:"",exp:t.exp??0,iat:t.iat??0}});return r.expires_at=t.exp,{user:r,target:t.target,locale:t.locale}},Je=()=>localStorage.getItem("canvas-token"),er=e=>{localStorage.setItem("canvas-token",e)},G=e=>e?Object.assign({},e):null,tr=e=>(ke(e?.access_token??"")?.impersonatedid??"")!=="",rr=e=>e.user,sr=e=>e.isLoading?"pending":"fulfilled",ir=e=>e.providerType,nr=e=>e.isAuthenticated,Ke={user:null,providerType:null,isAuthenticated:!1,isLoading:!0,isLoggingOut:!1},or=["auth/INITIALIZED","auth/USER_LOADED","auth/LOGOUT","auth/USER_UNLOADED","auth/LOGGING_OUT"];function ar(e){return or.includes(e.type)}function Ge(e=Ke,t){if(!ar(t))return e;switch(t.type){case"auth/INITIALIZED":case"auth/USER_LOADED":return{...e,user:t.user,providerType:t.providerType,isAuthenticated:t.user?!!t.user.access_token&&!t.user.expired:!1,isLoading:!1,isLoggingOut:!1};case"auth/LOGGING_OUT":return{...e,isLoggingOut:!0};case"auth/LOGOUT":case"auth/USER_UNLOADED":return{...e,user:null,isAuthenticated:!1,isLoggingOut:!0};default:return e}}var le={exports:{}},Z={};var Ye;function cr(){if(Ye)return Z;Ye=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(s,i,n){var o=null;if(n!==void 0&&(o=""+n),i.key!==void 0&&(o=""+i.key),"key"in i){n={};for(var l in i)l!=="key"&&(n[l]=i[l])}else n=i;return i=n.ref,{$$typeof:e,type:s,key:o,ref:i!==void 0?i:null,props:n}}return Z.Fragment=t,Z.jsx=r,Z.jsxs=r,Z}var Q={};var Ve;function lr(){return Ve||(Ve=1,process.env.NODE_ENV!=="production"&&(function(){function e(c){if(c==null)return null;if(typeof c=="function")return c.$$typeof===P?null:c.displayName||c.name||null;if(typeof c=="string")return c;switch(c){case S:return"Fragment";case a:return"Profiler";case R:return"StrictMode";case E:return"Suspense";case T:return"SuspenseList";case M:return"Activity"}if(typeof c=="object")switch(typeof c.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),c.$$typeof){case p:return"Portal";case f:return c.displayName||"Context";case d:return(c._context.displayName||"Context")+".Consumer";case v:var y=c.render;return c=c.displayName,c||(c=y.displayName||y.name||"",c=c!==""?"ForwardRef("+c+")":"ForwardRef"),c;case x:return y=c.displayName||null,y!==null?y:e(c.type)||"Memo";case C:y=c._payload,c=c._init;try{return e(c(y))}catch{}}return null}function t(c){return""+c}function r(c){try{t(c);var y=!1}catch{y=!0}if(y){y=console;var U=y.error,A=typeof Symbol=="function"&&Symbol.toStringTag&&c[Symbol.toStringTag]||c.constructor.name||"Object";return U.call(y,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",A),t(c)}}function s(c){if(c===S)return"<>";if(typeof c=="object"&&c!==null&&c.$$typeof===C)return"<...>";try{var y=e(c);return y?"<"+y+">":"<...>"}catch{return"<...>"}}function i(){var c=q.A;return c===null?null:c.getOwner()}function n(){return Error("react-stack-top-frame")}function o(c){if(B.call(c,"key")){var y=Object.getOwnPropertyDescriptor(c,"key").get;if(y&&y.isReactWarning)return!1}return c.key!==void 0}function l(c,y){function U(){Y||(Y=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",y))}U.isReactWarning=!0,Object.defineProperty(c,"key",{get:U,configurable:!0})}function u(){var c=e(this.type);return $[c]||($[c]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),c=this.props.ref,c!==void 0?c:null}function g(c,y,U,A,ue,Re){var O=U.ref;return c={$$typeof:k,type:c,key:y,props:U,_owner:A},(O!==void 0?O:null)!==null?Object.defineProperty(c,"ref",{enumerable:!1,get:u}):Object.defineProperty(c,"ref",{enumerable:!1,value:null}),c._store={},Object.defineProperty(c._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(c,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(c,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:ue}),Object.defineProperty(c,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Re}),Object.freeze&&(Object.freeze(c.props),Object.freeze(c)),c}function _(c,y,U,A,ue,Re){var O=y.children;if(O!==void 0)if(A)if(ee(O)){for(A=0;A<O.length;A++)h(O[A]);Object.freeze&&Object.freeze(O)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else h(O);if(B.call(y,"key")){O=e(c);var X=Object.keys(y).filter(function(_r){return _r!=="key"});A=0<X.length?"{key: someKey, "+X.join(": ..., ")+": ...}":"{key: someKey}",et[O+A]||(X=0<X.length?"{"+X.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
2
|
+
let props = %s;
|
|
3
|
+
<%s {...props} />
|
|
4
|
+
React keys must be passed directly to JSX without using spread:
|
|
5
|
+
let props = %s;
|
|
6
|
+
<%s key={someKey} {...props} />`,A,O,X,O),et[O+A]=!0)}if(O=null,U!==void 0&&(r(U),O=""+U),o(y)&&(r(y.key),O=""+y.key),"key"in y){U={};for(var xe in y)xe!=="key"&&(U[xe]=y[xe])}else U=y;return O&&l(U,typeof c=="function"?c.displayName||c.name||"Unknown":c),g(c,O,U,i(),ue,Re)}function h(c){b(c)?c._store&&(c._store.validated=1):typeof c=="object"&&c!==null&&c.$$typeof===C&&(c._payload.status==="fulfilled"?b(c._payload.value)&&c._payload.value._store&&(c._payload.value._store.validated=1):c._store&&(c._store.validated=1))}function b(c){return typeof c=="object"&&c!==null&&c.$$typeof===k}var w=N,k=Symbol.for("react.transitional.element"),p=Symbol.for("react.portal"),S=Symbol.for("react.fragment"),R=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),d=Symbol.for("react.consumer"),f=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),E=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),x=Symbol.for("react.memo"),C=Symbol.for("react.lazy"),M=Symbol.for("react.activity"),P=Symbol.for("react.client.reference"),q=w.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,B=Object.prototype.hasOwnProperty,ee=Array.isArray,z=console.createTask?console.createTask:function(){return null};w={react_stack_bottom_frame:function(c){return c()}};var Y,$={},V=w.react_stack_bottom_frame.bind(w,n)(),Qe=z(s(n)),et={};Q.Fragment=S,Q.jsx=function(c,y,U){var A=1e4>q.recentlyCreatedOwnerStacks++;return _(c,y,U,!1,A?Error("react-stack-top-frame"):V,A?z(s(c)):Qe)},Q.jsxs=function(c,y,U){var A=1e4>q.recentlyCreatedOwnerStacks++;return _(c,y,U,!0,A?Error("react-stack-top-frame"):V,A?z(s(c)):Qe)}})()),Q}var Xe;function ur(){return Xe||(Xe=1,process.env.NODE_ENV==="production"?le.exports=cr():le.exports=lr()),le.exports}var dr=ur();const Te=N.createContext(void 0);Te.displayName="AuthContext";class Ze{initialized=!1;loginInProgress=!1;logoutUri;updateState;userManager;constructor(t){this.logoutUri=t.logoutUri,this.userManager=new Qt({authority:t.authority,automaticSilentRenew:!1,client_id:t.clientId,redirect_uri:t.redirectUri,response_type:"code",scope:"openid profile",userStore:new ve({store:localStorage})})}async initialize(t,r){if(!this.initialized)if(this.updateState=t,this.initEvents(r),this.initialized=!0,$e()){const s=this.initCanvasUser();this.updateState({type:"auth/INITIALIZED",user:s,providerType:"canvas"}),s&&r.onUserLoaded?.(s)}else{const[s]=await Promise.all([this.userManager.getUser(),this.userManager.clearStaleState()]),i=s&&!s.expired?s:null;this.updateState({type:"auth/INITIALIZED",user:G(i),providerType:"surf"}),i&&r.onUserLoaded?.(i)}}surfStartLogin=async t=>{if(!this.loginInProgress){this.loginInProgress=!0;try{await this.userManager.signinRedirect({state:t})}catch(r){throw this.loginInProgress=!1,r}}};surfCompleteLogin=()=>this.userManager.signinRedirectCallback();canvasCompleteLogin=t=>{const r=Ee(t);return this.updateState?.({type:"auth/USER_LOADED",user:G(r.user),providerType:"canvas"}),r};surfRenewLogin=async t=>{await this.userManager.removeUser(),await this.surfStartLogin(t)};surfLogout=async()=>{this.updateState?.({type:"auth/LOGGING_OUT"}),await this.userManager.removeUser(),this.logoutUri&&(window.location.href=this.logoutUri)};impersonateSurfUser=async t=>{const r=await this.userManager.getUser();if(!r)return;const s=new K({...r,access_token:t});await this.userManager.storeUser(s),this.updateState?.({type:"auth/USER_LOADED",user:G(s),providerType:"surf"})};initCanvasUser=()=>{const t=Je();if(!t)return null;const{user:r}=Ee(t);return r.expired?null:G(r)};initEvents(t){t.onAccessTokenExpired&&this.userManager.events.addAccessTokenExpired(t.onAccessTokenExpired),t.onAccessTokenExpiring&&this.userManager.events.addAccessTokenExpiring(t.onAccessTokenExpiring),t.onSilentRenewError&&this.userManager.events.addSilentRenewError(t.onSilentRenewError),this.userManager.events.addUserLoaded(r=>{Fe(r)&&this.updateState?.({type:"auth/USER_LOADED",user:G(r),providerType:"surf"}),t?.onUserLoaded?.(r)}),t.onUserSessionChanged&&this.userManager.events.addUserSessionChanged(t.onUserSessionChanged),t.onUserSignedIn&&this.userManager.events.addUserSignedIn(t.onUserSignedIn),t.onUserSignedOut&&this.userManager.events.addUserSignedOut(t.onUserSignedOut),this.userManager.events.addUserUnloaded(()=>{this.updateState?.({type:"auth/USER_UNLOADED"}),t?.onUserUnloaded?.()})}}const hr=e=>{const[t]=N.useState(()=>new Ze(e.config)),[r,s]=N.useReducer(Ge,Ke),i=N.useRef(!1);N.useEffect(()=>{!t||i.current||(i.current=!0,(async()=>await t.initialize(o=>s(o),e.events))())},[t,e.events]);const n=N.useMemo(()=>({...r,surfStartLogin:t.surfStartLogin,surfCompleteLogin:t.surfCompleteLogin,canvasCompleteLogin:t.canvasCompleteLogin,surfRenewLogin:t.surfRenewLogin,surfLogout:t.surfLogout,impersonateSurfUser:t.impersonateSurfUser}),[r,t]);return dr.jsx(Te.Provider,{value:n,children:e.children})},gr=()=>{const e=N.useContext(Te);if(!e)throw new Error("useAuth must be used within an <AuthProvider>.");return e};I.AuthProvider=hr,I.AuthService=Ze,I.authReducer=Ge,I.convertUserToObject=G,I.getCanvasTokenFromLocalStorage=Je,I.getDataFromToken=ke,I.getUserAndMetadataForCanvasToken=Ee,I.isEmbedded=ze,I.isEmbeddedInCanvas=$e,I.isImpersonating=tr,I.isUserAuthenticated=Fe,I.selectAuthProviderType=ir,I.selectAuthStatus=sr,I.selectAuthUser=rr,I.selectIsAuthenticated=nr,I.setCanvasTokenInLocalStorage=er,I.useAuth=gr,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})}));
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { getDataFromToken, isUserAuthenticated, isEmbedded, isEmbeddedInCanvas, getUserAndMetadataForCanvasToken, getCanvasTokenFromLocalStorage, setCanvasTokenInLocalStorage, convertUserToObject, isImpersonating, } from './Auth.helpers';
|
|
2
|
+
export { selectAuthUser, selectAuthStatus, selectAuthProviderType, selectIsAuthenticated, } from './Auth.selectors';
|
|
3
|
+
export { authReducer } from './Auth.reducer';
|
|
4
|
+
export type { AuthState } from './Auth.state';
|
|
5
|
+
export type { AuthEventCallbacks, CustomUserState, ProviderType } from './Auth.types';
|
|
6
|
+
export { AuthProvider } from './AuthProvider';
|
|
7
|
+
export { default as AuthService } from './AuthService';
|
|
8
|
+
export { useAuth } from './useAuth';
|
package/package.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@uva-fnwi/datanose-core",
|
|
3
|
+
"description": "Shared OIDC authentication library for DataNose applications",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"version": "1.0.0",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "dist/core.umd.js",
|
|
9
|
+
"module": "dist/core.es.js",
|
|
10
|
+
"types": "dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/core.es.js",
|
|
15
|
+
"require": "./dist/core.umd.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"keywords": [
|
|
22
|
+
"oidc",
|
|
23
|
+
"auth",
|
|
24
|
+
"react",
|
|
25
|
+
"datanose"
|
|
26
|
+
],
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "https://github.com/UvA-FNWI/workflow-ui",
|
|
30
|
+
"directory": "packages/core"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public",
|
|
34
|
+
"registry": "https://registry.npmjs.org"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"react": "^19",
|
|
38
|
+
"react-dom": "^19"
|
|
39
|
+
},
|
|
40
|
+
"peerDependenciesMeta": {},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@eslint/js": "^9.39.1",
|
|
43
|
+
"@types/node": "^24.10.0",
|
|
44
|
+
"@types/react": "^19.2.2",
|
|
45
|
+
"@types/react-dom": "^19.2.2",
|
|
46
|
+
"@vitejs/plugin-react": "^5.1.0",
|
|
47
|
+
"@vitest/browser": "^4.0.18",
|
|
48
|
+
"@vitest/coverage-v8": "^4.0.18",
|
|
49
|
+
"eslint": "^9.39.1",
|
|
50
|
+
"eslint-plugin-react-hooks": "^5.2.0",
|
|
51
|
+
"eslint-plugin-react-refresh": "^0.4.24",
|
|
52
|
+
"globals": "^16.5.0",
|
|
53
|
+
"jsdom": "^27.0.1",
|
|
54
|
+
"prettier": "^3.6.2",
|
|
55
|
+
"typescript": "~5.9.3",
|
|
56
|
+
"typescript-eslint": "^8.46.3",
|
|
57
|
+
"vite": "^7.2.2",
|
|
58
|
+
"oidc-client-ts": "^2.4.0",
|
|
59
|
+
"vite-plugin-dts": "^4.5.4",
|
|
60
|
+
"vitest": "^4.0.4"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"dev": "vite build --watch",
|
|
64
|
+
"dev:local": "vite build --watch",
|
|
65
|
+
"build": "vite build",
|
|
66
|
+
"test": "vitest run",
|
|
67
|
+
"test:watch": "vitest",
|
|
68
|
+
"format": "prettier --write \"src/**/*.{ts,tsx,js,jsx,json,css,scss,md}\"",
|
|
69
|
+
"format:check": "prettier --check \"src/**/*.{ts,tsx,js,jsx,json,css,scss,md}\"",
|
|
70
|
+
"lint": "eslint src --ext .ts,.tsx",
|
|
71
|
+
"lint:fix": "eslint src --ext .ts,.tsx --fix"
|
|
72
|
+
}
|
|
73
|
+
}
|