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

hpower-backend-core

v1.2.15

Published

Librería con modulos basados en NestJS para la integración con backends de la organización que lo requieran

Readme

HP Core Library

Librería NestJS que proporciona servicios de AWS (S3, Secrets Manager) y autenticación JWT con JWKS.

📦 Instalación

Requisitos Previos

  • Node.js v16+ y npm v8+

Instalación

npm install hpower-backend-core

Instalar Dependencias Peer

npm install @nestjs/common @nestjs/core reflect-metadata express cookie-parser
npm install --save-dev @types/express @types/cookie-parser

🚀 Uso en tu Proyecto

1. Configurar cookie-parser (Requerido)

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cookieParser from 'cookie-parser';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // IMPORTANTE: Configurar cookie-parser para que AuthGuard pueda leer cookies
  app.use(cookieParser());

  await app.listen(3000);
}
bootstrap();

2. Importar el Módulo

app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { HPCoreModule } from 'hpower-backend-core';

@Module({
  imports: [
    ConfigModule.forRoot(),

    // Opción A: Configuración directa
    HPCoreModule.register({
      aws: {
        region: 'us-east-1',
        s3: {
          bucket: 'my-bucket',
        },
        secretsManager: {},
      },
      auth: {
        jwksUrl:
          'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXX/.well-known/jwks.json',
        issuer: 'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXX',
        audience: 'my-client-id',
      },
    }),

    // Opción B: Configuración asíncrona con ConfigService
    HPCoreModule.registerAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        aws: {
          region: config.get('AWS_REGION', 'us-east-1'),
          s3: {
            bucket: config.get('AWS_S3_BUCKET'),
          },
          secretsManager: {},
        },
        auth: {
          jwksUrl: config.get('JWKS_URL'),
          issuer: config.get('JWT_ISSUER'),
          audience: config.get('JWT_AUDIENCE'),
        },
      }),
    }),
  ],
})
export class AppModule {}

2. Usar los Servicios

S3Service

import { Injectable } from '@nestjs/common';
import { S3Service } from 'hpower-backend-core';

@Injectable()
export class FileService {
  constructor(private readonly s3: S3Service) {}

  async uploadFile(file: Express.Multer.File) {
    const key = `uploads/${Date.now()}-${file.originalname}`;
    const url = await this.s3.uploadFile(key, file.buffer, file.mimetype);
    return { url, key };
  }

  async downloadFile(key: string) {
    return this.s3.getFile(key);
  }

  async deleteFile(key: string) {
    return this.s3.deleteFile(key);
  }

  getPublicUrl(key: string) {
    return this.s3.getFileUrl(key);
  }
}

SecretsService

import { Injectable } from '@nestjs/common';
import { SecretsService } from 'hpower-backend-core';

@Injectable()
export class ConfigurationService {
  constructor(private readonly secrets: SecretsService) {}

  async getDatabaseCredentials() {
    const username = await this.secrets.getSecretValue(
      'db-credentials',
      'username',
    );
    const password = await this.secrets.getSecretValue(
      'db-credentials',
      'password',
    );
    return { username, password };
  }

  async getApiKeys() {
    return this.secrets.getSecretJson<{ apiKey: string }>('api-keys');
  }
}

AuthService

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from 'hpower-backend-core';

@Injectable()
export class AuthenticationService {
  constructor(private readonly auth: AuthService) {}

  async validateRequest(authHeader: string) {
    const token = this.auth.extractTokenFromHeader(authHeader);

    if (!token) {
      throw new UnauthorizedException('No token provided');
    }

    try {
      const payload = await this.auth.verifyToken(token);
      return payload;
    } catch (error) {
      throw new UnauthorizedException('Invalid token');
    }
  }
}

Guard de Autenticación

La librería incluye un AuthGuard que puedes usar directamente. Este guard soporta extracción de JWT desde:

  1. Header Authorization (Bearer token) - prioridad alta
  2. Cookie (access_token) - fallback si no hay header

Uso del AuthGuard incluido:

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from 'hpower-backend-core';

@Controller('protected')
export class ProtectedController {
  @Get()
  @UseGuards(AuthGuard)
  getProtectedResource() {
    return { message: 'This is a protected resource' };
  }
}

Ejemplo de Guard personalizado (si necesitas lógica adicional):

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { AuthService } from 'hpower-backend-core';

@Injectable()
export class CustomAuthGuard implements CanActivate {
  constructor(private readonly authService: AuthService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();

    // El token puede venir del header o de las cookies
    let token: string | undefined;

    // 1. Intentar extraer del header
    const authHeader = request.headers.authorization;
    if (authHeader) {
      token = this.authService.extractTokenFromHeader(authHeader);
    }

    // 2. Si no hay token en el header, intentar de las cookies
    if (!token && request.cookies) {
      token = request.cookies.access_token;
    }

    if (!token) {
      return false;
    }

    try {
      const payload = await this.authService.verifyToken(token);
      request.user = payload; // Adjuntar el usuario al request
      return true;
    } catch {
      return false;
    }
  }
}

📝 Variables de Entorno (.env)

# AWS
AWS_REGION=us-east-1
AWS_S3_BUCKET=my-bucket-name

# JWT/Auth
JWKS_URL=https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXX/.well-known/jwks.json
JWT_ISSUER=https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXX
JWT_AUDIENCE=your-client-id

🔄 Actualizar la Librería

Cuando hagas cambios en backend-core:

# 1. En el proyecto backend-core
npm run build

# 2. Si usas npm link, los cambios se reflejan automáticamente
# 3. Si usas path local, reinstala:
cd /ruta/a/tu/proyecto
npm install

🛠️ Desarrollo

# Compilar en modo watch (recompila automáticamente)
npm run build:watch

📚 Módulos Disponibles

  • HPCoreModule - Módulo principal que orquesta AWS y Auth
  • AWSModule - Módulo interno de AWS (S3 + Secrets Manager)
  • AuthModule - Módulo interno de autenticación JWT

🔧 Servicios Exportados

  • S3Service - Operaciones con AWS S3
  • SecretsService - Operaciones con AWS Secrets Manager
  • AuthService - Verificación de tokens JWT

📖 Interfaces Exportadas

  • HPCoreModuleOptions - Configuración del módulo principal
  • AWSModuleOptions - Configuración de AWS
  • AuthModuleOptions - Configuración de autenticación