MCPcopy Index your code
hub / github.com/descope/node-sdk

github.com/descope/node-sdk @v2.12.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v2.12.0 ↗ · + Follow
99 symbols 304 edges 73 files 18 documented · 18%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Descope SDK for Node.js

The Descope SDK for Node.js provides convenient access to the Descope user management and authentication API for a backend written in Node.js. You can read more on the Descope Website.

Requirements

The SDK supports Node version 16 and above.

Installing the SDK

Install the package with:

npm i --save @descope/node-sdk

Authentication Functions

Setup

Before you can use authentication functions listed below, you must initialize descopeClient to use all of the built-in SDK functions.

You'll need your Descope Project ID to create this, and you can find it on the project page in the Descope Console.

import DescopeClient from '@descope/node-sdk';

const descopeClient = DescopeClient({ projectId: 'my-project-ID' });

Once you've created a descopeClient, you can use that to work with the following functions:

  1. OTP Authentication
  2. Magic Link
  3. Enchanted Link
  4. OAuth
  5. SSO/SAML
  6. TOTP Authentication
  7. Passwords
  8. Session Validation
  9. Roles & Permission Validation
  10. Logging Out

Management Functions

Setup

Before you can use management functions listed below, you must initialize descopeClient.

If you wish to also use management functions, you will need to initialize a new version of your descopeClient, but this time with a ManagementKey as well as your Project ID. Create a management key in the Descope Console.

import DescopeClient from '@descope/node-sdk';

const descopeClient = DescopeClient({
  projectId: 'my-project-ID',
  managementKey: 'management-key',
});

Then, you can use that to work with the following functions:

  1. Manage Tenants
  2. Manage Users
  3. Manage Access Keys
  4. Manage SSO Setting
  5. Manage Permissions
  6. Manage Roles
  7. Query SSO Groups
  8. Manage Flows
  9. Manage JWTs
  10. Impersonate
  11. Embedded Links
  12. Audit
  13. Manage FGA (Fine-grained Authorization)
  14. Manage Project
  15. Manage SSO applications
  16. Manage Management Keys
  17. Manage Descopers
  18. Manage Engines

If you wish to run any of our code samples and play with them, check out our Code Examples section.

If you're performing end-to-end testing, check out the Utils for your end to end (e2e) tests and integration tests section. You will need to use the descopeClient you created under the setup of Management Functions.

Authentication Management Key

The authManagementKey is an alternative to the managementKey that provides a way to perform management operations while maintaining separation between authentication and management clients.

Key Differences

  • Purpose: Use authManagementKey for authentication-related management operations, while managementKey is for general management operations
  • Client Separation: You can have one client for management operations and another for authentication operations
  • Mutual Exclusivity: You cannot pass both authManagementKey and managementKey together - choose one based on your use case

Usage Examples

Using authManagementKey for authentication operations:

import DescopeClient from '@descope/node-sdk';

const authClient = DescopeClient({
  projectId: 'my-project-ID',
  authManagementKey: 'auth-management-key',
});

// This client can be used for authentication-related management operations

Separate clients for different operations:

import DescopeClient from '@descope/node-sdk';

// Client for general management operations
const managementClient = DescopeClient({
  projectId: 'my-project-ID',
  managementKey: 'management-key',
});

// Client for authentication operations
const authClient = DescopeClient({
  projectId: 'my-project-ID',
  authManagementKey: 'auth-management-key',
});

// Use managementClient for user management, tenant management, etc.
// Use authClient for authentication-related operations

Note: Create your authentication management key in the Descope Console, similar to how you create a regular management key.


Error Handling

Every async operation may fail. In case it does, there will be information regarding what happened on the response object. A typical case of error handling might look something like:

import DescopeClient, { SdkResponse } from '@descope/node-sdk';

const { DescopeErrors } = DescopeClient;

// ...

try {
  const resp = await sdk.otp.signIn.email(loginId);
  if (resp.error) {
    switch (resp.error.errorCode) {
      case DescopeErrors.userNotFound:
        // Handle specifically
        break;
      default:
      // Handle generally
      // `resp.error` will contain `errorCode`, `errorDescription` and sometimes `errorMessage` to
      // help understand what went wrong. See SdkResponse for more information.
    }
  }
} catch (e) {
  // Handle technical error
}

