@descope/web-js-sdk 0.1.0-alpha.7 → 0.1.0-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs.js +1 -1
- package/dist/cjs/index.cjs.js.map +1 -1
- package/dist/index.d.ts +29 -44
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +2 -2
- package/dist/index.umd.js.map +1 -1
- package/package.json +6 -6
package/dist/cjs/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),n=require("@fingerprintjs/fingerprintjs-pro"),s=require("js-cookie");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=a(t),r=a(s);const o="undefined"!=typeof window,c=o&&localStorage.getItem("fingerprint.public.key")||"A9aCLRHzKCv3uL69oqDr",l=o&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",u=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],d=e=>{const t=n.load({apiKey:e||c,endpoint:l});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=u("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 g,p,f,h,w;const v=e=>Object.assign({},e);class b{constructor(t){g.add(this),p.set(this,void 0),f.set(this,{}),h.set(this,0),e.__classPrivateFieldSet(this,p,t,"f")}get current(){return v(e.__classPrivateFieldGet(this,p,"f"))}update(t){const n=t;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],s=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==s.length)return!1;for(let s=0;s<n.length;s+=1){const a=n[s];if(e[a]!==t[a])return!1}return!0})(e.__classPrivateFieldGet(this,p,"f"),n)){const t=e.__classPrivateFieldGet(this,p,"f");e.__classPrivateFieldSet(this,p,n,"f"),Object.freeze(e.__classPrivateFieldGet(this,p,"f")),setTimeout((()=>{Object.values(e.__classPrivateFieldGet(this,f,"f")).forEach((e=>e(v(n),t)))}),0)}}subscribe(t){e.__classPrivateFieldSet(this,h,e.__classPrivateFieldGet(this,h,"f")+1,"f"),e.__classPrivateFieldGet(this,f,"f")[e.__classPrivateFieldGet(this,h,"f")]=t;const n=e.__classPrivateFieldGet(this,h,"f");return()=>e.__classPrivateFieldGet(this,g,"m",w).call(this,n.toString())}unsubscribeAll(){e.__classPrivateFieldSet(this,f,{},"f")}}p=new WeakMap,f=new WeakMap,h=new WeakMap,g=new WeakSet,w=function(t){!!e.__classPrivateFieldGet(this,f,"f")[t]&&delete e.__classPrivateFieldGet(this,f,"f")[t]};let S=[];function y(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=S.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),a);S.push(i)}}function _(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:s}){e&&r.default.set("DS",e,{path:t,domain:n,expires:s,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function m(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function k(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),n.publicKey.user.id=I(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.create(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:P(s.rawId),response:Object.assign(Object.assign({},s.response),{attestationObject:P(s.response.attestationObject),clientDataJSON:P(s.response.clientDataJSON)})}));var s}async function O(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.get(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:P(s.rawId),response:Object.assign(Object.assign({},s.response),{authenticatorData:P(s.response.authenticatorData),clientDataJSON:P(s.response.clientDataJSON),signature:P(s.response.signature),userHandle:s.response.userHandle?P(s.response.userHandle):void 0})}));var s}async function j(e=!1){const t=!!(PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function I(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function P(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}module.exports=t=>{var{autoRefresh:n=!0,persistTokens:s=!0}=t,a=e.__rest(t,["autoRefresh","persistTokens"]);o?d(a.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const c=a;let l,u;const g=new b({sessionToken:""}),p=new b({});c.hooks={beforeRequest:e=>null==l?void 0:l(e),afterRequest:(e,t)=>null==u?void 0:u(e,t)};const f=i.default(c),h=Object.assign(Object.assign({},f),{webauthn:(w=f,{async signUp(e,t){const n=await w.webauthn.signUp.start(e,window.location.origin,t),s=await k(n.data.options);return await w.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await w.webauthn.signIn.start(e,window.location.origin),n=await O(t.data.options);return await w.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await w.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await k(n.data.options);return await w.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await O(n.data.options);return await w.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await w.webauthn.update.start(e,window.location.origin,t),s=await k(n.data.options);return await w.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:k,get:O,isSupported:j}}),onSessionTokenChange:e=>{var t;const n=null===(t=g.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),g.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=p.current;return t&&Object.entries(t).length>0&&e(t),p.subscribe((t=>{e(t)}))}});var w;return o?(n&&["logout","logoutAll"].forEach((e=>{const t=f[e];h[e]=(...e)=>{const n=m(),s=[(null==e?void 0:e.shift())||n,...e],a=t(...s);return localStorage&&localStorage.removeItem("DSR"),r.default.remove("DS"),g.update({sessionToken:""}),a}})),l=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!e.token&&s&&(e.token=m()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.9"}),e},h.me=async(...e)=>{var t;const n=await f.me(...e);if(n.ok){const e=await(null===(t=n.response)||void 0===t?void 0:t.clone().json());p.update(e)}return n},(n||s)&&(u=(t,a)=>{!async function(t,n,s,a){try{if(401===n.status)return s.sessionToken.update({sessionToken:""}),void s.user.update({});const i=await(null==n?void 0:n.json());if(i){const n=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:r,refreshJwt:o,user:c}=n,l=e.__rest(n,["sessionJwt","refreshJwt","user"]);a.persistTokens&&_(r,o,l),r&&s.sessionToken.update({sessionToken:r}),c&&s.user.update(c),r&&o&&a.autoRefresh&&y(t,r,o)}}catch(e){console.error("Could not set tokens from body",e)}}(h.refresh,a,{sessionToken:g,user:p},{autoRefresh:n,persistTokens:s})}),n&&m()&&h.refresh(),h):(console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),h)};
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../../src/constants.ts","../../src/helpers.ts","../../src/fp.ts","../../src/state.ts","../../src/tokens.ts","../../src/webauthn.ts","../../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\n/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n\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\tsessionToken.update({ sessionToken: '' });\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\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\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","me","ok","body","json","_","status","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,EAAAF,IAAAC,KAA+B,CAAA,GAE/BE,EAAAH,IAAAC,KAAS,GAGRG,EAAAA,uBAAAH,KAAIF,EAAUD,EAAI,IAClB,CAEGO,cACH,OAAOb,EAAMc,EAAAA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,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,CErBGoL,CACCtC,EAAOuC,QACPxL,EACA,CAAEyI,eAAc7C,QAChB,CAAEoC,cAAaC,iBACf,GAICD,GAEHiB,EAAOuC,UAGDvC,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":["const FINGERPRINT_PUBLIC_KEY = 'fingerprint.public.key';\nconst FINGERPRINT_ENDPOINT_URL = 'fingerprint.endpoint.url';\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n/** Fingerprint.js identity key */\nexport const FP_KEY =\n\t(IS_BROWSER && localStorage.getItem(FINGERPRINT_PUBLIC_KEY)) || 'A9aCLRHzKCv3uL69oqDr';\n/** Fingerprint.js custom API endpoint */\nexport const FP_EP_URL =\n\t(IS_BROWSER && localStorage?.getItem(FINGERPRINT_ENDPOINT_URL)) || 'https://fp.descope.com';\n/** 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, FP_EP_URL, 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, endpoint: FP_EP_URL });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\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\t/** Checks if the browser supports WebAuthn,\n\t\t * and can optionally require in addition that The browser supports WebAuthn with built-in biometrics */\n\t\tisSupported\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\nasync function isSupported(requirePlatformAuthenticator: boolean = false): Promise<boolean> {\n\tconst supported = !!(\n\t\tPublicKeyCredential &&\n\t\tnavigator.credentials &&\n\t\tnavigator.credentials.create &&\n\t\tnavigator.credentials.get\n\t);\n\tif (\n\t\tsupported &&\n\t\trequirePlatformAuthenticator &&\n\t\tPublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n\t) {\n\t\treturn PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n\t}\n\treturn supported;\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport { IS_BROWSER, 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\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 (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\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 (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server'\n\t\t);\n\t\treturn webSdk;\n\t}\n\n\tif (autoRefresh) {\n\t\t// Make it easier for Descoper to just call logout/logoutAll without parameters,\n\t\t// In case this is a dev env and refresh is stored in localStorage\n\t\t['logout', 'logoutAll'].forEach((fnName) => {\n\t\t\tconst originFn = coreSdk[fnName] as Function;\n\t\t\twebSdk[fnName] = (...args: any) => {\n\t\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t\tconst token = args?.shift();\n\t\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\t\tconst res = originFn(...logoutArgs);\n\t\t\t\tclearTokens();\n\t\t\t\tsessionToken.update({ sessionToken: '' });\n\t\t\t\treturn res;\n\t\t\t};\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\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\tif (getRefreshToken()) {\n\t\t\t// refresh on init is done after afterRequestHook is configured\n\t\t\twebSdk.refresh();\n\t\t}\n\t}\n\n\treturn webSdk;\n};\n"],"names":["IS_BROWSER","window","FP_KEY","localStorage","getItem","FP_EP_URL","getQueryParam","param","Proxy","URLSearchParams","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","endpoint","async","sessionId","sessionStorage","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","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","isSupported","requirePlatformAuthenticator","supported","PublicKeyCredential","isUserVerifyingPlatformAuthenticatorAvailable","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","fnName","originFn","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","me","ok","body","json","_","status","authInfo","extractJWTResponse","handleDescopeTokens","refresh"],"mappings":"qOAAA,MAIaA,EAA+B,oBAAXC,OAEpBC,EACXF,GAAcG,aAAaC,QAPE,2BAOkC,uBAEpDC,EACXL,IAAc,OAAAG,uBAAAA,oBAAAA,aAAcC,QATG,8BASmC,yBCAvDE,EAAiBC,GARd,IAAIC,MAAM,IAAIC,gBAAgBR,OAAOS,SAASC,QAAS,CACrEC,IAAK,CAACC,EAAcC,IAASD,EAAaD,IAAIE,EAAKC,cAUtCR,GCRTS,EAAMC,IACX,MAAMC,EAASC,EAAIA,KAAC,CAAEC,OAAQH,GAASf,EAAQmB,SAAUhB,IAEzD,MAAO,CACNO,IAAKU,UACJ,IACC,IAAIC,EAAYC,eAAepB,QFCK,QEA/BmB,IACJA,EAAYjB,EFDuB,SEI/BiB,IACJA,GDGHE,KAAKC,MAAMX,SAAS,IACpBY,KAAKC,SAASb,SAAS,IAAIc,UAAU,GACrCF,KAAKC,SAASb,SAAS,IAAIc,UAAU,IACpCA,UAAU,EAAG,KCHZL,eAAeM,QFRqB,OEQaP,GAEjD,MAAMQ,QAAcb,EACdc,QAAYD,EAAMnB,IAAI,CAAEqB,SAAUV,IACxCC,eAAeM,QFVqB,OEUaE,EAAIE,UAOrD,CANC,MAAOC,GAEJC,OAAOC,UAEVC,QAAQC,MAAMJ,EAEf,GAEF,gBC5BF,MAmBMK,EAASC,GACdC,OAAAC,OAAA,CAAA,EAAYF,GAGb,MAAM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,eACN4D,EACAlD,EACAS,EACA4E,GAEA,IACC,GAAmB,MAAfrF,EAAIwL,OAIP,OAFA/K,EAAMmI,aAAarH,OAAO,CAAEqH,aAAc,UAC1CnI,EAAMkF,KAAKpE,OAAO,CAAA,GAGnB,MAAM8J,QAAarL,aAAG,EAAHA,EAAKsL,QACxB,GAAID,EAAM,CACT,MAAMxF,EA3BT,SAA4BwF,GAE3B,OAAOA,aAAA,EAAAA,EAAMI,WAAYJ,GAAS,CAAA,CACnC,CAwB6DK,CAAmBL,IAAvElI,WAAEA,EAAUmB,WAAEA,EAAUqB,KAAEA,GAAkDE,EAAzCtB,EAAnC+D,EAAAA,OAAAzC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ+C,eACX/D,EAAiBlB,EAAYmB,EAAYC,GAItCpB,GACH1C,EAAMmI,aAAarH,OAAO,CAAEqH,aAAczF,IAEvCwC,GACHlF,EAAMkF,KAAKpE,OAAOoE,GAIfxC,GAAcmB,GAAce,EAAQ8C,aACvClF,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CEZGwL,CACCvC,EAAOwC,QACP5L,EACA,CAAE4I,eAAcjD,QAChB,CAAEwC,cAAaC,iBACf,GAICD,GACChD,KAEHiE,EAAOwC,UAIFxC,IA/DN9I,QAAQkI,KACP,wIAEMY,EA4DK"}
|
package/dist/index.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs)
|
|
|
26
26
|
helpers: {
|
|
27
27
|
create: (options: string) => Promise<string>;
|
|
28
28
|
get: (options: string) => Promise<string>;
|
|
29
|
+
isSupported: (requirePlatformAuthenticator?: boolean) => Promise<boolean>;
|
|
29
30
|
};
|
|
30
31
|
};
|
|
31
32
|
onSessionTokenChange: (cb: (sessionToken: string) => void) => () => void;
|
|
@@ -112,47 +113,22 @@ declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs)
|
|
|
112
113
|
whatsapp: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
113
114
|
};
|
|
114
115
|
};
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
phone?: string;
|
|
132
|
-
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
|
|
133
|
-
sms: (identifier: string, uri: string, user?: {
|
|
134
|
-
email?: string;
|
|
135
|
-
name?: string;
|
|
136
|
-
phone?: string;
|
|
137
|
-
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
|
|
138
|
-
whatsapp: (identifier: string, uri: string, user?: {
|
|
139
|
-
email?: string;
|
|
140
|
-
name?: string;
|
|
141
|
-
phone?: string;
|
|
142
|
-
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
|
|
143
|
-
};
|
|
144
|
-
waitForSession: (pendingRef: string, config?: {
|
|
145
|
-
pollingIntervalMs: number;
|
|
146
|
-
timeoutMs: number;
|
|
147
|
-
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
148
|
-
update: {
|
|
149
|
-
email: (identifier: string, email: string, uri: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
150
|
-
phone: {
|
|
151
|
-
email: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
152
|
-
sms: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
153
|
-
whatsapp: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
154
|
-
};
|
|
155
|
-
};
|
|
116
|
+
};
|
|
117
|
+
enchantedLink: {
|
|
118
|
+
verify: (token: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
119
|
+
signIn: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
|
|
120
|
+
signUpOrIn: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
|
|
121
|
+
signUp: (identifier: string, uri: string, user?: {
|
|
122
|
+
email?: string;
|
|
123
|
+
name?: string;
|
|
124
|
+
phone?: string;
|
|
125
|
+
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
|
|
126
|
+
waitForSession: (pendingRef: string, config?: {
|
|
127
|
+
pollingIntervalMs: number;
|
|
128
|
+
timeoutMs: number;
|
|
129
|
+
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
130
|
+
update: {
|
|
131
|
+
email: (identifier: string, email: string, uri: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
|
|
156
132
|
};
|
|
157
133
|
};
|
|
158
134
|
oauth: {
|
|
@@ -205,8 +181,9 @@ declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs)
|
|
|
205
181
|
phone?: string;
|
|
206
182
|
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.TOTPResponse>>;
|
|
207
183
|
verify: (identifier: string, code: string, loginOptions?: {
|
|
208
|
-
stepup
|
|
209
|
-
|
|
184
|
+
stepup?: boolean;
|
|
185
|
+
mfa?: boolean;
|
|
186
|
+
customClaims?: Map<string, any>;
|
|
210
187
|
}, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
211
188
|
update: (identifier: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.TOTPResponse>>;
|
|
212
189
|
};
|
|
@@ -214,12 +191,20 @@ declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs)
|
|
|
214
191
|
start: (flowId: string, options?: {
|
|
215
192
|
redirectUrl?: string;
|
|
216
193
|
tenant?: string;
|
|
194
|
+
deviceInfo?: {
|
|
195
|
+
webAuthnSupport?: boolean;
|
|
196
|
+
};
|
|
197
|
+
lastUser?: {
|
|
198
|
+
authMethod?: "otp" | "totp" | "webauthn" | "magiclink" | "social" | "sso";
|
|
199
|
+
oauthProvider?: string;
|
|
200
|
+
externalId?: string;
|
|
201
|
+
};
|
|
217
202
|
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.FlowResponse>>;
|
|
218
203
|
next: (executionId: string, stepId: string, interactionId: string, input?: Record<string, FormDataEntryValue>) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.FlowResponse>>;
|
|
219
204
|
};
|
|
220
205
|
refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
221
206
|
logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
222
|
-
|
|
207
|
+
logoutAll: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
223
208
|
me: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<UserResponse>>;
|
|
224
209
|
isJwtExpired: (token: string) => boolean;
|
|
225
210
|
getJwtPermissions: (token: string, tenant?: string) => string[];
|
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
|
|
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="undefined"!=typeof window,r=o&&localStorage.getItem("fingerprint.public.key")||"A9aCLRHzKCv3uL69oqDr",c=o&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",l=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],u=e=>{const t=a({apiKey:e||r,endpoint:c});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=l("vsid")),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",e);const n=await t,s=await n.get({linkedId:e});sessionStorage.setItem("vrid",s.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var d,g,p,f,h;const w=e=>Object.assign({},e);class b{constructor(t){d.add(this),g.set(this,void 0),p.set(this,{}),f.set(this,0),e(this,g,t,"f")}get current(){return w(t(this,g,"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,g,"f"),s)){const n=t(this,g,"f");e(this,g,s,"f"),Object.freeze(t(this,g,"f")),setTimeout((()=>{Object.values(t(this,p,"f")).forEach((e=>e(w(s),n)))}),0)}}subscribe(n){e(this,f,t(this,f,"f")+1,"f"),t(this,p,"f")[t(this,f,"f")]=n;const s=t(this,f,"f");return()=>t(this,d,"m",h).call(this,s.toString())}unsubscribeAll(){e(this,p,{},"f")}}g=new WeakMap,p=new WeakMap,f=new WeakMap,d=new WeakSet,h=function(e){!!t(this,p,"f")[e]&&delete t(this,p,"f")[e]};let v=[];function m(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=v.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),a);v.push(i)}}function y(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 S(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function k(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),n.publicKey.user.id=I(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.create(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:T(s.rawId),response:Object.assign(Object.assign({},s.response),{attestationObject:T(s.response.attestationObject),clientDataJSON:T(s.response.clientDataJSON)})}));var s}async function O(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=I(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=I(e.id)})),n}(e),n=await navigator.credentials.get(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:T(s.rawId),response:Object.assign(Object.assign({},s.response),{authenticatorData:T(s.response.authenticatorData),clientDataJSON:T(s.response.clientDataJSON),signature:T(s.response.signature),userHandle:s.response.userHandle?T(s.response.userHandle):void 0})}));var s}async function j(e=!1){const t=!!(PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function I(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function T(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var D=e=>{var{autoRefresh:t=!0,persistTokens:a=!0}=e,r=n(e,["autoRefresh","persistTokens"]);o?u(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 l,d;const g=new b({sessionToken:""}),p=new b({});c.hooks={beforeRequest:e=>null==l?void 0:l(e),afterRequest:(e,t)=>null==d?void 0:d(e,t)};const f=s(c),h=Object.assign(Object.assign({},f),{webauthn:(w=f,{async signUp(e,t){const n=await w.webauthn.signUp.start(e,window.location.origin,t),s=await k(n.data.options);return await w.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await w.webauthn.signIn.start(e,window.location.origin),n=await O(t.data.options);return await w.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await w.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await k(n.data.options);return await w.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await O(n.data.options);return await w.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await w.webauthn.update.start(e,window.location.origin,t),s=await k(n.data.options);return await w.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:k,get:O,isSupported:j}}),onSessionTokenChange:e=>{var t;const n=null===(t=g.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),g.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=p.current;return t&&Object.entries(t).length>0&&e(t),p.subscribe((t=>{e(t)}))}});var w;return o?(t&&["logout","logoutAll"].forEach((e=>{const t=f[e];h[e]=(...e)=>{const n=S(),s=[(null==e?void 0:e.shift())||n,...e],a=t(...s);return localStorage&&localStorage.removeItem("DSR"),i.remove("DS"),g.update({sessionToken:""}),a}})),l=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!e.token&&a&&(e.token=S()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.9"}),e},h.me=async(...e)=>{var t;const n=await f.me(...e);if(n.ok){const e=await(null===(t=n.response)||void 0===t?void 0:t.clone().json());p.update(e)}return n},(t||a)&&(d=(e,s)=>{!async function(e,t,s,a){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,l=n(t,["sessionJwt","refreshJwt","user"]);a.persistTokens&&y(o,r,l),o&&s.sessionToken.update({sessionToken:o}),c&&s.user.update(c),o&&r&&a.autoRefresh&&m(e,o,r)}}catch(e){console.error("Could not set tokens from body",e)}}(h.refresh,s,{sessionToken:g,user:p},{autoRefresh:t,persistTokens:a})}),t&&S()&&h.refresh(),h):(console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),h)};export{D as default};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|
package/dist/index.esm.js.map
CHANGED
|
@@ -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 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\tsessionToken.update({ sessionToken: '' });\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\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\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","me","ok","body","json","_","status","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,eAAe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,EAAMiI,aAAanH,OAAO,CAAEmH,aAAc,UAC1CjI,EAAMmF,KAAKrE,OAAO,CAAA,GAGnB,MAAM2J,QAAalL,aAAG,EAAHA,EAAKmL,QACxB,GAAID,EAAM,CACT,MAAMpF,EA3BT,SAA4BoF,GAE3B,OAAOA,aAAA,EAAAA,EAAMI,WAAYJ,GAAS,CAAA,CACnC,CAwB6DK,CAAmBL,IAAvE/H,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,CErBGqL,CACCtC,EAAOuC,QACPzL,EACA,CAAE0I,eAAc9C,QAChB,CAAEqC,cAAaC,iBACf,GAICD,GAEHiB,EAAOuC,UAGDvC,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":["const FINGERPRINT_PUBLIC_KEY = 'fingerprint.public.key';\nconst FINGERPRINT_ENDPOINT_URL = 'fingerprint.endpoint.url';\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n/** Fingerprint.js identity key */\nexport const FP_KEY =\n\t(IS_BROWSER && localStorage.getItem(FINGERPRINT_PUBLIC_KEY)) || 'A9aCLRHzKCv3uL69oqDr';\n/** Fingerprint.js custom API endpoint */\nexport const FP_EP_URL =\n\t(IS_BROWSER && localStorage?.getItem(FINGERPRINT_ENDPOINT_URL)) || 'https://fp.descope.com';\n/** 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, FP_EP_URL, 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, endpoint: FP_EP_URL });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\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\t/** Checks if the browser supports WebAuthn,\n\t\t * and can optionally require in addition that The browser supports WebAuthn with built-in biometrics */\n\t\tisSupported\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\nasync function isSupported(requirePlatformAuthenticator: boolean = false): Promise<boolean> {\n\tconst supported = !!(\n\t\tPublicKeyCredential &&\n\t\tnavigator.credentials &&\n\t\tnavigator.credentials.create &&\n\t\tnavigator.credentials.get\n\t);\n\tif (\n\t\tsupported &&\n\t\trequirePlatformAuthenticator &&\n\t\tPublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n\t) {\n\t\treturn PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n\t}\n\treturn supported;\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport { IS_BROWSER, 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\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 (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\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 (!IS_BROWSER) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server'\n\t\t);\n\t\treturn webSdk;\n\t}\n\n\tif (autoRefresh) {\n\t\t// Make it easier for Descoper to just call logout/logoutAll without parameters,\n\t\t// In case this is a dev env and refresh is stored in localStorage\n\t\t['logout', 'logoutAll'].forEach((fnName) => {\n\t\t\tconst originFn = coreSdk[fnName] as Function;\n\t\t\twebSdk[fnName] = (...args: any) => {\n\t\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t\tconst token = args?.shift();\n\t\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\t\tconst res = originFn(...logoutArgs);\n\t\t\t\tclearTokens();\n\t\t\t\tsessionToken.update({ sessionToken: '' });\n\t\t\t\treturn res;\n\t\t\t};\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\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\tif (getRefreshToken()) {\n\t\t\t// refresh on init is done after afterRequestHook is configured\n\t\t\twebSdk.refresh();\n\t\t}\n\t}\n\n\treturn webSdk;\n};\n"],"names":["IS_BROWSER","window","FP_KEY","localStorage","getItem","FP_EP_URL","getQueryParam","param","Proxy","URLSearchParams","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","endpoint","async","sessionId","sessionStorage","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","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","isSupported","requirePlatformAuthenticator","supported","PublicKeyCredential","isUserVerifyingPlatformAuthenticatorAvailable","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","index","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","fnName","originFn","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","me","ok","body","json","_","status","authInfo","extractJWTResponse","handleDescopeTokens","refresh"],"mappings":"4MAAA,MAIaA,EAA+B,oBAAXC,OAEpBC,EACXF,GAAcG,aAAaC,QAPE,2BAOkC,uBAEpDC,EACXL,IAAc,OAAAG,uBAAAA,oBAAAA,aAAcC,QATG,8BASmC,yBCAvDE,EAAiBC,GARd,IAAIC,MAAM,IAAIC,gBAAgBR,OAAOS,SAASC,QAAS,CACrEC,IAAK,CAACC,EAAcC,IAASD,EAAaD,IAAIE,EAAKC,cAUtCR,GCRTS,EAAMC,IACX,MAAMC,EAASC,EAAK,CAAEC,OAAQH,GAASf,EAAQmB,SAAUhB,IAEzD,MAAO,CACNO,IAAKU,UACJ,IACC,IAAIC,EAAYC,eAAepB,QFCK,QEA/BmB,IACJA,EAAYjB,EFDuB,SEI/BiB,IACJA,GDGHE,KAAKC,MAAMX,SAAS,IACpBY,KAAKC,SAASb,SAAS,IAAIc,U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