@descope/web-js-sdk 1.48.1 → 1.48.2

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.
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jwt-decode"),n=require("@descope/core-js-sdk"),o=require("js-cookie"),i=require("@fingerprintjs/fingerprintjs-pro");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=r(n),a=r(o);const c="3.2.0",l="undefined"!=typeof window,d=Math.pow(2,31)-1,u=`https://descopecdn.com/npm/oidc-client-ts@${c}/dist/browser/oidc-client-ts.min.js`,p=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${c}/dist/browser/oidc-client-ts.min.js`;const f=["/v1/auth/refresh","/v1/auth/try-refresh","/v1/auth/me","/v1/auth/me/tenants","/v1/auth/me/history"];let g;const v=e=>{try{return t.jwtDecode(e).exp}catch(e){return null}},h=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:v(n)},w=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?v(o):void 0)},m=t=>{const{access_token:n,id_token:o,refresh_token:i,refresh_expire_in:r}=t,s=e.__rest(t,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:t.sessionJwt||n,idToken:o,refreshJwt:t.refreshJwt||i,sessionExpiration:t.sessionExpiration||w(t),cookieExpiration:t.cookieExpiration||h(t)},s)},y=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var i;return n[o]=[].concat((null===(i=e.hooks)||void 0===i?void 0:i[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},b=async e=>{if(!(null==e?void 0:e.ok))return{};const t=await(null==e?void 0:e.clone().json()),n=(null==t?void 0:t.authInfo)||t||{};return m(n)},k=()=>l&&!!window.descopeBridge,S=(e,t)=>{if(!((null==t?void 0:t.status)>=400&&(null==t?void 0:t.status)<500))return!1;const n=(null==e?void 0:e.path)||"";return f.includes(n)},_=void 0!==g||l&&void 0!==window.localStorage,O=(e,t)=>{var n,o;return null===(o=null===(n=g||l&&window.localStorage)||void 0===n?void 0:n.setItem)||void 0===o?void 0:o.call(n,e,t)},I=e=>{var t,n;return null===(n=null===(t=g||l&&window.localStorage)||void 0===t?void 0:t.getItem)||void 0===n?void 0:n.call(t,e)},x=e=>{var t,n;return null===(n=null===(t=g||l&&window.localStorage)||void 0===t?void 0:t.removeItem)||void 0===n?void 0:n.call(t,e)},j=e=>{var t,n,o,i,r;return null!==(r=null!==(n=null===(t=null==g?void 0:g.key)||void 0===t?void 0:t.call(g,e))&&void 0!==n?n:l&&(null===(i=null===(o=window.localStorage)||void 0===o?void 0:o.key)||void 0===i?void 0:i.call(o,e)))&&void 0!==r?r:null},D=(...e)=>{console.debug(...e)},T=(...e)=>{console.warn(...e)},U=(e,t)=>{let n;var o;return t>0?(n=1e3*t,D(`Using provided nextRefreshSeconds: ${t}s`)):n=((o=e)?o.getTime()-(new Date).getTime():0)-2e4,n>d&&(D(`Timeout is too large (${n}ms), setting it to ${d}ms`),n=d),n},C="DS",A="DSR",R="DSI",E="DSRCN";function $(e,t,n){if(t){const{cookieDomain:o,cookiePath:i,cookieSameSite:r,cookieExpiration:s,cookieSecure:c}=n,l=new Date(1e3*s),d=N(o);a.default.set(e,t,{path:i,domain:d?o:void 0,expires:l,sameSite:r,secure:c})}}function N(e){const t=window.location.hostname.split("."),n=null==e?void 0:e.split(".");return t.slice(-(null==n?void 0:n.length)).join(".")===e}const J=e=>(null==e?void 0:e.cookieName)||C,P=e=>(null==e?void 0:e.cookieName)||A;function q(e="",t){return a.default.get(P(t))||I(`${e}${A}`)||""}function K(e="",t){return a.default.get(J(t))||I(`${e}${C}`)||""}function L(e=""){return I(`${e}${R}`)||""}function V(e="",t,n,o){x(`${e}${A}`),x(`${e}${C}`),x(`${e}${R}`),x(`${e}${E}`);const i=J(t);a.default.remove(i,null==o?void 0:o.session);const r=P(n);a.default.remove(r,null==o?void 0:o.refresh)}const F=(e,t,n)=>o=>{const i=Object.assign(o,{token:o.token||q(e,t)});if(!n){const t=function(e=""){return I(`${e}${E}`)}(e);t&&(i.headers=Object.assign(Object.assign({},i.headers||{}),{"x-descope-refresh-cookie-name":t}))}const r=function(e=""){return I(`${e}DTD`)||""}(e);return r&&(i.headers=Object.assign(Object.assign({},i.headers||{}),{"x-descope-trusted-device-token":r})),i},M=l&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",W="vsid",H="vrid",B="fp",G=(e=!1)=>{const t=I(B);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},X=async(e,t=M)=>{try{if(G())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),o=new URL(t);o.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const r=new URL(t);r.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const s=r.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",a=i.load({apiKey:e,endpoint:[o.toString(),i.defaultEndpoint],scriptUrlPattern:[s,i.defaultScriptUrlPattern]}),c=await a,{requestId:l}=await c.get({linkedId:n}),d=((e,t)=>({[W]:e,[H]:t}))(n,l);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};O(B,JSON.stringify(t))})(d)}catch(e){console.warn("Could not load fingerprint",e)}},Z=e=>{const t=G(!0);return t&&e.body&&(e.body.fpData=t),e},Y="descopeFlowNonce",z="X-Descope-Flow-Nonce",Q="/v1/flow/start",ee="/v1/flow/next",te=(e,t=Y)=>`${t}${e}`,ne=(e,t=Y)=>{try{const n=te(e,t);x(n)}catch(e){console.error("Error removing flow nonce:",e)}},oe=e=>{var t;return(null===(t=/.*\|#\|(.*)/.exec(e))||void 0===t?void 0:t[1])||null},ie=e=>{var t;return e.path===ee&&(null===(t=e.body)||void 0===t?void 0:t.executionId)?oe(e.body.executionId):null},re="dls_last_user_login_id",se="dls_last_user_display_name",ae=e=>O(re,e),ce=()=>I(re),le=()=>I(se),de=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=ce(),r=le();i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r);return await e(...t)},ue=e=>t=>async(...n)=>{const o=await t(...n);return e||(x(re),x(se)),o};function pe(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const fe=(e,t,n,o)=>i=>async(...r)=>{const s=await i(...r);return V(e,t,n,null==o?void 0:o()),s};async function ge(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=be(n.publicKey.challenge),n.publicKey.user.id=be(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=be(e.id)})),n}(e),n=await navigator.credentials.create(t);return o=n,JSON.stringify({id:o.id,rawId:ke(o.rawId),type:o.type,response:{attestationObject:ke(o.response.attestationObject),clientDataJSON:ke(o.response.clientDataJSON)}});var o}async function ve(e){const t=me(e);return ye(await navigator.credentials.get(t))}async function he(e,t){const n=me(e);n.signal=t.signal,n.mediation="conditional";return ye(await navigator.credentials.get(n))}async function we(e=!1){var t,n;if(!l)return Promise.resolve(!1);if(k()){const e=null===(n=null===(t=window.descopeBridge)||void 0===t?void 0:t.hostInfo)||void 0===n?void 0:n.webauthn;if("boolean"==typeof e)return e}const o=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return o&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():o}function me(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=be(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=be(e.id)})),n}function ye(e){return JSON.stringify({id:e.id,rawId:ke(e.rawId),type:e.type,response:{authenticatorData:ke(e.response.authenticatorData),clientDataJSON:ke(e.response.clientDataJSON),signature:ke(e.response.signature),userHandle:e.response.userHandle?ke(e.response.userHandle):void 0}})}function be(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function ke(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var Se,_e=(Se=e=>({async signUp(t,n,o){const i=await e.webauthn.signUp.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await ge(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,r)},async signIn(t,n){const o=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!o.ok)return o;const i=await ve(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,i)},async signUpOrIn(t,n){var o;const i=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!i.ok)return i;if(null===(o=i.data)||void 0===o?void 0:o.create){const t=await ge(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,t)}{const t=await ve(i.data.options);return await e.webauthn.signIn.finish(i.data.transactionId,t)}},async update(t,n,o){const i=await e.webauthn.update.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await ge(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:ge,get:ve,isSupported:we,conditional:he}}),(...e)=>{const t=Se(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const Oe={config:"/fedcm/config"},Ie=()=>{if(window.crypto&&window.crypto.getRandomValues){const e=new Uint8Array(16);return window.crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}return Math.random().toString(36).substring(2)};async function xe(e,t){var n;try{await je(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function je(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=Ie(),s=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let n=document.getElementById("google-gsi-client-script");n||(n=document.createElement("script"),document.head.appendChild(n),n.async=!0,n.defer=!0,n.id="google-gsi-client-script",n.src="https://accounts.google.com/gsi/client"),n.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},n.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}(),a=await e.oauth.getOneTapClientId(t);if(!a.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const c=a.data.clientId;return new Promise((e=>{var a,l;const d=n=>{e({provider:t,nonce:r,credential:null==n?void 0:n.credential})};s.initialize(Object.assign(Object.assign({},n),{itp_support:null===(a=null==n?void 0:n.itp_support)||void 0===a||a,use_fedcm_for_prompt:null===(l=null==n?void 0:n.use_fedcm_for_prompt)||void 0===l||l,client_id:c,callback:d,nonce:r})),s.prompt((e=>{var t,n;if(i&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==i||i(n),void d()}if(o&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==o||o(t),void d()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!i.credential)return null;if(null==t?void 0:t.onCodeReceived){const o=await e.oauth.verifyOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!o.ok||!o.data)throw new Error("Failed to verify OneTap client ID for provider "+i.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,o.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+i.provider);null===(o=null==t?void 0:t.onAuthenticated)||void 0===o||o.call(t,n.data)}}var De=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await we(),o=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=o,e.flow.start(...t)}});const Te=()=>window.location.search.includes("code")&&window.location.search.includes("state");let Ue;const Ce=(e,t)=>new Promise(((n,o)=>{if(!e.length)return o(new Error("No URLs provided to loadScriptWithFallback"));const i=t();if(i)return n(i);const r=e.shift(),s=document.createElement("script");s.src=r,s.id=(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t).toString(16)})(r),s.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},s.addEventListener("error",(()=>{Ce(e,t),s.setAttribute("data-error","true")})),document.body.appendChild(s)}));const Ae=async(e,t,n)=>{Ue||(Ue=(async()=>{try{return require("oidc-client-ts")}catch(e){return Ce([u,p],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:i}=await Ue;if(!o)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=(null==n?void 0:n.redirectUri)||window.location.href;let s,a,c,l;if(null==n?void 0:n.issuer){if(!n.clientId)throw new Error("clientId is required when providing a custom issuer/authority");s=n.issuer,a=n.clientId,c=`${a}_user`,l="openid"}else(null==n?void 0:n.applicationId)?(s=e.httpClient.buildUrl(t),s=`${s}/${n.applicationId}`,a=t,c=`${a}_user`,l="openid email roles descope.custom_claims offline_access"):(s=e.httpClient.buildUrl(t),a=t,c=`${a}_user`,l="openid email roles descope.custom_claims offline_access");const d={authority:s,client_id:a,redirect_uri:r,response_type:"code",scope:(null==n?void 0:n.scope)||l,stateStore:new i({store:window.localStorage,prefix:a}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(d.redirect_uri=n.redirectUri),{client:new o(d),stateUserKey:c}},Re=(e,t,n)=>{const o=async()=>{let o,i;return o&&i||({client:o,stateUserKey:i}=await Ae(e,t,n)),{client:o,stateUserKey:i}},i=async(t="")=>{var n;const{client:i,stateUserKey:r}=await o(),s=await i.processSigninResponse(t||window.location.href);var a;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(s)))),O(r,JSON.stringify({id_token:(a=s).id_token,session_state:a.session_state,profile:a.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),s};return{loginWithRedirect:async(e={},t=!1)=>{const{client:n}=await o(),i=await n.createSigninRequest(e),{url:r}=i;return t||(window.location.href=r),{ok:!0,data:i}},finishLogin:i,finishLoginIfNeed:async(e="")=>{if(Te())return await i(e)},refreshToken:async t=>{var n;const{client:i,stateUserKey:r}=await o(),s=(e=>{const t=I(e);return t?JSON.parse(t):null})(r);if(!s)throw new Error("User not found in storage to refresh token");let a=t;if(!a){const t={};e.httpClient.hooks.beforeRequest(t),a=t.token}const c=await i.useRefreshToken({state:{refresh_token:a,session_state:s.session_state,profile:s.profile}});return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(c)))),c},logout:async(e,t=!1)=>{const{client:n,stateUserKey:i}=await o();e||(e={}),e.id_token_hint=e.id_token_hint||L(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await n.createSignoutRequest(e),{url:s}=r;return x(i),t||window.location.replace(s),r}}},Ee=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var n;return n=t.customStorage,g=n,e(t)}),(t=>n=>{var{fpKey:o,fpLoad:i}=n,r=e.__rest(n,["fpKey","fpLoad"]);return l?(o&&i&&X(o).catch((()=>null)),t(y(r,{beforeRequest:Z}))):t(r)}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.48.1"},t.baseHeaders)}))),(e=>t=>{const o=pe(),i=pe(),r=pe(),s=pe(),a=e(y(t,{afterRequest:async(e,t)=>{if(S(e,t))D("Session invalidated, notifying subscribers with empty values"),i.pub(null),r.pub(null),o.pub(null),s.pub(null);else{const e=await(async e=>{const t=await b(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)})(t);e&&r.pub(e);const{sessionJwt:n,sessionExpiration:a,claims:c}=await b(t);n&&i.pub(n),c&&s.pub(c),(a||n)&&o.pub(a||42)}}})),c=n.wrapWith(a,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return i.pub(null),r.pub(null),o.pub(null),s.pub(null),n}));return Object.assign(c,{onSessionTokenChange:i.sub,onUserChange:r.sub,onClaimsChange:s.sub,onIsAuthenticatedChange:e=>o.sub((t=>{e(!!t)}))})}),(t=>n=>{const{enableFlowNonce:o=!0,nonceStoragePrefix:i=Y}=n,r=e.__rest(n,["enableFlowNonce","nonceStoragePrefix"]);if(!o)return t(r);((e=Y)=>{try{if(!_)return;for(let i=0;i<(t=void 0,n=void 0,o=void 0,null!==(o=null!==(t=null==g?void 0:g.length)&&void 0!==t?t:l&&(null===(n=window.localStorage)||void 0===n?void 0:n.length))&&void 0!==o?o:0);i++){const t=j(i);if(t&&t.startsWith(e)){const e=I(t);if(e)try{JSON.parse(e).expiry<Date.now()&&x(t)}catch(e){x(t)}}}}catch(e){console.error("Error cleaning up expired nonces:",e)}var t,n,o})(i);return t(y(r,{afterRequest:async(e,t)=>{if(e.path!==Q&&e.path!==ee)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(z);let o=await t.clone().json().then((e=>(null==e?void 0:e.executionId)||null)).catch((()=>null));return o||(o=ie(e)),{nonce:n,executionId:oe(o)}}catch(e){return{nonce:null,executionId:null}}})(e,t);if(n&&o){((e,t,n,o=Y)=>{try{const i=te(e,o),r=n?172800:10800,s={value:t,expiry:Date.now()+1e3*r,isStart:n};O(i,JSON.stringify(s))}catch(e){console.error("Error setting flow nonce:",e)}})(o,n,e.path===Q,i)}},beforeRequest:e=>{if(e.path===ee){const t=ie(e);if(t){const n=((e,t=Y)=>{try{const n=te(e,t),o=I(n);if(!o)return null;const i=JSON.parse(o);return i.expiry<Date.now()?(ne(e,t),null):i.value}catch(e){return console.error("Error getting flow nonce:",e),null}})(t,i);n&&(e.headers=e.headers||{},e.headers[z]=n)}}return e}}))}),(o=>i=>{var{autoRefresh:r}=i,s=e.__rest(i,["autoRefresh"]);const a=!!r,c="object"==typeof r&&(null==r?void 0:r.customActivityTracking);if(!a||k())return Object.assign(o(s),{markUserActive:()=>{T("markUserActive() called but has no effect")}});const{clearAllTimers:d,setTimer:u}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let p,f,g=null,v=!1,h=!1;c&&(D("Activity-based refresh enabled"),g=(()=>{let e=!0;return{hadActivity:()=>e,reset:()=>{e=!1},markActive:()=>{e=!0}}})()),l&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&p&&new Date>p&&(D("Expiration time passed, refreshing session"),w.refresh(q()||f))}));const w=o(y(s,{afterRequest:async(e,n)=>{const{sessionJwt:o,refreshJwt:i,sessionExpiration:r,nextRefreshSeconds:s}=await b(n);if(S(e,n))D("Session invalidated, canceling all timers"),d();else if(o||r){if(p=((e,n)=>{if(n)return new Date(1e3*n);D("Could not extract expiration time from session token, trying to decode the token");try{const n=t.jwtDecode(e);if(n.exp)return new Date(1e3*n.exp)}catch(e){return null}})(o,r),!p)return void D("Could not extract expiration time from session token");f=i,v=s>0;const e=U(p,s);if(d(),e<=2e4)return void D("Session is too close to expiration, not setting refresh timer");const n=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});D(`Setting refresh timer for ${n}. (${e}ms)`),g&&(g.reset(),h=!1),u((()=>{if(l&&"hidden"===document.visibilityState)D("Skipping refresh due to timer - document is hidden");else{if(g&&v&&!g.hadActivity())return D("Skipping refresh due to timer - user is idle"),void(h=!0);D("Refreshing session due to timer"),w.refresh(q()||i)}}),e)}}}));return Object.assign(n.wrapWith(w,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return D("Clearing all timers"),d(),n})),{markUserActive:g?()=>{D("markUserActive() called"),v||D("markUserActive() called but server does not have inactivity timeout configured (no nextRefreshSeconds)"),g.markActive(),h&&(D("User became active after skipped refresh, triggering refresh"),h=!1,d(),w.refresh(q()||f))}:()=>{T("markUserActive() called but customActivityTracking is not enabled — this call has no effect")}})}),(t=>o=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:r=!1}=o,s=e.__rest(o,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(t(s),{getLastUserLoginId:ce,getLastUserDisplayName:le});const a=t(y(s,{afterRequest:async(e,t)=>{var n;const{userInfo:o,lastAuth:i}=await(async e=>{if(!(null==e?void 0:e.ok))return{userInfo:void 0,lastAuth:void 0};const t=await(null==e?void 0:e.clone().json()),n=m((null==t?void 0:t.authInfo)||t||{});return{userInfo:(null==n?void 0:n.user)||((null==n?void 0:n.hasOwnProperty("userId"))?n:void 0),lastAuth:t.lastAuth}})(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],s=null==o?void 0:o.name;r?(ae(r),(e=>{O(se,e)})(s)):(null==i?void 0:i.loginId)&&ae(i.loginId)}}));let c=n.wrapWith(a,["flow.start"],de);return c=n.wrapWith(c,["logout","logoutAll"],ue(r)),Object.assign(c,{getLastUserLoginId:ce,getLastUserDisplayName:le})}),(t=>o=>{var{persistTokens:i,sessionTokenViaCookie:r,refreshTokenViaCookie:s,storagePrefix:c,refreshCookieName:d}=o,u=e.__rest(o,["persistTokens","sessionTokenViaCookie","refreshTokenViaCookie","storagePrefix","refreshCookieName"]);if(!i||!l)return t(Object.assign({refreshCookieName:d},u));let p;const f=t(y(Object.assign({refreshCookieName:d},u),{beforeRequest:F(c,s,d),afterRequest:async(e,t)=>{if(S(e,t))D("Session invalidated, clearing persisted tokens"),V(c,r,s,p);else{const e=await b(t);e.cookieName?O(`${c||""}${E}`,e.cookieName):e.refreshJwt&&x(`${c||""}${E}`);const n=((e={},t=!1,n="",o=!1)=>{var i,r,s,c;const{sessionJwt:l,refreshJwt:d,trustedDeviceJwt:u}=e;let p;if(d)if(o){x(`${n}${A}`);const t=o.sameSite||"Strict",s=null===(i=o.secure)||void 0===i||i,a=null!==(r=o.domain)&&void 0!==r?r:e.cookieDomain,c=P(o);s&&"https:"!==window.location.protocol&&T("Refresh token cookie is configured with secure=true but the page is not using HTTPS. The cookie will not be set. To fix this, pass refreshTokenViaCookie: { secure: process.env['NODE_ENV'] !== 'development' }");const l=Object.assign(Object.assign({},e),{cookieSameSite:t,cookieSecure:s,cookieDomain:a});$(c,d,l);const u=N(a);p=Object.assign(Object.assign({},p),{refresh:{path:l.cookiePath,domain:u?a:void 0}})}else{const e=P(o);a.default.remove(e),O(`${n}${A}`,d)}if(l)if(t){const n=t.sameSite||"Strict",o=null===(s=t.secure)||void 0===s||s,i=null!==(c=t.domain)&&void 0!==c?c:e.cookieDomain,r=J(t);o&&"https:"!==window.location.protocol&&T("Session token cookie is configured with secure=true but the page is not using HTTPS. The cookie will not be set. To fix this, pass sessionTokenViaCookie: { secure: process.env['NODE_ENV'] !== 'development' }");const a=Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:o,cookieDomain:i});$(r,l,a);const d=N(i);p=Object.assign(Object.assign({},p),{session:{path:a.cookiePath,domain:d?i:void 0}})}else O(`${n}${C}`,l);return e.idToken&&O(`${n}${R}`,e.idToken),u&&O(`${n}DTD`,u),p})(e,r,c,s);n&&(p=n)}}})),g=n.wrapWith(f,["logout","logoutAll","oidc.logout"],fe(c,r,s,(()=>p)));return Object.assign(g,{getRefreshToken:()=>q(c,s),getSessionToken:()=>K(c,r),getIdToken:()=>L(c)})}))((e=>{const t=s.default(e),n=Re(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async(o,i)=>{var r;if(k())return D(`Refresh called in native flow: ${(new Error).stack}`),Promise.resolve({ok:!1,error:{errorCode:"J171000",errorDescription:"Refresh is not supported in native flows via the web SDK"}});if(e.oidcConfig)try{return await n.refreshToken(o),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const s=K(),a=q();let c="";if(e.getExternalToken)try{c=await(null===(r=e.getExternalToken)||void 0===r?void 0:r.call(e))}catch(e){D("Error getting external token while refreshing",e)}return t.refresh(o,{dcs:s?"t":"f",dcr:a?"t":"f"},c,i)},logout:async o=>{if(e.oidcConfig)try{return await n.logout({id_token_hint:o}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(o)},flow:De(t),webauthn:_e(t),fedcm:(o=t,i=e.projectId,{onetap:{requestExchangeCode(e){xe(o,e)},requestAuthentication(e){xe(o,e)}},async oneTap(e,t,n,i,r){await je(o,{provider:e,oneTapConfig:t,loginOptions:n,onSkipped:i,onDismissed:r})},async launch(e){var t;const n={identity:{context:e||"signin",providers:[{configURL:o.httpClient.buildUrl(i+Oe.config),clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return o.refresh(r.token)},isSupported:()=>l&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=o.httpClient.buildUrl(i+Oe.config);try{const o={identity:{context:e||"signin",providers:[{configURL:n,clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(o));return!!r&&!!r.token}catch(e){return!1}}}),oidc:n});var o,i}));exports.REFRESH_TOKEN_KEY=A,exports.SESSION_TOKEN_KEY=C,exports.clearFingerprintData=()=>{x(B)},exports.createSdk=Ee,exports.default=Ee,exports.ensureFingerprintIds=X,exports.getSessionToken=K,exports.hasOidcParamsInUrl=Te;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),t=require("jwt-decode"),n=require("@descope/core-js-sdk"),o=require("js-cookie"),i=require("@fingerprintjs/fingerprintjs-pro");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=r(n),a=r(o);const c="3.2.0",l="undefined"!=typeof window,d=Math.pow(2,31)-1,u=`https://descopecdn.com/npm/oidc-client-ts@${c}/dist/browser/oidc-client-ts.min.js`,p=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${c}/dist/browser/oidc-client-ts.min.js`;const f=["/v1/auth/refresh","/v1/auth/try-refresh","/v1/auth/me","/v1/auth/me/tenants","/v1/auth/me/history"];let g;const v=e=>{try{return t.jwtDecode(e).exp}catch(e){return null}},h=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:v(n)},w=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?v(o):void 0)},m=t=>{const{access_token:n,id_token:o,refresh_token:i,refresh_expire_in:r}=t,s=e.__rest(t,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:t.sessionJwt||n,idToken:o,refreshJwt:t.refreshJwt||i,sessionExpiration:t.sessionExpiration||w(t),cookieExpiration:t.cookieExpiration||h(t)},s)},y=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var i;return n[o]=[].concat((null===(i=e.hooks)||void 0===i?void 0:i[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},b=async e=>{if(!(null==e?void 0:e.ok))return{};const t=await(null==e?void 0:e.clone().json()),n=(null==t?void 0:t.authInfo)||t||{};return m(n)},k=()=>l&&!!window.descopeBridge,S=(e,t)=>{if(!((null==t?void 0:t.status)>=400&&(null==t?void 0:t.status)<500))return!1;const n=(null==e?void 0:e.path)||"";return f.includes(n)},_=void 0!==g||l&&void 0!==window.localStorage,O=(e,t)=>{var n,o;return null===(o=null===(n=g||l&&window.localStorage)||void 0===n?void 0:n.setItem)||void 0===o?void 0:o.call(n,e,t)},I=e=>{var t,n;return null===(n=null===(t=g||l&&window.localStorage)||void 0===t?void 0:t.getItem)||void 0===n?void 0:n.call(t,e)},x=e=>{var t,n;return null===(n=null===(t=g||l&&window.localStorage)||void 0===t?void 0:t.removeItem)||void 0===n?void 0:n.call(t,e)},j=e=>{var t,n,o,i,r;return null!==(r=null!==(n=null===(t=null==g?void 0:g.key)||void 0===t?void 0:t.call(g,e))&&void 0!==n?n:l&&(null===(i=null===(o=window.localStorage)||void 0===o?void 0:o.key)||void 0===i?void 0:i.call(o,e)))&&void 0!==r?r:null},D=(...e)=>{console.debug(...e)},T=(...e)=>{console.warn(...e)},U=(e,t)=>{let n;var o;return t>0?(n=1e3*t,D(`Using provided nextRefreshSeconds: ${t}s`)):n=((o=e)?o.getTime()-(new Date).getTime():0)-2e4,n>d&&(D(`Timeout is too large (${n}ms), setting it to ${d}ms`),n=d),n},C="DS",A="DSR",R="DSI",E="DSRCN";function $(e,t,n){if(t){const{cookieDomain:o,cookiePath:i,cookieSameSite:r,cookieExpiration:s,cookieSecure:c}=n,l=new Date(1e3*s),d=N(o);a.default.set(e,t,{path:i,domain:d?o:void 0,expires:l,sameSite:r,secure:c})}}function N(e){const t=window.location.hostname.split("."),n=null==e?void 0:e.split(".");return t.slice(-(null==n?void 0:n.length)).join(".")===e}const J=e=>(null==e?void 0:e.cookieName)||C,P=e=>(null==e?void 0:e.cookieName)||A;function q(e="",t){return a.default.get(P(t))||I(`${e}${A}`)||""}function K(e="",t){return a.default.get(J(t))||I(`${e}${C}`)||""}function L(e=""){return I(`${e}${R}`)||""}function V(e="",t,n,o){x(`${e}${A}`),x(`${e}${C}`),x(`${e}${R}`),x(`${e}${E}`);const i=J(t);a.default.remove(i,null==o?void 0:o.session);const r=P(n);a.default.remove(r,null==o?void 0:o.refresh)}const F=(e,t,n)=>o=>{const i=Object.assign(o,{token:o.token||q(e,t)});if(!n){const t=function(e=""){return I(`${e}${E}`)}(e);t&&(i.headers=Object.assign(Object.assign({},i.headers||{}),{"x-descope-refresh-cookie-name":t}))}const r=function(e=""){return I(`${e}DTD`)||""}(e);return r&&(i.headers=Object.assign(Object.assign({},i.headers||{}),{"x-descope-trusted-device-token":r})),i},M=l&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",W="vsid",H="vrid",B="fp",G=(e=!1)=>{const t=I(B);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},X=async(e,t=M)=>{try{if(G())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),o=new URL(t);o.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const r=new URL(t);r.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const s=r.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",a=i.load({apiKey:e,endpoint:[o.toString(),i.defaultEndpoint],scriptUrlPattern:[s,i.defaultScriptUrlPattern]}),c=await a,{requestId:l}=await c.get({linkedId:n}),d=((e,t)=>({[W]:e,[H]:t}))(n,l);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};O(B,JSON.stringify(t))})(d)}catch(e){console.warn("Could not load fingerprint",e)}},Z=e=>{const t=G(!0);return t&&e.body&&(e.body.fpData=t),e},Y="descopeFlowNonce",z="X-Descope-Flow-Nonce",Q="/v1/flow/start",ee="/v1/flow/next",te=(e,t=Y)=>`${t}${e}`,ne=(e,t=Y)=>{try{const n=te(e,t);x(n)}catch(e){console.error("Error removing flow nonce:",e)}},oe=e=>{var t;return(null===(t=/.*\|#\|(.*)/.exec(e))||void 0===t?void 0:t[1])||null},ie=e=>{var t;return e.path===ee&&(null===(t=e.body)||void 0===t?void 0:t.executionId)?oe(e.body.executionId):null},re="dls_last_user_login_id",se="dls_last_user_display_name",ae=e=>O(re,e),ce=()=>I(re),le=()=>I(se),de=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=ce(),r=le();i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r);return await e(...t)},ue=e=>t=>async(...n)=>{const o=await t(...n);return e||(x(re),x(se)),o};function pe(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const fe=(e,t,n,o)=>i=>async(...r)=>{const s=await i(...r);return V(e,t,n,null==o?void 0:o()),s};async function ge(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=be(n.publicKey.challenge),n.publicKey.user.id=be(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=be(e.id)})),n}(e),n=await navigator.credentials.create(t);return o=n,JSON.stringify({id:o.id,rawId:ke(o.rawId),type:o.type,response:{attestationObject:ke(o.response.attestationObject),clientDataJSON:ke(o.response.clientDataJSON)}});var o}async function ve(e){const t=me(e);return ye(await navigator.credentials.get(t))}async function he(e,t){const n=me(e);n.signal=t.signal,n.mediation="conditional";return ye(await navigator.credentials.get(n))}async function we(e=!1){var t,n;if(!l)return Promise.resolve(!1);if(k()){const e=null===(n=null===(t=window.descopeBridge)||void 0===t?void 0:t.hostInfo)||void 0===n?void 0:n.webauthn;if("boolean"==typeof e)return e}const o=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return o&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():o}function me(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=be(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=be(e.id)})),n}function ye(e){return JSON.stringify({id:e.id,rawId:ke(e.rawId),type:e.type,response:{authenticatorData:ke(e.response.authenticatorData),clientDataJSON:ke(e.response.clientDataJSON),signature:ke(e.response.signature),userHandle:e.response.userHandle?ke(e.response.userHandle):void 0}})}function be(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function ke(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var Se,_e=(Se=e=>({async signUp(t,n,o){const i=await e.webauthn.signUp.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await ge(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,r)},async signIn(t,n){const o=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!o.ok)return o;const i=await ve(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,i)},async signUpOrIn(t,n){var o;const i=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!i.ok)return i;if(null===(o=i.data)||void 0===o?void 0:o.create){const t=await ge(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,t)}{const t=await ve(i.data.options);return await e.webauthn.signIn.finish(i.data.transactionId,t)}},async update(t,n,o){const i=await e.webauthn.update.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await ge(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:ge,get:ve,isSupported:we,conditional:he}}),(...e)=>{const t=Se(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const Oe={config:"/fedcm/config"},Ie=()=>{if(window.crypto&&window.crypto.getRandomValues){const e=new Uint8Array(16);return window.crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}return Math.random().toString(36).substring(2)};async function xe(e,t){var n;try{await je(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function je(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=Ie(),s=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let n=document.getElementById("google-gsi-client-script");n||(n=document.createElement("script"),document.head.appendChild(n),n.async=!0,n.defer=!0,n.id="google-gsi-client-script",n.src="https://accounts.google.com/gsi/client"),n.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},n.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}(),a=await e.oauth.getOneTapClientId(t);if(!a.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const c=a.data.clientId;return new Promise((e=>{var a,l;const d=n=>{e({provider:t,nonce:r,credential:null==n?void 0:n.credential})};s.initialize(Object.assign(Object.assign({},n),{itp_support:null===(a=null==n?void 0:n.itp_support)||void 0===a||a,use_fedcm_for_prompt:null===(l=null==n?void 0:n.use_fedcm_for_prompt)||void 0===l||l,client_id:c,callback:d,nonce:r})),s.prompt((e=>{var t,n;if(i&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==i||i(n),void d()}if(o&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==o||o(t),void d()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!i.credential)return null;if(null==t?void 0:t.onCodeReceived){const o=await e.oauth.verifyOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!o.ok||!o.data)throw new Error("Failed to verify OneTap client ID for provider "+i.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,o.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+i.provider);null===(o=null==t?void 0:t.onAuthenticated)||void 0===o||o.call(t,n.data)}}var De=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await we(),o=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=o,e.flow.start(...t)}});const Te=()=>window.location.search.includes("code")&&window.location.search.includes("state");let Ue;const Ce=(e,t)=>new Promise(((n,o)=>{if(!e.length)return o(new Error("No URLs provided to loadScriptWithFallback"));const i=t();if(i)return n(i);const r=e.shift(),s=document.createElement("script");s.src=r,s.id=(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t).toString(16)})(r),s.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},s.addEventListener("error",(()=>{Ce(e,t),s.setAttribute("data-error","true")})),document.body.appendChild(s)}));const Ae=async(e,t,n)=>{Ue||(Ue=(async()=>{try{return require("oidc-client-ts")}catch(e){return Ce([u,p],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:i}=await Ue;if(!o)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=(null==n?void 0:n.redirectUri)||window.location.href;let s,a,c,l;if(null==n?void 0:n.issuer){if(!n.clientId)throw new Error("clientId is required when providing a custom issuer/authority");s=n.issuer,a=n.clientId,c=`${a}_user`,l="openid"}else(null==n?void 0:n.applicationId)?(s=e.httpClient.buildUrl(t),s=`${s}/${n.applicationId}`,a=t,c=`${a}_user`,l="openid email roles descope.custom_claims offline_access"):(s=e.httpClient.buildUrl(t),a=t,c=`${a}_user`,l="openid email roles descope.custom_claims offline_access");const d={authority:s,client_id:a,redirect_uri:r,response_type:"code",scope:(null==n?void 0:n.scope)||l,stateStore:new i({store:window.localStorage,prefix:a}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(d.redirect_uri=n.redirectUri),{client:new o(d),stateUserKey:c}},Re=(e,t,n)=>{const o=async()=>{let o,i;return o&&i||({client:o,stateUserKey:i}=await Ae(e,t,n)),{client:o,stateUserKey:i}},i=async(t="")=>{var n;const{client:i,stateUserKey:r}=await o(),s=await i.processSigninResponse(t||window.location.href);var a;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(s)))),O(r,JSON.stringify({id_token:(a=s).id_token,session_state:a.session_state,profile:a.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),s};return{loginWithRedirect:async(e={},t=!1)=>{const{client:n}=await o(),i=await n.createSigninRequest(e),{url:r}=i;return t||(window.location.href=r),{ok:!0,data:i}},finishLogin:i,finishLoginIfNeed:async(e="")=>{if(Te())return await i(e)},refreshToken:async t=>{var n;const{client:i,stateUserKey:r}=await o(),s=(e=>{const t=I(e);return t?JSON.parse(t):null})(r);if(!s)throw new Error("User not found in storage to refresh token");let a=t;if(!a){const t={};e.httpClient.hooks.beforeRequest(t),a=t.token}const c=await i.useRefreshToken({state:{refresh_token:a,session_state:s.session_state,profile:s.profile}});return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(c)))),c},logout:async(e,t=!1)=>{const{client:n,stateUserKey:i}=await o();e||(e={}),e.id_token_hint=e.id_token_hint||L(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await n.createSignoutRequest(e),{url:s}=r;return x(i),t||window.location.replace(s),r}}},Ee=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var n;return n=t.customStorage,g=n,e(t)}),(t=>n=>{var{fpKey:o,fpLoad:i}=n,r=e.__rest(n,["fpKey","fpLoad"]);return l?(o&&i&&X(o).catch((()=>null)),t(y(r,{beforeRequest:Z}))):t(r)}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.48.2"},t.baseHeaders)}))),(e=>t=>{const o=pe(),i=pe(),r=pe(),s=pe(),a=e(y(t,{afterRequest:async(e,t)=>{if(S(e,t))D("Session invalidated, notifying subscribers with empty values"),i.pub(null),r.pub(null),o.pub(null),s.pub(null);else{const e=await(async e=>{const t=await b(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)})(t);e&&r.pub(e);const{sessionJwt:n,sessionExpiration:a,claims:c}=await b(t);n&&i.pub(n),c&&s.pub(c),(a||n)&&o.pub(a||42)}}})),c=n.wrapWith(a,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return i.pub(null),r.pub(null),o.pub(null),s.pub(null),n}));return Object.assign(c,{onSessionTokenChange:i.sub,onUserChange:r.sub,onClaimsChange:s.sub,onIsAuthenticatedChange:e=>o.sub((t=>{e(!!t)}))})}),(t=>n=>{const{enableFlowNonce:o=!0,nonceStoragePrefix:i=Y}=n,r=e.__rest(n,["enableFlowNonce","nonceStoragePrefix"]);if(!o)return t(r);((e=Y)=>{try{if(!_)return;for(let i=0;i<(t=void 0,n=void 0,o=void 0,null!==(o=null!==(t=null==g?void 0:g.length)&&void 0!==t?t:l&&(null===(n=window.localStorage)||void 0===n?void 0:n.length))&&void 0!==o?o:0);i++){const t=j(i);if(t&&t.startsWith(e)){const e=I(t);if(e)try{JSON.parse(e).expiry<Date.now()&&x(t)}catch(e){x(t)}}}}catch(e){console.error("Error cleaning up expired nonces:",e)}var t,n,o})(i);return t(y(r,{afterRequest:async(e,t)=>{if(e.path!==Q&&e.path!==ee)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(z);let o=await t.clone().json().then((e=>(null==e?void 0:e.executionId)||null)).catch((()=>null));return o||(o=ie(e)),{nonce:n,executionId:oe(o)}}catch(e){return{nonce:null,executionId:null}}})(e,t);if(n&&o){((e,t,n,o=Y)=>{try{const i=te(e,o),r=n?172800:10800,s={value:t,expiry:Date.now()+1e3*r,isStart:n};O(i,JSON.stringify(s))}catch(e){console.error("Error setting flow nonce:",e)}})(o,n,e.path===Q,i)}},beforeRequest:e=>{if(e.path===ee){const t=ie(e);if(t){const n=((e,t=Y)=>{try{const n=te(e,t),o=I(n);if(!o)return null;const i=JSON.parse(o);return i.expiry<Date.now()?(ne(e,t),null):i.value}catch(e){return console.error("Error getting flow nonce:",e),null}})(t,i);n&&(e.headers=e.headers||{},e.headers[z]=n)}}return e}}))}),(o=>i=>{var{autoRefresh:r}=i,s=e.__rest(i,["autoRefresh"]);const a=!!r,c="object"==typeof r&&(null==r?void 0:r.customActivityTracking);if(!a||k())return Object.assign(o(s),{markUserActive:()=>{T("markUserActive() called but has no effect")}});const{clearAllTimers:d,setTimer:u}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let p,f,g=null,v=!1,h=!1;c&&(D("Activity-based refresh enabled"),g=(()=>{let e=!0;return{hadActivity:()=>e,reset:()=>{e=!1},markActive:()=>{e=!0}}})()),l&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&p&&new Date>p&&(D("Expiration time passed, refreshing session"),w.refresh(q()||f))}));const w=o(y(s,{afterRequest:async(e,n)=>{const{sessionJwt:o,refreshJwt:i,sessionExpiration:r,nextRefreshSeconds:s}=await b(n);if(S(e,n))D("Session invalidated, canceling all timers"),d();else if(o||r){if(p=((e,n)=>{if(n)return new Date(1e3*n);D("Could not extract expiration time from session token, trying to decode the token");try{const n=t.jwtDecode(e);if(n.exp)return new Date(1e3*n.exp)}catch(e){return null}})(o,r),!p)return void D("Could not extract expiration time from session token");f=i,v=s>0;const e=U(p,s);if(d(),e<=2e4)return void D("Session is too close to expiration, not setting refresh timer");const n=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});D(`Setting refresh timer for ${n}. (${e}ms)`),g&&(g.reset(),h=!1),u((()=>{if(l&&"hidden"===document.visibilityState)D("Skipping refresh due to timer - document is hidden");else{if(g&&v&&!g.hadActivity())return D("Skipping refresh due to timer - user is idle"),void(h=!0);D("Refreshing session due to timer"),w.refresh(q()||i)}}),e)}}}));return Object.assign(n.wrapWith(w,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return D("Clearing all timers"),d(),n})),{markUserActive:g?()=>{D("markUserActive() called"),v||D("markUserActive() called but server does not have inactivity timeout configured (no nextRefreshSeconds)"),g.markActive(),h&&(D("User became active after skipped refresh, triggering refresh"),h=!1,d(),w.refresh(q()||f))}:()=>{T("markUserActive() called but customActivityTracking is not enabled — this call has no effect")}})}),(t=>o=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:r=!1}=o,s=e.__rest(o,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(t(s),{getLastUserLoginId:ce,getLastUserDisplayName:le});const a=t(y(s,{afterRequest:async(e,t)=>{var n;const{userInfo:o,lastAuth:i}=await(async e=>{if(!(null==e?void 0:e.ok))return{userInfo:void 0,lastAuth:void 0};const t=await(null==e?void 0:e.clone().json()),n=m((null==t?void 0:t.authInfo)||t||{});return{userInfo:(null==n?void 0:n.user)||((null==n?void 0:n.hasOwnProperty("userId"))?n:void 0),lastAuth:t.lastAuth}})(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],s=null==o?void 0:o.name;r?(ae(r),(e=>{O(se,e)})(s)):(null==i?void 0:i.loginId)&&ae(i.loginId)}}));let c=n.wrapWith(a,["flow.start"],de);return c=n.wrapWith(c,["logout","logoutAll"],ue(r)),Object.assign(c,{getLastUserLoginId:ce,getLastUserDisplayName:le})}),(t=>o=>{var{persistTokens:i,sessionTokenViaCookie:r,refreshTokenViaCookie:s,storagePrefix:c,refreshCookieName:d}=o,u=e.__rest(o,["persistTokens","sessionTokenViaCookie","refreshTokenViaCookie","storagePrefix","refreshCookieName"]);if(!i||!l)return t(Object.assign({refreshCookieName:d},u));let p;const f=t(y(Object.assign({refreshCookieName:d},u),{beforeRequest:F(c,s,d),afterRequest:async(e,t)=>{if(S(e,t))D("Session invalidated, clearing persisted tokens"),V(c,r,s,p);else{const e=await b(t);e.cookieName?O(`${c||""}${E}`,e.cookieName):e.refreshJwt&&x(`${c||""}${E}`);const n=((e={},t=!1,n="",o=!1)=>{var i,r,s,c;const{sessionJwt:l,refreshJwt:d,trustedDeviceJwt:u}=e;let p;if(d)if(o){x(`${n}${A}`);const t=o.sameSite||"Strict",s=null===(i=o.secure)||void 0===i||i,a=null!==(r=o.domain)&&void 0!==r?r:e.cookieDomain,c=P(o);s&&"https:"!==window.location.protocol&&T("Refresh token cookie is configured with secure=true but the page is not using HTTPS. The cookie will not be set. To fix this, pass refreshTokenViaCookie: { secure: process.env['NODE_ENV'] !== 'development' }");const l=Object.assign(Object.assign({},e),{cookieSameSite:t,cookieSecure:s,cookieDomain:a});$(c,d,l);const u=N(a);p=Object.assign(Object.assign({},p),{refresh:{path:l.cookiePath,domain:u?a:void 0}})}else{const e=P(o);a.default.remove(e),O(`${n}${A}`,d)}if(l)if(t){const n=t.sameSite||"Strict",o=null===(s=t.secure)||void 0===s||s,i=null!==(c=t.domain)&&void 0!==c?c:e.cookieDomain,r=J(t);o&&"https:"!==window.location.protocol&&T("Session token cookie is configured with secure=true but the page is not using HTTPS. The cookie will not be set. To fix this, pass sessionTokenViaCookie: { secure: process.env['NODE_ENV'] !== 'development' }");const a=Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:o,cookieDomain:i});$(r,l,a);const d=N(i);p=Object.assign(Object.assign({},p),{session:{path:a.cookiePath,domain:d?i:void 0}})}else O(`${n}${C}`,l);return e.idToken&&O(`${n}${R}`,e.idToken),u&&O(`${n}DTD`,u),p})(e,r,c,s);n&&(p=n)}}})),g=n.wrapWith(f,["logout","logoutAll","oidc.logout"],fe(c,r,s,(()=>p)));return Object.assign(g,{getRefreshToken:()=>q(c,s),getSessionToken:()=>K(c,r),getIdToken:()=>L(c)})}))((e=>{const t=s.default(e),n=Re(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async(o,i)=>{var r;if(k())return D(`Refresh called in native flow: ${(new Error).stack}`),Promise.resolve({ok:!1,error:{errorCode:"J171000",errorDescription:"Refresh is not supported in native flows via the web SDK"}});if(e.oidcConfig)try{return await n.refreshToken(o),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const s=K(),a=q();let c="";if(e.getExternalToken)try{c=await(null===(r=e.getExternalToken)||void 0===r?void 0:r.call(e))}catch(e){D("Error getting external token while refreshing",e)}return t.refresh(o,{dcs:s?"t":"f",dcr:a?"t":"f"},c,i)},logout:async o=>{if(e.oidcConfig)try{return await n.logout({id_token_hint:o}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(o)},flow:De(t),webauthn:_e(t),fedcm:(o=t,i=e.projectId,{onetap:{requestExchangeCode(e){xe(o,e)},requestAuthentication(e){xe(o,e)}},async oneTap(e,t,n,i,r){await je(o,{provider:e,oneTapConfig:t,loginOptions:n,onSkipped:i,onDismissed:r})},async launch(e){var t;const n={identity:{context:e||"signin",providers:[{configURL:o.httpClient.buildUrl(i+Oe.config),clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return o.refresh(r.token)},isSupported:()=>l&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=o.httpClient.buildUrl(i+Oe.config);try{const o={identity:{context:e||"signin",providers:[{configURL:n,clientId:i}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(o));return!!r&&!!r.token}catch(e){return!1}}}),oidc:n});var o,i}));exports.REFRESH_TOKEN_KEY=A,exports.SESSION_TOKEN_KEY=C,exports.clearFingerprintData=()=>{x(B)},exports.createSdk=Ee,exports.default=Ee,exports.ensureFingerprintIds=X,exports.getSessionToken=K,exports.hasOidcParamsInUrl=Te;
2
2
  //# sourceMappingURL=index.cjs.js.map
package/dist/index.d.ts CHANGED
@@ -196,6 +196,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
196
196
  platform: "ios" | "android";
197
197
  oauthProvider?: string;
198
198
  oauthRedirect?: string;
199
+ externalAuthRedirect?: string;
199
200
  };
