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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@hphudev/core

v1.0.1

Published

Professional toolkit for Express.js and Node.js applications with authentication, logging, and more

Readme

@hphudev/core

🛠️ Professional toolkit for Express.js and Node.js applications with authentication, logging, and more.

Features

🔐 Authentication Module

  • 🎫 JWT Authentication - Access & refresh token management
  • 🔒 Password Hashing - Secure bcrypt-based password hashing
  • 🛡️ Express Middleware - Ready-to-use authentication middleware
  • 🎯 Role & Permission Authorization - Flexible access control

📝 Logger Module

  • 📊 Multiple Log Levels - debug, info, warn, error, fatal
  • 🎨 Pretty & JSON Formatting - Flexible output formats
  • 📁 File Transport with Rotation - Automatic log file management
  • 🌐 Express Request Logging - HTTP request/response logging middleware
  • 👶 Child Loggers - Inherit context across your application

Installation

npm install @hphudev/core
# or
yarn add @hphudev/core
# or
pnpm add @hphudev/core

Quick Start

JWT Authentication

import { JwtService } from '@hphudev/core';

const jwtService = new JwtService({
  accessSecret: process.env.JWT_ACCESS_SECRET!,
  refreshSecret: process.env.JWT_REFRESH_SECRET!,
  accessExpiresIn: '15m',
  refreshExpiresIn: '7d',
});

// Generate token pair
const tokens = jwtService.generateTokenPair({
  sub: 'user-123',
  email: '[email protected]',
  role: 'admin',
});

// Verify access token
const result = jwtService.verifyAccessToken(tokens.accessToken);
if (result.valid) {
  console.log('User ID:', result.payload?.sub);
}

Password Hashing

import { hashPassword, comparePassword, validatePassword } from '@hphudev/core';

// Hash password
const hash = await hashPassword('MySecurePassword123!');

// Verify password
const isValid = await comparePassword('MySecurePassword123!', hash);

// Validate password strength
const validation = validatePassword('weak');
// { valid: false, errors: ['Password must be at least 8 characters long', ...] }

Express Middleware

import express from 'express';
import {
  createAuthMiddleware,
  createRoleMiddleware,
  requestLogger,
  createLogger,
} from '@hphudev/core';

const app = express();

// Logger middleware
const logger = createLogger({ name: 'api', level: 'info' });
app.use(requestLogger(logger));

// Auth middleware
const authMiddleware = createAuthMiddleware({
  secret: process.env.JWT_ACCESS_SECRET!,
  skipPaths: ['/api/auth/login', '/api/public/*'],
});
app.use('/api', authMiddleware);

// Role-based authorization
app.get(
  '/api/admin/dashboard',
  authMiddleware,
  createRoleMiddleware(['admin']),
  (req, res) => res.json({ message: 'Admin dashboard' })
);

Logging

import { Logger, createLogger, fileTransport, jsonFormatter } from '@hphudev/core';

// Create a logger
const logger = createLogger({
  name: 'my-app',
  level: 'debug',
  format: 'pretty', // or 'json'
  colors: true,
});

// Basic logging
logger.debug('Debug message', { userId: '123' });
logger.info('User logged in', { email: '[email protected]' });
logger.warn('Rate limit approaching');
logger.error('Something went wrong', new Error('Oops'));
logger.fatal('Critical failure', new Error('System down'));

// Child logger with inherited context
const userLogger = logger.child({ name: 'users', context: { module: 'auth' } });
userLogger.info('User created'); // Includes module: 'auth' in context

// File logging with rotation
const fileLogger = createLogger({
  transports: [
    {
      transport: fileTransport({
        path: './logs/app.log',
        maxSize: 10 * 1024 * 1024, // 10MB
        maxFiles: 5,
      }),
      formatter: jsonFormatter,
    },
  ],
});

Sub-module Imports

For tree-shaking, import from specific sub-modules:

// JWT only
import { JwtService } from '@hphudev/core/jwt';

// Password only
import { hashPassword, comparePassword } from '@hphudev/core/password';

// Middleware only
import { createAuthMiddleware } from '@hphudev/core/middleware';

// Logger only
import { Logger, createLogger } from '@hphudev/core/logger';

API Reference

JWT Module (@hphudev/core/jwt)

| Export | Description | |--------|-------------| | JwtService | Full JWT management class | | createJwtService(config) | Create JwtService instance | | generateTokens(payload, config) | Quick token pair generation | | verifyAccessToken(token, secret) | Quick access token verification | | verifyRefreshToken(token, secret) | Quick refresh token verification |

Password Module (@hphudev/core/password)

| Export | Description | |--------|-------------| | PasswordService | Full password management class | | hashPassword(password, saltRounds?) | Hash a password | | comparePassword(password, hash) | Verify a password | | validatePassword(password, options?) | Validate password strength | | generatePassword(length?) | Generate random password |

Middleware Module (@hphudev/core/middleware)

| Export | Description | |--------|-------------| | createAuthMiddleware(options) | JWT authentication middleware | | createOptionalAuthMiddleware(options) | Optional authentication | | createRoleMiddleware(roles, options?) | Role-based authorization | | createPermissionMiddleware(permissions, options?) | Permission-based authorization | | extractBearerToken(req) | Extract token from Authorization header | | extractCookieToken(cookieName) | Extract token from cookie |

Logger Module (@hphudev/core/logger)

| Export | Description | |--------|-------------| | Logger | Full logger class | | createLogger(config?) | Create Logger instance | | debug/info/warn/error/fatal | Quick logging functions | | jsonFormatter | JSON output formatter | | prettyFormatter(colors?) | Human-readable formatter | | consoleTransport() | Console output transport | | fileTransport(options) | File output with rotation | | memoryTransport(store) | In-memory storage (testing) | | createRequestLogger(logger?, options?) | Express request logging | | createErrorLogger(logger?) | Express error logging |

Error Handling

import { AuthError, AuthErrorCode } from '@hphudev/core';

try {
  const result = jwtService.refreshTokens(invalidToken);
} catch (error) {
  if (error instanceof AuthError) {
    console.log(error.code);       // e.g., 'TOKEN_EXPIRED'
    console.log(error.statusCode); // e.g., 401
  }
}

TypeScript Support

Full TypeScript support with comprehensive type definitions:

import type {
  // Auth types
  TokenPayload, TokenPair, JwtConfig, VerifiedToken,
  PasswordConfig, PasswordValidationOptions,
  AuthMiddlewareOptions, AuthRequest, AuthResponse,
  // Logger types
  LoggerConfig, LogEntry, LogFormatter, LogTransport,
  FileTransportOptions, RequestLoggerOptions,
} from '@hphudev/core';

License

MIT