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

@bernierllc/auth-suite

v1.0.4

Published

Complete authentication suite with multi-provider support, session management, role-based access control, and MFA

Readme

@bernierllc/auth-suite

Complete authentication suite with multi-provider support, session management, role-based access control, and multi-factor authentication.

Features

  • 🔐 Complete Authentication - Built on @bernierllc/auth-service
  • 💫 Enhanced Session Management - Memory, Redis, or database storage with auto-cleanup
  • 🛡️ Role-Based Access Control (RBAC) - Hierarchical roles and permissions
  • 📱 Multi-Factor Authentication - TOTP, SMS, email, and backup codes
  • 📊 Comprehensive Audit Logging - Track all authentication events
  • 🔌 OAuth/SAML/LDAP Integration - Multiple provider support
  • 🚀 Advanced Security Features - Session management, permission checks
  • 📈 Production Ready - Built with crypto-utils for enterprise security

Installation

npm install @bernierllc/auth-suite

Quick Start

import { AuthSuite } from '@bernierllc/auth-suite';

// Initialize with enhanced features
const authSuite = new AuthSuite({
  // Core auth configuration
  jwt: {
    secret: process.env.JWT_SECRET,
    expiresIn: '15m',
    refreshExpiresIn: '7d'
  },
  
  // Enhanced session management
  sessions: {
    enabled: true,
    storage: 'memory', // or 'redis', 'database'
    cleanup: {
      enabled: true,
      intervalMs: 60000, // 1 minute
      maxIdleMs: 24 * 60 * 60 * 1000 // 24 hours
    }
  },

  // Role-based access control
  rbac: {
    enabled: true,
    hierarchical: true,
    roles: [
      {
        name: 'admin',
        description: 'System administrator',
        permissions: ['*:*'] // All permissions
      },
      {
        name: 'user',
        description: 'Regular user',
        permissions: ['profile:read', 'profile:update']
      }
    ],
    permissions: [
      {
        name: 'profile:read',
        description: 'Read user profile',
        resource: 'profile',
        actions: ['read']
      }
    ]
  },

  // Multi-factor authentication
  mfaEnhanced: {
    enabled: true,
    providers: [
      {
        type: 'totp',
        name: 'Google Authenticator',
        enabled: true,
        config: {}
      }
    ],
    requirements: [
      {
        trigger: 'login',
        providers: ['totp'],
        conditions: {}
      }
    ]
  },

  // Audit logging
  auditing: {
    enabled: true,
    events: ['login', 'logout', 'register', 'permission_change'],
    storage: 'file',
    retention: {
      days: 90,
      maxSize: '100MB'
    }
  }
});

// Register user with enhanced features
const registerResult = await authSuite.register({
  username: 'johndoe',
  email: '[email protected]',
  password: 'SecurePass123!',
  firstName: 'John',
  lastName: 'Doe',
  acceptTerms: true
});

if (registerResult.success) {
  console.log('User registered with session:', registerResult.session);
  console.log('Assigned permissions:', registerResult.permissions);
}

// Login with potential MFA
const loginResult = await authSuite.login({
  email: '[email protected]',
  password: 'SecurePass123!'
});

if (loginResult.mfaRequired) {
  console.log('MFA required, challenge:', loginResult.mfaChallenge);
  
  // Complete MFA verification
  const mfaResult = await authSuite.completeMfaLogin(
    loginResult.mfaChallenge.challengeId,
    '123456' // TOTP code from authenticator app
  );
  
  if (mfaResult.success) {
    console.log('Login complete with MFA');
  }
}

Core Features

Enhanced Session Management

// Session automatically created on login/register
const result = await authSuite.login(credentials);
if (result.success && result.session) {
  console.log('Session ID:', result.session.sessionId);
  console.log('Expires at:', result.session.expiresAt);
}

// Manual session management
const session = await authSuite.sessionManager.create('user-id', {
  customData: 'value'
});

// Cleanup expired sessions
const cleaned = await authSuite.cleanup();
console.log(`Cleaned up ${cleaned.sessions} expired sessions`);

Role-Based Access Control (RBAC)

// Check permissions
const permissionResult = await authSuite.checkPermission({
  userId: 'user-123',
  resource: 'documents',
  action: 'delete',
  context: { ownerId: 'user-123' }
});

if (permissionResult.allowed) {
  console.log('User can delete documents');
} else {
  console.log('Access denied:', permissionResult.reason);
}

// Assign roles
await authSuite.rbacManager.assignRole('user-123', 'admin');

// Get user permissions
const permissions = await authSuite.getUserPermissions('user-123');
console.log('User permissions:', permissions);

Multi-Factor Authentication

// Setup MFA for user
const mfaSetup = await authSuite.setupMfa('user-123', 'totp');
console.log('Show QR code to user:', mfaSetup.qrCode);

// Verify setup
const setupVerified = await authSuite.mfaManager.verifySetup('user-123', '123456');

// Generate backup codes
const backupCodes = await authSuite.mfaManager.regenerateBackupCodes('user-123');
console.log('Backup codes:', backupCodes);

// Verify backup code
const backupValid = await authSuite.mfaManager.verifyBackupCode('user-123', 'backup-code');

Audit Logging

// Logs are automatically generated for auth events
// Query audit logs
const auditLogs = await authSuite.getAuditLogs({
  userId: 'user-123',
  event: 'login',
  startDate: new Date('2025-01-01'),
  limit: 50
});

// Get audit statistics
const stats = await authSuite.auditManager.getLogStats();
console.log('Audit stats:', stats);

// Search logs
const searchResults = await authSuite.auditManager.searchLogs('failed login');

Configuration

Complete Configuration Options

