@descope/web-js-sdk 0.1.0-alpha.3 → 0.1.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,11 +19,11 @@ const myProjectId = 'xxx';
19
19
  const sdk = descopeSdk({ projectId: myProjectId });
20
20
 
21
21
  sdk.onSessionTokenChange((newSession, oldSession) => {
22
- // handle session token change...
22
+ // handle session token change...
23
23
  });
24
24
 
25
25
  sdk.onUserChange((newUser, oldUser) => {
26
- // handle user change...
26
+ // handle user change...
27
27
  });
28
28
  const userIdentifier = 'identifier';
29
29
  sdk.otp.signIn.email(userIdentifier);
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),s=require("@fingerprintjs/fingerprintjs-pro"),a=require("js-cookie");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=n(t),r=n(a);const o=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],c=e=>{const t=s.load({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=o("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 s=await t,a=await s.get({linkedId:e});sessionStorage.setItem("vrid",a.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var l,u,d,g,f;const h=e=>"string"==typeof e?e:Object.assign({},e);class p{constructor(t){l.add(this),u.set(this,void 0),d.set(this,{}),g.set(this,0),e.__classPrivateFieldSet(this,u,t,"f")}get current(){return h(e.__classPrivateFieldGet(this,u,"f"))}update(t){let s=t;if("object"==typeof t&&"object"==typeof e.__classPrivateFieldGet(this,u,"f")&&(s=Object.assign(Object.assign({},e.__classPrivateFieldGet(this,u,"f")),t)),!((e,t)=>{if("string"==typeof e)return e===t;const s=e&&Object.getOwnPropertyNames(e)||[],a=t&&Object.getOwnPropertyNames(t)||[];if(s.length!==a.length)return!1;for(let a=0;a<s.length;a+=1){const n=s[a];if(e[n]!==t[n])return!1}return!0})(e.__classPrivateFieldGet(this,u,"f"),s)){const t=e.__classPrivateFieldGet(this,u,"f");e.__classPrivateFieldSet(this,u,s,"f"),Object.freeze(e.__classPrivateFieldGet(this,u,"f")),setTimeout((()=>{Object.values(e.__classPrivateFieldGet(this,d,"f")).forEach((e=>e(h(s),t)))}),0)}}subscribe(t){var s;e.__classPrivateFieldSet(this,g,e.__classPrivateFieldGet(this,g,"f")+1,"f"),e.__classPrivateFieldGet(this,d,"f")[e.__classPrivateFieldGet(this,g,"f")]=t,((s=e.__classPrivateFieldGet(this,u,"f"))&&"string"!=typeof s?0===Object.entries(s).length:!s)||t(h(e.__classPrivateFieldGet(this,u,"f")));const a=e.__classPrivateFieldGet(this,g,"f");return()=>e.__classPrivateFieldGet(this,l,"m",f).call(this,a.toString())}unsubscribeAll(){e.__classPrivateFieldSet(this,d,{},"f")}}u=new WeakMap,d=new WeakMap,g=new WeakMap,l=new WeakSet,f=function(t){!!e.__classPrivateFieldGet(this,d,"f")[t]&&delete e.__classPrivateFieldGet(this,d,"f")[t]};let b=[];function v(e,t,s){const a=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(a){let t;for(;t=b.pop();)clearTimeout(t);const n=a.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(s)}),n);b.push(i)}}function w(e,t,s){!function(e,{cookiePath:t,cookieDomain:s,cookieExpiration:a}){e&&r.default.set("DS",e,{path:t,domain:s,expires:a,sameSite:"None",secure:!0})}(e,s),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function _(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function S(e){const t=function(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=O(s.publicKey.challenge),s.publicKey.user.id=O(s.publicKey.user.id),null===(t=s.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=O(e.id)})),s}(e),s=await navigator.credentials.create(t);return a=s,JSON.stringify(Object.assign(Object.assign({},a),{rawId:j(a.rawId),response:Object.assign(Object.assign({},a.response),{attestationObject:j(a.response.attestationObject),clientDataJSON:j(a.response.clientDataJSON)})}));var a}async function y(e){const t=function(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=O(s.publicKey.challenge),null===(t=s.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=O(e.id)})),s}(e),s=await navigator.credentials.get(t);return a=s,JSON.stringify(Object.assign(Object.assign({},a),{rawId:j(a.rawId),response:Object.assign(Object.assign({},a.response),{authenticatorData:j(a.response.authenticatorData),clientDataJSON:j(a.response.clientDataJSON),signature:j(a.response.signature),userHandle:a.response.userHandle?j(a.response.userHandle):void 0})}));var a}function O(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:s=!0,persistTokens:a=!0}=t,n=e.__rest(t,["autoRefresh","persistTokens"]);c(n.fpKey).get().catch((()=>null));const o=n;let l,u;const d=new p(""),g=new p({});o.hooks={beforeRequest:e=>null==l?void 0:l(e),afterRequest:(e,t)=>null==u?void 0:u(e,t)};const f=i.default(o),h=Object.assign(Object.assign({},f),{webauthn:(b=f,{async signUp(e,t){const s=await b.webauthn.signUp.start(e,window.location.origin,t),a=await S(s.data.options);return await b.webauthn.signUp.finish(s.data.transactionId,a)},async signIn(e){const t=await b.webauthn.signIn.start(e,window.location.origin),s=await y(t.data.options);return await b.webauthn.signIn.finish(t.data.transactionId,s)},async update(e,t){const s=await b.webauthn.update.start(e,window.location.origin,t),a=await S(s.data.options);return await b.webauthn.update.finish(s.data.transactionId,a)},helpers:{create:S,get:y}}),onSessionTokenChange:d.subscribe,onUserChange:g.subscribe});var b;return s&&(h.logout=(...e)=>{const t=_(),s=[(null==e?void 0:e.shift())||t,...e],a=f.logout(...s);return localStorage&&localStorage.removeItem("DSR"),r.default.remove("DS"),a}),l=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!e.token&&a&&(e.token=_()),e},(s||a)&&(u=(t,n)=>{!async function(t,s,a,n){try{const i=await(null==s?void 0:s.json());if(i){const s=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:r,refreshJwt:o,user:c}=s,l=e.__rest(s,["sessionJwt","refreshJwt","user"]);n.persistTokens&&w(r,o,l),a.sessionToken.update(r),a.user.update(c),r&&o&&n.autoRefresh&&v(t,r,o)}}catch(e){console.error("Could not set tokens from body",e)}}(h.refresh,n,{sessionToken:d,user:g},{autoRefresh:s,persistTokens:a})}),s&&h.refresh(),h};
1
+ "use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),s=require("@fingerprintjs/fingerprintjs-pro"),a=require("js-cookie");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=n(t),r=n(a);const o=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],c=e=>{const t=s.load({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=o("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 s=await t,a=await s.get({linkedId:e});sessionStorage.setItem("vrid",a.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var l,u,d,g,f;const h=e=>"string"==typeof e?e:Object.assign({},e);class p{constructor(t){l.add(this),u.set(this,void 0),d.set(this,{}),g.set(this,0),e.__classPrivateFieldSet(this,u,t,"f")}get current(){return h(e.__classPrivateFieldGet(this,u,"f"))}update(t){let s=t;if("object"==typeof t&&"object"==typeof e.__classPrivateFieldGet(this,u,"f")&&(s=Object.assign(Object.assign({},e.__classPrivateFieldGet(this,u,"f")),t)),!((e,t)=>{if("string"==typeof e)return e===t;const s=e&&Object.getOwnPropertyNames(e)||[],a=t&&Object.getOwnPropertyNames(t)||[];if(s.length!==a.length)return!1;for(let a=0;a<s.length;a+=1){const n=s[a];if(e[n]!==t[n])return!1}return!0})(e.__classPrivateFieldGet(this,u,"f"),s)){const t=e.__classPrivateFieldGet(this,u,"f");e.__classPrivateFieldSet(this,u,s,"f"),Object.freeze(e.__classPrivateFieldGet(this,u,"f")),setTimeout((()=>{Object.values(e.__classPrivateFieldGet(this,d,"f")).forEach((e=>e(h(s),t)))}),0)}}subscribe(t){var s;e.__classPrivateFieldSet(this,g,e.__classPrivateFieldGet(this,g,"f")+1,"f"),e.__classPrivateFieldGet(this,d,"f")[e.__classPrivateFieldGet(this,g,"f")]=t,((s=e.__classPrivateFieldGet(this,u,"f"))&&"string"!=typeof s?0===Object.entries(s).length:!s)||t(h(e.__classPrivateFieldGet(this,u,"f")));const a=e.__classPrivateFieldGet(this,g,"f");return()=>e.__classPrivateFieldGet(this,l,"m",f).call(this,a.toString())}unsubscribeAll(){e.__classPrivateFieldSet(this,d,{},"f")}}u=new WeakMap,d=new WeakMap,g=new WeakMap,l=new WeakSet,f=function(t){!!e.__classPrivateFieldGet(this,d,"f")[t]&&delete e.__classPrivateFieldGet(this,d,"f")[t]};let b=[];function w(e,t,s){const a=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(a){let t;for(;t=b.pop();)clearTimeout(t);const n=a.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(s)}),n);b.push(i)}}function v(e,t,s){!function(e,{cookiePath:t,cookieDomain:s,cookieExpiration:a}){e&&r.default.set("DS",e,{path:t,domain:s,expires:a,sameSite:"None",secure:!0})}(e,s),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function _(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function S(e){const t=function(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=O(s.publicKey.challenge),s.publicKey.user.id=O(s.publicKey.user.id),null===(t=s.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=O(e.id)})),s}(e),s=await navigator.credentials.create(t);return a=s,JSON.stringify(Object.assign(Object.assign({},a),{rawId:j(a.rawId),response:Object.assign(Object.assign({},a.response),{attestationObject:j(a.response.attestationObject),clientDataJSON:j(a.response.clientDataJSON)})}));var a}async function y(e){const t=function(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=O(s.publicKey.challenge),null===(t=s.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=O(e.id)})),s}(e),s=await navigator.credentials.get(t);return a=s,JSON.stringify(Object.assign(Object.assign({},a),{rawId:j(a.rawId),response:Object.assign(Object.assign({},a.response),{authenticatorData:j(a.response.authenticatorData),clientDataJSON:j(a.response.clientDataJSON),signature:j(a.response.signature),userHandle:a.response.userHandle?j(a.response.userHandle):void 0})}));var a}function O(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,"")}const m="undefined"!=typeof window;module.exports=t=>{var{autoRefresh:s=!0,persistTokens:a=!0}=t,n=e.__rest(t,["autoRefresh","persistTokens"]);m?c(n.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const o=n;let l,u;const d=new p(""),g=new p({});o.hooks={beforeRequest:e=>null==l?void 0:l(e),afterRequest:(e,t)=>null==u?void 0:u(e,t)};const f=i.default(o),h=Object.assign(Object.assign({},f),{webauthn:(b=f,{async signUp(e,t){const s=await b.webauthn.signUp.start(e,window.location.origin,t),a=await S(s.data.options);return await b.webauthn.signUp.finish(s.data.transactionId,a)},async signIn(e){const t=await b.webauthn.signIn.start(e,window.location.origin),s=await y(t.data.options);return await b.webauthn.signIn.finish(t.data.transactionId,s)},async update(e,t){const s=await b.webauthn.update.start(e,window.location.origin,t),a=await S(s.data.options);return await b.webauthn.update.finish(s.data.transactionId,a)},helpers:{create:S,get:y}}),onSessionTokenChange:d.subscribe,onUserChange:g.subscribe});var b;return s&&(h.logout=(...e)=>{const t=_(),s=[(null==e?void 0:e.shift())||t,...e],a=f.logout(...s);return localStorage&&localStorage.removeItem("DSR"),r.default.remove("DS"),a}),l=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!e.token&&a&&(e.token=_()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.4"}),e},(s||a)&&(u=(t,n)=>{!async function(t,s,a,n){try{const i=await(null==s?void 0:s.json());if(i){const s=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:r,refreshJwt:o,user:c}=s,l=e.__rest(s,["sessionJwt","refreshJwt","user"]);n.persistTokens&&v(r,o,l),a.sessionToken.update(r),a.user.update(c),r&&o&&n.autoRefresh&&w(t,r,o)}}catch(e){console.error("Could not set tokens from body",e)}}(h.refresh,n,{sessionToken:d,user:g},{autoRefresh:s,persistTokens:a})}),s&&h.refresh(),h};
2
2
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../../src/constants.ts","../../src/helpers.ts","../../src/fp.ts","../../src/state.ts","../../src/tokens.ts","../../src/webauthn.ts","../../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\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","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\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","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\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 // 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","// supported state types are string and object\ntype StateObject = string | Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject> (a: T, b: T) => {\n if (typeof a === 'string') {\n return a === b;\n }\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 if (typeof state === 'string') {\n return state;\n }\n return { ...state };\n}\n\nconst isEmpty = (state: StateObject): boolean => {\n if (!state || typeof state === 'string') {\n return !state;\n }\n return Object.entries(state).length === 0;\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 return clone(this.#state);\n\t}\n\n\tupdate(newState: T) {\n\t\tlet nextState: T = newState;\n\t\tif (typeof newState === 'object' && typeof this.#state === 'object') {\n\t\t\tnextState = { ...this.#state , ...newState };\n\t\t}\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) =>\n\t\t\t\t\tcb(clone(nextState) as T, prevState)\n\t\t\t\t);\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\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\tif (!isEmpty(this.#state)) {\n\t\t\tcb(clone(this.#state) as T);\n\t\t}\n\n // return unsubscribe function\n const 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> = (\n\tstate: T,\n\tprevState?: T\n) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\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(sessionJwt: string, refreshJwt: string, cookieParams: Partial<JWTResponse>) {\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(refreshFn: RefreshFn, res: Response, state: SdkState, options: TokensOptions) {\n\ttry {\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\t\t\t\n\t\t\t// Update state\n\t\t\tstate.sessionToken.update(sessionJwt);\n\t\t\tstate.user.update(user);\n\t\t\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 { 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(startResponse.data.transactionId, createResponse);\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(startResponse.data.transactionId, getResponse);\n\t\treturn finishResponse;\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(identifier, window.location.origin, token);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(startResponse.data.transactionId, createResponse);\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}\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(createOptions)) 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\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & { response: AuthenticatorAttestationResponse };\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 & { response: AuthenticatorAssertionResponse };\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 ? encodeBase64Url(credential.response.userHandle) : 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 { VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } 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\nconst prepareQueryParams = (\n\tqueryParams\n): {\n\t[key: string]: string;\n} => ({\n\t...queryParams,\n\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n});\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] & TokensOptions & {\n\t// FingerprintJS API key\n\tfpKey?: string;\n};\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\tfp(args.fpKey)\n\t\t.get()\n\t\t.catch(() => null);\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<string>('');\n\tconst user = new State<UserResponse | {}>({});\n\t\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\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: sessionToken.subscribe,\n\t\tonUserChange: user.subscribe\n\t};\n\n\tif (autoRefresh) {\n\t\twebSdk.logout = (...args: Parameters<CoreSdk['logout']>) => {\n\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t// Make it easier for Descoper to just call logout without parameters if this is dev env and refresh is stored in localStorage\n\t\t\tconst token = args?.shift();\n\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\tconst res = coreSdk.logout(...logoutArgs);\n\t\t\tclearTokens();\n\t\t\treturn res;\n\t\t};\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tconfig.queryParams = prepareQueryParams(config.queryParams);\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\treturn config;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (req, res) => {\n\t\t\thandleDescopeTokens(webSdk.refresh, res, { sessionToken, user }, { autoRefresh, persistTokens });\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\t// refresh on init is done after afterRequestHook is configured\n\t\twebSdk.refresh();\n\t}\n\n\treturn webSdk;\n};\n"],"names":["getQueryParam","param","Proxy","URLSearchParams","window","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","async","sessionId","sessionStorage","getItem","Date","now","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","entries","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","localStorage","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","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","autoRefresh","persistTokens","args","__rest","catch","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","helpers","onSessionTokenChange","onUserChange","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","body","json","authInfo","extractJWTResponse","handleDescopeTokens","refresh"],"mappings":"qOACO,MCSMA,EAAiBC,GARd,IAAIC,MAAM,IAAIC,gBAAgBC,OAAOC,SAASC,QAAS,CACrEC,IAAK,CAACC,EAAcC,IAASD,EAAaD,IAAIE,EAAKC,cAUtCT,GCRTU,EAAMC,IACX,MAAMC,EAASC,EAAAA,KAAK,CAAEC,OAAQH,GFLT,yBEOrB,MAAO,CACNL,IAAKS,UACJ,IACC,IAAIC,EAAYC,eAAeC,QFRK,QES/BF,IACJA,EAAYjB,EFVuB,SEa/BiB,IACJA,GDGHG,KAAKC,MAAMX,SAAS,IACpBY,KAAKC,SAASb,SAAS,IAAIc,UAAU,GACrCF,KAAKC,SAASb,SAAS,IAAIc,UAAU,IACpCA,UAAU,EAAG,KCHZN,eAAeO,QFjBqB,OEiBaR,GAEjD,MAAMS,QAAcb,EACdc,QAAYD,EAAMnB,IAAI,CAAEqB,SAAUX,IACxCC,eAAeO,QFnBqB,OEmBaE,EAAIE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AAAC,OAAAD,OAAAC,OAAA,GACD2J,GAAW,CACdC,KAA4BhL,eAAeC,QNXJ,SMWyC,GAChFgL,KAA4BjL,eAAeC,QNVJ,SMUyC,OAgE1EmJ,EAAO3F,OAASiF,IACpBU,EAAO3F,MAAQqC,KAETsD,CAAM,GAGVX,GAAeC,KAClBM,EAAmB,CAACM,EAAK7I,MF8BpBX,eAAmC8D,EAAsBnD,EAAeS,EAAiB8E,GAC/F,IACC,MAAMkF,QAAazK,aAAG,EAAHA,EAAK0K,QACxB,GAAID,EAAM,CACT,MAAM1E,EAhBT,SAA4B0E,GAE3B,OAAOA,aAAA,EAAAA,EAAME,WAAYF,GAAQ,CAAA,CAClC,CAa6DG,CAAmBH,IAAvErH,WAAEA,EAAUmB,WAAEA,EAAUsB,KAAEA,GAAkDE,EAAzCvB,EAAnC2D,EAAAA,OAAApC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ0C,eACX3D,EAAiBlB,EAAYmB,EAAYC,GAI1C/D,EAAM+H,aAAajH,OAAO6B,GAC1B3C,EAAMoF,KAAKtE,OAAOsE,GAGdzC,GAAcmB,GAAcgB,EAAQyC,aACvC9E,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOpE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CErDG0K,CAAoB7B,EAAO8B,QAAS9K,EAAK,CAAEwI,eAAc3C,QAAQ,CAAEmC,cAAcC,iBAAgB,GAI/FD,GAEHgB,EAAO8B,UAGD9B,CAAM"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../../src/constants.ts","../../src/helpers.ts","../../src/fp.ts","../../src/state.ts","../../src/tokens.ts","../../src/webauthn.ts","../../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\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","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\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","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\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","// supported state types are string and object\ntype StateObject = string | Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tif (typeof a === 'string') {\n\t\treturn a === b;\n\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\tif (typeof state === 'string') {\n\t\treturn state;\n\t}\n\treturn { ...state };\n};\n\nconst isEmpty = (state: StateObject): boolean => {\n\tif (!state || typeof state === 'string') {\n\t\treturn !state;\n\t}\n\treturn Object.entries(state).length === 0;\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);\n\t}\n\n\tupdate(newState: T) {\n\t\tlet nextState: T = newState;\n\t\tif (typeof newState === 'object' && typeof this.#state === 'object') {\n\t\t\tnextState = { ...this.#state, ...newState };\n\t\t}\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\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\tif (!isEmpty(this.#state)) {\n\t\t\tcb(clone(this.#state) as T);\n\t\t}\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';\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\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\tstate.sessionToken.update(sessionJwt);\n\t\t\tstate.user.update(user);\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 { 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 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}\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\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 { VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } 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// this sdk can be used in SSR apps\nconst isBrowser = typeof window !== 'undefined';\n\nconst prepareQueryParams = (\n\tqueryParams\n): {\n\t[key: string]: string;\n} => ({\n\t...queryParams,\n\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n});\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 (!isBrowser) {\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<string>('');\n\tconst user = new State<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\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: sessionToken.subscribe,\n\t\tonUserChange: user.subscribe\n\t};\n\n\tif (autoRefresh) {\n\t\twebSdk.logout = (...args: Parameters<CoreSdk['logout']>) => {\n\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t// Make it easier for Descoper to just call logout without parameters if this is dev env and refresh is stored in localStorage\n\t\t\tconst token = args?.shift();\n\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\tconst res = coreSdk.logout(...logoutArgs);\n\t\t\tclearTokens();\n\t\t\treturn res;\n\t\t};\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tconfig.queryParams = prepareQueryParams(config.queryParams);\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\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (req, 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\t// refresh on init is done after afterRequestHook is configured\n\t\twebSdk.refresh();\n\t}\n\n\treturn webSdk;\n};\n"],"names":["getQueryParam","param","Proxy","URLSearchParams","window","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","async","sessionId","sessionStorage","getItem","Date","now","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","entries","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","localStorage","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","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","isBrowser","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","helpers","onSessionTokenChange","onUserChange","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","body","json","authInfo","extractJWTResponse","handleDescopeTokens","refresh"],"mappings":"qOACO,MCSMA,EAAiBC,GAR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AnC4D,EAAAA,OAAArC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ2C,eACX5D,EAAiBlB,EAAYmB,EAAYC,GAI1C/D,EAAMiI,aAAanH,OAAO6B,GAC1B3C,EAAMoF,KAAKtE,OAAOsE,GAGdzC,GAAcmB,GAAcgB,EAAQ0C,aACvC/E,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOpE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CE5CG6K,CACC9B,EAAO+B,QACPjL,EACA,CAAE0I,eAAc7C,QAChB,CAAEoC,cAAaC,iBACf,GAICD,GAEHiB,EAAO+B,UAGD/B,CAAM"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ export declare const authInfo: {
2
+ sessionJwt: string;
3
+ refreshJwt: string;
4
+ cookieDomain: string;
5
+ cookiePath: string;
6
+ cookieExpiration: number;
7
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldSet as t,__classPrivateFieldGet as e,__rest as s}from"tslib";import n from"@descope/core-js-sdk";import{load as a}from"@fingerprintjs/fingerprintjs-pro";import r from"js-cookie";const i=t=>new Proxy(new URLSearchParams(window.location.search),{get:(t,e)=>t.get(e.toString())})[t],o=t=>{const e=a({apiKey:t||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let t=sessionStorage.getItem("vsid");t||(t=i("vsid")),t||(t=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",t);const s=await e,n=await s.get({linkedId:t});sessionStorage.setItem("vrid",n.requestId)}catch(t){global.FB_DEBUG&&console.error(t)}}}};var c,u,l,g,f;const p=t=>"string"==typeof t?t:Object.assign({},t);class h{constructor(e){c.add(this),u.set(this,void 0),l.set(this,{}),g.set(this,0),t(this,u,e,"f")}get current(){return p(e(this,u,"f"))}update(s){let n=s;if("object"==typeof s&&"object"==typeof e(this,u,"f")&&(n=Object.assign(Object.assign({},e(this,u,"f")),s)),!((t,e)=>{if("string"==typeof t)return t===e;const s=t&&Object.getOwnPropertyNames(t)||[],n=e&&Object.getOwnPropertyNames(e)||[];if(s.length!==n.length)return!1;for(let n=0;n<s.length;n+=1){const a=s[n];if(t[a]!==e[a])return!1}return!0})(e(this,u,"f"),n)){const s=e(this,u,"f");t(this,u,n,"f"),Object.freeze(e(this,u,"f")),setTimeout((()=>{Object.values(e(this,l,"f")).forEach((t=>t(p(n),s)))}),0)}}subscribe(s){var n;t(this,g,e(this,g,"f")+1,"f"),e(this,l,"f")[e(this,g,"f")]=s,((n=e(this,u,"f"))&&"string"!=typeof n?0===Object.entries(n).length:!n)||s(p(e(this,u,"f")));const a=e(this,g,"f");return()=>e(this,c,"m",f).call(this,a.toString())}unsubscribeAll(){t(this,l,{},"f")}}u=new WeakMap,l=new WeakMap,g=new WeakMap,c=new WeakSet,f=function(t){!!e(this,l,"f")[t]&&delete e(this,l,"f")[t]};let d=[];function b(t,e,s){const n=function(t){const e=t.split(".");try{if(3===e.length){const e=JSON.parse(window.atob(t.split(".")[1]));if(e.exp)return new Date(1e3*e.exp)}}catch(t){}return null}(e);if(n){let e;for(;e=d.pop();)clearTimeout(e);const a=n.getTime()-2e4-(new Date).getTime(),r=setTimeout((()=>{t(s)}),a);d.push(r)}}function w(t,e,s){!function(t,{cookiePath:e,cookieDomain:s,cookieExpiration:n}){t&&r.set("DS",t,{path:e,domain:s,expires:n,sameSite:"None",secure:!0})}(t,s),function(t){localStorage&&t&&localStorage.setItem("DSR",t)}(e)}function m(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function S(t){const e=function(t){var e;const s=JSON.parse(t);return s.publicKey.challenge=v(s.publicKey.challenge),s.publicKey.user.id=v(s.publicKey.user.id),null===(e=s.publicKey.excludeCredentials)||void 0===e||e.forEach((t=>{t.id=v(t.id)})),s}(t),s=await navigator.credentials.create(e);return n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:O(n.rawId),response:Object.assign(Object.assign({},n.response),{attestationObject:O(n.response.attestationObject),clientDataJSON:O(n.response.clientDataJSON)})}));var n}async function y(t){const e=function(t){var e;const s=JSON.parse(t);return s.publicKey.challenge=v(s.publicKey.challenge),null===(e=s.publicKey.allowCredentials)||void 0===e||e.forEach((t=>{t.id=v(t.id)})),s}(t),s=await navigator.credentials.get(e);return n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:O(n.rawId),response:Object.assign(Object.assign({},n.response),{authenticatorData:O(n.response.authenticatorData),clientDataJSON:O(n.response.clientDataJSON),signature:O(n.response.signature),userHandle:n.response.userHandle?O(n.response.userHandle):void 0})}));var n}function v(t){const e=t.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(e),(t=>t.charCodeAt(0))).buffer}function O(t){return btoa(String.fromCharCode.apply(null,new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var j=t=>{var{autoRefresh:e=!0,persistTokens:a=!0}=t,i=s(t,["autoRefresh","persistTokens"]);o(i.fpKey).get().catch((()=>null));const c=i;let u,l;const g=new h(""),f=new h({});c.hooks={beforeRequest:t=>null==u?void 0:u(t),afterRequest:(t,e)=>null==l?void 0:l(t,e)};const p=n(c),d=Object.assign(Object.assign({},p),{webauthn:(v=p,{async signUp(t,e){const s=await v.webauthn.signUp.start(t,window.location.origin,e),n=await S(s.data.options);return await v.webauthn.signUp.finish(s.data.transactionId,n)},async signIn(t){const e=await v.webauthn.signIn.start(t,window.location.origin),s=await y(e.data.options);return await v.webauthn.signIn.finish(e.data.transactionId,s)},async update(t,e){const s=await v.webauthn.update.start(t,window.location.origin,e),n=await S(s.data.options);return await v.webauthn.update.finish(s.data.transactionId,n)},helpers:{create:S,get:y}}),onSessionTokenChange:g.subscribe,onUserChange:f.subscribe});var v;return e&&(d.logout=(...t)=>{const e=m(),s=[(null==t?void 0:t.shift())||e,...t],n=p.logout(...s);return localStorage&&localStorage.removeItem("DSR"),r.remove("DS"),n}),u=t=>{var e;return t.queryParams=(e=t.queryParams,Object.assign(Object.assign({},e),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!t.token&&a&&(t.token=m()),t},(e||a)&&(l=(t,n)=>{!async function(t,e,n,a){try{const r=await(null==e?void 0:e.json());if(r){const e=function(t){return(null==t?void 0:t.authInfo)||t||{}}(r),{sessionJwt:i,refreshJwt:o,user:c}=e,u=s(e,["sessionJwt","refreshJwt","user"]);a.persistTokens&&w(i,o,u),n.sessionToken.update(i),n.user.update(c),i&&o&&a.autoRefresh&&b(t,i,o)}}catch(t){console.error("Could not set tokens from body",t)}}(d.refresh,n,{sessionToken:g,user:f},{autoRefresh:e,persistTokens:a})}),e&&d.refresh(),d};export{j 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 i from"js-cookie";const r=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],o=e=>{const t=a({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=r("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 c,u,l,g,f;const d=e=>"string"==typeof e?e:Object.assign({},e);class p{constructor(t){c.add(this),u.set(this,void 0),l.set(this,{}),g.set(this,0),e(this,u,t,"f")}get current(){return d(t(this,u,"f"))}update(n){let s=n;if("object"==typeof n&&"object"==typeof t(this,u,"f")&&(s=Object.assign(Object.assign({},t(this,u,"f")),n)),!((e,t)=>{if("string"==typeof e)return 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,u,"f"),s)){const n=t(this,u,"f");e(this,u,s,"f"),Object.freeze(t(this,u,"f")),setTimeout((()=>{Object.values(t(this,l,"f")).forEach((e=>e(d(s),n)))}),0)}}subscribe(n){var s;e(this,g,t(this,g,"f")+1,"f"),t(this,l,"f")[t(this,g,"f")]=n,((s=t(this,u,"f"))&&"string"!=typeof s?0===Object.entries(s).length:!s)||n(d(t(this,u,"f")));const a=t(this,g,"f");return()=>t(this,c,"m",f).call(this,a.toString())}unsubscribeAll(){e(this,l,{},"f")}}u=new WeakMap,l=new WeakMap,g=new WeakMap,c=new WeakSet,f=function(e){!!t(this,l,"f")[e]&&delete t(this,l,"f")[e]};let h=[];function b(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=h.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),a);h.push(i)}}function w(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:s}){e&&i.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=S(n.publicKey.challenge),n.publicKey.user.id=S(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=S(e.id)})),n}(e),n=await navigator.credentials.create(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:O(s.rawId),response:Object.assign(Object.assign({},s.response),{attestationObject:O(s.response.attestationObject),clientDataJSON:O(s.response.clientDataJSON)})}));var s}async function v(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=S(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=S(e.id)})),n}(e),n=await navigator.credentials.get(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:O(s.rawId),response:Object.assign(Object.assign({},s.response),{authenticatorData:O(s.response.authenticatorData),clientDataJSON:O(s.response.clientDataJSON),signature:O(s.response.signature),userHandle:s.response.userHandle?O(s.response.userHandle):void 0})}));var s}function S(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function O(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const j="undefined"!=typeof window;var k=e=>{var{autoRefresh:t=!0,persistTokens:a=!0}=e,r=n(e,["autoRefresh","persistTokens"]);j?o(r.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const c=r;let u,l;const g=new p(""),f=new p({});c.hooks={beforeRequest:e=>null==u?void 0:u(e),afterRequest:(e,t)=>null==l?void 0:l(e,t)};const d=s(c),h=Object.assign(Object.assign({},d),{webauthn:(S=d,{async signUp(e,t){const n=await S.webauthn.signUp.start(e,window.location.origin,t),s=await m(n.data.options);return await S.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await S.webauthn.signIn.start(e,window.location.origin),n=await v(t.data.options);return await S.webauthn.signIn.finish(t.data.transactionId,n)},async update(e,t){const n=await S.webauthn.update.start(e,window.location.origin,t),s=await m(n.data.options);return await S.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:m,get:v}}),onSessionTokenChange:g.subscribe,onUserChange:f.subscribe});var S;return t&&(h.logout=(...e)=>{const t=y(),n=[(null==e?void 0:e.shift())||t,...e],s=d.logout(...n);return localStorage&&localStorage.removeItem("DSR"),i.remove("DS"),s}),u=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!e.token&&a&&(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.4"}),e},(t||a)&&(l=(e,s)=>{!async function(e,t,s,a){try{const i=await(null==t?void 0:t.json());if(i){const t=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:r,refreshJwt:o,user:c}=t,u=n(t,["sessionJwt","refreshJwt","user"]);a.persistTokens&&w(r,o,u),s.sessionToken.update(r),s.user.update(c),r&&o&&a.autoRefresh&&b(e,r,o)}}catch(e){console.error("Could not set tokens from body",e)}}(h.refresh,s,{sessionToken:g,user:f},{autoRefresh:t,persistTokens:a})}),t&&h.refresh(),h};export{k as default};
2
2
  //# sourceMappingURL=index.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/constants.ts","../src/helpers.ts","../src/fp.ts","../src/state.ts","../src/tokens.ts","../src/webauthn.ts","../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\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","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\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","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\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 // 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","// supported state types are string and object\ntype StateObject = string | Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject> (a: T, b: T) => {\n if (typeof a === 'string') {\n return a === b;\n }\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 if (typeof state === 'string') {\n return state;\n }\n return { ...state };\n}\n\nconst isEmpty = (state: StateObject): boolean => {\n if (!state || typeof state === 'string') {\n return !state;\n }\n return Object.entries(state).length === 0;\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 return clone(this.#state);\n\t}\n\n\tupdate(newState: T) {\n\t\tlet nextState: T = newState;\n\t\tif (typeof newState === 'object' && typeof this.#state === 'object') {\n\t\t\tnextState = { ...this.#state , ...newState };\n\t\t}\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) =>\n\t\t\t\t\tcb(clone(nextState) as T, prevState)\n\t\t\t\t);\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\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\tif (!isEmpty(this.#state)) {\n\t\t\tcb(clone(this.#state) as T);\n\t\t}\n\n // return unsubscribe function\n const 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> = (\n\tstate: T,\n\tprevState?: T\n) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\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(sessionJwt: string, refreshJwt: string, cookieParams: Partial<JWTResponse>) {\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(refreshFn: RefreshFn, res: Response, state: SdkState, options: TokensOptions) {\n\ttry {\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\t\t\t\n\t\t\t// Update state\n\t\t\tstate.sessionToken.update(sessionJwt);\n\t\t\tstate.user.update(user);\n\t\t\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 { 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(startResponse.data.transactionId, createResponse);\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(startResponse.data.transactionId, getResponse);\n\t\treturn finishResponse;\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(identifier, window.location.origin, token);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(startResponse.data.transactionId, createResponse);\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}\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(createOptions)) 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\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & { response: AuthenticatorAttestationResponse };\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 & { response: AuthenticatorAssertionResponse };\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 ? encodeBase64Url(credential.response.userHandle) : 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 { VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } 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\nconst prepareQueryParams = (\n\tqueryParams\n): {\n\t[key: string]: string;\n} => ({\n\t...queryParams,\n\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n});\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] & TokensOptions & {\n\t// FingerprintJS API key\n\tfpKey?: string;\n};\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\tfp(args.fpKey)\n\t\t.get()\n\t\t.catch(() => null);\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<string>('');\n\tconst user = new State<UserResponse | {}>({});\n\t\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\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: sessionToken.subscribe,\n\t\tonUserChange: user.subscribe\n\t};\n\n\tif (autoRefresh) {\n\t\twebSdk.logout = (...args: Parameters<CoreSdk['logout']>) => {\n\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t// Make it easier for Descoper to just call logout without parameters if this is dev env and refresh is stored in localStorage\n\t\t\tconst token = args?.shift();\n\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\tconst res = coreSdk.logout(...logoutArgs);\n\t\t\tclearTokens();\n\t\t\treturn res;\n\t\t};\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tconfig.queryParams = prepareQueryParams(config.queryParams);\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\treturn config;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (req, res) => {\n\t\t\thandleDescopeTokens(webSdk.refresh, res, { sessionToken, user }, { autoRefresh, persistTokens });\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\t// refresh on init is done after afterRequestHook is configured\n\t\twebSdk.refresh();\n\t}\n\n\treturn webSdk;\n};\n"],"names":["getQueryParam","param","Proxy","URLSearchParams","window","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","async","sessionId","sessionStorage","getItem","Date","now","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","entries","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","localStorage","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","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","index","autoRefresh","persistTokens","args","__rest","catch","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","helpers","onSessionTokenChange","onUserChange","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","body","json","authInfo","extractJWTResponse","handleDescopeTokens","refresh"],"mappings":"4MACO,MCSMA,EAAiBC,GARd,IAAIC,MAAM,IAAIC,gBAAgBC,OAAOC,SAASC,QAAS,CACrEC,IAAK,CAACC,EAAcC,IAASD,EAAaD,IAAIE,EAAKC,cAUtCT,GCRTU,EAAMC,IACX,MAAMC,EAASC,EAAK,CAAEC,OAAQH,GFLT,yBEOrB,MAAO,CACNL,IAAKS,UACJ,IACC,IAAIC,EAAYC,eAAeC,QFRK,QES/BF,IACJA,EAAYjB,EFVuB,SEa/BiB,IACJA,GDGHG,KAAKC,MAAMX,SAAS,IACpBY,KAAKC,SAASb,SAAS,IAAIc,UAAU,GACrCF,KAAKC,SAASb,SAAS,IAAIc,UAAU,IACpCA,UAAU,EAAG,KCHZN,eAAeO,QFjBqB,OEiBaR,GAEjD,MAAMS,QAAcb,EACdc,QAAYD,EAAMnB,IAAI,CAAEqB,SAAUX,IACxCC,eAAeO,QFnBqB,OEmBaE,EAAIE,UAOrD,CANC,MAAOC,GAEJC,OAAOC,UAEVC,QAAQC,MAAMJ,EAEf,GAEF,gBC5BF,MAsBMK,EAASC,GACQ,iBAAVA,EACFA,EAETC,OAAAC,OAAA,CAAA,EAAYF,GAUd,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,cACD,OAAOb,EAAMc,EAAAL,KAAIF,EAAA,KACnB,CAEDQ,OAAOC,GACN,IAAIC,EAAeD,EAInB,GAHwB,iB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nC4D,EAAArC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ2C,eACX5D,EAAiBlB,EAAYmB,EAAYC,GAI1C/D,EAAMgI,aAAalH,OAAO6B,GAC1B3C,EAAMoF,KAAKtE,OAAOsE,GAGdzC,GAAcmB,GAAcgB,EAAQ0C,aACvC/E,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOpE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CErDG2K,CAAoB7B,EAAO8B,QAAS/K,EAAK,CAAEyI,eAAc5C,QAAQ,CAAEoC,cAAcC,iBAAgB,GAI/FD,GAEHgB,EAAO8B,UAGD9B,CAAM"}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/constants.ts","../src/helpers.ts","../src/fp.ts","../src/state.ts","../src/tokens.ts","../src/webauthn.ts","../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\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","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\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","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\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","// supported state types are string and object\ntype StateObject = string | Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tif (typeof a === 'string') {\n\t\treturn a === b;\n\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\tif (typeof state === 'string') {\n\t\treturn state;\n\t}\n\treturn { ...state };\n};\n\nconst isEmpty = (state: StateObject): boolean => {\n\tif (!state || typeof state === 'string') {\n\t\treturn !state;\n\t}\n\treturn Object.entries(state).length === 0;\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);\n\t}\n\n\tupdate(newState: T) {\n\t\tlet nextState: T = newState;\n\t\tif (typeof newState === 'object' && typeof this.#state === 'object') {\n\t\t\tnextState = { ...this.#state, ...newState };\n\t\t}\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\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\tif (!isEmpty(this.#state)) {\n\t\t\tcb(clone(this.#state) as T);\n\t\t}\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';\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\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\tstate.sessionToken.update(sessionJwt);\n\t\t\tstate.user.update(user);\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 { 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 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}\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\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 { VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } 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// this sdk can be used in SSR apps\nconst isBrowser = typeof window !== 'undefined';\n\nconst prepareQueryParams = (\n\tqueryParams\n): {\n\t[key: string]: string;\n} => ({\n\t...queryParams,\n\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n});\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 (!isBrowser) {\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<string>('');\n\tconst user = new State<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\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: sessionToken.subscribe,\n\t\tonUserChange: user.subscribe\n\t};\n\n\tif (autoRefresh) {\n\t\twebSdk.logout = (...args: Parameters<CoreSdk['logout']>) => {\n\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t// Make it easier for Descoper to just call logout without parameters if this is dev env and refresh is stored in localStorage\n\t\t\tconst token = args?.shift();\n\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\tconst res = coreSdk.logout(...logoutArgs);\n\t\t\tclearTokens();\n\t\t\treturn res;\n\t\t};\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tconfig.queryParams = prepareQueryParams(config.queryParams);\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\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (req, 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\t// refresh on init is done after afterRequestHook is configured\n\t\twebSdk.refresh();\n\t}\n\n\treturn webSdk;\n};\n"],"names":["getQueryParam","param","Proxy","URLSearchParams","window","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","async","sessionId","sessionStorage","getItem","Date","now","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","entries","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","localStorage","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","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","isBrowser","index","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","helpers","onSessionTokenChange","onUserChange","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","body","json","authInfo","extractJWTResponse","handleDescopeTokens","refresh"],"mappings":"4MACO,MCSMA,EAAiBC,GARd,IAAIC,MAAM,IAAIC,gBAAgBC,OAAOC,SAASC,QAAS,CACrEC,IAAK,CAACC,EAAcC,IAASD,EAAaD,IAAIE,EAAKC,cAUtCT,GCRTU,EAAMC,IACX,MAAMC,EAASC,EAAK,CAAEC,OAAQH,GFLT,yBEOrB,MAAO,CACNL,IAAKS,UACJ,IACC,IAAIC,EAAYC,eAAeC,QFRK,QES/BF,IACJA,EAAYjB,EFVuB,SEa/BiB,IACJA,GDGHG,KAAKC,MAAMX,SAAS,IACpBY,KAAKC,SAASb,SAAS,IAAIc,UAAU,GACrCF,KAAKC,SAASb,SAAS,IAAIc,UAAU,IACpCA,UAAU,EAAG,KCHZN,eAAeO,QFjBqB,OEiBaR,GAEjD,MAAMS,QAAcb,EACdc,QAAYD,EAAMnB,IAAI,CAAEqB,SAAUX,IACxCC,eAAeO,QFnBq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C,OAAA,GACD8J,GAAW,CACdC,KAA4BnL,eAAeC,QNhBJ,SMgByC,GAChFmL,KAA4BpL,eAAeC,QNfJ,SMeyC,OAwE1EsJ,EAAO9F,OAASmF,IACpBW,EAAO9F,MAAQqC,KAEhByD,EAAO8B,QACHlK,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAmI,EAAO8B,SAAO,CACjB,qBAAsB,SACtB,wBAAyB,kBAEnB9B,CAAM,GAGVZ,GAAeC,KAClBO,EAAmB,CAACM,EAAKhJ,MFgBpBX,eACN8D,EACAnD,EACAS,EACA8E,GAEA,IACC,MAAMsF,QAAa7K,aAAG,EAAHA,EAAK8K,QACxB,GAAID,EAAM,CACT,MAAM9E,EArBT,SAA4B8E,GAE3B,OAAOA,aAAA,EAAAA,EAAME,WAAYF,GAAS,CAAA,CACnC,CAkB6DG,CAAmBH,IAAvEzH,WAAEA,EAAUmB,WAAEA,EAAUsB,KAAEA,GAAkDE,EAAzCvB,EAAnC6D,EAAAtC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ4C,eACX7D,EAAiBlB,EAAYmB,EAAYC,GAI1C/D,EAAMkI,aAAapH,OAAO6B,GAC1B3C,EAAMoF,KAAKtE,OAAOsE,GAGdzC,GAAcmB,GAAcgB,EAAQ2C,aACvChF,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOpE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CE5CG8K,CACC9B,EAAO+B,QACPlL,EACA,CAAE2I,eAAc9C,QAChB,CAAEqC,cAAaC,iBACf,GAICD,GAEHiB,EAAO+B,UAGD/B,CAAM"}
package/dist/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).descopeSdk=t()}(this,(function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}function n(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function r(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n}function o(e){this.message=e}o.prototype=new Error,o.prototype.name="InvalidCharacterError";var i="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new o("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,i=0,a=0,s="";r=t.charAt(a++);~r&&(n=i%4?64*n+r:r,i++%4)?s+=String.fromCharCode(255&n>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s};function a(e){this.message=e}function s(e,t){if("string"!=typeof e)throw new a("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(i(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return i(t)}}(e.split(".")[n]))}catch(e){throw new a("Invalid token specified: "+e.message)}}a.prototype=new Error,a.prototype.name="InvalidTokenError";var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},u="__lodash_hash_undefined__",l="[object Function]",p="[object GeneratorFunction]",d=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,f=/^\w*$/,h=/^\./,g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,v=/\\(\\)?/g,y=/^\[object .+?Constructor\]$/,b="object"==typeof c&&c&&c.Object===Object&&c,m="object"==typeof self&&self&&self.Object===Object&&self,w=b||m||Function("return this")();var O,j=Array.prototype,k=Function.prototype,I=Object.prototype,_=w["__core-js_shared__"],S=(O=/[^.]+$/.exec(_&&_.keys&&_.keys.IE_PROTO||""))?"Symbol(src)_1."+O:"",x=k.toString,P=I.hasOwnProperty,U=I.toString,R=RegExp("^"+x.call(P).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),E=w.Symbol,C=j.splice,T=z(w,"Map"),D=z(Object,"create"),q=E?E.prototype:void 0,A=q?q.toString:void 0;function $(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function J(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function M(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function N(e,t){for(var n,r,o=e.length;o--;)if((n=e[o][0])===(r=t)||n!=n&&r!=r)return o;return-1}function K(e,t){var n;t=function(e,t){if(G(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||V(e))return!0;return f.test(e)||!d.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:G(n=t)?n:F(n);for(var r=0,o=t.length;null!=e&&r<o;)e=e[H(t[r++])];return r&&r==o?e:void 0}function L(e){if(!Z(e)||(t=e,S&&S in t))return!1;var t,n=function(e){var t=Z(e)?U.call(e):"";return t==l||t==p}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?R:y;return n.test(function(e){if(null!=e){try{return x.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function B(e,t){var n,r,o=e.__data__;return("string"==(r=typeof(n=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function z(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return L(n)?n:void 0}$.prototype.clear=function(){this.__data__=D?D(null):{}},$.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},$.prototype.get=function(e){var t=this.__data__;if(D){var n=t[e];return n===u?void 0:n}return P.call(t,e)?t[e]:void 0},$.prototype.has=function(e){var t=this.__data__;return D?void 0!==t[e]:P.call(t,e)},$.prototype.set=function(e,t){return this.__data__[e]=D&&void 0===t?u:t,this},J.prototype.clear=function(){this.__data__=[]},J.prototype.delete=function(e){var t=this.__data__,n=N(t,e);return!(n<0)&&(n==t.length-1?t.pop():C.call(t,n,1),!0)},J.prototype.get=function(e){var t=this.__data__,n=N(t,e);return n<0?void 0:t[n][1]},J.prototype.has=function(e){return N(this.__data__,e)>-1},J.prototype.set=function(e,t){var n=this.__data__,r=N(n,e);return r<0?n.push([e,t]):n[r][1]=t,this},M.prototype.clear=function(){this.__data__={hash:new $,map:new(T||J),string:new $}},M.prototype.delete=function(e){return B(this,e).delete(e)},M.prototype.get=function(e){return B(this,e).get(e)},M.prototype.has=function(e){return B(this,e).has(e)},M.prototype.set=function(e,t){return B(this,e).set(e,t),this};var F=W((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(V(e))return A?A.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return h.test(e)&&n.push(""),e.replace(g,(function(e,t,r,o){n.push(r?o.replace(v,"$1"):t||e)})),n}));function H(e){if("string"==typeof e||V(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function W(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=e.apply(this,r);return n.cache=i.set(o,a),a};return n.cache=new(W.Cache||M),n}W.Cache=M;var G=Array.isArray;function Z(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function V(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==U.call(e)}var Q,X=function(e,t,n){var r=null==e?void 0:K(e,t);return void 0===r?n:r},Y="/v1/auth/accesskey/exchange",ee="/v1/auth/otp/verify",te="/v1/auth/otp/signin",ne="/v1/auth/otp/signup",re={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},oe="/v1/auth/otp/signup-in",ie="/v1/auth/magiclink/verify",ae="/v1/auth/magiclink/signin",se="/v1/auth/magiclink/signup",ce="/v1/auth/magiclink/pending-session",ue={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/email"},le="/v1/auth/magiclink/signup-in",pe="/v1/auth/oauth/authorize",de="/v1/auth/saml/authorize",fe="/v1/auth/totp/verify",he="/v1/auth/totp/signup",ge="/v1/user/totp/update",ve={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},ye={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},be={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},me="/v1/flow/start",we="/v1/flow/next";!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(Q||(Q={}));const Oe=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}},je=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,r])=>(e[n]=r,e)),e),e}),{})),ke=e=>void 0===e?void 0:JSON.stringify(e),Ie=(e,t="")=>{let n=e;return""!==t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},_e=({baseUrl:e,projectId:t,baseConfig:n,logger:r,hooks:o,cookiePolicy:i})=>{const a=((e,t)=>{const n=t||fetch;if(!n)throw new Error("fetch is not defined");return e?async(...t)=>{e.log((e=>Oe().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const r=await n(...t);return e[r.ok?"log":"error"](await(async e=>{const t=await e.text();return e.text=()=>Promise.resolve(t),e.json=()=>Promise.resolve(JSON.parse(t)),Oe().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(r)),r}:n})(r),s=async r=>{const s=(null==o?void 0:o.beforeRequest)?o.beforeRequest(r):r,{path:c,body:u,headers:l,queryParams:p,method:d,token:f}=s,h=await a((({path:e,baseUrl:t,queryParams:n})=>{const r=new URL(e,t);return n&&(r.search=new URLSearchParams(n).toString()),r})({path:c,baseUrl:e,queryParams:p}),{headers:je(Ie(t,f),(null==n?void 0:n.baseHeaders)||{},l),method:d,body:ke(u),credentials:i||"include"});return(null==o?void 0:o.afterRequest)&&o.afterRequest(r,null==h?void 0:h.clone()),h};return{get:(e,{headers:t,queryParams:n,token:r}={})=>s({path:e,headers:t,queryParams:n,body:void 0,method:Q.get,token:r}),post:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.post,token:o}),put:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.put,token:o}),delete:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.delete,token:o})}};function Se(e){const{exp:t}=Ce(e);return(new Date).getTime()/1e3>t}function xe(e,t){return Ee(e,t,"permissions")}function Pe(e,t){return Ee(e,t,"roles")}const Ue=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function Re(e){const t=await e,n={code:t.status,ok:t.ok,response:t},r=await t.json();return t.ok?n.data=r:n.error=r,n}function Ee(e,t,n){var r;let o=Ce(e);t&&(o=null===(r=o.tenants)||void 0===r?void 0:r[t]);const i=o[n];return Array.isArray(i)?i:[]}function Ce(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return s(e)}const Te=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),De=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),qe=e=>t=>e.test(t),Ae=qe(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),$e=qe(/^\+[1-9]{1}[0-9]{3,14}$/),Je=Te(Ae,'"{val}" is not a valid email'),Me=Te($e,'"{val}" is not a valid phone number'),Ne=Te((1,e=>e.length>=1),"Minimum length is 1");const Ke=Te((e=>"string"==typeof e),"Input is not a string"),Le=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>De(...e).validate(n[t]))),t(...n)),Be=e=>[Ke(`"${e}" must be a string`),Ne(`"${e}" must not be empty`)],ze=e=>[Ke(`"${e}" must be a string`),Je()],Fe=e=>[Ke(`"${e}" must be a string`),Me()],He=Le(Be("accessKey")),We=e=>({exchange:He((t=>Re(e.get(Y,{token:t}))))});var Ge,Ze,Ve,Qe,Xe;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(Ge||(Ge={})),function(e){e.email="email",e.sms="sms",e.whatsapp="whatsapp"}(Ze||(Ze={})),function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Ve||(Ve={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify"}(Qe||(Qe={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify",e.updatePhone="updatePhone"}(Xe||(Xe={}));const Ye=Be("identifier"),et=Le(Ye,Be("code")),tt=Le(Ye),nt=Le(Ye,Fe("phone")),rt=Le(Ye,ze("email")),ot=e=>({verify:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:et(((t,r)=>Re(e.post(Ue(ee,n),{code:r,externalId:t}))))})),{}),signIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tt((t=>Re(e.post(Ue(te,n),{externalId:t}))))})),{}),signUp:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tt(((t,r)=>Re(e.post(Ue(ne,n),{externalId:t,user:r}))))})),{}),signUpOrIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tt((t=>Re(e.post(Ue(oe,n),{externalId:t}))))})),{}),update:{email:rt(((t,n,r)=>Re(e.post(re.email,{externalId:t,email:n},{token:r})))),phone:Object.keys(Ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:nt(((t,r,o)=>Re(e.post(Ue(re.phone,n),{externalId:t,phone:r},{token:o}))))})),{})}}),it=Be("identifier"),at=Be("uri"),st=Le(Be("token")),ct=Le(it,at),ut=Le(Be("pendingRef")),lt=Le(it,Fe("phone"),at),pt=Le(it,ze("email"),at),dt=e=>({verify:st((t=>Re(e.post(ie,{token:t})))),signIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(ae,n),{externalId:t,URI:r,crossDevice:!0}))))})),{}),signUpOrIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(le,n),{externalId:t,URI:r,crossDevice:!0}))))})),{}),signUp:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r,o)=>Re(e.post(Ue(se,n),{externalId:t,URI:r,user:o,crossDevice:!0}))))})),{}),waitForSession:ut(((t,n)=>new Promise((r=>{const{pollingIntervalMs:o,timeoutMs:i}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||6e5,6e5)}))(n);let a;const s=setInterval((async()=>{const n=await e.post(ce,{pendingRef:t});n.ok&&(clearInterval(s),a&&clearTimeout(a),r(Re(Promise.resolve(n))))}),o);a=setTimeout((()=>{r({error:{message:`Session polling timeout exceeded: ${i}ms`,code:"0"},ok:!1}),clearInterval(s)}),i)})))),update:{email:pt(((t,n,r,o)=>Re(e.post(ue.email,{externalId:t,email:n,URI:r,crossDevice:!0},{token:o})))),phone:Object.keys(Ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:lt(((t,r,o,i)=>Re(e.post(Ue(ue.phone,n),{externalId:t,phone:r,URI:o,crossDevice:!0},{token:i}))))})),{})}}),ft=e=>({verify:st((t=>Re(e.post(ie,{token:t})))),signIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(ae,n),{externalId:t,URI:r}))))})),{}),signUp:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r,o)=>Re(e.post(Ue(se,n),{externalId:t,URI:r,user:o}))))})),{}),signUpOrIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(le,n),{externalId:t,URI:r}))))})),{}),update:{email:pt(((t,n,r,o)=>Re(e.post(ue.email,{externalId:t,email:n,URI:r},{token:o})))),phone:Object.keys(Ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:lt(((t,r,o,i)=>Re(e.post(Ue(ue.phone,n),{externalId:t,phone:r,URI:o},{token:i}))))})),{})},crossDevice:dt(e)}),ht=Le(Be("code")),gt=e=>({exchange:ht((t=>Re(e.get("/v1/auth/exchange",{queryParams:{code:t}}))))});var vt;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple"}(vt||(vt={}));const yt=e=>Object.assign({start:Object.keys(vt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:async(t,{redirect:r=!1}={})=>{const o=await e.get(pe,{queryParams:Object.assign({provider:n},t&&{redirectURL:t})});if(!r||!o.ok)return Re(Promise.resolve(o));const{url:i}=await o.json();window.location.href=i}})),{})},gt(e)),bt=Le(Be("flowId")),mt=Le(Be("executionId"),Be("stepId"),Be("interactionId")),wt=e=>({start:bt((t=>Re(e.post(me,{flowId:t})))),next:mt(((t,n,r,o)=>Re(e.post(we,{executionId:t,stepId:n,interactionId:r,input:o}))))}),Ot=Le(Be("tenant")),jt=e=>Object.assign({start:Ot((async(t,n,{redirect:r=!1}={})=>{const o=await e.get(de,{queryParams:{tenant:t,redirectURL:n}});if(!r||!o.ok)return Re(Promise.resolve(o));const{url:i}=await o.json();window.location.href=i}))},gt(e)),kt=Be("identifier"),It=Le(kt,Be("code")),_t=Le(kt),St=Le(kt),xt=e=>({signUp:_t(((t,n)=>Re(e.post(he,{externalId:t,user:n})))),verify:It(((t,n)=>Re(e.post(fe,{externalId:t,code:n})))),update:St(((t,n)=>Re(e.post(ge,{externalId:t},{token:n}))))}),Pt=Be("identifier"),Ut=Be("origin"),Rt=Le(Pt,Ut,Be("name")),Et=Le(Pt,Ut),Ct=Le(Pt,Ut,Be("token")),Tt=Le(Be("transactionId"),Be("response")),Dt=e=>({signUp:{start:Rt(((t,n,r)=>Re(e.post(ve.start,{user:{externalId:t,name:r},origin:n})))),finish:Tt(((t,n)=>Re(e.post(ve.finish,{transactionId:t,response:n}))))},signIn:{start:Et(((t,n)=>Re(e.post(ye.start,{externalId:t,origin:n})))),finish:Tt(((t,n)=>Re(e.post(ye.finish,{transactionId:t,response:n}))))},update:{start:Ct(((t,n,r)=>Re(e.post(be.start,{externalId:t,origin:n},{token:r})))),finish:Tt(((t,n)=>Re(e.post(be.finish,{transactionId:t,response:n}))))}}),qt=Le(Be("token"));var At;const $t=Le([("projectId",At=Be("projectId"),Te(((e,t)=>e=>De(...t).validate(X(e,"projectId")))(0,At))())])((({projectId:e,logger:t,baseUrl:n,hooks:r,cookiePolicy:o})=>{return i=_e({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:r,cookiePolicy:o}),{accessKey:We(i),otp:ot(i),magicLink:ft(i),oauth:yt(i),saml:jt(i),totp:xt(i),webauthn:Dt(i),flow:wt(i),refresh:e=>Re(i.get("/v1/auth/refresh",{token:e})),logout:e=>Re(i.get("/v1/auth/logoutall",{token:e})),me:e=>Re(i.get("/v1/auth/me",{token:e})),isJwtExpired:qt(Se),getJwtPermissions:qt(xe),getJwtRoles:qt(Pe),httpClient:i};var i}));$t.DeliveryMethods=Ze;const Jt="vsid",Mt="vrid";function Nt(e,t,n){return void 0===n&&(n=0),t(n).catch((function(r){if(n>=e.maxRetries||!e.shouldRetry(r))throw r;var o,i,a,s,c=(o=e.baseDelay,i=e.maxDelay,a=e.baseDelay*Math.pow(2,n),Math.max(o,Math.min(i,a)));return(s=c,new Promise((function(e){return setTimeout(e,s)}))).then((function(){return Nt(e,t,n+1)}))}))}var Kt="Failed to load the JS script of the agent";function Lt(n){var r,o=n.scriptUrlPattern,i=n.token,a=n.apiKey,s=void 0===a?i:a,c=t(n,["scriptUrlPattern","token","apiKey"]),u=(r=n,"scriptUrlPattern",Object.prototype.hasOwnProperty.call(r,"scriptUrlPattern")?o:void 0),l=[];return Promise.resolve().then((function(){if(!s||"string"!=typeof s)throw new Error("API key required");return Nt({maxRetries:5,baseDelay:100,maxDelay:3e3,shouldRetry:function(e){return!(e instanceof Error&&"Blocked by CSP"===e.message)}},(function(){var e,t=new Date,n=function(){return l.push({startedAt:t,finishedAt:new Date})},r=function(e,t,n,r){var o,i=document,a="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),r=t.blockedURI;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(o=t,c())};i.addEventListener(a,s);var c=function(){return i.removeEventListener(a,s)};return Promise.resolve().then(t).then((function(e){return c(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(c(),o)return function(){throw new Error("Blocked by CSP")}();throw e}))}))}(e=function(e,t){void 0===t&&(t="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js");var n=encodeURIComponent;return t.replace(/<[^<>]+>/g,(function(t){return"<version>"===t?"3":"<apiKey>"===t?n(e):"<loaderVersion>"===t?n("3.7.1"):t}))}(s,u),(function(){return function(e){return new Promise((function(t,n){var r=document.createElement("script"),o=function(){var e;return null===(e=r.parentNode)||void 0===e?void 0:e.removeChild(r)},i=document.head||document.getElementsByTagName("head")[0];r.onload=function(){o(),t()},r.onerror=function(){o(),n(new Error(Kt))},r.async=!0,r.src=e,i.appendChild(r)}))}(e)}));return r.then(n,n),r}))})).then((function(){var t=window,n="__fpjs_p_l_b",r=t[n];if(function(e,t){var n,r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(t,n),"function"!=typeof(null==r?void 0:r.load))throw new Error(Kt);return r.load(e(e({},c),{ldi:{attempts:l}}))}))}const Bt=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],zt=e=>{const t=Lt({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem(Jt);e||(e=Bt(Jt)),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem(Jt,e);const n=await t,r=await n.get({linkedId:e});sessionStorage.setItem(Mt,r.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var Ft,Ht,Wt,Gt,Zt;const Vt=e=>"string"==typeof e?e:Object.assign({},e);class Qt{constructor(e){Ft.add(this),Ht.set(this,void 0),Wt.set(this,{}),Gt.set(this,0),r(this,Ht,e,"f")}get current(){return Vt(n(this,Ht,"f"))}update(e){let t=e;if("object"==typeof e&&"object"==typeof n(this,Ht,"f")&&(t=Object.assign(Object.assign({},n(this,Ht,"f")),e)),!((e,t)=>{if("string"==typeof e)return e===t;const n=e&&Object.getOwnPropertyNames(e)||[],r=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==r.length)return!1;for(let r=0;r<n.length;r+=1){const o=n[r];if(e[o]!==t[o])return!1}return!0})(n(this,Ht,"f"),t)){const e=n(this,Ht,"f");r(this,Ht,t,"f"),Object.freeze(n(this,Ht,"f")),setTimeout((()=>{Object.values(n(this,Wt,"f")).forEach((n=>n(Vt(t),e)))}),0)}}subscribe(e){var t;r(this,Gt,n(this,Gt,"f")+1,"f"),n(this,Wt,"f")[n(this,Gt,"f")]=e,((t=n(this,Ht,"f"))&&"string"!=typeof t?0===Object.entries(t).length:!t)||e(Vt(n(this,Ht,"f")));const o=n(this,Gt,"f");return()=>n(this,Ft,"m",Zt).call(this,o.toString())}unsubscribeAll(){r(this,Wt,{},"f")}}
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).descopeSdk=t()}(this,(function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}function n(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function r(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n}function o(e){this.message=e}o.prototype=new Error,o.prototype.name="InvalidCharacterError";var i="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new o("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,i=0,a=0,s="";r=t.charAt(a++);~r&&(n=i%4?64*n+r:r,i++%4)?s+=String.fromCharCode(255&n>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s};function a(e){this.message=e}function s(e,t){if("string"!=typeof e)throw new a("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(i(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return i(t)}}(e.split(".")[n]))}catch(e){throw new a("Invalid token specified: "+e.message)}}a.prototype=new Error,a.prototype.name="InvalidTokenError";var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},u="__lodash_hash_undefined__",l="[object Function]",p="[object GeneratorFunction]",d=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,f=/^\w*$/,h=/^\./,g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,v=/\\(\\)?/g,y=/^\[object .+?Constructor\]$/,b="object"==typeof c&&c&&c.Object===Object&&c,m="object"==typeof self&&self&&self.Object===Object&&self,w=b||m||Function("return this")();var O,j=Array.prototype,k=Function.prototype,I=Object.prototype,_=w["__core-js_shared__"],x=(O=/[^.]+$/.exec(_&&_.keys&&_.keys.IE_PROTO||""))?"Symbol(src)_1."+O:"",S=k.toString,P=I.hasOwnProperty,U=I.toString,R=RegExp("^"+S.call(P).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),E=w.Symbol,C=j.splice,T=F(w,"Map"),D=F(Object,"create"),q=E?E.prototype:void 0,A=q?q.toString:void 0;function $(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function J(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function M(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function N(e,t){for(var n,r,o=e.length;o--;)if((n=e[o][0])===(r=t)||n!=n&&r!=r)return o;return-1}function K(e,t){var n;t=function(e,t){if(G(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||V(e))return!0;return f.test(e)||!d.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:G(n=t)?n:z(n);for(var r=0,o=t.length;null!=e&&r<o;)e=e[H(t[r++])];return r&&r==o?e:void 0}function L(e){if(!Z(e)||(t=e,x&&x in t))return!1;var t,n=function(e){var t=Z(e)?U.call(e):"";return t==l||t==p}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?R:y;return n.test(function(e){if(null!=e){try{return S.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function B(e,t){var n,r,o=e.__data__;return("string"==(r=typeof(n=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function F(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return L(n)?n:void 0}$.prototype.clear=function(){this.__data__=D?D(null):{}},$.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},$.prototype.get=function(e){var t=this.__data__;if(D){var n=t[e];return n===u?void 0:n}return P.call(t,e)?t[e]:void 0},$.prototype.has=function(e){var t=this.__data__;return D?void 0!==t[e]:P.call(t,e)},$.prototype.set=function(e,t){return this.__data__[e]=D&&void 0===t?u:t,this},J.prototype.clear=function(){this.__data__=[]},J.prototype.delete=function(e){var t=this.__data__,n=N(t,e);return!(n<0)&&(n==t.length-1?t.pop():C.call(t,n,1),!0)},J.prototype.get=function(e){var t=this.__data__,n=N(t,e);return n<0?void 0:t[n][1]},J.prototype.has=function(e){return N(this.__data__,e)>-1},J.prototype.set=function(e,t){var n=this.__data__,r=N(n,e);return r<0?n.push([e,t]):n[r][1]=t,this},M.prototype.clear=function(){this.__data__={hash:new $,map:new(T||J),string:new $}},M.prototype.delete=function(e){return B(this,e).delete(e)},M.prototype.get=function(e){return B(this,e).get(e)},M.prototype.has=function(e){return B(this,e).has(e)},M.prototype.set=function(e,t){return B(this,e).set(e,t),this};var z=W((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(V(e))return A?A.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return h.test(e)&&n.push(""),e.replace(g,(function(e,t,r,o){n.push(r?o.replace(v,"$1"):t||e)})),n}));function H(e){if("string"==typeof e||V(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function W(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=e.apply(this,r);return n.cache=i.set(o,a),a};return n.cache=new(W.Cache||M),n}W.Cache=M;var G=Array.isArray;function Z(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function V(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==U.call(e)}var Q,X=function(e,t,n){var r=null==e?void 0:K(e,t);return void 0===r?n:r},Y="/v1/auth/accesskey/exchange",ee="/v1/auth/otp/verify",te="/v1/auth/otp/signin",ne="/v1/auth/otp/signup",re={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},oe="/v1/auth/otp/signup-in",ie="/v1/auth/magiclink/verify",ae="/v1/auth/magiclink/signin",se="/v1/auth/magiclink/signup",ce="/v1/auth/magiclink/pending-session",ue={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/email"},le="/v1/auth/magiclink/signup-in",pe="/v1/auth/oauth/authorize",de="/v1/auth/saml/authorize",fe="/v1/auth/totp/verify",he="/v1/auth/totp/signup",ge="/v1/user/totp/update",ve={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},ye={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},be={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},me="/v1/flow/start",we="/v1/flow/next";!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(Q||(Q={}));const Oe=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}},je=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,r])=>(e[n]=r,e)),e),e}),{})),ke=e=>void 0===e?void 0:JSON.stringify(e),Ie=(e,t="")=>{let n=e;return""!==t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},_e=({baseUrl:e,projectId:t,baseConfig:n,logger:r,hooks:o,cookiePolicy:i})=>{const a=((e,t)=>{const n=t||fetch;if(!n)throw new Error("fetch is not defined");return e?async(...t)=>{e.log((e=>Oe().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const r=await n(...t);return e[r.ok?"log":"error"](await(async e=>{const t=await e.text();return e.text=()=>Promise.resolve(t),e.json=()=>Promise.resolve(JSON.parse(t)),Oe().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(r)),r}:n})(r),s=async r=>{const s=(null==o?void 0:o.beforeRequest)?o.beforeRequest(r):r,{path:c,body:u,headers:l,queryParams:p,method:d,token:f}=s,h=await a((({path:e,baseUrl:t,queryParams:n})=>{const r=new URL(e,t);return n&&(r.search=new URLSearchParams(n).toString()),r})({path:c,baseUrl:e,queryParams:p}),{headers:je(Ie(t,f),(null==n?void 0:n.baseHeaders)||{},l),method:d,body:ke(u),credentials:i||"include"});return(null==o?void 0:o.afterRequest)&&o.afterRequest(r,null==h?void 0:h.clone()),h};return{get:(e,{headers:t,queryParams:n,token:r}={})=>s({path:e,headers:t,queryParams:n,body:void 0,method:Q.get,token:r}),post:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.post,token:o}),put:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.put,token:o}),delete:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.delete,token:o})}};function xe(e){const{exp:t}=Ce(e);return(new Date).getTime()/1e3>t}function Se(e,t){return Ee(e,t,"permissions")}function Pe(e,t){return Ee(e,t,"roles")}const Ue=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function Re(e){const t=await e,n={code:t.status,ok:t.ok,response:t},r=await t.json();return t.ok?n.data=r:n.error=r,n}function Ee(e,t,n){var r;let o=Ce(e);t&&(o=null===(r=o.tenants)||void 0===r?void 0:r[t]);const i=o[n];return Array.isArray(i)?i:[]}function Ce(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return s(e)}const Te=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),De=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),qe=e=>t=>e.test(t),Ae=qe(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),$e=qe(/^\+[1-9]{1}[0-9]{3,14}$/),Je=Te(Ae,'"{val}" is not a valid email'),Me=Te($e,'"{val}" is not a valid phone number'),Ne=Te((1,e=>e.length>=1),"Minimum length is 1");const Ke=Te((e=>"string"==typeof e),"Input is not a string"),Le=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>De(...e).validate(n[t]))),t(...n)),Be=e=>[Ke(`"${e}" must be a string`),Ne(`"${e}" must not be empty`)],Fe=e=>[Ke(`"${e}" must be a string`),Je()],ze=e=>[Ke(`"${e}" must be a string`),Me()],He=Le(Be("accessKey")),We=e=>({exchange:He((t=>Re(e.get(Y,{token:t}))))});var Ge,Ze,Ve,Qe,Xe;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(Ge||(Ge={})),function(e){e.email="email",e.sms="sms",e.whatsapp="whatsapp"}(Ze||(Ze={})),function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Ve||(Ve={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify"}(Qe||(Qe={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify",e.updatePhone="updatePhone"}(Xe||(Xe={}));const Ye=Be("identifier"),et=Le(Ye,Be("code")),tt=Le(Ye),nt=Le(Ye,ze("phone")),rt=Le(Ye,Fe("email")),ot=e=>({verify:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:et(((t,r)=>Re(e.post(Ue(ee,n),{code:r,externalId:t}))))})),{}),signIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tt((t=>Re(e.post(Ue(te,n),{externalId:t}))))})),{}),signUp:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tt(((t,r)=>Re(e.post(Ue(ne,n),{externalId:t,user:r}))))})),{}),signUpOrIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:tt((t=>Re(e.post(Ue(oe,n),{externalId:t}))))})),{}),update:{email:rt(((t,n,r)=>Re(e.post(re.email,{externalId:t,email:n},{token:r})))),phone:Object.keys(Ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:nt(((t,r,o)=>Re(e.post(Ue(re.phone,n),{externalId:t,phone:r},{token:o}))))})),{})}}),it=Be("identifier"),at=Be("uri"),st=Le(Be("token")),ct=Le(it,at),ut=Le(Be("pendingRef")),lt=Le(it,ze("phone"),at),pt=Le(it,Fe("email"),at),dt=e=>({verify:st((t=>Re(e.post(ie,{token:t})))),signIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(ae,n),{externalId:t,URI:r,crossDevice:!0}))))})),{}),signUpOrIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(le,n),{externalId:t,URI:r,crossDevice:!0}))))})),{}),signUp:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r,o)=>Re(e.post(Ue(se,n),{externalId:t,URI:r,user:o,crossDevice:!0}))))})),{}),waitForSession:ut(((t,n)=>new Promise((r=>{const{pollingIntervalMs:o,timeoutMs:i}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||6e5,6e5)}))(n);let a;const s=setInterval((async()=>{const n=await e.post(ce,{pendingRef:t});n.ok&&(clearInterval(s),a&&clearTimeout(a),r(Re(Promise.resolve(n))))}),o);a=setTimeout((()=>{r({error:{message:`Session polling timeout exceeded: ${i}ms`,code:"0"},ok:!1}),clearInterval(s)}),i)})))),update:{email:pt(((t,n,r,o)=>Re(e.post(ue.email,{externalId:t,email:n,URI:r,crossDevice:!0},{token:o})))),phone:Object.keys(Ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:lt(((t,r,o,i)=>Re(e.post(Ue(ue.phone,n),{externalId:t,phone:r,URI:o,crossDevice:!0},{token:i}))))})),{})}}),ft=e=>({verify:st((t=>Re(e.post(ie,{token:t})))),signIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(ae,n),{externalId:t,URI:r}))))})),{}),signUp:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r,o)=>Re(e.post(Ue(se,n),{externalId:t,URI:r,user:o}))))})),{}),signUpOrIn:Object.keys(Ze).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ct(((t,r)=>Re(e.post(Ue(le,n),{externalId:t,URI:r}))))})),{}),update:{email:pt(((t,n,r,o)=>Re(e.post(ue.email,{externalId:t,email:n,URI:r},{token:o})))),phone:Object.keys(Ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:lt(((t,r,o,i)=>Re(e.post(Ue(ue.phone,n),{externalId:t,phone:r,URI:o},{token:i}))))})),{})},crossDevice:dt(e)}),ht=Le(Be("code")),gt=e=>({exchange:ht((t=>Re(e.get("/v1/auth/exchange",{queryParams:{code:t}}))))});var vt;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple"}(vt||(vt={}));const yt=e=>Object.assign({start:Object.keys(vt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:async(t,{redirect:r=!1}={})=>{const o=await e.get(pe,{queryParams:Object.assign({provider:n},t&&{redirectURL:t})});if(!r||!o.ok)return Re(Promise.resolve(o));const{url:i}=await o.json();window.location.href=i}})),{})},gt(e)),bt=Le(Be("flowId")),mt=Le(Be("executionId"),Be("stepId"),Be("interactionId")),wt=e=>({start:bt((t=>Re(e.post(me,{flowId:t})))),next:mt(((t,n,r,o)=>Re(e.post(we,{executionId:t,stepId:n,interactionId:r,input:o}))))}),Ot=Le(Be("tenant")),jt=e=>Object.assign({start:Ot((async(t,n,{redirect:r=!1}={})=>{const o=await e.get(de,{queryParams:{tenant:t,redirectURL:n}});if(!r||!o.ok)return Re(Promise.resolve(o));const{url:i}=await o.json();window.location.href=i}))},gt(e)),kt=Be("identifier"),It=Le(kt,Be("code")),_t=Le(kt),xt=Le(kt),St=e=>({signUp:_t(((t,n)=>Re(e.post(he,{externalId:t,user:n})))),verify:It(((t,n)=>Re(e.post(fe,{externalId:t,code:n})))),update:xt(((t,n)=>Re(e.post(ge,{externalId:t},{token:n}))))}),Pt=Be("identifier"),Ut=Be("origin"),Rt=Le(Pt,Ut,Be("name")),Et=Le(Pt,Ut),Ct=Le(Pt,Ut,Be("token")),Tt=Le(Be("transactionId"),Be("response")),Dt=e=>({signUp:{start:Rt(((t,n,r)=>Re(e.post(ve.start,{user:{externalId:t,name:r},origin:n})))),finish:Tt(((t,n)=>Re(e.post(ve.finish,{transactionId:t,response:n}))))},signIn:{start:Et(((t,n)=>Re(e.post(ye.start,{externalId:t,origin:n})))),finish:Tt(((t,n)=>Re(e.post(ye.finish,{transactionId:t,response:n}))))},update:{start:Ct(((t,n,r)=>Re(e.post(be.start,{externalId:t,origin:n},{token:r})))),finish:Tt(((t,n)=>Re(e.post(be.finish,{transactionId:t,response:n}))))}}),qt=Le(Be("token"));var At;const $t=Le([("projectId",At=Be("projectId"),Te(((e,t)=>e=>De(...t).validate(X(e,"projectId")))(0,At))())])((({projectId:e,logger:t,baseUrl:n,hooks:r,cookiePolicy:o})=>{return i=_e({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:r,cookiePolicy:o}),{accessKey:We(i),otp:ot(i),magicLink:ft(i),oauth:yt(i),saml:jt(i),totp:St(i),webauthn:Dt(i),flow:wt(i),refresh:e=>Re(i.get("/v1/auth/refresh",{token:e})),logout:e=>Re(i.get("/v1/auth/logoutall",{token:e})),me:e=>Re(i.get("/v1/auth/me",{token:e})),isJwtExpired:qt(xe),getJwtPermissions:qt(Se),getJwtRoles:qt(Pe),httpClient:i};var i}));$t.DeliveryMethods=Ze;const Jt="vsid",Mt="vrid";function Nt(e,t,n){return void 0===n&&(n=0),t(n).catch((function(r){if(n>=e.maxRetries||!e.shouldRetry(r))throw r;var o,i,a,s,c=(o=e.baseDelay,i=e.maxDelay,a=e.baseDelay*Math.pow(2,n),Math.max(o,Math.min(i,a)));return(s=c,new Promise((function(e){return setTimeout(e,s)}))).then((function(){return Nt(e,t,n+1)}))}))}var Kt="Failed to load the JS script of the agent";function Lt(n){var r,o=n.scriptUrlPattern,i=n.token,a=n.apiKey,s=void 0===a?i:a,c=t(n,["scriptUrlPattern","token","apiKey"]),u=(r=n,"scriptUrlPattern",Object.prototype.hasOwnProperty.call(r,"scriptUrlPattern")?o:void 0),l=[];return Promise.resolve().then((function(){if(!s||"string"!=typeof s)throw new Error("API key required");return Nt({maxRetries:5,baseDelay:100,maxDelay:3e3,shouldRetry:function(e){return!(e instanceof Error&&"Blocked by CSP"===e.message)}},(function(){var e,t=new Date,n=function(){return l.push({startedAt:t,finishedAt:new Date})},r=function(e,t,n,r){var o,i=document,a="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),r=t.blockedURI;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(o=t,c())};i.addEventListener(a,s);var c=function(){return i.removeEventListener(a,s)};return Promise.resolve().then(t).then((function(e){return c(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(c(),o)return function(){throw new Error("Blocked by CSP")}();throw e}))}))}(e=function(e,t){void 0===t&&(t="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js");var n=encodeURIComponent;return t.replace(/<[^<>]+>/g,(function(t){return"<version>"===t?"3":"<apiKey>"===t?n(e):"<loaderVersion>"===t?n("3.7.1"):t}))}(s,u),(function(){return function(e){return new Promise((function(t,n){var r=document.createElement("script"),o=function(){var e;return null===(e=r.parentNode)||void 0===e?void 0:e.removeChild(r)},i=document.head||document.getElementsByTagName("head")[0];r.onload=function(){o(),t()},r.onerror=function(){o(),n(new Error(Kt))},r.async=!0,r.src=e,i.appendChild(r)}))}(e)}));return r.then(n,n),r}))})).then((function(){var t=window,n="__fpjs_p_l_b",r=t[n];if(function(e,t){var n,r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(t,n),"function"!=typeof(null==r?void 0:r.load))throw new Error(Kt);return r.load(e(e({},c),{ldi:{attempts:l}}))}))}const Bt=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],Ft=e=>{const t=Lt({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem(Jt);e||(e=Bt(Jt)),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem(Jt,e);const n=await t,r=await n.get({linkedId:e});sessionStorage.setItem(Mt,r.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var zt,Ht,Wt,Gt,Zt;const Vt=e=>"string"==typeof e?e:Object.assign({},e);class Qt{constructor(e){zt.add(this),Ht.set(this,void 0),Wt.set(this,{}),Gt.set(this,0),r(this,Ht,e,"f")}get current(){return Vt(n(this,Ht,"f"))}update(e){let t=e;if("object"==typeof e&&"object"==typeof n(this,Ht,"f")&&(t=Object.assign(Object.assign({},n(this,Ht,"f")),e)),!((e,t)=>{if("string"==typeof e)return e===t;const n=e&&Object.getOwnPropertyNames(e)||[],r=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==r.length)return!1;for(let r=0;r<n.length;r+=1){const o=n[r];if(e[o]!==t[o])return!1}return!0})(n(this,Ht,"f"),t)){const e=n(this,Ht,"f");r(this,Ht,t,"f"),Object.freeze(n(this,Ht,"f")),setTimeout((()=>{Object.values(n(this,Wt,"f")).forEach((n=>n(Vt(t),e)))}),0)}}subscribe(e){var t;r(this,Gt,n(this,Gt,"f")+1,"f"),n(this,Wt,"f")[n(this,Gt,"f")]=e,((t=n(this,Ht,"f"))&&"string"!=typeof t?0===Object.entries(t).length:!t)||e(Vt(n(this,Ht,"f")));const o=n(this,Gt,"f");return()=>n(this,zt,"m",Zt).call(this,o.toString())}unsubscribeAll(){r(this,Wt,{},"f")}}
2
2
  /*! js-cookie v3.0.1 | MIT */
3
- function Xt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}Ht=new WeakMap,Wt=new WeakMap,Gt=new WeakMap,Ft=new WeakSet,Zt=function(e){!!n(this,Wt,"f")[e]&&delete n(this,Wt,"f")[e]};var Yt=function e(t,n){function r(e,r,o){if("undefined"!=typeof document){"number"==typeof(o=Xt({},n,o)).expires&&(o.expires=new Date(Date.now()+864e5*o.expires)),o.expires&&(o.expires=o.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var a in o)o[a]&&(i+="; "+a,!0!==o[a]&&(i+="="+o[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},o=0;o<n.length;o++){var i=n[o].split("="),a=i.slice(1).join("=");try{var s=decodeURIComponent(i[0]);if(r[s]=t.read(a,s),e===s)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",Xt({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,Xt({},this.attributes,t))},withConverter:function(t){return e(Xt({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const en="DSR";let tn=[];function nn(e,t,n){const r=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(r){let t;for(;t=tn.pop();)clearTimeout(t);const o=r.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),o);tn.push(i)}}function rn(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:r}){e&&Yt.set("DS",e,{path:t,domain:n,expires:r,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem(en,e)}(t)}function on(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem(en):""}async function an(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=cn(n.publicKey.challenge),n.publicKey.user.id=cn(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=cn(e.id)})),n}(e),n=await navigator.credentials.create(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:un(r.rawId),response:Object.assign(Object.assign({},r.response),{attestationObject:un(r.response.attestationObject),clientDataJSON:un(r.response.clientDataJSON)})}));var r}async function sn(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=cn(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=cn(e.id)})),n}(e),n=await navigator.credentials.get(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:un(r.rawId),response:Object.assign(Object.assign({},r.response),{authenticatorData:un(r.response.authenticatorData),clientDataJSON:un(r.response.clientDataJSON),signature:un(r.response.signature),userHandle:r.response.userHandle?un(r.response.userHandle):void 0})}));var r}function cn(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function un(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}return e=>{var{autoRefresh:n=!0,persistTokens:r=!0}=e,o=t(e,["autoRefresh","persistTokens"]);zt(o.fpKey).get().catch((()=>null));const i=o;let a,s;const c=new Qt(""),u=new Qt({});i.hooks={beforeRequest:e=>null==a?void 0:a(e),afterRequest:(e,t)=>null==s?void 0:s(e,t)};const l=$t(i),p=Object.assign(Object.assign({},l),{webauthn:(d=l,{async signUp(e,t){const n=await d.webauthn.signUp.start(e,window.location.origin,t),r=await an(n.data.options);return await d.webauthn.signUp.finish(n.data.transactionId,r)},async signIn(e){const t=await d.webauthn.signIn.start(e,window.location.origin),n=await sn(t.data.options);return await d.webauthn.signIn.finish(t.data.transactionId,n)},async update(e,t){const n=await d.webauthn.update.start(e,window.location.origin,t),r=await an(n.data.options);return await d.webauthn.update.finish(n.data.transactionId,r)},helpers:{create:an,get:sn}}),onSessionTokenChange:c.subscribe,onUserChange:u.subscribe});var d;return n&&(p.logout=(...e)=>{const t=on(),n=[(null==e?void 0:e.shift())||t,...e],r=l.logout(...n);return localStorage&&localStorage.removeItem(en),Yt.remove("DS"),r}),a=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{[Jt]:sessionStorage.getItem(Jt)||"",[Mt]:sessionStorage.getItem(Mt)||""})),!e.token&&r&&(e.token=on()),e},(n||r)&&(s=(e,o)=>{!async function(e,n,r,o){try{const i=await(null==n?void 0:n.json());if(i){const n=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:a,refreshJwt:s,user:c}=n,u=t(n,["sessionJwt","refreshJwt","user"]);o.persistTokens&&rn(a,s,u),r.sessionToken.update(a),r.user.update(c),a&&s&&o.autoRefresh&&nn(e,a,s)}}catch(e){console.error("Could not set tokens from body",e)}}(p.refresh,o,{sessionToken:c,user:u},{autoRefresh:n,persistTokens:r})}),n&&p.refresh(),p}}));
3
+ function Xt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}Ht=new WeakMap,Wt=new WeakMap,Gt=new WeakMap,zt=new WeakSet,Zt=function(e){!!n(this,Wt,"f")[e]&&delete n(this,Wt,"f")[e]};var Yt=function e(t,n){function r(e,r,o){if("undefined"!=typeof document){"number"==typeof(o=Xt({},n,o)).expires&&(o.expires=new Date(Date.now()+864e5*o.expires)),o.expires&&(o.expires=o.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var a in o)o[a]&&(i+="; "+a,!0!==o[a]&&(i+="="+o[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},o=0;o<n.length;o++){var i=n[o].split("="),a=i.slice(1).join("=");try{var s=decodeURIComponent(i[0]);if(r[s]=t.read(a,s),e===s)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",Xt({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,Xt({},this.attributes,t))},withConverter:function(t){return e(Xt({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const en="DSR";let tn=[];function nn(e,t,n){const r=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(r){let t;for(;t=tn.pop();)clearTimeout(t);const o=r.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),o);tn.push(i)}}function rn(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:r}){e&&Yt.set("DS",e,{path:t,domain:n,expires:r,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem(en,e)}(t)}function on(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem(en):""}async function an(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=cn(n.publicKey.challenge),n.publicKey.user.id=cn(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=cn(e.id)})),n}(e),n=await navigator.credentials.create(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:un(r.rawId),response:Object.assign(Object.assign({},r.response),{attestationObject:un(r.response.attestationObject),clientDataJSON:un(r.response.clientDataJSON)})}));var r}async function sn(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=cn(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=cn(e.id)})),n}(e),n=await navigator.credentials.get(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:un(r.rawId),response:Object.assign(Object.assign({},r.response),{authenticatorData:un(r.response.authenticatorData),clientDataJSON:un(r.response.clientDataJSON),signature:un(r.response.signature),userHandle:r.response.userHandle?un(r.response.userHandle):void 0})}));var r}function cn(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function un(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const ln="undefined"!=typeof window;return e=>{var{autoRefresh:n=!0,persistTokens:r=!0}=e,o=t(e,["autoRefresh","persistTokens"]);ln?Ft(o.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const i=o;let a,s;const c=new Qt(""),u=new Qt({});i.hooks={beforeRequest:e=>null==a?void 0:a(e),afterRequest:(e,t)=>null==s?void 0:s(e,t)};const l=$t(i),p=Object.assign(Object.assign({},l),{webauthn:(d=l,{async signUp(e,t){const n=await d.webauthn.signUp.start(e,window.location.origin,t),r=await an(n.data.options);return await d.webauthn.signUp.finish(n.data.transactionId,r)},async signIn(e){const t=await d.webauthn.signIn.start(e,window.location.origin),n=await sn(t.data.options);return await d.webauthn.signIn.finish(t.data.transactionId,n)},async update(e,t){const n=await d.webauthn.update.start(e,window.location.origin,t),r=await an(n.data.options);return await d.webauthn.update.finish(n.data.transactionId,r)},helpers:{create:an,get:sn}}),onSessionTokenChange:c.subscribe,onUserChange:u.subscribe});var d;return n&&(p.logout=(...e)=>{const t=on(),n=[(null==e?void 0:e.shift())||t,...e],r=l.logout(...n);return localStorage&&localStorage.removeItem(en),Yt.remove("DS"),r}),a=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{[Jt]:sessionStorage.getItem(Jt)||"",[Mt]:sessionStorage.getItem(Mt)||""})),!e.token&&r&&(e.token=on()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.4"}),e},(n||r)&&(s=(e,o)=>{!async function(e,n,r,o){try{const i=await(null==n?void 0:n.json());if(i){const n=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:a,refreshJwt:s,user:c}=n,u=t(n,["sessionJwt","refreshJwt","user"]);o.persistTokens&&rn(a,s,u),r.sessionToken.update(a),r.user.update(c),a&&s&&o.autoRefresh&&nn(e,a,s)}}catch(e){console.error("Could not set tokens from body",e)}}(p.refresh,o,{sessionToken:c,user:u},{autoRefresh:n,persistTokens:r})}),n&&p.refresh(),p}}));
4
4
  //# sourceMappingURL=index.umd.js.map