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.6.0

Published

Permissions guard and decorators for Regcheq NestJS services. Header-based, zero runtime deps.

Downloads

653

Readme

@regcheq/auth-library

Librería compartida de autorización para los microservicios NestJS de Regcheq. Expone un PermissionsGuard y decoradores que leen headers inyectados por el API Gateway. No valida JWT, no usa Redis, no hace llamadas HTTP. Cero dependencias runtime.

Arquitectura

El API Gateway es responsable de:

  1. Validar criptográficamente el JWT del usuario.
  2. Resolver los permisos asociados.
  3. Inyectar en cada request downstream los headers:
    • x-user-permissions (CSV de permisos)
    • x-user-id, x-user-email, x-user-name
    • x-company-id

Los microservicios solo verifican que los permisos inyectados cubran los requeridos por el endpoint. Para llamadas servicio-a-servicio se acepta un bypass mediante shared secret.

Instalación

npm install @regcheq/auth-library

No requiere registrar módulos ni configurar providers.

Uso

Opción A — Guard por controller (recomendado)

import { Controller, Get, UseGuards } from '@nestjs/common';
import {
  PermissionsGuard,
  RequirePermissions,
  CurrentUser,
  Company,
  CurrentUserPayload,
} from '@regcheq/auth-library';

@Controller('reports')
@UseGuards(PermissionsGuard)
export class ReportsController {
  @Get()
  @RequirePermissions('web-client:user:view')
  findAll(
    @CurrentUser() user: CurrentUserPayload,
    @Company() companyId: string | undefined,
  ) {
    return { user, companyId };
  }
}

Opción B — Guard global

// main.ts
import { PermissionsGuard } from '@regcheq/auth-library';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalGuards(new PermissionsGuard());
  await app.listen(3000);
}

Rutas sin @RequirePermissions() son públicas.

Llamadas servicio-a-servicio (S2S)

Cuando un microservicio llama a otro internamente, debe adjuntar el header x-internal-auth-token con el shared secret para que el PermissionsGuard del destino haga Fast-Track bypass. La librería expone un helper agnóstico de HTTP client para no forzar ninguna dependencia.

Helper

import { internalAuthHeaders } from '@regcheq/auth-library';

Retorna { 'x-internal-auth-token': process.env.INTERNAL_SERVICE_SECRET } si la env var está definida, o {} si no.

Uso con @nestjs/axios

this.http.get(url, { headers: { ...internalAuthHeaders() } });
this.http.post(url, body, { headers: { ...internalAuthHeaders() } });

Uso con fetch

await fetch(url, { headers: { ...internalAuthHeaders() } });

Opcional: interceptor global en un servicio

Si un servicio hace muchas llamadas internas y prefiere no repetir el helper, puede registrar un interceptor local en main.ts (código que vive en el servicio, no en la librería):

import { internalAuthHeaders } from '@regcheq/auth-library';

const httpService = app.get(HttpService);
httpService.axiosRef.interceptors.request.use((config) => {
  if (isInternalUrl(config.url)) {
    Object.assign(config.headers, internalAuthHeaders());
  }
  return config;
});

La decisión de qué URLs son internas se deja al servicio consumidor (tiene más contexto). La librería no mantiene una allowlist global para evitar el riesgo de filtrar el secret por mala configuración.

Por qué no un interceptor en la librería

  • Forzaría un peer-dep de @nestjs/axios/axios (lo que v2 eliminó deliberadamente).
  • Una allowlist de dominios centralizada es frágil: subdominios, redirects y proxies pueden filtrar el secret hacia destinos externos.
  • Explicitud en cada call site es auditable (grep internalAuthHeaders).

Variables de entorno

| Variable | Requerida | Descripción | |---|---|---| | INTERNAL_SERVICE_SECRET | Sí (para S2S) | Shared secret; si el header x-internal-auth-token coincide, se hace bypass de la validación de permisos. |

Si INTERNAL_SERVICE_SECRET no está definida, el Fast-Track S2S queda deshabilitado y todas las peticiones requieren x-user-permissions.

Headers esperados

| Header | Uso | |---|---| | x-user-permissions | CSV con permisos del usuario. Inyectado por el Gateway. | | x-internal-auth-token | Token S2S. Si coincide con INTERNAL_SERVICE_SECRET → bypass. | | x-user-id, x-user-email, x-user-name | Datos de usuario (leídos por @CurrentUser()). | | x-company-id | Tenant (leído por @Company()). |

Flujo del guard

  1. Si el endpoint no tiene @RequirePermissions()200.
  2. Si x-internal-auth-token == INTERNAL_SERVICE_SECRET200 (S2S).
  3. Si no hay x-user-permissions401.
  4. Si x-user-permissions no cubre todos los requeridos → 403.
  5. Caso contrario → 200.

Migración desde v1.x

v2 es un breaking change. Cambios requeridos en cada servicio consumidor:

  • [ ] npm install @regcheq/auth-library@^2.0.0
  • [ ] Eliminar AuthModule.register({...}) de AppModule (el módulo ya no existe).
  • [ ] Eliminar ioredis del servicio si solo se usaba para esta librería.
  • [ ] Eliminar @nestjs/axios del servicio si solo se usaba para esta librería.
  • [ ] Configurar INTERNAL_SERVICE_SECRET en el .env del servicio.
  • [ ] Confirmar con el equipo de Gateway que los headers x-user-permissions, x-user-id, x-user-email, x-user-name, x-company-id se están inyectando correctamente.
  • [ ] Elegir entre @UseGuards(PermissionsGuard) por controller o app.useGlobalGuards(new PermissionsGuard()) en main.ts.

Los decoradores @CurrentUser() y @Company() siguen funcionando pero ahora leen headers en lugar de req.context. La forma de CurrentUserPayload ahora es { id, email, name } (sin roles ni permissions, que dejaron de inyectarse en el request).

Tests

npm test

Licencia

UNLICENSED · Regcheq internal use only.