@descope/web-js-sdk 1.33.6 → 1.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -174,6 +174,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
174
174
  locale?: string;
175
175
  oidcPrompt?: string;
176
176
  oidcErrorRedirectUri?: string;
177
+ oidcResource?: string;
177
178
  nativeOptions?: {
178
179
  platform: "ios" | "android";
179
180
  oauthProvider?: string;
@@ -183,7 +184,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
183
184
  applicationScopes?: string;
184
185
  outboundAppId?: string;
185
186
  outboundAppScopes?: string[];
186
- }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
187
+ }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "oidcResource" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
187
188
  lastAuth?: Omit<{
188
189
  authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
189
190
  oauthProvider?: string;
@@ -845,6 +846,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
845
846
  locale?: string;
846
847
  oidcPrompt?: string;
847
848
  oidcErrorRedirectUri?: string;
849
+ oidcResource?: string;
848
850
  nativeOptions?: {
849
851
  platform: "ios" | "android";
850
852
  oauthProvider?: string;
@@ -854,7 +856,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
854
856
  applicationScopes?: string;
855
857
  outboundAppId?: string;
856
858
  outboundAppScopes?: string[];
857
- }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
859
+ }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "oidcResource" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
858
860
  lastAuth?: Omit<{
859
861
  authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
860
862
  oauthProvider?: string;
@@ -1516,6 +1518,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
1516
1518
  locale?: string;
1517
1519
  oidcPrompt?: string;
1518
1520
  oidcErrorRedirectUri?: string;
1521
+ oidcResource?: string;
1519
1522
  nativeOptions?: {
1520
1523
  platform: "ios" | "android";
1521
1524
  oauthProvider?: string;
@@ -1525,7 +1528,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
1525
1528
  applicationScopes?: string;
1526
1529
  outboundAppId?: string;
1527
1530
  outboundAppScopes?: string[];
1528
- }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
1531
+ }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "oidcResource" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
1529
1532
  lastAuth?: Omit<{
1530
1533
  authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
1531
1534
  oauthProvider?: string;
@@ -2194,6 +2197,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
2194
2197
  locale?: string;
2195
2198
  oidcPrompt?: string;
2196
2199
  oidcErrorRedirectUri?: string;
2200
+ oidcResource?: string;
2197
2201
  nativeOptions?: {
2198
2202
  platform: "ios" | "android";
2199
2203
  oauthProvider?: string;
@@ -2203,7 +2207,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
2203
2207
  applicationScopes?: string;
2204
2208
  outboundAppId?: string;
2205
2209
  outboundAppScopes?: string[];
2206
- }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
2210
+ }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "oidcResource" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
2207
2211
  lastAuth?: Omit<{
2208
2212
  authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
2209
2213
  oauthProvider?: string;
@@ -2865,6 +2869,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
2865
2869
  locale?: string;
2866
2870
  oidcPrompt?: string;
2867
2871
  oidcErrorRedirectUri?: string;
2872
+ oidcResource?: string;
2868
2873
  nativeOptions?: {
2869
2874
  platform: "ios" | "android";
2870
2875
  oauthProvider?: string;
@@ -2874,7 +2879,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
2874
2879
  applicationScopes?: string;
2875
2880
  outboundAppId?: string;
2876
2881
  outboundAppScopes?: string[];
2877
- }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
2882
+ }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "oidcResource" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
2878
2883
  lastAuth?: Omit<{
2879
2884
  authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
2880
2885
  oauthProvider?: string;
@@ -3536,6 +3541,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
3536
3541
  locale?: string;
3537
3542
  oidcPrompt?: string;
3538
3543
  oidcErrorRedirectUri?: string;
3544
+ oidcResource?: string;
3539
3545
  nativeOptions?: {
3540
3546
  platform: "ios" | "android";
3541
3547
  oauthProvider?: string;
@@ -3545,7 +3551,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
3545
3551
  applicationScopes?: string;
3546
3552
  outboundAppId?: string;
3547
3553
  outboundAppScopes?: string[];
3548
- }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
3554
+ }, "tenant" | "redirectUrl" | "redirectAuth" | "oidcIdpStateId" | "samlIdpStateId" | "samlIdpUsername" | "ssoAppId" | "thirdPartyAppId" | "oidcLoginHint" | "preview" | "abTestingKey" | "client" | "locale" | "oidcPrompt" | "oidcErrorRedirectUri" | "oidcResource" | "nativeOptions" | "thirdPartyAppStateId" | "applicationScopes" | "outboundAppId" | "outboundAppScopes"> & {
3549
3555
  lastAuth?: Omit<{
3550
3556
  authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
3551
3557
  oauthProvider?: 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 a,defaultScriptUrlPattern as s}from"@fingerprintjs/fingerprintjs-pro";const c=e=>{try{return t(e).exp}catch(e){return null}},l=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:c(n)},d=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?c(o):void 0)},u=(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},p=async t=>{if(!(null==t?void 0:t.ok))return{};const n=await(null==t?void 0:t.clone().json());return(t=>{const{access_token:n,id_token:o,refresh_token:i,refresh_expire_in:r}=t,a=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||d(t),cookieExpiration:t.cookieExpiration||l(t)},a)})((null==n?void 0:n.authInfo)||n||{})},g=async e=>{const t=await p(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},f="undefined"!=typeof localStorage,w=(e,t)=>f&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),h=e=>f&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),v=e=>f&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),y=(...e)=>{console.debug(...e)},m="3.2.0",b="undefined"!=typeof window,S=Math.pow(2,31)-1,k=`https://descopecdn.com/npm/oidc-client-ts@${m}/dist/browser/oidc-client-ts.min.js`,I=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${m}/dist/browser/oidc-client-ts.min.js`,_=e=>{let t=((n=e)?n.getTime()-(new Date).getTime():0)-2e4;var n;return t>S&&(y(`Timeout is too large (${t}ms), setting it to ${S}ms`),t=S),t},O="DS",x="DSR",U="DSI";function j(e,t,n){if(t){const{cookieDomain:o,cookiePath:r,cookieSameSite:a,cookieExpiration:s,cookieSecure:c}=n,l=new Date(1e3*s),d=function(e){const t=window.location.hostname.split("."),n=e.split(".");return t.slice(-n.length).join(".")===e}(o);i.set(e,t,{path:r,domain:d?o:void 0,expires:l,sameSite:a,secure:c})}}function C(e=""){return h(`${e}${x}`)||""}function D(e=""){return i.get(O)||h(`${e}${O}`)||""}function R(e=""){return h(`${e}${U}`)||""}function T(e=""){v(`${e}${x}`),v(`${e}${O}`),v(`${e}${U}`),i.remove(O)}const A=b&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",E="vsid",J="vrid",$="fp",L=(e=!1)=>{const t=localStorage.getItem($);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},N=async(e,t=A)=>{try{if(L())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(),a],scriptUrlPattern:[c,s]}),d=await l,{requestId:u}=await d.get({linkedId:n}),p=((e,t)=>({[E]:e,[J]:t}))(n,u);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem($,JSON.stringify(t))})(p)}catch(e){console.warn("Could not load fingerprint",e)}},P=()=>{localStorage.removeItem($)},K=e=>{const t=L(!0);return t&&e.body&&(e.body.fpData=t),e},q="descopeFlowNonce",F="X-Descope-Flow-Nonce",V="/v1/flow/start",M="/v1/flow/next",H=(e,t=q)=>`${t}${e}`,B=(e,t=q)=>{try{const n=H(e,t);v(n)}catch(e){console.error("Error removing flow nonce:",e)}},G=e=>{var t;return(null===(t=/.*\|#\|(.*)/.exec(e))||void 0===t?void 0:t[1])||null},W=e=>{var t;return e.path===M&&(null===(t=e.body)||void 0===t?void 0:t.executionId)?G(e.body.executionId):null},X="dls_last_user_login_id",Z="dls_last_user_display_name",z=()=>h(X),Q=()=>h(Z),Y=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=z(),r=Q();i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r);return await e(...t)},ee=e=>t=>async(...n)=>{const o=await t(...n);return e||(v(X),v(Z)),o};function te(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const ne=e=>t=>async(...n)=>{const o=await t(...n);return T(e),o};async function oe(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=le(n.publicKey.challenge),n.publicKey.user.id=le(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=le(e.id)})),n}(e),n=await navigator.credentials.create(t);return o=n,JSON.stringify({id:o.id,rawId:de(o.rawId),type:o.type,response:{attestationObject:de(o.response.attestationObject),clientDataJSON:de(o.response.clientDataJSON)}});var o}async function ie(e){const t=se(e);return ce(await navigator.credentials.get(t))}async function re(e,t){const n=se(e);n.signal=t.signal,n.mediation="conditional";return ce(await navigator.credentials.get(n))}async function ae(e=!1){if(!b)return Promise.resolve(!1);const t=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function se(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=le(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=le(e.id)})),n}function ce(e){return JSON.stringify({id:e.id,rawId:de(e.rawId),type:e.type,response:{authenticatorData:de(e.response.authenticatorData),clientDataJSON:de(e.response.clientDataJSON),signature:de(e.response.signature),userHandle:e.response.userHandle?de(e.response.userHandle):void 0}})}function le(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function de(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var ue,pe=(ue=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 oe(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 ie(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 oe(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,t)}{const t=await ie(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 oe(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:oe,get:ie,isSupported:ae,conditional:re}}),(...e)=>{const t=ue(...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 ge={config:"/fedcm/config"},fe=()=>{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 we(e,t){var n;try{await he(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function he(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=fe(),a=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")}}))}(),s=await e.oauth.getOneTapClientId(t);if(!s.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const c=s.data.clientId;return new Promise((e=>{var s,l;const d=n=>{e({provider:t,nonce:r,credential:null==n?void 0:n.credential})};a.initialize(Object.assign(Object.assign({},n),{itp_support:null===(s=null==n?void 0:n.itp_support)||void 0===s||s,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})),a.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 ve=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await ae(),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 ye=()=>window.location.search.includes("code")&&window.location.search.includes("state");let me;const be=(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(),a=document.createElement("script");a.src=r,a.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),a.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},a.addEventListener("error",(()=>{be(e,t),a.setAttribute("data-error","true")})),document.body.appendChild(a)}));const Se=async(e,t,n)=>{me||(me=(async()=>{try{return require("oidc-client-ts")}catch(e){return be([k,I],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:i}=await me;if(!o)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=t,a=(null==n?void 0:n.redirectUri)||window.location.href,s=(null==n?void 0:n.scope)||"openid email roles descope.custom_claims offline_access",c=`${r}_user`;let l=e.httpClient.buildUrl(t);(null==n?void 0:n.applicationId)&&(l=`${l}/${n.applicationId}`);const d={authority:l,client_id:t,redirect_uri:a,response_type:"code",scope:s,stateStore:new i({store:window.localStorage,prefix:r}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(d.redirect_uri=n.redirectUri),(null==n?void 0:n.scope)&&(d.scope=n.scope),{client:new o(d),stateUserKey:c}},ke=(e,t,n)=>{const o=async()=>{let o,i;return o&&i||({client:o,stateUserKey:i}=await Se(e,t,n)),{client:o,stateUserKey:i}},i=async(t="")=>{var n;const{client:i,stateUserKey:r}=await o(),a=await i.processSigninResponse(t||window.location.href);var s;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(a)))),window.localStorage.setItem(r,JSON.stringify({id_token:(s=a).id_token,session_state:s.session_state,profile:s.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),a};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(ye())return await i(e)},refreshToken:async t=>{var n;const{client:i,stateUserKey:r}=await o(),a=(e=>{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null})(r);if(!a)throw new Error("User not found in storage to refresh token");let s=t;if(!s){const t={};e.httpClient.hooks.beforeRequest(t),s=t.token}const c=await i.useRefreshToken({state:{refresh_token:s,session_state:a.session_state,profile:a.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||R(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await n.createSignoutRequest(e),{url:a}=r;return window.localStorage.removeItem(i),t||window.location.replace(a),r}}},Ie=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((t=>n=>{var{fpKey:o,fpLoad:i}=n,r=e(n,["fpKey","fpLoad"]);return b?(o&&i&&N(o).catch((()=>null)),t(u(r,{beforeRequest:K}))):t(r)}),(n=>i=>{var{autoRefresh:r}=i,a=e(i,["autoRefresh"]);if(!r||"undefined"!=typeof window&&window.descopeBridge)return n(a);const{clearAllTimers:s,setTimer:c}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let l,d;b&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&l&&new Date>l&&(y("Expiration time passed, refreshing session"),g.refresh(C()||d))}));const g=n(u(a,{afterRequest:async(e,n)=>{const{sessionJwt:o,refreshJwt:i,sessionExpiration:r}=await p(n);if(401===(null==n?void 0:n.status))y("Received 401, canceling all timers"),s();else if(o||r){if(l=((e,n)=>{if(n)return new Date(1e3*n);y("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),!l)return void y("Could not extract expiration time from session token");d=i;const e=_(l);if(s(),e<=2e4)return void y("Session is too close to expiration, not setting refresh timer");const n=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});y(`Setting refresh timer for ${n}. (${e}ms)`),c((()=>{y("Refreshing session due to timer"),g.refresh(C()||i)}),e)}}}));return o(g,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return y("Clearing all timers"),s(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.33.6"},t.baseHeaders)}))),(e=>t=>{const n=te(),i=te(),r=te(),a=e(u(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))i.pub(null),r.pub(null),n.pub(null);else{const e=await g(t);e&&r.pub(e);const{sessionJwt:o,sessionExpiration:a}=await p(t);o&&i.pub(o),(a||o)&&n.pub(a||42)}}})),s=o(a,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const o=await e(...t);return i.pub(null),r.pub(null),n.pub(null),o}));return Object.assign(s,{onSessionTokenChange:i.sub,onUserChange:r.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(!f)return;for(let t=0;t<localStorage.length;t++){const n=localStorage.key(t);if(n&&n.startsWith(e)){const e=h(n);if(e)try{JSON.parse(e).expiry<Date.now()&&v(n)}catch(e){v(n)}}}}catch(e){console.error("Error cleaning up expired nonces:",e)}})(i);return t(u(r,{afterRequest:async(e,t)=>{if(e.path!==V&&e.path!==M)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(F);let o=await t.clone().json().then((e=>(null==e?void 0:e.executionId)||null)).catch((()=>null));return o||(o=W(e)),{nonce:n,executionId:G(o)}}catch(e){return{nonce:null,executionId:null}}})(e,t);if(n&&o){((e,t,n,o=q)=>{try{const i=H(e,o),r=n?172800:10800,a={value:t,expiry:Date.now()+1e3*r,isStart:n};w(i,JSON.stringify(a))}catch(e){console.error("Error setting flow nonce:",e)}})(o,n,e.path===V,i)}},beforeRequest:e=>{if(e.path===M){const t=W(e);if(t){const n=((e,t=q)=>{try{const n=H(e,t),o=h(n);if(!o)return null;const i=JSON.parse(o);return i.expiry<Date.now()?(B(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[F]=n)}}return e}}))}),(t=>n=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:r=!1}=n,a=e(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(t(a),{getLastUserLoginId:z,getLastUserDisplayName:Q});const s=t(u(a,{afterRequest:async(e,t)=>{var n;const o=await g(t),i=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],r=null==o?void 0:o.name;i&&((e=>{w(X,e)})(i),(e=>{w(Z,e)})(r))}}));let c=o(s,["flow.start"],Y);return c=o(c,["logout","logoutAll"],ee(r)),Object.assign(c,{getLastUserLoginId:z,getLastUserDisplayName:Q})}),(t=>n=>{var{persistTokens:i,sessionTokenViaCookie:r,storagePrefix:a}=n,s=e(n,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!i||!b)return t(s);const c=t(u(s,{beforeRequest:(l=a,e=>Object.assign(e,{token:e.token||C(l)})),afterRequest:async(e,t)=>{const n=/^\/v\d+\/mgmt\//.test(e.path);401===(null==t?void 0:t.status)?n||T(a):((e={},t=!1,n="")=>{var o;const{sessionJwt:i,refreshJwt:r}=e;if(r&&w(`${n}${x}`,r),i)if(t){const n=t.sameSite||"Strict",r=null===(o=t.secure)||void 0===o||o;j(O,i,Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:r}))}else w(`${n}${O}`,i);e.idToken&&w(`${n}${U}`,e.idToken)})(await p(t),r,a)}}));var l;const d=o(c,["logout","logoutAll","oidc.logout"],ne(a));return Object.assign(d,{getRefreshToken:()=>C(a),getSessionToken:()=>D(a),getIdToken:()=>R(a)})}))((e=>{const t=n(e),o=ke(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async n=>{var i;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 r=D(),a=C();let s="";if(e.getExternalToken)try{s=await(null===(i=e.getExternalToken)||void 0===i?void 0:i.call(e))}catch(e){y("Error getting external token while refreshing",e)}return t.refresh(n,{dcs:r?"t":"f",dcr:a?"t":"f"},s)},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:ve(t),webauthn:pe(t),fedcm:(i=t,r=e.projectId,{onetap:{requestExchangeCode(e){we(i,e)},requestAuthentication(e){we(i,e)}},async oneTap(e,t,n,o,r){await he(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+ge.config),clientId:r}]}},o=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return i.refresh(o.token)},isSupported:()=>b&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=i.httpClient.buildUrl(r+ge.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{x as REFRESH_TOKEN_KEY,O as SESSION_TOKEN_KEY,P as clearFingerprintData,Ie as default,N as ensureFingerprintIds,ye 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 a,defaultScriptUrlPattern as s}from"@fingerprintjs/fingerprintjs-pro";const c=e=>{try{return t(e).exp}catch(e){return null}},l=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:c(n)},d=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?c(o):void 0)},u=(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},p=async t=>{if(!(null==t?void 0:t.ok))return{};const n=await(null==t?void 0:t.clone().json());return(t=>{const{access_token:n,id_token:o,refresh_token:i,refresh_expire_in:r}=t,a=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||d(t),cookieExpiration:t.cookieExpiration||l(t)},a)})((null==n?void 0:n.authInfo)||n||{})},g=async e=>{const t=await p(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},f="undefined"!=typeof localStorage,w=(e,t)=>f&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),h=e=>f&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),v=e=>f&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),y=(...e)=>{console.debug(...e)},m="3.2.0",b="undefined"!=typeof window,S=Math.pow(2,31)-1,k=`https://descopecdn.com/npm/oidc-client-ts@${m}/dist/browser/oidc-client-ts.min.js`,I=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${m}/dist/browser/oidc-client-ts.min.js`,_=e=>{let t=((n=e)?n.getTime()-(new Date).getTime():0)-2e4;var n;return t>S&&(y(`Timeout is too large (${t}ms), setting it to ${S}ms`),t=S),t},O="DS",x="DSR",U="DSI";function j(e,t,n){if(t){const{cookieDomain:o,cookiePath:r,cookieSameSite:a,cookieExpiration:s,cookieSecure:c}=n,l=new Date(1e3*s),d=function(e){const t=window.location.hostname.split("."),n=e.split(".");return t.slice(-n.length).join(".")===e}(o);i.set(e,t,{path:r,domain:d?o:void 0,expires:l,sameSite:a,secure:c})}}function C(e=""){return h(`${e}${x}`)||""}function D(e=""){return i.get(O)||h(`${e}${O}`)||""}function R(e=""){return h(`${e}${U}`)||""}function T(e=""){v(`${e}${x}`),v(`${e}${O}`),v(`${e}${U}`),i.remove(O)}const A=b&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",E="vsid",J="vrid",$="fp",L=(e=!1)=>{const t=localStorage.getItem($);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},N=async(e,t=A)=>{try{if(L())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(),a],scriptUrlPattern:[c,s]}),d=await l,{requestId:u}=await d.get({linkedId:n}),p=((e,t)=>({[E]:e,[J]:t}))(n,u);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem($,JSON.stringify(t))})(p)}catch(e){console.warn("Could not load fingerprint",e)}},P=()=>{localStorage.removeItem($)},K=e=>{const t=L(!0);return t&&e.body&&(e.body.fpData=t),e},q="descopeFlowNonce",F="X-Descope-Flow-Nonce",V="/v1/flow/start",M="/v1/flow/next",H=(e,t=q)=>`${t}${e}`,B=(e,t=q)=>{try{const n=H(e,t);v(n)}catch(e){console.error("Error removing flow nonce:",e)}},G=e=>{var t;return(null===(t=/.*\|#\|(.*)/.exec(e))||void 0===t?void 0:t[1])||null},W=e=>{var t;return e.path===M&&(null===(t=e.body)||void 0===t?void 0:t.executionId)?G(e.body.executionId):null},X="dls_last_user_login_id",Z="dls_last_user_display_name",z=()=>h(X),Q=()=>h(Z),Y=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=z(),r=Q();i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r);return await e(...t)},ee=e=>t=>async(...n)=>{const o=await t(...n);return e||(v(X),v(Z)),o};function te(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const ne=e=>t=>async(...n)=>{const o=await t(...n);return T(e),o};async function oe(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=le(n.publicKey.challenge),n.publicKey.user.id=le(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=le(e.id)})),n}(e),n=await navigator.credentials.create(t);return o=n,JSON.stringify({id:o.id,rawId:de(o.rawId),type:o.type,response:{attestationObject:de(o.response.attestationObject),clientDataJSON:de(o.response.clientDataJSON)}});var o}async function ie(e){const t=se(e);return ce(await navigator.credentials.get(t))}async function re(e,t){const n=se(e);n.signal=t.signal,n.mediation="conditional";return ce(await navigator.credentials.get(n))}async function ae(e=!1){if(!b)return Promise.resolve(!1);const t=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function se(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=le(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=le(e.id)})),n}function ce(e){return JSON.stringify({id:e.id,rawId:de(e.rawId),type:e.type,response:{authenticatorData:de(e.response.authenticatorData),clientDataJSON:de(e.response.clientDataJSON),signature:de(e.response.signature),userHandle:e.response.userHandle?de(e.response.userHandle):void 0}})}function le(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function de(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var ue,pe=(ue=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 oe(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 ie(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 oe(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,t)}{const t=await ie(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 oe(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:oe,get:ie,isSupported:ae,conditional:re}}),(...e)=>{const t=ue(...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 ge={config:"/fedcm/config"},fe=()=>{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 we(e,t){var n;try{await he(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function he(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=fe(),a=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")}}))}(),s=await e.oauth.getOneTapClientId(t);if(!s.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const c=s.data.clientId;return new Promise((e=>{var s,l;const d=n=>{e({provider:t,nonce:r,credential:null==n?void 0:n.credential})};a.initialize(Object.assign(Object.assign({},n),{itp_support:null===(s=null==n?void 0:n.itp_support)||void 0===s||s,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})),a.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 ve=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await ae(),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 ye=()=>window.location.search.includes("code")&&window.location.search.includes("state");let me;const be=(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(),a=document.createElement("script");a.src=r,a.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),a.onload=()=>{const e=t();if(e)return n(e);throw new Error("Could not get entry after loading script from URL")},a.addEventListener("error",(()=>{be(e,t),a.setAttribute("data-error","true")})),document.body.appendChild(a)}));const Se=async(e,t,n)=>{me||(me=(async()=>{try{return require("oidc-client-ts")}catch(e){return be([k,I],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:i}=await me;if(!o)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=t,a=(null==n?void 0:n.redirectUri)||window.location.href,s=(null==n?void 0:n.scope)||"openid email roles descope.custom_claims offline_access",c=`${r}_user`;let l=e.httpClient.buildUrl(t);(null==n?void 0:n.applicationId)&&(l=`${l}/${n.applicationId}`);const d={authority:l,client_id:t,redirect_uri:a,response_type:"code",scope:s,stateStore:new i({store:window.localStorage,prefix:r}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==n?void 0:n.redirectUri)&&(d.redirect_uri=n.redirectUri),(null==n?void 0:n.scope)&&(d.scope=n.scope),{client:new o(d),stateUserKey:c}},ke=(e,t,n)=>{const o=async()=>{let o,i;return o&&i||({client:o,stateUserKey:i}=await Se(e,t,n)),{client:o,stateUserKey:i}},i=async(t="")=>{var n;const{client:i,stateUserKey:r}=await o(),a=await i.processSigninResponse(t||window.location.href);var s;return await(null===(n=e.httpClient.hooks)||void 0===n?void 0:n.afterRequest({},new Response(JSON.stringify(a)))),window.localStorage.setItem(r,JSON.stringify({id_token:(s=a).id_token,session_state:s.session_state,profile:s.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),a};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(ye())return await i(e)},refreshToken:async t=>{var n;const{client:i,stateUserKey:r}=await o(),a=(e=>{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null})(r);if(!a)throw new Error("User not found in storage to refresh token");let s=t;if(!s){const t={};e.httpClient.hooks.beforeRequest(t),s=t.token}const c=await i.useRefreshToken({state:{refresh_token:s,session_state:a.session_state,profile:a.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||R(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await n.createSignoutRequest(e),{url:a}=r;return window.localStorage.removeItem(i),t||window.location.replace(a),r}}},Ie=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((t=>n=>{var{fpKey:o,fpLoad:i}=n,r=e(n,["fpKey","fpLoad"]);return b?(o&&i&&N(o).catch((()=>null)),t(u(r,{beforeRequest:K}))):t(r)}),(n=>i=>{var{autoRefresh:r}=i,a=e(i,["autoRefresh"]);if(!r||"undefined"!=typeof window&&window.descopeBridge)return n(a);const{clearAllTimers:s,setTimer:c}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let l,d;b&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&l&&new Date>l&&(y("Expiration time passed, refreshing session"),g.refresh(C()||d))}));const g=n(u(a,{afterRequest:async(e,n)=>{const{sessionJwt:o,refreshJwt:i,sessionExpiration:r}=await p(n);if(401===(null==n?void 0:n.status))y("Received 401, canceling all timers"),s();else if(o||r){if(l=((e,n)=>{if(n)return new Date(1e3*n);y("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),!l)return void y("Could not extract expiration time from session token");d=i;const e=_(l);if(s(),e<=2e4)return void y("Session is too close to expiration, not setting refresh timer");const n=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});y(`Setting refresh timer for ${n}. (${e}ms)`),c((()=>{y("Refreshing session due to timer"),g.refresh(C()||i)}),e)}}}));return o(g,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return y("Clearing all timers"),s(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.34.0"},t.baseHeaders)}))),(e=>t=>{const n=te(),i=te(),r=te(),a=e(u(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))i.pub(null),r.pub(null),n.pub(null);else{const e=await g(t);e&&r.pub(e);const{sessionJwt:o,sessionExpiration:a}=await p(t);o&&i.pub(o),(a||o)&&n.pub(a||42)}}})),s=o(a,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const o=await e(...t);return i.pub(null),r.pub(null),n.pub(null),o}));return Object.assign(s,{onSessionTokenChange:i.sub,onUserChange:r.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(!f)return;for(let t=0;t<localStorage.length;t++){const n=localStorage.key(t);if(n&&n.startsWith(e)){const e=h(n);if(e)try{JSON.parse(e).expiry<Date.now()&&v(n)}catch(e){v(n)}}}}catch(e){console.error("Error cleaning up expired nonces:",e)}})(i);return t(u(r,{afterRequest:async(e,t)=>{if(e.path!==V&&e.path!==M)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(F);let o=await t.clone().json().then((e=>(null==e?void 0:e.executionId)||null)).catch((()=>null));return o||(o=W(e)),{nonce:n,executionId:G(o)}}catch(e){return{nonce:null,executionId:null}}})(e,t);if(n&&o){((e,t,n,o=q)=>{try{const i=H(e,o),r=n?172800:10800,a={value:t,expiry:Date.now()+1e3*r,isStart:n};w(i,JSON.stringify(a))}catch(e){console.error("Error setting flow nonce:",e)}})(o,n,e.path===V,i)}},beforeRequest:e=>{if(e.path===M){const t=W(e);if(t){const n=((e,t=q)=>{try{const n=H(e,t),o=h(n);if(!o)return null;const i=JSON.parse(o);return i.expiry<Date.now()?(B(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[F]=n)}}return e}}))}),(t=>n=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:r=!1}=n,a=e(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(t(a),{getLastUserLoginId:z,getLastUserDisplayName:Q});const s=t(u(a,{afterRequest:async(e,t)=>{var n;const o=await g(t),i=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],r=null==o?void 0:o.name;i&&((e=>{w(X,e)})(i),(e=>{w(Z,e)})(r))}}));let c=o(s,["flow.start"],Y);return c=o(c,["logout","logoutAll"],ee(r)),Object.assign(c,{getLastUserLoginId:z,getLastUserDisplayName:Q})}),(t=>n=>{var{persistTokens:i,sessionTokenViaCookie:r,storagePrefix:a}=n,s=e(n,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!i||!b)return t(s);const c=t(u(s,{beforeRequest:(l=a,e=>Object.assign(e,{token:e.token||C(l)})),afterRequest:async(e,t)=>{const n=/^\/v\d+\/mgmt\//.test(e.path);401===(null==t?void 0:t.status)?n||T(a):((e={},t=!1,n="")=>{var o;const{sessionJwt:i,refreshJwt:r}=e;if(r&&w(`${n}${x}`,r),i)if(t){const n=t.sameSite||"Strict",r=null===(o=t.secure)||void 0===o||o;j(O,i,Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:r}))}else w(`${n}${O}`,i);e.idToken&&w(`${n}${U}`,e.idToken)})(await p(t),r,a)}}));var l;const d=o(c,["logout","logoutAll","oidc.logout"],ne(a));return Object.assign(d,{getRefreshToken:()=>C(a),getSessionToken:()=>D(a),getIdToken:()=>R(a)})}))((e=>{const t=n(e),o=ke(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async n=>{var i;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 r=D(),a=C();let s="";if(e.getExternalToken)try{s=await(null===(i=e.getExternalToken)||void 0===i?void 0:i.call(e))}catch(e){y("Error getting external token while refreshing",e)}return t.refresh(n,{dcs:r?"t":"f",dcr:a?"t":"f"},s)},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:ve(t),webauthn:pe(t),fedcm:(i=t,r=e.projectId,{onetap:{requestExchangeCode(e){we(i,e)},requestAuthentication(e){we(i,e)}},async oneTap(e,t,n,o,r){await he(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+ge.config),clientId:r}]}},o=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return i.refresh(o.token)},isSupported:()=>b&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=i.httpClient.buildUrl(r+ge.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{x as REFRESH_TOKEN_KEY,O as SESSION_TOKEN_KEY,P as clearFingerprintData,Ie as default,N as ensureFingerprintIds,ye as hasOidcParamsInUrl};
2
2
  //# sourceMappingURL=index.esm.js.map