OTP Authentication

Send a user a one-time password (OTP) using your preferred delivery method (Email / SMS / Voice call / WhatsApp). An email address or phone number must be provided accordingly.

The user can either sign up, sign in or sign up or in

// Every user must have a login ID. All other user information is optional
const loginId = 'desmond@descope.com';
const user = {
  name: 'Desmond Copland',
  phone: '212-555-1234',
  email: loginId,
};
await descopeClient.otp.signUp['email'](loginId, user);

The user will receive a code using the selected delivery method. Verify that code using:

const jwtResponse = await descopeClient.otp.verify['email'](loginId, 'code');
// jwtResponse.data.sessionJwt
// jwtResponse.data.refreshJwt

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

Magic Link

Send a user a Magic Link using your preferred delivery method (email / SMS). The Magic Link will redirect the user to page where the its token needs to be verified. This redirection can be configured in code, or globally in the Descope Console

The user can either sign up, sign in or sign up or in

// If configured globally, the redirect URI is optional. If provided however, it will be used
// instead of any global configuration
const URI = 'http://myapp.com/verify-magic-link';
await descopeClient.magicLink.signUpOrIn['email']('desmond@descope.com', URI);

To verify a magic link, your redirect page must call the validation function on the token (t) parameter (https://your-redirect-address.com/verify?t=<token>):

const jwtResponse = await descopeClient.magicLink.verify('token');
// jwtResponse.data.sessionJwt;
// jwtResponse.data.refreshJwt;

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

Enchanted Link

Using the Enchanted Link APIs enables users to sign in by clicking a link delivered to their email address. The email will include 3 different links, and the user will have to click the right one, based on the 2-digit number that is displayed when initiating the authentication process.

This method is similar to Magic Link but differs in two major ways:

  • The user must choose the correct link out of the three, instead of having just one single link.
  • This supports cross-device clicking, meaning the user can try to log in on one device, like a computer, while clicking the link on another device, for instance a mobile phone.

The Enchanted Link will redirect the user to page where the its token needs to be verified. This redirection can be configured in code per request, or set globally in the Descope Console.

The user can either sign up, sign in or sign up or in

// If configured globally, the redirect URI is optional. If provided however, it will be used
// instead of any global configuration.
const URI = 'http://myapp.com/verify-enchanted-link';
const enchantedLinkRes = await descopeClient.enchantedLink.signIn('desmond@descope.com', URI);
enchantedLinkRes.data.linkId; // Should be displayed to the user so they can click the corresponding link in the email
enchantedLinkRes.data.pendingRef; // Used to poll for a valid session

After sending the link, you must poll to receive a valid session using the pendingRef from the previous step. A valid session will be returned only after the user clicks the right link.

// Poll for a certain number of tries / time frame. You can control the polling interval and time frame
// with the optional WaitForSessionConfig
const jwtResponse = await descopeClient.enchantedLink.waitForSession(
  enchantedLinkRes.data.pendingRef,
);
// jwtResponse.data.sessionJwt;
// jwtResponse.data.refreshJwt;

To verify an enchanted link, your redirect page must call the validation function on the token (t) parameter (https://your-redirect-address.com/verify?t=<token>). Once the token is verified, the session polling will receive a valid response.

try {
  await descopeClient.enchantedLink.verify('token');
  // token is invalid
} catch (error) {
  // token is valid
}

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

OAuth

Users can authenticate using their social logins, via the OAuth protocol. Configure your OAuth settings on the Descope console. To start an OAuth flow call:

// Choose an oauth provider out of the supported providers
// If configured globally, the return URL is optional. If provided however, it will be used
// instead of any global configuration.

const urlRes = await descopeClient.oauth.start['google'](redirectUrl);
urlRes.data.url; // Redirect the user to the returned URL to start the OAuth redirect chain

The user will authenticate with the authentication provider, and will be redirected back to the redirect URL, with an appended code HTTP URL parameter. Exchange it to validate the user:

const jwtResponse = await descopeClient.oauth.exchange('token');
// jwtResponse.data.sessionJwt;
// jwtResponse.data.refreshJwt;

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

SSO/SAML

Users can authenticate to a specific tenant using SAML or Single Sign On. Configure your SSO/SAML settings on the Descope console. To start a flow call:

// If configured globally, the return URL is optional. If provided however, it will be used
// instead of any global configuration.
const redirectUrl = 'https://my-app.com/handle-saml';
const urlRes = await descopeClient.saml.start('tenant'); // Choose which tenant to log into. An email can also be provided here and the domain will be extracted from it
urlRes.data.url; // Redirect the user to the given returned URL to start the SSO/SAML redirect chain

The user will authenticate with the authentication provider configured for that tenant, and will be redirected back to the redirect URL, with an appended code HTTP URL parameter. Exchange it to validate the user:

const jwtResponse = await descopeClient.saml.exchange('token');
// jwtResponse.data.sessionJwt;
// jwtResponse.data.refreshJwt;

The session and refresh JWTs should be returned to the caller, and passed with every request in the session. Read more on session validation

TOTP Authentication

The user can authenticate using an authenticator app, such as Google Authenticator. Sign up like you would using any other authentication method. The sign up response will then contain a QR code image that can be displayed to the user to scan using their mobile device camera app, or the user can enter the key manually or click on the link provided by the provisioningURL.

Existing users can add TOTP using the update function.

// Every user must have a login ID. All other user information is optional
const loginId = 'desmond@descope.com';
const user = {
  name: 'Desmond Copland',
  phone: '212-555-1234',
  email: loginId,
};
const totpRes = await descopeClient.totp.signUp(loginId, user);
// Use one of the provided options to have the user add their credentials to the authenticator
totpRes.data.provisioningURL;
totpRes.data.image;
totpRes.data.key;

There are 3 different ways to allow the user to save their credentials in their authenticator app - either by clicking the provisioning URL, scanning the QR image or inserting the key manually. After that, signing in is done using the code the app produces.

```typescript const jwtResponse = await descopeClient.totp.verify(loginId, 'code'); // jwtResponse.data.sessionJwt; // jwtResponse.data.refreshJwt

Extension points exported contracts — how you extend this code

Token (Interface)
Parsed JWT token
lib/types.ts
PatchUserOptions (Interface)
(no doc)
lib/management/user.ts
IDPResponse (Interface)
(no doc)
lib/types.ts
FGAResourceIdentifier (Interface)
(no doc)
lib/management/types.ts
AuthenticationInfo (Interface)
(no doc)
lib/types.ts
FGAResourceDetails (Interface)
(no doc)
lib/management/types.ts
RefreshAuthenticationInfo (Interface)
(no doc)
lib/types.ts
UserOptions (Interface)
(no doc)
lib/management/types.ts

Core symbols most depended-on inside this repo

handleSdkRes
called by 98
examples/managementCli/src/index.ts
WithFGA
called by 32
lib/management/fga.ts
withManagement
called by 30
lib/management/index.ts
resetMockHttpClient
called by 27
lib/management/testutils.ts
returnOK
called by 11
examples/es6/src/index.ts
returnCookies
called by 7
examples/es6/src/index.ts
setCookies
called by 7
examples/commonjs/index.js
getCookieValue
called by 6
lib/helpers.ts

Shape

Function 90
Interface 9

Languages

TypeScript100%

Modules by API surface

lib/index.ts16 symbols
lib/management/user.ts9 symbols
lib/helpers.ts7 symbols
lib/index.test.ts6 symbols
examples/es6/src/index.ts6 symbols
lib/types.ts5 symbols
examples/commonjs/index.js5 symbols
lib/management/types.ts3 symbols
lib/management/sso.ts3 symbols
rollup.config.js2 symbols
lib/management/testutils.ts2 symbols
lib/management/fga.ts2 symbols

For agents

$ claude mcp add node-sdk \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact