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

@regcheq/auth-library

v1.4.0

Published

Auth module, guards, and middleware for Regcheq services

Downloads

32

Readme

Regcheq Auth Library

Libreria interna para estandarizar autenticacion y autorizacion en servicios NestJS. Provee middleware para validar JWT, carga de permisos via Redis y decoradores para acceder al contexto de usuario.

Que resuelve

  • Verificacion de JWT con public key (local o desde servicio de auth).
  • Contexto unificado en req.context y req.user.
  • Guard de permisos con decorador simple.
  • Cache local + Redis para permisos por rol, con invalidacion por canal.

Instalacion

npm i @regcheq/auth-library

Uso rapido en NestJS

  1. Registrar el modulo global
import { Module } from '@nestjs/common';
import { AuthModule } from '@regcheq/auth-library';

@Module({
  imports: [
    AuthModule.register({
      authServiceUrl: 'https://auth.mi-dominio.com',
      // o publicKey: '-----BEGIN PUBLIC KEY-----...'
      redisOptions: { host: '127.0.0.1', port: 6379 },
      rolesUpdateChannel: 'events:roles:updated'
    }),
  ],
})
export class AppModule {}
  1. Proteger rutas con permisos
import { Controller, Get, UseGuards } from '@nestjs/common';
import { PermissionsGuard, RequirePermissions } from '@regcheq/auth-library';

@Controller('reportes')
@UseGuards(PermissionsGuard)
export class ReportesController {
  @Get()
  @RequirePermissions('reports.read')
  findAll() {
    return [];
  }
}
  1. Acceder al usuario actual
import { Controller, Get } from '@nestjs/common';
import { CurrentUser, Company } from '@regcheq/auth-library';

@Controller('me')
export class MeController {
  @Get()
  getMe(@CurrentUser() user, @Company() companyId: string) {
    return { user, companyId };
  }
}

Como funciona

  • El middleware toma el token Authorization: Bearer <token>.
  • Verifica el JWT con la public key.
  • Enriquece el request con context y user.
  • El guard revisa permisos declarados con @RequirePermissions.
  • Si source en el token es internal, el guard permite acceso sin validar permisos.

AuthModuleOptions

Opciones disponibles al registrar el modulo:

  • authServiceUrl: URL del servicio de auth para obtener la public key (GET /public-key).
  • publicKey: PEM directo para verificar JWT (si existe, ignora authServiceUrl).
  • redisOptions: opciones de conexion para ioredis.
  • rolesUpdateChannel: canal para invalidar cache local (default events:roles:updated).
  • onUnauthorized: callback para lanzar una excepcion 401 desde tu app.
  • onForbidden: callback para lanzar una excepcion 403 desde tu app.

Ejemplo de callbacks:

import { UnauthorizedException, ForbiddenException } from '@nestjs/common';

AuthModule.register({
  authServiceUrl: 'https://auth.mi-dominio.com',
  redisOptions: { host: '127.0.0.1', port: 6379 },
  onUnauthorized: (message) => { throw new UnauthorizedException(message); },
  onForbidden: (message) => { throw new ForbiddenException(message); },
});

Contexto agregado al request

La libreria agrega informacion en el request para que puedas usarla en controladores y servicios:

interface AuthContext {
  companyId: string;
  user: { id: string; name: string; email: string };
  roles: string[];
  permissions: string[];
  source: 'internal' | 'external';
}

Disponibles en req.context y req.user (con permissions).

Permisos y cache

  • Los permisos por rol se leen desde Redis con la llave auth:role:<role>:permissions.
  • La libreria mantiene un cache local por rol y lo invalida con Pub/Sub.
  • El canal de invalidacion se configura con rolesUpdateChannel.

Versionado (SemVer)

Este paquete sigue SemVer:

  • PATCH: fixes internos sin cambios de API.
  • MINOR: nuevas funcionalidades compatibles.
  • MAJOR: cambios que rompen compatibilidad.

Commits (Conventional Commits)

El release automatico usa Conventional Commits. Ejemplos:

  • feat: agrega nuevo decorador -> MINOR
  • fix: corrige validacion de token -> PATCH
  • feat!: cambia estructura de contexto -> MAJOR

O con breaking change explicito:

feat: agrega autenticacion

BREAKING CHANGE: cambia nombre de export en index

Tipos comunes: feat, fix, chore, docs, refactor, test.

Requisitos de desarrollo

El repo usa Node 22 (ver .nvmrc).

nvm use
npm ci

Exportaciones

export * from './auth.module';
export * from './guards/permissions.guard';
export * from './decorators/auth.decorators';
export * from './interfaces/auth-context.interface';
export * from './interfaces/auth-options.interface';