@descope/web-js-sdk 1.43.1 → 1.45.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/cjs/index.cjs.js +1 -1
- package/dist/cjs/index.cjs.js.map +1 -1
- package/dist/index.d.ts +13 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +2 -2
- package/dist/index.umd.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -109,6 +109,12 @@ declare const ensureFingerprintIds: (fpKey: string, baseUrl?: string) => Promise
|
|
|
109
109
|
/** Clear Fingerprint data from storage */
|
|
110
110
|
declare const clearFingerprintData: () => void;
|
|
111
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Return the session token. first try to get from cookie, and fallback to local storage
|
|
114
|
+
* See sessionTokenViaCookie option for more details about session token location
|
|
115
|
+
*/
|
|
116
|
+
declare function getSessionToken(prefix?: string, sessionTokenViaCookie?: CookieConfig): string;
|
|
117
|
+
|
|
112
118
|
declare const hasOidcParamsInUrl: () => boolean;
|
|
113
119
|
|
|
114
120
|
declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPersistTokens, sessionTokenViaCookie, refreshTokenViaCookie, storagePrefix, ...config }: {
|
|
@@ -747,6 +753,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
747
753
|
scopes?: string[];
|
|
748
754
|
tenantId?: string;
|
|
749
755
|
tenantLevel?: boolean;
|
|
756
|
+
externalIdentifier?: string;
|
|
750
757
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
751
758
|
};
|
|
752
759
|
saml: {
|
|
@@ -1466,6 +1473,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
1466
1473
|
scopes?: string[];
|
|
1467
1474
|
tenantId?: string;
|
|
1468
1475
|
tenantLevel?: boolean;
|
|
1476
|
+
externalIdentifier?: string;
|
|
1469
1477
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
1470
1478
|
};
|
|
1471
1479
|
saml: {
|
|
@@ -2185,6 +2193,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
2185
2193
|
scopes?: string[];
|
|
2186
2194
|
tenantId?: string;
|
|
2187
2195
|
tenantLevel?: boolean;
|
|
2196
|
+
externalIdentifier?: string;
|
|
2188
2197
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
2189
2198
|
};
|
|
2190
2199
|
saml: {
|
|
@@ -2912,6 +2921,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
2912
2921
|
scopes?: string[];
|
|
2913
2922
|
tenantId?: string;
|
|
2914
2923
|
tenantLevel?: boolean;
|
|
2924
|
+
externalIdentifier?: string;
|
|
2915
2925
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
2916
2926
|
};
|
|
2917
2927
|
saml: {
|
|
@@ -3631,6 +3641,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
3631
3641
|
scopes?: string[];
|
|
3632
3642
|
tenantId?: string;
|
|
3633
3643
|
tenantLevel?: boolean;
|
|
3644
|
+
externalIdentifier?: string;
|
|
3634
3645
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
3635
3646
|
};
|
|
3636
3647
|
saml: {
|
|
@@ -4350,6 +4361,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
4350
4361
|
scopes?: string[];
|
|
4351
4362
|
tenantId?: string;
|
|
4352
4363
|
tenantLevel?: boolean;
|
|
4364
|
+
externalIdentifier?: string;
|
|
4353
4365
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
4354
4366
|
};
|
|
4355
4367
|
saml: {
|
|
@@ -4483,4 +4495,4 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
4483
4495
|
getIdToken: () => string;
|
|
4484
4496
|
};
|
|
4485
4497
|
|
|
4486
|
-
export { type CookieConfig, type CustomStorage, type FlowNonceOptions, type OidcConfig, type OneTapConfig, REFRESH_TOKEN_KEY, SESSION_TOKEN_KEY, clearFingerprintData, decoratedCreateSdk as createSdk, decoratedCreateSdk as default, ensureFingerprintIds, hasOidcParamsInUrl };
|
|
4498
|
+
export { type CookieConfig, type CustomStorage, type FlowNonceOptions, type OidcConfig, type OneTapConfig, REFRESH_TOKEN_KEY, SESSION_TOKEN_KEY, clearFingerprintData, decoratedCreateSdk as createSdk, decoratedCreateSdk as default, ensureFingerprintIds, getSessionToken, hasOidcParamsInUrl };
|
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 l="3.2.0",c="undefined"!=typeof window,d=Math.pow(2,31)-1,u=`https://descopecdn.com/npm/oidc-client-ts@${l}/dist/browser/oidc-client-ts.min.js`,p=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${l}/dist/browser/oidc-client-ts.min.js`;let g;const f=e=>{try{return t(e).exp}catch(e){return null}},v=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:f(n)},w=e=>{const{expires_in:t,expires_at:n,access_token:o}=e;return n||(t?Math.floor(Date.now()/1e3)+t:o?f(o):void 0)},h=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||v(t)},s)},m=(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},y=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 h(n)},b=()=>c&&!!window.descopeBridge,k=void 0!==g||c&&void 0!==window.localStorage,S=(e,t)=>{var n,o;return null===(o=null===(n=g||c&&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||c&&window.localStorage)||void 0===t?void 0:t.getItem)||void 0===n?void 0:n.call(t,e)},O=e=>{var t,n;return null===(n=null===(t=g||c&&window.localStorage)||void 0===t?void 0:t.removeItem)||void 0===n?void 0:n.call(t,e)},_=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:c&&(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},x=(...e)=>{console.debug(...e)},D=(e,t)=>{let n;var o;return t>0?(n=1e3*t,x(`Using provided nextRefreshSeconds: ${t}s`)):n=((o=e)?o.getTime()-(new Date).getTime():0)-2e4,n>d&&(x(`Timeout is too large (${n}ms), setting it to ${d}ms`),n=d),n},j="DS",U="DSR",C="DSI";function R(e,t,n){if(t){const{cookieDomain:o,cookiePath:r,cookieSameSite:s,cookieExpiration:a,cookieSecure:l}=n,c=new Date(1e3*a),d=T(o);i.set(e,t,{path:r,domain:d?o:void 0,expires:c,sameSite:s,secure:l})}}function T(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 $=e=>(null==e?void 0:e.cookieName)||j,A=e=>(null==e?void 0:e.cookieName)||U;function E(e="",t){return i.get(A(t))||I(`${e}${U}`)||""}function J(e="",t){return i.get($(t))||I(`${e}${j}`)||""}function L(e=""){return I(`${e}${C}`)||""}function N(e="",t,n,o){O(`${e}${U}`),O(`${e}${j}`),O(`${e}${C}`);const r=$(t);i.remove(r,null==o?void 0:o.session);const s=A(n);i.remove(s,null==o?void 0:o.refresh)}const P=(e,t)=>n=>{const o=Object.assign(n,{token:n.token||E(e,t)}),i=function(e=""){return I(`${e}DTD`)||""}(e);return i&&(o.headers=Object.assign(Object.assign({},o.headers||{}),{"x-descope-trusted-device-token":i})),o},K=c&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",q="vsid",V="vrid",F="fp",M=(e=!1)=>{const t=I(F);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},B=async(e,t=K)=>{try{if(M())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 l=i.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",c=r({apiKey:e,endpoint:[o.toString(),s],scriptUrlPattern:[l,a]}),d=await c,{requestId:u}=await d.get({linkedId:n}),p=((e,t)=>({[q]:e,[V]:t}))(n,u);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};S(F,JSON.stringify(t))})(p)}catch(e){console.warn("Could not load fingerprint",e)}},H=()=>{O(F)},G=e=>{const t=M(!0);return t&&e.body&&(e.body.fpData=t),e},W="descopeFlowNonce",X="X-Descope-Flow-Nonce",Z="/v1/flow/start",z="/v1/flow/next",Q=(e,t=W)=>`${t}${e}`,Y=(e,t=W)=>{try{const n=Q(e,t);O(n)}catch(e){console.error("Error removing flow nonce:",e)}},ee=e=>{var t;return(null===(t=/.*\|#\|(.*)/.exec(e))||void 0===t?void 0:t[1])||null},te=e=>{var t;return e.path===z&&(null===(t=e.body)||void 0===t?void 0:t.executionId)?ee(e.body.executionId):null},ne="dls_last_user_login_id",oe="dls_last_user_display_name",ie=e=>S(ne,e),re=()=>I(ne),se=()=>I(oe),ae=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=re(),r=se();i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r);return await e(...t)},le=e=>t=>async(...n)=>{const o=await t(...n);return e||(O(ne),O(oe)),o};function ce(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const de=(e,t,n,o)=>i=>async(...r)=>{const s=await i(...r);return N(e,t,n,null==o?void 0:o()),s};async function ue(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=he(n.publicKey.challenge),n.publicKey.user.id=he(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=he(e.id)})),n}(e),n=await navigator.credentials.create(t);return o=n,JSON.stringify({id:o.id,rawId:me(o.rawId),type:o.type,response:{attestationObject:me(o.response.attestationObject),clientDataJSON:me(o.response.clientDataJSON)}});var o}async function pe(e){const t=ve(e);return we(await navigator.credentials.get(t))}async function ge(e,t){const n=ve(e);n.signal=t.signal,n.mediation="conditional";return we(await navigator.credentials.get(n))}async function fe(e=!1){var t,n;if(!c)return Promise.resolve(!1);if(b()){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 ve(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=he(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=he(e.id)})),n}function we(e){return JSON.stringify({id:e.id,rawId:me(e.rawId),type:e.type,response:{authenticatorData:me(e.response.authenticatorData),clientDataJSON:me(e.response.clientDataJSON),signature:me(e.response.signature),userHandle:e.response.userHandle?me(e.response.userHandle):void 0}})}function he(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function me(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var ye,be=(ye=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 ue(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 pe(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 ue(i.data.options);return await e.webauthn.signUp.finish(i.data.transactionId,t)}{const t=await pe(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 ue(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:ue,get:pe,isSupported:fe,conditional:ge}}),(...e)=>{const t=ye(...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 ke={config:"/fedcm/config"},Se=()=>{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 Ie(e,t){var n;try{await Oe(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function Oe(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=Se(),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 l=a.data.clientId;return new Promise((e=>{var a,c;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===(c=null==n?void 0:n.use_fedcm_for_prompt)||void 0===c||c,client_id:l,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 _e=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await fe(),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 xe=()=>window.location.search.includes("code")&&window.location.search.includes("state");let De;const je=(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",(()=>{je(e,t),s.setAttribute("data-error","true")})),document.body.appendChild(s)}));const Ue=async(e,t,n)=>{De||(De=(async()=>{try{return require("oidc-client-ts")}catch(e){return je([u,p],(()=>window.oidc))}})());const{OidcClient:o,WebStorageStateStore:i}=await De;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,l,c;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,l=`${a}_user`,c="openid"}else(null==n?void 0:n.applicationId)?(s=e.httpClient.buildUrl(t),s=`${s}/${n.applicationId}`,a=t,l=`${a}_user`,c="openid email roles descope.custom_claims offline_access"):(s=e.httpClient.buildUrl(t),a=t,l=`${a}_user`,c="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)||c,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:l}},Ce=(e,t,n)=>{const o=async()=>{let o,i;return o&&i||({client:o,stateUserKey:i}=await Ue(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)))),S(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(xe())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 l=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(l)))),l},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 O(i),t||window.location.replace(s),r}}},Re=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 c?(o&&i&&B(o).catch((()=>null)),t(m(r,{beforeRequest:G}))):t(r)}),(n=>i=>{var{autoRefresh:r}=i,s=e(i,["autoRefresh"]);if(!r||b())return n(s);const{clearAllTimers:a,setTimer:l}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let d,u;c&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&d&&new Date>d&&(x("Expiration time passed, refreshing session"),p.refresh(E()||u))}));const p=n(m(s,{afterRequest:async(e,n)=>{const{sessionJwt:o,refreshJwt:i,sessionExpiration:r,nextRefreshSeconds:s}=await y(n);if(401===(null==n?void 0:n.status))x("Received 401, canceling all timers"),a();else if(o||r){if(d=((e,n)=>{if(n)return new Date(1e3*n);x("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),!d)return void x("Could not extract expiration time from session token");u=i;const e=D(d,s);if(a(),e<=2e4)return void x("Session is too close to expiration, not setting refresh timer");const n=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});x(`Setting refresh timer for ${n}. (${e}ms)`),l((()=>{c&&"hidden"===document.visibilityState?x("Skipping refresh due to timer - document is hidden"):(x("Refreshing session due to timer"),p.refresh(E()||i))}),e)}}}));return o(p,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return x("Clearing all timers"),a(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.43.1"},t.baseHeaders)}))),(e=>t=>{const n=ce(),i=ce(),r=ce(),s=ce(),a=e(m(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))i.pub(null),r.pub(null),n.pub(null),s.pub(null);else{const e=await(async e=>{const t=await y(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:l}=await y(t);o&&i.pub(o),l&&s.pub(l),(a||o)&&n.pub(a||42)}}})),l=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(l,{onSessionTokenChange:i.sub,onUserChange:r.sub,onClaimsChange:s.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(t=>n=>{const{enableFlowNonce:o=!0,nonceStoragePrefix:i=W}=n,r=e(n,["enableFlowNonce","nonceStoragePrefix"]);if(!o)return t(r);((e=W)=>{try{if(!k)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:c&&(null===(n=window.localStorage)||void 0===n?void 0:n.length))&&void 0!==o?o:0);i++){const t=_(i);if(t&&t.startsWith(e)){const e=I(t);if(e)try{JSON.parse(e).expiry<Date.now()&&O(t)}catch(e){O(t)}}}}catch(e){console.error("Error cleaning up expired nonces:",e)}var t,n,o})(i);return t(m(r,{afterRequest:async(e,t)=>{if(e.path!==Z&&e.path!==z)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(X);let o=await t.clone().json().then((e=>(null==e?void 0:e.executionId)||null)).catch((()=>null));return o||(o=te(e)),{nonce:n,executionId:ee(o)}}catch(e){return{nonce:null,executionId:null}}})(e,t);if(n&&o){((e,t,n,o=W)=>{try{const i=Q(e,o),r=n?172800:10800,s={value:t,expiry:Date.now()+1e3*r,isStart:n};S(i,JSON.stringify(s))}catch(e){console.error("Error setting flow nonce:",e)}})(o,n,e.path===Z,i)}},beforeRequest:e=>{if(e.path===z){const t=te(e);if(t){const n=((e,t=W)=>{try{const n=Q(e,t),o=I(n);if(!o)return null;const i=JSON.parse(o);return i.expiry<Date.now()?(Y(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[X]=n)}}return e}}))}),(t=>n=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:r=!1}=n,s=e(n,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(t(s),{getLastUserLoginId:re,getLastUserDisplayName:se});const a=t(m(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=h((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?(ie(r),(e=>{S(oe,e)})(s)):(null==i?void 0:i.loginId)&&ie(i.loginId)}}));let l=o(a,["flow.start"],ae);return l=o(l,["logout","logoutAll"],le(r)),Object.assign(l,{getLastUserLoginId:re,getLastUserDisplayName:se})}),(t=>n=>{var{persistTokens:r,sessionTokenViaCookie:s,refreshTokenViaCookie:a,storagePrefix:l}=n,d=e(n,["persistTokens","sessionTokenViaCookie","refreshTokenViaCookie","storagePrefix"]);if(!r||!c)return t(d);let u;const p=t(m(d,{beforeRequest:P(l,a),afterRequest:async(e,t)=>{const n=/^\/v\d+\/mgmt\//.test(e.path);if(401===(null==t?void 0:t.status))n||N(l,s,a,u);else{const e=((e={},t=!1,n="",o=!1)=>{var r,s,a,l;const{sessionJwt:c,refreshJwt:d,trustedDeviceJwt:u}=e;let p;if(d)if(o){O(`${n}${U}`);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,l=A(o),c=Object.assign(Object.assign({},e),{cookieSameSite:t,cookieSecure:i,cookieDomain:a});R(l,d,c);const u=T(a);p=Object.assign(Object.assign({},p),{refresh:{path:c.cookiePath,domain:u?a:void 0}})}else{const e=A(o);i.remove(e),S(`${n}${U}`,d)}if(c)if(t){const n=t.sameSite||"Strict",o=null===(a=t.secure)||void 0===a||a,i=null!==(l=t.domain)&&void 0!==l?l:e.cookieDomain,r=$(t),s=Object.assign(Object.assign({},e),{cookieSameSite:n,cookieSecure:o,cookieDomain:i});R(r,c,s);const d=T(i);p=Object.assign(Object.assign({},p),{session:{path:s.cookiePath,domain:d?i:void 0}})}else S(`${n}${j}`,c);return e.idToken&&S(`${n}${C}`,e.idToken),u&&S(`${n}DTD`,u),p})(await y(t),s,l,a);e&&(u=e)}}})),g=o(p,["logout","logoutAll","oidc.logout"],de(l,s,a,(()=>u)));return Object.assign(g,{getRefreshToken:()=>E(l,a),getSessionToken:()=>J(l,s),getIdToken:()=>L(l)})}))((e=>{const t=n(e),o=Ce(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async(n,i)=>{var r;if(b())return x(`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=J(),a=E();let l="";if(e.getExternalToken)try{l=await(null===(r=e.getExternalToken)||void 0===r?void 0:r.call(e))}catch(e){x("Error getting external token while refreshing",e)}return t.refresh(n,{dcs:s?"t":"f",dcr:a?"t":"f"},l,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:_e(t),webauthn:be(t),fedcm:(i=t,r=e.projectId,{onetap:{requestExchangeCode(e){Ie(i,e)},requestAuthentication(e){Ie(i,e)}},async oneTap(e,t,n,o,r){await Oe(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+ke.config),clientId:r}]}},o=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return i.refresh(o.token)},isSupported:()=>c&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=i.httpClient.buildUrl(r+ke.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{U as REFRESH_TOKEN_KEY,j as SESSION_TOKEN_KEY,H as clearFingerprintData,Re as createSdk,Re as default,B as ensureFingerprintIds,xe 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 l="3.2.0",c="undefined"!=typeof window,d=Math.pow(2,31)-1,u=`https://descopecdn.com/npm/oidc-client-ts@${l}/dist/browser/oidc-client-ts.min.js`,p=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${l}/dist/browser/oidc-client-ts.min.js`;const g=["/v1/auth/refresh","/v1/auth/try-refresh","/v1/auth/me","/v1/auth/me/tenants","/v1/auth/me/history"];let f;const v=e=>{try{return t(e).exp}catch(e){return null}},w=e=>{const{refresh_expire_in:t,refresh_token:n}=e;return t?Math.floor(Date.now()/1e3)+t:v(n)},h=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||h(t),cookieExpiration:t.cookieExpiration||w(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=()=>c&&!!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 g.includes(n)},I=void 0!==f||c&&void 0!==window.localStorage,O=(e,t)=>{var n,o;return null===(o=null===(n=f||c&&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=f||c&&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=f||c&&window.localStorage)||void 0===t?void 0:t.removeItem)||void 0===n?void 0:n.call(t,e)},D=e=>{var t,n,o,i,r;return null!==(r=null!==(n=null===(t=null==f?void 0:f.key)||void 0===t?void 0:t.call(f,e))&&void 0!==n?n:c&&(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},T=(...e)=>{console.debug(...e)},j=(...e)=>{console.warn(...e)},C=(e,t)=>{let n;var o;return t>0?(n=1e3*t,T(`Using provided nextRefreshSeconds: ${t}s`)):n=((o=e)?o.getTime()-(new Date).getTime():0)-2e4,n>d&&(T(`Timeout is too large (${n}ms), setting it to ${d}ms`),n=d),n},U="DS",R="DSR",E="DSI";function $(e,t,n){if(t){const{cookieDomain:o,cookiePath:r,cookieSameSite:s,cookieExpiration:a,cookieSecure:l}=n,c=new Date(1e3*a),d=A(o);i.set(e,t,{path:r,domain:d?o:void 0,expires:c,sameSite:s,secure:l})}}function A(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)||U,N=e=>(null==e?void 0:e.cookieName)||R;function P(e="",t){return i.get(N(t))||_(`${e}${R}`)||""}function L(e="",t){return i.get(J(t))||_(`${e}${U}`)||""}function K(e=""){return _(`${e}${E}`)||""}function q(e="",t,n,o){x(`${e}${R}`),x(`${e}${U}`),x(`${e}${E}`);const r=J(t);i.remove(r,null==o?void 0:o.session);const s=N(n);i.remove(s,null==o?void 0:o.refresh)}const V=(e,t)=>n=>{const o=Object.assign(n,{token:n.token||P(e,t)}),i=function(e=""){return _(`${e}DTD`)||""}(e);return i&&(o.headers=Object.assign(Object.assign({},o.headers||{}),{"x-descope-trusted-device-token":i})),o},F=c&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",M="vsid",H="vrid",B="fp",G=(e=!1)=>{const t=_(B);if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},W=async(e,t=F)=>{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 i=new URL(t);i.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const l=i.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",c=r({apiKey:e,endpoint:[o.toString(),s],scriptUrlPattern:[l,a]}),d=await c,{requestId:u}=await d.get({linkedId:n}),p=((e,t)=>({[M]:e,[H]:t}))(n,u);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};O(B,JSON.stringify(t))})(p)}catch(e){console.warn("Could not load fingerprint",e)}},X=()=>{x(B)},Z=e=>{const t=G(!0);return t&&e.body&&(e.body.fpData=t),e},z="descopeFlowNonce",Q="X-Descope-Flow-Nonce",Y="/v1/flow/start",ee="/v1/flow/next",te=(e,t=z)=>`${t}${e}`,ne=(e,t=z)=>{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),le=()=>_(re),ce=()=>_(se),de=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=le(),r=ce();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 ge=(e,t,n,o)=>i=>async(...r)=>{const s=await i(...r);return q(e,t,n,null==o?void 0:o()),s};async function fe(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 we(e,t){const n=me(e);n.signal=t.signal,n.mediation="conditional";return ye(await navigator.credentials.get(n))}async function he(e=!1){var t,n;if(!c)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,Ie=(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 fe(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 fe(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 fe(i.data.options);return await e.webauthn.update.finish(i.data.transactionId,r)},helpers:{create:fe,get:ve,isSupported:he,conditional:we}}),(...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"},_e=()=>{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 De(e,t)}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}async function De(e,t){var n,o;const i=await async function(e,t="google",n,o,i){const r=_e(),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 l=a.data.clientId;return new Promise((e=>{var a,c;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===(c=null==n?void 0:n.use_fedcm_for_prompt)||void 0===c||c,client_id:l,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 Te=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await he(),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 je=()=>window.location.search.includes("code")&&window.location.search.includes("state");let Ce;const Ue=(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",(()=>{Ue(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 Ue([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,l,c;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,l=`${a}_user`,c="openid"}else(null==n?void 0:n.applicationId)?(s=e.httpClient.buildUrl(t),s=`${s}/${n.applicationId}`,a=t,l=`${a}_user`,c="openid email roles descope.custom_claims offline_access"):(s=e.httpClient.buildUrl(t),a=t,l=`${a}_user`,c="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)||c,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:l}},Ee=(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)))),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(je())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 l=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(l)))),l},logout:async(e,t=!1)=>{const{client:n,stateUserKey:i}=await o();e||(e={}),e.id_token_hint=e.id_token_hint||K(),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}}},$e=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var n;return n=t.customStorage,f=n,e(t)}),(t=>n=>{var{fpKey:o,fpLoad:i}=n,r=e(n,["fpKey","fpLoad"]);return c?(o&&i&&W(o).catch((()=>null)),t(y(r,{beforeRequest:Z}))):t(r)}),(n=>i=>{var{autoRefresh:r}=i,s=e(i,["autoRefresh"]);if(!r||k())return n(s);const{clearAllTimers:a,setTimer:l}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let d,u;c&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&d&&new Date>d&&(T("Expiration time passed, refreshing session"),p.refresh(P()||u))}));const p=n(y(s,{afterRequest:async(e,n)=>{const{sessionJwt:o,refreshJwt:i,sessionExpiration:r,nextRefreshSeconds:s}=await b(n);if(S(e,n))T("Session invalidated, canceling all timers"),a();else if(o||r){if(d=((e,n)=>{if(n)return new Date(1e3*n);T("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),!d)return void T("Could not extract expiration time from session token");u=i;const e=C(d,s);if(a(),e<=2e4)return void T("Session is too close to expiration, not setting refresh timer");const n=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});T(`Setting refresh timer for ${n}. (${e}ms)`),l((()=>{c&&"hidden"===document.visibilityState?T("Skipping refresh due to timer - document is hidden"):(T("Refreshing session due to timer"),p.refresh(P()||i))}),e)}}}));return o(p,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const n=await e(...t);return T("Clearing all timers"),a(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.45.0"},t.baseHeaders)}))),(e=>t=>{const n=pe(),i=pe(),r=pe(),s=pe(),a=e(y(t,{afterRequest:async(e,t)=>{if(S(e,t))T("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:l}=await b(t);o&&i.pub(o),l&&s.pub(l),(a||o)&&n.pub(a||42)}}})),l=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(l,{onSessionTokenChange:i.sub,onUserChange:r.sub,onClaimsChange:s.sub,onIsAuthenticatedChange:e=>n.sub((t=>{e(!!t)}))})}),(t=>n=>{const{enableFlowNonce:o=!0,nonceStoragePrefix:i=z}=n,r=e(n,["enableFlowNonce","nonceStoragePrefix"]);if(!o)return t(r);((e=z)=>{try{if(!I)return;for(let i=0;i<(t=void 0,n=void 0,o=void 0,null!==(o=null!==(t=null==f?void 0:f.length)&&void 0!==t?t:c&&(null===(n=window.localStorage)||void 0===n?void 0:n.length))&&void 0!==o?o:0);i++){const t=D(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!==Y&&e.path!==ee)return;const{nonce:n,executionId:o}=await(async(e,t)=>{try{const n=t.headers.get(Q);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=z)=>{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===Y,i)}},beforeRequest:e=>{if(e.path===ee){const t=ie(e);if(t){const n=((e,t=z)=>{try{const n=te(e,t),o=_(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[Q]=n)}}return e}}))}),(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:ce});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 l=o(a,["flow.start"],de);return l=o(l,["logout","logoutAll"],ue(r)),Object.assign(l,{getLastUserLoginId:le,getLastUserDisplayName:ce})}),(t=>n=>{var{persistTokens:r,sessionTokenViaCookie:s,refreshTokenViaCookie:a,storagePrefix:l}=n,d=e(n,["persistTokens","sessionTokenViaCookie","refreshTokenViaCookie","storagePrefix"]);if(!r||!c)return t(d);let u;const p=t(y(d,{beforeRequest:V(l,a),afterRequest:async(e,t)=>{if(S(e,t))T("Session invalidated, clearing persisted tokens"),q(l,s,a,u);else{const e=((e={},t=!1,n="",o=!1)=>{var r,s,a,l;const{sessionJwt:c,refreshJwt:d,trustedDeviceJwt:u}=e;let p;if(d)if(o){x(`${n}${R}`);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,l=N(o);i&&"https:"!==window.location.protocol&&j("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 c=Object.assign(Object.assign({},e),{cookieSameSite:t,cookieSecure:i,cookieDomain:a});$(l,d,c);const u=A(a);p=Object.assign(Object.assign({},p),{refresh:{path:c.cookiePath,domain:u?a:void 0}})}else{const e=N(o);i.remove(e),O(`${n}${R}`,d)}if(c)if(t){const n=t.sameSite||"Strict",o=null===(a=t.secure)||void 0===a||a,i=null!==(l=t.domain)&&void 0!==l?l:e.cookieDomain,r=J(t);o&&"https:"!==window.location.protocol&&j("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});$(r,c,s);const d=A(i);p=Object.assign(Object.assign({},p),{session:{path:s.cookiePath,domain:d?i:void 0}})}else O(`${n}${U}`,c);return e.idToken&&O(`${n}${E}`,e.idToken),u&&O(`${n}DTD`,u),p})(await b(t),s,l,a);e&&(u=e)}}})),g=o(p,["logout","logoutAll","oidc.logout"],ge(l,s,a,(()=>u)));return Object.assign(g,{getRefreshToken:()=>P(l,a),getSessionToken:()=>L(l,s),getIdToken:()=>K(l)})}))((e=>{const t=n(e),o=Ee(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async(n,i)=>{var r;if(k())return T(`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=L(),a=P();let l="";if(e.getExternalToken)try{l=await(null===(r=e.getExternalToken)||void 0===r?void 0:r.call(e))}catch(e){T("Error getting external token while refreshing",e)}return t.refresh(n,{dcs:s?"t":"f",dcr:a?"t":"f"},l,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:Te(t),webauthn:Ie(t),fedcm:(i=t,r=e.projectId,{onetap:{requestExchangeCode(e){xe(i,e)},requestAuthentication(e){xe(i,e)}},async oneTap(e,t,n,o,r){await De(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+Oe.config),clientId:r}]}},o=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(n));return i.refresh(o.token)},isSupported:()=>c&&"IdentityCredential"in window,async isLoggedIn(e){var t;const n=i.httpClient.buildUrl(r+Oe.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{R as REFRESH_TOKEN_KEY,U as SESSION_TOKEN_KEY,X as clearFingerprintData,$e as createSdk,$e as default,W as ensureFingerprintIds,L as getSessionToken,je as hasOidcParamsInUrl};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|