@descope/node-sdk
Advanced tools
Comparing version 1.0.4-alpha.5 to 1.0.4-alpha.6
@@ -1,2 +0,2 @@ | ||
"use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),i=require("jose"),r=require("node-fetch");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=o(t),n=o(r);const a=(e,t)=>`${e}=${t};`,d=t=>(...i)=>e.__awaiter(void 0,void 0,void 0,(function*(){var e;const r=yield t(...i);if(!r.data)return r;let{sessionJwt:o,refreshJwt:s}=r.data,n=a("DS",o);return s?n+=a("DSR",s):(n+=(null===(e=r.response)||void 0===e?void 0:e.headers.get("set-cookie"))||"",s=((e,t)=>{const i=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return i?i[1]:null})(n,"DSR")),Object.assign(Object.assign({},r),{data:Object.assign(Object.assign({},r.data),{refreshJwt:s,cookies:n})})})),l=(e,t,i)=>{if(!e)return;const r="string"==typeof t?t.split("."):t,o=r.shift()||"";if(0===r.length||"*"===o){const t=t=>{if(!t||"function"!=typeof e[t])throw Error(`cannot wrap value at key "${t.toString()}"`);e[t]=i(e[t])};"*"===o?Object.keys(e).forEach(t):t(o)}else l(e[o],r,i)};globalThis.fetch||(globalThis.fetch=n.default,globalThis.Headers=r.Headers,globalThis.Request=r.Request,globalThis.Response=r.Response);const c=(...t)=>{const r=s.default(...t);var o,n;o=r,n=d,["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(o,e,n)));const{projectId:a,logger:c}=t[0],u={};return Object.assign(Object.assign({},r),{getKey(t){return e.__awaiter(this,void 0,void 0,(function*(){if(!(null==t?void 0:t.kid))throw Error("header.kid must not be empty");if(u[t.kid])return u[t.kid];if(Object.assign(u,yield e.__awaiter(void 0,void 0,void 0,(function*(){const t=(yield r.httpClient.get(`keys/${a}`).then((e=>e.json())))||[];return(yield Promise.all(t.map((t=>e.__awaiter(void 0,void 0,void 0,(function*(){return[t.kid,yield i.importJWK(t)]})))))).reduce(((e,[t,i])=>t?Object.assign(Object.assign({},e),{[t.toString()]:i}):e),{})}))),!u[t.kid])throw Error("failed to fetch matching key");return u[t.kid]}))},validateToken(t){return e.__awaiter(this,void 0,void 0,(function*(){return{token:(yield i.jwtVerify(t,this.getKey,{algorithms:["ES384"]})).payload}}))},validateSession(t,i){return e.__awaiter(this,void 0,void 0,(function*(){if(!t)throw Error("session token must not be empty");try{return yield this.validateToken(t)}catch(e){try{return yield this.validateToken(i),(yield this.refresh(i)).data}catch(e){throw null==c||c.error("failed to validate refresh token",e),Error("could not validate tokens")}}}))}})};c.DeliveryMethods=s.default.DeliveryMethods,module.exports=c; | ||
"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; | ||
//# sourceMappingURL=index.cjs.js.map |
@@ -16,2 +16,5 @@ import * as _descope_core_js_sdk from '@descope/core-js-sdk'; | ||
declare const refreshTokenCookieName = "DSR"; | ||
declare const sessionTokenCookieName = "DS"; | ||
declare const sdkWithAttributes: ((args_0: { | ||
@@ -265,4 +268,6 @@ projectId: string; | ||
DeliveryMethods: typeof _descope_core_js_sdk__default.DeliveryMethods; | ||
RefreshTokenCookieName: typeof refreshTokenCookieName; | ||
SessionTokenCookieName: typeof sessionTokenCookieName; | ||
}; | ||
export { sdkWithAttributes as default }; |
@@ -1,2 +0,2 @@ | ||
import{__awaiter as e}from"tslib";import t from"@descope/core-js-sdk";import{jwtVerify as i,importJWK as o}from"jose";import r,{Headers as n,Request as s,Response as a}from"node-fetch";const d=(e,t)=>`${e}=${t};`,c=t=>(...i)=>e(void 0,void 0,void 0,(function*(){var e;const o=yield t(...i);if(!o.data)return o;let{sessionJwt:r,refreshJwt:n}=o.data,s=d("DS",r);return n?s+=d("DSR",n):(s+=(null===(e=o.response)||void 0===e?void 0:e.headers.get("set-cookie"))||"",n=((e,t)=>{const i=null==e?void 0:e.match(RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return i?i[1]:null})(s,"DSR")),Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{refreshJwt:n,cookies:s})})})),l=(e,t,i)=>{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]=i(e[t])};"*"===r?Object.keys(e).forEach(t):t(r)}else l(e[r],o,i)};globalThis.fetch||(globalThis.fetch=r,globalThis.Headers=n,globalThis.Request=s,globalThis.Response=a);const h=(...r)=>{const n=t(...r);var s,a;s=n,a=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(s,e,a)));const{projectId:d,logger:h}=r[0],f={};return Object.assign(Object.assign({},n),{getKey(t){return e(this,void 0,void 0,(function*(){if(!(null==t?void 0:t.kid))throw Error("header.kid must not be empty");if(f[t.kid])return f[t.kid];if(Object.assign(f,yield e(void 0,void 0,void 0,(function*(){const t=(yield n.httpClient.get(`keys/${d}`).then((e=>e.json())))||[];return(yield Promise.all(t.map((t=>e(void 0,void 0,void 0,(function*(){return[t.kid,yield o(t)]})))))).reduce(((e,[t,i])=>t?Object.assign(Object.assign({},e),{[t.toString()]:i}):e),{})}))),!f[t.kid])throw Error("failed to fetch matching key");return f[t.kid]}))},validateToken(t){return e(this,void 0,void 0,(function*(){return{token:(yield i(t,this.getKey,{algorithms:["ES384"]})).payload}}))},validateSession(t,i){return e(this,void 0,void 0,(function*(){if(!t)throw Error("session token must not be empty");try{return yield this.validateToken(t)}catch(e){try{return yield this.validateToken(i),(yield this.refresh(i)).data}catch(e){throw null==h||h.error("failed to validate refresh token",e),Error("could not validate tokens")}}}))}})};h.DeliveryMethods=t.DeliveryMethods;export{h as default}; | ||
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}; | ||
//# sourceMappingURL=index.esm.js.map |
{ | ||
"name": "@descope/node-sdk", | ||
"version": "1.0.4-alpha.5", | ||
"version": "1.0.4-alpha.6", | ||
"description": "Node.js library used to integrate with Descope", | ||
@@ -97,3 +97,3 @@ "typings": "./dist/index.d.ts", | ||
"dependencies": { | ||
"@descope/core-js-sdk": "0.0.41-alpha.9", | ||
"@descope/core-js-sdk": "0.0.41-alpha.10", | ||
"jose": "4.8.1", | ||
@@ -100,0 +100,0 @@ "node-fetch": "2.6.7" |
227
README.md
@@ -5,225 +5,20 @@ # Descope Node.js SDK | ||
## Installing the SDK | ||
## ExpressStart with OTP Authentication | ||
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). | ||
This section will show you how to implement user authentication using a one-time password (OTP). A typical four step flow for OTP authentictaion is shown below. | ||
Run the following code in your project. These commands will add the Descope SDK for Node as a project dependency, and set the `DESCOPE_PROJECT_ID` variable to a valid \<ProjectID\>. | ||
```mermaid | ||
flowchart LR | ||
signup[1. customer sign-up]-- customer gets OTP -->verify[3. customer verification] | ||
signin[2. customer sign-in]-- customer gets OTP -->verify | ||
verify-- access private API -->validate[4. session validation] | ||
```bash | ||
npm i --save @descope/node-sdk | ||
``` | ||
### Prerequisites | ||
## What do you want to implement? | ||
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). | ||
Click one of the following links to open the documentation for that specific functionality. | ||
* Run the following commands in your project | ||
- [x] [One time passwords (OTP)](./docs/otp.md) | ||
- [x] [Magic Links](./docs/magiclink.md) | ||
- [x] [OAuth/Social](./docs/oauth.md) | ||
These commands will add the Descope NodeJS SDK as a project dependency. | ||
```bash | ||
npm i --save @descope/node-sdk | ||
``` | ||
* Import and initialize the ExpresSDK for NodeJS client in your source code | ||
```javascript | ||
import DescopeClient from '@descope/node-sdk'; | ||
const descopeClient = DescopeClient({ projectId: <ProjectID> }); | ||
``` | ||
or | ||
```javascript | ||
const sdk = require('@descope/node-sdk'); | ||
const descopeClient = sdk({ projectId: <ProjectID> }); | ||
``` | ||
### 1. Customer Sign-up | ||
In your sign-up route for OTP (for example, `myapp.com/signup`) generate a sign-up request and send the OTP verification code via the selected delivery method. In the example below an email is sent to "mytestmail@test.com". In additon, optional user data (for exmaple, a custom username in the code sample below) can be gathered during the sign-up process. | ||
```javascript | ||
await descopeClient.otp.signUp.email("mytestmail@test.com"); | ||
``` | ||
### 2. Customer Sign-in | ||
In your sign-in route for OTP (for exmaple, `myapp.com/login`) generate a sign-in request send the OTP verification code via the selected delivery method. In the example below an email is sent to "mytestmail@test.com". | ||
```javascript | ||
await descopeClient.otp.signIn.email("mytestmail@test.com"); | ||
``` | ||
### 3. Customer Verification | ||
In your verify customer route for OTP (for example, `myapp.com/verify`) verify the OTP from either a customer sign-up or sign-in. The VerifyCode function call will write the necessary tokens and cookies to the response writer (`w`), which will be used by the NodeJS client to validate each session interaction. | ||
```javascript | ||
const out = await descopeClient.otp.verify.email(identifier, code); | ||
if (out.data.cookies) { | ||
res.set('Set-Cookie', out.data.cookies); | ||
} | ||
``` | ||
### 4. Session Validation | ||
Session validation checks to see that the visitor to your website or application is who they say they are, by comparing the value in the validation variables against the session data that is already stored. | ||
```javascript | ||
const out = await descopeClient.validateSession(session_jwt, refresh_jwt); | ||
if (out?.cookies) { | ||
res.set('Set-Cookie', out.cookies); | ||
} | ||
``` | ||
## ExpressStart with MagicLink Authentication | ||
This section will help you implement user authentication using Magiclinks. A typical four step flow for OTP authentictaion is shown below. | ||
```mermaid | ||
flowchart LR | ||
signup[1. customer sign-up]-- customer gets MagicLink -->verify[3. MagicLink verification] | ||
signin[2. customer sign-in]-- customer gets MagicLink -->verify | ||
verify-- access private API -->validate[4. session validation] | ||
``` | ||
### Prerequisites | ||
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). | ||
* Run the following commands in your project | ||
These commands will add the Descope NodeJS SDK as a project dependency. | ||
```bash | ||
npm i --save @descope/node-sdk | ||
``` | ||
* Import and initialize the ExpresSDK for NodeJS client in your source code | ||
```javascript | ||
import DescopeClient from '@descope/node-sdk'; | ||
const descopeClient = DescopeClient({ projectId: <ProjectID> }); | ||
``` | ||
or | ||
```javascript | ||
const sdk = require('@descope/node-sdk'); | ||
const descopeClient = sdk({ projectId: <ProjectID> }); | ||
``` | ||
### 1. Customer Sign-up | ||
In your sign-up route using magic link (for example, `myapp.com/signup`) generate a sign-up request and send the magic link via the selected delivery method. In the example below an email is sent to "mytestmail@test.com" containing the magic link and the link will automatically return back to the provided URL ("https://mydomain.com/verify"). In additon, optional user data (for exmaple, a custom username in the code sample below) can be gathered during the sign-up process. | ||
```javascript | ||
await descopeClient.magiclink.signUp.email("mytestmail@test.com", { name: "custom name" }) | ||
``` | ||
### 2. Customer Sign-in | ||
In your sign-in route using magic link (for exmaple, `myapp.com/login`) generate a sign-in request send the magic link via the selected delivery method. In the example below an email is sent to "mytestmail@test.com" containing the magic link and the link will automatically return back to the provided URL ("https://mydomain.com/verify"). | ||
```javascript | ||
await descopeClient.magiclink.signIn.email("mytestmail@test.com") | ||
``` | ||
### 3. Customer Verification | ||
In your verify customer route for magic link (for example, `mydomain.com/verify`) verify the token from either a customer sign-up or sign-in. | ||
```javascript | ||
const out = await descopeClient.magiclink.verify(token) | ||
if (out.data.cookies) { | ||
res.set('Set-Cookie', out.data.cookies) | ||
} | ||
``` | ||
### 4. Session Validation | ||
Session validation checks to see that the visitor to your website or application is who they say they are, by comparing the value in the validation variables against the session data that is already stored. | ||
```javascript | ||
const out = await descopeClient.validateSession(session_jwt, refresh_jwt) | ||
if (out?.cookies) { | ||
res.set('Set-Cookie', out.cookies) | ||
} | ||
``` | ||
## ExpressStart with OAuth Authentication | ||
In the example below, we assume using the Descope builtin oauth provider, in that case, we dont need to define any specific application details. | ||
### Prerequisites | ||
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). | ||
* Run the following commands in your project | ||
These commands will add the Descope NodeJS SDK as a project dependency. | ||
```bash | ||
npm i --save @descope/node-sdk | ||
``` | ||
* Import and initialize the ExpresSDK for NodeJS client in your source code | ||
```javascript | ||
import DescopeClient from '@descope/node-sdk'; | ||
const descopeClient = DescopeClient({ projectId: <ProjectID> }); | ||
``` | ||
or | ||
```javascript | ||
const sdk = require('@descope/node-sdk'); | ||
const descopeClient = sdk({ projectId: <ProjectID> }); | ||
``` | ||
* Make sure to set the return url to exchange in the Descope Oauth authentication methods settings or use the start first argument. | ||
### 1. Customer Sign-up/Sign-In | ||
In your OAuth start flow (for example, `myapp.com/login-with-facebook`) generate a url to redirect the user to. In the example below the login | ||
```javascript | ||
const out = await descopeClient.oauth.start.facebook(); | ||
return out.data.url; | ||
``` | ||
### 2. Customer Exchange | ||
In your exchange for any of the oauth provider (for example, `mydomain.com/exchange`) verify the code from the provider by using the exchange method. | ||
```javascript | ||
const code = req.query.code | ||
const out = await descopeClient.oauth.exchnage(code); | ||
if (out.data.cookies) { | ||
res.set('Set-Cookie', out.data.cookies); | ||
} | ||
``` | ||
### 3. Session Validation | ||
Session validation checks to see that the visitor to your website or application is who they say they are, by comparing the value in the validation variables against the session data that is already stored. | ||
```javascript | ||
const out = await descopeClient.validateSession(session_jwt, refresh_jwt); | ||
if (out.cookies) { | ||
res.set('Set-Cookie', out.cookies); | ||
} | ||
``` | ||
### 4. Error handling | ||
Each authentication function may return an error upon authentication failure or bad request. In case of an error, you will recieve an sdk response with `ok` equal to false and the error details are also included, such as the `errorCode` and the `errorDescription`. Needless to say, the `data` will be empty whenever an error occur. | ||
```javascript | ||
const out = await descopeClient.oauth.start.facebook(); | ||
if (!out.ok) { | ||
console.log(`an error has occured [code: ${out.errorCode}] with message: "${out.errorDescription}"`) | ||
} else { | ||
... | ||
} | ||
``` | ||
## Run the Examples | ||
@@ -271,2 +66,2 @@ | ||
The Descope ExpresSDK for Go is licensed for use under the terms and conditions of the [MIT license Agreement](https://github.com/descope/go-sdk/blob/main/LICENSE). | ||
The Descope ExpresSDK for Node is licensed for use under the terms and conditions of the [MIT license Agreement](https://github.com/descope/node-sdk/blob/main/LICENSE). |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
762080
1655
66
+ Added@descope/core-js-sdk@0.0.41-alpha.10(transitive)
- Removed@descope/core-js-sdk@0.0.41-alpha.9(transitive)