@descope/node-sdk 1.0.4-alpha.6 → 1.0.4-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,7 +14,7 @@ npm i --save @descope/node-sdk
14
14
 
15
15
  ## What do you want to implement?
16
16
 
17
- Click one of the following links to open the documentation for that specific functionality.
17
+ Click one of the following links to open the documentation for that specific functionality.
18
18
 
19
19
  - [x] [One time passwords (OTP)](./docs/otp.md)
20
20
  - [x] [Magic Links](./docs/magiclink.md)
@@ -26,7 +26,7 @@ Instantly run the end-to-end ExpresSDK for NodeJS examples, as shown below. The
26
26
 
27
27
  ### Prerequisites
28
28
 
29
- Run the following commands in your project. Replace any instance of `<ProjectID>` in the code below with your company's Project ID, which can be found in the [Descope console](https://app.descope.com).
29
+ Run the following commands in your project. Replace any instance of `<ProjectID>` in the code below with your company's Project ID, which can be found in the [Descope console](https://app.descope.com).
30
30
 
31
31
  This commands will add the Descope NodeJS SDK as a project dependency, clone the SDK repository locally, and set the `DESCOPE_PROJECT_ID`.
32
32
 
@@ -40,25 +40,28 @@ export DESCOPE_PROJECT_ID=<ProjectID>
40
40
  **TL;DR**: Run `npm run quick`
41
41
 
42
42
  Run the following commands in the root of the project to build and run the examples.
43
+
43
44
  1. Run this to start the ES6 typescript module example
44
45
 
45
- ```code bash
46
- npm i
47
- npm run build
48
- cd examples/es6
49
- npm i
50
- npm start
51
- ```
46
+ ```code bash
47
+ npm i && \
48
+ npm run build && \
49
+ cd examples/es6 && \
50
+ npm i && \
51
+ npm run generateCerts && \
52
+ npm start
53
+ ```
52
54
 
53
55
  2. Run this to start the commonjs example
54
56
 
55
- ```code bash
56
- npm i
57
- npm run build
58
- cd examples/commonjs
59
- npm i
60
- npm start
61
- ```
57
+ ```code bash
58
+ npm i && \
59
+ npm run build && \
60
+ cd examples/commonjs && \
61
+ npm i && \
62
+ npm run generateCerts && \
63
+ npm start
64
+ ```
62
65
 
63
66
  ## License
64
67
 
