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

@hemia/vault-client

v0.0.1

Published

vault-client

Readme

@hemia/vault-client

📌 Descripción

@hemia/vault-client es un cliente TypeScript para HashiCorp Vault que facilita la autenticación y recuperación de secretos usando el método AppRole. Diseñado para aplicaciones que necesitan acceso seguro a secretos almacenados en Vault.

✨ Características principales

  • 🔐 Autenticación AppRole: Integración nativa con el método de autenticación AppRole de Vault
  • 🚀 Cache de tokens: Sistema inteligente de cache para tokens con TTL automático
  • 📦 TypeScript: Soporte completo para tipos con genéricos
  • 🔧 Configurable: Soporte para múltiples secret engines (kv, secret, etc.)
  • 🎯 Simple: API intuitiva y fácil de usar
  • 🧪 Testeado: Suite completa de tests incluida

📂 Estructura del Proyecto

@hemia/vault-client/
├── src/
│   ├── VaultClient.ts           # Cliente principal de Vault
│   ├── index.ts                 # Punto de entrada del paquete
│   ├── types/
│   │   └── VaultConfig.ts       # Definiciones de tipos
│   └── __tests__/
│       └── VaultClient.test.ts  # Tests del cliente
├── dist/                        # Archivos compilados
├── package.json
├── tsconfig.json
├── rollup.config.mjs
├── jest.config.js
└── README.md

🛠 Instalación

npm install @hemia/vault-client

Peer Dependencies

npm install axios

🚀 Uso rápido

Configuración básica

import { VaultClient, VaultConfig } from '@hemia/vault-client';

const config: VaultConfig = {
  vaultUrl: 'https://vault.company.com',
  roleId: 'your-role-id',
  secretId: 'your-secret-id',
  environment: 'production'
};

const vaultClient = new VaultClient(config);

Obtener secretos

// Obtener secreto sin tipado
const secret = await vaultClient.getSecret('myapp', 'database');
console.log(secret); // { username: "user", password: "pass", host: "db.com" }

// Obtener secreto con tipado
interface DatabaseConfig {
  username: string;
  password: string;
  host: string;
  port: number;
}

const dbConfig = await vaultClient.getSecret<DatabaseConfig>('myapp', 'database');
console.log(dbConfig.username); // IntelliSense disponible!

⚙️ Configuración

VaultConfig

interface VaultConfig {
  vaultUrl: string;        // URL base del servidor Vault
  roleId: string;          // Role ID para autenticación AppRole
  secretId: string;        // Secret ID para autenticación AppRole
  environment: string;     // Entorno (dev, staging, prod, etc.)
  secretEngine?: string;   // Motor de secretos (por defecto: 'kv')
}

Ejemplos de configuración

Configuración para desarrollo

const devConfig: VaultConfig = {
  vaultUrl: 'http://localhost:8200',
  roleId: process.env.VAULT_ROLE_ID!,
  secretId: process.env.VAULT_SECRET_ID!,
  environment: 'dev'
};

Configuración para producción con secret engine personalizado

const prodConfig: VaultConfig = {
  vaultUrl: 'https://vault.company.com',
  roleId: process.env.VAULT_ROLE_ID!,
  secretId: process.env.VAULT_SECRET_ID!,
  environment: 'prod',
  secretEngine: 'secret' // Usar motor 'secret' en lugar de 'kv'
};

🔧 API Reference

VaultClient

constructor(config: VaultConfig)

Crea una nueva instancia del cliente Vault.

getSecret<T = any>(system: string, secretName: string): Promise<T>

Obtiene un secreto de Vault.

Parámetros:

  • system: Nombre del sistema/aplicación
  • secretName: Nombre del secreto específico

Retorna: Promise con los datos del secreto

Ejemplo de rutas generadas:

  • KV Engine: /v1/kv/data/{environment}/{system}/{secretName}
  • Secret Engine: /v1/secret/data/{environment}/{system}/{secretName}

� Ejemplos avanzados

Manejo de errores

try {
  const secret = await vaultClient.getSecret('myapp', 'api-keys');
  console.log('Secret retrieved:', secret);
} catch (error) {
  if (error.response?.status === 404) {
    console.error('Secret not found');
  } else if (error.response?.status === 403) {
    console.error('Permission denied');
  } else {
    console.error('Vault error:', error.message);
  }
}

Uso con diferentes tipos

// Configuración de base de datos
interface DatabaseConfig {
  host: string;
  port: number;
  username: string;
  password: string;
  database: string;
}

// Claves API
interface ApiKeys {
  publicKey: string;
  secretKey: string;
  webhookSecret: string;
}

// Obtener secretos tipados
const dbConfig = await vaultClient.getSecret<DatabaseConfig>('myapp', 'database');
const apiKeys = await vaultClient.getSecret<ApiKeys>('myapp', 'stripe-keys');

Variables de entorno

# .env
VAULT_URL=https://vault.company.com
VAULT_ROLE_ID=12345678-1234-1234-1234-123456789012
VAULT_SECRET_ID=87654321-4321-4321-4321-210987654321
VAULT_ENVIRONMENT=production
const config: VaultConfig = {
  vaultUrl: process.env.VAULT_URL!,
  roleId: process.env.VAULT_ROLE_ID!,
  secretId: process.env.VAULT_SECRET_ID!,
  environment: process.env.VAULT_ENVIRONMENT!
};

🧪 Testing

Ejecutar tests

npm test                 # Ejecutar todos los tests
npm run test:coverage    # Tests con cobertura
npm run test:watch       # Tests en modo watch

Tests de integración

Los tests incluyen casos para:

  • ✅ Autenticación con AppRole
  • ✅ Recuperación de secretos
  • ✅ Cache de tokens
  • ✅ Manejo de errores
  • ✅ Diferentes secret engines

🔧 Desarrollo

Scripts disponibles

npm run build           # Compilar el proyecto
npm run clean           # Limpiar archivos generados
npm test               # Ejecutar tests
npm run test:coverage  # Tests con cobertura

Estructura de archivos generados

dist/
├── hemia-vault-client.js       # Build CommonJS
├── hemia-vault-client.esm.js   # Build ES Modules
└── types/                      # Definiciones TypeScript
    ├── index.d.ts
    ├── VaultClient.d.ts
    └── types/
        └── VaultConfig.d.ts

🚀 Publicación

Para publicar una nueva versión:

npm run build    # Compilar
# Subir cambios al repositorio

🤝 Contribución

  1. Fork el proyecto
  2. Crea una rama para tu feature (git checkout -b feature/nueva-funcionalidad)
  3. Commit tus cambios (git commit -am 'Agregar nueva funcionalidad')
  4. Push a la rama (git push origin feature/nueva-funcionalidad)
  5. Crea un Pull Request

📄 Licencia

Este proyecto está bajo la licencia ISC.

🔗 Enlaces relacionados