@descope/web-js-sdk 0.1.0-alpha.5 → 0.1.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),s=require("@fingerprintjs/fingerprintjs-pro"),n=require("js-cookie");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=a(t),r=a(n);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,n=await s.get({linkedId:e});sessionStorage.setItem("vrid",n.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var l,u,d,g,f;const h=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){const s=t;if(!((e,t)=>{const s=e&&Object.getOwnPropertyNames(e)||[],n=t&&Object.getOwnPropertyNames(t)||[];if(s.length!==n.length)return!1;for(let n=0;n<s.length;n+=1){const a=s[n];if(e[a]!==t[a])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){e.__classPrivateFieldSet(this,g,e.__classPrivateFieldGet(this,g,"f")+1,"f"),e.__classPrivateFieldGet(this,d,"f")[e.__classPrivateFieldGet(this,g,"f")]=t;const s=e.__classPrivateFieldGet(this,g,"f");return()=>e.__classPrivateFieldGet(this,l,"m",f).call(this,s.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 w=[];function b(e,t,s){const n=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(n){let t;for(;t=w.pop();)clearTimeout(t);const a=n.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(s)}),a);w.push(i)}}function v(e,t,s){!function(e,{cookiePath:t,cookieDomain:s,cookieExpiration:n}){e&&r.default.set("DS",e,{path:t,domain:s,expires:n,sameSite:"None",secure:!0})}(e,s),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function S(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function _(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 n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:m(n.rawId),response:Object.assign(Object.assign({},n.response),{attestationObject:m(n.response.attestationObject),clientDataJSON:m(n.response.clientDataJSON)})}));var n}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 n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:m(n.rawId),response:Object.assign(Object.assign({},n.response),{authenticatorData:m(n.response.authenticatorData),clientDataJSON:m(n.response.clientDataJSON),signature:m(n.response.signature),userHandle:n.response.userHandle?m(n.response.userHandle):void 0})}));var n}function O(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function m(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const k="undefined"!=typeof window;module.exports=t=>{var{autoRefresh:s=!0,persistTokens:n=!0}=t,a=e.__rest(t,["autoRefresh","persistTokens"]);k?c(a.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const o=a;let l,u;const d=new p({sessionToken:""}),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:(w=f,{async signUp(e,t){const s=await w.webauthn.signUp.start(e,window.location.origin,t),n=await _(s.data.options);return await w.webauthn.signUp.finish(s.data.transactionId,n)},async signIn(e){const t=await w.webauthn.signIn.start(e,window.location.origin),s=await y(t.data.options);return await w.webauthn.signIn.finish(t.data.transactionId,s)},async update(e,t){const s=await w.webauthn.update.start(e,window.location.origin,t),n=await _(s.data.options);return await w.webauthn.update.finish(s.data.transactionId,n)},helpers:{create:_,get:y}}),onSessionTokenChange:e=>{var t;const s=null===(t=d.current)||void 0===t?void 0:t.sessionToken;return s&&e(s),d.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=g.current;return t&&Object.entries(t).length>0&&e(t),g.subscribe((t=>{e(t)}))}});var w;return s&&(h.logout=(...e)=>{const t=S(),s=[(null==e?void 0:e.shift())||t,...e],n=f.logout(...s);return localStorage&&localStorage.removeItem("DSR"),r.default.remove("DS"),n}),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&&n&&(e.token=S()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.5"}),e},(s||n)&&(u=(t,a)=>{!async function(t,s,n,a){try{if(401===s.status)return n.sessionToken.update({sessionToken:""}),void n.user.update({});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"]);a.persistTokens&&v(r,o,l),r&&n.sessionToken.update({sessionToken:r}),c&&n.user.update(c),r&&o&&a.autoRefresh&&b(t,r,o)}}catch(e){console.error("Could not set tokens from body",e)}}(h.refresh,a,{sessionToken:d,user:g},{autoRefresh:s,persistTokens:n})}),s&&h.refresh(),h};
1
+ "use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),s=require("@fingerprintjs/fingerprintjs-pro"),n=require("js-cookie");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=a(t),r=a(n);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,n=await s.get({linkedId:e});sessionStorage.setItem("vrid",n.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var l,u,d,g,h;const p=e=>Object.assign({},e);class f{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 p(e.__classPrivateFieldGet(this,u,"f"))}update(t){const s=t;if(!((e,t)=>{const s=e&&Object.getOwnPropertyNames(e)||[],n=t&&Object.getOwnPropertyNames(t)||[];if(s.length!==n.length)return!1;for(let n=0;n<s.length;n+=1){const a=s[n];if(e[a]!==t[a])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(p(s),t)))}),0)}}subscribe(t){e.__classPrivateFieldSet(this,g,e.__classPrivateFieldGet(this,g,"f")+1,"f"),e.__classPrivateFieldGet(this,d,"f")[e.__classPrivateFieldGet(this,g,"f")]=t;const s=e.__classPrivateFieldGet(this,g,"f");return()=>e.__classPrivateFieldGet(this,l,"m",h).call(this,s.toString())}unsubscribeAll(){e.__classPrivateFieldSet(this,d,{},"f")}}u=new WeakMap,d=new WeakMap,g=new WeakMap,l=new WeakSet,h=function(t){!!e.__classPrivateFieldGet(this,d,"f")[t]&&delete e.__classPrivateFieldGet(this,d,"f")[t]};let w=[];function b(e,t,s){const n=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(n){let t;for(;t=w.pop();)clearTimeout(t);const a=n.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(s)}),a);w.push(i)}}function v(e,t,s){!function(e,{cookiePath:t,cookieDomain:s,cookieExpiration:n}){e&&r.default.set("DS",e,{path:t,domain:s,expires:n,sameSite:"None",secure:!0})}(e,s),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function S(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function _(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 n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:m(n.rawId),response:Object.assign(Object.assign({},n.response),{attestationObject:m(n.response.attestationObject),clientDataJSON:m(n.response.clientDataJSON)})}));var n}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 n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:m(n.rawId),response:Object.assign(Object.assign({},n.response),{authenticatorData:m(n.response.authenticatorData),clientDataJSON:m(n.response.clientDataJSON),signature:m(n.response.signature),userHandle:n.response.userHandle?m(n.response.userHandle):void 0})}));var n}function O(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function m(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const k="undefined"!=typeof window;module.exports=t=>{var{autoRefresh:s=!0,persistTokens:n=!0}=t,a=e.__rest(t,["autoRefresh","persistTokens"]);k?c(a.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const o=a;let l,u;const d=new f({sessionToken:""}),g=new f({});o.hooks={beforeRequest:e=>null==l?void 0:l(e),afterRequest:(e,t)=>null==u?void 0:u(e,t)};const h=i.default(o),p=Object.assign(Object.assign({},h),{webauthn:(w=h,{async signUp(e,t){const s=await w.webauthn.signUp.start(e,window.location.origin,t),n=await _(s.data.options);return await w.webauthn.signUp.finish(s.data.transactionId,n)},async signIn(e){const t=await w.webauthn.signIn.start(e,window.location.origin),s=await y(t.data.options);return await w.webauthn.signIn.finish(t.data.transactionId,s)},async signUpOrIn(e){var t;const s=await w.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=s.data)||void 0===t?void 0:t.create){const e=await _(s.data.options);return await w.webauthn.signUp.finish(s.data.transactionId,e)}{const e=await y(s.data.options);return await w.webauthn.signIn.finish(s.data.transactionId,e)}},async update(e,t){const s=await w.webauthn.update.start(e,window.location.origin,t),n=await _(s.data.options);return await w.webauthn.update.finish(s.data.transactionId,n)},helpers:{create:_,get:y}}),onSessionTokenChange:e=>{var t;const s=null===(t=d.current)||void 0===t?void 0:t.sessionToken;return s&&e(s),d.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=g.current;return t&&Object.entries(t).length>0&&e(t),g.subscribe((t=>{e(t)}))}});var w;return s&&(p.logout=(...e)=>{const t=S(),s=[(null==e?void 0:e.shift())||t,...e],n=h.logout(...s);return localStorage&&localStorage.removeItem("DSR"),r.default.remove("DS"),n}),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&&n&&(e.token=S()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.6"}),e},(s||n)&&(u=(t,a)=>{!async function(t,s,n,a){try{if(401===s.status)return n.sessionToken.update({sessionToken:""}),void n.user.update({});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"]);a.persistTokens&&v(r,o,l),r&&n.sessionToken.update({sessionToken:r}),c&&n.user.update(c),r&&o&&a.autoRefresh&&b(t,r,o)}}catch(e){console.error("Could not set tokens from body",e)}}(p.refresh,a,{sessionToken:d,user:g},{autoRefresh:s,persistTokens:n})}),s&&p.refresh(),p};
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\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 = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { 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<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t}\n\t};\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","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","currentSessionToken","onUserChange","currUser","entries","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","status","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,UAOrD,CANC,MAAOC,GAEJC,OAAOC,UAEVC,QAAQC,MAAMJ,EAEf,GAEF,gBC5BF,MAmBMK,EAASC,GACdC,OAAAC,OAAA,CAAA,EAAYF,GAGb,MAAMG,EAOLC,YAAYC,eANZC,EAAUC,IAAAC,UAAA,GAEVC,EAAA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A4BrL,eAAeC,QNfJ,SMeyC,OA+F1EoJ,EAAO7F,OAASkF,IACpBW,EAAO7F,MAAQqC,KAEhBwD,EAAOiC,QACHnK,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAiI,EAAOiC,SAAO,CACjB,qBAAsB,SACtB,wBAAyB,kBAEnBjC,CAAM,GAGVZ,GAAeC,KAClBO,EAAmB,CAACM,EAAK9I,MFPpBX,eACN6D,EACAlD,EACAS,EACA6E,GAEA,IACC,GAAmB,MAAftF,EAAI8K,OAIP,OAFArK,EAAMgI,aAAalH,OAAO,CAAEkH,aAAc,UAC1ChI,EAAMmF,KAAKrE,OAAO,CAAA,GAGnB,MAAMwJ,QAAa/K,aAAG,EAAHA,EAAKgL,QACxB,GAAID,EAAM,CACT,MAAMjF,EA3BT,SAA4BiF,GAE3B,OAAOA,aAAA,EAAAA,EAAME,WAAYF,GAAS,CAAA,CACnC,CAwB6DG,CAAmBH,IAAvE5H,WAAEA,EAAUmB,WAAEA,EAAUsB,KAAEA,GAAkDE,EAAzCvB,EAAnC4D,EAAAA,OAAArC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ2C,eACX5D,EAAiBlB,EAAYmB,EAAYC,GAItCpB,GACH1C,EAAMgI,aAAalH,OAAO,CAAEkH,aAActF,IAEvCyC,GACHnF,EAAMmF,KAAKrE,OAAOqE,GAIfzC,GAAcmB,GAAcgB,EAAQ0C,aACvC/E,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CE/BGgL,CACClC,EAAOmC,QACPpL,EACA,CAAEyI,eAAc7C,QAChB,CAAEoC,cAAaC,iBACf,GAICD,GAEHiB,EAAOmC,UAGDnC,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 = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget\n\t}\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<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t}\n\t};\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","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","signUpOrIn","helpers","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","status","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,U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,IACC,GAAmB,MAAftF,EAAI+K,OAIP,OAFAtK,EAAMgI,aAAalH,OAAO,CAAEkH,aAAc,UAC1ChI,EAAMmF,KAAKrE,OAAO,CAAA,GAGnB,MAAMyJ,QAAahL,aAAG,EAAHA,EAAKiL,QACxB,GAAID,EAAM,CACT,MAAMlF,EA3BT,SAA4BkF,GAE3B,OAAOA,aAAA,EAAAA,EAAME,WAAYF,GAAS,CAAA,CACnC,CAwB6DG,CAAmBH,IAAvE7H,WAAEA,EAAUmB,WAAEA,EAAUsB,KAAEA,GAAkDE,EAAzCvB,EAAnC4D,EAAAA,OAAArC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ2C,eACX5D,EAAiBlB,EAAYmB,EAAYC,GAItCpB,GACH1C,EAAMgI,aAAalH,OAAO,CAAEkH,aAActF,IAEvCyC,GACHnF,EAAMmF,KAAKrE,OAAOqE,GAIfzC,GAAcmB,GAAcgB,EAAQ0C,aACvC/E,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CE/BGiL,CACCnC,EAAOoC,QACPrL,EACA,CAAEyI,eAAc7C,QAChB,CAAEoC,cAAaC,iBACf,GAICD,GAEHiB,EAAOoC,UAGDpC,CAAM"}
package/dist/index.d.ts CHANGED
@@ -19,8 +19,9 @@ declare type WebJSSDKArgs = Parameters<typeof _descope_core_js_sdk__default>[0]
19
19
  */
