@aion2hub/vault-client
v1.0.0
Published
HashiCorp Vault client library for Aion2Hub services
Downloads
14
Maintainers
Readme
@aion2hub/vault-client
HashiCorp Vault client library for Aion2Hub microservices.
Features
- ✅ AppRole Authentication: Secure service-to-service authentication
- ✅ Automatic Token Renewal: Handles token expiration automatically
- ✅ Retry Logic: Exponential backoff for failed requests
- ✅ Fallback Support: Falls back to environment variables if Vault is unavailable
- ✅ TypeScript: Full TypeScript support with type definitions
- ✅ Connection Pooling: Efficient connection management
- ✅ Error Handling: Comprehensive error handling and logging
Installation
npm install @aion2hub/vault-clientUsage
Basic Usage
import { VaultClient } from '@aion2hub/vault-client';
const client = new VaultClient({
vaultAddr: 'http://vault:8200',
roleId: process.env.VAULT_ROLE_ID,
secretId: process.env.VAULT_SECRET_ID,
enableFallback: true,
});
await client.initialize();
// Get a secret
const dbSecret = await client.getSecret('aion2hub/data/shared/database');
console.log(dbSecret.password);
// Get a specific field
const jwtSecret = await client.getSecretField('aion2hub/data/shared/jwt', 'secret');
// Get database URL
const dbUrl = await client.getDatabaseUrl('aion2hub_users');Using Environment Variables
import { createVaultClientFromEnv } from '@aion2hub/vault-client';
const client = createVaultClientFromEnv();
await client.initialize();
const secrets = await client.getSecret('aion2hub/data/services/user-service');Development Mode (with root token)
const client = new VaultClient({
vaultAddr: 'http://vault:8200',
token: 'dev-root-token',
});
await client.initialize();Configuration
VaultClientConfig
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| vaultAddr | string | required | Vault server address |
| roleId | string | optional | AppRole role_id |
| secretId | string | optional | AppRole secret_id |
| token | string | optional | Root token (dev only) |
| enableFallback | boolean | true | Enable fallback to env vars |
| maxRetries | number | 3 | Maximum retry attempts |
| retryDelay | number | 1000 | Initial retry delay (ms) |
Environment Variables
| Variable | Description |
|----------|-------------|
| VAULT_ADDR | Vault server address |
| VAULT_ROLE_ID | AppRole role_id |
| VAULT_SECRET_ID | AppRole secret_id |
| VAULT_TOKEN | Root token (dev only) |
| VAULT_ENABLE_FALLBACK | Enable fallback (true/false) |
API Reference
VaultClient
initialize(): Promise<void>
Initialize the client and authenticate with Vault.
getSecret(path: string): Promise<SecretData>
Get a secret from Vault.
const secret = await client.getSecret('aion2hub/data/shared/database');
// { host: 'postgres', port: '5432', user: 'aion2hub', password: '...' }getSecrets(paths: string[]): Promise<Record<string, SecretData>>
Get multiple secrets at once.
const secrets = await client.getSecrets([
'aion2hub/data/shared/database',
'aion2hub/data/shared/jwt',
]);getSecretField(path: string, field: string, defaultValue?: string): Promise<string>
Get a specific field from a secret.
const password = await client.getSecretField(
'aion2hub/data/shared/database',
'password',
'default-password'
);getDatabaseUrl(dbName: string): Promise<string>
Build a PostgreSQL connection URL from Vault secrets.
const dbUrl = await client.getDatabaseUrl('aion2hub_users');
// postgresql://aion2hub:password123@postgres:5432/aion2hub_usershealthCheck(): Promise<boolean>
Check if Vault is healthy and unsealed.
const isHealthy = await client.healthCheck();isAuthenticated(): boolean
Check if the client is authenticated.
if (client.isAuthenticated()) {
console.log('Client is authenticated');
}Error Handling
The client includes comprehensive error handling:
try {
const secret = await client.getSecret('aion2hub/data/shared/database');
} catch (error) {
console.error('Failed to retrieve secret:', error);
// Fallback to environment variables if enabled
}Retry Logic
Failed requests are automatically retried with exponential backoff:
- Attempt 1: Immediate
- Attempt 2: 1 second delay
- Attempt 3: 2 second delay
- Attempt 4: 4 second delay (if maxRetries > 3)
Fallback Mode
When enableFallback is true (default), the client will return empty objects instead of throwing errors if Vault is unavailable. This allows services to fall back to environment variables.
const client = new VaultClient({
vaultAddr: 'http://vault:8200',
roleId: process.env.VAULT_ROLE_ID,
secretId: process.env.VAULT_SECRET_ID,
enableFallback: true, // Enable fallback
});
// If Vault is down, this returns {} instead of throwing
const secret = await client.getSecret('aion2hub/data/shared/database');
// Use fallback values
const dbPassword = secret.password || process.env.DB_PASSWORD;Development
# Install dependencies
npm install
# Build
npm run build
# Watch mode
npm run watch
# Clean
npm run cleanLicense
MIT