interface AuthSuiteConfig {
  // Core auth service configuration
  jwt: {
    secret: string;
    issuer?: string;
    audience?: string;
    expiresIn?: string | number;
    refreshExpiresIn?: string | number;
    algorithm?: JWTAlgorithm;
  };

  // Password policy
  password: {
    minLength: number;
    requireUppercase: boolean;
    requireLowercase: boolean;
    requireNumbers: boolean;
    requireSymbols: boolean;
    preventReuse?: number;
    maxAge?: number;
  };

  // Enhanced session management
  sessions?: {
    enabled?: boolean; // default: true
    storage?: 'memory' | 'redis' | 'database'; // default: 'memory'
    cleanup?: {
      enabled: boolean; // default: true
      intervalMs: number; // default: 60000 (1 minute)
      maxIdleMs: number; // default: 24 hours
    };
    persistence?: {
      enabled: boolean; // default: false
      ttl: number; // default: 7 days
    };
  };

  // Role-based access control
  rbac?: {
    enabled: boolean; // default: false
    hierarchical: boolean; // default: false
    roles: RoleDefinition[];
    permissions: PermissionDefinition[];
  };

  // Multi-factor authentication
  mfaEnhanced?: {
    enabled: boolean; // default: false
    providers: MfaProvider[];
    requirements: MfaRequirement[];
    backup: {
      enabled: boolean; // default: true
      codeCount: number; // default: 10
      codeLength: number; // default: 8
    };
  };

  // Audit logging
  auditing?: {
    enabled: boolean; // default: true
    events: AuditEvent[];
    storage: 'file' | 'database' | 'external'; // default: 'file'
    retention: {
      days: number; // default: 90
      maxSize: string; // default: '100MB'
    };
  };

  // Security settings
  security: {
    maxLoginAttempts: number;
    lockoutDuration: number;
    sessionTimeout: number;
    requireEmailVerification: boolean;
    allowMultipleSessions: boolean;
  };
}

Role Definition

interface RoleDefinition {
  name: string;
  description: string;
  permissions: string[]; // e.g., ['users:read', 'documents:*']
  parent?: string; // for hierarchical roles
  metadata?: Record<string, any>;
}

Permission Definition

interface PermissionDefinition {
  name: string; // e.g., 'documents:delete'
  description: string;
  resource: string; // e.g., 'documents'
  actions: string[]; // e.g., ['delete']
  conditions?: PermissionCondition[]; // conditional permissions
}

API Reference

Class: AuthSuite

Core Authentication

  • register(credentials: RegisterCredentials): Promise<AuthSuiteResult>
  • login(credentials: LoginCredentials): Promise<AuthSuiteResult>
  • verifyToken(token: string): Promise<User | null>
  • logout(sessionId?: string): Promise<{success: boolean}>

MFA Management

  • setupMfa(userId: string, type: string): Promise<{secret: string; qrCode?: string}>
  • completeMfaLogin(challengeId: string, response: string): Promise<AuthSuiteResult>

Permission Management

  • checkPermission(check: PermissionCheck): Promise<PermissionResult>
  • getUserRoles(userId: string): Promise<string[]>
  • getUserPermissions(userId: string): Promise<string[]>

Audit and Cleanup

  • getAuditLogs(filters: AuditQueryFilters): Promise<AuditLog[]>
  • cleanup(): Promise<{sessions: number; auditLogs: number}>

Manager Classes

For advanced usage, managers can be used directly:

import { 
  MemorySessionManager, 
  BasicRBACManager, 
  TOTPMfaManager, 
  FileAuditManager 
} from '@bernierllc/auth-suite';

Integration with Crypto-Utils

This suite leverages @bernierllc/crypto-utils for:

  • JWT Generation & Verification - Secure token handling
  • Magic Links - Password reset functionality
  • API Key Generation - MFA backup codes and secrets
  • Password Hashing - Secure password storage

Dependencies

  • @bernierllc/auth-service - Core authentication service
  • @bernierllc/crypto-utils - Cryptographic utilities
  • @bernierllc/logger - Structured logging
  • bcrypt - Password hashing
  • uuid - Unique ID generation

Production Considerations

Session Storage

For production deployments:

  • Memory: Fast but not persistent, use for single-instance apps
  • Redis: Recommended for multi-instance deployments
  • Database: Use for full persistence and audit requirements

Security

  • Use strong JWT secrets (256-bit minimum)
  • Enable MFA for sensitive applications
  • Configure appropriate session timeouts
  • Monitor audit logs for suspicious activity
  • Use HTTPS in production
  • Implement rate limiting

Performance

  • Cleanup expired sessions regularly
  • Index audit log queries for performance
  • Consider external audit log storage for high-volume applications
  • Use Redis for session storage in clustered environments

Examples

Basic Usage

const authSuite = new AuthSuite({
  jwt: { secret: process.env.JWT_SECRET },
  sessions: { enabled: true },
  auditing: { enabled: true }
});

Enterprise Setup

const authSuite = new AuthSuite({
  jwt: {
    secret: process.env.JWT_SECRET,
    expiresIn: '15m',
    refreshExpiresIn: '7d',
    issuer: 'mycompany.com'
  },
  rbac: {
    enabled: true,
    hierarchical: true,
    roles: enterpriseRoles,
    permissions: enterprisePermissions
  },
  mfaEnhanced: {
    enabled: true,
    providers: [
      { type: 'totp', name: 'Authenticator', enabled: true, config: {} }
    ],
    requirements: [
      { trigger: 'login', providers: ['totp'] }
    ]
  },
  sessions: {
    storage: 'redis',
    cleanup: { enabled: true, intervalMs: 30000 }
  },
  auditing: {
    enabled: true,
    storage: 'database',
    retention: { days: 365, maxSize: '1GB' }
  }
});

License

Copyright (c) 2025 Bernier LLC. All rights reserved.