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

firefun-node-auth

v0.1.0-alpha.18

Published

A secure, production-ready Node.js authentication package with JWT, 2FA, passkeys, and more

Readme

🔐 firefun-node-auth

Alpha Release - A secure, production-ready Node.js authentication package built by FireFun Games.

A comprehensive authentication solution featuring JWT tokens, 2FA, passkeys (WebAuthn), rate limiting, and automated cleanup. Extracted from our production auth system and packaged for reuse across Node.js projects.

✨ Features

Core Authentication

  • User Registration & Login - Secure user account creation and authentication
  • JWT Token Management - Access tokens with refresh token rotation
  • Password Security - Bcrypt hashing with configurable rounds
  • Input Validation - Zod schemas for comprehensive request validation

Advanced Security

  • Two-Factor Authentication (2FA) - TOTP-based 2FA with QR codes
  • Passkeys (WebAuthn) - Modern passwordless authentication
  • Rate Limiting - Configurable protection against brute force attacks
  • Encrypted Secrets - AES-256-GCM encryption for sensitive 2FA data
  • Token Cleanup - Automated cleanup of expired tokens and challenges
  • Account Management - Secure account deletion with cascade cleanup

Infrastructure Features

  • Database Management - PostgreSQL with Prisma ORM
  • TypeScript - Full type safety across the package
  • Modular Design - Use individual components or the complete solution
  • Scheduled Jobs - Background cleanup tasks with node-cron
  • Express Integration - Ready-to-use middleware and routes
  • Serverless Optimized - Lazy loading and cold start optimization for Vercel, AWS Lambda, etc.

🛠️ Tech Stack

  • Runtime: Node.js (>=16)
  • Framework: Express.js
  • Language: TypeScript
  • Database: PostgreSQL with Prisma
  • Authentication: JWT, TOTP, WebAuthn
  • Security: bcrypt, AES-256-GCM encryption, rate limiting

🚀 Installation

npm install firefun-node-auth @prisma/client express

# Quick database setup
npx firefun-auth-setup

📖 Quick Start

1. Basic Setup

import express from 'express';
import { PrismaClient } from '@prisma/client';
import { FirefunAuth } from 'firefun-node-auth';

const app = express();
const prisma = new PrismaClient();

// Initialize FirefunAuth
const auth = new FirefunAuth({
  appName: 'My App',
  prisma,
  jwt: {
    secret: process.env.JWT_SECRET!,
    expiresIn: '15m',
    refreshExpiresIn: '7d',
  },
  security: {
    bcryptRounds: 12,
  },
  encryption: {
    keys: {
      v1: process.env.ENCRYPTION_KEY_V1!,
    },
    currentVersion: 'v1',
  },
  webauthn: {
    rpName: 'My App',
    rpId: 'localhost',
    origin: 'http://localhost:3000',
  },
  rateLimiting: {
    general: { windowMs: 900000, maxRequests: 100, message: 'Too many requests' },
    auth: { windowMs: 900000, maxRequests: 5, message: 'Too many auth attempts' },
    twoFA: { windowMs: 900000, maxRequests: 3, message: 'Too many 2FA attempts' },
  },
  scheduler: {
    schedule: '0 2 * * *', // Daily at 2 AM
    timezone: 'America/New_York',
  },
});

// Apply general rate limiting
app.use(auth.getRateLimitMiddleware().general);

// Setup routes
app.use('/api/auth', auth.createAuthRoutes());
app.use('/api/passkey', auth.createPasskeyRoutes());

// Start cleanup scheduler
auth.startScheduler();

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

2. Serverless Usage (Vercel, AWS Lambda, etc.)

For optimal serverless performance:

import { FirefunAuth } from 'firefun-node-auth';

// Enable serverless mode for faster cold starts
const auth = new FirefunAuth({
  // ... your config
  serverless: true, // 🚀 Enable serverless optimizations
});

// Use lazy-loaded components
app.use('/api/auth', auth.createAuthRoutes());

Or use standalone functions for individual endpoints:

// api/auth/register.js (Vercel function)
import { registerUserWithRateLimit } from 'firefun-node-auth/serverless';

export default async function handler(req, res) {
  return registerUserWithRateLimit(req, res, {
    // your config here
    serverless: true,
  });
}

Available serverless functions:

import {
  registerUser,
  loginUser,
  loginWith2FA,
  refreshTokenHandler,
  generate2FASecret,
  // ... and more
} from 'firefun-node-auth/serverless';

3. Database Setup

Option 1: Automatic Setup (Recommended)

npx firefun-auth-setup

This will automatically:

  • Copy Prisma schema and migrations to your project
  • Generate the Prisma client
  • Run database migrations
  • Validate your setup

Option 2: Manual Setup

# Copy schema and migrations
cp node_modules/firefun-node-auth/prisma/schema.prisma ./prisma/
cp -r node_modules/firefun-node-auth/prisma/migrations ./prisma/

# Generate client and run migrations
npx prisma generate
npx prisma migrate deploy

4. Environment Configuration

Create your .env file:

# Database
DATABASE_URL="postgresql://user:password@localhost:5432/myapp"

# JWT (required - min 32 chars)
JWT_SECRET="your-super-secret-jwt-key-at-least-32-characters-long"

# Encryption (required - min 32 chars)
ENCRYPTION_KEY_V1="your-encryption-key-v1-at-least-32-characters-long"

# Optional configurations
PORT=3000
NODE_ENV=development

📚 API Endpoints

