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

a205-portal-health-lib-auth

v1.0.3

Published

Librería NestJS para **validar access tokens JWT** emitidos por **Azure AD B2C**. Obtiene las claves públicas (JWKS) del tenant, verifica la firma con **RS256** y expone el payload tipado mediante un caso de uso inyectable.

Readme

a205-portal-health-lib-auth

Librería NestJS para validar access tokens JWT emitidos por Azure AD B2C. Obtiene las claves públicas (JWKS) del tenant, verifica la firma con RS256 y expone el payload tipado mediante un caso de uso inyectable.

Uso pensado para el ecosistema Portal de Clientes Colmena (backend). Paquete con license: UNLICENSED; distribución según políticas internas de la organización.


Características

  • Verificación de JWT con jose: jwtVerify + createRemoteJWKSet.
  • Issuer y audience tomados del propio token (iss, aud); la URL de JWKS se construye con tenant y policy que envía el consumidor.
  • Módulo Nest listo para importar: ConfigModule global + registro del puerto TokenVerifierPort con implementación real (TokenVerifierAdapter).
  • DTOs de entrada/salida (TokenPayloadRequest, TokenPayloadResponse) para contratos claros entre capas.

Requisitos

  • Node.js LTS (recomendado: alineado con @types/node del proyecto).
  • NestJS 11.x y dependencias peer implícitas (@nestjs/common, @nestjs/core, etc.), tal como en package.json.

Instalación

Desde el registro npm corporativo o el origen que use Colmena (ajusta el scope y la URL según corresponda):

npm install a205-portal-health-lib-auth

Asegúrate de que tu aplicación ya importa reflect-metadata (estándar en NestJS).


Uso rápido

1. Importar el módulo

En el módulo raíz (o en un módulo de autenticación) importa AuthModule:

import { Module } from '@nestjs/common';
import { AuthModule } from 'a205-portal-health-lib-auth';

@Module({
  imports: [AuthModule],
})
export class AppModule {}

AuthModule registra ConfigModule.forRoot({ isGlobal: true }) y exporta el caso de uso y la infraestructura necesaria.

2. Inyectar el caso de uso

import { Injectable } from '@nestjs/common';
import { TokenVerifierUseCase } from 'a205-portal-health-lib-auth';

@Injectable()
export class ExampleService {
  constructor(private readonly tokenVerifier: TokenVerifierUseCase) {}

  async validateToken(accessToken: string, tenant: string, policy: string) {
    return this.tokenVerifier.execute({
      accessToken,
      tenant,
      policy,
    });
  }
}

3. Contrato de entrada

| Campo | Descripción | |----------------|-------------| | accessToken | JWT de acceso (Bearer) emitido por B2C. | | tenant | Nombre del tenant B2C (segmento del host *.b2clogin.com). | | policy | Nombre de la user flow / custom policy usada en la emisión del token. |

El adaptador construye la URL de claves públicas así:

https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/discovery/v2.0/keys

y valida el token con issuer y audience extraídos del JWT.

4. Respuesta y errores

  • Éxito: objeto compatible con TokenPayloadResponse (claims estándar sub, iss, aud, exp, iat y extensiones opcionales definidas en el DTO).
  • Error: UnauthorizedException de NestJS si faltan datos obligatorios, la verificación falla o el payload no cumple el mapeo mínimo esperado.

Tipos TypeScript (barrel del paquete):

import type { TokenPayloadRequest, TokenPayloadResponse } from 'a205-portal-health-lib-auth';

Desarrollo en este repositorio

npm ci
npm run build
npm run test
npm run lint

El artefacto publicable apunta a dist/ (main / types en package.json).


Arquitectura (resumen)

| Capa | Rol | |-----------------|-----| | AuthModule | Composición: configuración global + módulo de aplicación. | | TokenVerifierUseCase | Orquestación y validación de requisitos de negocio (token, tenant, policy). | | TokenVerifierPort | Puerto abstracto para intercambiar implementación (real vs mock en tests). | | TokenVerifierAdapter | Integración con Azure AD B2C + jose. |

Para pruebas locales o entornos sin B2C, puedes sustituir el provider 'TokenVerifierPort' por TokenVerifierMockAdapter en InfrastructureModule (solo en ramas de desarrollo / tests; no dejar mocks en producción).


Licencia

UNLICENSED — uso y redistribución sujetos a las políticas internas de Colmena / Sonda Digital Factory.