@@ -0,0 +1 @@
1
+ export {};
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("@descope/core-js-sdk"),t=require("jose"),s=require("node-fetch"),i=require("tslib");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=o(e),r=o(s);const n=(e,t,s)=>`${e}=${t}; Domain=${(null==s?void 0:s.cookieDomain)||""}; Max-Age=${(null==s?void 0:s.cookieMaxAge)||""}; Path=${(null==s?void 0:s.cookiePath)||"/"}; HttpOnly; SameSite=Strict`,c=e=>async(...t)=>{var s,o,a;const r=await e(...t);if(!r.data)return r;let c=r.data,{sessionJwt:l,refreshJwt:h}=c,d=i.__rest(c,["sessionJwt","refreshJwt"]);const u=[n("DS",l,d)];return h?u.push(n("DSR",h,d)):(null===(s=r.response)||void 0===s?void 0:s.headers.get("set-cookie"))&&(h=((e,t)=>{const s=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return s?s[1]:null})(null===(o=r.response)||void 0===o?void 0:o.headers.get("set-cookie"),"DSR"),u.push(null===(a=r.response)||void 0===a?void 0:a.headers.get("set-cookie"))),Object.assign(Object.assign({},r),{data:Object.assign(Object.assign({},r.data),{refreshJwt:h,cookies:u})})},l=(e,t,s)=>{if(!e)return;const i="string"==typeof t?t.split("."):t,o=i.shift()||"";if(0===i.length||"*"===o){const t=t=>{if(!t||"function"!=typeof e[t])throw Error(`cannot wrap value at key "${t.toString()}"`);e[t]=s(e[t])};"*"===o?Object.keys(e).forEach(t):t(o)}else l(e[o],i,s)};globalThis.fetch||(globalThis.fetch=r.default,globalThis.Headers=s.Headers,globalThis.Request=s.Request,globalThis.Response=s.Response);const h=(...e)=>{const s=a.default(...e);var i,o;i=s,o=c,["otp.verify.*","magicLink.verify","magicLink.crossDevice.signUp.*","magicLink.crossDevice.signIn.*","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"].forEach((e=>l(i,e,o)));const{projectId:r,logger:n}=e[0],h={};return Object.assign(Object.assign({},s),{async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(h[e.kid])return h[e.kid];if(Object.assign(h,await(async()=>{const e=await s.httpClient.get(`v1/keys/${r}`).then((e=>e.json()));return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await t.importJWK(e)])))).reduce(((e,[t,s])=>t?Object.assign(Object.assign({},e),{[t.toString()]:s}):e),{}):{}})()),!h[e.kid])throw Error("failed to fetch matching key");return h[e.kid]},async validateToken(e){return{token:(await t.jwtVerify(e,this.getKey,{algorithms:["ES384"]})).payload}},async validateSession(e,t){if(!e)throw Error("session token must not be empty");try{return await this.validateToken(e)}catch(e){try{return await this.validateToken(t),(await this.refresh(t)).data}catch(e){throw null==n||n.error("failed to validate refresh token",e),Error("could not validate tokens")}}}})};h.DeliveryMethods=a.default.DeliveryMethods,h.RefreshTokenCookieName="DSR",h.SessionTokenCookieName="DS",module.exports=h;
1
+ "use strict";var e=require("@descope/core-js-sdk"),t=require("jose"),s=require("node-fetch"),o=require("tslib");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var a=r(e),n=r(s);const i=(e,t,s)=>`${e}=${t}; Domain=${(null==s?void 0:s.cookieDomain)||""}; Max-Age=${(null==s?void 0:s.cookieMaxAge)||""}; Path=${(null==s?void 0:s.cookiePath)||"/"}; HttpOnly; SameSite=Strict`,c=e=>async(...t)=>{var s,r,a;const n=await e(...t);if(!n.data)return n;let c=n.data,{sessionJwt:l,refreshJwt:d}=c,u=o.__rest(c,["sessionJwt","refreshJwt"]);const h=[i("DS",l,u)];return d?h.push(i("DSR",d,u)):(null===(s=n.response)||void 0===s?void 0:s.headers.get("set-cookie"))&&(d=((e,t)=>{const s=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return s?s[1]:null})(null===(r=n.response)||void 0===r?void 0:r.headers.get("set-cookie"),"DSR"),h.push(null===(a=n.response)||void 0===a?void 0:a.headers.get("set-cookie"))),Object.assign(Object.assign({},n),{data:Object.assign(Object.assign({},n.data),{refreshJwt:d,cookies:h})})},l=(e,t,s)=>{if(!e)return;const o="string"==typeof t?t.split("."):t,r=o.shift()||"";if(0===o.length||"*"===r){const t=t=>{if(!t||"function"!=typeof e[t])throw Error(`cannot wrap value at key "${t.toString()}"`);e[t]=s(e[t])};"*"===r?Object.keys(e).forEach(t):t(r)}else l(e[r],o,s)};function d(e,t,s){var o,r;const a=s?null===(r=null===(o=e.token.tenants)||void 0===o?void 0:o[s])||void 0===r?void 0:r[t]:e.token[t];return Array.isArray(a)?a:[]}globalThis.fetch||(globalThis.fetch=n.default,globalThis.Headers=s.Headers,globalThis.Request=s.Request,globalThis.Response=s.Response);const u=(...e)=>{const s=[...e];s[0].hooks=s[0].hooks||{};const o=s[0].hooks.beforeRequest;s[0].hooks.beforeRequest=e=>{var t;const s=e;return s.headers=Object.assign(Object.assign({},s.headers),{"x-descope-sdk-name":"nodejs","x-descope-sdk-node-version":(null===(t=null===process||void 0===process?void 0:process.versions)||void 0===t?void 0:t.node)||"","x-descope-sdk-version":"1.0.4-alpha.7"}),(null==o?void 0:o(s))||s};const r=a.default(...s);var n,i;n=r,i=c,["otp.verify.*","magicLink.verify","magicLink.crossDevice.signUp.*","magicLink.crossDevice.signIn.*","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"].forEach((e=>l(n,e,i)));const{projectId:u,logger:h}=e[0],v={},f=Object.assign(Object.assign({},r),{async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(v[e.kid])return v[e.kid];if(Object.assign(v,await(async()=>{const e=await r.httpClient.get(`v1/keys/${u}`).then((e=>e.json()));return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await t.importJWK(e)])))).reduce(((e,[t,s])=>t?Object.assign(Object.assign({},e),{[t.toString()]:s}):e),{}):{}})()),!v[e.kid])throw Error("failed to fetch matching key");return v[e.kid]},validateJwt:async e=>({jwt:e,token:(await t.jwtVerify(e,f.getKey,{issuer:u,clockTolerance:5})).payload}),async validateSession(e,t){var s,o;if(!e&&!t)throw Error("both refresh token and session token are empty");if(e)try{return await f.validateJwt(e)}catch(e){if(!t)throw null==h||h.error("failed to validate session token and no refresh token provided",e),Error("could not validate tokens")}if(t)try{await f.validateJwt(t);const e=await f.refresh(t);if(e.ok){return await f.validateJwt(null===(s=e.data)||void 0===s?void 0:s.sessionJwt)}throw Error(null===(o=e.error)||void 0===o?void 0:o.message)}catch(e){throw null==h||h.error("failed to validate refresh token",e),Error("could not validate tokens")}throw Error("could not validate token")},async exchangeAccessKey(e){if(!e)throw Error("access key must not be empty");let t;try{t=await f.accessKey.exchange(e)}catch(e){throw null==h||h.error("failed to exchange access key",e),Error("could not exchange access key")}const{sessionJwt:s}=t.data;if(!s)throw null==h||h.error("failed to parse exchange access key response"),Error("could not exchange access key");try{return await f.validateJwt(s)}catch(e){throw null==h||h.error("failed to parse jwt from access key",e),Error("could not exchange access key")}},validatePermissions:(e,t)=>f.validateTenantPermissions(e,null,t),validateTenantPermissions(e,t,s){const o=d(e,"permissions",t);return s.every((e=>o.includes(e)))},validateRoles:(e,t)=>f.validateTenantRoles(e,null,t),validateTenantRoles(e,t,s){const o=d(e,"roles",t);return s.every((e=>o.includes(e)))}});return f};u.DeliveryMethods=a.default.DeliveryMethods,u.RefreshTokenCookieName="DSR",u.SessionTokenCookieName="DS",module.exports=u;
2
2
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../../lib/constants.ts","../../lib/helpers.ts","../../lib/index.ts"],"sourcesContent":["// eslint-disable-next-line import/prefer-default-export\nexport const refreshTokenCookieName = 'DSR'\nexport const sessionTokenCookieName = 'DS'\n","import type { SdkResponse } from '@descope/core-js-sdk'\nimport { refreshTokenCookieName, sessionTokenCookieName } from './constants'\n\nconst generateCookie = (name: string, value: string, options?: any) =>\n `${name}=${value}; Domain=${options?.cookieDomain || ''}; Max-Age=${\n options?.cookieMaxAge || ''\n }; Path=${options?.cookiePath || '/'}; HttpOnly; SameSite=Strict`\n\nconst getCookieValue = (cookie: string | null | undefined, name: string) => {\n const match = cookie?.match(RegExp(`(?:^|;\\\\s*)${name}=([^;]*)`))\n return match ? match[1] : null\n}\n\n// eslint-disable-next-line import/prefer-default-export\nexport const withCookie =\n <T extends Array<any>, U extends Promise<SdkResponse>>(fn: (...args: T) => U) =>\n async (...args: T): Promise<SdkResponse> => {\n const resp = await fn(...args)\n\n if (!resp.data) {\n return resp\n }\n\n // eslint-disable-next-line prefer-const\n let { sessionJwt, refreshJwt, ...rest } = resp.data\n const cookies = [generateCookie(sessionTokenCookieName, sessionJwt, rest)]\n\n if (!refreshJwt) {\n if (resp.response?.headers.get('set-cookie')) {\n refreshJwt = getCookieValue(\n resp.response?.headers.get('set-cookie'),\n refreshTokenCookieName,\n )\n cookies.push(resp.response?.headers.get('set-cookie')!)\n }\n } else {\n cookies.push(generateCookie(refreshTokenCookieName, refreshJwt, rest))\n }\n\n return { ...resp, data: { ...resp.data, refreshJwt, cookies } }\n }\n\nexport const wrapWith = <T extends Record<string, any>>(\n obj: T,\n path: string | string[],\n wrappingFn: Function,\n // eslint-disable-next-line consistent-return\n): void => {\n if (!obj) return\n\n const pathSections = typeof path === 'string' ? path.split('.') : path\n const section = pathSections.shift() || ('' as keyof T)\n\n if (pathSections.length === 0 || section === '*') {\n const wrap = (key: keyof T) => {\n if (key && typeof obj[key] === 'function') {\n // eslint-disable-next-line no-param-reassign\n obj[key] = wrappingFn(obj[key])\n } else {\n throw Error(`cannot wrap value at key \"${key.toString()}\"`)\n }\n }\n if (section === '*') {\n Object.keys(obj).forEach(wrap)\n } else {\n wrap(section)\n }\n } else {\n wrapWith(obj[section], pathSections, wrappingFn)\n }\n}\n\nexport const bulkWrapWith = (\n obj: Parameters<typeof wrapWith>[0],\n paths: string[],\n wrappingFn: Parameters<typeof wrapWith>[2],\n) => paths.forEach((path: string) => wrapWith(obj, path, wrappingFn))\n","import createSdk from '@descope/core-js-sdk'\nimport { KeyLike, jwtVerify, JWK, JWTHeaderParameters, importJWK } from 'jose'\nimport fetch, { Headers, Response, Request } from 'node-fetch'\nimport { bulkWrapWith, withCookie } from './helpers'\nimport { AuthenticationInfo } from './types'\nimport { refreshTokenCookieName, sessionTokenCookieName } from './constants'\n\nif (!globalThis.fetch) {\n // @ts-ignore\n globalThis.fetch = fetch\n // @ts-ignore\n globalThis.Headers = Headers\n // @ts-ignore\n globalThis.Request = Request\n // @ts-ignore\n globalThis.Response = Response\n}\n\nconst sdk = (...args: Parameters<typeof createSdk>) => {\n const coreSdk = createSdk(...args)\n\n bulkWrapWith(\n coreSdk,\n [\n 'otp.verify.*',\n 'magicLink.verify',\n 'magicLink.crossDevice.signUp.*',\n 'magicLink.crossDevice.signIn.*',\n 'oauth.exchange',\n 'saml.exchange',\n 'totp.verify',\n 'webauthn.signIn.finish',\n 'webauthn.signUp.finish',\n 'refresh',\n ],\n withCookie,\n )\n\n const { projectId, logger } = args[0]\n\n const keys: Record<string, KeyLike | Uint8Array> = {}\n\n const fetchKeys = async () => {\n const publicKeys: JWK[] = await coreSdk.httpClient\n .get(`v1/keys/${projectId}`)\n .then((resp) => resp.json())\n if (!Array.isArray(publicKeys)) return {}\n const kidJwksPairs = await Promise.all(\n publicKeys.map(async (key) => [key.kid, await importJWK(key)]),\n )\n\n return kidJwksPairs.reduce(\n (acc, [kid, jwk]) => (kid ? { ...acc, [kid.toString()]: jwk } : acc),\n {},\n )\n }\n\n return {\n ...coreSdk,\n\n async getKey(header: JWTHeaderParameters): Promise<KeyLike | Uint8Array> {\n if (!header?.kid) throw Error('header.kid must not be empty')\n\n if (keys[header.kid]) return keys[header.kid]\n\n // do we need to fetch once or every time?\n Object.assign(keys, await fetchKeys())\n\n if (!keys[header.kid]) throw Error('failed to fetch matching key')\n\n return keys[header.kid]\n },\n\n async validateToken(token: string): Promise<AuthenticationInfo> {\n const res = await jwtVerify(token, this.getKey, { algorithms: ['ES384'] })\n\n return { token: res.payload }\n },\n\n async validateSession(\n sessionToken: string,\n refreshToken: string,\n ): Promise<AuthenticationInfo | undefined> {\n if (!sessionToken) throw Error('session token must not be empty')\n\n try {\n const token = await this.validateToken(sessionToken)\n return token\n } catch (error) {\n try {\n await this.validateToken(refreshToken)\n\n return (await this.refresh(refreshToken)).data\n } catch (refreshTokenErr) {\n logger?.error('failed to validate refresh token', refreshTokenErr)\n\n throw Error('could not validate tokens')\n }\n }\n },\n }\n}\n\nconst sdkWithAttributes = sdk as typeof sdk & {\n DeliveryMethods: typeof createSdk.DeliveryMethods\n RefreshTokenCookieName: typeof refreshTokenCookieName\n SessionTokenCookieName: typeof sessionTokenCookieName\n}\n\nsdkWithAttributes.DeliveryMethods = createSdk.DeliveryMethods\nsdkWithAttributes.RefreshTokenCookieName = refreshTokenCookieName\nsdkWithAttributes.SessionTokenCookieName = sessionTokenCookieName\n\nexport default sdkWithAttributes\n\nexport type { DeliveryMethod, OAuthProvider } from '@descope/core-js-sdk'\n"],"names":["generateCookie","name","value","options","cookieDomain","cookieMaxAge","cookiePath","withCookie","fn","async","args","resp","data","_d","sessionJwt","refreshJwt","rest","__rest","cookies","push","_a","response","headers","get","cookie","match","RegExp","getCookieValue","_b","_c","Object","assign","wrapWith","obj","path","wrappingFn","pathSections","split","section","shift","length","wrap","key","Error","toString","keys","forEach","globalThis","fetch","Headers","Request","Response","sdkWithAttributes","coreSdk","createSdk","projectId","logger","header","kid","publicKeys","httpClient","then","json","Array","isArray","Promise","all","map","importJWK","reduce","acc","jwk","fetchKeys","token","jwtVerify","this","getKey","algorithms","payload","sessionToken","refreshToken","validateToken","error","refresh","refreshTokenErr","DeliveryMethods","RefreshTokenCookieName","SessionTokenCookieName"],"mappings":"0MACO,MCEDA,EAAiB,CAACC,EAAcC,EAAeC,IACnD,GAAGF,KAAQC,cAAiBC,aAAA,EAAAA,EAASC,eAAgB,gBACnDD,aAAA,EAAAA,EAASE,eAAgB,aACjBF,a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AAEC,WAAY,CAAC,YAE3CC,QACrB,EAEDrE,sBACEsE,EACAC,GAEA,IAAKD,EAAc,MAAMpC,MAAM,mCAE/B,IAEE,aADoBgC,KAAKM,cAAcF,EAYxC,CAVC,MAAOG,GACP,IAGE,aAFMP,KAAKM,cAAcD,UAEXL,KAAKQ,QAAQH,IAAepE,IAK3C,CAJC,MAAOwE,GAGP,MAFA5B,SAAAA,EAAQ0B,MAAM,mCAAoCE,GAE5CzC,MAAM,4BACb,CACF,CACF,GACF,EASHS,EAAkBiC,gBAAkB/B,EAAS,QAAC+B,gBAC9CjC,EAAkBkC,uBF7GoB,ME8GtClC,EAAkBmC,uBF7GoB"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../../lib/constants.ts","../../lib/helpers.ts","../../lib/index.ts"],"sourcesContent":["// eslint-disable-next-line import/prefer-default-export\n/** Refresh JWT cookie name */\nexport const refreshTokenCookieName = 'DSR';\n/** Session JWT cookie name */\nexport const sessionTokenCookieName = 'DS';\n/** The key of the tenants claims in the claims map */\nexport const authorizedTenantsClaimName = 'tenants';\n/** The key of the permissions claims in the claims map either under tenant or top level */\nexport const permissionsClaimName = 'permissions';\n/** The key of the roles claims in the claims map either under tenant or top level */\nexport const rolesClaimName = 'roles';\n","import type { ResponseData, SdkResponse } from '@descope/core-js-sdk';\nimport { AuthenticationInfo } from './types';\nimport {\n refreshTokenCookieName,\n sessionTokenCookieName,\n authorizedTenantsClaimName,\n} from './constants';\n\n/**\n * Generate a cookie string from given parameters\n * @param name name of the cookie\n * @param value value of cookie that must be already encoded\n * @param options any options to put on the cookie like cookieDomain, cookieMaxAge, cookiePath\n * @returns Cookie string with all options on the string\n */\nconst generateCookie = (name: string, value: string, options?: Record<string, string | number>) =>\n `${name}=${value}; Domain=${options?.cookieDomain || ''}; Max-Age=${\n options?.cookieMaxAge || ''\n }; Path=${options?.cookiePath || '/'}; HttpOnly; SameSite=Strict`;\n\n/**\n * Parse the cookie string and return the value of the cookie\n * @param cookie the raw cookie string\n * @param name the name of the cookie to get value for\n * @returns the value of the given cookie\n */\nconst getCookieValue = (cookie: string | null | undefined, name: string) => {\n const match = cookie?.match(RegExp(`(?:^|;\\\\s*)${name}=([^;]*)`));\n return match ? match[1] : null;\n};\n\n// eslint-disable-next-line import/prefer-default-export\n/**\n * Add cookie generation to core-js functions.\n * @param fn the function we are wrapping\n * @returns Wrapped function with cookie generation\n */\nexport const withCookie =\n <T extends Array<any>, U extends Promise<SdkResponse<ResponseData>>>(fn: (...args: T) => U) =>\n async (...args: T): Promise<SdkResponse<ResponseData>> => {\n const resp = await fn(...args);\n\n // istanbul ignore next\n if (!resp.data) {\n return resp;\n }\n\n // eslint-disable-next-line prefer-const\n let { sessionJwt, refreshJwt, ...rest } = resp.data;\n const cookies = [generateCookie(sessionTokenCookieName, sessionJwt, rest)];\n\n if (!refreshJwt) {\n if (resp.response?.headers.get('set-cookie')) {\n refreshJwt = getCookieValue(\n resp.response?.headers.get('set-cookie'),\n refreshTokenCookieName,\n );\n cookies.push(resp.response?.headers.get('set-cookie')!);\n }\n } else {\n cookies.push(generateCookie(refreshTokenCookieName, refreshJwt, rest));\n }\n\n return { ...resp, data: { ...resp.data, refreshJwt, cookies } };\n };\n\n/**\n * Wrap given object internal functions (can be deep inside the object) with the given wrapping function\n * @param obj we will deep wrap functions inside this object based on the given path\n * @param path the path of internal objects to walk before wrapping the final result. Path is collection of parts separated by '.' that support '*' to say all of the keys for the part.\n * @param wrappingFn function to wrap with\n * @returns void, we update the functions in place\n */\nexport const wrapWith = <T extends Record<string, any>>(\n obj: T,\n path: string | string[],\n wrappingFn: Function,\n // eslint-disable-next-line consistent-return\n): void => {\n if (!obj) return;\n\n const pathSections = typeof path === 'string' ? path.split('.') : path;\n const section = pathSections.shift() || ('' as keyof T);\n\n if (pathSections.length === 0 || section === '*') {\n const wrap = (key: keyof T) => {\n if (key && typeof obj[key] === 'function') {\n // eslint-disable-next-line no-param-reassign\n obj[key] = wrappingFn(obj[key]);\n } else {\n // istanbul ignore next\n throw Error(`cannot wrap value at key \"${key.toString()}\"`);\n }\n };\n if (section === '*') {\n Object.keys(obj).forEach(wrap);\n } else {\n wrap(section);\n }\n } else {\n wrapWith(obj[section], pathSections, wrappingFn);\n }\n};\n\n/**\n * Wrap given object internal functions (can be deep inside the object) with the given wrapping function based on multiple paths.\n * @param obj we will deep wrap functions inside this object based on the given paths\n * @param paths multiple paths of internal objects to walk before wrapping the final result. Path is collection of parts separated by '.' that support '*' to say all of the keys for the part.\n * @param wrappingFn function to wrap with\n * @returns void, we update the functions in place\n */\nexport const bulkWrapWith = (\n obj: Parameters<typeof wrapWith>[0],\n paths: string[],\n wrappingFn: Parameters<typeof wrapWith>[2],\n) => paths.forEach((path: string) => wrapWith(obj, path, wrappingFn));\n\n/**\n * Get the claim (used for permissions or roles) for a given tenant or top level if tenant is empty\n * @param authInfo The parsed authentication info from the JWT\n * @param claim name of the claim\n * @param tenant tenant to retrieve the claim for\n * @returns\n */\nexport function getAuthorizationClaimItems(\n authInfo: AuthenticationInfo,\n claim: string,\n tenant?: string,\n): string[] {\n const value = tenant\n ? authInfo.token[authorizedTenantsClaimName]?.[tenant]?.[claim]\n : authInfo.token[claim];\n return Array.isArray(value) ? value : [];\n}\n","import createSdk, {\n SdkResponse,\n ExchangeAccessKeyResponse,\n RequestConfig,\n} from '@descope/core-js-sdk';\nimport { KeyLike, jwtVerify, JWK, JWTHeaderParameters, importJWK } from 'jose';\nimport fetch, { Headers, Response, Request } from 'node-fetch';\nimport { bulkWrapWith, withCookie, getAuthorizationClaimItems } from './helpers';\nimport { AuthenticationInfo } from './types';\nimport {\n refreshTokenCookieName,\n sessionTokenCookieName,\n permissionsClaimName,\n rolesClaimName,\n} from './constants';\n\ndeclare const BUILD_VERSION: string;\n\n/* istanbul ignore next */\nif (!globalThis.fetch) {\n // @ts-ignore\n globalThis.fetch = fetch;\n // @ts-ignore\n globalThis.Headers = Headers;\n // @ts-ignore\n globalThis.Request = Request;\n // @ts-ignore\n globalThis.Response = Response;\n}\n\nconst nodeSdk = (...args: Parameters<typeof createSdk>) => {\n const funcArgs: typeof args = [...args];\n funcArgs[0].hooks = funcArgs[0].hooks || {};\n const origBeforeRequest = funcArgs[0].hooks.beforeRequest;\n funcArgs[0].hooks.beforeRequest = (config: RequestConfig) => {\n const conf = config;\n conf.headers = {\n ...conf.headers,\n 'x-descope-sdk-name': 'nodejs',\n 'x-descope-sdk-node-version': process?.versions?.node || '',\n 'x-descope-sdk-version': BUILD_VERSION,\n };\n return origBeforeRequest?.(conf) || conf;\n };\n const coreSdk = createSdk(...funcArgs);\n\n bulkWrapWith(\n coreSdk,\n [\n 'otp.verify.*',\n 'magicLink.verify',\n 'magicLink.crossDevice.signUp.*',\n 'magicLink.crossDevice.signIn.*',\n 'oauth.exchange',\n 'saml.exchange',\n 'totp.verify',\n 'webauthn.signIn.finish',\n 'webauthn.signUp.finish',\n 'refresh',\n ],\n withCookie,\n );\n\n const { projectId, logger } = args[0];\n\n const keys: Record<string, KeyLike | Uint8Array> = {};\n\n /** Fetch the public keys (JWKs) from Descope for the configured project */\n const fetchKeys = async () => {\n const publicKeys: JWK[] = await coreSdk.httpClient\n .get(`v1/keys/${projectId}`)\n .then((resp) => resp.json());\n if (!Array.isArray(publicKeys)) return {};\n const kidJwksPairs = await Promise.all(\n publicKeys.map(async (key) => [key.kid, await importJWK(key)]),\n );\n\n return kidJwksPairs.reduce(\n (acc, [kid, jwk]) => (kid ? { ...acc, [kid.toString()]: jwk } : acc),\n {},\n );\n };\n\n const sdk = {\n ...coreSdk,\n\n /** Get the key that can validate the given JWT KID in the header. Can retrieve the public key from local cache or from Descope. */\n async getKey(header: JWTHeaderParameters): Promise<KeyLike | Uint8Array> {\n if (!header?.kid) throw Error('header.kid must not be empty');\n\n if (keys[header.kid]) return keys[header.kid];\n\n // do we need to fetch once or every time?\n Object.assign(keys, await fetchKeys());\n\n if (!keys[header.kid]) throw Error('failed to fetch matching key');\n\n return keys[header.kid];\n },\n\n /**\n * Validate the given JWT with the right key and make sure the issuer is correct\n * @param jwt the JWT string to parse and validate\n * @returns AuthenticationInfo with the parsed token and JWT. Will throw an error if validation fails.\n */\n async validateJwt(jwt: string): Promise<AuthenticationInfo> {\n // Do not hard-code the algo because library does not support `None` so all are valid\n const res = await jwtVerify(jwt, sdk.getKey, { issuer: projectId, clockTolerance: 5 });\n\n return { jwt, token: res.payload };\n },\n\n /**\n * Validate session based on at least one of session and refresh JWTs. You must provide at least one of them.\n *\n * @param sessionToken session JWT\n * @param refreshToken refresh JWT\n * @returns AuthenticationInfo promise or throws Error if there is an issue with JWTs\n */\n async validateSession(\n sessionToken?: string,\n refreshToken?: string,\n ): Promise<AuthenticationInfo> {\n if (!sessionToken && !refreshToken)\n throw Error('both refresh token and session token are empty');\n\n if (sessionToken) {\n try {\n const token = await sdk.validateJwt(sessionToken);\n return token;\n } catch (error) {\n if (!refreshToken) {\n logger?.error('failed to validate session token and no refresh token provided', error);\n throw Error('could not validate tokens');\n }\n }\n }\n if (refreshToken) {\n try {\n await sdk.validateJwt(refreshToken);\n const jwtResp = await sdk.refresh(refreshToken);\n if (jwtResp.ok) {\n const token = await sdk.validateJwt(jwtResp.data?.sessionJwt);\n return token;\n }\n throw Error(jwtResp.error?.message);\n } catch (refreshTokenErr) {\n logger?.error('failed to validate refresh token', refreshTokenErr);\n throw Error('could not validate tokens');\n }\n }\n /* istanbul ignore next */\n throw Error('could not validate token');\n },\n\n /**\n * Exchange API key (access key) for a session key\n * @param accessKey access key to exchange for a session JWT\n * @returns AuthneticationInfo with session JWT data\n */\n async exchangeAccessKey(accessKey: string): Promise<AuthenticationInfo> {\n if (!accessKey) throw Error('access key must not be empty');\n\n let resp: SdkResponse<ExchangeAccessKeyResponse>;\n try {\n resp = await sdk.accessKey.exchange(accessKey);\n } catch (error) {\n logger?.error('failed to exchange access key', error);\n throw Error('could not exchange access key');\n }\n\n const { sessionJwt } = resp.data;\n if (!sessionJwt) {\n logger?.error('failed to parse exchange access key response');\n throw Error('could not exchange access key');\n }\n\n try {\n const token = await sdk.validateJwt(sessionJwt);\n return token;\n } catch (error) {\n logger?.error('failed to parse jwt from access key', error);\n throw Error('could not exchange access key');\n }\n },\n\n /**\n * Make sure that all given permissions exist on the parsed JWT top level claims\n * @param authInfo JWT parsed info\n * @param permissions list of permissions to make sure they exist on te JWT claims\n * @returns true if all permissions exist, false otherwise\n */\n validatePermissions(authInfo: AuthenticationInfo, permissions: string[]): boolean {\n return sdk.validateTenantPermissions(authInfo, null, permissions);\n },\n\n /**\n * Make sure that all given permissions exist on the parsed JWT tenant claims\n * @param authInfo JWT parsed info\n * @param permissions list of permissions to make sure they exist on te JWT claims\n * @returns true if all permissions exist, false otherwise\n */\n validateTenantPermissions(\n authInfo: AuthenticationInfo,\n tenant: string,\n permissions: string[],\n ): boolean {\n const granted = getAuthorizationClaimItems(authInfo, permissionsClaimName, tenant);\n return permissions.every((perm) => granted.includes(perm));\n },\n\n /**\n * Make sure that all given roles exist on the parsed JWT top level claims\n * @param authInfo JWT parsed info\n * @param roles list of roles to make sure they exist on te JWT claims\n * @returns true if all roles exist, false otherwise\n */\n validateRoles(authInfo: AuthenticationInfo, roles: string[]): boolean {\n return sdk.validateTenantRoles(authInfo, null, roles);\n },\n\n /**\n * Make sure that all given roles exist on the parsed JWT tenant claims\n * @param authInfo JWT parsed info\n * @param roles list of roles to make sure they exist on te JWT claims\n * @returns true if all roles exist, false otherwise\n */\n validateTenantRoles(authInfo: AuthenticationInfo, tenant: string, roles: string[]): boolean {\n const membership = getAuthorizationClaimItems(authInfo, rolesClaimName, tenant);\n return roles.every((role) => membership.includes(role));\n },\n };\n\n return sdk;\n};\n\n/** Descope SDK client with delivery methods enum.\n *\n * Please see full documentation at {@link https://docs.descope.com/guides Descope Docs}\n * @example Usage\n *\n * ```js\n * import descopeSdk from '@descope/node-sdk';\n *\n * const myProjectId = 'xxx';\n * const sdk = descopeSdk({ projectId: myProjectId });\n *\n * const userIdentifier = 'identifier';\n * sdk.otp.signIn.email(userIdentifier);\n * const jwtResponse = sdk.otp.verify.email(userIdentifier, codeFromEmail);\n * ```\n */\nconst sdkWithAttributes = nodeSdk as typeof nodeSdk & {\n DeliveryMethods: typeof createSdk.DeliveryMethods;\n RefreshTokenCookieName: typeof refreshTokenCookieName;\n SessionTokenCookieName: typeof sessionTokenCookieName;\n};\n\nsdkWithAttributes.DeliveryMethods = createSdk.DeliveryMethods;\nsdkWithAttributes.RefreshTokenCookieName = refreshTokenCookieName;\nsdkWithAttributes.SessionTokenCookieName = sessionTokenCookieName;\n\nexport default sdkWithAttributes;\n\nexport type { DeliveryMethod, OAuthProvider } from '@descope/core-js-sdk';\n"],"names":["generateCookie","name","value","options","cookieDomain","cookieMaxAge","cookiePath","withCookie","fn","async","args","resp","data","_d","sessionJwt","refreshJwt","rest","__rest","cookies","push","_a","response","headers","get","cookie","match","RegExp","getCookieValue","_b","_c","Object","assign","wrapWith","obj","path","wrappingFn","pathSections","split","section","shift","length","wrap","key","Error","toString","keys","forEach","getAuthorizationClaimItems","authInfo","claim","tenant","token","Array","isArray","globalThis","fetch","Headers","Request","Response","sdkWithAttributes","funcArgs","hooks","origBeforeRequest","beforeRequest","config","conf","process","versions","node","coreSdk","createSdk","projectId","logger","sdk","header","kid","publicKeys","httpClient","then","json","Promise","all","map","importJWK","reduce","acc","jwk","fetchKeys","jwt","jwtVerify","getKey","issuer","clockTolerance","payload","sessionToken","refreshToken","validateJwt","error","jwtResp","refresh","ok","message","refreshTokenErr","accessKey","exchange","validatePermissions","permissions","validateTenantPermissions","granted","every","perm","includes","validateRoles","roles","validateTenantRoles","membership","role","DeliveryMethods","RefreshTokenCookieName","SessionTokenCookieName"],"mappings":"0MAEO,MCaDA,EAAiB,CAACC,EAAcC,EAAeC,IACnD,GAAGF,KAAQC,cAAiBC,aAAA,EAAAA,EAASC,eAAgB,gBACnDD,aAAA,EAAAA,EAASE,eAAgB,aACjBF,aAAA,EAAAA,EAASG,aAAc,iCAmBtBC,EAC0DC,GACrEC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C5C3D,MAAM,4BACb,CAGH,MAAMA,MAAM,2BACb,EAODlC,wBAAwB8F,GACtB,IAAKA,EAAW,MAAM5D,MAAM,gCAE5B,IAAIhC,EACJ,IACEA,QAAa8D,EAAI8B,UAAUC,SAASD,EAIrC,CAHC,MAAON,GAEP,MADAzB,SAAAA,EAAQyB,MAAM,gCAAiCA,GACzCtD,MAAM,gCACb,CAED,MAAM7B,WAAEA,GAAeH,EAAKC,KAC5B,IAAKE,EAEH,MADA0D,SAAAA,EAAQyB,MAAM,gDACRtD,MAAM,iCAGd,IAEE,aADoB8B,EAAIuB,YAAYlF,EAKrC,CAHC,MAAOmF,GAEP,MADAzB,SAAAA,EAAQyB,MAAM,sCAAuCA,GAC/CtD,MAAM,gCACb,CACF,EAQD8D,oBAAmB,CAACzD,EAA8B0D,IACzCjC,EAAIkC,0BAA0B3D,EAAU,KAAM0D,GASvDC,0BACE3D,EACAE,EACAwD,GAEA,MAAME,EAAU7D,EAA2BC,EFvMb,cEuM6CE,GAC3E,OAAOwD,EAAYG,OAAOC,GAASF,EAAQG,SAASD,IACrD,EAQDE,cAAa,CAAChE,EAA8BiE,IACnCxC,EAAIyC,oBAAoBlE,EAAU,KAAMiE,GASjDC,oBAAoBlE,EAA8BE,EAAgB+D,GAChE,MAAME,EAAapE,EAA2BC,EF1NtB,QE0NgDE,GACxE,OAAO+D,EAAMJ,OAAOO,GAASD,EAAWJ,SAASK,IAClD,IAGH,OAAO3C,CAAG,EAyBZd,EAAkB0D,gBAAkB/C,EAAS,QAAC+C,gBAC9C1D,EAAkB2D,uBFjQoB,MEkQtC3D,EAAkB4D,uBFhQoB"}
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,21 +1,43 @@
1
1
  import * as _descope_core_js_sdk from '@descope/core-js-sdk';
