@axa-fr/oidc-client 7.4.0 → 7.5.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 +14 -2
- package/dist/crypto.d.ts +1 -0
- package/dist/index.js +809 -639
- package/dist/index.umd.cjs +2 -2
- package/dist/initSession.d.ts +6 -2
- package/dist/initWorker.d.ts +6 -2
- package/dist/jwt.d.ts +6 -0
- package/dist/login.d.ts +1 -1
- package/dist/oidc.d.ts +1 -0
- package/dist/oidcClient.d.ts +1 -0
- package/dist/requests.d.ts +9 -9
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +2 -2
- package/src/crypto.ts +11 -6
- package/src/initSession.ts +29 -9
- package/src/initWorker.ts +31 -9
- package/src/jwt.ts +248 -0
- package/src/login.ts +61 -21
- package/src/oidc.ts +68 -34
- package/src/oidcClient.ts +4 -0
- package/src/parseTokens.ts +24 -15
- package/src/requests.ts +43 -10
- package/src/types.ts +1 -0
- package/src/version.ts +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(b,j){typeof exports=="object"&&typeof module<"u"?j(exports):typeof define=="function"&&define.amd?define(["exports"],j):(b=typeof globalThis<"u"?globalThis:b||self,j(b["oidc-client"]={}))})(this,function(b){"use strict";const F=console;class ke{constructor(e,t,s,i=2e3,o=!0){this._callback=e,this._client_id=t,this._url=s,this._interval=i||2e3,this._stopOnError=o;const r=s.indexOf("/",s.indexOf("//")+2);this._frame_origin=s.substr(0,r),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=s}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1)})}_message(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data==="error"?(F.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):e.data==="changed"?(F.debug(e),F.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):F.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))}start(e){F.debug("CheckSessionIFrame.start :"+e),this.stop();const t=()=>{this._frame.contentWindow.postMessage(this._client_id+" "+e,this._frame_origin)};t(),this._timer=window.setInterval(t,this._interval)}stop(){this._timer&&(F.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)}}const m={service_worker_not_supported_by_browser:"service_worker_not_supported_by_browser",token_aquired:"token_aquired",logout_from_another_tab:"logout_from_another_tab",logout_from_same_tab:"logout_from_same_tab",token_renewed:"token_renewed",token_timer:"token_timer",loginAsync_begin:"loginAsync_begin",loginAsync_error:"loginAsync_error",loginCallbackAsync_begin:"loginCallbackAsync_begin",loginCallbackAsync_end:"loginCallbackAsync_end",loginCallbackAsync_error:"loginCallbackAsync_error",refreshTokensAsync_begin:"refreshTokensAsync_begin",refreshTokensAsync:"refreshTokensAsync",refreshTokensAsync_end:"refreshTokensAsync_end",refreshTokensAsync_error:"refreshTokensAsync_error",refreshTokensAsync_silent_error:"refreshTokensAsync_silent_error",tryKeepExistingSessionAsync_begin:"tryKeepExistingSessionAsync_begin",tryKeepExistingSessionAsync_end:"tryKeepExistingSessionAsync_end",tryKeepExistingSessionAsync_error:"tryKeepExistingSessionAsync_error",silentLoginAsync_begin:"silentLoginAsync_begin",silentLoginAsync:"silentLoginAsync",silentLoginAsync_end:"silentLoginAsync_end",silentLoginAsync_error:"silentLoginAsync_error",syncTokensAsync_begin:"syncTokensAsync_begin",syncTokensAsync_end:"syncTokensAsync_end",syncTokensAsync_error:"syncTokensAsync_error"},I=(n,e=sessionStorage)=>{const t=k=>(e[`oidc.${n}`]=JSON.stringify({tokens:null,status:k}),Promise.resolve()),s=async()=>{if(!e[`oidc.${n}`])return e[`oidc.${n}`]=JSON.stringify({tokens:null,status:null}),{tokens:null,status:null};const k=JSON.parse(e[`oidc.${n}`]);return Promise.resolve({tokens:k.tokens,status:k.status})},i=k=>{e[`oidc.${n}`]=JSON.stringify({tokens:k})},o=async k=>{e[`oidc.session_state.${n}`]=k},r=async()=>e[`oidc.session_state.${n}`],l=k=>{localStorage[`oidc.nonce.${n}`]=k.nonce},c=async()=>({nonce:localStorage[`oidc.nonce.${n}`]}),h=()=>e[`oidc.${n}`]?JSON.stringify({tokens:JSON.parse(e[`oidc.${n}`]).tokens}):null;let a=null;return{clearAsync:t,initAsync:s,setTokens:i,getTokens:h,setSessionStateAsync:o,getSessionStateAsync:r,setNonceAsync:l,getNonceAsync:c,setLoginParams:(k,w)=>{a=w,e[`oidc.login.${k}`]=JSON.stringify(w)},getLoginParams:k=>{const w=e[`oidc.login.${k}`];return a||(a=JSON.parse(w)),a},getStateAsync:async()=>e[`oidc.state.${n}`],setStateAsync:async k=>{e[`oidc.state.${n}`]=k},getCodeVerifierAsync:async()=>e[`oidc.code_verifier.${n}`],setCodeVerifierAsync:async k=>{e[`oidc.code_verifier.${n}`]=k}}},me=n=>decodeURIComponent(Array.prototype.map.call(atob(n),e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join("")),pe=n=>JSON.parse(me(n.split(".")[1].replace("-","+").replace("_","/"))),te=n=>{try{return n&&we(n,".")===2?pe(n):null}catch(e){console.warn(e)}return null},we=(n,e)=>n.split(e).length-1,q={access_token_or_id_token_invalid:"access_token_or_id_token_invalid",access_token_invalid:"access_token_invalid",id_token_invalid:"id_token_invalid"},se=(n,e=null,t)=>{if(!n)return null;let s;const i=typeof n.expiresIn=="string"?parseInt(n.expiresIn,10):n.expiresIn;if(n.issuedAt)typeof n.issuedAt=="string"&&(n.issuedAt=parseInt(n.issuedAt,10));else{const a=new Date().getTime()/1e3;n.issuedAt=a}n.accessTokenPayload!==void 0?s=n.accessTokenPayload:s=te(n.accessToken);const o=n.idTokenPayload?n.idTokenPayload:te(n.idToken),r=o&&o.exp?o.exp:Number.MAX_VALUE,l=s&&s.exp?s.exp:n.issuedAt+i;let c;n.expiresAt?c=n.expiresAt:t===q.access_token_invalid?c=l:t===q.id_token_invalid?c=r:c=r<l?r:l;const h={...n,idTokenPayload:o,accessTokenPayload:s,expiresAt:c};if(e!=null&&"refreshToken"in e&&!("refreshToken"in n)){const a=e.refreshToken;return{...h,refreshToken:a}}return h},H=(n,e,t)=>{if(!n)return null;if(!n.issued_at){const i=new Date().getTime()/1e3;n.issued_at=i}const s={accessToken:n.access_token,expiresIn:n.expires_in,idToken:n.id_token,scope:n.scope,tokenType:n.token_type,issuedAt:n.issued_at};return"refresh_token"in n&&(s.refreshToken=n.refresh_token),n.accessTokenPayload!==void 0&&(s.accessTokenPayload=n.accessTokenPayload),n.idTokenPayload!==void 0&&(s.idTokenPayload=n.idTokenPayload),n.fromServiceWorker!==void 0&&(s.fromServiceWorker=n.fromServiceWorker),se(s,e,t)},M=(n,e)=>{const t=new Date().getTime()/1e3;return Math.round(e-n-t)},X=n=>n?M(0,n.expiresAt)>0:!1,Ae=async(n,e=200,t=50)=>{let s=t;if(!n.tokens)return null;for(;!X(n.tokens)&&s>0;)await x(e),s=s-1;return{isTokensValid:X(n.tokens),tokens:n.tokens,numberWaited:s-t}},oe=(n,e,t)=>{if(n.idTokenPayload){const s=n.idTokenPayload;if(t.issuer!==s.iss)return{isValid:!1,reason:`Issuer does not match (oidcServerConfiguration issuer) ${t.issuer} !== (idTokenPayload issuer) ${s.iss}`};const i=new Date().getTime()/1e3;if(s.exp&&s.exp<i)return{isValid:!1,reason:`Token expired (idTokenPayload exp) ${s.exp} < (currentTimeUnixSecond) ${i}`};const o=60*60*24*7;if(s.iat&&s.iat+o<i)return{isValid:!1,reason:`Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${s.iat+o} < (currentTimeUnixSecond) ${i}`};if(s.nonce&&s.nonce!==e)return{isValid:!1,reason:`Nonce does not match (idTokenPayload nonce) ${s.nonce} !== (nonce) ${e}`}}return{isValid:!0,reason:""}},V=function(){const n=function(){let c,h;const a=(function(){const f={},u={setTimeout:function(d,g,k){f[g]=setTimeout(function(){d.postMessage(g),f[g]=null},k)},setInterval:function(d,g,k){f[g]=setInterval(function(){d.postMessage(g)},k)},clearTimeout:function(d,g){clearTimeout(f[g]),f[g]=null},clearInterval:function(d,g){clearInterval(f[g]),f[g]=null}};function y(d,g){const k=g.data[0],w=g.data[1],S=g.data[2];u[k]&&u[k](d,w,S)}this.onmessage=function(d){y(self,d)},this.onconnect=function(d){const g=d.ports[0];g.onmessage=function(k){y(g,k)}}}).toString();try{const f=new Blob(["(",a,")()"],{type:"application/javascript"});h=URL.createObjectURL(f)}catch{return null}const _=typeof process>"u";try{if(SharedWorker)return c=new SharedWorker(h),c.port}catch{_&&console.warn("SharedWorker not available")}try{if(Worker)return c=new Worker(h),c}catch{_&&console.warn("Worker not available")}return null}();if(!n){const c=typeof window>"u"?global:window;return{setTimeout:setTimeout.bind(c),clearTimeout:clearTimeout.bind(c),setInterval:setInterval.bind(c),clearInterval:clearInterval.bind(c)}}const e=function(){let c=0;return function(){return c++,c}}(),t={},s={};n.onmessage=function(c){const h=c.data,a=t[h];if(a){a(),t[h]=null;return}const _=s[h];_&&_()};function i(c,h){const a=e();return n.postMessage(["setTimeout",a,h]),t[a]=c,a}function o(c){n.postMessage(["clearTimeout",c]),t[c]=null}function r(c,h){const a=e();return n.postMessage(["setInterval",a,h]),s[a]=c,a}function l(c){n.postMessage(["clearInterval",c]),s[c]=null}return{setTimeout:i,clearTimeout:o,setInterval:r,clearInterval:l}}(),ie="7.4.0",re=n=>{const e=n.appVersion,t=n.userAgent,s="-";let i=s;const o=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Chrome OS",r:/CrOS/},{s:"Linux",r:/(Linux|X11(?!.*CrOS))/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(const l in o){const c=o[l];if(c.r.test(t)){i=c.s;break}}let r=s;switch(/Windows/.test(i)&&(r=/Windows (.*)/.exec(i)[1],i="Windows"),i){case"Mac OS":case"Mac OS X":case"Android":r=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(t)[1];break;case"iOS":{const l=/OS (\d+)_(\d+)_?(\d+)?/.exec(e);r=l[1]+"."+l[2]+"."+(parseInt(l[3])|0);break}}return{os:i,osVersion:r}};function ve(){const n=navigator.userAgent;let e,t=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(t[1]))return e=/\brv[ :]+(\d+)/g.exec(n)||[],{name:"ie",version:e[1]||""};if(t[1]==="Chrome"&&(e=n.match(/\bOPR|Edge\/(\d+)/),e!=null)){let s=e[1];if(!s){const i=n.split(e[0]+"/");i.length>1&&(s=i[1])}return{name:"opera",version:s}}return t=t[2]?[t[1],t[2]]:[navigator.appName,navigator.appVersion,"-?"],(e=n.match(/version\/(\d+)/i))!=null&&t.splice(1,1,e[1]),{name:t[0].toLowerCase(),version:t[1]}}let ae=null;const x=n=>new Promise(e=>V.setTimeout(e,n));let G;const ce=()=>{try{const e=re(navigator).os==="Android"?240:150;G=new AbortController,fetch(`/OidcKeepAliveServiceWorker.json?minSleepSeconds=${e}`,{signal:G.signal}).catch(s=>{console.log(s)}),x(e*1e3).then(ce)}catch(n){console.log(n)}},le=()=>{G&&G.abort()},Se=()=>fetch("/OidcKeepAliveServiceWorker.json",{headers:{"oidc-vanilla":"true"}}).then(n=>n.statusText==="oidc-service-worker").catch(n=>{console.log(n)}),Te=n=>!!(n.os==="iOS"&&n.osVersion.startsWith("12")||n.os==="Mac OS X"&&n.osVersion.startsWith("10_15_6")),E=n=>e=>new Promise(function(t,s){const i=new MessageChannel;i.port1.onmessage=function(o){o.data&&o.data.error?s(o.data.error):t(o.data)},n.active.postMessage(e,[i.port2])}),O=async(n,e)=>{if(typeof window>"u"||typeof navigator>"u"||!navigator.serviceWorker||!n)return null;const{name:t,version:s}=ve();if(t==="chrome"&&parseInt(s)<=70||t==="opera"&&(!s||parseInt(s.split(".")[0])<80)||t==="ie")return null;const i=re(navigator);if(Te(i))return null;const o=await navigator.serviceWorker.register(n);try{await navigator.serviceWorker.ready}catch{return null}const r=async p=>E(o)({type:"clear",data:{status:p},configurationName:e}),l=async(p,A,T)=>{const v=await E(o)({type:"init",data:{oidcServerConfiguration:p,where:A,oidcConfiguration:{token_renew_mode:T.token_renew_mode,service_worker_convert_all_requests_to_cors:T.service_worker_convert_all_requests_to_cors}},configurationName:e}),N=v.version;if(N!==ie)if(console.warn(`Service worker ${N} version mismatch with js client version ${ie}, unregistering and reloading`),T.service_worker_update_require_callback)await T.service_worker_update_require_callback(o,le);else{le(),await o.update();const W=await o.unregister();console.log(`Service worker unregistering ${W}`),await x(2e3),window.location.reload()}return{tokens:H(v.tokens,null,T.token_renew_mode),status:v.status}},c=()=>{ae==null&&(ae="not_null",ce())},h=p=>E(o)({type:"setSessionState",data:{sessionState:p},configurationName:e}),a=async()=>(await E(o)({type:"getSessionState",data:null,configurationName:e})).sessionState,_=p=>(sessionStorage["oidc.nonce"]=p.nonce,E(o)({type:"setNonce",data:{nonce:p},configurationName:e})),f=async()=>{let A=(await E(o)({type:"getNonce",data:null,configurationName:e})).nonce;return A||(A=sessionStorage["oidc.nonce"],console.warn("nonce not found in service worker, using sessionStorage")),{nonce:A}};let u=null;return{clearAsync:r,initAsync:l,startKeepAliveServiceWorker:c,isServiceWorkerProxyActiveAsync:Se,setSessionStateAsync:h,getSessionStateAsync:a,setNonceAsync:_,getNonceAsync:f,setLoginParams:(p,A)=>{u=A,localStorage[`oidc.login.${p}`]=JSON.stringify(A)},getLoginParams:p=>{const A=localStorage[`oidc.login.${p}`];return u||(u=JSON.parse(A)),u},getStateAsync:async()=>{let A=(await E(o)({type:"getState",data:null,configurationName:e})).state;return A||(A=sessionStorage[`oidc.state.${e}`],console.warn("state not found in service worker, using sessionStorage")),A},setStateAsync:async p=>(sessionStorage[`oidc.state.${e}`]=p,E(o)({type:"setState",data:{state:p},configurationName:e})),getCodeVerifierAsync:async()=>{let A=(await E(o)({type:"getCodeVerifier",data:null,configurationName:e})).codeVerifier;return A||(A=sessionStorage[`oidc.code_verifier.${e}`],console.warn("codeVerifier not found in service worker, using sessionStorage")),A},setCodeVerifierAsync:async p=>(sessionStorage[`oidc.code_verifier.${e}`]=p,E(o)({type:"setCodeVerifier",data:{codeVerifier:p},configurationName:e}))}};async function ue(n,e,t=!1,s=null){const i=c=>{n.tokens=c},{tokens:o,status:r}=await n.synchroniseTokensAsync(e,0,t,s,i);if(await O(n.configuration.service_worker_relative_url,n.configurationName)||await I(n.configurationName,n.configuration.storage).setTokens(n.tokens),!n.tokens){await n.destroyAsync(r);return}return n.timeoutId&&(n.timeoutId=U(n,o.refreshToken,n.tokens.expiresAt,s)),n.tokens}const U=(n,e,t,s=null)=>{const i=n.configuration.refresh_time_before_tokens_expiration_in_second;return V.setTimeout(async()=>{const r={timeLeft:M(i,t)};n.publishEvent($.eventNames.token_timer,r),await ue(n,e,!1,s)},1e3)},z=(n,e,t)=>(s=null,i=null,o=null)=>{if(!e.silent_redirect_uri||!e.silent_login_uri)return Promise.resolve(null);try{t(m.silentLoginAsync_begin,{});let r="";if(i&&(s==null&&(s={}),s.state=i),o&&(s==null&&(s={}),s.scope=o),s!=null)for(const[_,f]of Object.entries(s))r===""?r=`?${encodeURIComponent(_)}=${encodeURIComponent(f)}`:r+=`&${encodeURIComponent(_)}=${encodeURIComponent(f)}`;const l=e.silent_login_uri+r,c=l.indexOf("/",l.indexOf("//")+2),h=l.substr(0,c),a=document.createElement("iframe");return a.width="0px",a.height="0px",a.id=`${n}_oidc_iframe`,a.setAttribute("src",l),document.body.appendChild(a),new Promise((_,f)=>{try{let u=!1;window.onmessage=d=>{if(d.origin===h&&d.source===a.contentWindow){const g=`${n}_oidc_tokens:`,k=`${n}_oidc_error:`,w=d.data;if(w&&typeof w=="string"&&!u){if(w.startsWith(g)){const S=JSON.parse(d.data.replace(g,""));t(m.silentLoginAsync_end,{}),a.remove(),u=!0,_(S)}else if(w.startsWith(k)){const S=JSON.parse(d.data.replace(k,""));t(m.silentLoginAsync_error,S),a.remove(),u=!0,f(new Error("oidc_"+S.error))}}}};const y=e.silent_login_timeout;setTimeout(()=>{u||(t(m.silentLoginAsync_error,{reason:"timeout"}),a.remove(),u=!0,f(new Error("timeout")))},y)}catch(u){a.remove(),t(m.silentLoginAsync_error,u),f(u)}})}catch(r){throw t(m.silentLoginAsync_error,r),r}},be=(n,e,t,s,i)=>(o=null,r=void 0)=>{o={...o};const l=(h,a,_)=>z(e,t,s.bind(i))(h,a,_);return(async()=>{i.timeoutId&&V.clearTimeout(i.timeoutId);let h;o&&"state"in o&&(h=o.state,delete o.state);try{const a=t.extras?{...t.extras,...o}:o,_=await l({...a,prompt:"none"},h,r);if(_)return i.tokens=_.tokens,s(m.token_aquired,{}),i.timeoutId=U(i,i.tokens.refreshToken,i.tokens.expiresAt,o),{}}catch(a){return a}})()},Ee=(n,e,t)=>(s,i,o,r=!1)=>{const l=(c,h=void 0,a=void 0)=>z(n.configurationName,t,n.publishEvent.bind(n))(c,h,a);return new Promise((c,h)=>{if(t.silent_login_uri&&t.silent_redirect_uri&&t.monitor_session&&s&&o&&!r){const a=()=>{n.checkSessionIFrame.stop();const _=n.tokens;if(_===null)return;const f=_.idToken,u=_.idTokenPayload;return l({prompt:"none",id_token_hint:f,scope:t.scope||"openid"}).then(y=>{const d=y.tokens.idTokenPayload;if(u.sub===d.sub){const g=y.sessionState;n.checkSessionIFrame.start(y.sessionState),u.sid===d.sid?console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",g):console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",g)}else console.debug("SessionMonitor._callback: Different subject signed into OP:",d.sub)}).catch(async y=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",y);for(const[d,g]of Object.entries(e))await g.logoutOtherTabAsync(t.client_id,u.sub)})};n.checkSessionIFrame=new ke(a,i,s),n.checkSessionIFrame.load().then(()=>{n.checkSessionIFrame.start(o),c(n.checkSessionIFrame)}).catch(_=>{h(_)})}else c(null)})};for(var Pe=Le,P=[],de="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",J=0,Ie=de.length;J<Ie;++J)P[J]=de[J];function Oe(n){return P[n>>18&63]+P[n>>12&63]+P[n>>6&63]+P[n&63]}function Ce(n,e,t){for(var s,i=[],o=e;o<t;o+=3)s=(n[o]<<16&16711680)+(n[o+1]<<8&65280)+(n[o+2]&255),i.push(Oe(s));return i.join("")}function Le(n){for(var e,t=n.length,s=t%3,i=[],o=16383,r=0,l=t-s;r<l;r+=o)i.push(Ce(n,r,r+o>l?l:r+o));return s===1?(e=n[t-1],i.push(P[e>>2]+P[e<<4&63]+"==")):s===2&&(e=(n[t-2]<<8)+n[t-1],i.push(P[e>>10]+P[e>>4&63]+P[e<<2&63]+"=")),i.join("")}const he=()=>{const n=typeof window<"u"&&!!window.crypto,e=n&&!!window.crypto.subtle;return{hasCrypto:n,hasSubtleCrypto:e}},Y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Ne=n=>{const e=[];for(let t=0;t<n.byteLength;t+=1){const s=n[t]%Y.length;e.push(Y[s])}return e.join("")},We=n=>Pe(new Uint8Array(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),Q=n=>{const e=new Uint8Array(n),{hasCrypto:t}=he();if(t)window.crypto.getRandomValues(e);else for(let s=0;s<n;s+=1)e[s]=Math.random()*Y.length|0;return Ne(e)};function xe(n){const e=new ArrayBuffer(n.length),t=new Uint8Array(e);for(let s=0;s<n.length;s++)t[s]=n.charCodeAt(s);return t}const $e=n=>{if(n.length<43||n.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:e}=he();return e?new Promise((t,s)=>{crypto.subtle.digest("SHA-256",xe(n)).then(i=>t(We(new Uint8Array(i))),i=>s(i))}):Promise.reject(new Error("window.crypto.subtle is unavailable."))},R={},Fe=(n,e=window.sessionStorage,t)=>{if(!R[n]&&e){const i=e.getItem(n);i&&(R[n]=JSON.parse(i))}const s=1e3*t;return R[n]&&R[n].timestamp+s>Date.now()?R[n].result:null},Re=(n,e,t=window.sessionStorage)=>{const s=Date.now();R[n]={result:e,timestamp:s},t&&t.setItem(n,JSON.stringify({result:e,timestamp:s}))},De=60*60,Me=n=>async(e,t=De,s=window.sessionStorage,i=1e4)=>{const o=`${e}/.well-known/openid-configuration`,r=`oidc.server:${e}`,l=Fe(r,s,t);if(l)return new ee(l);const c=await K(n)(o,{},i);if(c.status!==200)return null;const h=await c.json();return Re(r,h,s),new ee(h)},K=n=>async(e,t={},s=1e4,i=0)=>{let o;try{const r=new AbortController;setTimeout(()=>r.abort(),s),o=await n(e,{...t,signal:r.signal})}catch(r){if(r.name==="AbortError"||r.message==="Network request failed"){if(i<=1)return await K(n)(e,t,s,i+1);throw r}else throw console.error(r.message),r}return o},Z={refresh_token:"refresh_token",access_token:"access_token"},_e=n=>async(e,t,s=Z.refresh_token,i,o=1e4)=>{const r={token:t,token_type_hint:s,client_id:i},l=[];for(const a in r){const _=encodeURIComponent(a),f=encodeURIComponent(r[a]);l.push(`${_}=${f}`)}const c=l.join("&");return(await K(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:c},o)).status!==200?{success:!1}:{success:!0}},Ve=n=>async(e,t,s,i,o,r=1e4)=>{for(const[_,f]of Object.entries(s))t[_]===void 0&&(t[_]=f);const l=[];for(const _ in t){const f=encodeURIComponent(_),u=encodeURIComponent(t[_]);l.push(`${f}=${u}`)}const c=l.join("&"),h=await K(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:c},r);if(h.status!==200)return{success:!1,status:h.status};const a=await h.json();return{success:!0,data:H(a,i,o)}},Ue=n=>async(e,t)=>{t=t?{...t}:{};const s=Q(128),i=await $e(s);await n.setCodeVerifierAsync(s),await n.setStateAsync(t.state),t.code_challenge=i,t.code_challenge_method="S256";let o="";if(t)for(const[r,l]of Object.entries(t))o===""?o+="?":o+="&",o+=`${r}=${encodeURIComponent(l)}`;window.location.href=`${e}${o}`},Ke=n=>async(e,t,s,i=1e4)=>{t=t?{...t}:{},t.code_verifier=await n.getCodeVerifierAsync();const o=[];for(const h in t){const a=encodeURIComponent(h),_=encodeURIComponent(t[h]);o.push(`${a}=${_}`)}const r=o.join("&"),l=await K(fetch)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:r},i);if(await Promise.all([n.setCodeVerifierAsync(null),n.setStateAsync(null)]),l.status!==200)return{success:!1,status:l.status};const c=await l.json();return{success:!0,data:{state:t.state,tokens:H(c,null,s)}}},fe=n=>{const e=n.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!e)throw new Error("Invalid URL");let t=e[6],s=e[7];if(s){const i=s.split("?");i.length===2&&(s=i[0],t=i[1])}return t.startsWith("?")&&(t=t.slice(1)),e&&{href:n,protocol:e[1],host:e[2],hostname:e[3],port:e[4],path:e[5],search:t,hash:s}},Be=n=>{const e=fe(n);let{path:t}=e;t.endsWith("/")&&(t=t.slice(0,-1));let{hash:s}=e;return s==="#_=_"&&(s=""),s&&(t+=s),t},B=n=>{const e=fe(n),{search:t}=e;return je(t)},je=n=>{const e={};let t,s,i;const o=n.split("&");for(s=0,i=o.length;s<i;s++)t=o[s].split("="),e[decodeURIComponent(t[0])]=decodeURIComponent(t[1]);return e},qe=(n,e,t,s,i)=>(o=void 0,r=null,l=!1,c=void 0)=>{const h=r;return r={...r},(async()=>{const _=n.location,f=o||_.pathname+(_.search||"")+(_.hash||"");if("state"in r||(r.state=Q(16)),s(m.loginAsync_begin,{}),r)for(const u of Object.keys(r))u.endsWith(":token_request")&&delete r[u];try{const u=l?t.silent_redirect_uri:t.redirect_uri;c||(c=t.scope);const y=t.extras?{...t.extras,...r}:r;y.nonce||(y.nonce=Q(12));const d={nonce:y.nonce},g=await O(t.service_worker_relative_url,e),k=await i(t.authority,t.authority_configuration);let w;if(g)g.setLoginParams(e,{callbackPath:f,extras:h}),await g.initAsync(k,"loginAsync",t),await g.setNonceAsync(d),g.startKeepAliveServiceWorker(),w=g;else{const p=I(e,t.storage??sessionStorage);p.setLoginParams(e,{callbackPath:f,extras:h}),await p.setNonceAsync(d),w=p}const S={client_id:t.client_id,redirect_uri:u,scope:c,response_type:"code",...y};await Ue(w)(k.authorizationEndpoint,S)}catch(u){throw s(m.loginAsync_error,u),u}})()},Ge=n=>async(e=!1)=>{try{n.publishEvent(m.loginCallbackAsync_begin,{});const t=n.configuration,s=t.client_id,i=e?t.silent_redirect_uri:t.redirect_uri,o=t.authority,r=t.token_request_timeout,l=await n.initAsync(o,t.authority_configuration),h=B(window.location.href).session_state,a=await O(t.service_worker_relative_url,n.configurationName);let _,f,u,y;if(a)await a.initAsync(l,"loginCallbackAsync",t),await a.setSessionStateAsync(h),f=await a.getNonceAsync(),u=a.getLoginParams(n.configurationName),y=await a.getStateAsync(),a.startKeepAliveServiceWorker(),_=a;else{const v=I(n.configurationName,t.storage??sessionStorage);await v.setSessionStateAsync(h),f=await v.getNonceAsync(),u=v.getLoginParams(n.configurationName),y=await v.getStateAsync(),_=v}const d=B(window.location.toString());if(d.iss&&d.iss!==l.issuer)throw console.error(),new Error(`issuer not valid (expected: ${l.issuer}, received: ${d.iss})`);if(d.state&&d.state!==y)throw new Error(`state not valid (expected: ${y}, received: ${d.state})`);const g={code:d.code,grant_type:"authorization_code",client_id:t.client_id,redirect_uri:i},k={};if(t.token_request_extras)for(const[v,N]of Object.entries(t.token_request_extras))k[v]=N;if(u&&u.extras)for(const[v,N]of Object.entries(u.extras))v.endsWith(":token_request")&&(k[v.replace(":token_request","")]=N);const w=await Ke(_)(l.tokenEndpoint,{...g,...k},n.configuration.token_renew_mode,r);if(!w.success)throw new Error("Token request failed");let S;const p=w.data.tokens;if(a?(await a.initAsync(i,"syncTokensAsync",t),S=a.getLoginParams(n.configurationName)):S=I(n.configurationName,t.storage).getLoginParams(n.configurationName),w.data.state!==k.state)throw new Error("state is not valid");const{isValid:A,reason:T}=oe(p,f.nonce,l);if(!A)throw new Error(`Tokens are not OpenID valid, reason: ${T}`);return await n.startCheckSessionAsync(l.checkSessionIframe,s,h,e),n.publishEvent(m.loginCallbackAsync_end,{}),{tokens:p,state:"request.state",callbackPath:S.callbackPath}}catch(t){throw console.error(t),n.publishEvent(m.loginCallbackAsync_error,t),t}},ye={access_token:"access_token",refresh_token:"refresh_token"},Je=n=>async e=>{V.clearTimeout(n.timeoutId),n.timeoutId=null,n.checkSessionIFrame&&n.checkSessionIFrame.stop();const t=await O(n.configuration.service_worker_relative_url,n.configurationName);t?await t.clearAsync(e):await I(n.configurationName,n.configuration.storage).clearAsync(e),n.tokens=null,n.userInfo=null},He=(n,e,t,s,i)=>async(o=void 0,r=null)=>{const l=n.configuration,c=await n.initAsync(l.authority,l.authority_configuration);o&&typeof o!="string"&&(o=void 0,i.warn("callbackPathOrUrl path is not a string"));const h=o??location.pathname+(location.search||"")+(location.hash||"");let a=!1;o&&(a=o.includes("https://")||o.includes("http://"));const _=a?o:s.location.origin+h,f=n.tokens?n.tokens.idToken:"";try{const y=c.revocationEndpoint;if(y){const d=[],g=n.tokens.accessToken;if(g&&l.logout_tokens_to_invalidate.includes(ye.access_token)){const w=_e(t)(y,g,Z.access_token,l.client_id);d.push(w)}const k=n.tokens.refreshToken;if(k&&l.logout_tokens_to_invalidate.includes(ye.refresh_token)){const w=_e(t)(y,k,Z.refresh_token,l.client_id);d.push(w)}d.length>0&&await Promise.all(d)}}catch(y){i.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"),i.warn(y)}const u=n.tokens&&n.tokens.idTokenPayload?n.tokens.idTokenPayload.sub:null;await n.destroyAsync("LOGGED_OUT");for(const[y,d]of Object.entries(e))d!==n&&await n.logoutSameTabAsync(n.configuration.client_id,u);if(c.endSessionEndpoint){r||(r={id_token_hint:f},o!==null&&(r.post_logout_redirect_uri=_));let y="";if(r)for(const[d,g]of Object.entries(r))y===""?y+="?":y+="&",y+=`${d}=${encodeURIComponent(g)}`;s.location.href=`${c.endSessionEndpoint}${y}`}else s.location.reload()},Xe=n=>async(e=!1)=>{if(n.userInfo!=null&&!e)return n.userInfo;for(;n.tokens&&!X(n.tokens);)await x(200);if(!n.tokens)return null;const t=n.tokens.accessToken;if(!t)return null;const i=(await n.initAsync(n.configuration.authority,n.configuration.authority_configuration)).userInfoEndpoint,r=await(async l=>{const c=await fetch(i,{headers:{authorization:`Bearer ${l}`}});return c.status!==200?null:c.json()})(t);return n.userInfo=r,r},ge=()=>fetch;class ee{constructor(e){this.authorizationEndpoint=e.authorization_endpoint,this.tokenEndpoint=e.token_endpoint,this.revocationEndpoint=e.revocation_endpoint,this.userInfoEndpoint=e.userinfo_endpoint,this.checkSessionIframe=e.check_session_iframe,this.issuer=e.issuer,this.endSessionEndpoint=e.end_session_endpoint}}const C={},ze=n=>(e,t="default")=>(C[t]||(C[t]=new $(e,t,n)),C[t]),Ye=async n=>{const{parsedTokens:e,callbackPath:t}=await n.loginCallbackAsync();return n.timeoutId=U(n,e.refreshToken,e.expiresAt),{callbackPath:t}},Qe=n=>Math.floor(Math.random()*n),L=class L{constructor(e,t="default",s){this.initPromise=null,this.tryKeepExistingSessionPromise=null,this.loginPromise=null,this.loginCallbackPromise=null,this.loginCallbackWithAutoTokensRenewPromise=null,this.userInfoPromise=null,this.renewTokensPromise=null,this.logoutPromise=null;let i=e.silent_login_uri;e.silent_redirect_uri&&!e.silent_login_uri&&(i=`${e.silent_redirect_uri.replace("-callback","").replace("callback","")}-login`);let o=e.refresh_time_before_tokens_expiration_in_second??120;o>60&&(o=o-Math.floor(Math.random()*40)),e.logout_tokens_to_invalidate||(e.logout_tokens_to_invalidate=["access_token","refresh_token"]),e.authority_timeout_wellknowurl_in_millisecond||(e.authority_timeout_wellknowurl_in_millisecond=1e4),this.configuration={...e,silent_login_uri:i,monitor_session:e.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:o,silent_login_timeout:e.silent_login_timeout??12e3,token_renew_mode:e.token_renew_mode??q.access_token_or_id_token_invalid},this.getFetch=s??ge,this.configurationName=t,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,this.synchroniseTokensAsync.bind(this),this.loginCallbackWithAutoTokensRenewAsync.bind(this),this.initAsync.bind(this),this.loginCallbackAsync.bind(this),this.subscribeEvents.bind(this),this.removeEventSubscription.bind(this),this.publishEvent.bind(this),this.destroyAsync.bind(this),this.logoutAsync.bind(this),this.renewTokensAsync.bind(this),this.initAsync(this.configuration.authority,this.configuration.authority_configuration)}subscribeEvents(e){const t=Qe(9999999999999).toString();return this.events.push({id:t,func:e}),t}removeEventSubscription(e){const t=this.events.filter(s=>s.id!==e);this.events=t}publishEvent(e,t){this.events.forEach(s=>{s.func(e,t)})}static get(e="default"){const t=typeof process>"u";if(!Object.prototype.hasOwnProperty.call(C,e)&&t)throw Error(`OIDC library does seem initialized.
|
|
2
|
-
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${e}"></OidcProvider> compoment.`);return C[e]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=B(window.location.href);window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:e.session_state})}`,window.location.origin)}}_silentLoginErrorCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=B(window.location.href);window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:e.error})}`,window.location.origin)}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame()}}async initAsync(e,t){if(this.initPromise!==null)return this.initPromise;const s=async()=>{if(t!=null)return new ee({authorization_endpoint:t.authorization_endpoint,end_session_endpoint:t.end_session_endpoint,revocation_endpoint:t.revocation_endpoint,token_endpoint:t.token_endpoint,userinfo_endpoint:t.userinfo_endpoint,check_session_iframe:t.check_session_iframe,issuer:t.issuer});const o=await O(this.configuration.service_worker_relative_url,this.configurationName)?window.localStorage:null;return await Me(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,o,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=s(),this.initPromise.then(i=>(this.initPromise=null,i))}async tryKeepExistingSessionAsync(){if(this.tryKeepExistingSessionPromise!==null)return this.tryKeepExistingSessionPromise;const e=async()=>{let t;if(this.tokens!=null)return!1;this.publishEvent(m.tryKeepExistingSessionAsync_begin,{});try{const s=this.configuration,i=await this.initAsync(s.authority,s.authority_configuration);if(t=await O(s.service_worker_relative_url,this.configurationName),t){const{tokens:o}=await t.initAsync(i,"tryKeepExistingSessionAsync",s);if(o){t.startKeepAliveServiceWorker(),this.tokens=o;const r=t.getLoginParams(this.configurationName);this.timeoutId=U(this,this.tokens.refreshToken,this.tokens.expiresAt,r.extras);const l=await t.getSessionStateAsync();return await this.startCheckSessionAsync(i.check_session_iframe,s.client_id,l),this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside ServiceWorker are valid"}),!0}this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:"no exiting session found"})}else{s.service_worker_relative_url&&this.publishEvent(m.service_worker_not_supported_by_browser,{message:"service worker is not supported by this browser"});const o=I(this.configurationName,s.storage??sessionStorage),{tokens:r}=await o.initAsync();if(r){this.tokens=se(r,null,s.token_renew_mode);const l=o.getLoginParams(this.configurationName);this.timeoutId=U(this,r.refreshToken,this.tokens.expiresAt,l.extras);const c=await o.getSessionStateAsync();return await this.startCheckSessionAsync(i.check_session_iframe,s.client_id,c),this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside storage are valid"}),!0}}return this.publishEvent(m.tryKeepExistingSessionAsync_end,{success:!1,message:t?"service worker sessions not retrieved":"session storage sessions not retrieved"}),!1}catch(s){return console.error(s),t&&await t.clearAsync(),this.publishEvent(m.tryKeepExistingSessionAsync_error,"tokens inside ServiceWorker are invalid"),!1}};return this.tryKeepExistingSessionPromise=e(),this.tryKeepExistingSessionPromise.then(t=>(this.tryKeepExistingSessionPromise=null,t))}async startCheckSessionAsync(e,t,s,i=!1){await Ee(this,C,this.configuration)(e,t,s,i)}async loginAsync(e=void 0,t=null,s=!1,i=void 0,o=!1){return this.loginPromise!==null?this.loginPromise:o?be(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(t,i):(this.loginPromise=qe(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this))(e,t,s,i),this.loginPromise.then(r=>(this.loginPromise=null,r)))}async loginCallbackAsync(e=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const t=async()=>{const s=await Ge(this)(e),i=s.tokens;if(this.tokens=i,!await O(this.configuration.service_worker_relative_url,this.configurationName))I(this.configurationName,this.configuration.storage).setTokens(i);else if(!i.fromServiceWorker)throw Error("security issue, parsedTokens.fromServiceWorker is not defined");return this.publishEvent(L.eventNames.token_aquired,i),{parsedTokens:i,state:s.state,callbackPath:s.callbackPath}};return this.loginCallbackPromise=t(),this.loginCallbackPromise.then(s=>(this.loginCallbackPromise=null,s))}async synchroniseTokensAsync(e,t=0,s=!1,i=null,o){for(;!navigator.onLine&&document.hidden;)await x(1e3),this.publishEvent(m.refreshTokensAsync,{message:"wait because navigator is offline and hidden"});let r=6;for(;!navigator.onLine&&r>0;)await x(1e3),r--,this.publishEvent(m.refreshTokensAsync,{message:`wait because navigator is offline try ${r}`});let l=Math.floor(Math.random()*15)+10;for(;document.hidden&&l>0;)await x(1e3),l--,this.publishEvent(m.refreshTokensAsync,{message:`wait because navigator is hidden try ${l}`});const h=document.hidden?t:t+1;i||(i={});const a=this.configuration,_=(u,y,d=null)=>z(this.configurationName,this.configuration,this.publishEvent.bind(this))(u,y,d),f=async()=>{try{let u;const y=await O(a.service_worker_relative_url,this.configurationName);y?u=y.getLoginParams(this.configurationName):u=I(this.configurationName,a.storage).getLoginParams(this.configurationName);const d=await _({...u.extras,...i,prompt:"none"},u.state);if(d)return o(d.tokens),this.publishEvent(L.eventNames.token_renewed,{}),{tokens:d.tokens,status:"LOGGED"}}catch(u){if(console.error(u),this.publishEvent(m.refreshTokensAsync_silent_error,{message:"exceptionSilent",exception:u.message}),u&&u.message&&u.message.startsWith("oidc"))return o(null),this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent"}),{tokens:null,status:"SESSION_LOST"}}return this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token silent return"}),await this.synchroniseTokensAsync(null,h,s,i,o)};if(t>4)return o(null),this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token"}),{tokens:null,status:"SESSION_LOST"};try{const{status:u,tokens:y,nonce:d}=await this.syncTokensInfoAsync(a,this.configurationName,this.tokens,s);switch(u){case"SESSION_LOST":return o(null),this.publishEvent(m.refreshTokensAsync_error,{message:"refresh token session lost"}),{tokens:null,status:"SESSION_LOST"};case"NOT_CONNECTED":return o(null),{tokens:null,status:null};case"TOKENS_VALID":return o(y),{tokens:y,status:"LOGGED_IN"};case"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":return o(y),this.publishEvent(L.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:y,status:"LOGGED_IN"};case"LOGOUT_FROM_ANOTHER_TAB":return o(null),this.publishEvent(m.logout_from_another_tab,{status:"session syncTokensAsync"}),{tokens:null,status:"LOGGED_OUT"};case"REQUIRE_SYNC_TOKENS":return this.publishEvent(m.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:t}),await f();default:{if(this.publishEvent(m.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:t}),!e)return await f();const g=a.client_id,k=a.redirect_uri,w=a.authority,p={...a.token_request_extras?a.token_request_extras:{}};for(const[T,v]of Object.entries(i))T.endsWith(":token_request")&&(p[T.replace(":token_request","")]=v);return await(async()=>{const T={client_id:g,redirect_uri:k,grant_type:"refresh_token",refresh_token:y.refreshToken},v=await this.initAsync(w,a.authority_configuration),N=document.hidden?1e4:3e4*10,W=await Ve(this.getFetch())(v.tokenEndpoint,T,p,y,a.token_renew_mode,N);if(W.success){const{isValid:Ze,reason:en}=oe(W.data,d.nonce,v);return Ze?(o(W.data),this.publishEvent(m.refreshTokensAsync_end,{success:W.success}),this.publishEvent(L.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:W.data,status:"LOGGED_IN"}):(o(null),this.publishEvent(m.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${en}`}),{tokens:null,status:"SESSION_LOST"})}else return this.publishEvent(m.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:W}),await this.synchroniseTokensAsync(e,h,s,i,o)})()}}}catch(u){return console.error(u),this.publishEvent(m.refreshTokensAsync_silent_error,{message:"exception",exception:u.message}),this.synchroniseTokensAsync(e,h,s,i,o)}}async syncTokensInfoAsync(e,t,s,i=!1){const o={nonce:null};if(!s)return{tokens:null,status:"NOT_CONNECTED",nonce:o};let r=o;const l=await this.initAsync(e.authority,e.authority_configuration),c=await O(e.service_worker_relative_url,t);if(c){const{status:_,tokens:f}=await c.initAsync(l,"syncTokensAsync",e);if(_==="LOGGED_OUT")return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};if(_==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(!_||!f)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:o};if(f.issuedAt!==s.issuedAt){const y=M(e.refresh_time_before_tokens_expiration_in_second,f.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",d=await c.getNonceAsync();return{tokens:f,status:y,nonce:d}}r=await c.getNonceAsync()}else{const _=I(t,e.storage??sessionStorage),{tokens:f,status:u}=await _.initAsync();if(f){if(u==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(f.issuedAt!==s.issuedAt){const d=M(e.refresh_time_before_tokens_expiration_in_second,f.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",g=await _.getNonceAsync();return{tokens:f,status:d,nonce:g}}}else return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};r=await _.getNonceAsync()}const a=M(e.refresh_time_before_tokens_expiration_in_second,s.expiresAt)>0?"TOKENS_VALID":"TOKENS_INVALID";return i?{tokens:s,status:"FORCE_REFRESH",nonce:r}:{tokens:s,status:a,nonce:r}}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=Ye(this),this.loginCallbackWithAutoTokensRenewPromise.then(e=>(this.loginCallbackWithAutoTokensRenewPromise=null,e)))}userInfoAsync(e=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=Xe(this)(e),this.userInfoPromise.then(t=>(this.userInfoPromise=null,t)))}async renewTokensAsync(e=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return V.clearTimeout(this.timeoutId),this.renewTokensPromise=ue(this,this.tokens.refreshToken,!0,e),this.renewTokensPromise.then(t=>(this.renewTokensPromise=null,t))}async destroyAsync(e){return await Je(this)(e)}async logoutSameTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(this.publishEvent(m.logout_from_same_tab,{message:t}),await this.destroyAsync("LOGGED_OUT"))}async logoutOtherTabAsync(e,t){this.configuration.monitor_session&&this.configuration.client_id===e&&t&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===t&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(m.logout_from_another_tab,{message:"SessionMonitor",sub:t}))}async logoutAsync(e=void 0,t=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=He(this,C,this.getFetch(),window,console)(e,t),this.logoutPromise.then(s=>(this.logoutPromise=null,s)))}};L.getOrCreate=e=>(t,s="default")=>ze(e)(t,s),L.eventNames=m;let $=L;const D=class D{constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,t){this._oidc.publishEvent(e,t)}static get(e="default"){return new D($.get(e))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,t=null,s=!1,i=void 0,o=!1){return this._oidc.loginAsync(e,t,s,i,o)}logoutAsync(e=void 0,t=null){return this._oidc.logoutAsync(e,t)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null){return this._oidc.renewTokensAsync(e)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async getValidTokenAsync(e=200,t=50){return Ae(this._oidc,e,t)}async userInfoAsync(e=!1){return this._oidc.userInfoAsync(e)}};D.getOrCreate=e=>(t,s="default")=>new D($.getOrCreate(e)(t,s)),D.eventNames=$.eventNames;let ne=D;b.OidcClient=ne,b.TokenRenewMode=q,b.getFetchDefault=ge,b.getParseQueryStringFromLocation=B,b.getPath=Be,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(x,q){typeof exports=="object"&&typeof module<"u"?q(exports):typeof define=="function"&&define.amd?define(["exports"],q):(x=typeof globalThis<"u"?globalThis:x||self,q(x["oidc-client"]={}))})(this,function(x){"use strict";const F=console;class Ne{constructor(e,s,t,i=2e3,o=!0){this._callback=e,this._client_id=s,this._url=t,this._interval=i||2e3,this._stopOnError=o;const r=t.indexOf("/",t.indexOf("//")+2);this._frame_origin=t.substr(0,r),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.width=0,this._frame.height=0,this._frame.src=t}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1)})}_message(e){e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data==="error"?(F.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):e.data==="changed"?(F.debug(e),F.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):F.debug("CheckSessionIFrame: "+e.data+" message from check session op iframe"))}start(e){F.debug("CheckSessionIFrame.start :"+e),this.stop();const s=()=>{this._frame.contentWindow.postMessage(this._client_id+" "+e,this._frame_origin)};s(),this._timer=window.setInterval(s,this._interval)}stop(){this._timer&&(F.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)}}const k={service_worker_not_supported_by_browser:"service_worker_not_supported_by_browser",token_aquired:"token_aquired",logout_from_another_tab:"logout_from_another_tab",logout_from_same_tab:"logout_from_same_tab",token_renewed:"token_renewed",token_timer:"token_timer",loginAsync_begin:"loginAsync_begin",loginAsync_error:"loginAsync_error",loginCallbackAsync_begin:"loginCallbackAsync_begin",loginCallbackAsync_end:"loginCallbackAsync_end",loginCallbackAsync_error:"loginCallbackAsync_error",refreshTokensAsync_begin:"refreshTokensAsync_begin",refreshTokensAsync:"refreshTokensAsync",refreshTokensAsync_end:"refreshTokensAsync_end",refreshTokensAsync_error:"refreshTokensAsync_error",refreshTokensAsync_silent_error:"refreshTokensAsync_silent_error",tryKeepExistingSessionAsync_begin:"tryKeepExistingSessionAsync_begin",tryKeepExistingSessionAsync_end:"tryKeepExistingSessionAsync_end",tryKeepExistingSessionAsync_error:"tryKeepExistingSessionAsync_error",silentLoginAsync_begin:"silentLoginAsync_begin",silentLoginAsync:"silentLoginAsync",silentLoginAsync_end:"silentLoginAsync_end",silentLoginAsync_error:"silentLoginAsync_error",syncTokensAsync_begin:"syncTokensAsync_begin",syncTokensAsync_end:"syncTokensAsync_end",syncTokensAsync_error:"syncTokensAsync_error"},O=(n,e=sessionStorage)=>{const s=p=>(e[`oidc.${n}`]=JSON.stringify({tokens:null,status:p}),Promise.resolve()),t=async()=>{if(!e[`oidc.${n}`])return e[`oidc.${n}`]=JSON.stringify({tokens:null,status:null}),{tokens:null,status:null};const p=JSON.parse(e[`oidc.${n}`]);return Promise.resolve({tokens:p.tokens,status:p.status})},i=p=>{e[`oidc.${n}`]=JSON.stringify({tokens:p})},o=async p=>{e[`oidc.session_state.${n}`]=p},r=async()=>e[`oidc.session_state.${n}`],l=p=>{e[`oidc.nonce.${n}`]=p.nonce},a=p=>{e[`oidc.jwk.${n}`]=JSON.stringify(p)},f=()=>JSON.parse(e[`oidc.jwk.${n}`]),c=async()=>({nonce:e[`oidc.nonce.${n}`]}),_=p=>{e[`oidc.dpop_nonce.${n}`]=p},y=()=>e[`oidc.dpop_nonce.${n}`],u=()=>e[`oidc.${n}`]?JSON.stringify({tokens:JSON.parse(e[`oidc.${n}`]).tokens}):null;let d={};return{clearAsync:s,initAsync:t,setTokens:i,getTokens:u,setSessionStateAsync:o,getSessionStateAsync:r,setNonceAsync:l,getNonceAsync:c,setLoginParams:p=>{d[n]=p,e[`oidc.login.${n}`]=JSON.stringify(p)},getLoginParams:()=>{const p=e[`oidc.login.${n}`];return d[n]||(d[n]=JSON.parse(p)),d[n]},getStateAsync:async()=>e[`oidc.state.${n}`],setStateAsync:async p=>{e[`oidc.state.${n}`]=p},getCodeVerifierAsync:async()=>e[`oidc.code_verifier.${n}`],setCodeVerifierAsync:async p=>{e[`oidc.code_verifier.${n}`]=p},setDemonstratingProofOfPossessionNonce:_,getDemonstratingProofOfPossessionNonce:y,setDemonstratingProofOfPossessionJwkAsync:a,getDemonstratingProofOfPossessionJwkAsync:f}},Le=n=>decodeURIComponent(Array.prototype.map.call(atob(n),e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join("")),We=n=>JSON.parse(Le(n.split(".")[1].replace("-","+").replace("_","/"))),ce=n=>{try{return n&&De(n,".")===2?We(n):null}catch(e){console.warn(e)}return null},De=(n,e)=>n.split(e).length-1,G={access_token_or_id_token_invalid:"access_token_or_id_token_invalid",access_token_invalid:"access_token_invalid",id_token_invalid:"id_token_invalid"};function $e(n,e,s){if(n.issuedAt){if(typeof n.issuedAt=="string")return parseInt(n.issuedAt,10)}else return e&&e.iat?e.iat:s&&s.iat?s.iat:new Date().getTime()/1e3;return n.issuedAt}const le=(n,e=null,s)=>{if(!n)return null;let t;const i=typeof n.expiresIn=="string"?parseInt(n.expiresIn,10):n.expiresIn;n.accessTokenPayload!==void 0?t=n.accessTokenPayload:t=ce(n.accessToken);const o=n.idTokenPayload?n.idTokenPayload:ce(n.idToken),r=o&&o.exp?o.exp:Number.MAX_VALUE,l=t&&t.exp?t.exp:n.issuedAt+i;n.issuedAt=$e(n,t,o);let a;n.expiresAt?a=n.expiresAt:s===G.access_token_invalid?a=l:s===G.id_token_invalid?a=r:a=r<l?r:l;const f={...n,idTokenPayload:o,accessTokenPayload:t,expiresAt:a};if(e!=null&&"refreshToken"in e&&!("refreshToken"in n)){const c=e.refreshToken;return{...f,refreshToken:c}}return f},Q=(n,e,s)=>{if(!n)return null;if(!n.issued_at){const i=new Date().getTime()/1e3;n.issued_at=i}const t={accessToken:n.access_token,expiresIn:n.expires_in,idToken:n.id_token,scope:n.scope,tokenType:n.token_type,issuedAt:n.issued_at};return"refresh_token"in n&&(t.refreshToken=n.refresh_token),n.accessTokenPayload!==void 0&&(t.accessTokenPayload=n.accessTokenPayload),n.idTokenPayload!==void 0&&(t.idTokenPayload=n.idTokenPayload),le(t,e,s)},U=(n,e)=>{const s=new Date().getTime()/1e3,t=e-s;return Math.round(t-n)},Z=n=>n?U(0,n.expiresAt)>0:!1,Re=async(n,e=200,s=50)=>{let t=s;if(!n.tokens)return null;for(;!Z(n.tokens)&&t>0;)await $(e),t=t-1;return{isTokensValid:Z(n.tokens),tokens:n.tokens,numberWaited:t-s}},ue=(n,e,s)=>{if(n.idTokenPayload){const t=n.idTokenPayload;if(s.issuer!==t.iss)return{isValid:!1,reason:`Issuer does not match (oidcServerConfiguration issuer) ${s.issuer} !== (idTokenPayload issuer) ${t.iss}`};const i=new Date().getTime()/1e3;if(t.exp&&t.exp<i)return{isValid:!1,reason:`Token expired (idTokenPayload exp) ${t.exp} < (currentTimeUnixSecond) ${i}`};const o=60*60*24*7;if(t.iat&&t.iat+o<i)return{isValid:!1,reason:`Token is used from too long time (idTokenPayload iat + timeInSevenDays) ${t.iat+o} < (currentTimeUnixSecond) ${i}`};if(t.nonce&&t.nonce!==e)return{isValid:!1,reason:`Nonce does not match (idTokenPayload nonce) ${t.nonce} !== (nonce) ${e}`}}return{isValid:!0,reason:""}},K=function(){const n=function(){let a,f;const c=(function(){const y={},u={setTimeout:function(h,g,w){y[g]=setTimeout(function(){h.postMessage(g),y[g]=null},w)},setInterval:function(h,g,w){y[g]=setInterval(function(){h.postMessage(g)},w)},clearTimeout:function(h,g){clearTimeout(y[g]),y[g]=null},clearInterval:function(h,g){clearInterval(y[g]),y[g]=null}};function d(h,g){const w=g.data[0],S=g.data[1],b=g.data[2];u[w]&&u[w](h,S,b)}this.onmessage=function(h){d(self,h)},this.onconnect=function(h){const g=h.ports[0];g.onmessage=function(w){d(g,w)}}}).toString();try{const y=new Blob(["(",c,")()"],{type:"application/javascript"});f=URL.createObjectURL(y)}catch{return null}const _=typeof process>"u";try{if(SharedWorker)return a=new SharedWorker(f),a.port}catch{_&&console.warn("SharedWorker not available")}try{if(Worker)return a=new Worker(f),a}catch{_&&console.warn("Worker not available")}return null}();if(!n){const a=typeof window>"u"?global:window;return{setTimeout:setTimeout.bind(a),clearTimeout:clearTimeout.bind(a),setInterval:setInterval.bind(a),clearInterval:clearInterval.bind(a)}}const e=function(){let a=0;return function(){return a++,a}}(),s={},t={};n.onmessage=function(a){const f=a.data,c=s[f];if(c){c(),s[f]=null;return}const _=t[f];_&&_()};function i(a,f){const c=e();return n.postMessage(["setTimeout",c,f]),s[c]=a,c}function o(a){n.postMessage(["clearTimeout",a]),s[a]=null}function r(a,f){const c=e();return n.postMessage(["setInterval",c,f]),t[c]=a,c}function l(a){n.postMessage(["clearInterval",a]),t[a]=null}return{setTimeout:i,clearTimeout:o,setInterval:r,clearInterval:l}}(),de="7.5.0",he=n=>{const e=n.appVersion,s=n.userAgent,t="-";let i=t;const o=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Chrome OS",r:/CrOS/},{s:"Linux",r:/(Linux|X11(?!.*CrOS))/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(const l in o){const a=o[l];if(a.r.test(s)){i=a.s;break}}let r=t;switch(/Windows/.test(i)&&(r=/Windows (.*)/.exec(i)[1],i="Windows"),i){case"Mac OS":case"Mac OS X":case"Android":r=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(s)[1];break;case"iOS":{const l=/OS (\d+)_(\d+)_?(\d+)?/.exec(e);r=l[1]+"."+l[2]+"."+(parseInt(l[3])|0);break}}return{os:i,osVersion:r}};function Fe(){const n=navigator.userAgent;let e,s=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(s[1]))return e=/\brv[ :]+(\d+)/g.exec(n)||[],{name:"ie",version:e[1]||""};if(s[1]==="Chrome"&&(e=n.match(/\bOPR|Edge\/(\d+)/),e!=null)){let t=e[1];if(!t){const i=n.split(e[0]+"/");i.length>1&&(t=i[1])}return{name:"opera",version:t}}return s=s[2]?[s[1],s[2]]:[navigator.appName,navigator.appVersion,"-?"],(e=n.match(/version\/(\d+)/i))!=null&&s.splice(1,1,e[1]),{name:s[0].toLowerCase(),version:s[1]}}let fe=null;const $=n=>new Promise(e=>K.setTimeout(e,n));let H;const _e=()=>{try{const e=he(navigator).os==="Android"?240:150;H=new AbortController,fetch(`/OidcKeepAliveServiceWorker.json?minSleepSeconds=${e}`,{signal:H.signal}).catch(t=>{console.log(t)}),$(e*1e3).then(_e)}catch(n){console.log(n)}},ye=()=>{H&&H.abort()},Ve=()=>fetch("/OidcKeepAliveServiceWorker.json",{headers:{"oidc-vanilla":"true"}}).then(n=>n.statusText==="oidc-service-worker").catch(n=>{console.log(n)}),Me=n=>!!(n.os==="iOS"&&n.osVersion.startsWith("12")||n.os==="Mac OS X"&&n.osVersion.startsWith("10_15_6")),N=n=>e=>new Promise(function(s,t){const i=new MessageChannel;i.port1.onmessage=function(o){o.data&&o.data.error?t(o.data.error):s(o.data)},n.active.postMessage(e,[i.port2])}),I=async(n,e)=>{if(typeof window>"u"||typeof navigator>"u"||!navigator.serviceWorker||!n)return null;const{name:s,version:t}=Fe();if(s==="chrome"&&parseInt(t)<=70||s==="opera"&&(!t||parseInt(t.split(".")[0])<80)||s==="ie")return null;const i=he(navigator);if(Me(i))return null;const o=await navigator.serviceWorker.register(n);try{await navigator.serviceWorker.ready}catch{return null}const r=async m=>N(o)({type:"clear",data:{status:m},configurationName:e}),l=async(m,v,A)=>{const T=await N(o)({type:"init",data:{oidcServerConfiguration:m,where:v,oidcConfiguration:{token_renew_mode:A.token_renew_mode,service_worker_convert_all_requests_to_cors:A.service_worker_convert_all_requests_to_cors}},configurationName:e}),z=T.version;if(z!==de)if(console.warn(`Service worker ${z} version mismatch with js client version ${de}, unregistering and reloading`),A.service_worker_update_require_callback)await A.service_worker_update_require_callback(o,ye);else{ye(),await o.update();const ae=await o.unregister();console.log(`Service worker unregistering ${ae}`),await $(2e3),window.location.reload()}return{tokens:Q(T.tokens,null,A.token_renew_mode),status:T.status}},a=()=>{fe==null&&(fe="not_null",_e())},f=m=>N(o)({type:"setSessionState",data:{sessionState:m},configurationName:e}),c=async()=>(await N(o)({type:"getSessionState",data:null,configurationName:e})).sessionState,_=m=>(sessionStorage[`oidc.nonce.${e}`]=m.nonce,N(o)({type:"setNonce",data:{nonce:m},configurationName:e})),y=async()=>{let v=(await N(o)({type:"getNonce",data:null,configurationName:e})).nonce;return v||(v=sessionStorage[`oidc.nonce.${e}`],console.warn("nonce not found in service worker, using sessionStorage")),{nonce:v}};let u={};return{clearAsync:r,initAsync:l,startKeepAliveServiceWorker:a,isServiceWorkerProxyActiveAsync:Ve,setSessionStateAsync:f,getSessionStateAsync:c,setNonceAsync:_,getNonceAsync:y,setLoginParams:m=>{u[e]=m,localStorage[`oidc.login.${e}`]=JSON.stringify(m)},getLoginParams:()=>{const m=localStorage[`oidc.login.${e}`];return u[e]||(u[e]=JSON.parse(m)),u[e]},getStateAsync:async()=>{let v=(await N(o)({type:"getState",data:null,configurationName:e})).state;return v||(v=sessionStorage[`oidc.state.${e}`],console.warn("state not found in service worker, using sessionStorage")),v},setStateAsync:async m=>(sessionStorage[`oidc.state.${e}`]=m,N(o)({type:"setState",data:{state:m},configurationName:e})),getCodeVerifierAsync:async()=>{let v=(await N(o)({type:"getCodeVerifier",data:null,configurationName:e})).codeVerifier;return v||(v=sessionStorage[`oidc.code_verifier.${e}`],console.warn("codeVerifier not found in service worker, using sessionStorage")),v},setCodeVerifierAsync:async m=>(sessionStorage[`oidc.code_verifier.${e}`]=m,N(o)({type:"setCodeVerifier",data:{codeVerifier:m},configurationName:e})),setDemonstratingProofOfPossessionNonce:m=>{localStorage[`oidc.dpop_nonce.${e}`]=m},getDemonstratingProofOfPossessionNonce:()=>localStorage[`oidc.dpop_nonce.${e}`],setDemonstratingProofOfPossessionJwkAsync:m=>{localStorage[`oidc.jwk.${e}`]=JSON.stringify(m)},getDemonstratingProofOfPossessionJwkAsync:()=>JSON.parse(localStorage[`oidc.jwk.${e}`])}};async function ge(n,e,s=!1,t=null){const i=a=>{n.tokens=a},{tokens:o,status:r}=await n.synchroniseTokensAsync(e,0,s,t,i);if(await I(n.configuration.service_worker_relative_url,n.configurationName)||await O(n.configurationName,n.configuration.storage).setTokens(n.tokens),!n.tokens){await n.destroyAsync(r);return}return n.timeoutId&&(n.timeoutId=B(n,o.refreshToken,n.tokens.expiresAt,t)),n.tokens}const B=(n,e,s,t=null)=>{const i=n.configuration.refresh_time_before_tokens_expiration_in_second;return K.setTimeout(async()=>{const r={timeLeft:U(i,s)};n.publishEvent(R.eventNames.token_timer,r),await ge(n,e,!1,t)},1e3)},ee=(n,e,s)=>(t=null,i=null,o=null)=>{if(!e.silent_redirect_uri||!e.silent_login_uri)return Promise.resolve(null);try{s(k.silentLoginAsync_begin,{});let r="";if(i&&(t==null&&(t={}),t.state=i),o&&(t==null&&(t={}),t.scope=o),t!=null)for(const[_,y]of Object.entries(t))r===""?r=`?${encodeURIComponent(_)}=${encodeURIComponent(y)}`:r+=`&${encodeURIComponent(_)}=${encodeURIComponent(y)}`;const l=e.silent_login_uri+r,a=l.indexOf("/",l.indexOf("//")+2),f=l.substr(0,a),c=document.createElement("iframe");return c.width="0px",c.height="0px",c.id=`${n}_oidc_iframe`,c.setAttribute("src",l),document.body.appendChild(c),new Promise((_,y)=>{try{let u=!1;window.onmessage=h=>{if(h.origin===f&&h.source===c.contentWindow){const g=`${n}_oidc_tokens:`,w=`${n}_oidc_error:`,S=h.data;if(S&&typeof S=="string"&&!u){if(S.startsWith(g)){const b=JSON.parse(h.data.replace(g,""));s(k.silentLoginAsync_end,{}),c.remove(),u=!0,_(b)}else if(S.startsWith(w)){const b=JSON.parse(h.data.replace(w,""));s(k.silentLoginAsync_error,b),c.remove(),u=!0,y(new Error("oidc_"+b.error))}}}};const d=e.silent_login_timeout;setTimeout(()=>{u||(s(k.silentLoginAsync_error,{reason:"timeout"}),c.remove(),u=!0,y(new Error("timeout")))},d)}catch(u){c.remove(),s(k.silentLoginAsync_error,u),y(u)}})}catch(r){throw s(k.silentLoginAsync_error,r),r}},Ue=(n,e,s,t,i)=>(o=null,r=void 0)=>{o={...o};const l=(f,c,_)=>ee(e,s,t.bind(i))(f,c,_);return(async()=>{i.timeoutId&&K.clearTimeout(i.timeoutId);let f;o&&"state"in o&&(f=o.state,delete o.state);try{const c=s.extras?{...s.extras,...o}:o,_=await l({...c,prompt:"none"},f,r);if(_)return i.tokens=_.tokens,t(k.token_aquired,{}),i.timeoutId=B(i,i.tokens.refreshToken,i.tokens.expiresAt,o),{}}catch(c){return c}})()},Ke=(n,e,s)=>(t,i,o,r=!1)=>{const l=(a,f=void 0,c=void 0)=>ee(n.configurationName,s,n.publishEvent.bind(n))(a,f,c);return new Promise((a,f)=>{if(s.silent_login_uri&&s.silent_redirect_uri&&s.monitor_session&&t&&o&&!r){const c=()=>{n.checkSessionIFrame.stop();const _=n.tokens;if(_===null)return;const y=_.idToken,u=_.idTokenPayload;return l({prompt:"none",id_token_hint:y,scope:s.scope||"openid"}).then(d=>{const h=d.tokens.idTokenPayload;if(u.sub===h.sub){const g=d.sessionState;n.checkSessionIFrame.start(d.sessionState),u.sid===h.sid?console.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",g):console.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",g)}else console.debug("SessionMonitor._callback: Different subject signed into OP:",h.sub)}).catch(async d=>{console.warn("SessionMonitor._callback: Silent login failed, logging out other tabs:",d);for(const[h,g]of Object.entries(e))await g.logoutOtherTabAsync(s.client_id,u.sub)})};n.checkSessionIFrame=new Ne(c,i,t),n.checkSessionIFrame.load().then(()=>{n.checkSessionIFrame.start(o),a(n.checkSessionIFrame)}).catch(_=>{f(_)})}else a(null)})};for(var Be=Ge,L=[],ke="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",X=0,Je=ke.length;X<Je;++X)L[X]=ke[X];function je(n){return L[n>>18&63]+L[n>>12&63]+L[n>>6&63]+L[n&63]}function qe(n,e,s){for(var t,i=[],o=e;o<s;o+=3)t=(n[o]<<16&16711680)+(n[o+1]<<8&65280)+(n[o+2]&255),i.push(je(t));return i.join("")}function Ge(n){for(var e,s=n.length,t=s%3,i=[],o=16383,r=0,l=s-t;r<l;r+=o)i.push(qe(n,r,r+o>l?l:r+o));return t===1?(e=n[s-1],i.push(L[e>>2]+L[e<<4&63]+"==")):t===2&&(e=(n[s-2]<<8)+n[s-1],i.push(L[e>>10]+L[e>>4&63]+L[e<<2&63]+"=")),i.join("")}const me=()=>{const n=typeof window<"u"&&!!window.crypto,e=n&&!!window.crypto.subtle;return{hasCrypto:n,hasSubtleCrypto:e}},ne="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",He=n=>{const e=[];for(let s=0;s<n.byteLength;s+=1){const t=n[s]%ne.length;e.push(ne[t])}return e.join("")},Xe=n=>Be(new Uint8Array(n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),se=n=>{const e=new Uint8Array(n),{hasCrypto:s}=me();if(s)window.crypto.getRandomValues(e);else for(let t=0;t<n;t+=1)e[t]=Math.random()*ne.length|0;return He(e)};function Ye(n){const e=new ArrayBuffer(n.length),s=new Uint8Array(e);for(let t=0;t<n.length;t++)s[t]=n.charCodeAt(t);return s}function pe(n){return new Promise((e,s)=>{crypto.subtle.digest("SHA-256",Ye(n)).then(t=>e(Xe(new Uint8Array(t))),t=>s(t))})}const ze=n=>{if(n.length<43||n.length>128)return Promise.reject(new Error("Invalid code length."));const{hasSubtleCrypto:e}=me();return e?pe(n):Promise.reject(new Error("window.crypto.subtle is unavailable."))},V={},Qe=(n,e=window.sessionStorage,s)=>{if(!V[n]&&e){const i=e.getItem(n);i&&(V[n]=JSON.parse(i))}const t=1e3*s;return V[n]&&V[n].timestamp+t>Date.now()?V[n].result:null},Ze=(n,e,s=window.sessionStorage)=>{const t=Date.now();V[n]={result:e,timestamp:t},s&&s.setItem(n,JSON.stringify({result:e,timestamp:t}))},en=60*60,nn=n=>async(e,s=en,t=window.sessionStorage,i=1e4)=>{const o=`${e}/.well-known/openid-configuration`,r=`oidc.server:${e}`,l=Qe(r,t,s);if(l)return new ie(l);const a=await J(n)(o,{},i);if(a.status!==200)return null;const f=await a.json();return Ze(r,f,t),new ie(f)},J=n=>async(e,s={},t=1e4,i=0)=>{let o;try{const r=new AbortController;setTimeout(()=>r.abort(),t),o=await n(e,{...s,signal:r.signal})}catch(r){if(r.name==="AbortError"||r.message==="Network request failed"){if(i<=1)return await J(n)(e,s,t,i+1);throw r}else throw console.error(r.message),r}return o},te={refresh_token:"refresh_token",access_token:"access_token"},we=n=>async(e,s,t=te.refresh_token,i,o=1e4)=>{const r={token:s,token_type_hint:t,client_id:i},l=[];for(const c in r){const _=encodeURIComponent(c),y=encodeURIComponent(r[c]);l.push(`${_}=${y}`)}const a=l.join("&");return(await J(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},body:a},o)).status!==200?{success:!1}:{success:!0}},sn=n=>async(e,s,t,i,o={},r,l=1e4)=>{for(const[u,d]of Object.entries(t))s[u]===void 0&&(s[u]=d);const a=[];for(const u in s){const d=encodeURIComponent(u),h=encodeURIComponent(s[u]);a.push(`${d}=${h}`)}const f=a.join("&"),c=await J(n)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...o},body:f},l);if(c.status!==200)return{success:!1,status:c.status,demonstratingProofOfPossessionNonce:null};const _=await c.json();let y=null;return c.headers.has(Y)&&(y=c.headers.get(Y)),{success:!0,data:Q(_,i,r),demonstratingProofOfPossessionNonce:y}},tn=n=>async(e,s)=>{s=s?{...s}:{};const t=se(128),i=await ze(t);await n.setCodeVerifierAsync(t),await n.setStateAsync(s.state),s.code_challenge=i,s.code_challenge_method="S256";let o="";if(s)for(const[r,l]of Object.entries(s))o===""?o+="?":o+="&",o+=`${r}=${encodeURIComponent(l)}`;window.location.href=`${e}${o}`},Y="DPoP-Nonce",on=n=>async(e,s,t,i,o=1e4)=>{s=s?{...s}:{},s.code_verifier=await n.getCodeVerifierAsync();const r=[];for(const _ in s){const y=encodeURIComponent(_),u=encodeURIComponent(s[_]);r.push(`${y}=${u}`)}const l=r.join("&"),a=await J(fetch)(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8",...t},body:l},o);if(await Promise.all([n.setCodeVerifierAsync(null),n.setStateAsync(null)]),a.status!==200)return{success:!1,status:a.status};let f=null;a.headers.has(Y)&&(f=a.headers.get(Y));const c=await a.json();return{success:!0,data:{state:s.state,tokens:Q(c,null,i),demonstratingProofOfPossessionNonce:f}}},Ae=n=>{const e=n.match(/^([a-z][\w-]+\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!e)throw new Error("Invalid URL");let s=e[6],t=e[7];if(t){const i=t.split("?");i.length===2&&(t=i[0],s=i[1])}return s.startsWith("?")&&(s=s.slice(1)),e&&{href:n,protocol:e[1],host:e[2],hostname:e[3],port:e[4],path:e[5],search:s,hash:t}},rn=n=>{const e=Ae(n);let{path:s}=e;s.endsWith("/")&&(s=s.slice(0,-1));let{hash:t}=e;return t==="#_=_"&&(t=""),t&&(s+=t),s},j=n=>{const e=Ae(n),{search:s}=e;return an(s)},an=n=>{const e={};let s,t,i;const o=n.split("&");for(t=0,i=o.length;t<i;t++)s=o[t].split("="),e[decodeURIComponent(s[0])]=decodeURIComponent(s[1]);return e};function Se(n){return new TextEncoder().encode(n)}function ve(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+/g,"")}function cn(n){return encodeURIComponent(n).replace(/%([0-9A-F]{2})/g,function(t,i){return String.fromCharCode(parseInt(i,16))})}function Te(n){let e="";return n.forEach(function(s){e+=String.fromCharCode(s)}),ve(e)}function be(n){return ve(cn(n))}var Pe={};Pe.sign=(n,e,s,t="dpop+jwt")=>{n=Object.assign({},n),e.typ=t,e.alg="ES256",e.kid||(e.jwk={kty:n.kty,crv:n.crv,x:n.x,y:n.y});const i={protected:be(JSON.stringify(e)),payload:be(JSON.stringify(s))},o={name:"ECDSA",namedCurve:"P-256",hash:{name:"ES256"}},r=!0,l=["sign"];return window.crypto.subtle.importKey("jwk",n,o,r,l).then(function(a){const f=Se(i.protected+"."+i.payload),c={name:"ECDSA",hash:{name:"SHA-256"}};return window.crypto.subtle.sign(c,a,f).then(function(_){return i.signature=Te(new Uint8Array(_)),i.protected+"."+i.payload+"."+i.signature})})};const oe={};oe.generate=function(){const n={name:"ECDSA",namedCurve:"P-256"},e=!0,s=["sign","verify"];return window.crypto.subtle.generateKey(n,e,s).then(function(t){return window.crypto.subtle.exportKey("jwk",t.privateKey)})},oe.neuter=function(n){const e=Object.assign({},n);return delete e.d,e.key_ops=["verify"],e};var Oe={};Oe.thumbprint=function(n){const e='{"crv":"CRV","kty":"EC","x":"X","y":"Y"}'.replace("CRV",n.crv).replace("X",n.x).replace("Y",n.y);return window.crypto.subtle.digest({name:"SHA-256"},Se(e)).then(function(s){return Te(new Uint8Array(s))})};const ln=function(){const n="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",e="0123456789abcdef";let s=0,t="";for(let i=0;i<36;i++)n[i]!=="-"&&n[i]!=="4"&&(s=Math.random()*16|0),n[i]==="x"?t+=e[s]:n[i]==="y"?(s&=3,s|=8,t+=e[s]):t+=n[i];return t},un=()=>oe.generate().then(function(n){return n}),Ee=(n,e="POST",s,t={})=>{const i={jit:btoa(ln()),htm:e,htu:s,iat:Math.round(Date.now()/1e3),...t};return Oe.thumbprint(n).then(function(o){return Pe.sign(n,{},i).then(function(r){return r})})},dn=(n,e,s,t,i)=>(o=void 0,r=null,l=!1,a=void 0)=>{const f=r;return r={...r},(async()=>{const _=n.location,y=o||_.pathname+(_.search||"")+(_.hash||"");if("state"in r||(r.state=se(16)),t(k.loginAsync_begin,{}),r)for(const u of Object.keys(r))u.endsWith(":token_request")&&delete r[u];try{const u=l?s.silent_redirect_uri:s.redirect_uri;a||(a=s.scope);const d=s.extras?{...s.extras,...r}:r;d.nonce||(d.nonce=se(12));const h={nonce:d.nonce},g=await I(s.service_worker_relative_url,e),w=await i(s.authority,s.authority_configuration);let S;if(g)g.setLoginParams({callbackPath:y,extras:f}),await g.initAsync(w,"loginAsync",s),await g.setNonceAsync(h),g.startKeepAliveServiceWorker(),S=g;else{const P=O(e,s.storage??sessionStorage);P.setLoginParams({callbackPath:y,extras:f}),await P.setNonceAsync(h),S=P}const b={client_id:s.client_id,redirect_uri:u,scope:a,response_type:"code",...d};await tn(S)(w.authorizationEndpoint,b)}catch(u){throw t(k.loginAsync_error,u),u}})()},hn=n=>async(e=!1)=>{try{n.publishEvent(k.loginCallbackAsync_begin,{});const s=n.configuration,t=s.client_id,i=e?s.silent_redirect_uri:s.redirect_uri,o=s.authority,r=s.token_request_timeout,l=await n.initAsync(o,s.authority_configuration),f=j(window.location.href).session_state,c=await I(s.service_worker_relative_url,n.configurationName);let _,y,u,d;if(c)await c.initAsync(l,"loginCallbackAsync",s),await c.setSessionStateAsync(f),y=await c.getNonceAsync(),u=c.getLoginParams(),d=await c.getStateAsync(),c.startKeepAliveServiceWorker(),_=c;else{const A=O(n.configurationName,s.storage??sessionStorage);await A.setSessionStateAsync(f),y=await A.getNonceAsync(),u=A.getLoginParams(),d=await A.getStateAsync(),_=A}const h=j(window.location.toString());if(h.iss&&h.iss!==l.issuer)throw console.error(),new Error(`issuer not valid (expected: ${l.issuer}, received: ${h.iss})`);if(h.state&&h.state!==d)throw new Error(`state not valid (expected: ${d}, received: ${h.state})`);const g={code:h.code,grant_type:"authorization_code",client_id:s.client_id,redirect_uri:i},w={};if(s.token_request_extras)for(const[A,T]of Object.entries(s.token_request_extras))w[A]=T;if(u&&u.extras)for(const[A,T]of Object.entries(u.extras))A.endsWith(":token_request")&&(w[A.replace(":token_request","")]=T);const S=l.tokenEndpoint,b={};if(s.demonstrating_proof_of_possession){const A=await un();c?await c.setDemonstratingProofOfPossessionJwkAsync(A):await O(n.configurationName,s.storage).setDemonstratingProofOfPossessionJwkAsync(A),b.DPoP=await Ee(A,"POST",S)}const P=await on(_)(S,{...g,...w},b,n.configuration.token_renew_mode,r);if(!P.success)throw new Error("Token request failed");let p;const E=P.data.tokens,C=P.data.demonstratingProofOfPossessionNonce;if(P.data.state!==w.state)throw new Error("state is not valid");const{isValid:m,reason:v}=ue(E,y.nonce,l);if(!m)throw new Error(`Tokens are not OpenID valid, reason: ${v}`);if(c){if(E.refreshToken&&!E.refreshToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Refresh token should be hidden by service worker");if(C&&E.accessToken&&E.accessToken.includes("SECURED_BY_OIDC_SERVICE_WORKER"))throw new Error("Demonstration of proof of possession require Access token not hidden by service worker")}if(c)await c.initAsync(i,"syncTokensAsync",s),p=c.getLoginParams(),C&&await c.setDemonstratingProofOfPossessionNonce(C);else{const A=O(n.configurationName,s.storage);p=A.getLoginParams(),C&&await A.setDemonstratingProofOfPossessionNonce(C)}return await n.startCheckSessionAsync(l.checkSessionIframe,t,f,e),n.publishEvent(k.loginCallbackAsync_end,{}),{tokens:E,state:"request.state",callbackPath:p.callbackPath}}catch(s){throw console.error(s),n.publishEvent(k.loginCallbackAsync_error,s),s}},Ie={access_token:"access_token",refresh_token:"refresh_token"},fn=n=>async e=>{K.clearTimeout(n.timeoutId),n.timeoutId=null,n.checkSessionIFrame&&n.checkSessionIFrame.stop();const s=await I(n.configuration.service_worker_relative_url,n.configurationName);s?await s.clearAsync(e):await O(n.configurationName,n.configuration.storage).clearAsync(e),n.tokens=null,n.userInfo=null},_n=(n,e,s,t,i)=>async(o=void 0,r=null)=>{const l=n.configuration,a=await n.initAsync(l.authority,l.authority_configuration);o&&typeof o!="string"&&(o=void 0,i.warn("callbackPathOrUrl path is not a string"));const f=o??location.pathname+(location.search||"")+(location.hash||"");let c=!1;o&&(c=o.includes("https://")||o.includes("http://"));const _=c?o:t.location.origin+f,y=n.tokens?n.tokens.idToken:"";try{const d=a.revocationEndpoint;if(d){const h=[],g=n.tokens.accessToken;if(g&&l.logout_tokens_to_invalidate.includes(Ie.access_token)){const S=we(s)(d,g,te.access_token,l.client_id);h.push(S)}const w=n.tokens.refreshToken;if(w&&l.logout_tokens_to_invalidate.includes(Ie.refresh_token)){const S=we(s)(d,w,te.refresh_token,l.client_id);h.push(S)}h.length>0&&await Promise.all(h)}}catch(d){i.warn("logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error"),i.warn(d)}const u=n.tokens&&n.tokens.idTokenPayload?n.tokens.idTokenPayload.sub:null;await n.destroyAsync("LOGGED_OUT");for(const[d,h]of Object.entries(e))h!==n&&await n.logoutSameTabAsync(n.configuration.client_id,u);if(a.endSessionEndpoint){r||(r={id_token_hint:y},o!==null&&(r.post_logout_redirect_uri=_));let d="";if(r)for(const[h,g]of Object.entries(r))d===""?d+="?":d+="&",d+=`${h}=${encodeURIComponent(g)}`;t.location.href=`${a.endSessionEndpoint}${d}`}else t.location.reload()},yn=n=>async(e=!1)=>{if(n.userInfo!=null&&!e)return n.userInfo;for(;n.tokens&&!Z(n.tokens);)await $(200);if(!n.tokens)return null;const s=n.tokens.accessToken;if(!s)return null;const i=(await n.initAsync(n.configuration.authority,n.configuration.authority_configuration)).userInfoEndpoint,r=await(async l=>{const a=await fetch(i,{headers:{authorization:`Bearer ${l}`}});return a.status!==200?null:a.json()})(s);return n.userInfo=r,r},Ce=()=>fetch;class ie{constructor(e){this.authorizationEndpoint=e.authorization_endpoint,this.tokenEndpoint=e.token_endpoint,this.revocationEndpoint=e.revocation_endpoint,this.userInfoEndpoint=e.userinfo_endpoint,this.checkSessionIframe=e.check_session_iframe,this.issuer=e.issuer,this.endSessionEndpoint=e.end_session_endpoint}}const W={},gn=n=>(e,s="default")=>(W[s]||(W[s]=new R(e,s,n)),W[s]),kn=async n=>{const{parsedTokens:e,callbackPath:s}=await n.loginCallbackAsync();return n.timeoutId=B(n,e.refreshToken,e.expiresAt),{callbackPath:s}},mn=n=>Math.floor(Math.random()*n),D=class D{constructor(e,s="default",t){this.initPromise=null,this.tryKeepExistingSessionPromise=null,this.loginPromise=null,this.loginCallbackPromise=null,this.loginCallbackWithAutoTokensRenewPromise=null,this.userInfoPromise=null,this.renewTokensPromise=null,this.logoutPromise=null;let i=e.silent_login_uri;e.silent_redirect_uri&&!e.silent_login_uri&&(i=`${e.silent_redirect_uri.replace("-callback","").replace("callback","")}-login`);let o=e.refresh_time_before_tokens_expiration_in_second??120;o>60&&(o=o-Math.floor(Math.random()*40)),this.configuration={...e,silent_login_uri:i,monitor_session:e.monitor_session??!1,refresh_time_before_tokens_expiration_in_second:o,silent_login_timeout:e.silent_login_timeout??12e3,token_renew_mode:e.token_renew_mode??G.access_token_or_id_token_invalid,demonstrating_proof_of_possession:e.demonstrating_proof_of_possession??!1,authority_timeout_wellknowurl_in_millisecond:e.authority_timeout_wellknowurl_in_millisecond??1e4,logout_tokens_to_invalidate:e.logout_tokens_to_invalidate??["access_token","refresh_token"]},this.getFetch=t??Ce,this.configurationName=s,this.tokens=null,this.userInfo=null,this.events=[],this.timeoutId=null,this.synchroniseTokensAsync.bind(this),this.loginCallbackWithAutoTokensRenewAsync.bind(this),this.initAsync.bind(this),this.loginCallbackAsync.bind(this),this.subscribeEvents.bind(this),this.removeEventSubscription.bind(this),this.publishEvent.bind(this),this.destroyAsync.bind(this),this.logoutAsync.bind(this),this.renewTokensAsync.bind(this),this.initAsync(this.configuration.authority,this.configuration.authority_configuration)}subscribeEvents(e){const s=mn(9999999999999).toString();return this.events.push({id:s,func:e}),s}removeEventSubscription(e){const s=this.events.filter(t=>t.id!==e);this.events=s}publishEvent(e,s){this.events.forEach(t=>{t.func(e,s)})}static get(e="default"){const s=typeof process>"u";if(!Object.prototype.hasOwnProperty.call(W,e)&&s)throw Error(`OIDC library does seem initialized.
|
|
2
|
+
Please checkout that you are using OIDC hook inside a <OidcProvider configurationName="${e}"></OidcProvider> compoment.`);return W[e]}_silentLoginCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=j(window.location.href);window.parent.postMessage(`${this.configurationName}_oidc_tokens:${JSON.stringify({tokens:this.tokens,sessionState:e.session_state})}`,window.location.origin)}}_silentLoginErrorCallbackFromIFrame(){if(this.configuration.silent_redirect_uri&&this.configuration.silent_login_uri){const e=j(window.location.href);window.parent.postMessage(`${this.configurationName}_oidc_error:${JSON.stringify({error:e.error})}`,window.location.origin)}}async silentLoginCallbackAsync(){try{await this.loginCallbackAsync(!0),this._silentLoginCallbackFromIFrame()}catch(e){console.error(e),this._silentLoginErrorCallbackFromIFrame()}}async initAsync(e,s){if(this.initPromise!==null)return this.initPromise;const t=async()=>{if(s!=null)return new ie({authorization_endpoint:s.authorization_endpoint,end_session_endpoint:s.end_session_endpoint,revocation_endpoint:s.revocation_endpoint,token_endpoint:s.token_endpoint,userinfo_endpoint:s.userinfo_endpoint,check_session_iframe:s.check_session_iframe,issuer:s.issuer});const o=await I(this.configuration.service_worker_relative_url,this.configurationName)?window.localStorage:null;return await nn(this.getFetch())(e,this.configuration.authority_time_cache_wellknowurl_in_second??60*60,o,this.configuration.authority_timeout_wellknowurl_in_millisecond)};return this.initPromise=t(),this.initPromise.then(i=>(this.initPromise=null,i))}async tryKeepExistingSessionAsync(){if(this.tryKeepExistingSessionPromise!==null)return this.tryKeepExistingSessionPromise;const e=async()=>{let s;if(this.tokens!=null)return!1;this.publishEvent(k.tryKeepExistingSessionAsync_begin,{});try{const t=this.configuration,i=await this.initAsync(t.authority,t.authority_configuration);if(s=await I(t.service_worker_relative_url,this.configurationName),s){const{tokens:o}=await s.initAsync(i,"tryKeepExistingSessionAsync",t);if(o){s.startKeepAliveServiceWorker(),this.tokens=o;const r=s.getLoginParams(this.configurationName);this.timeoutId=B(this,this.tokens.refreshToken,this.tokens.expiresAt,r.extras);const l=await s.getSessionStateAsync();return await this.startCheckSessionAsync(i.check_session_iframe,t.client_id,l),this.publishEvent(k.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside ServiceWorker are valid"}),!0}this.publishEvent(k.tryKeepExistingSessionAsync_end,{success:!1,message:"no exiting session found"})}else{t.service_worker_relative_url&&this.publishEvent(k.service_worker_not_supported_by_browser,{message:"service worker is not supported by this browser"});const o=O(this.configurationName,t.storage??sessionStorage),{tokens:r}=await o.initAsync();if(r){this.tokens=le(r,null,t.token_renew_mode);const l=o.getLoginParams();this.timeoutId=B(this,r.refreshToken,this.tokens.expiresAt,l.extras);const a=await o.getSessionStateAsync();return await this.startCheckSessionAsync(i.check_session_iframe,t.client_id,a),this.publishEvent(k.tryKeepExistingSessionAsync_end,{success:!0,message:"tokens inside storage are valid"}),!0}}return this.publishEvent(k.tryKeepExistingSessionAsync_end,{success:!1,message:s?"service worker sessions not retrieved":"session storage sessions not retrieved"}),!1}catch(t){return console.error(t),s&&await s.clearAsync(),this.publishEvent(k.tryKeepExistingSessionAsync_error,"tokens inside ServiceWorker are invalid"),!1}};return this.tryKeepExistingSessionPromise=e(),this.tryKeepExistingSessionPromise.then(s=>(this.tryKeepExistingSessionPromise=null,s))}async startCheckSessionAsync(e,s,t,i=!1){await Ke(this,W,this.configuration)(e,s,t,i)}async loginAsync(e=void 0,s=null,t=!1,i=void 0,o=!1){return this.loginPromise!==null?this.loginPromise:o?Ue(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this)(s,i):(this.loginPromise=dn(window,this.configurationName,this.configuration,this.publishEvent.bind(this),this.initAsync.bind(this))(e,s,t,i),this.loginPromise.then(r=>(this.loginPromise=null,r)))}async loginCallbackAsync(e=!1){if(this.loginCallbackPromise!==null)return this.loginCallbackPromise;const s=async()=>{const t=await hn(this)(e),i=t.tokens;return this.tokens=i,await I(this.configuration.service_worker_relative_url,this.configurationName)||O(this.configurationName,this.configuration.storage).setTokens(i),this.publishEvent(D.eventNames.token_aquired,i),{parsedTokens:i,state:t.state,callbackPath:t.callbackPath}};return this.loginCallbackPromise=s(),this.loginCallbackPromise.then(t=>(this.loginCallbackPromise=null,t))}async synchroniseTokensAsync(e,s=0,t=!1,i=null,o){for(;!navigator.onLine&&document.hidden;)await $(1e3),this.publishEvent(k.refreshTokensAsync,{message:"wait because navigator is offline and hidden"});let r=6;for(;!navigator.onLine&&r>0;)await $(1e3),r--,this.publishEvent(k.refreshTokensAsync,{message:`wait because navigator is offline try ${r}`});let l=Math.floor(Math.random()*15)+10;for(;document.hidden&&l>0;)await $(1e3),l--,this.publishEvent(k.refreshTokensAsync,{message:`wait because navigator is hidden try ${l}`});const f=document.hidden?s:s+1;i||(i={});const c=this.configuration,_=(u,d,h=null)=>ee(this.configurationName,this.configuration,this.publishEvent.bind(this))(u,d,h),y=async()=>{try{let u;const d=await I(c.service_worker_relative_url,this.configurationName);d?u=d.getLoginParams():u=O(this.configurationName,c.storage).getLoginParams();const h=await _({...u.extras,...i,prompt:"none"},u.state);if(h)return o(h.tokens),this.publishEvent(D.eventNames.token_renewed,{}),{tokens:h.tokens,status:"LOGGED"}}catch(u){if(console.error(u),this.publishEvent(k.refreshTokensAsync_silent_error,{message:"exceptionSilent",exception:u.message}),u&&u.message&&u.message.startsWith("oidc"))return o(null),this.publishEvent(k.refreshTokensAsync_error,{message:"refresh token silent"}),{tokens:null,status:"SESSION_LOST"}}return this.publishEvent(k.refreshTokensAsync_error,{message:"refresh token silent return"}),await this.synchroniseTokensAsync(null,f,t,i,o)};if(s>4)return o(null),this.publishEvent(k.refreshTokensAsync_error,{message:"refresh token"}),{tokens:null,status:"SESSION_LOST"};try{const{status:u,tokens:d,nonce:h}=await this.syncTokensInfoAsync(c,this.configurationName,this.tokens,t);switch(u){case"SESSION_LOST":return o(null),this.publishEvent(k.refreshTokensAsync_error,{message:"refresh token session lost"}),{tokens:null,status:"SESSION_LOST"};case"NOT_CONNECTED":return o(null),{tokens:null,status:null};case"TOKENS_VALID":return o(d),{tokens:d,status:"LOGGED_IN"};case"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":return o(d),this.publishEvent(D.eventNames.token_renewed,{reason:"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID"}),{tokens:d,status:"LOGGED_IN"};case"LOGOUT_FROM_ANOTHER_TAB":return o(null),this.publishEvent(k.logout_from_another_tab,{status:"session syncTokensAsync"}),{tokens:null,status:"LOGGED_OUT"};case"REQUIRE_SYNC_TOKENS":return this.publishEvent(k.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:s}),await y();default:{if(this.publishEvent(k.refreshTokensAsync_begin,{refreshToken:e,status:u,tryNumber:s}),!e)return await y();const g=c.client_id,w=c.redirect_uri,S=c.authority,P={...c.token_request_extras?c.token_request_extras:{}};for(const[E,C]of Object.entries(i))E.endsWith(":token_request")&&(P[E.replace(":token_request","")]=C);return await(async()=>{const E={client_id:g,redirect_uri:w,grant_type:"refresh_token",refresh_token:d.refreshToken},C=await this.initAsync(S,c.authority_configuration),m=document.hidden?1e4:3e4*10,v=C.tokenEndpoint,A={};c.demonstrating_proof_of_possession&&(A.DPoP=await this.generateDemonstrationOfProofOfPossessionAsync(d.accessToken,v,"POST"));const T=await sn(this.getFetch())(v,E,P,d,A,c.token_renew_mode,m);if(T.success){const{isValid:z,reason:ae}=ue(T.data,h.nonce,C);if(!z)return o(null),this.publishEvent(k.refreshTokensAsync_error,{message:`refresh token return not valid tokens, reason: ${ae}`}),{tokens:null,status:"SESSION_LOST"};if(o(T.data),T.demonstratingProofOfPossessionNonce){const xe=await I(c.service_worker_relative_url,this.configurationName);xe?await xe.setDemonstratingProofOfPossessionNonce(T.demonstratingProofOfPossessionNonce):await O(this.configurationName,c.storage).setDemonstratingProofOfPossessionNonce(T.demonstratingProofOfPossessionNonce)}return this.publishEvent(k.refreshTokensAsync_end,{success:T.success}),this.publishEvent(D.eventNames.token_renewed,{reason:"REFRESH_TOKEN"}),{tokens:T.data,status:"LOGGED_IN"}}else return this.publishEvent(k.refreshTokensAsync_silent_error,{message:"bad request",tokenResponse:T}),await this.synchroniseTokensAsync(e,f,t,i,o)})()}}}catch(u){return console.error(u),this.publishEvent(k.refreshTokensAsync_silent_error,{message:"exception",exception:u.message}),this.synchroniseTokensAsync(e,f,t,i,o)}}async generateDemonstrationOfProofOfPossessionAsync(e,s,t){const i=this.configuration,o={ath:await pe(e)},r=await I(i.service_worker_relative_url,this.configurationName);let l=null,a;if(r)l=await r.getDemonstratingProofOfPossessionNonce(),a=await r.getDemonstratingProofOfPossessionJwkAsync();else{const f=O(this.configurationName,i.storage);a=await f.getDemonstratingProofOfPossessionJwkAsync(),l=await f.getDemonstratingProofOfPossessionNonce()}return l&&(o.nonce=l),await Ee(a,t,s,o)}async syncTokensInfoAsync(e,s,t,i=!1){const o={nonce:null};if(!t)return{tokens:null,status:"NOT_CONNECTED",nonce:o};let r=o;const l=await this.initAsync(e.authority,e.authority_configuration),a=await I(e.service_worker_relative_url,s);if(a){const{status:_,tokens:y}=await a.initAsync(l,"syncTokensAsync",e);if(_==="LOGGED_OUT")return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};if(_==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(!_||!y)return{tokens:null,status:"REQUIRE_SYNC_TOKENS",nonce:o};if(y.issuedAt!==t.issuedAt){const d=U(e.refresh_time_before_tokens_expiration_in_second,y.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",h=await a.getNonceAsync();return{tokens:y,status:d,nonce:h}}r=await a.getNonceAsync()}else{const _=O(s,e.storage??sessionStorage),{tokens:y,status:u}=await _.initAsync();if(y){if(u==="SESSIONS_LOST")return{tokens:null,status:"SESSIONS_LOST",nonce:o};if(y.issuedAt!==t.issuedAt){const h=U(e.refresh_time_before_tokens_expiration_in_second,y.expiresAt)>0?"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_VALID":"TOKEN_UPDATED_BY_ANOTHER_TAB_TOKENS_INVALID",g=await _.getNonceAsync();return{tokens:y,status:h,nonce:g}}}else return{tokens:null,status:"LOGOUT_FROM_ANOTHER_TAB",nonce:o};r=await _.getNonceAsync()}const c=U(e.refresh_time_before_tokens_expiration_in_second,t.expiresAt)>0?"TOKENS_VALID":"TOKENS_INVALID";return i?{tokens:t,status:"FORCE_REFRESH",nonce:r}:{tokens:t,status:c,nonce:r}}loginCallbackWithAutoTokensRenewAsync(){return this.loginCallbackWithAutoTokensRenewPromise!==null?this.loginCallbackWithAutoTokensRenewPromise:(this.loginCallbackWithAutoTokensRenewPromise=kn(this),this.loginCallbackWithAutoTokensRenewPromise.then(e=>(this.loginCallbackWithAutoTokensRenewPromise=null,e)))}userInfoAsync(e=!1){return this.userInfoPromise!==null?this.userInfoPromise:(this.userInfoPromise=yn(this)(e),this.userInfoPromise.then(s=>(this.userInfoPromise=null,s)))}async renewTokensAsync(e=null){if(this.renewTokensPromise!==null)return this.renewTokensPromise;if(this.timeoutId)return K.clearTimeout(this.timeoutId),this.renewTokensPromise=ge(this,this.tokens.refreshToken,!0,e),this.renewTokensPromise.then(s=>(this.renewTokensPromise=null,s))}async destroyAsync(e){return await fn(this)(e)}async logoutSameTabAsync(e,s){this.configuration.monitor_session&&this.configuration.client_id===e&&s&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===s&&(this.publishEvent(k.logout_from_same_tab,{message:s}),await this.destroyAsync("LOGGED_OUT"))}async logoutOtherTabAsync(e,s){this.configuration.monitor_session&&this.configuration.client_id===e&&s&&this.tokens&&this.tokens.idTokenPayload&&this.tokens.idTokenPayload.sub===s&&(await this.destroyAsync("LOGGED_OUT"),this.publishEvent(k.logout_from_another_tab,{message:"SessionMonitor",sub:s}))}async logoutAsync(e=void 0,s=null){return this.logoutPromise?this.logoutPromise:(this.logoutPromise=_n(this,W,this.getFetch(),window,console)(e,s),this.logoutPromise.then(t=>(this.logoutPromise=null,t)))}};D.getOrCreate=e=>(s,t="default")=>gn(e)(s,t),D.eventNames=k;let R=D;const M=class M{constructor(e){this._oidc=e}subscribeEvents(e){return this._oidc.subscribeEvents(e)}removeEventSubscription(e){this._oidc.removeEventSubscription(e)}publishEvent(e,s){this._oidc.publishEvent(e,s)}static get(e="default"){return new M(R.get(e))}tryKeepExistingSessionAsync(){return this._oidc.tryKeepExistingSessionAsync()}loginAsync(e=void 0,s=null,t=!1,i=void 0,o=!1){return this._oidc.loginAsync(e,s,t,i,o)}logoutAsync(e=void 0,s=null){return this._oidc.logoutAsync(e,s)}silentLoginCallbackAsync(){return this._oidc.silentLoginCallbackAsync()}renewTokensAsync(e=null){return this._oidc.renewTokensAsync(e)}loginCallbackAsync(){return this._oidc.loginCallbackWithAutoTokensRenewAsync()}get tokens(){return this._oidc.tokens}get configuration(){return this._oidc.configuration}async generateDemonstrationOfProofOfPossessionAsync(e,s,t){return this._oidc.generateDemonstrationOfProofOfPossessionAsync(e,s,t)}async getValidTokenAsync(e=200,s=50){return Re(this._oidc,e,s)}async userInfoAsync(e=!1){return this._oidc.userInfoAsync(e)}};M.getOrCreate=e=>(s,t="default")=>new M(R.getOrCreate(e)(s,t)),M.eventNames=R.eventNames;let re=M;x.OidcClient=re,x.TokenRenewMode=G,x.getFetchDefault=Ce,x.getParseQueryStringFromLocation=j,x.getPath=rn,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"})});
|
package/dist/initSession.d.ts
CHANGED
|
@@ -12,10 +12,14 @@ export declare const initSession: (configurationName: any, storage?: Storage) =>
|
|
|
12
12
|
getNonceAsync: () => Promise<{
|
|
13
13
|
nonce: any;
|
|
14
14
|
}>;
|
|
15
|
-
setLoginParams: (
|
|
16
|
-
getLoginParams: (
|
|
15
|
+
setLoginParams: (data: any) => void;
|
|
16
|
+
getLoginParams: () => any;
|
|
17
17
|
getStateAsync: () => Promise<any>;
|
|
18
18
|
setStateAsync: (state: string) => Promise<void>;
|
|
19
19
|
getCodeVerifierAsync: () => Promise<any>;
|
|
20
20
|
setCodeVerifierAsync: (codeVerifier: any) => Promise<void>;
|
|
21
|
+
setDemonstratingProofOfPossessionNonce: (dpopNonce: string) => void;
|
|
22
|
+
getDemonstratingProofOfPossessionNonce: () => any;
|
|
23
|
+
setDemonstratingProofOfPossessionJwkAsync: (jwk: any) => void;
|
|
24
|
+
getDemonstratingProofOfPossessionJwkAsync: () => any;
|
|
21
25
|
};
|
package/dist/initWorker.d.ts
CHANGED
|
@@ -19,10 +19,14 @@ export declare const initWorkerAsync: (serviceWorkerRelativeUrl: any, configurat
|
|
|
19
19
|
getNonceAsync: () => Promise<{
|
|
20
20
|
nonce: any;
|
|
21
21
|
}>;
|
|
22
|
-
setLoginParams: (
|
|
23
|
-
getLoginParams: (
|
|
22
|
+
setLoginParams: (data: any) => void;
|
|
23
|
+
getLoginParams: () => any;
|
|
24
24
|
getStateAsync: () => Promise<any>;
|
|
25
25
|
setStateAsync: (state: string) => Promise<unknown>;
|
|
26
26
|
getCodeVerifierAsync: () => Promise<any>;
|
|
27
27
|
setCodeVerifierAsync: (codeVerifier: string) => Promise<unknown>;
|
|
28
|
+
setDemonstratingProofOfPossessionNonce: (dpopNonce: string) => void;
|
|
29
|
+
getDemonstratingProofOfPossessionNonce: () => any;
|
|
30
|
+
setDemonstratingProofOfPossessionJwkAsync: (jwk: any) => void;
|
|
31
|
+
getDemonstratingProofOfPossessionJwkAsync: () => any;
|
|
28
32
|
}>;
|
package/dist/jwt.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare var JWT: {};
|
|
2
|
+
declare const EC: {};
|
|
3
|
+
export declare var JWK: {};
|
|
4
|
+
export declare const generateJwkAsync: () => any;
|
|
5
|
+
export declare const generateJwtDemonstratingProofOfPossessionAsync: (jwk: any, method: string, url: string, extrasClaims?: {}) => any;
|
|
6
|
+
export default EC;
|
package/dist/login.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OidcConfiguration, StringMap } from './types.js';
|
|
2
|
-
export declare const defaultLoginAsync: (window: any, configurationName:
|
|
2
|
+
export declare const defaultLoginAsync: (window: any, configurationName: string, configuration: OidcConfiguration, publishEvent: (string: any, any: any) => void, initAsync: Function) => (callbackPath?: string, extras?: StringMap, isSilentSignin?: boolean, scope?: string) => Promise<void>;
|
|
3
3
|
export declare const loginCallbackAsync: (oidc: any) => (isSilentSignin?: boolean) => Promise<{
|
|
4
4
|
tokens: import("./parseTokens.js").Tokens;
|
|
5
5
|
state: string;
|
package/dist/oidc.d.ts
CHANGED
|
@@ -78,6 +78,7 @@ export declare class Oidc {
|
|
|
78
78
|
loginCallbackPromise: Promise<any>;
|
|
79
79
|
loginCallbackAsync(isSilenSignin?: boolean): Promise<any>;
|
|
80
80
|
synchroniseTokensAsync(refreshToken: any, index: number, forceRefresh: boolean, extras: StringMap, updateTokens: any): any;
|
|
81
|
+
generateDemonstrationOfProofOfPossessionAsync(accessToken: string, url: string, method: string): Promise<string>;
|
|
81
82
|
syncTokensInfoAsync(configuration: any, configurationName: any, currentTokens: any, forceRefresh?: boolean): Promise<{
|
|
82
83
|
tokens: any;
|
|
83
84
|
status: string;
|
package/dist/oidcClient.d.ts
CHANGED
|
@@ -48,6 +48,7 @@ export declare class OidcClient {
|
|
|
48
48
|
loginCallbackAsync(): Promise<LoginCallback>;
|
|
49
49
|
get tokens(): Tokens;
|
|
50
50
|
get configuration(): OidcConfiguration;
|
|
51
|
+
generateDemonstrationOfProofOfPossessionAsync(accessToken: string, url: string, method: string): Promise<string>;
|
|
51
52
|
getValidTokenAsync(waitMs?: number, numberWait?: number): Promise<ValidToken>;
|
|
52
53
|
userInfoAsync<T extends OidcUserInfo = OidcUserInfo>(noCache?: boolean): Promise<T>;
|
|
53
54
|
}
|
package/dist/requests.d.ts
CHANGED
|
@@ -8,17 +8,15 @@ export declare const TOKEN_TYPE: {
|
|
|
8
8
|
export declare const performRevocationRequestAsync: (fetch: any) => (url: any, token: any, token_type: string, client_id: any, timeoutMs?: number) => Promise<{
|
|
9
9
|
success: boolean;
|
|
10
10
|
}>;
|
|
11
|
-
|
|
11
|
+
type PerformTokenRequestResponse = {
|
|
12
12
|
success: boolean;
|
|
13
|
-
status
|
|
14
|
-
data?:
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
status?: undefined;
|
|
19
|
-
}>;
|
|
13
|
+
status?: number;
|
|
14
|
+
data?: any;
|
|
15
|
+
demonstratingProofOfPossessionNonce?: string;
|
|
16
|
+
};
|
|
17
|
+
export declare const performTokenRequestAsync: (fetch: Fetch) => (url: string, details: any, extras: any, oldTokens: any, headersExtras: {}, tokenRenewMode: string, timeoutMs?: number) => Promise<PerformTokenRequestResponse>;
|
|
20
18
|
export declare const performAuthorizationRequestAsync: (storage: any) => (url: any, extras: StringMap) => Promise<void>;
|
|
21
|
-
export declare const performFirstTokenRequestAsync: (storage: any) => (url: any,
|
|
19
|
+
export declare const performFirstTokenRequestAsync: (storage: any) => (url: any, formBodyExtras: any, headersExtras: any, tokenRenewMode: string, timeoutMs?: number) => Promise<{
|
|
22
20
|
success: boolean;
|
|
23
21
|
status: number;
|
|
24
22
|
data?: undefined;
|
|
@@ -27,6 +25,8 @@ export declare const performFirstTokenRequestAsync: (storage: any) => (url: any,
|
|
|
27
25
|
data: {
|
|
28
26
|
state: any;
|
|
29
27
|
tokens: import("./parseTokens.js").Tokens;
|
|
28
|
+
demonstratingProofOfPossessionNonce: string;
|
|
30
29
|
};
|
|
31
30
|
status?: undefined;
|
|
32
31
|
}>;
|
|
32
|
+
export {};
|
package/dist/types.d.ts
CHANGED
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,KAAK,GAAG,OAAO,MAAM,CAAC,KAAK,CAAC;AAExC,MAAM,MAAM,WAAW,GAAG,cAAc,GAAG,eAAe,CAAC;AAE3D,MAAM,MAAM,kCAAkC,GAAG,CAAC,YAAY,EAAC,GAAG,EAAE,aAAa,EAAC,QAAQ,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAE7G,MAAM,MAAM,iBAAiB,GAAG;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,mBAAmB,CAAC,EAAC,MAAM,CAAC;IAC5B,gBAAgB,CAAC,EAAC,MAAM,CAAC;IACzB,oBAAoB,CAAC,EAAC,MAAM,CAAC;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,0CAA0C,CAAC,EAAE,MAAM,CAAC;IACpD,4CAA4C,CAAC,EAAE,MAAM,CAAC;IACtD,uBAAuB,CAAC,EAAE,sBAAsB,CAAC;IACjD,+CAA+C,CAAC,EAAE,MAAM,CAAC;IACzD,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,2BAA2B,CAAC,EAAC,MAAM,CAAC;IACpC,mBAAmB,CAAC,EAAC,OAAO,CAAC;IAC7B,2CAA2C,CAAC,EAAC,OAAO,CAAC;IACrD,sCAAsC,CAAC,EAAC,kCAAkC,CAAC;IAC3E,MAAM,CAAC,EAAC,SAAS,CAAC;IAClB,oBAAoB,CAAC,EAAC,SAAS,CAAC;IAChC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,2BAA2B,CAAC,EAAC,KAAK,CAAC,WAAW,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,KAAK,GAAG,OAAO,MAAM,CAAC,KAAK,CAAC;AAExC,MAAM,MAAM,WAAW,GAAG,cAAc,GAAG,eAAe,CAAC;AAE3D,MAAM,MAAM,kCAAkC,GAAG,CAAC,YAAY,EAAC,GAAG,EAAE,aAAa,EAAC,QAAQ,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAE7G,MAAM,MAAM,iBAAiB,GAAG;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,mBAAmB,CAAC,EAAC,MAAM,CAAC;IAC5B,gBAAgB,CAAC,EAAC,MAAM,CAAC;IACzB,oBAAoB,CAAC,EAAC,MAAM,CAAC;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,0CAA0C,CAAC,EAAE,MAAM,CAAC;IACpD,4CAA4C,CAAC,EAAE,MAAM,CAAC;IACtD,uBAAuB,CAAC,EAAE,sBAAsB,CAAC;IACjD,+CAA+C,CAAC,EAAE,MAAM,CAAC;IACzD,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,2BAA2B,CAAC,EAAC,MAAM,CAAC;IACpC,mBAAmB,CAAC,EAAC,OAAO,CAAC;IAC7B,2CAA2C,CAAC,EAAC,OAAO,CAAC;IACrD,sCAAsC,CAAC,EAAC,kCAAkC,CAAC;IAC3E,MAAM,CAAC,EAAC,SAAS,CAAC;IAClB,oBAAoB,CAAC,EAAC,SAAS,CAAC;IAChC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,2BAA2B,CAAC,EAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAChD,iCAAiC,CAAC,EAAC,OAAO,CAAC;CAC9C,CAAC;AAEF,MAAM,WAAW,SAAS;IACtB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,sBAAsB;IACnC,sBAAsB,EAAE,MAAM,CAAC;IAC/B,cAAc,EAAE,MAAM,CAAC;IACvB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,oBAAoB,CAAC,EAAC,MAAM,CAAC;IAC7B,MAAM,EAAC,MAAM,CAAC;CACjB"}
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
declare const _default: "7.
|
|
1
|
+
declare const _default: "7.5.0";
|
|
2
2
|
export default _default;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@axa-fr/oidc-client",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.5.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.umd.cjs",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"url": "https://github.com/AxaFrance/oidc-client.git"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@axa-fr/oidc-client-service-worker": "7.
|
|
23
|
+
"@axa-fr/oidc-client-service-worker": "7.5.0"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
26
|
"@testing-library/dom": "^9.3.1",
|
package/src/crypto.ts
CHANGED
|
@@ -44,7 +44,16 @@ export function textEncodeLite(str: string) {
|
|
|
44
44
|
}
|
|
45
45
|
return bufView;
|
|
46
46
|
}
|
|
47
|
-
|
|
47
|
+
|
|
48
|
+
export function base64urlOfHashOfASCIIEncodingAsync(code: string):Promise<string> {
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
crypto.subtle.digest('SHA-256', textEncodeLite(code)).then(buffer => {
|
|
51
|
+
return resolve(urlSafe(new Uint8Array(buffer)));
|
|
52
|
+
}, error => reject(error));
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const deriveChallengeAsync = (code: string): Promise<string> => {
|
|
48
57
|
if (code.length < 43 || code.length > 128) {
|
|
49
58
|
return Promise.reject(new Error('Invalid code length.'));
|
|
50
59
|
}
|
|
@@ -53,9 +62,5 @@ export function textEncodeLite(str: string) {
|
|
|
53
62
|
return Promise.reject(new Error('window.crypto.subtle is unavailable.'));
|
|
54
63
|
}
|
|
55
64
|
|
|
56
|
-
return
|
|
57
|
-
crypto.subtle.digest('SHA-256', textEncodeLite(code)).then(buffer => {
|
|
58
|
-
return resolve(urlSafe(new Uint8Array(buffer)));
|
|
59
|
-
}, error => reject(error));
|
|
60
|
-
});
|
|
65
|
+
return base64urlOfHashOfASCIIEncodingAsync(code);
|
|
61
66
|
};
|
package/src/initSession.ts
CHANGED
|
@@ -26,12 +26,28 @@ export const initSession = (configurationName, storage = sessionStorage) => {
|
|
|
26
26
|
};
|
|
27
27
|
|
|
28
28
|
const setNonceAsync = (nonce) => {
|
|
29
|
-
|
|
29
|
+
storage[`oidc.nonce.${configurationName}`] = nonce.nonce;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const setDemonstratingProofOfPossessionJwkAsync = (jwk) => {
|
|
33
|
+
storage[`oidc.jwk.${configurationName}`] = JSON.stringify(jwk);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const getDemonstratingProofOfPossessionJwkAsync = () => {
|
|
37
|
+
return JSON.parse(storage[`oidc.jwk.${configurationName}`]);
|
|
30
38
|
};
|
|
31
39
|
|
|
32
40
|
const getNonceAsync = async () => {
|
|
33
41
|
// @ts-ignore
|
|
34
|
-
return { nonce:
|
|
42
|
+
return { nonce: storage[`oidc.nonce.${configurationName}`] };
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const setDemonstratingProofOfPossessionNonce = (dpopNonce:string) => {
|
|
46
|
+
storage[`oidc.dpop_nonce.${configurationName}`] = dpopNonce;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const getDemonstratingProofOfPossessionNonce = () => {
|
|
50
|
+
return storage[`oidc.dpop_nonce.${configurationName}`];
|
|
35
51
|
};
|
|
36
52
|
|
|
37
53
|
const getTokens = () => {
|
|
@@ -41,17 +57,17 @@ export const initSession = (configurationName, storage = sessionStorage) => {
|
|
|
41
57
|
return JSON.stringify({ tokens: JSON.parse(storage[`oidc.${configurationName}`]).tokens });
|
|
42
58
|
};
|
|
43
59
|
|
|
44
|
-
let getLoginParamsCache =
|
|
45
|
-
const setLoginParams = (
|
|
46
|
-
getLoginParamsCache = data;
|
|
60
|
+
let getLoginParamsCache = {};
|
|
61
|
+
const setLoginParams = (data) => {
|
|
62
|
+
getLoginParamsCache[configurationName] = data;
|
|
47
63
|
storage[`oidc.login.${configurationName}`] = JSON.stringify(data);
|
|
48
64
|
};
|
|
49
|
-
const getLoginParams = (
|
|
65
|
+
const getLoginParams = () => {
|
|
50
66
|
const dataString = storage[`oidc.login.${configurationName}`];
|
|
51
|
-
if (!getLoginParamsCache) {
|
|
52
|
-
getLoginParamsCache = JSON.parse(dataString);
|
|
67
|
+
if (!getLoginParamsCache[configurationName]) {
|
|
68
|
+
getLoginParamsCache[configurationName] = JSON.parse(dataString);
|
|
53
69
|
}
|
|
54
|
-
return getLoginParamsCache;
|
|
70
|
+
return getLoginParamsCache[configurationName];
|
|
55
71
|
};
|
|
56
72
|
|
|
57
73
|
const getStateAsync = async () => {
|
|
@@ -85,5 +101,9 @@ export const initSession = (configurationName, storage = sessionStorage) => {
|
|
|
85
101
|
setStateAsync,
|
|
86
102
|
getCodeVerifierAsync,
|
|
87
103
|
setCodeVerifierAsync,
|
|
104
|
+
setDemonstratingProofOfPossessionNonce,
|
|
105
|
+
getDemonstratingProofOfPossessionNonce,
|
|
106
|
+
setDemonstratingProofOfPossessionJwkAsync,
|
|
107
|
+
getDemonstratingProofOfPossessionJwkAsync,
|
|
88
108
|
};
|
|
89
109
|
};
|
package/src/initWorker.ts
CHANGED
|
@@ -250,7 +250,7 @@ export const initWorkerAsync = async(serviceWorkerRelativeUrl, configurationName
|
|
|
250
250
|
};
|
|
251
251
|
|
|
252
252
|
const setNonceAsync = (nonce) => {
|
|
253
|
-
sessionStorage[
|
|
253
|
+
sessionStorage[`oidc.nonce.${configurationName}`] = nonce.nonce;
|
|
254
254
|
return sendMessageAsync(registration)({ type: 'setNonce', data: { nonce }, configurationName });
|
|
255
255
|
};
|
|
256
256
|
const getNonceAsync = async () => {
|
|
@@ -259,25 +259,43 @@ export const initWorkerAsync = async(serviceWorkerRelativeUrl, configurationName
|
|
|
259
259
|
// @ts-ignore
|
|
260
260
|
let nonce = result.nonce;
|
|
261
261
|
if (!nonce) {
|
|
262
|
-
nonce = sessionStorage[
|
|
262
|
+
nonce = sessionStorage[`oidc.nonce.${configurationName}`];
|
|
263
263
|
console.warn('nonce not found in service worker, using sessionStorage');
|
|
264
264
|
}
|
|
265
265
|
return { nonce };
|
|
266
266
|
};
|
|
267
267
|
|
|
268
|
-
let getLoginParamsCache =
|
|
269
|
-
const setLoginParams = (
|
|
270
|
-
getLoginParamsCache = data;
|
|
268
|
+
let getLoginParamsCache = {};
|
|
269
|
+
const setLoginParams = (data) => {
|
|
270
|
+
getLoginParamsCache[configurationName] = data;
|
|
271
271
|
localStorage[`oidc.login.${configurationName}`] = JSON.stringify(data);
|
|
272
272
|
};
|
|
273
|
-
|
|
273
|
+
|
|
274
|
+
const getLoginParams = () => {
|
|
274
275
|
const dataString = localStorage[`oidc.login.${configurationName}`];
|
|
275
|
-
if (!getLoginParamsCache) {
|
|
276
|
-
getLoginParamsCache = JSON.parse(dataString);
|
|
276
|
+
if (!getLoginParamsCache[configurationName]) {
|
|
277
|
+
getLoginParamsCache[configurationName] = JSON.parse(dataString);
|
|
277
278
|
}
|
|
278
|
-
return getLoginParamsCache;
|
|
279
|
+
return getLoginParamsCache[configurationName];
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
const setDemonstratingProofOfPossessionNonce = (dpopNonce: string) => {
|
|
284
|
+
localStorage[`oidc.dpop_nonce.${configurationName}`] = dpopNonce;
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
const getDemonstratingProofOfPossessionNonce = () => {
|
|
288
|
+
return localStorage[`oidc.dpop_nonce.${configurationName}`];
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
const setDemonstratingProofOfPossessionJwkAsync = (jwk) => {
|
|
292
|
+
localStorage[`oidc.jwk.${configurationName}`] = JSON.stringify(jwk);
|
|
279
293
|
};
|
|
280
294
|
|
|
295
|
+
const getDemonstratingProofOfPossessionJwkAsync = () => {
|
|
296
|
+
return JSON.parse(localStorage[`oidc.jwk.${configurationName}`]);
|
|
297
|
+
};
|
|
298
|
+
|
|
281
299
|
const getStateAsync = async () => {
|
|
282
300
|
const result = await sendMessageAsync(registration)({ type: 'getState', data: null, configurationName });
|
|
283
301
|
// @ts-ignore
|
|
@@ -325,5 +343,9 @@ export const initWorkerAsync = async(serviceWorkerRelativeUrl, configurationName
|
|
|
325
343
|
setStateAsync,
|
|
326
344
|
getCodeVerifierAsync,
|
|
327
345
|
setCodeVerifierAsync,
|
|
346
|
+
setDemonstratingProofOfPossessionNonce,
|
|
347
|
+
getDemonstratingProofOfPossessionNonce,
|
|
348
|
+
setDemonstratingProofOfPossessionJwkAsync,
|
|
349
|
+
getDemonstratingProofOfPossessionJwkAsync,
|
|
328
350
|
};
|
|
329
351
|
};
|