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 🙏

© 2025 – Pkg Stats / Ryan Hefner

thrilled-be-auth

v1.0.0

Published

Authentication package for Express backend applications with JWT, bcrypt, and Redis support

Readme

be-auth

Comprehensive authentication package for Express backend applications. This package provides JWT token management, password security, session handling, role-based access control (RBAC), and authentication middleware.

Features

  • 🔐 JWT Provider: Access/refresh token management with blacklisting support
  • 🔒 Password Manager: Secure password hashing, validation, and reset flows
  • 📱 Session Manager: Redis-based session management with multi-device support
  • 🛡️ Authentication Middleware: Express middleware for route protection
  • 👥 RBAC System: Role and permission management with hierarchical support
  • 🔧 Utility Functions: Crypto, validation, time, IP, and device utilities
  • Rate Limiting: Built-in rate limiting for authentication endpoints
  • 📊 Event Logging: Comprehensive authentication event tracking

Installation

npm install be-auth

# Using npm
npm install @thrilled/be-auth

Dependencies

This package requires the following peer dependencies:

yarn add ioredis express jsonwebtoken bcrypt be-core be-types be-databases

Quick Start

Basic Setup

import express from 'express';
import Redis from 'ioredis';
import { JWTProvider, PasswordManager, SessionManager, AuthMiddleware, RBACManager, AuthConfig } from '@thrilled/be-auth';

const app = express();
const redis = new Redis(process.env.REDIS_URL);

// Configuration
const config: AuthConfig = {
  jwt: {
    accessToken: {
      secret: process.env.JWT_ACCESS_SECRET,
      expiresIn: '15m',
      algorithm: 'HS256',
    },
    refreshToken: {
      secret: process.env.JWT_REFRESH_SECRET,
      expiresIn: '7d',
      algorithm: 'HS256',
    },
  },
  password: {
    saltRounds: 12,
    minLength: 8,
    requireUppercase: true,
    requireLowercase: true,
    requireNumbers: true,
    requireSpecialChars: true,
  },
  session: {
    defaultTTL: '24h',
    maxSessionsPerUser: 5,
    enableRollingSession: true,
  },
  rbac: {
    enableRoleHierarchy: true,
    defaultRole: 'user',
  },
};

// Initialize components
const jwtProvider = new JWTProvider(redis, config.jwt);
const passwordManager = new PasswordManager(redis, config.password);
const sessionManager = new SessionManager(redis, config.session);
const rbacManager = new RBACManager(redis, config.rbac);
const authMiddleware = new AuthMiddleware(jwtProvider, sessionManager, config);

Authentication Middleware Usage

// Protect all routes under /api/protected
app.use('/api/protected', authMiddleware.requireAuth());

// Admin-only routes
app.use('/api/admin', authMiddleware.requireAdmin());

// Role-based protection
app.get('/api/moderator', authMiddleware.requireRoles(['admin', 'moderator']), (req, res) => {
  res.json({ message: 'Moderator content' });
});

// Permission-based protection
app.post('/api/content', authMiddleware.requirePermissions(['content.write']), (req, res) => {
  res.json({ message: 'Content created' });
});

// Custom authorization
app.get(
  '/api/users/:userId/data',
  authMiddleware.requireAuth(),
  authMiddleware.authorize(async (authContext, req) => {
    return authContext.userId === req.params.userId || authContext.roles.includes('admin');
  }),
  (req, res) => {
    res.json({ data: 'User data' });
  }
);

// Rate limiting
app.post(
  '/api/auth/login',
  authMiddleware.rateLimit(5, 15 * 60 * 1000), // 5 attempts per 15 minutes
  async (req, res) => {
    // Login logic
  }
);

Core Components

JWT Provider

Manages access and refresh tokens with comprehensive security features.

// Create access token
const accessToken = await jwtProvider.createAccessToken({
  userId: 'user123',
  sessionId: 'session456',
  roles: ['user'],
  permissions: ['read', 'write'],
  userData: { email: '[email protected]' },
});

// Create refresh token
const refreshToken = await jwtProvider.createRefreshToken('user123', 'session456');

// Verify tokens
const payload = await jwtProvider.verifyAccessToken(accessToken);
const refreshData = await jwtProvider.verifyRefreshToken(refreshToken);

// Refresh tokens
const newTokens = await jwtProvider.refreshTokens(refreshToken, {
  userData: { email: '[email protected]' },
  roles: ['user'],
  permissions: ['read', 'write'],
});

// Blacklist tokens
await jwtProvider.blacklistToken(accessToken);
await jwtProvider.blacklistUserTokens('user123');

For more detailed documentation, examples, and API reference, see the full documentation in the package.

Building

Run nx build auth to build the library.

Running unit tests

Run nx test auth to execute the unit tests via Jest.