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

@jmlq/auth

v0.0.1-alpha.1

Published

JWT authentication package with clean architecture

Readme

@ml-dev-core/jwt.auth

🔐 Paquete de autenticación JWT con Arquitectura Limpia para aplicaciones TypeScript.

🚀 Instalación Rápida

npm install @ml-dev-core/jwt.auth bcryptjs
npm install --save-dev @types/bcryptjs

📖 Documentación

✨ Características Principales

  • Clean Architecture: Separación clara de responsabilidades
  • Framework Agnostic: Compatible con Express, NestJS, Fastify, etc.
  • Database Independent: Repositorios como interfaces
  • TypeScript Native: Tipado fuerte y autocompletado
  • JWT Completo: Access + Refresh tokens con rotación
  • Multi-Algorithm: HS256, RS256, ES256 y más
  • Password Security: Bcrypt con políticas configurables
  • Testing Ready: Repositorios in-memory incluidos
  • Production Ready: Manejo de errores y validaciones

🏃‍♂️ Inicio Rápido

1. Configuración Básica

import {
  AuthServiceFactory,
  IAuthConfig,
  InMemoryUserRepository,
  InMemoryCredentialRepository,
} from "@ml-dev-core/jwt.auth";

const config: IAuthConfig = {
  jwt: {
    accessTokenSecret: process.env.JWT_ACCESS_SECRET!,
    refreshTokenSecret: process.env.JWT_REFRESH_SECRET!,
    accessTokenExpirationMs: 15 * 60 * 1000, // 15 minutos
    refreshTokenExpirationMs: 7 * 24 * 60 * 60 * 1000, // 7 días
    accessTokenExpiration: "15m",
    refreshTokenExpiration: "7d",
  },
  bcrypt: { saltRounds: 12 },
  algorithm: "HS256",
  info: {
    issuer: "your-app",
    audience: "your-client",
  },
};

const authServices = AuthServiceFactory.create(
  config,
  new InMemoryUserRepository(),
  new InMemoryCredentialRepository()
);

2. Casos de Uso

// Registro
const registerResult = await authServices.registerUserUseCase.execute({
  email: "[email protected]",
  password: "SecurePassword123!",
  confirmPassword: "SecurePassword123!",
});

// Login
const loginResult = await authServices.loginWithPasswordUseCase.execute({
  email: "[email protected]",
  password: "SecurePassword123!",
});

console.log("Access Token:", loginResult.accessToken);
console.log("Refresh Token:", loginResult.refreshToken);

// Refresh
const refreshResult = await authServices.refreshTokenUseCase.execute({
  refreshToken: loginResult.refreshToken,
});

// Logout
await authServices.logoutUseCase.execute({
  refreshToken: refreshResult.refreshToken,
});

3. Middleware (Express)

import { JwtTokenVerifier } from "@ml-dev-core/jwt.auth";

export const authMiddleware = async (req, res, next) => {
  try {
    const token = req.headers.authorization?.substring(7);
    const verifier = new JwtTokenVerifier();

    const isValid = await verifier.verify(
      token,
      config.jwt.accessTokenSecret,
      config.algorithm
    );

    if (!isValid) {
      return res.status(401).json({ error: "Token inválido" });
    }

    const payload = await verifier.parsePayload(token);
    req.user = payload;
    next();
  } catch (error) {
    res.status(401).json({ error: "Error de autenticación" });
  }
};

🏗️ Arquitectura

┌─────────────────────────────────────────┐
│           APPLICATION LAYER             │
│  (Use Cases, DTOs, Factories)           │
├─────────────────────────────────────────┤
│            DOMAIN LAYER                 │
│  (Entities, Value Objects, Ports)       │
├─────────────────────────────────────────┤
│         INFRASTRUCTURE LAYER            │
│  (JWT, Repositories, Security)          │
├─────────────────────────────────────────┤
│            SHARED LAYER                 │
│  (Types, Constants, Utils)              │
└─────────────────────────────────────────┘