20
20
  declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs) => {
21
21
  webauthn: {
22
- signUp(identifier: string, name: string): Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.ResponseData>>;
23
- signIn(identifier: string): Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.ResponseData>>;
22
+ signUp(identifier: string, name: string): Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
23
+ signIn(identifier: string): Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
24
+ signUpOrIn(identifier: string): Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
24
25
  update(identifier: string, token: string): Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.ResponseData>>;
25
26
  helpers: {
26
27
  create: (options: string) => Promise<string>;
@@ -187,10 +188,7 @@ declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs)
187
188
  redirect: true;
188
189
  } ? undefined : _descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
189
190
  };
190
- exchange: (code: string, loginOptions?: {
191
- stepup: boolean;
192
- customClaims: Map<string, any>;
193
- }, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
191
+ exchange: (code: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
194
192
  };
195
193
  saml: {
196
194
  start: <B_1 extends {
@@ -198,10 +196,7 @@ declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs)
198
196
  }>(tenantNameOrEmail: string, config?: B_1) => Promise<B_1 extends {
199
197
  redirect: true;
200
198
  } ? undefined : _descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.URLResponse>>;
201
- exchange: (code: string, loginOptions?: {
202
- stepup: boolean;
203
- customClaims: Map<string, any>;
204
- }, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
199
+ exchange: (code: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
205
200
  };
206
201
  totp: {
207
202
  signUp: (identifier: string, user?: {
@@ -216,7 +211,10 @@ declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs)
216
211
  update: (identifier: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.TOTPResponse>>;
217
212
  };
218
213
  flow: {
219
- start: (flowId: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.FlowResponse>>;
214
+ start: (flowId: string, options?: {
215
+ redirectUrl?: string;
216
+ tenant?: string;
217
+ }) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.FlowResponse>>;
220
218
  next: (executionId: string, stepId: string, interactionId: string, input?: Record<string, FormDataEntryValue>) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.FlowResponse>>;
221
219
  };
222
220
  refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldSet as e,__classPrivateFieldGet as t,__rest as n}from"tslib";import s from"@descope/core-js-sdk";import{load as a}from"@fingerprintjs/fingerprintjs-pro";import o from"js-cookie";const r=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],i=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,d;const p=e=>Object.assign({},e);class h{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 p(t(this,u,"f"))}update(n){const s=n;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],s=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==s.length)return!1;for(let s=0;s<n.length;s+=1){const a=n[s];if(e[a]!==t[a])return!1}return!0})(t(this,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(p(s),n)))}),0)}}subscribe(n){e(this,g,t(this,g,"f")+1,"f"),t(this,l,"f")[t(this,g,"f")]=n;const s=t(this,g,"f");return()=>t(this,c,"m",d).call(this,s.toString())}unsubscribeAll(){e(this,l,{},"f")}}u=new WeakMap,l=new WeakMap,g=new WeakMap,c=new WeakSet,d=function(e){!!t(this,l,"f")[e]&&delete t(this,l,"f")[e]};let f=[];function w(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=f.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),o=setTimeout((()=>{e(n)}),a);f.push(o)}}function b(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:s}){e&&o.set("DS",e,{path:t,domain:n,expires:s,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function v(){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=y(n.publicKey.challenge),n.publicKey.user.id=y(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=y(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 S(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=y(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=y(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 y(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 k="undefined"!=typeof window;var j=e=>{var{autoRefresh:t=!0,persistTokens:a=!0}=e,r=n(e,["autoRefresh","persistTokens"]);k?i(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 h({sessionToken:""}),d=new h({});c.hooks={beforeRequest:e=>null==u?void 0:u(e),afterRequest:(e,t)=>null==l?void 0:l(e,t)};const p=s(c),f=Object.assign(Object.assign({},p),{webauthn:(y=p,{async signUp(e,t){const n=await y.webauthn.signUp.start(e,window.location.origin,t),s=await m(n.data.options);return await y.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await y.webauthn.signIn.start(e,window.location.origin),n=await S(t.data.options);return await y.webauthn.signIn.finish(t.data.transactionId,n)},async update(e,t){const n=await y.webauthn.update.start(e,window.location.origin,t),s=await m(n.data.options);return await y.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:m,get:S}}),onSessionTokenChange:e=>{var t;const n=null===(t=g.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),g.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=d.current;return t&&Object.entries(t).length>0&&e(t),d.subscribe((t=>{e(t)}))}});var y;return t&&(f.logout=(...e)=>{const t=v(),n=[(null==e?void 0:e.shift())||t,...e],s=p.logout(...n);return localStorage&&localStorage.removeItem("DSR"),o.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=v()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.5"}),e},(t||a)&&(l=(e,s)=>{!async function(e,t,s,a){try{if(401===t.status)return s.sessionToken.update({sessionToken:""}),void s.user.update({});const o=await(null==t?void 0:t.json());if(o){const t=function(e){return(null==e?void 0:e.authInfo)||e||{}}(o),{sessionJwt:r,refreshJwt:i,user:c}=t,u=n(t,["sessionJwt","refreshJwt","user"]);a.persistTokens&&b(r,i,u),r&&s.sessionToken.update({sessionToken:r}),c&&s.user.update(c),r&&i&&a.autoRefresh&&w(e,r,i)}}catch(e){console.error("Could not set tokens from body",e)}}(f.refresh,s,{sessionToken:g,user:d},{autoRefresh:t,persistTokens:a})}),t&&f.refresh(),f};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 o=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],r=e=>{const t=a({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 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,d,g;const p=e=>Object.assign({},e);class h{constructor(t){c.add(this),u.set(this,void 0),l.set(this,{}),d.set(this,0),e(this,u,t,"f")}get current(){return p(t(this,u,"f"))}update(n){const s=n;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],s=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==s.length)return!1;for(let s=0;s<n.length;s+=1){const a=n[s];if(e[a]!==t[a])return!1}return!0})(t(this,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(p(s),n)))}),0)}}subscribe(n){e(this,d,t(this,d,"f")+1,"f"),t(this,l,"f")[t(this,d,"f")]=n;const s=t(this,d,"f");return()=>t(this,c,"m",g).call(this,s.toString())}unsubscribeAll(){e(this,l,{},"f")}}u=new WeakMap,l=new WeakMap,d=new WeakMap,c=new WeakSet,g=function(e){!!t(this,l,"f")[e]&&delete t(this,l,"f")[e]};let f=[];function w(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=f.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),a);f.push(i)}}function b(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 v(){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=y(n.publicKey.challenge),n.publicKey.user.id=y(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=y(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 S(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=y(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=y(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 y(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 k="undefined"!=typeof window;var j=e=>{var{autoRefresh:t=!0,persistTokens:a=!0}=e,o=n(e,["autoRefresh","persistTokens"]);k?r(o.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const c=o;let u,l;const d=new h({sessionToken:""}),g=new h({});c.hooks={beforeRequest:e=>null==u?void 0:u(e),afterRequest:(e,t)=>null==l?void 0:l(e,t)};const p=s(c),f=Object.assign(Object.assign({},p),{webauthn:(y=p,{async signUp(e,t){const n=await y.webauthn.signUp.start(e,window.location.origin,t),s=await m(n.data.options);return await y.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await y.webauthn.signIn.start(e,window.location.origin),n=await S(t.data.options);return await y.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await y.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await m(n.data.options);return await y.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await S(n.data.options);return await y.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await y.webauthn.update.start(e,window.location.origin,t),s=await m(n.data.options);return await y.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:m,get:S}}),onSessionTokenChange:e=>{var t;const n=null===(t=d.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),d.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=g.current;return t&&Object.entries(t).length>0&&e(t),g.subscribe((t=>{e(t)}))}});var y;return t&&(f.logout=(...e)=>{const t=v(),n=[(null==e?void 0:e.shift())||t,...e],s=p.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=v()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.6"}),e},(t||a)&&(l=(e,s)=>{!async function(e,t,s,a){try{if(401===t.status)return s.sessionToken.update({sessionToken:""}),void s.user.update({});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:o,refreshJwt:r,user:c}=t,u=n(t,["sessionJwt","refreshJwt","user"]);a.persistTokens&&b(o,r,u),o&&s.sessionToken.update({sessionToken:o}),c&&s.user.update(c),o&&r&&a.autoRefresh&&w(e,o,r)}}catch(e){console.error("Could not set tokens from body",e)}}(f.refresh,s,{sessionToken:d,user:g},{autoRefresh:t,persistTokens:a})}),t&&f.refresh(),f};export{j 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\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 = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { 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<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t}\n\t};\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","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","currentSessionToken","onUserChange","currUser","entries","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","status","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,MAmBMK,EAASC,GACdC,OAAAC,OAAA,CAAA,EAAYF,GAGb,MAAMG,EAOLC,YAAYC,eANZC,EAAUC,IAAAC,UAAA,GAEVC,EAAAF,IAAAC,KAA+B,CAAA,GAE/BE,EAAAH,IAAAC,KAAS,GAGRG,EAAAH,KAAIF,EAAUD,EAAI,IAClB,CAEGO,cACH,OAAOb,EAAMc,EAAAL,KAAIF,EAAA,KACjB,CAEDQ,OAAOC,GACN,MAAMC,EAAeD,EACrB,IAxCc,EAAwBE,EAAMC,KAC7C,MAAMC,EAAeF,GAAKhB,OAAOmB,oBAAoBH,IAAO,GACtDI,EAAeH,GAAKjB,OAAOmB,oBAAo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E,OAAO,CAAA,GAGnB,MAAMyJ,QAAahL,aAAG,EAAHA,EAAKiL,QACxB,GAAID,EAAM,CACT,MAAMlF,EA3BT,SAA4BkF,GAE3B,OAAOA,aAAA,EAAAA,EAAME,WAAYF,GAAS,CAAA,CACnC,CAwB6DG,CAAmBH,IAAvE7H,WAAEA,EAAUmB,WAAEA,EAAUsB,KAAEA,GAAkDE,EAAzCvB,EAAnC6D,EAAAtC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ4C,eACX7D,EAAiBlB,EAAYmB,EAAYC,GAItCpB,GACH1C,EAAMiI,aAAanH,OAAO,CAAEmH,aAAcvF,IAEvCyC,GACHnF,EAAMmF,KAAKrE,OAAOqE,GAIfzC,GAAcmB,GAAcgB,EAAQ2C,aACvChF,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CE/BGiL,CACClC,EAAOmC,QACPrL,EACA,CAAE0I,eAAc9C,QAChB,CAAEqC,cAAaC,iBACf,GAICD,GAEHiB,EAAOmC,UAGDnC,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 = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget\n\t}\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<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t}\n\t};\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","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","signUpOrIn","helpers","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","status","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,gBC5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