Authentication Routes (/api/auth)

  • POST /register - User registration
  • POST /login - User login (with 2FA support)
  • POST /login/2fa - Complete 2FA login
  • POST /refresh - Refresh access token
  • POST /2fa/generate - Generate 2FA secret (protected)
  • POST /2fa/confirm - Enable 2FA (protected)
  • POST /2fa/reset - Reset 2FA (protected)
  • POST /2fa/disable - Disable 2FA (protected)
  • DELETE /account - Delete account (protected)

Passkey Routes (/api/passkey)

  • POST /authenticate/start - Start passkey authentication
  • POST /authenticate/complete - Complete passkey authentication
  • POST /register/start - Start passkey registration (protected)
  • POST /register/complete - Complete passkey registration (protected)
  • GET /list - List user's passkeys (protected)
  • DELETE /:id - Delete passkey (protected)
  • PATCH /:id/rename - Rename passkey (protected)

Protected Route Example

import { AuthenticatedRequest } from 'firefun-node-auth';

// Protect routes with the auth middleware
app.get('/api/profile', auth.getAuthMiddleware(), (req: AuthenticatedRequest, res) => {
  const userId = req.userId; // Available after auth middleware
  res.json({ message: `Hello user ${userId}` });
});

🚀 Serverless Performance

Cold Start Optimization

The package includes several optimizations for serverless environments:

  • Lazy Initialization: Heavy components only load when needed
  • Reduced Memory Footprint: Minimal upfront initialization
  • Faster Cold Starts: < 100ms initialization in serverless mode
  • Optimized Dependencies: Dynamic imports for heavy libraries
  • Background Tasks Disabled: No scheduler in serverless mode

Performance Comparison

| Mode | Cold Start Time | Memory Usage | Initialization | |------|----------------|--------------|----------------| | Traditional | ~500ms | High | All upfront | | Serverless | < 100ms | Low | Lazy loaded |

Vercel Deployment Example

// api/auth/[...auth].ts
import { FirefunAuth } from 'firefun-node-auth';

const auth = new FirefunAuth({
  // your config
  serverless: true,
});

export default async function handler(req, res) {
  const authRouter = auth.createAuthRoutes();
  return authRouter(req, res);
}

🔧 Advanced Usage

Custom Rate Limiting

const rateLimits = auth.getRateLimitMiddleware();

// Apply specific rate limits to custom routes
app.use('/api/sensitive', rateLimits.twoFA);

Manual Cleanup

// Trigger cleanup manually
const result = await auth.performCleanup();
console.log(`Cleaned up ${result.refreshTokensDeleted} tokens and ${result.challengesDeleted} challenges`);

Using Individual Components

import { AuthController, AuthMiddleware, CleanupService } from 'firefun-node-auth';

// Use components individually for custom implementations
const authMiddleware = new AuthMiddleware({ jwtSecret: 'your-secret' });
const cleanupService = new CleanupService(prisma);

🔒 Security Features

Password Requirements

  • Minimum 8 characters (configurable)
  • At least one uppercase letter
  • At least one number
  • At least one special character

2FA Implementation

  • TOTP-based (compatible with Google Authenticator, Authy, etc.)
  • QR code generation for easy setup
  • Encrypted storage of secrets using AES-256-GCM
  • Password verification required for all 2FA operations

Rate Limiting

  • General: 100 requests per 15 minutes
  • Authentication: 5 attempts per 15 minutes
  • 2FA Operations: 3 attempts per 15 minutes

Token Security

  • Short-lived access tokens (15 minutes default)
  • Refresh token rotation
  • Automatic cleanup of expired tokens

🏗️ Architecture

The package follows a modular architecture:

firefun-node-auth/
├── controllers/     # Business logic (Auth, Passkey)
├── middleware/      # Express middleware (Auth, Rate Limiting)
├── services/        # Background services (Cleanup)
├── utils/           # Utilities (Encryption)
├── schemas/         # Validation schemas
├── jobs/            # Scheduled job management
└── types/           # TypeScript type definitions

📋 Requirements

  • Node.js: >= 16.0.0
  • Database: PostgreSQL (via Prisma)
  • Express: >= 5.0.0

🔧 Troubleshooting

Setup Issues

"No package.json found" error:

  • Make sure you're running npx firefun-auth-setup in your project root

Database connection errors:

  • Verify your DATABASE_URL in .env is correct
  • Make sure your database server is running
  • Try running npx prisma migrate deploy manually

Permission errors:

  • On macOS/Linux, you might need to run with elevated permissions
  • Try: sudo npx firefun-auth-setup

Existing Prisma setup:

  • The setup script backs up existing files to .backup extensions
  • Review and merge any custom changes from your backups

Getting Help

🧪 Development

For package development:

git clone https://github.com/firefun-games/node-auth-package.git
cd node-auth-package
npm install
npm run build

📋 Changelog

v0.1.0-alpha.4 - Enhanced Error Handling

  • Centralized Error Handler: New intelligent error categorization system
  • Improved Error Messages: Specific, actionable error responses instead of generic "Internal server error"
  • Database Error Handling: User-friendly messages for Prisma errors (connection issues, duplicates, etc.)
  • JWT Error Improvements: Clear messages for expired/invalid tokens with guidance
  • JSON Parsing Errors: Detailed error context for malformed requests
  • Security Focused: No sensitive internal details exposed in error responses
  • Consistent Format: Standardized error response structure across all endpoints

v0.1.0-alpha.3 - Previous Release

  • Authentication system with JWT, 2FA, and passkeys
  • Serverless optimization
  • Rate limiting and cleanup jobs

📄 License

ISC License. See LICENSE file for details.

🤝 Contributing

This package is currently in alpha. Issues and suggestions welcome!

🚀 About FireFun Games

Built with ❤️ by FireFun Games for our Node.js projects and shared with the community.


⭐ If this package helps secure your Node.js applications, please consider giving it a star!