@descope/web-js-sdk 1.34.2 → 1.35.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 +18 -6
- 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
|
@@ -135,7 +135,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
135
135
|
oidcConfig?: OidcConfig;
|
|
136
136
|
getExternalToken?: () => Promise<string>;
|
|
137
137
|
} & FingerprintOptions & AutoRefreshOptions & FlowNonceOptions & LastLoggedInUserOptions & PersistTokensOptions<A>) => A extends false ? (({
|
|
138
|
-
refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
138
|
+
refresh: (token?: string, tryRefresh?: boolean) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
139
139
|
logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
140
140
|
flow: {
|
|
141
141
|
start: (flowId: string, options?: Pick<{
|
|
@@ -653,6 +653,8 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
653
653
|
connect: (appId: string, options?: {
|
|
654
654
|
redirectUrl?: string;
|
|
655
655
|
scopes?: string[];
|
|
656
|
+
tenantId?: string;
|
|
657
|
+
tenantLevel?: boolean;
|
|
656
658
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
657
659
|
};
|
|
658
660
|
saml: {
|
|
@@ -763,7 +765,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
763
765
|
getCurrentTenant: (token: string) => string;
|
|
764
766
|
httpClient: _descope_core_js_sdk.HttpClient;
|
|
765
767
|
} | {
|
|
766
|
-
refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
768
|
+
refresh: (token?: string, tryRefresh?: boolean) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
767
769
|
logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
768
770
|
flow: {
|
|
769
771
|
start: (flowId: string, options?: Pick<{
|
|
@@ -1281,6 +1283,8 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
1281
1283
|
connect: (appId: string, options?: {
|
|
1282
1284
|
redirectUrl?: string;
|
|
1283
1285
|
scopes?: string[];
|
|
1286
|
+
tenantId?: string;
|
|
1287
|
+
tenantLevel?: boolean;
|
|
1284
1288
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
1285
1289
|
};
|
|
1286
1290
|
saml: {
|
|
@@ -1391,7 +1395,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
1391
1395
|
getCurrentTenant: (token: string) => string;
|
|
1392
1396
|
httpClient: _descope_core_js_sdk.HttpClient;
|
|
1393
1397
|
} | {
|
|
1394
|
-
refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
1398
|
+
refresh: (token?: string, tryRefresh?: boolean) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
1395
1399
|
logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
1396
1400
|
flow: {
|
|
1397
1401
|
start: (flowId: string, options?: Pick<{
|
|
@@ -1909,6 +1913,8 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
1909
1913
|
connect: (appId: string, options?: {
|
|
1910
1914
|
redirectUrl?: string;
|
|
1911
1915
|
scopes?: string[];
|
|
1916
|
+
tenantId?: string;
|
|
1917
|
+
tenantLevel?: boolean;
|
|
1912
1918
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
1913
1919
|
};
|
|
1914
1920
|
saml: {
|
|
@@ -2026,7 +2032,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
2026
2032
|
getLastUserLoginId: () => string;
|
|
2027
2033
|
getLastUserDisplayName: () => string;
|
|
2028
2034
|
} : ((({
|
|
2029
|
-
refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
2035
|
+
refresh: (token?: string, tryRefresh?: boolean) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
2030
2036
|
logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
2031
2037
|
flow: {
|
|
2032
2038
|
start: (flowId: string, options?: Pick<{
|
|
@@ -2544,6 +2550,8 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
2544
2550
|
connect: (appId: string, options?: {
|
|
2545
2551
|
redirectUrl?: string;
|
|
2546
2552
|
scopes?: string[];
|
|
2553
|
+
tenantId?: string;
|
|
2554
|
+
tenantLevel?: boolean;
|
|
2547
2555
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
2548
2556
|
};
|
|
2549
2557
|
saml: {
|
|
@@ -2654,7 +2662,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
2654
2662
|
getCurrentTenant: (token: string) => string;
|
|
2655
2663
|
httpClient: _descope_core_js_sdk.HttpClient;
|
|
2656
2664
|
} | {
|
|
2657
|
-
refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
2665
|
+
refresh: (token?: string, tryRefresh?: boolean) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
2658
2666
|
logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
2659
2667
|
flow: {
|
|
2660
2668
|
start: (flowId: string, options?: Pick<{
|
|
@@ -3172,6 +3180,8 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
3172
3180
|
connect: (appId: string, options?: {
|
|
3173
3181
|
redirectUrl?: string;
|
|
3174
3182
|
scopes?: string[];
|
|
3183
|
+
tenantId?: string;
|
|
3184
|
+
tenantLevel?: boolean;
|
|
3175
3185
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
3176
3186
|
};
|
|
3177
3187
|
saml: {
|
|
@@ -3282,7 +3292,7 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
3282
3292
|
getCurrentTenant: (token: string) => string;
|
|
3283
3293
|
httpClient: _descope_core_js_sdk.HttpClient;
|
|
3284
3294
|
} | {
|
|
3285
|
-
refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
3295
|
+
refresh: (token?: string, tryRefresh?: boolean) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
3286
3296
|
logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
3287
3297
|
flow: {
|
|
3288
3298
|
start: (flowId: string, options?: Pick<{
|
|
@@ -3800,6 +3810,8 @@ declare const decoratedCreateSdk: <A extends CookieConfig>({ persistTokens: isPe
|
|
|
3800
3810
|
connect: (appId: string, options?: {
|
|
3801
3811
|
redirectUrl?: string;
|
|
3802
3812
|
scopes?: string[];
|
|
3813
|
+
tenantId?: string;
|
|
3814
|
+
tenantLevel?: boolean;
|
|
3803
3815
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
|
|
3804
3816
|
};
|
|
3805
3817
|
saml: {
|
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.34.2"},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.35.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,i)=>{var r;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 a=D(),s=C();let c="";if(e.getExternalToken)try{c=await(null===(r=e.getExternalToken)||void 0===r?void 0:r.call(e))}catch(e){y("Error getting external token while refreshing",e)}return t.refresh(n,{dcs:a?"t":"f",dcr:s?"t":"f"},c,i)},logout:async n=>{if(e.oidcConfig)try{return await o.logout({id_token_hint:n}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(n)},flow: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
|