npm package: @hphudev/core
Description: Professional toolkit for Express.js and Node.js applications with authentication, logging, and more
Author: hphudev
Latest version: 1.0.1

# @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

```bash
npm install @hphudev/core
# or
yarn add @hphudev/core
# or
pnpm add @hphudev/core
```

## Quick Start

### JWT Authentication

```typescript
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: 'user@example.com',
  role: 'admin',
});

// Verify access token
const result = jwtService.verifyAccessToken(tokens.accessToken);
if (result.valid) {
  console.log('User ID:', result.payload?.sub);
}
```

### Password Hashing

```typescript
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

```typescript
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

```typescript
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: 'user@example.com' });
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:

```typescript
// 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

```typescript
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:

```typescript
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