@descope/web-js-sdk 0.1.0-alpha.11 → 0.1.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),n=require("@fingerprintjs/fingerprintjs-pro"),s=require("js-cookie");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=a(t),r=a(s);const o="undefined"!=typeof window,l=o&&localStorage.getItem("fingerprint.public.key")||"A9aCLRHzKCv3uL69oqDr",c=o&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",u=e=>{const t=n.load({apiKey:e||l,endpoint:c});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",e);const n=await t,s=await n.get({linkedId:e});sessionStorage.setItem("vrid",s.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var d,g,p,f,h;const v=e=>Object.assign({},e);class w{constructor(t){d.add(this),g.set(this,void 0),p.set(this,{}),f.set(this,0),e.__classPrivateFieldSet(this,g,t,"f")}get current(){return v(e.__classPrivateFieldGet(this,g,"f"))}update(t){const n=t;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],s=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==s.length)return!1;for(let s=0;s<n.length;s+=1){const a=n[s];if(e[a]!==t[a])return!1}return!0})(e.__classPrivateFieldGet(this,g,"f"),n)){const t=e.__classPrivateFieldGet(this,g,"f");e.__classPrivateFieldSet(this,g,n,"f"),Object.freeze(e.__classPrivateFieldGet(this,g,"f")),setTimeout((()=>{Object.values(e.__classPrivateFieldGet(this,p,"f")).forEach((e=>e(v(n),t)))}),0)}}subscribe(t){e.__classPrivateFieldSet(this,f,e.__classPrivateFieldGet(this,f,"f")+1,"f"),e.__classPrivateFieldGet(this,p,"f")[e.__classPrivateFieldGet(this,f,"f")]=t;const n=e.__classPrivateFieldGet(this,f,"f");return()=>e.__classPrivateFieldGet(this,d,"m",h).call(this,n.toString())}unsubscribeAll(){e.__classPrivateFieldSet(this,p,{},"f")}}g=new WeakMap,p=new WeakMap,f=new WeakMap,d=new WeakSet,h=function(t){!!e.__classPrivateFieldGet(this,p,"f")[t]&&delete e.__classPrivateFieldGet(this,p,"f")[t]};let b=[];function S(e,t,n){const s=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(s){let t;for(;t=b.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),a);b.push(i)}}function _(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:s}){e&&r.default.set("DS",e,{path:t,domain:n,expires:s,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function y(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function m(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),n.publicKey.user.id=I(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.create(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:j(s.rawId),response:Object.assign(Object.assign({},s.response),{attestationObject:j(s.response.attestationObject),clientDataJSON:j(s.response.clientDataJSON)})}));var s}async function k(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.get(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:j(s.rawId),response:Object.assign(Object.assign({},s.response),{authenticatorData:j(s.response.authenticatorData),clientDataJSON:j(s.response.clientDataJSON),signature:j(s.response.signature),userHandle:s.response.userHandle?j(s.response.userHandle):void 0})}));var s}async function O(e=!1){if(!o)return Promise.resolve(!1);const t=!!(PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function I(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function j(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}module.exports=t=>{var{autoRefresh:n=!0,persistTokens:s=!0}=t,a=e.__rest(t,["autoRefresh","persistTokens"]);o?u(a.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const l=a;let c,d;const g=new w({sessionToken:""}),p=new w({});l.hooks={beforeRequest:e=>null==c?void 0:c(e),afterRequest:(e,t)=>null==d?void 0:d(e,t)};const f=i.default(l),h=(v=f,{async signUp(e,t){const n=await v.webauthn.signUp.start(e,window.location.origin,t),s=await m(n.data.options);return await v.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await v.webauthn.signIn.start(e,window.location.origin),n=await k(t.data.options);return await v.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await v.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await m(n.data.options);return await v.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await k(n.data.options);return await v.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await v.webauthn.update.start(e,window.location.origin,t),s=await m(n.data.options);return await v.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:m,get:k,isSupported:O}});var v;const b=Object.assign(Object.assign({},f),{flow:Object.assign(Object.assign({},f.flow),{start:async(e,t)=>{const n=await h.helpers.isSupported(),s=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("dls_last_user_external_id"),a={tenant:null==t?void 0:t.tenant,redirectUrl:window.location.href,deviceInfo:{webAuthnSupport:n}};return s&&(a.lastUser={externalId:s}),f.flow.start(e,a)}}),webauthn:h,onSessionTokenChange:e=>{var t;const n=null===(t=g.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),g.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=p.current;return t&&Object.entries(t).length>0&&e(t),p.subscribe((t=>{e(t)}))},getRefreshToken:y});return o?(n&&["logout","logoutAll"].forEach((e=>{const t=f[e];b[e]=(...e)=>{const n=y(),s=[(null==e?void 0:e.shift())||n,...e],a=t(...s);return localStorage&&localStorage.removeItem("DSR"),r.default.remove("DS"),o&&(null===localStorage||void 0===localStorage||localStorage.removeItem("dls_last_user_external_id")),g.update({sessionToken:""}),a}})),c=e=>{if(e.body){const t={vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""};e.body.fpData=t}return!e.token&&s&&(e.token=y()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.11"}),e},b.me=async(...e)=>{var t;const n=await f.me(...e);if(n.ok){const e=await(null===(t=n.response)||void 0===t?void 0:t.clone().json());p.update(e)}return n},(n||s)&&(d=(t,a)=>{!async function(t,n,s,a){var i;try{if(401===n.status)return s.sessionToken.update({sessionToken:""}),void s.user.update({});const r=await(null==n?void 0:n.json());if(r){const n=function(e){return(null==e?void 0:e.authInfo)||e||{}}(r),{sessionJwt:l,refreshJwt:c,user:u}=n,d=e.__rest(n,["sessionJwt","refreshJwt","user"]);if(a.persistTokens&&_(l,c,d),l&&s.sessionToken.update({sessionToken:l}),u){const e=null===(i=null==u?void 0:u.externalIds)||void 0===i?void 0:i[0];o&&e&&(null===localStorage||void 0===localStorage||localStorage.setItem("dls_last_user_external_id",e)),s.user.update(u)}l&&c&&a.autoRefresh&&S(t,l,c)}}catch(e){console.error("Could not set tokens from body",e)}}(b.refresh,a,{sessionToken:g,user:p},{autoRefresh:n,persistTokens:s})}),n&&y()&&b.refresh(),b):(console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),b)};
1
+ "use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),n=require("@fingerprintjs/fingerprintjs-pro"),s=require("js-cookie");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=a(t),r=a(s);const o="undefined"!=typeof window,l=o&&localStorage.getItem("fingerprint.public.key")||"A9aCLRHzKCv3uL69oqDr",c=o&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",u=e=>{const t=n.load({apiKey:e||l,endpoint:c});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",e);const n=await t,s=await n.get({linkedId:e});sessionStorage.setItem("vrid",s.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var d,g,p,f,h;const v=e=>Object.assign({},e);class w{constructor(t){d.add(this),g.set(this,void 0),p.set(this,{}),f.set(this,0),e.__classPrivateFieldSet(this,g,t,"f")}get current(){return v(e.__classPrivateFieldGet(this,g,"f"))}update(t){const n=t;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],s=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==s.length)return!1;for(let s=0;s<n.length;s+=1){const a=n[s];if(e[a]!==t[a])return!1}return!0})(e.__classPrivateFieldGet(this,g,"f"),n)){const t=e.__classPrivateFieldGet(this,g,"f");e.__classPrivateFieldSet(this,g,n,"f"),Object.freeze(e.__classPrivateFieldGet(this,g,"f")),setTimeout((()=>{Object.values(e.__classPrivateFieldGet(this,p,"f")).forEach((e=>e(v(n),t)))}),0)}}subscribe(t){e.__classPrivateFieldSet(this,f,e.__classPrivateFieldGet(this,f,"f")+1,"f"),e.__classPrivateFieldGet(this,p,"f")[e.__classPrivateFieldGet(this,f,"f")]=t;const n=e.__classPrivateFieldGet(this,f,"f");return()=>e.__classPrivateFieldGet(this,d,"m",h).call(this,n.toString())}unsubscribeAll(){e.__classPrivateFieldSet(this,p,{},"f")}}g=new WeakMap,p=new WeakMap,f=new WeakMap,d=new WeakSet,h=function(t){!!e.__classPrivateFieldGet(this,p,"f")[t]&&delete e.__classPrivateFieldGet(this,p,"f")[t]};let b=[];function S(e,t,n){const s=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(s){let t;for(;t=b.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),a);b.push(i)}}function _(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:s}){e&&r.default.set("DS",e,{path:t,domain:n,expires:s,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function y(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function m(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),n.publicKey.user.id=I(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.create(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:j(s.rawId),response:Object.assign(Object.assign({},s.response),{attestationObject:j(s.response.attestationObject),clientDataJSON:j(s.response.clientDataJSON)})}));var s}async function k(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.get(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:j(s.rawId),response:Object.assign(Object.assign({},s.response),{authenticatorData:j(s.response.authenticatorData),clientDataJSON:j(s.response.clientDataJSON),signature:j(s.response.signature),userHandle:s.response.userHandle?j(s.response.userHandle):void 0})}));var s}async function O(e=!1){if(!o)return Promise.resolve(!1);const t=!!(PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function I(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function j(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}module.exports=t=>{var{autoRefresh:n=!0,persistTokens:s=!0}=t,a=e.__rest(t,["autoRefresh","persistTokens"]);o?u(a.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const l=a;let c,d;const g=new w({sessionToken:""}),p=new w({});l.hooks={beforeRequest:e=>null==c?void 0:c(e),afterRequest:(e,t)=>null==d?void 0:d(e,t)};const f=i.default(l),h=(v=f,{async signUp(e,t){const n=await v.webauthn.signUp.start(e,window.location.origin,t),s=await m(n.data.options);return await v.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await v.webauthn.signIn.start(e,window.location.origin),n=await k(t.data.options);return await v.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await v.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await m(n.data.options);return await v.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await k(n.data.options);return await v.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await v.webauthn.update.start(e,window.location.origin,t),s=await m(n.data.options);return await v.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:m,get:k,isSupported:O}});var v;const b=Object.assign(Object.assign({},f),{flow:Object.assign(Object.assign({},f.flow),{start:async(e,t,n,s)=>{const a=await h.helpers.isSupported(),i=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("dls_last_user_external_id"),r={tenant:null==s?void 0:s.tenant,redirectUrl:window.location.href,deviceInfo:{webAuthnSupport:a}};return i&&(r.lastUser={externalId:i}),f.flow.start(e,t,n,r)}}),webauthn:h,onSessionTokenChange:e=>{var t;const n=null===(t=g.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),g.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=p.current;return t&&Object.entries(t).length>0&&e(t),p.subscribe((t=>{e(t)}))},getRefreshToken:y});return o?(n&&["logout","logoutAll"].forEach((e=>{const t=f[e];b[e]=(...e)=>{const n=y(),s=[(null==e?void 0:e.shift())||n,...e],a=t(...s);return localStorage&&localStorage.removeItem("DSR"),r.default.remove("DS"),o&&(null===localStorage||void 0===localStorage||localStorage.removeItem("dls_last_user_external_id")),g.update({sessionToken:""}),a}})),c=e=>{if(e.body){const t={vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""};e.body.fpData=t}return!e.token&&s&&(e.token=y()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.12"}),e},b.me=async(...e)=>{var t;const n=await f.me(...e);if(n.ok){const e=await(null===(t=n.response)||void 0===t?void 0:t.clone().json());p.update(e)}return n},(n||s)&&(d=(t,a)=>{!async function(t,n,s,a){var i;try{if(401===n.status)return s.sessionToken.update({sessionToken:""}),void s.user.update({});const r=await(null==n?void 0:n.json());if(r){const n=function(e){return(null==e?void 0:e.authInfo)||e||{}}(r),{sessionJwt:l,refreshJwt:c,user:u}=n,d=e.__rest(n,["sessionJwt","refreshJwt","user"]);if(a.persistTokens&&_(l,c,d),l&&s.sessionToken.update({sessionToken:l}),u){const e=null===(i=null==u?void 0:u.externalIds)||void 0===i?void 0:i[0];o&&e&&(null===localStorage||void 0===localStorage||localStorage.setItem("dls_last_user_external_id",e)),s.user.update(u)}l&&c&&a.autoRefresh&&S(t,l,c)}}catch(e){console.error("Could not set tokens from body",e)}}(b.refresh,a,{sessionToken:g,user:p},{autoRefresh:n,persistTokens:s})}),n&&y()&&b.refresh(),b):(console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),b)};
2
2
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../../src/constants.ts","../../src/fp.ts","../../src/helpers.ts","../../src/state.ts","../../src/tokens.ts","../../src/webauthn.ts","../../src/index.ts"],"sourcesContent":["const FINGERPRINT_PUBLIC_KEY = 'fingerprint.public.key';\nconst FINGERPRINT_ENDPOINT_URL = 'fingerprint.endpoint.url';\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n/** Fingerprint.js identity key */\nexport const FP_KEY =\n\t(IS_BROWSER && localStorage.getItem(FINGERPRINT_PUBLIC_KEY)) || 'A9aCLRHzKCv3uL69oqDr';\n/** Fingerprint.js custom API endpoint */\nexport const FP_EP_URL =\n\t(IS_BROWSER && localStorage?.getItem(FINGERPRINT_ENDPOINT_URL)) || 'https://fp.descope.com';\n/** Fingerprint visitor data */\nexport const FP_BODY_DATA = 'fpData';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n/** External Id of the last user logged in */\nexport const LOCAL_STORAGE_LAST_USER_EXTERNAL_ID = 'dls_last_user_external_id';\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, FP_EP_URL, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY, endpoint: FP_EP_URL });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n\t\t\t\t// istanbul ignore next\n\t\t\t\tif (global.FB_DEBUG) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error(ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n\nexport default fp;\n","/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","// supported state types are string and object\ntype StateObject = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\nimport { IS_BROWSER, LOCAL_STORAGE_LAST_USER_EXTERNAL_ID } from './constants';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tconst externalId = user?.externalIds?.[0];\n\t\t\t\tif (IS_BROWSER && externalId) {\n\t\t\t\t\tlocalStorage?.setItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID, externalId);\n\t\t\t\t}\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { IS_BROWSER } from './constants';\nimport { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget,\n\t\t/** Checks if the browser supports WebAuthn,\n\t\t * and can optionally require in addition that The browser supports WebAuthn with built-in biometrics */\n\t\tisSupported\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\nasync function isSupported(requirePlatformAuthenticator: boolean = false): Promise<boolean> {\n\tif (!IS_BROWSER) {\n\t\treturn Promise.resolve(false);\n\t}\n\tconst supported = !!(\n\t\tPublicKeyCredential &&\n\t\tnavigator.credentials &&\n\t\tnavigator.credentials.create &&\n\t\tnavigator.credentials.get\n\t);\n\tif (\n\t\tsupported &&\n\t\trequirePlatformAuthenticator &&\n\t\tPublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n\t) {\n\t\treturn PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n\t}\n\treturn supported;\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport {\n\tFP_BODY_DATA,\n\tIS_BROWSER,\n\tLOCAL_STORAGE_LAST_USER_EXTERNAL_ID,\n\tVISITOR_REQUEST_ID_PARAM,\n\tVISITOR_SESSION_ID_PARAM\n} from './constants';\nimport fp from './fp';\nimport State from './state';\nimport { clearTokens, getRefreshToken, handleDescopeTokens } from './tokens';\nimport { CoreSdk, TokensOptions } from './types';\nimport createWebAuthn from './webauthn';\n\ndeclare const BUILD_VERSION: string;\n\n/** Configuration arguments which include the Descope core SDK args and fingerprint configuration.\n * Also specifies token options - if we should persist tokens from responses automatically and auto-refresh.\n */\nexport type WebJSSDKArgs = Parameters<typeof createSdk>[0] &\n\tTokensOptions & {\n\t\t// FingerprintJS API key\n\t\tfpKey?: string;\n\t};\n\n/**\n * Wrapper around DescopeSDK to handle fingerprint.js and storage of JWT tokens in cookies and localStorage,\n * It also sets a timer to refresh session JWT automatically.\n */\nexport default ({ autoRefresh = true, persistTokens = true, ...args }: WebJSSDKArgs) => {\n\t// istanbul ignore next\n\tif (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\tconst webauthnSdk = createWebAuthn(coreSdk);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\tflow: {\n\t\t\t...coreSdk.flow,\n\t\t\tstart: async (flowId: string, options?: { tenant?: string }) => {\n\t\t\t\tconst webAuthnSupport = await webauthnSdk.helpers.isSupported();\n\t\t\t\tconst lastUserExternalId = localStorage?.getItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID);\n\t\t\t\tconst readyOptions: Parameters<typeof coreSdk.flow.start>[1] = {\n\t\t\t\t\ttenant: options?.tenant,\n\t\t\t\t\tredirectUrl: window.location.href,\n\t\t\t\t\tdeviceInfo: {\n\t\t\t\t\t\twebAuthnSupport\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tif (lastUserExternalId) {\n\t\t\t\t\treadyOptions.lastUser = {\n\t\t\t\t\t\texternalId: lastUserExternalId\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn coreSdk.flow.start(flowId, readyOptions);\n\t\t\t}\n\t\t},\n\t\twebauthn: webauthnSdk,\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t},\n\t\t// Returns refresh token. Use this function when:\n\t\t// 1. You need to pass refresh token to another party (For example, in SSR)\n\t\t// 2. Descope project's configuration is set to manage token response in BODY (in contrast to manage response in COOKIES)\n\t\t// NOTE: Refresh token is sensitive token. Prefer using this function only for testing, and to manage token response in COOKIES)\n\t\tgetRefreshToken\n\t};\n\n\tif (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server'\n\t\t);\n\t\treturn webSdk;\n\t}\n\n\tif (autoRefresh) {\n\t\t// Make it easier for Descoper to just call logout/logoutAll without parameters,\n\t\t// In case this is a dev env and refresh is stored in localStorage\n\t\t['logout', 'logoutAll'].forEach((fnName) => {\n\t\t\tconst originFn = coreSdk[fnName] as Function;\n\t\t\twebSdk[fnName] = (...args: any) => {\n\t\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t\tconst token = args?.shift();\n\t\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\t\tconst res = originFn(...logoutArgs);\n\t\t\t\tclearTokens();\n\t\t\t\tIS_BROWSER && localStorage?.removeItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID);\n\t\t\t\tsessionToken.update({ sessionToken: '' });\n\t\t\t\treturn res;\n\t\t\t};\n\t\t});\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tif (config.body) {\n\t\t\tconst fpData = {\n\t\t\t\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t\t\t\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n\t\t\t};\n\t\t\tconfig.body[FP_BODY_DATA] = fpData;\n\t\t}\n\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\tconfig.headers = {\n\t\t\t...config.headers,\n\t\t\t'x-descope-sdk-name': 'web-js',\n\t\t\t'x-descope-sdk-version': BUILD_VERSION\n\t\t};\n\t\treturn config;\n\t};\n\n\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\tif (getRefreshToken()) {\n\t\t\t// refresh on init is done after afterRequestHook is configured\n\t\t\twebSdk.refresh();\n\t\t}\n\t}\n\n\treturn webSdk;\n};\n"],"names":["IS_BROWSER","window","FP_KEY","localStorage","getItem","FP_EP_URL","fp","fpKey","agentP","load","apiKey","endpoint","get","async","sessionId","sessionStorage","Date","now","toString","Math","random","substring","setItem","agent","res","linkedId","requestId","ex","global","FB_DEBUG","console","error","clone","state","Object","assign","State","constructor","init","_State_state","set","this","_State_subscribers","_State_token","__classPrivateFieldSet","current","__classPrivateFieldGet","update","newState","nextState","a","b","aProperties","getOwnPropertyNames","bProperties","length","i","propName","compare","prevState","freeze","setTimeout","values","forEach","cb","subscribe","currentToken","_State_instances","_State_unsubscribe","call","unsubscribeAll","token","refreshTimeoutIds","setRefreshSessionTimeout","refreshFn","sessionJwt","refreshJWT","sessionExpiration","parts","split","claims","JSON","parse","atob","exp","getSessionExpiration","previousTimeout","pop","clearTimeout","refreshTimeout","getTime","timeoutId","push","setDescopeTokens","refreshJwt","cookieParams","cookiePath","cookieDomain","cookieExpiration","Cookies","path","domain","expires","sameSite","secure","setSessionToken","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","isSupported","requirePlatformAuthenticator","Promise","resolve","supported","PublicKeyCredential","isUserVerifyingPlatformAuthenticatorAvailable","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webauthnSdk","sdk","identifier","name","startResponse","webauthn","signUp","start","location","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","webSdk","flow","flowId","webAuthnSupport","lastUserExternalId","readyOptions","tenant","redirectUrl","href","deviceInfo","lastUser","externalId","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","fnName","originFn","refreshToken","logoutArgs","shift","removeItem","remove","body","fpData","vsid","vrid","headers","me","ok","json","_","status","_b","authInfo","extractJWTResponse","externalIds","handleDescopeTokens","refresh"],"mappings":"qOAAA,MAIaA,EAA+B,oBAAXC,OAEpBC,EACXF,GAAcG,aAAaC,QAPE,2BAOkC,uBAEpDC,EACXL,IAAc,OAAAG,uBAAAA,oBAAAA,aAAcC,QATG,8BASmC,yBCL9DE,EAAMC,IACX,MAAMC,EAASC,EAAIA,KAAC,CAAEC,OAAQH,GAASL,EAAQS,SAAUN,IAEzD,MAAO,CACNO,IAAKC,UACJ,IACC,IAAIC,EAAYC,eAAeX,QDGK,QCD/BU,IACJA,GCVHE,KAAKC,MAAMC,SAAS,IACpBC,KAAKC,SAASF,SAAS,IAAIG,UAAU,GACrCF,KAAKC,SAASF,SAAS,IAAIG,UAAU,IACpCA,UAAU,EAAG,KDUZN,eAAeO,QDHqB,OCGaR,GAEjD,MAAMS,QAAcf,EACdgB,QAAYD,EAAMX,IAAI,CAAEa,SAAUX,IACxCC,eAAeO,QDLqB,OCKaE,EAAIE,UAOrD,CANC,MAAOC,GAEJC,OAAOC,UAEVC,QAAQC,MAAMJ,EAEf,GAEF,gBEzBF,MAmBMK,EAASC,GACdC,OAAAC,OAAA,CAAA,EAAYF,GAGb,MAAMG,EAOLC,YAAYC,eANZC,EAAUC,IAAAC,UAAA,GAEVC,EAAAF,IAAAC,KAA+B,CAAA,GAE/BE,EAAAH,IAAAC,KAAS,GAGRG,EAAAA,uBAAAH,KAAIF,EAAUD,EAAI,IAClB,CAEGO,cACH,OAAOb,EAAMc,EAAAA,uBAAAL,KAAIF,EAAA,KACjB,CAEDQ,OAAOC,GACN,MAAMC,EAAeD,EACrB,IAxCc,EAAwBE,EAAMC,KAC7C,MAAMC,EAAeF,GAAKhB,OAAOmB,oBAAoBH,IAAO,GACtDI,EAAeH,GAAKjB,OAAOmB,oBAAoBF,IAAO,GAE5D,GAAIC,EAAYG,SAAWD,EAAYC,OACtC,OAAO,EAGR,IAAK,IAAIC,EAAI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AAeC,KAClBO,EAAmB,CAACyD,EAAGtM,MFvDlBX,eACN6D,EACAlD,EACAS,EACA4E,SAEA,IACC,GAAmB,MAAfrF,EAAIuM,OAIP,OAFA9L,EAAMqI,aAAavH,OAAO,CAAEuH,aAAc,UAC1CrI,EAAMkF,KAAKpE,OAAO,CAAA,GAGnB,MAAMuK,QAAa9L,aAAG,EAAHA,EAAKqM,QACxB,GAAIP,EAAM,CACT,MAAMU,EA3BT,SAA4BV,GAE3B,OAAOA,aAAA,EAAAA,EAAMW,WAAYX,GAAS,CAAA,CACnC,CAwB6DY,CAAmBZ,IAAvE3I,WAAEA,EAAUmB,WAAEA,EAAUqB,KAAEA,GAAkD6G,EAAzCjI,EAAnCiE,EAAAA,OAAAgE,EAAA,CAAA,aAAA,aAAA,SAUN,GARInH,EAAQiD,eACXjE,EAAiBlB,EAAYmB,EAAYC,GAItCpB,GACH1C,EAAMqI,aAAavH,OAAO,CAAEuH,aAAc3F,IAEvCwC,EAAM,CACT,MAAMsF,EAAiC,QAApBpF,EAAAF,aAAA,EAAAA,EAAMgH,mBAAc,IAAA9G,OAAA,EAAAA,EAAA,GACnCrH,GAAcyM,IACL,OAAZtM,mBAAY,IAAZA,cAAAA,aAAcmB,QJnIgC,4BImIamL,IAE5DxK,EAAMkF,KAAKpE,OAAOoE,EAClB,CAGGxC,GAAcmB,GAAce,EAAQgD,aACvCpF,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CEaGyM,CACCtC,EAAOuC,QACP7M,EACA,CAAE8I,eAAcnD,QAChB,CAAE0C,cAAaC,iBACf,GAICD,GACClD,KAEHmF,EAAOuC,UAIFvC,IAvENhK,QAAQoI,KACP,wIAEM4B,EAoEK"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../../src/constants.ts","../../src/fp.ts","../../src/helpers.ts","../../src/state.ts","../../src/tokens.ts","../../src/webauthn.ts","../../src/index.ts"],"sourcesContent":["const FINGERPRINT_PUBLIC_KEY = 'fingerprint.public.key';\nconst FINGERPRINT_ENDPOINT_URL = 'fingerprint.endpoint.url';\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n/** Fingerprint.js identity key */\nexport const FP_KEY =\n\t(IS_BROWSER && localStorage.getItem(FINGERPRINT_PUBLIC_KEY)) || 'A9aCLRHzKCv3uL69oqDr';\n/** Fingerprint.js custom API endpoint */\nexport const FP_EP_URL =\n\t(IS_BROWSER && localStorage?.getItem(FINGERPRINT_ENDPOINT_URL)) || 'https://fp.descope.com';\n/** Fingerprint visitor data */\nexport const FP_BODY_DATA = 'fpData';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n/** External Id of the last user logged in */\nexport const LOCAL_STORAGE_LAST_USER_EXTERNAL_ID = 'dls_last_user_external_id';\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, FP_EP_URL, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY, endpoint: FP_EP_URL });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n\t\t\t\t// istanbul ignore next\n\t\t\t\tif (global.FB_DEBUG) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error(ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n\nexport default fp;\n","/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","// supported state types are string and object\ntype StateObject = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\nimport { IS_BROWSER, LOCAL_STORAGE_LAST_USER_EXTERNAL_ID } from './constants';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tconst externalId = user?.externalIds?.[0];\n\t\t\t\tif (IS_BROWSER && externalId) {\n\t\t\t\t\tlocalStorage?.setItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID, externalId);\n\t\t\t\t}\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { IS_BROWSER } from './constants';\nimport { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget,\n\t\t/** Checks if the browser supports WebAuthn,\n\t\t * and can optionally require in addition that The browser supports WebAuthn with built-in biometrics */\n\t\tisSupported\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\nasync function isSupported(requirePlatformAuthenticator: boolean = false): Promise<boolean> {\n\tif (!IS_BROWSER) {\n\t\treturn Promise.resolve(false);\n\t}\n\tconst supported = !!(\n\t\tPublicKeyCredential &&\n\t\tnavigator.credentials &&\n\t\tnavigator.credentials.create &&\n\t\tnavigator.credentials.get\n\t);\n\tif (\n\t\tsupported &&\n\t\trequirePlatformAuthenticator &&\n\t\tPublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n\t) {\n\t\treturn PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n\t}\n\treturn supported;\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport {\n\tFP_BODY_DATA,\n\tIS_BROWSER,\n\tLOCAL_STORAGE_LAST_USER_EXTERNAL_ID,\n\tVISITOR_REQUEST_ID_PARAM,\n\tVISITOR_SESSION_ID_PARAM\n} from './constants';\nimport fp from './fp';\nimport State from './state';\nimport { clearTokens, getRefreshToken, handleDescopeTokens } from './tokens';\nimport { CoreSdk, TokensOptions } from './types';\nimport createWebAuthn from './webauthn';\n\ndeclare const BUILD_VERSION: string;\n\n/** Configuration arguments which include the Descope core SDK args and fingerprint configuration.\n * Also specifies token options - if we should persist tokens from responses automatically and auto-refresh.\n */\nexport type WebJSSDKArgs = Parameters<typeof createSdk>[0] &\n\tTokensOptions & {\n\t\t// FingerprintJS API key\n\t\tfpKey?: string;\n\t};\n\n/**\n * Wrapper around DescopeSDK to handle fingerprint.js and storage of JWT tokens in cookies and localStorage,\n * It also sets a timer to refresh session JWT automatically.\n */\nexport default ({ autoRefresh = true, persistTokens = true, ...args }: WebJSSDKArgs) => {\n\t// istanbul ignore next\n\tif (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\tconst webauthnSdk = createWebAuthn(coreSdk);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\tflow: {\n\t\t\t...coreSdk.flow,\n\t\t\tstart: async (\n\t\t\t\tflowId: string,\n\t\t\t\tinteractionId?: string,\n\t\t\t\tinput?: Record<string, FormDataEntryValue>,\n\t\t\t\toptions?: { tenant?: string }\n\t\t\t) => {\n\t\t\t\tconst webAuthnSupport = await webauthnSdk.helpers.isSupported();\n\t\t\t\tconst lastUserExternalId = localStorage?.getItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID);\n\t\t\t\tconst readyOptions: Parameters<typeof coreSdk.flow.start>[3] = {\n\t\t\t\t\ttenant: options?.tenant,\n\t\t\t\t\tredirectUrl: window.location.href,\n\t\t\t\t\tdeviceInfo: {\n\t\t\t\t\t\twebAuthnSupport\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tif (lastUserExternalId) {\n\t\t\t\t\treadyOptions.lastUser = {\n\t\t\t\t\t\texternalId: lastUserExternalId\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn coreSdk.flow.start(flowId, interactionId, input, readyOptions);\n\t\t\t}\n\t\t},\n\t\twebauthn: webauthnSdk,\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t},\n\t\t// Returns refresh token. Use this function when:\n\t\t// 1. You need to pass refresh token to another party (For example, in SSR)\n\t\t// 2. Descope project's configuration is set to manage token response in BODY (in contrast to manage response in COOKIES)\n\t\t// NOTE: Refresh token is sensitive token. Prefer using this function only for testing, and to manage token response in COOKIES)\n\t\tgetRefreshToken\n\t};\n\n\tif (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server'\n\t\t);\n\t\treturn webSdk;\n\t}\n\n\tif (autoRefresh) {\n\t\t// Make it easier for Descoper to just call logout/logoutAll without parameters,\n\t\t// In case this is a dev env and refresh is stored in localStorage\n\t\t['logout', 'logoutAll'].forEach((fnName) => {\n\t\t\tconst originFn = coreSdk[fnName] as Function;\n\t\t\twebSdk[fnName] = (...args: any) => {\n\t\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t\tconst token = args?.shift();\n\t\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\t\tconst res = originFn(...logoutArgs);\n\t\t\t\tclearTokens();\n\t\t\t\tIS_BROWSER && localStorage?.removeItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID);\n\t\t\t\tsessionToken.update({ sessionToken: '' });\n\t\t\t\treturn res;\n\t\t\t};\n\t\t});\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tif (config.body) {\n\t\t\tconst fpData = {\n\t\t\t\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t\t\t\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n\t\t\t};\n\t\t\tconfig.body[FP_BODY_DATA] = fpData;\n\t\t}\n\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\tconfig.headers = {\n\t\t\t...config.headers,\n\t\t\t'x-descope-sdk-name': 'web-js',\n\t\t\t'x-descope-sdk-version': BUILD_VERSION\n\t\t};\n\t\treturn config;\n\t};\n\n\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\tif (getRefreshToken()) {\n\t\t\t// refresh on init is done after afterRequestHook is configured\n\t\t\twebSdk.refresh();\n\t\t}\n\t}\n\n\treturn webSdk;\n};\n"],"names":["IS_BROWSER","window","FP_KEY","localStorage","getItem","FP_EP_URL","fp","fpKey","agentP","load","apiKey","endpoint","get","async","sessionId","sessionStorage","Date","now","toString","Math","random","substring","setItem","agent","res","linkedId","requestId","ex","global","FB_DEBUG","console","error","clone","state","Object","assign","State","constructor","init","_State_state","set","this","_State_subscribers","_State_token","__classPrivateFieldSet","current","__classPrivateFieldGet","update","newState","nextState","a","b","aProperties","getOwnPropertyNames","bProperties","length","i","propName","compare","prevState","freeze","setTimeout","values","forEach","cb","subscribe","currentToken","_State_instances","_State_unsubscribe","call","unsubscribeAll","token","refreshTimeoutIds","setRefreshSessionTimeout","refreshFn","sessionJwt","refreshJWT","sessionExpiration","parts","split","claims","JSON","parse","atob","exp","getSessionExpiration","previousTimeout","pop","clearTimeout","refreshTimeout","getTime","timeoutId","push","setDescopeTokens","refreshJwt","cookieParams","cookiePath","cookieDomain","cookieExpiration","Cookies","path","domain","expires","sameSite","secure","setSessionToken","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","isSupported","requirePlatformAuthenticator","Promise","resolve","supported","PublicKeyCredential","isUserVerifyingPlatformAuthenticatorAvailable","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webauthnSdk","sdk","identifier","name","startResponse","webauthn","signUp","start","location","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","webSdk","flow","flowId","interactionId","input","webAuthnSupport","lastUserExternalId","readyOptions","tenant","redirectUrl","href","deviceInfo","lastUser","externalId","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","fnName","originFn","refreshToken","logoutArgs","shift","removeItem","remove","body","fpData","vsid","vrid","headers","me","ok","json","_","status","_b","authInfo","extractJWTResponse","externalIds","handleDescopeTokens","refresh"],"mappings":"qOAAA,MAIaA,EAA+B,oBAAXC,OAEpBC,EACXF,GAAcG,aAAaC,QAPE,2BAOkC,uBAEpDC,EACXL,IAAc,OAAAG,uBAAAA,oBAAAA,aAAcC,QATG,8BASmC,yBCL9DE,EAAMC,IACX,MAAMC,EAASC,EAAIA,KAAC,CAAEC,OAAQH,GAASL,EAAQS,SAAUN,IAEzD,MAA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,GAAS,CAAA,CACnC,CAwB6DY,CAAmBZ,IAAvE7I,WAAEA,EAAUmB,WAAEA,EAAUqB,KAAEA,GAAkD+G,EAAzCnI,EAAnCiE,EAAAA,OAAAkE,EAAA,CAAA,aAAA,aAAA,SAUN,GARIrH,EAAQiD,eACXjE,EAAiBlB,EAAYmB,EAAYC,GAItCpB,GACH1C,EAAMqI,aAAavH,OAAO,CAAEuH,aAAc3F,IAEvCwC,EAAM,CACT,MAAMwF,EAAiC,QAApBtF,EAAAF,aAAA,EAAAA,EAAMkH,mBAAc,IAAAhH,OAAA,EAAAA,EAAA,GACnCrH,GAAc2M,IACL,OAAZxM,mBAAY,IAAZA,cAAAA,aAAcmB,QJnIgC,4BImIaqL,IAE5D1K,EAAMkF,KAAKpE,OAAOoE,EAClB,CAGGxC,GAAcmB,GAAce,EAAQgD,aACvCpF,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CEkBG2M,CACCxC,EAAOyC,QACP/M,EACA,CAAE8I,eAAcnD,QAChB,CAAE0C,cAAaC,iBACf,GAICD,GACClD,KAEHmF,EAAOyC,UAIFzC,IAvENhK,QAAQoI,KACP,wIAEM4B,EAoEK"}
package/dist/index.d.ts CHANGED
@@ -22,7 +22,7 @@ declare type WebJSSDKArgs = Parameters<typeof _descope_core_js_sdk__default>[0]
22
22
  */
23
23
  declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs) => {
24
24
  flow: {
25
- start: (flowId: string, options?: {
25
+ start: (flowId: string, interactionId?: string, input?: Record<string, FormDataEntryValue>, options?: {
26
26
  tenant?: string;
27
27
  }) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.FlowResponse>>;
28
28
  next: (executionId: string, stepId: string, interactionId: string, input?: Record<string, FormDataEntryValue>) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.FlowResponse>>;
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldSet as e,__classPrivateFieldGet as t,__rest as n}from"tslib";import s from"@descope/core-js-sdk";import{load as a}from"@fingerprintjs/fingerprintjs-pro";import o from"js-cookie";const i="undefined"!=typeof window,r=i&&localStorage.getItem("fingerprint.public.key")||"A9aCLRHzKCv3uL69oqDr",l=i&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",c=e=>{const t=a({apiKey:e||r,endpoint:l});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",e);const n=await t,s=await n.get({linkedId:e});sessionStorage.setItem("vrid",s.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var u,d,g,p,f;const h=e=>Object.assign({},e);class w{constructor(t){u.add(this),d.set(this,void 0),g.set(this,{}),p.set(this,0),e(this,d,t,"f")}get current(){return h(t(this,d,"f"))}update(n){const s=n;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],s=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==s.length)return!1;for(let s=0;s<n.length;s+=1){const a=n[s];if(e[a]!==t[a])return!1}return!0})(t(this,d,"f"),s)){const n=t(this,d,"f");e(this,d,s,"f"),Object.freeze(t(this,d,"f")),setTimeout((()=>{Object.values(t(this,g,"f")).forEach((e=>e(h(s),n)))}),0)}}subscribe(n){e(this,p,t(this,p,"f")+1,"f"),t(this,g,"f")[t(this,p,"f")]=n;const s=t(this,p,"f");return()=>t(this,u,"m",f).call(this,s.toString())}unsubscribeAll(){e(this,g,{},"f")}}d=new WeakMap,g=new WeakMap,p=new WeakMap,u=new WeakSet,f=function(e){!!t(this,g,"f")[e]&&delete t(this,g,"f")[e]};let b=[];function v(e,t,n){const s=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(s){let t;for(;t=b.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),o=setTimeout((()=>{e(n)}),a);b.push(o)}}function S(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:s}){e&&o.set("DS",e,{path:t,domain:n,expires:s,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function m(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function y(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),n.publicKey.user.id=I(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.create(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:j(s.rawId),response:Object.assign(Object.assign({},s.response),{attestationObject:j(s.response.attestationObject),clientDataJSON:j(s.response.clientDataJSON)})}));var s}async function k(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.get(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:j(s.rawId),response:Object.assign(Object.assign({},s.response),{authenticatorData:j(s.response.authenticatorData),clientDataJSON:j(s.response.clientDataJSON),signature:j(s.response.signature),userHandle:s.response.userHandle?j(s.response.userHandle):void 0})}));var s}async function O(e=!1){if(!i)return Promise.resolve(!1);const t=!!(PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function I(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function j(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var T=e=>{var{autoRefresh:t=!0,persistTokens:a=!0}=e,r=n(e,["autoRefresh","persistTokens"]);i?c(r.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const l=r;let u,d;const g=new w({sessionToken:""}),p=new w({});l.hooks={beforeRequest:e=>null==u?void 0:u(e),afterRequest:(e,t)=>null==d?void 0:d(e,t)};const f=s(l),h=(b=f,{async signUp(e,t){const n=await b.webauthn.signUp.start(e,window.location.origin,t),s=await y(n.data.options);return await b.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await b.webauthn.signIn.start(e,window.location.origin),n=await k(t.data.options);return await b.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await b.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await y(n.data.options);return await b.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await k(n.data.options);return await b.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await b.webauthn.update.start(e,window.location.origin,t),s=await y(n.data.options);return await b.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:y,get:k,isSupported:O}});var b;const I=Object.assign(Object.assign({},f),{flow:Object.assign(Object.assign({},f.flow),{start:async(e,t)=>{const n=await h.helpers.isSupported(),s=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("dls_last_user_external_id"),a={tenant:null==t?void 0:t.tenant,redirectUrl:window.location.href,deviceInfo:{webAuthnSupport:n}};return s&&(a.lastUser={externalId:s}),f.flow.start(e,a)}}),webauthn:h,onSessionTokenChange:e=>{var t;const n=null===(t=g.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),g.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=p.current;return t&&Object.entries(t).length>0&&e(t),p.subscribe((t=>{e(t)}))},getRefreshToken:m});return i?(t&&["logout","logoutAll"].forEach((e=>{const t=f[e];I[e]=(...e)=>{const n=m(),s=[(null==e?void 0:e.shift())||n,...e],a=t(...s);return localStorage&&localStorage.removeItem("DSR"),o.remove("DS"),i&&(null===localStorage||void 0===localStorage||localStorage.removeItem("dls_last_user_external_id")),g.update({sessionToken:""}),a}})),u=e=>{if(e.body){const t={vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""};e.body.fpData=t}return!e.token&&a&&(e.token=m()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.11"}),e},I.me=async(...e)=>{var t;const n=await f.me(...e);if(n.ok){const e=await(null===(t=n.response)||void 0===t?void 0:t.clone().json());p.update(e)}return n},(t||a)&&(d=(e,s)=>{!async function(e,t,s,a){var o;try{if(401===t.status)return s.sessionToken.update({sessionToken:""}),void s.user.update({});const r=await(null==t?void 0:t.json());if(r){const t=function(e){return(null==e?void 0:e.authInfo)||e||{}}(r),{sessionJwt:l,refreshJwt:c,user:u}=t,d=n(t,["sessionJwt","refreshJwt","user"]);if(a.persistTokens&&S(l,c,d),l&&s.sessionToken.update({sessionToken:l}),u){const e=null===(o=null==u?void 0:u.externalIds)||void 0===o?void 0:o[0];i&&e&&(null===localStorage||void 0===localStorage||localStorage.setItem("dls_last_user_external_id",e)),s.user.update(u)}l&&c&&a.autoRefresh&&v(e,l,c)}}catch(e){console.error("Could not set tokens from body",e)}}(I.refresh,s,{sessionToken:g,user:p},{autoRefresh:t,persistTokens:a})}),t&&m()&&I.refresh(),I):(console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),I)};export{T as default};
1
+ import{__classPrivateFieldSet as e,__classPrivateFieldGet as t,__rest as n}from"tslib";import s from"@descope/core-js-sdk";import{load as a}from"@fingerprintjs/fingerprintjs-pro";import o from"js-cookie";const i="undefined"!=typeof window,r=i&&localStorage.getItem("fingerprint.public.key")||"A9aCLRHzKCv3uL69oqDr",l=i&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",c=e=>{const t=a({apiKey:e||r,endpoint:l});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",e);const n=await t,s=await n.get({linkedId:e});sessionStorage.setItem("vrid",s.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var u,d,g,p,f;const h=e=>Object.assign({},e);class w{constructor(t){u.add(this),d.set(this,void 0),g.set(this,{}),p.set(this,0),e(this,d,t,"f")}get current(){return h(t(this,d,"f"))}update(n){const s=n;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],s=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==s.length)return!1;for(let s=0;s<n.length;s+=1){const a=n[s];if(e[a]!==t[a])return!1}return!0})(t(this,d,"f"),s)){const n=t(this,d,"f");e(this,d,s,"f"),Object.freeze(t(this,d,"f")),setTimeout((()=>{Object.values(t(this,g,"f")).forEach((e=>e(h(s),n)))}),0)}}subscribe(n){e(this,p,t(this,p,"f")+1,"f"),t(this,g,"f")[t(this,p,"f")]=n;const s=t(this,p,"f");return()=>t(this,u,"m",f).call(this,s.toString())}unsubscribeAll(){e(this,g,{},"f")}}d=new WeakMap,g=new WeakMap,p=new WeakMap,u=new WeakSet,f=function(e){!!t(this,g,"f")[e]&&delete t(this,g,"f")[e]};let b=[];function v(e,t,n){const s=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(s){let t;for(;t=b.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),o=setTimeout((()=>{e(n)}),a);b.push(o)}}function S(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:s}){e&&o.set("DS",e,{path:t,domain:n,expires:s,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function m(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function y(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),n.publicKey.user.id=I(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.create(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:j(s.rawId),response:Object.assign(Object.assign({},s.response),{attestationObject:j(s.response.attestationObject),clientDataJSON:j(s.response.clientDataJSON)})}));var s}async function k(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.get(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:j(s.rawId),response:Object.assign(Object.assign({},s.response),{authenticatorData:j(s.response.authenticatorData),clientDataJSON:j(s.response.clientDataJSON),signature:j(s.response.signature),userHandle:s.response.userHandle?j(s.response.userHandle):void 0})}));var s}async function O(e=!1){if(!i)return Promise.resolve(!1);const t=!!(PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function I(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function j(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var T=e=>{var{autoRefresh:t=!0,persistTokens:a=!0}=e,r=n(e,["autoRefresh","persistTokens"]);i?c(r.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const l=r;let u,d;const g=new w({sessionToken:""}),p=new w({});l.hooks={beforeRequest:e=>null==u?void 0:u(e),afterRequest:(e,t)=>null==d?void 0:d(e,t)};const f=s(l),h=(b=f,{async signUp(e,t){const n=await b.webauthn.signUp.start(e,window.location.origin,t),s=await y(n.data.options);return await b.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await b.webauthn.signIn.start(e,window.location.origin),n=await k(t.data.options);return await b.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await b.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await y(n.data.options);return await b.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await k(n.data.options);return await b.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await b.webauthn.update.start(e,window.location.origin,t),s=await y(n.data.options);return await b.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:y,get:k,isSupported:O}});var b;const I=Object.assign(Object.assign({},f),{flow:Object.assign(Object.assign({},f.flow),{start:async(e,t,n,s)=>{const a=await h.helpers.isSupported(),o=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("dls_last_user_external_id"),i={tenant:null==s?void 0:s.tenant,redirectUrl:window.location.href,deviceInfo:{webAuthnSupport:a}};return o&&(i.lastUser={externalId:o}),f.flow.start(e,t,n,i)}}),webauthn:h,onSessionTokenChange:e=>{var t;const n=null===(t=g.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),g.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=p.current;return t&&Object.entries(t).length>0&&e(t),p.subscribe((t=>{e(t)}))},getRefreshToken:m});return i?(t&&["logout","logoutAll"].forEach((e=>{const t=f[e];I[e]=(...e)=>{const n=m(),s=[(null==e?void 0:e.shift())||n,...e],a=t(...s);return localStorage&&localStorage.removeItem("DSR"),o.remove("DS"),i&&(null===localStorage||void 0===localStorage||localStorage.removeItem("dls_last_user_external_id")),g.update({sessionToken:""}),a}})),u=e=>{if(e.body){const t={vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""};e.body.fpData=t}return!e.token&&a&&(e.token=m()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.12"}),e},I.me=async(...e)=>{var t;const n=await f.me(...e);if(n.ok){const e=await(null===(t=n.response)||void 0===t?void 0:t.clone().json());p.update(e)}return n},(t||a)&&(d=(e,s)=>{!async function(e,t,s,a){var o;try{if(401===t.status)return s.sessionToken.update({sessionToken:""}),void s.user.update({});const r=await(null==t?void 0:t.json());if(r){const t=function(e){return(null==e?void 0:e.authInfo)||e||{}}(r),{sessionJwt:l,refreshJwt:c,user:u}=t,d=n(t,["sessionJwt","refreshJwt","user"]);if(a.persistTokens&&S(l,c,d),l&&s.sessionToken.update({sessionToken:l}),u){const e=null===(o=null==u?void 0:u.externalIds)||void 0===o?void 0:o[0];i&&e&&(null===localStorage||void 0===localStorage||localStorage.setItem("dls_last_user_external_id",e)),s.user.update(u)}l&&c&&a.autoRefresh&&v(e,l,c)}}catch(e){console.error("Could not set tokens from body",e)}}(I.refresh,s,{sessionToken:g,user:p},{autoRefresh:t,persistTokens:a})}),t&&m()&&I.refresh(),I):(console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),I)};export{T as default};
2
2
  //# sourceMappingURL=index.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/constants.ts","../src/fp.ts","../src/helpers.ts","../src/state.ts","../src/tokens.ts","../src/webauthn.ts","../src/index.ts"],"sourcesContent":["const FINGERPRINT_PUBLIC_KEY = 'fingerprint.public.key';\nconst FINGERPRINT_ENDPOINT_URL = 'fingerprint.endpoint.url';\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n/** Fingerprint.js identity key */\nexport const FP_KEY =\n\t(IS_BROWSER && localStorage.getItem(FINGERPRINT_PUBLIC_KEY)) || 'A9aCLRHzKCv3uL69oqDr';\n/** Fingerprint.js custom API endpoint */\nexport const FP_EP_URL =\n\t(IS_BROWSER && localStorage?.getItem(FINGERPRINT_ENDPOINT_URL)) || 'https://fp.descope.com';\n/** Fingerprint visitor data */\nexport const FP_BODY_DATA = 'fpData';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n/** External Id of the last user logged in */\nexport const LOCAL_STORAGE_LAST_USER_EXTERNAL_ID = 'dls_last_user_external_id';\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, FP_EP_URL, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY, endpoint: FP_EP_URL });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n\t\t\t\t// istanbul ignore next\n\t\t\t\tif (global.FB_DEBUG) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error(ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n\nexport default fp;\n","/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","// supported state types are string and object\ntype StateObject = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\nimport { IS_BROWSER, LOCAL_STORAGE_LAST_USER_EXTERNAL_ID } from './constants';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tconst externalId = user?.externalIds?.[0];\n\t\t\t\tif (IS_BROWSER && externalId) {\n\t\t\t\t\tlocalStorage?.setItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID, externalId);\n\t\t\t\t}\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { IS_BROWSER } from './constants';\nimport { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget,\n\t\t/** Checks if the browser supports WebAuthn,\n\t\t * and can optionally require in addition that The browser supports WebAuthn with built-in biometrics */\n\t\tisSupported\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\nasync function isSupported(requirePlatformAuthenticator: boolean = false): Promise<boolean> {\n\tif (!IS_BROWSER) {\n\t\treturn Promise.resolve(false);\n\t}\n\tconst supported = !!(\n\t\tPublicKeyCredential &&\n\t\tnavigator.credentials &&\n\t\tnavigator.credentials.create &&\n\t\tnavigator.credentials.get\n\t);\n\tif (\n\t\tsupported &&\n\t\trequirePlatformAuthenticator &&\n\t\tPublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n\t) {\n\t\treturn PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n\t}\n\treturn supported;\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport {\n\tFP_BODY_DATA,\n\tIS_BROWSER,\n\tLOCAL_STORAGE_LAST_USER_EXTERNAL_ID,\n\tVISITOR_REQUEST_ID_PARAM,\n\tVISITOR_SESSION_ID_PARAM\n} from './constants';\nimport fp from './fp';\nimport State from './state';\nimport { clearTokens, getRefreshToken, handleDescopeTokens } from './tokens';\nimport { CoreSdk, TokensOptions } from './types';\nimport createWebAuthn from './webauthn';\n\ndeclare const BUILD_VERSION: string;\n\n/** Configuration arguments which include the Descope core SDK args and fingerprint configuration.\n * Also specifies token options - if we should persist tokens from responses automatically and auto-refresh.\n */\nexport type WebJSSDKArgs = Parameters<typeof createSdk>[0] &\n\tTokensOptions & {\n\t\t// FingerprintJS API key\n\t\tfpKey?: string;\n\t};\n\n/**\n * Wrapper around DescopeSDK to handle fingerprint.js and storage of JWT tokens in cookies and localStorage,\n * It also sets a timer to refresh session JWT automatically.\n */\nexport default ({ autoRefresh = true, persistTokens = true, ...args }: WebJSSDKArgs) => {\n\t// istanbul ignore next\n\tif (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\tconst webauthnSdk = createWebAuthn(coreSdk);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\tflow: {\n\t\t\t...coreSdk.flow,\n\t\t\tstart: async (flowId: string, options?: { tenant?: string }) => {\n\t\t\t\tconst webAuthnSupport = await webauthnSdk.helpers.isSupported();\n\t\t\t\tconst lastUserExternalId = localStorage?.getItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID);\n\t\t\t\tconst readyOptions: Parameters<typeof coreSdk.flow.start>[1] = {\n\t\t\t\t\ttenant: options?.tenant,\n\t\t\t\t\tredirectUrl: window.location.href,\n\t\t\t\t\tdeviceInfo: {\n\t\t\t\t\t\twebAuthnSupport\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tif (lastUserExternalId) {\n\t\t\t\t\treadyOptions.lastUser = {\n\t\t\t\t\t\texternalId: lastUserExternalId\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn coreSdk.flow.start(flowId, readyOptions);\n\t\t\t}\n\t\t},\n\t\twebauthn: webauthnSdk,\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t},\n\t\t// Returns refresh token. Use this function when:\n\t\t// 1. You need to pass refresh token to another party (For example, in SSR)\n\t\t// 2. Descope project's configuration is set to manage token response in BODY (in contrast to manage response in COOKIES)\n\t\t// NOTE: Refresh token is sensitive token. Prefer using this function only for testing, and to manage token response in COOKIES)\n\t\tgetRefreshToken\n\t};\n\n\tif (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server'\n\t\t);\n\t\treturn webSdk;\n\t}\n\n\tif (autoRefresh) {\n\t\t// Make it easier for Descoper to just call logout/logoutAll without parameters,\n\t\t// In case this is a dev env and refresh is stored in localStorage\n\t\t['logout', 'logoutAll'].forEach((fnName) => {\n\t\t\tconst originFn = coreSdk[fnName] as Function;\n\t\t\twebSdk[fnName] = (...args: any) => {\n\t\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t\tconst token = args?.shift();\n\t\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\t\tconst res = originFn(...logoutArgs);\n\t\t\t\tclearTokens();\n\t\t\t\tIS_BROWSER && localStorage?.removeItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID);\n\t\t\t\tsessionToken.update({ sessionToken: '' });\n\t\t\t\treturn res;\n\t\t\t};\n\t\t});\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tif (config.body) {\n\t\t\tconst fpData = {\n\t\t\t\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t\t\t\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n\t\t\t};\n\t\t\tconfig.body[FP_BODY_DATA] = fpData;\n\t\t}\n\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\tconfig.headers = {\n\t\t\t...config.headers,\n\t\t\t'x-descope-sdk-name': 'web-js',\n\t\t\t'x-descope-sdk-version': BUILD_VERSION\n\t\t};\n\t\treturn config;\n\t};\n\n\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\tif (getRefreshToken()) {\n\t\t\t// refresh on init is done after afterRequestHook is configured\n\t\t\twebSdk.refresh();\n\t\t}\n\t}\n\n\treturn webSdk;\n};\n"],"names":["IS_BROWSER","window","FP_KEY","localStorage","getItem","FP_EP_URL","fp","fpKey","agentP","load","apiKey","endpoint","get","async","sessionId","sessionStorage","Date","now","toString","Math","random","substring","setItem","agent","res","linkedId","requestId","ex","global","FB_DEBUG","console","error","clone","state","Object","assign","State","constructor","init","_State_state","set","this","_State_subscribers","_State_token","__classPrivateFieldSet","current","__classPrivateFieldGet","update","newState","nextState","a","b","aProperties","getOwnPropertyNames","bProperties","length","i","propName","compare","prevState","freeze","setTimeout","values","forEach","cb","subscribe","currentToken","_State_instances","_State_unsubscribe","call","unsubscribeAll","token","refreshTimeoutIds","setRefreshSessionTimeout","refreshFn","sessionJwt","refreshJWT","sessionExpiration","parts","split","claims","JSON","parse","atob","exp","getSessionExpiration","previousTimeout","pop","clearTimeout","refreshTimeout","getTime","timeoutId","push","setDescopeTokens","refreshJwt","cookieParams","cookiePath","cookieDomain","cookieExpiration","Cookies","path","domain","expires","sameSite","secure","setSessionToken","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","isSupported","requirePlatformAuthenticator","Promise","resolve","supported","PublicKeyCredential","isUserVerifyingPlatformAuthenticatorAvailable","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","index","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webauthnSdk","sdk","identifier","name","startResponse","webauthn","signUp","start","location","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","webSdk","flow","flowId","webAuthnSupport","lastUserExternalId","readyOptions","tenant","redirectUrl","href","deviceInfo","lastUser","externalId","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","fnName","originFn","refreshToken","logoutArgs","shift","removeItem","remove","body","fpData","vsid","vrid","headers","me","ok","json","_","status","_b","authInfo","extractJWTResponse","externalIds","handleDescopeTokens","refresh"],"mappings":"4MAAA,MAIaA,EAA+B,oBAAXC,OAEpBC,EACXF,GAAcG,aAAaC,QAPE,2BAOkC,uBAEpDC,EACXL,IAAc,OAAAG,uBAAAA,oBAAAA,aAAcC,QATG,8BASmC,yBCL9DE,EAAMC,IACX,MAAMC,EAASC,EAAK,CAAEC,OAAQH,GAASL,EAAQS,SAAUN,IAEzD,MAAO,CACNO,IAAKC,UACJ,IACC,IAAIC,EAAYC,eAAeX,QDGK,QCD/BU,IACJA,GCVHE,KAAKC,MAAMC,SAAS,IACpBC,KAAKC,SAASF,SAAS,IAAIG,UAAU,GACrCF,KAAKC,SAASF,SAAS,IAAIG,UAAU,IACpCA,UAAU,EAAG,KDUZN,eAAeO,QDHqB,OCGaR,GAEjD,MAAMS,QAAcf,EACdgB,QAAYD,EAAMX,IAAI,CAAEa,SAAUX,IACxCC,eAAeO,QDLqB,OCKaE,EAAIE,UAOrD,CANC,MAAOC,GAEJC,OAAOC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,IAE5DzK,EAAMkF,KAAKpE,OAAOoE,EAClB,CAGGxC,GAAcmB,GAAce,EAAQiD,aACvCrF,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CEaG0M,CACCtC,EAAOuC,QACP9M,EACA,CAAE+I,eAAcpD,QAChB,CAAE2C,cAAaC,iBACf,GAICD,GACCnD,KAEHoF,EAAOuC,UAIFvC,IAvENjK,QAAQqI,KACP,wIAEM4B,EAoEK"}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/constants.ts","../src/fp.ts","../src/helpers.ts","../src/state.ts","../src/tokens.ts","../src/webauthn.ts","../src/index.ts"],"sourcesContent":["const FINGERPRINT_PUBLIC_KEY = 'fingerprint.public.key';\nconst FINGERPRINT_ENDPOINT_URL = 'fingerprint.endpoint.url';\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n/** Fingerprint.js identity key */\nexport const FP_KEY =\n\t(IS_BROWSER && localStorage.getItem(FINGERPRINT_PUBLIC_KEY)) || 'A9aCLRHzKCv3uL69oqDr';\n/** Fingerprint.js custom API endpoint */\nexport const FP_EP_URL =\n\t(IS_BROWSER && localStorage?.getItem(FINGERPRINT_ENDPOINT_URL)) || 'https://fp.descope.com';\n/** Fingerprint visitor data */\nexport const FP_BODY_DATA = 'fpData';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n/** External Id of the last user logged in */\nexport const LOCAL_STORAGE_LAST_USER_EXTERNAL_ID = 'dls_last_user_external_id';\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, FP_EP_URL, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY, endpoint: FP_EP_URL });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n\t\t\t\t// istanbul ignore next\n\t\t\t\tif (global.FB_DEBUG) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error(ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n\nexport default fp;\n","/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","// supported state types are string and object\ntype StateObject = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\nimport { IS_BROWSER, LOCAL_STORAGE_LAST_USER_EXTERNAL_ID } from './constants';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tconst externalId = user?.externalIds?.[0];\n\t\t\t\tif (IS_BROWSER && externalId) {\n\t\t\t\t\tlocalStorage?.setItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID, externalId);\n\t\t\t\t}\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { IS_BROWSER } from './constants';\nimport { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget,\n\t\t/** Checks if the browser supports WebAuthn,\n\t\t * and can optionally require in addition that The browser supports WebAuthn with built-in biometrics */\n\t\tisSupported\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\nasync function isSupported(requirePlatformAuthenticator: boolean = false): Promise<boolean> {\n\tif (!IS_BROWSER) {\n\t\treturn Promise.resolve(false);\n\t}\n\tconst supported = !!(\n\t\tPublicKeyCredential &&\n\t\tnavigator.credentials &&\n\t\tnavigator.credentials.create &&\n\t\tnavigator.credentials.get\n\t);\n\tif (\n\t\tsupported &&\n\t\trequirePlatformAuthenticator &&\n\t\tPublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n\t) {\n\t\treturn PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n\t}\n\treturn supported;\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport {\n\tFP_BODY_DATA,\n\tIS_BROWSER,\n\tLOCAL_STORAGE_LAST_USER_EXTERNAL_ID,\n\tVISITOR_REQUEST_ID_PARAM,\n\tVISITOR_SESSION_ID_PARAM\n} from './constants';\nimport fp from './fp';\nimport State from './state';\nimport { clearTokens, getRefreshToken, handleDescopeTokens } from './tokens';\nimport { CoreSdk, TokensOptions } from './types';\nimport createWebAuthn from './webauthn';\n\ndeclare const BUILD_VERSION: string;\n\n/** Configuration arguments which include the Descope core SDK args and fingerprint configuration.\n * Also specifies token options - if we should persist tokens from responses automatically and auto-refresh.\n */\nexport type WebJSSDKArgs = Parameters<typeof createSdk>[0] &\n\tTokensOptions & {\n\t\t// FingerprintJS API key\n\t\tfpKey?: string;\n\t};\n\n/**\n * Wrapper around DescopeSDK to handle fingerprint.js and storage of JWT tokens in cookies and localStorage,\n * It also sets a timer to refresh session JWT automatically.\n */\nexport default ({ autoRefresh = true, persistTokens = true, ...args }: WebJSSDKArgs) => {\n\t// istanbul ignore next\n\tif (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\tconst webauthnSdk = createWebAuthn(coreSdk);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\tflow: {\n\t\t\t...coreSdk.flow,\n\t\t\tstart: async (\n\t\t\t\tflowId: string,\n\t\t\t\tinteractionId?: string,\n\t\t\t\tinput?: Record<string, FormDataEntryValue>,\n\t\t\t\toptions?: { tenant?: string }\n\t\t\t) => {\n\t\t\t\tconst webAuthnSupport = await webauthnSdk.helpers.isSupported();\n\t\t\t\tconst lastUserExternalId = localStorage?.getItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID);\n\t\t\t\tconst readyOptions: Parameters<typeof coreSdk.flow.start>[3] = {\n\t\t\t\t\ttenant: options?.tenant,\n\t\t\t\t\tredirectUrl: window.location.href,\n\t\t\t\t\tdeviceInfo: {\n\t\t\t\t\t\twebAuthnSupport\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tif (lastUserExternalId) {\n\t\t\t\t\treadyOptions.lastUser = {\n\t\t\t\t\t\texternalId: lastUserExternalId\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn coreSdk.flow.start(flowId, interactionId, input, readyOptions);\n\t\t\t}\n\t\t},\n\t\twebauthn: webauthnSdk,\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t},\n\t\t// Returns refresh token. Use this function when:\n\t\t// 1. You need to pass refresh token to another party (For example, in SSR)\n\t\t// 2. Descope project's configuration is set to manage token response in BODY (in contrast to manage response in COOKIES)\n\t\t// NOTE: Refresh token is sensitive token. Prefer using this function only for testing, and to manage token response in COOKIES)\n\t\tgetRefreshToken\n\t};\n\n\tif (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server'\n\t\t);\n\t\treturn webSdk;\n\t}\n\n\tif (autoRefresh) {\n\t\t// Make it easier for Descoper to just call logout/logoutAll without parameters,\n\t\t// In case this is a dev env and refresh is stored in localStorage\n\t\t['logout', 'logoutAll'].forEach((fnName) => {\n\t\t\tconst originFn = coreSdk[fnName] as Function;\n\t\t\twebSdk[fnName] = (...args: any) => {\n\t\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t\tconst token = args?.shift();\n\t\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\t\tconst res = originFn(...logoutArgs);\n\t\t\t\tclearTokens();\n\t\t\t\tIS_BROWSER && localStorage?.removeItem(LOCAL_STORAGE_LAST_USER_EXTERNAL_ID);\n\t\t\t\tsessionToken.update({ sessionToken: '' });\n\t\t\t\treturn res;\n\t\t\t};\n\t\t});\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tif (config.body) {\n\t\t\tconst fpData = {\n\t\t\t\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t\t\t\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n\t\t\t};\n\t\t\tconfig.body[FP_BODY_DATA] = fpData;\n\t\t}\n\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\tconfig.headers = {\n\t\t\t...config.headers,\n\t\t\t'x-descope-sdk-name': 'web-js',\n\t\t\t'x-descope-sdk-version': BUILD_VERSION\n\t\t};\n\t\treturn config;\n\t};\n\n\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\tif (getRefreshToken()) {\n\t\t\t// refresh on init is done after afterRequestHook is configured\n\t\t\twebSdk.refresh();\n\t\t}\n\t}\n\n\treturn webSdk;\n};\n"],"names":["IS_BROWSER","window","FP_KEY","localStorage","getItem","FP_EP_URL","fp","fpKey","agentP","load","apiKey","endpoint","get","async","sessionId","sessionStorage","Date","now","toString","Math","random","substring","setItem","agent","res","linkedId","requestId","ex","global","FB_DEBUG","console","error","clone","state","Object","assign","State","constructor","init","_State_state","set","this","_State_subscribers","_State_token","__classPrivateFieldSet","current","__classPrivateFieldGet","update","newState","nextState","a","b","aProperties","getOwnPropertyNames","bProperties","length","i","propName","compare","prevState","freeze","setTimeout","values","forEach","cb","subscribe","currentToken","_State_instances","_State_unsubscribe","call","unsubscribeAll","token","refreshTimeoutIds","setRefreshSessionTimeout","refreshFn","sessionJwt","refreshJWT","sessionExpiration","parts","split","claims","JSON","parse","atob","exp","getSessionExpiration","previousTimeout","pop","clearTimeout","refreshTimeout","getTime","timeoutId","push","setDescopeTokens","refreshJwt","cookieParams","cookiePath","cookieDomain","cookieExpiration","Cookies","path","domain","expires","sameSite","secure","setSessionToken","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","isSupported","requirePlatformAuthenticator","Promise","resolve","supported","PublicKeyCredential","isUserVerifyingPlatformAuthenticatorAvailable","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","index","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webauthnSdk","sdk","identifier","name","startResponse","webauthn","signUp","start","location","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","webSdk","flow","flowId","interactionId","input","webAuthnSupport","lastUserExternalId","readyOptions","tenant","redirectUrl","href","deviceInfo","lastUser","externalId","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","fnName","originFn","refreshToken","logoutArgs","shift","removeItem","remove","body","fpData","vsid","vrid","headers","me","ok","json","_","status","_b","authInfo","extractJWTResponse","externalIds","handleDescopeTokens","refresh"],"mappings":"4MAAA,MAIaA,EAA+B,oBAAXC,OAEpBC,EACXF,GAAcG,aAAaC,QAPE,2BAOkC,uBAEpDC,EACXL,IAAc,OAAAG,uBAAAA,oBAAAA,aAAcC,QATG,8BASmC,yBCL9DE,EAAMC,IACX,MAAMC,EAASC,EAAK,CAAEC,OAAQH,GAASL,EAAQS,SAAUN,IAEzD,MAAO,CACNO,IAAKC,UACJ,IACC,IAAIC,EAAYC,eAAeX,QDGK,QCD/BU,IACJA,GCVHE,KAAKC,MAAMC,SAAS,IACpBC,KAAKC,SAASF,SAAS,IAAIG,UAAU,GACrCF,KAAKC,SAASF,SAAS,IAAIG,UAAU,IACpCA,UAAU,EAAG,KDUZN,eAAeO,QDHqB,OCGaR,GAEjD,MAAMS,QAAcf,EACdgB,QAAYD,EAAMX,IAAI,CAAEa,SAAUX,IACxCC,eAAeO,QDLqB,OCKaE,EAAIE,UAOrD,CANC,MAAOC,GAEJC,OAAOC,UAEVC,QAAQC,MAAMJ,EAEf,GAEF,gBEzBF,MAmBMK,EAASC,GACdC,OAAAC,OAAA,CAAA,EAAYF,GAGb,MAAMG,EAOLC,YAAYC,eANZC,EAAUC,IAAAC,UAAA,GAEVC,EAAAF,IAAAC,KAA+B,CAAA,GAE/BE,EAAAH,IAAAC,KAAS,GAGRG,EAAAH,KAAIF,EAAUD,EAAI,IAClB,CAEGO,cACH,OAAOb,EAAMc,EAAAL,KAAIF,EAAA,KACjB,CAEDQ,OAAOC,GACN,MAAMC,EAAeD,EACrB,IAxCc,EAAwBE,EAAMC,KAC7C,MAAMC,EAAeF,GAAKhB,OAAOmB,oBAAoBH,IAAO,GACtDI,EAAeH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