2
- import _descope_core_js_sdk__default from '@descope/core-js-sdk';
2
+ import _descope_core_js_sdk__default, { RequestConfig, SdkResponse, ExchangeAccessKeyResponse } from '@descope/core-js-sdk';
3
3
  export { DeliveryMethod, OAuthProvider } from '@descope/core-js-sdk';
4
4
  import { JWTHeaderParameters, KeyLike } from 'jose';
5
5
 
6
+ /** Parsed JWT token */
6
7
  interface Token {
7
8
  sub?: string;
8
9
  exp?: number;
9
10
  iss?: string;
11
+ [claim: string]: unknown;
10
12
  }
13
+ /** All information regarding token including the raw JWT, parsed JWT and cookies */
11
14
  interface AuthenticationInfo {
12
- token?: Token;
15
+ jwt: string;
16
+ token: Token;
13
17
  cookies?: string[];
14
18
  }
15
19
 
20
+ /** Refresh JWT cookie name */
16
21
  declare const refreshTokenCookieName = "DSR";
22
+ /** Session JWT cookie name */
17
23
  declare const sessionTokenCookieName = "DS";
18
24
 
25
+ /** Descope SDK client with delivery methods enum.
26
+ *
27
+ * Please see full documentation at {@link https://docs.descope.com/guides Descope Docs}
28
+ * @example Usage
29
+ *
30
+ * ```js
31
+ * import descopeSdk from '@descope/node-sdk';
32
+ *
33
+ * const myProjectId = 'xxx';
34
+ * const sdk = descopeSdk({ projectId: myProjectId });
35
+ *
36
+ * const userIdentifier = 'identifier';
37
+ * sdk.otp.signIn.email(userIdentifier);
38
+ * const jwtResponse = sdk.otp.verify.email(userIdentifier, codeFromEmail);
39
+ * ```
40
+ */
19
41
  declare const sdkWithAttributes: ((args_0: {
20
42
  projectId: string;
21
43
  logger?: {
@@ -33,205 +55,284 @@ declare const sdkWithAttributes: ((args_0: {
33
55
  };
34
56
  };
35
57
  baseUrl?: string;
58
+ hooks?: {
59
+ beforeRequest?: (config: RequestConfig) => RequestConfig;
60
+ afterRequest?: (req: RequestConfig, res: globalThis.Response) => void;
61
+ };
62
+ cookiePolicy?: RequestCredentials;
36
63
  }) => {
64
+ /** Get the key that can validate the given JWT KID in the header. Can retrieve the public key from local cache or from Descope. */
37
65
  getKey(header: JWTHeaderParameters): Promise<KeyLike | Uint8Array>;
38
- validateToken(token: string): Promise<AuthenticationInfo>;
39
- validateSession(sessionToken: string, refreshToken: string): Promise<AuthenticationInfo | undefined>;
66
+ /**
67
+ * Validate the given JWT with the right key and make sure the issuer is correct
68
+ * @param jwt the JWT string to parse and validate
69
+ * @returns AuthenticationInfo with the parsed token and JWT. Will throw an error if validation fails.
70
+ */
71
+ validateJwt(jwt: string): Promise<AuthenticationInfo>;
72
+ /**
73
+ * Validate session based on at least one of session and refresh JWTs. You must provide at least one of them.
74
+ *
75
+ * @param sessionToken session JWT
76
+ * @param refreshToken refresh JWT
77
+ * @returns AuthenticationInfo promise or throws Error if there is an issue with JWTs
78
+ */
79
+ validateSession(sessionToken?: string, refreshToken?: string): Promise<AuthenticationInfo>;
80
+ /**
81
+ * Exchange API key (access key) for a session key
82
+ * @param accessKey access key to exchange for a session JWT
83
+ * @returns AuthneticationInfo with session JWT data
84
+ */
85
+ exchangeAccessKey(accessKey: string): Promise<AuthenticationInfo>;
86
+ /**
87
+ * Make sure that all given permissions exist on the parsed JWT top level claims
88
+ * @param authInfo JWT parsed info
89
+ * @param permissions list of permissions to make sure they exist on te JWT claims
90
+ * @returns true if all permissions exist, false otherwise
91
+ */
92
+ validatePermissions(authInfo: AuthenticationInfo, permissions: string[]): boolean;
93
+ /**
94
+ * Make sure that all given permissions exist on the parsed JWT tenant claims
95
+ * @param authInfo JWT parsed info
96
+ * @param permissions list of permissions to make sure they exist on te JWT claims
97
+ * @returns true if all permissions exist, false otherwise
98
+ */
99
+ validateTenantPermissions(authInfo: AuthenticationInfo, tenant: string, permissions: string[]): boolean;
100
+ /**
101
+ * Make sure that all given roles exist on the parsed JWT top level claims
102
+ * @param authInfo JWT parsed info
103
+ * @param roles list of roles to make sure they exist on te JWT claims
104
+ * @returns true if all roles exist, false otherwise
105
+ */
106
+ validateRoles(authInfo: AuthenticationInfo, roles: string[]): boolean;
107
+ /**
108
+ * Make sure that all given roles exist on the parsed JWT tenant claims
109
+ * @param authInfo JWT parsed info
110
+ * @param roles list of roles to make sure they exist on te JWT claims
111
+ * @returns true if all roles exist, false otherwise
112
+ */
113
+ validateTenantRoles(authInfo: AuthenticationInfo, tenant: string, roles: string[]): boolean;
114
+ accessKey: {
115
+ exchange: (accessKey: string) => Promise<SdkResponse<ExchangeAccessKeyResponse>>;
116
+ };
40
117
  otp: {
41
118
  verify: {
42
- email: (identifier: string, code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
43
- sms: (identifier: string, code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
44
- whatsapp: (identifier: string, code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
119
+ email: (identifier: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
120
+ sms: (identifier: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
121
+ whatsapp: (identifier: string, code: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
45
122
  };
46
123
  signIn: {
47
- email: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
48
- sms: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
49
- whatsapp: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
124
+ email: (identifier: string) => Promise<SdkResponse<never>>;
125
+ sms: (identifier: string) => Promise<SdkResponse<never>>;
126
+ whatsapp: (identifier: string) => Promise<SdkResponse<never>>;
50
127
  };
51
128
  signUp: {
52
129
  email: (identifier: string, user?: {
53
130
  email?: string;
54
131
  name?: string;
55
132
  phone?: string;
56
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
133
+ }) => Promise<SdkResponse<never>>;
57
134
  sms: (identifier: string, user?: {
58
135
  email?: string;
59
136
  name?: string;
60
137
  phone?: string;
61
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
138
+ }) => Promise<SdkResponse<never>>;
62
139
  whatsapp: (identifier: string, user?: {
63
140
  email?: string;
64
141
  name?: string;
65
142
  phone?: string;
66
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
143
+ }) => Promise<SdkResponse<never>>;
67
144
  };
68
145
  signUpOrIn: {
69
- email: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
70
- sms: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
71
- whatsapp: (identifier: string) => Promise<_descope_core_js_sdk.SdkResponse>;
146
+ email: (identifier: string) => Promise<SdkResponse<never>>;
147
+ sms: (identifier: string) => Promise<SdkResponse<never>>;
148
+ whatsapp: (identifier: string) => Promise<SdkResponse<never>>;
72
149
  };
73
150
  update: {
74
- email: (identifier: string, email: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
151
+ email: (identifier: string, email: string, token?: string) => Promise<SdkResponse<never>>;
75
152
  phone: {
76
- email: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
77
- sms: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
78
- whatsapp: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
153
+ email: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
154
+ sms: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
155
+ whatsapp: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
79
156
  };
80
157
  };
81
158
  };
82
159
  magicLink: {
83
- verify: (token: string) => Promise<_descope_core_js_sdk.SdkResponse>;
160
+ verify: (token: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
84
161
  signIn: {
85
- email: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
86
- sms: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
87
- whatsapp: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
162
+ email: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
163
+ sms: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
164
+ whatsapp: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
88
165
  };
89
166
  signUp: {
90
167
  email: (identifier: string, uri: string, user?: {
91
168
  email?: string;
92
169
  name?: string;
93
170
  phone?: string;
94
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
171
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
95
172
  sms: (identifier: string, uri: string, user?: {
96
173
  email?: string;
97
174
  name?: string;
98
175
  phone?: string;
99
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
176
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
100
177
  whatsapp: (identifier: string, uri: string, user?: {
101
178
  email?: string;
102
179
  name?: string;
103
180
  phone?: string;
104
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
181
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
105
182
  };
106
183
  signUpOrIn: {
107
- email: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
108
- sms: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
109
- whatsapp: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
184
+ email: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
185
+ sms: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
186
+ whatsapp: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
110
187
  };
111
188
  update: {
112
- email: (identifier: string, email: string, uri: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
189
+ email: (identifier: string, email: string, uri: string, token?: string) => Promise<SdkResponse<never>>;
113
190
  phone: {
114
- email: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
115
- sms: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
116
- whatsapp: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
191
+ email: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
192
+ sms: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
193
+ whatsapp: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
117
194
  };
118
195
  };
119
196
  crossDevice: {
120
- verify: (token: string) => Promise<_descope_core_js_sdk.SdkResponse>;
197
+ verify: (token: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
121
198
  signIn: {
122
- email: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
123
- sms: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
124
- whatsapp: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
199
+ email: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
200
+ sms: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
201
+ whatsapp: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
125
202
  };
126
203
  signUpOrIn: {
127
- email: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
128
- sms: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
129
- whatsapp: (identifier: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse>;
204
+ email: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
205
+ sms: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
206
+ whatsapp: (identifier: string, uri: string) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
130
207
  };
131
208
  signUp: {
132
209
  email: (identifier: string, uri: string, user?: {
133
210
  email?: string;
134
211
  name?: string;
135
212
  phone?: string;
136
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
213
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
137
214
  sms: (identifier: string, uri: string, user?: {
138
215
  email?: string;
139
216
  name?: string;
140
217
  phone?: string;
141
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
218
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
142
219
  whatsapp: (identifier: string, uri: string, user?: {
143
220
  email?: string;
144
221
  name?: string;
145
222
  phone?: string;
146
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
223
+ }) => Promise<SdkResponse<_descope_core_js_sdk.PendingRefResponse>>;
147
224
  };
148
225
  waitForSession: (pendingRef: string, config?: {
149
226
  pollingIntervalMs: number;
150
227
  timeoutMs: number;
151
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
228
+ }) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>; /**
229
+ * Make sure that all given roles exist on the parsed JWT tenant claims
230
+ * @param authInfo JWT parsed info
231
+ * @param roles list of roles to make sure they exist on te JWT claims
232
+ * @returns true if all roles exist, false otherwise
233
+ */
152
234
  update: {
153
- email: (identifier: string, email: string, uri: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
235
+ email: (identifier: string, email: string, uri: string, token?: string) => Promise<SdkResponse<never>>;
154
236
  phone: {
155
- email: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
156
- sms: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
157
- whatsapp: (identifier: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse>;
237
+ email: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
238
+ sms: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
239
+ whatsapp: (identifier: string, phone: string) => Promise<SdkResponse<never>>;
158
240
  };
159
241
  };
160
242
  };
161
243
  };
162
244
  oauth: {
163
- exchange: (code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
164
245
  start: {
165
246
  facebook: <B extends {
166
247
  redirect: boolean;
167
248
  }>(redirectURL?: string, config?: B) => Promise<B extends {
168
249
  redirect: true;
169
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
250
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
170
251
  github: <B_1 extends {
171
252
  redirect: boolean;
172
253
  }>(redirectURL?: string, config?: B_1) => Promise<B_1 extends {
173
254
  redirect: true;
174
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
255
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
175
256
  google: <B_2 extends {
176
257
  redirect: boolean;
177
258
  }>(redirectURL?: string, config?: B_2) => Promise<B_2 extends {
178
259
  redirect: true;
179
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
260
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
180
261
  microsoft: <B_3 extends {
181
262
  redirect: boolean;
182
263
  }>(redirectURL?: string, config?: B_3) => Promise<B_3 extends {
183
264
  redirect: true;
184
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
265
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
185
266
  gitlab: <B_4 extends {
186
267
  redirect: boolean;
187
268
  }>(redirectURL?: string, config?: B_4) => Promise<B_4 extends {
188
269
  redirect: true;
189
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
270
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
190
271
  apple: <B_5 extends {
191
272
  redirect: boolean;
192
273
  }>(redirectURL?: string, config?: B_5) => Promise<B_5 extends {
193
274
  redirect: true;
194
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
275
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
195
276
  };
277
+ exchange: (code: string, loginOptions?: {
278
+ stepup: boolean;
279
+ customClaims: Map<string, any>;
280
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
196
281
  };
197
282
  saml: {
198
- exchange: (code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
199
283
  start: <B_1 extends {
200
284
  redirect: boolean;
201
285
  }>(tenantNameOrEmail: string, config?: B_1) => Promise<B_1 extends {
202
286
  redirect: true;
203
- } ? undefined : _descope_core_js_sdk.SdkResponse>;
287
+ } ? undefined : SdkResponse<_descope_core_js_sdk.URLResponse>>;
288
+ exchange: (code: string, loginOptions?: {
289
+ stepup: boolean;
290
+ customClaims: Map<string, any>;
291
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
204
292
  };
205
293
  totp: {
206
294
  signUp: (identifier: string, user?: {
207
295
  email?: string;
208
296
  name?: string;
209
297
  phone?: string;
210
- }) => Promise<_descope_core_js_sdk.SdkResponse>;
211
- verify: (identifier: string, code: string) => Promise<_descope_core_js_sdk.SdkResponse>;
212
- update: (identifier: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
298
+ }) => Promise<SdkResponse<_descope_core_js_sdk.TOTPResponse>>;
299
+ verify: (identifier: string, code: string, loginOptions?: {
300
+ stepup: boolean;
301
+ customClaims: Map<string, any>;
302
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
303
+ update: (identifier: string, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.TOTPResponse>>;
213
304
  };
214
305
  webauthn: {
215
306
  signUp: {
216
- start: (identifier: string, origin: string, name: string) => Promise<_descope_core_js_sdk.SdkResponse>;
217
- finish: (transactionId: string, response: string) => Promise<_descope_core_js_sdk.SdkResponse>;
307
+ start: (identifier: string, origin: string, name: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
308
+ finish: (transactionId: string, response: string, loginOptions?: {
309
+ stepup: boolean;
310
+ customClaims: Map<string, any>;
311
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
218
312
  };
219
313
  signIn: {
220
- start: (identifier: string, origin: string) => Promise<_descope_core_js_sdk.SdkResponse>;
221
- finish: (transactionId: string, response: string) => Promise<_descope_core_js_sdk.SdkResponse>;
314
+ start: (identifier: string, origin: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
315
+ finish: (transactionId: string, response: string, loginOptions?: {
316
+ stepup: boolean;
317
+ customClaims: Map<string, any>;
318
+ }, token?: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
222
319
  };
223
- add: {
224
- start: (identifier: string, origin: string, token: string) => Promise<_descope_core_js_sdk.SdkResponse>;
225
- finish: (transactionId: string, response: string) => Promise<_descope_core_js_sdk.SdkResponse>;
320
+ update: {
321
+ start: (identifier: string, origin: string, token: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
322
+ finish: (transactionId: string, response: string) => Promise<SdkResponse<_descope_core_js_sdk.ResponseData>>;
226
323
  };
227
324
  };
228
325
  flow: {
229
- start: (flowId: string) => Promise<_descope_core_js_sdk.SdkResponse>;
230
- next: (executionId: string, stepId: string, actionId: string, input?: Record<string, FormDataEntryValue>) => Promise<_descope_core_js_sdk.SdkResponse>;
326
+ start: (flowId: string) => Promise<SdkResponse<_descope_core_js_sdk.FlowResponse>>;
327
+ next: (executionId: string, stepId: string, interactionId: string, input?: Record<string, FormDataEntryValue>) => Promise<SdkResponse<_descope_core_js_sdk.FlowResponse>>;
231
328
  };
232
- refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
233
- logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse>;
329
+ refresh: (token?: string) => Promise<SdkResponse<_descope_core_js_sdk.JWTResponse>>;
330
+ logout: (token?: string) => Promise<SdkResponse<never>>;
331
+ deleteCookies: (token?: string) => Promise<SdkResponse<never>>;
332
+ me: (token?: string) => Promise<SdkResponse<_descope_core_js_sdk.UserResponse>>;
234
333
  isJwtExpired: (token: string) => boolean;
334
+ getJwtPermissions: (token: string, tenant?: string) => string[];
335
+ getJwtRoles: (token: string, tenant?: string) => string[];
235
336
  httpClient: {
236
337
  get: (path: string, config?: {
237
338
  headers?: HeadersInit;
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"@descope/core-js-sdk";import{jwtVerify as t,importJWK as i}from"jose";import o,{Headers as s,Request as a,Response as r}from"node-fetch";import{__rest as n}from"tslib";const c=(e,t,i)=>`${e}=${t}; Domain=${(null==i?void 0:i.cookieDomain)||""}; Max-Age=${(null==i?void 0:i.cookieMaxAge)||""}; Path=${(null==i?void 0:i.cookiePath)||"/"}; HttpOnly; SameSite=Strict`,l=e=>async(...t)=>{var i,o,s;const a=await e(...t);if(!a.data)return a;let r=a.data,{sessionJwt:l,refreshJwt:h}=r,d=n(r,["sessionJwt","refreshJwt"]);const g=[c("DS",l,d)];return h?g.push(c("DSR",h,d)):(null===(i=a.response)||void 0===i?void 0:i.headers.get("set-cookie"))&&(h=((e,t)=>{const i=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return i?i[1]:null})(null===(o=a.response)||void 0===o?void 0:o.headers.get("set-cookie"),"DSR"),g.push(null===(s=a.response)||void 0===s?void 0:s.headers.get("set-cookie"))),Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{refreshJwt:h,cookies:g})})},h=(e,t,i)=>{if(!e)return;const o="string"==typeof t?t.split("."):t,s=o.shift()||"";if(0===o.length||"*"===s){const t=t=>{if(!t||"function"!=typeof e[t])throw Error(`cannot wrap value at key "${t.toString()}"`);e[t]=i(e[t])};"*"===s?Object.keys(e).forEach(t):t(s)}else h(e[s],o,i)};globalThis.fetch||(globalThis.fetch=o,globalThis.Headers=s,globalThis.Request=a,globalThis.Response=r);const d=(...o)=>{const s=e(...o);var a,r;a=s,r=l,["otp.verify.*","magicLink.verify","magicLink.crossDevice.signUp.*","magicLink.crossDevice.signIn.*","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"].forEach((e=>h(a,e,r)));const{projectId:n,logger:c}=o[0],d={};return Object.assign(Object.assign({},s),{async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(d[e.kid])return d[e.kid];if(Object.assign(d,await(async()=>{const e=await s.httpClient.get(`v1/keys/${n}`).then((e=>e.json()));return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await i(e)])))).reduce(((e,[t,i])=>t?Object.assign(Object.assign({},e),{[t.toString()]:i}):e),{}):{}})()),!d[e.kid])throw Error("failed to fetch matching key");return d[e.kid]},async validateToken(e){return{token:(await t(e,this.getKey,{algorithms:["ES384"]})).payload}},async validateSession(e,t){if(!e)throw Error("session token must not be empty");try{return await this.validateToken(e)}catch(e){try{return await this.validateToken(t),(await this.refresh(t)).data}catch(e){throw null==c||c.error("failed to validate refresh token",e),Error("could not validate tokens")}}}})};d.DeliveryMethods=e.DeliveryMethods,d.RefreshTokenCookieName="DSR",d.SessionTokenCookieName="DS";export{d as default};
1
+ import e from"@descope/core-js-sdk";import{jwtVerify as o,importJWK as t}from"jose";import s,{Headers as r,Request as a,Response as n}from"node-fetch";import{__rest as i}from"tslib";const c=(e,o,t)=>`${e}=${o}; Domain=${(null==t?void 0:t.cookieDomain)||""}; Max-Age=${(null==t?void 0:t.cookieMaxAge)||""}; Path=${(null==t?void 0:t.cookiePath)||"/"}; HttpOnly; SameSite=Strict`,l=e=>async(...o)=>{var t,s,r;const a=await e(...o);if(!a.data)return a;let n=a.data,{sessionJwt:l,refreshJwt:d}=n,h=i(n,["sessionJwt","refreshJwt"]);const u=[c("DS",l,h)];return d?u.push(c("DSR",d,h)):(null===(t=a.response)||void 0===t?void 0:t.headers.get("set-cookie"))&&(d=((e,o)=>{const t=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${o}=([^;]*)`));return t?t[1]:null})(null===(s=a.response)||void 0===s?void 0:s.headers.get("set-cookie"),"DSR"),u.push(null===(r=a.response)||void 0===r?void 0:r.headers.get("set-cookie"))),Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{refreshJwt:d,cookies:u})})},d=(e,o,t)=>{if(!e)return;const s="string"==typeof o?o.split("."):o,r=s.shift()||"";if(0===s.length||"*"===r){const o=o=>{if(!o||"function"!=typeof e[o])throw Error(`cannot wrap value at key "${o.toString()}"`);e[o]=t(e[o])};"*"===r?Object.keys(e).forEach(o):o(r)}else d(e[r],s,t)};function h(e,o,t){var s,r;const a=t?null===(r=null===(s=e.token.tenants)||void 0===s?void 0:s[t])||void 0===r?void 0:r[o]:e.token[o];return Array.isArray(a)?a:[]}globalThis.fetch||(globalThis.fetch=s,globalThis.Headers=r,globalThis.Request=a,globalThis.Response=n);const u=(...s)=>{const r=[...s];r[0].hooks=r[0].hooks||{};const a=r[0].hooks.beforeRequest;r[0].hooks.beforeRequest=e=>{var o;const t=e;return t.headers=Object.assign(Object.assign({},t.headers),{"x-descope-sdk-name":"nodejs","x-descope-sdk-node-version":(null===(o=null===process||void 0===process?void 0:process.versions)||void 0===o?void 0:o.node)||"","x-descope-sdk-version":"1.0.4-alpha.7"}),(null==a?void 0:a(t))||t};const n=e(...r);var i,c;i=n,c=l,["otp.verify.*","magicLink.verify","magicLink.crossDevice.signUp.*","magicLink.crossDevice.signIn.*","oauth.exchange","saml.exchange","totp.verify","webauthn.signIn.finish","webauthn.signUp.finish","refresh"].forEach((e=>d(i,e,c)));const{projectId:u,logger:v}=s[0],f={},k=Object.assign(Object.assign({},n),{async getKey(e){if(!(null==e?void 0:e.kid))throw Error("header.kid must not be empty");if(f[e.kid])return f[e.kid];if(Object.assign(f,await(async()=>{const e=await n.httpClient.get(`v1/keys/${u}`).then((e=>e.json()));return Array.isArray(e)?(await Promise.all(e.map((async e=>[e.kid,await t(e)])))).reduce(((e,[o,t])=>o?Object.assign(Object.assign({},e),{[o.toString()]:t}):e),{}):{}})()),!f[e.kid])throw Error("failed to fetch matching key");return f[e.kid]},validateJwt:async e=>({jwt:e,token:(await o(e,k.getKey,{issuer:u,clockTolerance:5})).payload}),async validateSession(e,o){var t,s;if(!e&&!o)throw Error("both refresh token and session token are empty");if(e)try{return await k.validateJwt(e)}catch(e){if(!o)throw null==v||v.error("failed to validate session token and no refresh token provided",e),Error("could not validate tokens")}if(o)try{await k.validateJwt(o);const e=await k.refresh(o);if(e.ok){return await k.validateJwt(null===(t=e.data)||void 0===t?void 0:t.sessionJwt)}throw Error(null===(s=e.error)||void 0===s?void 0:s.message)}catch(e){throw null==v||v.error("failed to validate refresh token",e),Error("could not validate tokens")}throw Error("could not validate token")},async exchangeAccessKey(e){if(!e)throw Error("access key must not be empty");let o;try{o=await k.accessKey.exchange(e)}catch(e){throw null==v||v.error("failed to exchange access key",e),Error("could not exchange access key")}const{sessionJwt:t}=o.data;if(!t)throw null==v||v.error("failed to parse exchange access key response"),Error("could not exchange access key");try{return await k.validateJwt(t)}catch(e){throw null==v||v.error("failed to parse jwt from access key",e),Error("could not exchange access key")}},validatePermissions:(e,o)=>k.validateTenantPermissions(e,null,o),validateTenantPermissions(e,o,t){const s=h(e,"permissions",o);return t.every((e=>s.includes(e)))},validateRoles:(e,o)=>k.validateTenantRoles(e,null,o),validateTenantRoles(e,o,t){const s=h(e,"roles",o);return t.every((e=>s.includes(e)))}});return k};u.DeliveryMethods=e.DeliveryMethods,u.RefreshTokenCookieName="DSR",u.SessionTokenCookieName="DS";export{u as default};
2
2
  //# sourceMappingURL=index.esm.js.map