npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@frontegg/client

v5.3.2

Published

Frontegg Javascript Library for backend node servers

Downloads

62,375

Readme

Breaking Changes

  • As of version 3.0.0 and 4.0.0, we will no longer provide proxy middlewares

  • As of version 5.0.0, node 12 is no loner supported.

To see an example implementation, head over to our sample proxy project


Installation

Install the package using npm

# node 14+
npm install @frontegg/client

Usage

Frontegg offers multiple components for integration with the Frontegg's scaleable back end and front end libraries

Initialize the frontegg context when initializing your app

const { FronteggContext } = require('@frontegg/client');

FronteggContext.init({
  FRONTEGG_CLIENT_ID: '<YOUR_CLIENT_ID>',
  FRONTEGG_API_KEY: '<YOUR_API_KEY>',
});

Middleware

Use Frontegg's "withAuthentication" auth guard to protect your routes.

A simple usage example:

const { withAuthentication } = require('@frontegg/client');

// This route can now only be accessed by authenticated users
app.use('/protected', withAuthentication(), (req, res) => {
  // Authenticated user data will be available on the req.frontegg object
  callSomeAction(req.frontegg.user);
  res.status(200);
});

Head over to the Docs to find more usage examples of the guard.

Access tokens

When using M2M authentication, access tokens will be cached by the SDK. By default access tokens will be cached locally, however you can use two other kinds of cache:

  • ioredis
  • redis

Use ioredis as your cache

When initializing your context, pass an access tokens options object with your ioredis parameters

const { FronteggContext } = require('@frontegg/client');

const accessTokensOptions = {
  cache: {
    type: 'ioredis',
    options: {
      host: 'localhost',
      port: 6379,
      password: '',
      db: 10,
    },
  },
};

FronteggContext.init(
  {
    FRONTEGG_CLIENT_ID: '<YOUR_CLIENT_ID>',
    FRONTEGG_API_KEY: '<YOUR_API_KEY>',
  },
  {
    accessTokensOptions,
  },
);

Use redis as your cache

When initializing your context, pass an access tokens options object with your redis parameters

const { FronteggContext } = require('@frontegg/client');

const accessTokensOptions = {
  cache: {
    type: 'redis',
    options: {
      url: 'redis[s]://[[username][:password]@][host][:port][/db-number]',
    },
  },
};

FronteggContext.init(
  {
    FRONTEGG_CLIENT_ID: '<YOUR_CLIENT_ID>',
    FRONTEGG_API_KEY: '<YOUR_API_KEY>',
  },
  {
    accessTokensOptions,
  },
);

Clients

Frontegg provides various clients for seamless integration with the Frontegg API.

For example, Frontegg’s Managed Audit Logs feature allows a SaaS company to embed an end-to-end working feature in just 5 lines of code

Create a new Audits client

const { AuditsClient } = require('@frontegg/client');
const audits = new AuditsClient();

// initialize the module
await audits.init('MY-CLIENT-ID', 'MY-AUDITS-KEY');

Sending audits

await audits.sendAudit({
  tenantId: 'my-tenant-id',
  time: Date(),
  user: '[email protected]',
  resource: 'Portal',
  action: 'Login',
  severity: 'Medium',
  ip: '1.2.3.4',
});

Fetching audits

const { data, total } = await audits.getAudits({
  tenantId: 'my-tenant-id',
  filter: 'any-text-filter',
  sortBy: 'my-sort-field',
  sortDirection: 'asc | desc',
  offset: 0, // Offset for starting the page
  count: 50, // Number of desired items
});

Entitlements Client

Initializing the client


const { EntitlementsClient } = require('@frontegg/client');

// initialize the FronteggContext
FronteggContext.init(
  {
    FRONTEGG_CLIENT_ID: '<YOUR_CLIENT_ID>',
    FRONTEGG_API_KEY: '<YOUR_API_KEY>',
  },
  {
    accessTokensOptions,
  },
);

// initialize entitlements client
const client = await EntitlementsClient.init(/* */);
await client.ready();

Using the client

The client can be used to determine if authorized user or tenant is entitled to particular feature or permission.

First, we need to validate its token, using the IdentityClient:

// validate token and decode its properties
const userOrTenantEntity = await identityClient.validateToken(token, { withRolesAndPermissions: true });

Note, that some JWT tokens might not contain permissions stored in their payloads. Permissions are essential for entitlement decision-making, so remember to add option flag: withRolesAndPermissions: true.

(see Validating JWT manually section for more details).

step-up

The client can be used to verify whether an authorized user has undergone step-up authentication.

You can also require session max age to determine a stepped up user

// Validate the token and decode its properties for a stepped-up user
const steppedUpUserEntity = await identityClient.validateToken(token, { stepUp: true });

// Validate the token with session maximum age requirement (up to one hour) for a stepped-up user
const steppedUpUserEntityWithMaxAge = await identityClient.validateToken(token, { stepUp: { maxAge: 3600 } });

entitlements

When the user/tenant entity is resolved, you can start querying the entitlements engine:

const userEntitlementsClient = client.forUser(userOrTenantEntity);

let result;

// asking for feature entitlement
result = await userEntitlementsClient.isEntitledToFeature('foo');
// or
result = await userEntitlementsClient.isEntitledTo({
  featureKey: 'foo'
});

// asking for permission entitlement
result = await userEntitlementsClient.isEntitledToPermission('foo.read');
// or
result = await userEntitlementsClient.isEntitledTo({
  permissionKey: 'foo'
});

The result of those queries has the following structure:

type IsEntitledResult = {
  result: boolean,
  justficiation?: string
}

When result: true, then justficiation is not given.

Closing the client

To gracefully close the client:

client.destroy();

Working with the REST API

Frontegg provides a comprehensive REST API for your application. In order to use the API from your backend it is required to initialize the client and the authenticator which maintains the backend to backend session

const authenticator = new FronteggAuthenticator();
await authenticator.init('<YOUR_CLIENT_ID>', '<YOUR_API_KEY>');

// You can optionally set the base url from the HttpClient
const httpClient = new HttpClient(authenticator, { baseURL: 'https://api.frontegg.com' });

await httpClient.post(
  'identity/resources/auth/v1/user',
  {
    email: '[email protected]',
    password: 'my-super-duper-password',
  },
  {
    // When providing vendor-host, it will replace(<...>) https://<api>.frontegg.com with vendor host
    'frontegg-vendor-host': 'acme.frontegg',
  },
);

Validating JWT manually

If required you can implement your own middleware which will validate the Frontegg JWT using the IdentityClient

First, let's import the IdentityClient

const { IdentityClient } = require('@frontegg/client');

Then, initialize the client

const identityClient = new IdentityClient({ FRONTEGG_CLIENT_ID: 'your-client-id', FRONTEGG_API_KEY: 'your-api-key' });

And use this client to validate

app.use('/protected', (req, res, next) => {
  const token = req.headers.authorization;
  let user: IUser;
  try {
    user = identityClient.validateIdentityOnToken(token, { roles: ['admin'], permissions: ['read'] });
    req.user = user;
  } catch (e) {
    console.error(e);
    next(e);
    return;
  }

  next();
});