Capas y Responsabilidades

  • Domain: Lógica de negocio pura (entities, value objects, interfaces)
  • Application: Orquestación de casos de uso y DTOs
  • Infrastructure: Implementaciones concretas (JWT, bcrypt, repositorios)
  • Shared: Utilidades y tipos compartidos

📦 Exports Principales

// Factory principal
import { AuthServiceFactory } from "@ml-dev-core/jwt.auth";

// Casos de uso
import {
  LoginWithPasswordUseCase,
  RegisterUserUseCase,
  RefreshTokenUseCase,
  LogoutUseCase,
} from "@ml-dev-core/jwt.auth";

// DTOs
import {
  LoginRequest,
  LoginResponse,
  RegisterUserRequest,
  RefreshTokenRequest,
} from "@ml-dev-core/jwt.auth";

// Entidades del dominio
import { User, Credential } from "@ml-dev-core/jwt.auth";

// Value Objects
import { Email, HashedPassword, Role, Id } from "@ml-dev-core/jwt.auth";

// Componentes JWT
import { JwtTokenGenerator, JwtTokenVerifier } from "@ml-dev-core/jwt.auth";

// Implementaciones de seguridad
import { BcryptPasswordHasher } from "@ml-dev-core/jwt.auth";

// Repositorios in-memory (testing)
import {
  InMemoryUserRepository,
  InMemoryCredentialRepository,
} from "@ml-dev-core/jwt.auth";

// Interfaces
import {
  IUserRepository,
  ICredentialRepository,
  IAuthConfig,
} from "@ml-dev-core/jwt.auth";

🔧 Configuración de Variables de Entorno

# JWT Secrets
JWT_ACCESS_SECRET=your_super_secret_access_key_here
JWT_REFRESH_SECRET=your_super_secret_refresh_key_here

# JWT Timing
JWT_ACCESS_EXPIRATION=15m
JWT_REFRESH_EXPIRATION=7d

# JWT Info
JWT_ISSUER=your-app-name
JWT_AUDIENCE=your-client-app
JWT_ALGORITHM=HS256

# Security
BCRYPT_SALT_ROUNDS=12

🧪 Testing

import {
  AuthServiceFactory,
  InMemoryUserRepository,
  InMemoryCredentialRepository,
} from "@ml-dev-core/jwt.auth";

describe("Auth Tests", () => {
  let authServices;

  beforeEach(() => {
    authServices = AuthServiceFactory.create(
      testConfig,
      new InMemoryUserRepository(),
      new InMemoryCredentialRepository()
    );
  });

  it("should register and login user", async () => {
    // Test implementation
  });
});

📱 Frameworks Soportados

Express.js

app.use("/auth", authRoutes);
app.use("/api", authMiddleware);

NestJS

@UseGuards(JwtAuthGuard)
@Controller("protected")
export class ProtectedController {}

Fastify

fastify.addHook("onRequest", authMiddleware);

🔐 Algoritmos JWT Soportados

  • HMAC: HS256, HS384, HS512 (clave simétrica)
  • RSA: RS256, RS384, RS512 (clave asimétrica)
  • ECDSA: ES256, ES384, ES512 (curva elíptica)

📄 Scripts Disponibles

# Construcción
npm run build

# Testing
npm test
npm run test:coverage
npm run test:watch

# Ejemplos
npm run example:help          # Ver todos los comandos
npm run example:all           # Ejecutar todos los ejemplos
npm run example:use-cases     # Ejemplos de casos de uso
npm run example:jwt           # Ejemplos de JWT
npm run example:factories     # Ejemplos de factories

📋 Roadmap

  • [ ] Integración con Prisma ORM
  • [ ] Soporte para OAuth2
  • [ ] Rate limiting integrado
  • [ ] Audit logging
  • [ ] Multi-tenancy support

📜 Licencia

MIT © MLahuasi


¿Necesitas ayuda? Consulta la documentación completa o revisa los ejemplos.