200
201
  thirdPartyAppStateId?: string;
201
202
  applicationScopes?: string;
@@ -917,6 +918,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
917
918
  platform: "ios" | "android";
918
919
  oauthProvider?: string;
919
920
  oauthRedirect?: string;
921
+ externalAuthRedirect?: string;
920
922
  };
921
923
  thirdPartyAppStateId?: string;
922
924
  applicationScopes?: string;
@@ -1638,6 +1640,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
1638
1640
  platform: "ios" | "android";
1639
1641
  oauthProvider?: string;
1640
1642
  oauthRedirect?: string;
1643
+ externalAuthRedirect?: string;
1641
1644
  };
1642
1645
  thirdPartyAppStateId?: string;
1643
1646
  applicationScopes?: string;
@@ -2369,6 +2372,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
2369
2372
  platform: "ios" | "android";
2370
2373
  oauthProvider?: string;
2371
2374
  oauthRedirect?: string;
2375
+ externalAuthRedirect?: string;
2372
2376
  };
2373
2377
  thirdPartyAppStateId?: string;
2374
2378
  applicationScopes?: string;
@@ -3090,6 +3094,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
3090
3094
  platform: "ios" | "android";
3091
3095
  oauthProvider?: string;
3092
3096
  oauthRedirect?: string;
3097
+ externalAuthRedirect?: string;
3093
3098
  };
3094
3099
  thirdPartyAppStateId?: string;
3095
3100
  applicationScopes?: string;
@@ -3811,6 +3816,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
3811
3816
  platform: "ios" | "android";
3812
3817
  oauthProvider?: string;
3813
3818
  oauthRedirect?: string;
3819
+ externalAuthRedirect?: string;
3814
3820
  };
3815
3821
  thirdPartyAppStateId?: string;
3816
3822
  applicationScopes?: string;
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{__rest as e}from"tslib";import{jwtDecode as t}from"jwt-decode";import n,{wrapWith as o}from"@descope/core-js-sdk";import i from"js-cookie";import{load as r,defaultEndpoint as s,defaultScriptUrlPattern as a}from"@fingerprintjs/fingerprintjs-pro";const c="3.2.0",l="undefined"!=typeof window,d=Math.pow(2,31)-1,u=`https://descopecdn.com/npm/oidc-client-ts@${c}/dist/browser/oidc-client-ts.min.js`,p=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${c}/dist/browser/oidc-client-ts.min.js`;const f=["/v1/auth/refresh","/v1/auth/try-refresh","/v1/auth/me","/v1/auth/me/tenants","/v1/auth/me/history"];let g;const v=e=>{try{return t(e).exp}catch(e){return null}},h=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:v(n)},w=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?v(o):void 0)},m=t=>{const{access_token:n,id_token:o,refresh_token:i,refresh_expire_in:r}=t,s=e(t,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:t.sessionJwt||n,idToken:o,refreshJwt:t.refreshJwt||i,sessionExpiration:t.sessionExpiration||w(t),cookieExpiration:t.cookieExpiration||h(t)},s)},y=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var i;return n[o]=[].concat((null===(i=e.hooks)||void 0===i?void 0:i[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},b=async e=>{if(!(null==e?void 0:e.ok))return{};const t=await(null==e?void 0:e.clone().json()),n=(null==t?void 0:t.authInfo)||t||{};return m(n)},k=()=>l&&!!window.descopeBridge,S=(e,t)=>{if(!((null==t?void 0:t.status)>=400&&(null==t?void 0:t.status)<500))return!1;const n=(null==e?void 0:e.path)||"";return f.includes(n)},O=void 0!==g||l&&void 0!==window.localStorage,I=(e,t)=>{var n,o;return null===(o=null===(n=g||l&&window.localStorage)||void 0===n?void 0:n.setItem)||void 0===o?void 0:o.call(n,e,t)},_=e=>{var t,n;return null===(n=null===(t=g||l&&window.localStorage)||void 0===t?void 0:t.getItem)||void 0===n?void 0:n.call(t,e)},x=e=>{var t,n;return null===(n=null===(t=g||l&&window.localStorage)||void 0===t?void 0:t.removeItem)||void 0===n?void 0:n.call(t,e)},j=e=>{var t,n,o,i,r;return null!==(r=null!==(n=null===(t=null==g?void 0:g.key)||void 0===t?void 0:t.call(g,e))&&void 0!==n?n:l&&(null===(i=null===(o=window.localStorage)||void 0===o?void 0:o.key)||void 0===i?void 0:i.call(o,e)))&&void 0!==r?r:null},U=(...e)=>{console.debug(...e)},D=(...e)=>{console.warn(...e)},T=(e,t)=>{let n;var o;return t>0?(n=1e3*t,U(`Using provided nextRefreshSeconds: ${t}s`)):n=((o=e)?o.getTime()-(new Date).getTime():0)-2e4,n>d&&(U(`Timeout is too large (${n}ms), setting it to ${d}ms`),n=d),n},C="DS",A="DSR",R="DSI",$="DSRCN";function E(e,t,n){if(t){const{cookieDomain:o,cookiePath:r,cookieSameSite:s,cookieExpiration:a,cookieSecure:c}=n,l=new Date(1e3*a),d=N(o);i.set(e,t,{path:r,domain:d?o:void 0,expires:l,sameSite:s,secure:c})}}function N(e){const t=window.location.hostname.split("."),n=null==e?void 0:e.split(".");return t.slice(-(null==n?void 0:n.length)).join(".")===e}const J=e=>(null==e?void 0:e.cookieName)||C,P=e=>(null==e?void 0:e.cookieName)||A;function L(e="",t){return i.get(P(t))||_(`${e}${A}`)||""}function K(e="",t){return i.get(J(t))||_(`${e}${C}`)||""}function q(e=""){return _(`${e}${R}`)||""}function V(e="",t,n,o){x(`${e}${A}`),x(`${e}${C}`),x(`${e}${R}`),x(`${e}${$}`);const r=J(t);i.remove(r,null==o?void 0:o.session);const s=P(n);i.remove(s,null==o?void 0:o.refresh)}const F=(e,t,n)=>o=>{const i=Object.assign(o,{token:o.token||L(e,t)});if(!n){const t=function(e=""){return _(`${e}${$}`)}(e);t&&(i.headers=Object.assign(Object.assign({},i.headers||{}),{"x-descope-refresh-cookie-name":t}))}const r=function(e=""){return _(`${e}DTD`)||""}(e);return r&&(i.headers=Object.assign(Object.assign({},i.headers||{}),{"x-descope-trusted-device-token":r})),i},M=l&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",H="vsid",B="vrid",G="fp",W=(e=!1)=>{const t=_(G);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},X=async(e,t=M)=>{try{if(W())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),o=new URL(t);o.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const i=new URL(t);i.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const c=i.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",l=r({apiKey:e,endpoint:[o.toString(),s],scriptUrlPattern:[c,a]}),d=await l,{requestId:u}=await d.get({linkedId:n}),p=((e,t)=>({[H]:e,[B]:t}))(n,u);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};I(G,JSON.stringify(t))})(p)}catch(e){console.warn("Could not load fingerprint",e)}},Z=()=>{x(G)},z=e=>{const t=W(!0);return t&&e.body&&(e.body.fpData=t),e},Q="descopeFlowNonce",Y="X-Descope-Flow-Nonce",ee="/v1/flow/start",te="/v1/flow/next",ne=(e,t=Q)=>`${t}${e}`,oe=(e,t=Q)=>{try{const n=ne(e,t);x(n)}catch(e){console.error("Error removing flow nonce:",e)}},ie=e=>{var t;return(null===(t=/.*\|#\|(.*)/.exec(e))||void 0===t?void 0:t[1])||null},re=e=>{var t;return e.path===te&&(null===(t=e.body)||void 0===t?void 0:t.executionId)?ie(e.body.executionId):null},se="dls_last_user_login_id",ae="dls_last_user_display_name",ce=e=>I(se,e),le=()=>_(se),de=()=>_(ae),ue=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=le(),r=de();i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r);return await e(...t)},pe=e=>t=>async(...n)=>{const o=await t(...n);return e||(x(se),x(ae)),o};function fe(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const ge=(e,t,n,o)=>i=>async(...r)=>{const s=await i(...r);return V(e,t,n,null==o?void 0:o()),s};async function ve(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=ke(n.publicKey.challenge),n.publicKey.user.id=ke(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=ke(e.id)})),n}(e),n=await navigator.credentials.create(t);return o=n,JSON.stringify({id:o.id,rawId:Se(o.rawId),type:o.type,response:{attestationObject:Se(o.response.attestationObject),clientDataJSON:Se(o.response.clientDataJSON)}});var o}async function he(e){const t=ye(e);return be(await navigator.credentials.get(t))}async function we(e,t){const n=ye(e);n.signal=t.signal,n.mediation="conditional";return be(await navigator.credentials.get(n))}async function me(e=!1){var t,n;if(!l)return Promise.resolve(!1);if(k()){const e=null===(n=null===(t=window.descopeBridge)||void 0===t?void 0:t.hostInfo)||void 0===n?void 0:n.webauthn;if("boolean"==typeof e)return e}const o=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return o&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():o}function ye(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=ke(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=ke(e.id)})),n}function be(e){return JSON.stringify({id:e.id,rawId:Se(e.rawId),type:e.type,response:{authenticatorData:Se(e.response.authenticatorData),clientDataJSON:Se(e.response.clientDataJSON),signature:Se(e.response.signature),userHandle:e.response.userHandle?Se(e.response.userHandle):void 0}})}function ke(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function Se(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var Oe,Ie=(Oe=e=>({async signUp(t,n,o){const i=await e.webauthn.signUp.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await ve(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,r)},async signIn(t,n){const o=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!o.ok)return o;const i=await he(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,i)},async signUpOrIn(t,n){var o;const i=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!i.ok)return i;if(null===(o=i.data)||void 0===o?void 0:o.create){const t=await ve(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,t)}{const t=await he(i.data.options);return await e.webauthn.signIn.finish(i.data.transactionId,t)}},async update(t,n,o){const i=await e.webauthn.update.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await ve(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:ve,get:he,isSupported:me,conditional:we}}),(...e)=>{const t=Oe(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const _e={config:"/fedcm/config"},xe=()=>{if(window.crypto&&window.crypto.getRandomValues){const e=new Uint8Array(16);return window.crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}return Math.random().toString(36).substring(2)};async function je(e,t){var n;try{await Ue(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function Ue(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=xe(),s=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let n=document.getElementById("google-gsi-client-script");n||(n=document.createElement("script"),document.head.appendChild(n),n.async=!0,n.defer=!0,n.id="google-gsi-client-script",n.src="https://accounts.google.com/gsi/client"),n.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},n.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}(),a=await e.oauth.getOneTapClientId(t);if(!a.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const c=a.data.clientId;return new Promise((e=>{var a,l;const d=n=>{e({provider:t,nonce:r,credential:null==n?void 0:n.credential})};s.initialize(Object.assign(Object.assign({},n),{itp_support:null===(a=null==n?void 0:n.itp_support)||void 0===a||a,use_fedcm_for_prompt:null===(l=null==n?void 0:n.use_fedcm_for_prompt)||void 0===l||l,client_id:c,callback:d,nonce:r})),s.prompt((e=>{var t,n;if(i&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==i||i(n),void d()}if(o&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==o||o(t),void d()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!i.credential)return null;if(null==t?void 0:t.onCodeReceived){const o=await e.oauth.verifyOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!o.ok||!o.data)throw new Error("Failed to verify OneTap client ID for provider "+i.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,o.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+i.provider);null===(o=null==t?void 0:t.onAuthenticated)||void 0===o||o.call(t,n.data)}}var De=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await me(),o=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=o,e.flow.start(...t)}});const Te=()=>window.location.search.includes("code")&&window.location.search.includes("state");let Ce;const Ae=(e,t)=>new Promise(((n,o)=>{if(!e.length)return o(new Error("No URLs provided to loadScriptWithFallback"));const i=t();if(i)return n(i);const r=e.shift(),s=document.createElement("script");s.src=r,s.id=(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t).toString(16)})(r),s.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},s.addEventListener("error",(()=>{Ae(e,t),s.setAttribute("data-error","true")})),document.body.appendChild(s)}));const Re=async(e,t,n)=>{Ce||(Ce=(async()=>{try{return require("oidc-client-ts")}catch(e){return Ae([u,p],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:i}=await Ce;if(!o)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=(null==n?void 0:n.redirectUri)||window.location.href;let s,a,c,l;if(null==n?void 0:n.issuer){if(!n.clientId)throw new Error("clientId is required when providing a custom issuer/authority");s=n.issuer,a=n.clientId,c=`${a}_user`,l="openid"}else(null==n?void 0:n.applicationId)?(s=e.httpClient.buildUrl(t),s=`${s}/${n.applicationId}`,a=t,c=`${a}_user`,l="openid email roles descope.custom_claims offline_access"):(s=e.httpClient.buildUrl(t),a=t,c=`${a}_user`,l="openid email roles descope.custom_claims offline_access");const d={authority:s,client_id:a,redirect_uri:r,response_type:"code",scope:(null==n?void 0:n.scope)||l,stateStore:new i({store:window.localStorage,prefix:a}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(d.redirect_uri=n.redirectUri),{client:new o(d),stateUserKey:c}},$e=(e,t,n)=>{const o=async()=>{let o,i;return o&&i||({client:o,stateUserKey:i}=await Re(e,t,n)),{client:o,stateUserKey:i}},i=async(t="")=>{var n;const{client:i,stateUserKey:r}=await o(),s=await i.processSigninResponse(t||window.location.href);var a;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(s)))),I(r,JSON.stringify({id_token:(a=s).id_token,session_state:a.session_state,profile:a.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),s};return{loginWithRedirect:async(e={},t=!1)=>{const{client:n}=await o(),i=await n.createSigninRequest(e),{url:r}=i;return t||(window.location.href=r),{ok:!0,data:i}},finishLogin:i,finishLoginIfNeed:async(e="")=>{if(Te())return await i(e)},refreshToken:async t=>{var n;const{client:i,stateUserKey:r}=await o(),s=(e=>{const t=_(e);return t?JSON.parse(t):null})(r);if(!s)throw new Error("User not found in storage to refresh token");let a=t;if(!a){const t={};e.httpClient.hooks.beforeRequest(t),a=t.token}const c=await i.useRefreshToken({state:{refresh_token:a,session_state:s.session_state,profile:s.profile}});return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(c)))),c},logout:async(e,t=!1)=>{const{client:n,stateUserKey:i}=await o();e||(e={}),e.id_token_hint=e.id_token_hint||q(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await n.createSignoutRequest(e),{url:s}=r;return x(i),t||window.location.replace(s),r}}},Ee=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var n;return n=t.customStorage,g=n,e(t)}),(t=>n=>{var{fpKey:o,fpLoad:i}=n,r=e(n,["fpKey","fpLoad"]);return l?(o&&i&&X(o).catch((()=>null)),t(y(r,{beforeRequest:z}))):t(r)}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.48.1"},t.baseHeaders)}))),(e=>t=>{const n=fe(),i=fe(),r=fe(),s=fe(),a=e(y(t,{afterRequest:async(e,t)=>{if(S(e,t))U("Session invalidated, notifying subscribers with empty values"),i.pub(null),r.pub(null),n.pub(null),s.pub(null);else{const e=await(async e=>{const t=await b(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)})(t);e&&r.pub(e);const{sessionJwt:o,sessionExpiration:a,claims:c}=await b(t);o&&i.pub(o),c&&s.pub(c),(a||o)&&n.pub(a||42)}}})),c=o(a,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const o=await e(...t);return i.pub(null),r.pub(null),n.pub(null),s.pub(null),o}));return Object.assign(c,{onSessionTokenChange:i.sub,onUserChange:r.sub,onClaimsChange:s.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(t=>n=>{const{enableFlowNonce:o=!0,nonceStoragePrefix:i=Q}=n,r=e(n,["enableFlowNonce","nonceStoragePrefix"]);if(!o)return t(r);((e=Q)=>{try{if(!O)return;for(let i=0;i<(t=void 0,n=void 0,o=void 0,null!==(o=null!==(t=null==g?void 0:g.length)&&void 0!==t?t:l&&(null===(n=window.localStorage)||void 0===n?void 0:n.length))&&void 0!==o?o:0);i++){const t=j(i);if(t&&t.startsWith(e)){const e=_(t);if(e)try{JSON.parse(e).expiry<Date.now()&&x(t)}catch(e){x(t)}}}}catch(e){console.error("Error cleaning up expired nonces:",e)}var t,n,o})(i);return t(y(r,{afterRequest:async(e,t)=>{if(e.path!==ee&&e.path!==te)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(Y);let o=await t.clone().json().then((e=>(null==e?void 0:e.executionId)||null)).catch((()=>null));return o||(o=re(e)),{nonce:n,executionId:ie(o)}}catch(e){return{nonce:null,executionId:null}}})(e,t);if(n&&o){((e,t,n,o=Q)=>{try{const i=ne(e,o),r=n?172800:10800,s={value:t,expiry:Date.now()+1e3*r,isStart:n};I(i,JSON.stringify(s))}catch(e){console.error("Error setting flow nonce:",e)}})(o,n,e.path===ee,i)}},beforeRequest:e=>{if(e.path===te){const t=re(e);if(t){const n=((e,t=Q)=>{try{const n=ne(e,t),o=_(n);if(!o)return null;const i=JSON.parse(o);return i.expiry<Date.now()?(oe(e,t),null):i.value}catch(e){return console.error("Error getting flow nonce:",e),null}})(t,i);n&&(e.headers=e.headers||{},e.headers[Y]=n)}}return e}}))}),(n=>i=>{var{autoRefresh:r}=i,s=e(i,["autoRefresh"]);const a=!!r,c="object"==typeof r&&(null==r?void 0:r.customActivityTracking);if(!a||k())return Object.assign(n(s),{markUserActive:()=>{D("markUserActive() called but has no effect")}});const{clearAllTimers:d,setTimer:u}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let p,f,g=null,v=!1,h=!1;c&&(U("Activity-based refresh enabled"),g=(()=>{let e=!0;return{hadActivity:()=>e,reset:()=>{e=!1},markActive:()=>{e=!0}}})()),l&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&p&&new Date>p&&(U("Expiration time passed, refreshing session"),w.refresh(L()||f))}));const w=n(y(s,{afterRequest:async(e,n)=>{const{sessionJwt:o,refreshJwt:i,sessionExpiration:r,nextRefreshSeconds:s}=await b(n);if(S(e,n))U("Session invalidated, canceling all timers"),d();else if(o||r){if(p=((e,n)=>{if(n)return new Date(1e3*n);U("Could not extract expiration time from session token, trying to decode the token");try{const n=t(e);if(n.exp)return new Date(1e3*n.exp)}catch(e){return null}})(o,r),!p)return void U("Could not extract expiration time from session token");f=i,v=s>0;const e=T(p,s);if(d(),e<=2e4)return void U("Session is too close to expiration, not setting refresh timer");const n=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});U(`Setting refresh timer for ${n}. (${e}ms)`),g&&(g.reset(),h=!1),u((()=>{if(l&&"hidden"===document.visibilityState)U("Skipping refresh due to timer - document is hidden");else{if(g&&v&&!g.hadActivity())return U("Skipping refresh due to timer - user is idle"),void(h=!0);U("Refreshing session due to timer"),w.refresh(L()||i)}}),e)}}}));return Object.assign(o(w,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return U("Clearing all timers"),d(),n})),{markUserActive:g?()=>{U("markUserActive() called"),v||U("markUserActive() called but server does not have inactivity timeout configured (no nextRefreshSeconds)"),g.markActive(),h&&(U("User became active after skipped refresh, triggering refresh"),h=!1,d(),w.refresh(L()||f))}:()=>{D("markUserActive() called but customActivityTracking is not enabled — this call has no effect")}})}),(t=>n=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:r=!1}=n,s=e(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(t(s),{getLastUserLoginId:le,getLastUserDisplayName:de});const a=t(y(s,{afterRequest:async(e,t)=>{var n;const{userInfo:o,lastAuth:i}=await(async e=>{if(!(null==e?void 0:e.ok))return{userInfo:void 0,lastAuth:void 0};const t=await(null==e?void 0:e.clone().json()),n=m((null==t?void 0:t.authInfo)||t||{});return{userInfo:(null==n?void 0:n.user)||((null==n?void 0:n.hasOwnProperty("userId"))?n:void 0),lastAuth:t.lastAuth}})(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],s=null==o?void 0:o.name;r?(ce(r),(e=>{I(ae,e)})(s)):(null==i?void 0:i.loginId)&&ce(i.loginId)}}));let c=o(a,["flow.start"],ue);return c=o(c,["logout","logoutAll"],pe(r)),Object.assign(c,{getLastUserLoginId:le,getLastUserDisplayName:de})}),(t=>n=>{var{persistTokens:r,sessionTokenViaCookie:s,refreshTokenViaCookie:a,storagePrefix:c,refreshCookieName:d}=n,u=e(n,["persistTokens","sessionTokenViaCookie","refreshTokenViaCookie","storagePrefix","refreshCookieName"]);if(!r||!l)return t(Object.assign({refreshCookieName:d},u));let p;const f=t(y(Object.assign({refreshCookieName:d},u),{beforeRequest:F(c,a,d),afterRequest:async(e,t)=>{if(S(e,t))U("Session invalidated, clearing persisted tokens"),V(c,s,a,p);else{const e=await b(t);e.cookieName?I(`${c||""}${$}`,e.cookieName):e.refreshJwt&&x(`${c||""}${$}`);const n=((e={},t=!1,n="",o=!1)=>{var r,s,a,c;const{sessionJwt:l,refreshJwt:d,trustedDeviceJwt:u}=e;let p;if(d)if(o){x(`${n}${A}`);const t=o.sameSite||"Strict",i=null===(r=o.secure)||void 0===r||r,a=null!==(s=o.domain)&&void 0!==s?s:e.cookieDomain,c=P(o);i&&"https:"!==window.location.protocol&&D("Refresh token cookie is configured with secure=true but the page is not using HTTPS. The cookie will not be set. To fix this, pass refreshTokenViaCookie: { secure: process.env['NODE_ENV'] !== 'development' }");const l=Object.assign(Object.assign({},e),{cookieSameSite:t,cookieSecure:i,cookieDomain:a});E(c,d,l);const u=N(a);p=Object.assign(Object.assign({},p),{refresh:{path:l.cookiePath,domain:u?a:void 0}})}else{const e=P(o);i.remove(e),I(`${n}${A}`,d)}if(l)if(t){const n=t.sameSite||"Strict",o=null===(a=t.secure)||void 0===a||a,i=null!==(c=t.domain)&&void 0!==c?c:e.cookieDomain,r=J(t);o&&"https:"!==window.location.protocol&&D("Session token cookie is configured with secure=true but the page is not using HTTPS. The cookie will not be set. To fix this, pass sessionTokenViaCookie: { secure: process.env['NODE_ENV'] !== 'development' }");const s=Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:o,cookieDomain:i});E(r,l,s);const d=N(i);p=Object.assign(Object.assign({},p),{session:{path:s.cookiePath,domain:d?i:void 0}})}else I(`${n}${C}`,l);return e.idToken&&I(`${n}${R}`,e.idToken),u&&I(`${n}DTD`,u),p})(e,s,c,a);n&&(p=n)}}})),g=o(f,["logout","logoutAll","oidc.logout"],ge(c,s,a,(()=>p)));return Object.assign(g,{getRefreshToken:()=>L(c,a),getSessionToken:()=>K(c,s),getIdToken:()=>q(c)})}))((e=>{const t=n(e),o=$e(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async(n,i)=>{var r;if(k())return U(`Refresh called in native flow: ${(new Error).stack}`),Promise.resolve({ok:!1,error:{errorCode:"J171000",errorDescription:"Refresh is not supported in native flows via the web SDK"}});if(e.oidcConfig)try{return await o.refreshToken(n),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const s=K(),a=L();let c="";if(e.getExternalToken)try{c=await(null===(r=e.getExternalToken)||void 0===r?void 0:r.call(e))}catch(e){U("Error getting external token while refreshing",e)}return t.refresh(n,{dcs:s?"t":"f",dcr:a?"t":"f"},c,i)},logout:async n=>{if(e.oidcConfig)try{return await o.logout({id_token_hint:n}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(n)},flow:De(t),webauthn:Ie(t),fedcm:(i=t,r=e.projectId,{onetap:{requestExchangeCode(e){je(i,e)},requestAuthentication(e){je(i,e)}},async oneTap(e,t,n,o,r){await Ue(i,{provider:e,oneTapConfig:t,loginOptions:n,onSkipped:o,onDismissed:r})},async launch(e){var t;const n={identity:{context:e||"signin",providers:[{configURL:i.httpClient.buildUrl(r+_e.config),clientId:r}]}},o=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return i.refresh(o.token)},isSupported:()=>l&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=i.httpClient.buildUrl(r+_e.config);try{const o={identity:{context:e||"signin",providers:[{configURL:n,clientId:r}]}},i=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(o));return!!i&&!!i.token}catch(e){return!1}}}),oidc:o});var i,r}));export{A as REFRESH_TOKEN_KEY,C as SESSION_TOKEN_KEY,Z as clearFingerprintData,Ee as createSdk,Ee as default,X as ensureFingerprintIds,K as getSessionToken,Te as hasOidcParamsInUrl};
1
+ import{__rest as e}from"tslib";import{jwtDecode as t}from"jwt-decode";import n,{wrapWith as o}from"@descope/core-js-sdk";import i from"js-cookie";import{load as r,defaultEndpoint as s,defaultScriptUrlPattern as a}from"@fingerprintjs/fingerprintjs-pro";const c="3.2.0",l="undefined"!=typeof window,d=Math.pow(2,31)-1,u=`https://descopecdn.com/npm/oidc-client-ts@${c}/dist/browser/oidc-client-ts.min.js`,p=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${c}/dist/browser/oidc-client-ts.min.js`;const f=["/v1/auth/refresh","/v1/auth/try-refresh","/v1/auth/me","/v1/auth/me/tenants","/v1/auth/me/history"];let g;const v=e=>{try{return t(e).exp}catch(e){return null}},h=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:v(n)},w=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?v(o):void 0)},m=t=>{const{access_token:n,id_token:o,refresh_token:i,refresh_expire_in:r}=t,s=e(t,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:t.sessionJwt||n,idToken:o,refreshJwt:t.refreshJwt||i,sessionExpiration:t.sessionExpiration||w(t),cookieExpiration:t.cookieExpiration||h(t)},s)},y=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var i;return n[o]=[].concat((null===(i=e.hooks)||void 0===i?void 0:i[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},b=async e=>{if(!(null==e?void 0:e.ok))return{};const t=await(null==e?void 0:e.clone().json()),n=(null==t?void 0:t.authInfo)||t||{};return m(n)},k=()=>l&&!!window.descopeBridge,S=(e,t)=>{if(!((null==t?void 0:t.status)>=400&&(null==t?void 0:t.status)<500))return!1;const n=(null==e?void 0:e.path)||"";return f.includes(n)},O=void 0!==g||l&&void 0!==window.localStorage,I=(e,t)=>{var n,o;return null===(o=null===(n=g||l&&window.localStorage)||void 0===n?void 0:n.setItem)||void 0===o?void 0:o.call(n,e,t)},_=e=>{var t,n;return null===(n=null===(t=g||l&&window.localStorage)||void 0===t?void 0:t.getItem)||void 0===n?void 0:n.call(t,e)},x=e=>{var t,n;return null===(n=null===(t=g||l&&window.localStorage)||void 0===t?void 0:t.removeItem)||void 0===n?void 0:n.call(t,e)},j=e=>{var t,n,o,i,r;return null!==(r=null!==(n=null===(t=null==g?void 0:g.key)||void 0===t?void 0:t.call(g,e))&&void 0!==n?n:l&&(null===(i=null===(o=window.localStorage)||void 0===o?void 0:o.key)||void 0===i?void 0:i.call(o,e)))&&void 0!==r?r:null},U=(...e)=>{console.debug(...e)},D=(...e)=>{console.warn(...e)},T=(e,t)=>{let n;var o;return t>0?(n=1e3*t,U(`Using provided nextRefreshSeconds: ${t}s`)):n=((o=e)?o.getTime()-(new Date).getTime():0)-2e4,n>d&&(U(`Timeout is too large (${n}ms), setting it to ${d}ms`),n=d),n},C="DS",A="DSR",R="DSI",$="DSRCN";function E(e,t,n){if(t){const{cookieDomain:o,cookiePath:r,cookieSameSite:s,cookieExpiration:a,cookieSecure:c}=n,l=new Date(1e3*a),d=N(o);i.set(e,t,{path:r,domain:d?o:void 0,expires:l,sameSite:s,secure:c})}}function N(e){const t=window.location.hostname.split("."),n=null==e?void 0:e.split(".");return t.slice(-(null==n?void 0:n.length)).join(".")===e}const J=e=>(null==e?void 0:e.cookieName)||C,P=e=>(null==e?void 0:e.cookieName)||A;function L(e="",t){return i.get(P(t))||_(`${e}${A}`)||""}function K(e="",t){return i.get(J(t))||_(`${e}${C}`)||""}function q(e=""){return _(`${e}${R}`)||""}function V(e="",t,n,o){x(`${e}${A}`),x(`${e}${C}`),x(`${e}${R}`),x(`${e}${$}`);const r=J(t);i.remove(r,null==o?void 0:o.session);const s=P(n);i.remove(s,null==o?void 0:o.refresh)}const F=(e,t,n)=>o=>{const i=Object.assign(o,{token:o.token||L(e,t)});if(!n){const t=function(e=""){return _(`${e}${$}`)}(e);t&&(i.headers=Object.assign(Object.assign({},i.headers||{}),{"x-descope-refresh-cookie-name":t}))}const r=function(e=""){return _(`${e}DTD`)||""}(e);return r&&(i.headers=Object.assign(Object.assign({},i.headers||{}),{"x-descope-trusted-device-token":r})),i},M=l&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",H="vsid",B="vrid",G="fp",W=(e=!1)=>{const t=_(G);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},X=async(e,t=M)=>{try{if(W())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),o=new URL(t);o.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const i=new URL(t);i.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const c=i.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",l=r({apiKey:e,endpoint:[o.toString(),s],scriptUrlPattern:[c,a]}),d=await l,{requestId:u}=await d.get({linkedId:n}),p=((e,t)=>({[H]:e,[B]:t}))(n,u);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};I(G,JSON.stringify(t))})(p)}catch(e){console.warn("Could not load fingerprint",e)}},Z=()=>{x(G)},z=e=>{const t=W(!0);return t&&e.body&&(e.body.fpData=t),e},Q="descopeFlowNonce",Y="X-Descope-Flow-Nonce",ee="/v1/flow/start",te="/v1/flow/next",ne=(e,t=Q)=>`${t}${e}`,oe=(e,t=Q)=>{try{const n=ne(e,t);x(n)}catch(e){console.error("Error removing flow nonce:",e)}},ie=e=>{var t;return(null===(t=/.*\|#\|(.*)/.exec(e))||void 0===t?void 0:t[1])||null},re=e=>{var t;return e.path===te&&(null===(t=e.body)||void 0===t?void 0:t.executionId)?ie(e.body.executionId):null},se="dls_last_user_login_id",ae="dls_last_user_display_name",ce=e=>I(se,e),le=()=>_(se),de=()=>_(ae),ue=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=le(),r=de();i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r);return await e(...t)},pe=e=>t=>async(...n)=>{const o=await t(...n);return e||(x(se),x(ae)),o};function fe(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const ge=(e,t,n,o)=>i=>async(...r)=>{const s=await i(...r);return V(e,t,n,null==o?void 0:o()),s};async function ve(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=ke(n.publicKey.challenge),n.publicKey.user.id=ke(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=ke(e.id)})),n}(e),n=await navigator.credentials.create(t);return o=n,JSON.stringify({id:o.id,rawId:Se(o.rawId),type:o.type,response:{attestationObject:Se(o.response.attestationObject),clientDataJSON:Se(o.response.clientDataJSON)}});var o}async function he(e){const t=ye(e);return be(await navigator.credentials.get(t))}async function we(e,t){const n=ye(e);n.signal=t.signal,n.mediation="conditional";return be(await navigator.credentials.get(n))}async function me(e=!1){var t,n;if(!l)return Promise.resolve(!1);if(k()){const e=null===(n=null===(t=window.descopeBridge)||void 0===t?void 0:t.hostInfo)||void 0===n?void 0:n.webauthn;if("boolean"==typeof e)return e}const o=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return o&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():o}function ye(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=ke(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=ke(e.id)})),n}function be(e){return JSON.stringify({id:e.id,rawId:Se(e.rawId),type:e.type,response:{authenticatorData:Se(e.response.authenticatorData),clientDataJSON:Se(e.response.clientDataJSON),signature:Se(e.response.signature),userHandle:e.response.userHandle?Se(e.response.userHandle):void 0}})}function ke(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function Se(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var Oe,Ie=(Oe=e=>({async signUp(t,n,o){const i=await e.webauthn.signUp.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await ve(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,r)},async signIn(t,n){const o=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!o.ok)return o;const i=await he(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,i)},async signUpOrIn(t,n){var o;const i=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!i.ok)return i;if(null===(o=i.data)||void 0===o?void 0:o.create){const t=await ve(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,t)}{const t=await he(i.data.options);return await e.webauthn.signIn.finish(i.data.transactionId,t)}},async update(t,n,o){const i=await e.webauthn.update.start(t,window.location.origin,n,o);if(!i.ok)return i;const r=await ve(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:ve,get:he,isSupported:me,conditional:we}}),(...e)=>{const t=Oe(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const _e={config:"/fedcm/config"},xe=()=>{if(window.crypto&&window.crypto.getRandomValues){const e=new Uint8Array(16);return window.crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}return Math.random().toString(36).substring(2)};async function je(e,t){var n;try{await Ue(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function Ue(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=xe(),s=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let n=document.getElementById("google-gsi-client-script");n||(n=document.createElement("script"),document.head.appendChild(n),n.async=!0,n.defer=!0,n.id="google-gsi-client-script",n.src="https://accounts.google.com/gsi/client"),n.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},n.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}(),a=await e.oauth.getOneTapClientId(t);if(!a.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const c=a.data.clientId;return new Promise((e=>{var a,l;const d=n=>{e({provider:t,nonce:r,credential:null==n?void 0:n.credential})};s.initialize(Object.assign(Object.assign({},n),{itp_support:null===(a=null==n?void 0:n.itp_support)||void 0===a||a,use_fedcm_for_prompt:null===(l=null==n?void 0:n.use_fedcm_for_prompt)||void 0===l||l,client_id:c,callback:d,nonce:r})),s.prompt((e=>{var t,n;if(i&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==i||i(n),void d()}if(o&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);return null==o||o(t),void d()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!i.credential)return null;if(null==t?void 0:t.onCodeReceived){const o=await e.oauth.verifyOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!o.ok||!o.data)throw new Error("Failed to verify OneTap client ID for provider "+i.provider);null===(n=null==t?void 0:t.onCodeReceived)||void 0===n||n.call(t,o.data.code)}else{const n=await e.oauth.exchangeOneTapIDToken(i.provider,i.credential,i.nonce,null==t?void 0:t.loginOptions);if(!n.ok||!n.data)throw new Error("Failed to exchange OneTap client ID for provider "+i.provider);null===(o=null==t?void 0:t.onAuthenticated)||void 0===o||o.call(t,n.data)}}var De=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await me(),o=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=o,e.flow.start(...t)}});const Te=()=>window.location.search.includes("code")&&window.location.search.includes("state");let Ce;const Ae=(e,t)=>new Promise(((n,o)=>{if(!e.length)return o(new Error("No URLs provided to loadScriptWithFallback"));const i=t();if(i)return n(i);const r=e.shift(),s=document.createElement("script");s.src=r,s.id=(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t).toString(16)})(r),s.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},s.addEventListener("error",(()=>{Ae(e,t),s.setAttribute("data-error","true")})),document.body.appendChild(s)}));const Re=async(e,t,n)=>{Ce||(Ce=(async()=>{try{return require("oidc-client-ts")}catch(e){return Ae([u,p],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:i}=await Ce;if(!o)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=(null==n?void 0:n.redirectUri)||window.location.href;let s,a,c,l;if(null==n?void 0:n.issuer){if(!n.clientId)throw new Error("clientId is required when providing a custom issuer/authority");s=n.issuer,a=n.clientId,c=`${a}_user`,l="openid"}else(null==n?void 0:n.applicationId)?(s=e.httpClient.buildUrl(t),s=`${s}/${n.applicationId}`,a=t,c=`${a}_user`,l="openid email roles descope.custom_claims offline_access"):(s=e.httpClient.buildUrl(t),a=t,c=`${a}_user`,l="openid email roles descope.custom_claims offline_access");const d={authority:s,client_id:a,redirect_uri:r,response_type:"code",scope:(null==n?void 0:n.scope)||l,stateStore:new i({store:window.localStorage,prefix:a}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(d.redirect_uri=n.redirectUri),{client:new o(d),stateUserKey:c}},$e=(e,t,n)=>{const o=async()=>{let o,i;return o&&i||({client:o,stateUserKey:i}=await Re(e,t,n)),{client:o,stateUserKey:i}},i=async(t="")=>{var n;const{client:i,stateUserKey:r}=await o(),s=await i.processSigninResponse(t||window.location.href);var a;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(s)))),I(r,JSON.stringify({id_token:(a=s).id_token,session_state:a.session_state,profile:a.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),s};return{loginWithRedirect:async(e={},t=!1)=>{const{client:n}=await o(),i=await n.createSigninRequest(e),{url:r}=i;return t||(window.location.href=r),{ok:!0,data:i}},finishLogin:i,finishLoginIfNeed:async(e="")=>{if(Te())return await i(e)},refreshToken:async t=>{var n;const{client:i,stateUserKey:r}=await o(),s=(e=>{const t=_(e);return t?JSON.parse(t):null})(r);if(!s)throw new Error("User not found in storage to refresh token");let a=t;if(!a){const t={};e.httpClient.hooks.beforeRequest(t),a=t.token}const c=await i.useRefreshToken({state:{refresh_token:a,session_state:s.session_state,profile:s.profile}});return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(c)))),c},logout:async(e,t=!1)=>{const{client:n,stateUserKey:i}=await o();e||(e={}),e.id_token_hint=e.id_token_hint||q(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await n.createSignoutRequest(e),{url:s}=r;return x(i),t||window.location.replace(s),r}}},Ee=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var n;return n=t.customStorage,g=n,e(t)}),(t=>n=>{var{fpKey:o,fpLoad:i}=n,r=e(n,["fpKey","fpLoad"]);return l?(o&&i&&X(o).catch((()=>null)),t(y(r,{beforeRequest:z}))):t(r)}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.48.2"},t.baseHeaders)}))),(e=>t=>{const n=fe(),i=fe(),r=fe(),s=fe(),a=e(y(t,{afterRequest:async(e,t)=>{if(S(e,t))U("Session invalidated, notifying subscribers with empty values"),i.pub(null),r.pub(null),n.pub(null),s.pub(null);else{const e=await(async e=>{const t=await b(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)})(t);e&&r.pub(e);const{sessionJwt:o,sessionExpiration:a,claims:c}=await b(t);o&&i.pub(o),c&&s.pub(c),(a||o)&&n.pub(a||42)}}})),c=o(a,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const o=await e(...t);return i.pub(null),r.pub(null),n.pub(null),s.pub(null),o}));return Object.assign(c,{onSessionTokenChange:i.sub,onUserChange:r.sub,onClaimsChange:s.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(t=>n=>{const{enableFlowNonce:o=!0,nonceStoragePrefix:i=Q}=n,r=e(n,["enableFlowNonce","nonceStoragePrefix"]);if(!o)return t(r);((e=Q)=>{try{if(!O)return;for(let i=0;i<(t=void 0,n=void 0,o=void 0,null!==(o=null!==(t=null==g?void 0:g.length)&&void 0!==t?t:l&&(null===(n=window.localStorage)||void 0===n?void 0:n.length))&&void 0!==o?o:0);i++){const t=j(i);if(t&&t.startsWith(e)){const e=_(t);if(e)try{JSON.parse(e).expiry<Date.now()&&x(t)}catch(e){x(t)}}}}catch(e){console.error("Error cleaning up expired nonces:",e)}var t,n,o})(i);return t(y(r,{afterRequest:async(e,t)=>{if(e.path!==ee&&e.path!==te)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(Y);let o=await t.clone().json().then((e=>(null==e?void 0:e.executionId)||null)).catch((()=>null));return o||(o=re(e)),{nonce:n,executionId:ie(o)}}catch(e){return{nonce:null,executionId:null}}})(e,t);if(n&&o){((e,t,n,o=Q)=>{try{const i=ne(e,o),r=n?172800:10800,s={value:t,expiry:Date.now()+1e3*r,isStart:n};I(i,JSON.stringify(s))}catch(e){console.error("Error setting flow nonce:",e)}})(o,n,e.path===ee,i)}},beforeRequest:e=>{if(e.path===te){const t=re(e);if(t){const n=((e,t=Q)=>{try{const n=ne(e,t),o=_(n);if(!o)return null;const i=JSON.parse(o);return i.expiry<Date.now()?(oe(e,t),null):i.value}catch(e){return console.error("Error getting flow nonce:",e),null}})(t,i);n&&(e.headers=e.headers||{},e.headers[Y]=n)}}return e}}))}),(n=>i=>{var{autoRefresh:r}=i,s=e(i,["autoRefresh"]);const a=!!r,c="object"==typeof r&&(null==r?void 0:r.customActivityTracking);if(!a||k())return Object.assign(n(s),{markUserActive:()=>{D("markUserActive() called but has no effect")}});const{clearAllTimers:d,setTimer:u}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let p,f,g=null,v=!1,h=!1;c&&(U("Activity-based refresh enabled"),g=(()=>{let e=!0;return{hadActivity:()=>e,reset:()=>{e=!1},markActive:()=>{e=!0}}})()),l&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&p&&new Date>p&&(U("Expiration time passed, refreshing session"),w.refresh(L()||f))}));const w=n(y(s,{afterRequest:async(e,n)=>{const{sessionJwt:o,refreshJwt:i,sessionExpiration:r,nextRefreshSeconds:s}=await b(n);if(S(e,n))U("Session invalidated, canceling all timers"),d();else if(o||r){if(p=((e,n)=>{if(n)return new Date(1e3*n);U("Could not extract expiration time from session token, trying to decode the token");try{const n=t(e);if(n.exp)return new Date(1e3*n.exp)}catch(e){return null}})(o,r),!p)return void U("Could not extract expiration time from session token");f=i,v=s>0;const e=T(p,s);if(d(),e<=2e4)return void U("Session is too close to expiration, not setting refresh timer");const n=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});U(`Setting refresh timer for ${n}. (${e}ms)`),g&&(g.reset(),h=!1),u((()=>{if(l&&"hidden"===document.visibilityState)U("Skipping refresh due to timer - document is hidden");else{if(g&&v&&!g.hadActivity())return U("Skipping refresh due to timer - user is idle"),void(h=!0);U("Refreshing session due to timer"),w.refresh(L()||i)}}),e)}}}));return Object.assign(o(w,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return U("Clearing all timers"),d(),n})),{markUserActive:g?()=>{U("markUserActive() called"),v||U("markUserActive() called but server does not have inactivity timeout configured (no nextRefreshSeconds)"),g.markActive(),h&&(U("User became active after skipped refresh, triggering refresh"),h=!1,d(),w.refresh(L()||f))}:()=>{D("markUserActive() called but customActivityTracking is not enabled — this call has no effect")}})}),(t=>n=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:r=!1}=n,s=e(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(t(s),{getLastUserLoginId:le,getLastUserDisplayName:de});const a=t(y(s,{afterRequest:async(e,t)=>{var n;const{userInfo:o,lastAuth:i}=await(async e=>{if(!(null==e?void 0:e.ok))return{userInfo:void 0,lastAuth:void 0};const t=await(null==e?void 0:e.clone().json()),n=m((null==t?void 0:t.authInfo)||t||{});return{userInfo:(null==n?void 0:n.user)||((null==n?void 0:n.hasOwnProperty("userId"))?n:void 0),lastAuth:t.lastAuth}})(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],s=null==o?void 0:o.name;r?(ce(r),(e=>{I(ae,e)})(s)):(null==i?void 0:i.loginId)&&ce(i.loginId)}}));let c=o(a,["flow.start"],ue);return c=o(c,["logout","logoutAll"],pe(r)),Object.assign(c,{getLastUserLoginId:le,getLastUserDisplayName:de})}),(t=>n=>{var{persistTokens:r,sessionTokenViaCookie:s,refreshTokenViaCookie:a,storagePrefix:c,refreshCookieName:d}=n,u=e(n,["persistTokens","sessionTokenViaCookie","refreshTokenViaCookie","storagePrefix","refreshCookieName"]);if(!r||!l)return t(Object.assign({refreshCookieName:d},u));let p;const f=t(y(Object.assign({refreshCookieName:d},u),{beforeRequest:F(c,a,d),afterRequest:async(e,t)=>{if(S(e,t))U("Session invalidated, clearing persisted tokens"),V(c,s,a,p);else{const e=await b(t);e.cookieName?I(`${c||""}${$}`,e.cookieName):e.refreshJwt&&x(`${c||""}${$}`);const n=((e={},t=!1,n="",o=!1)=>{var r,s,a,c;const{sessionJwt:l,refreshJwt:d,trustedDeviceJwt:u}=e;let p;if(d)if(o){x(`${n}${A}`);const t=o.sameSite||"Strict",i=null===(r=o.secure)||void 0===r||r,a=null!==(s=o.domain)&&void 0!==s?s:e.cookieDomain,c=P(o);i&&"https:"!==window.location.protocol&&D("Refresh token cookie is configured with secure=true but the page is not using HTTPS. The cookie will not be set. To fix this, pass refreshTokenViaCookie: { secure: process.env['NODE_ENV'] !== 'development' }");const l=Object.assign(Object.assign({},e),{cookieSameSite:t,cookieSecure:i,cookieDomain:a});E(c,d,l);const u=N(a);p=Object.assign(Object.assign({},p),{refresh:{path:l.cookiePath,domain:u?a:void 0}})}else{const e=P(o);i.remove(e),I(`${n}${A}`,d)}if(l)if(t){const n=t.sameSite||"Strict",o=null===(a=t.secure)||void 0===a||a,i=null!==(c=t.domain)&&void 0!==c?c:e.cookieDomain,r=J(t);o&&"https:"!==window.location.protocol&&D("Session token cookie is configured with secure=true but the page is not using HTTPS. The cookie will not be set. To fix this, pass sessionTokenViaCookie: { secure: process.env['NODE_ENV'] !== 'development' }");const s=Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:o,cookieDomain:i});E(r,l,s);const d=N(i);p=Object.assign(Object.assign({},p),{session:{path:s.cookiePath,domain:d?i:void 0}})}else I(`${n}${C}`,l);return e.idToken&&I(`${n}${R}`,e.idToken),u&&I(`${n}DTD`,u),p})(e,s,c,a);n&&(p=n)}}})),g=o(f,["logout","logoutAll","oidc.logout"],ge(c,s,a,(()=>p)));return Object.assign(g,{getRefreshToken:()=>L(c,a),getSessionToken:()=>K(c,s),getIdToken:()=>q(c)})}))((e=>{const t=n(e),o=$e(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async(n,i)=>{var r;if(k())return U(`Refresh called in native flow: ${(new Error).stack}`),Promise.resolve({ok:!1,error:{errorCode:"J171000",errorDescription:"Refresh is not supported in native flows via the web SDK"}});if(e.oidcConfig)try{return await o.refreshToken(n),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const s=K(),a=L();let c="";if(e.getExternalToken)try{c=await(null===(r=e.getExternalToken)||void 0===r?void 0:r.call(e))}catch(e){U("Error getting external token while refreshing",e)}return t.refresh(n,{dcs:s?"t":"f",dcr:a?"t":"f"},c,i)},logout:async n=>{if(e.oidcConfig)try{return await o.logout({id_token_hint:n}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(n)},flow:De(t),webauthn:Ie(t),fedcm:(i=t,r=e.projectId,{onetap:{requestExchangeCode(e){je(i,e)},requestAuthentication(e){je(i,e)}},async oneTap(e,t,n,o,r){await Ue(i,{provider:e,oneTapConfig:t,loginOptions:n,onSkipped:o,onDismissed:r})},async launch(e){var t;const n={identity:{context:e||"signin",providers:[{configURL:i.httpClient.buildUrl(r+_e.config),clientId:r}]}},o=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return i.refresh(o.token)},isSupported:()=>l&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=i.httpClient.buildUrl(r+_e.config);try{const o={identity:{context:e||"signin",providers:[{configURL:n,clientId:r}]}},i=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(o));return!!i&&!!i.token}catch(e){return!1}}}),oidc:o});var i,r}));export{A as REFRESH_TOKEN_KEY,C as SESSION_TOKEN_KEY,Z as clearFingerprintData,Ee as createSdk,Ee as default,X as ensureFingerprintIds,K as getSessionToken,Te as hasOidcParamsInUrl};
2
2
  //# sourceMappingURL=index.esm.js.map