### Quick Start Paths Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/MANIFEST.md Provides a table mapping common goals to the relevant starting documentation files. ```text | Goal | Start With | |------|-----------| | Get started quickly | `00-START-HERE.md` | | Learn the basics | `README.md` | | Find a specific task | `INDEX.md` | | Set up authentication | `configuration.md` + `api-reference/AuthenticationMethods.md` | | Look up a method | `api-reference/VaultClient.md` | | Understand KV handling | `KV-engines.md` | | Handle errors | `errors.md` | | Check types | `types.md` | ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/namecheap/node-vault-client/blob/master/CONTRIBUTING.md Install dependencies, start a local Vault server, and run linting and tests. Ensure linting and tests pass before pushing changes. ```shell npm ci # install dependencies from the lockfile npm install config # peer dependency used by the node-config integration and coverage docker compose up -d # start a local dev Vault on 127.0.0.1:8200 npm run lint # ESLint (must be clean) npm run test:unit # fast unit tests (no Vault required) npm test # full suite, including integration/e2e (needs the Vault container) npm run coverage # unit tests with c8 coverage report ``` -------------------------------- ### Kubernetes Auth Example with Custom Token Path Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Example demonstrating Kubernetes authentication with a custom path for the service-account JWT token. ```javascript const vault = VaultClient.boot('main', { api: { url: 'https://vault.kubernetes.default.svc:8200/' }, auth: { type: 'kubernetes', config: { role: 'my_app_role', tokenPath: '/custom/jwt/path', }, }, }); ``` -------------------------------- ### Kubernetes Auth Example Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Example of booting the Vault client with Kubernetes authentication and reading a secret. Assumes default token path and role configuration. ```javascript const vault = VaultClient.boot('main', { api: { url: 'https://vault.kubernetes.default.svc:8200/' }, auth: { type: 'kubernetes', config: { role: 'my_app_role', }, }, }); const secret = await vault.read('secret/my-app/db'); ``` -------------------------------- ### Complete Vault Client Setup and Usage Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Demonstrates the complete setup for initializing the Vault client and using `fillNodeConfig` to populate application configuration with secrets. Ensure VAULT_ADDR and VAULT_TOKEN environment variables are set. ```javascript // app.js const config = require('config'); const VaultClient = require('node-vault-client'); // Initialize Vault client const vault = VaultClient.boot('main', { api: { url: process.env.VAULT_ADDR }, auth: { type: 'token', config: { token: process.env.VAULT_TOKEN }, }, }); // Populate config from Vault async function start() { await vault.fillNodeConfig(); // Now config has Vault secrets merged in console.log(`Connecting to ${config.database.host}:${config.database.port}`); console.log(`User: ${config.database.username}`); // ... start application } start().catch(err => { console.error('Failed to populate config:', err); process.exit(1); }); ``` -------------------------------- ### Example Implementation of __detectMount Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/MountResolver.md Provides an example implementation of the `__detectMount` method within a VaultClient, showing how to make a request to the Vault API for mount detection. ```javascript __detectMount(path) { return this.__auth.getAuthToken() .then((token) => { const detectPath = `sys/internal/ui/mounts/${path}`; return this.__api.makeRequest('GET', detectPath, null, this.getHeaders(token)); }); } ``` -------------------------------- ### VaultApiClient makeRequest Examples Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultApiClient.md Demonstrates how to use the makeRequest method for different HTTP operations like GET, POST, and PATCH. Shows initialization of the client and usage with various parameters and headers. ```javascript const client = new VaultApiClient( { url: 'https://vault.example.com:8200/', apiVersion: 'v1' }, console ); // Simple GET const result = await client.makeRequest('GET', 'secret/data/my-app'); // Request: GET https://vault.example.com:8200/v1/secret/data/my-app // POST with body const authResult = await client.makeRequest( 'POST', 'auth/approle/login', { role_id: '...', secret_id: '...' }, { 'X-Vault-Token': 'token-123' } ); // PATCH with merge-patch content-type const updateResult = await client.makeRequest( 'PATCH', 'secret/data/my-app', { new_key: 'value' }, { 'Content-Type': 'application/merge-patch+json', 'X-Vault-Token': '...' } ); ``` -------------------------------- ### MountResolver Example Usage Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/MountResolver.md Demonstrates how to instantiate and use the MountResolver to resolve the KV engine version for a specific path. This example shows setting up overrides and enabling detection. ```javascript const resolver = new MountResolver( detectFn, // async function { secret: 2 }, // override: secret is always v2 logger, { disabled: false } // detection enabled ); const result = await resolver.resolve('secret/my-app/db'); // { mount: 'secret', version: 2, type: 'kv' } ``` -------------------------------- ### AppRole Authentication Example Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Example of initializing the Vault client with AppRole authentication using environment variables for credentials and then reading a secret. ```javascript const vault = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'appRole', config: { role_id: process.env.VAULT_ROLE_ID, secret_id: process.env.VAULT_SECRET_ID, }, }, }); const secret = await vault.read('secret/my-app/db'); ``` -------------------------------- ### Default Configuration File Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Example of a default JSON configuration file. This file sets up basic application settings. ```javascript // config/default.json { "database": { "host": "localhost", "port": 5432 } } ``` -------------------------------- ### Configure Vault Client with Token Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/README.md Example of bootstrapping the Vault client for a development environment using token-based authentication. ```javascript VaultClient.boot('dev', { api: { url: 'https://vault.dev.example.com:8200/' }, auth: { type: 'token', config: { token: process.env.VAULT_TOKEN }, }, }); ``` -------------------------------- ### Install node-vault-client Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/00-START-HERE.md Install the node-vault-client package using npm. This command should be run in your project's root directory. ```bash npm install --save node-vault-client ``` -------------------------------- ### Custom Logger Example with Pino Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/configuration.md Example of integrating a custom logger, specifically Pino, with the Vault client. Ensure the logger is configured with the desired level. ```javascript const pino = require('pino'); const logger = pino({ level: 'debug' }); const vault = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'token', config: { token: '...' } }, logger: logger, }); ``` -------------------------------- ### Install Config NPM Package Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Provides the command to install the 'config' NPM package, which is required for certain configuration functionalities. ```bash npm install --save config ``` -------------------------------- ### Kubernetes Authentication Configuration Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Configuration example for initializing the Vault client with Kubernetes authentication. ```APIDOC ## Kubernetes Auth (VaultKubernetesAuth) Authenticate using a Kubernetes service-account JWT token. **Module:** `src/auth/VaultKubernetesAuth.js` ### Configuration ```javascript const vaultClient = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'kubernetes', mount: 'kubernetes', // optional, default: 'kubernetes' config: { role: 'my_k8s_role', tokenPath: '/var/run/secrets/kubernetes.io/serviceaccount/token', // optional namespace: 'my-namespace', // optional }, }, }); ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | config.role | String | Yes | Role configured in Vault Kubernetes auth backend | | config.tokenPath | String | No | Path to Kubernetes service-account JWT. Default: `/var/run/secrets/kubernetes.io/serviceaccount/token` | | config.namespace | String | No | Vault namespace header | ### Behavior - **Authentication:** 1. Reads JWT from the configured `tokenPath` 2. Sends JWT to `POST /auth/{mount}/login` with the configured role - **Renewal:** Obtained token is renewed before expiration if renewable - **Reauthentication:** Allowed; if token expires, reads a new JWT and reauthenticates - **Token Path:** Defaults to the standard Kubernetes in-pod service-account path ### Throws - `Error` — when the JWT file cannot be read (permission denied, file not found, etc.) - `AuthTokenExpiredError` — when token expires and reauthentication fails ### Example ```javascript const vault = VaultClient.boot('main', { api: { url: 'https://vault.kubernetes.default.svc:8200/' }, auth: { type: 'kubernetes', config: { role: 'my_app_role', }, }, }); const secret = await vault.read('secret/my-app/db'); ``` ### Example (custom token path) ```javascript const vault = VaultClient.boot('main', { api: { url: 'https://vault.kubernetes.default.svc:8200/' }, auth: { type: 'kubernetes', config: { role: 'my_app_role', tokenPath: '/custom/jwt/path', }, }, }); ``` ### Vault Setup ```bash vault auth enable kubernetes vault write auth/kubernetes/config \ kubernetes_host="https://kubernetes.default.svc:443" \ kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt \ token_reviewer_jwt=@/var/run/secrets/kubernetes.io/serviceaccount/token vault write auth/kubernetes/role/my_app_role \ bound_service_account_names=my_app \ bound_service_account_namespaces=default \ policies=my_app_policy \ ttl=1h ``` ``` -------------------------------- ### Configure Vault Client with Kubernetes Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/README.md Example of bootstrapping the Vault client for a production environment using Kubernetes authentication for pods. ```javascript VaultClient.boot('prod', { api: { url: 'https://vault.kubernetes.default.svc:8200/' }, auth: { type: 'kubernetes', config: { role: process.env.VAULT_ROLE }, }, }); ``` -------------------------------- ### Initialize and Use Vault Client Source: https://github.com/namecheap/node-vault-client/blob/master/README.md Demonstrates how to initialize the Vault client with specific API and authentication configurations (using AppRole in this example). It then shows how to read data from a secret path and log the retrieved data. Ensure your Vault server URL and AppRole credentials are correctly configured. ```javascript const VaultClient = require('node-vault-client'); const vaultClient = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'appRole', // one of: 'appRole' | 'token' | 'iam' | 'kubernetes' config: { role_id: '637c065f-c644-5e12-d3d1-e9fa4363af61' } }, }); vaultClient.read('secret/tst').then(lease => { console.log(lease.getData()); // read() resolves to a Lease; use getData()/getValue(key) }).catch(e => console.error(e)); ``` -------------------------------- ### Instantiate VaultNodeConfig Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Initialize VaultNodeConfig with a configured VaultClient instance. Ensure the NPM 'config' package is installed, otherwise a VaultError will be thrown. ```javascript new VaultNodeConfig(vaultClient) ``` -------------------------------- ### Setup Token Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/INDEX.md Configures the Vault client to authenticate using a static token. Ensure the VAULT_TOKEN environment variable is set. ```javascript VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'token', config: { token: process.env.VAULT_TOKEN }, }, }); ``` -------------------------------- ### Vault Kubernetes Auth Backend Setup Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Bash commands to enable and configure the Kubernetes auth method in Vault, including setting up a role. ```bash vault auth enable kubernetes vault write auth/kubernetes/config \ kubernetes_host="https://kubernetes.default.svc:443" \ kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt \ token_reviewer_jwt=@/var/run/secrets/kubernetes.io/serviceaccount/token vault write auth/kubernetes/role/my_app_role \ bound_service_account_names=my_app \ bound_service_account_namespaces=default \ policies=my_app_policy \ ttl=1h ``` -------------------------------- ### Configure Vault Client with Internal CA/Proxy Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/README.md Example of bootstrapping the Vault client for an internal environment, specifying a custom CA certificate for TLS and using token authentication. ```javascript const { Agent, ProxyAgent } = require('undici'); const fs = require('fs'); VaultClient.boot('internal', { api: { url: 'https://vault.internal:8200/', requestOptions: { dispatcher: new Agent({ connect: { ca: fs.readFileSync('/etc/ssl/internal-ca.pem'), }, }), }, }, auth: { type: 'token', config: { token: '...' } }, }); ``` -------------------------------- ### Vault Data Structure Example Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Illustrates the expected structure of data within HashiCorp Vault for the 'secret/db' and 'pki/issue/client' paths. This data will be merged into the application configuration. ```text secret/db: { username: "postgres", password: "secretpassword123", } pki/issue/client: { certificate: "-----BEGIN CERTIFICATE-----...", private_key: "-----BEGIN PRIVATE KEY-----...", } ``` -------------------------------- ### Custom Vault Variables Configuration (JS) Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Example of a custom JavaScript configuration file mapping application settings to Vault paths. This specific example targets database credentials. ```javascript // config/custom-vault-variables.js module.exports = { database: { username: 'secret/my-app/db#username', password: 'secret/my-app/db#password', }, logging: { // Level is static, not in Vault }, }; ``` -------------------------------- ### Setup AppRole Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/INDEX.md Configures the Vault client to authenticate using AppRole. Requires VAULT_ROLE_ID and VAULT_SECRET_ID environment variables. ```javascript VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'appRole', config: { role_id: process.env.VAULT_ROLE_ID, secret_id: process.env.VAULT_SECRET_ID, }, }, }); ``` -------------------------------- ### In-Flight Deduplication Example Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/MountResolver.md Demonstrates how concurrent reads to paths sharing a common mount segment are deduplicated by the MountResolver, resulting in a single detection call. ```javascript // Concurrent reads const [lease1, lease2] = await Promise.all([ vault.read('secret/foo'), vault.read('secret/bar'), ]); // MountResolver: // 1. Both paths start with 'secret/' (same first segment) // 2. Grouped under in-flight key 'secret' // 3. Only ONE detection call made // 4. Both requests wait for the shared promise ``` -------------------------------- ### Setup Kubernetes Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/INDEX.md Configures the Vault client to authenticate using Kubernetes service account tokens. Specify the Vault role. ```javascript VaultClient.boot('prod', { api: { url: 'https://vault.kubernetes.default.svc:8200/' }, auth: { type: 'kubernetes', config: { role: 'my_app' }, }, }); ``` -------------------------------- ### Application Default Configuration (JS) Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Example of a default JavaScript configuration file for the application. This sets static values and placeholders for secrets to be filled from Vault. ```javascript // config/default.js module.exports = { database: { host: 'localhost', port: 5432, // username and password come from Vault }, logging: { level: 'info', }, }; ``` -------------------------------- ### Vault AppRole Setup Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Commands to set up an AppRole in Vault, including enabling the auth method, creating a role, and retrieving the RoleID and SecretID. ```bash vault auth enable approle vault write auth/approle/role/my_role \ token_ttl=1h \ token_max_ttl=24h \ bind_secret_id=true vault read auth/approle/role/my_role/role-id vault write -f auth/approle/role/my_role/secret-id ``` -------------------------------- ### Handle Substitution Key Not Found Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Shows an example where a substitution key is not found in Vault. Ensure the specified key exists within the Vault secret path. ```javascript // Vault secret: secret/my-app/db = { username: 'admin' } // Config: db_password: 'secret/my-app/db#password' (doesn't exist) // Error: Can't find substitution for "secret/my-app/db#password" ``` -------------------------------- ### Configure Vault Client with AWS IAM Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/README.md Example of bootstrapping the Vault client for a production environment using AWS IAM authentication for EC2 instances. ```javascript VaultClient.boot('prod', { api: { url: 'https://vault.aws.internal:8200/' }, auth: { type: 'iam', config: { role: process.env.VAULT_ROLE, region: 'us-west-2', }, }, }); ``` -------------------------------- ### VaultIAMAuth Configuration Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Configuration example for initializing the Vault client with AWS IAM authentication. This method uses AWS IAM credentials to authenticate with Vault. ```APIDOC ## AWS IAM Auth (VaultIAMAuth) Authenticate using AWS IAM credentials via SigV4-signed GetCallerIdentity request. ### Configuration ```javascript const vaultClient = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'iam', mount: 'aws', // optional, default: 'aws' config: { role: 'my_iam_role', iam_server_id_header_value: 'https://vault.example.com:8200/', // optional namespace: 'my-namespace', // optional region: 'eu-central-1', // optional credentials: { // optional accessKeyId: 'AKIA...', secretAccessKey: 'wJalrXUtn...', }, }, }, }); ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | config.role | String | Yes | Vault AppRole name in the AWS auth backend | | config.iam_server_id_header_value | String | No | X-Vault-AWS-IAM-Server-ID header value (typically Vault URL) | | config.namespace | String | No | Vault namespace header | | config.region | String | No | AWS STS region (e.g., `eu-central-1`). When set, signs against regional STS endpoint. Default: global endpoint (`us-east-1`) | | config.credentials | Object | No | AWS credentials object; if omitted, resolved from AWS SDK credential provider chain | | config.credentials.accessKeyId | String | Conditional | AWS access key ID | | config.credentials.secretAccessKey | String | Conditional | AWS secret access key | ### Behavior - **Authentication:** 1. Resolves AWS credentials (from config or credential provider chain) 2. Signs a `GetCallerIdentity` request with SigV4 3. Sends signed request details to Vault's `POST /auth/{mount}/login` - **Renewal:** Obtained token is renewed before expiration if renewable - **Reauthentication:** Allowed; if token expires, re-signs a new GetCallerIdentity request - **Credential Resolution:** Uses `@aws-sdk/credential-providers` `fromNodeProviderChain()` if no credentials provided ### Region Parameter By default, the SigV4 signature and request are bound to the global STS endpoint (`sts.amazonaws.com`, scope `us-east-1`). Set `config.region` to sign against a regional endpoint when Vault is configured for a specific region: ```javascript region: 'eu-central-1' // signs against sts.eu-central-1.amazonaws.com ``` Without matching region config, Vault's STS replay fails with `SignatureDoesNotMatch — Credential should be scoped to a valid region`. ### Throws - `InvalidAWSCredentialsError` — when credentials config is invalid (array format, missing accessKeyId, or missing secretAccessKey) - `AuthTokenExpiredError` — when token expires and reauthentication fails ### Example (with credential provider chain) ```javascript const vault = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'iam', config: { role: 'my_ec2_role', iam_server_id_header_value: 'https://vault.example.com:8200/', region: 'us-east-1', }, }, }); const secret = await vault.read('secret/my-app/db'); ``` ### Example (with explicit credentials) ```javascript const vault = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'iam', config: { role: 'my_iam_role', region: 'eu-central-1', credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }, }, }, }); ``` ``` -------------------------------- ### VaultClient API Request Options with Proxy Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/configuration.md Example of configuring a proxy agent for VaultClient requests using undici's ProxyAgent. ```javascript const { ProxyAgent } = require('undici'); requestOptions: { dispatcher: new ProxyAgent('http://proxy.example.com:8080') } ``` -------------------------------- ### Perform Raw Requests to Vault Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/README.md This example demonstrates how to make raw HTTP requests to Vault, which is useful for non-KV backends like Transit or PKI. It shows a POST request to encrypt data. ```javascript // For Transit, PKI, or other non-KV backends const result = await vault.request('POST', 'transit/encrypt/my-key', { plaintext: Buffer.from('hello').toString('base64'), }); console.log(result.data.ciphertext); ``` -------------------------------- ### Vault Authentication Methods Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/00-START-HERE.md Configuration examples for different Vault authentication types: token, AppRole, AWS IAM, and Kubernetes. Choose the method appropriate for your environment. ```javascript // Token (development) { auth: { type: 'token', config: { token: '...' } } } ``` ```javascript // AppRole (services, CI/CD) { auth: { type: 'appRole', config: { role_id: '...', secret_id: '...' } } } ``` ```javascript // AWS IAM (EC2, Lambda) { auth: { type: 'iam', config: { role: '...', region: 'us-west-2' } } } ``` ```javascript // Kubernetes (pods) { auth: { type: 'kubernetes', config: { role: '...' } } } ``` -------------------------------- ### Use Token Authentication to Read Secrets Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Example of initializing the VaultClient with token authentication using an environment variable and then reading a secret. The token is validated on first use. ```javascript const vault = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'token', config: { token: process.env.VAULT_TOKEN }, }, }); const secret = await vault.read('secret/my-app/db'); ``` -------------------------------- ### Vault AWS IAM Auth Backend Setup Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Bash commands to set up and configure the AWS IAM authentication backend in Vault. This includes enabling the auth method, configuring the AWS client, setting the STS region, optionally setting the server ID header, and creating an IAM role. ```bash vault auth enable aws # Configure Vault's AWS auth backend client vault write auth/aws/config/client \ access_key=AKIA... \ secret_key=wJalr... # Configure STS region if not us-east-1 vault write auth/aws/config/client sts_region=eu-central-1 # Optionally set the server-id header value vault write auth/aws/config/client \ iam_server_id_header_value='https://vault.example.com:8200' # Create a role vault write auth/aws/role/my_iam_role \ auth_type=iam \ bound_iam_principal_arn='arn:aws:iam::123456789012:role/my_ec2_role' \ token_ttl=1h ``` -------------------------------- ### VaultClient.boot(name, [options]) Source: https://github.com/namecheap/node-vault-client/blob/master/README.md Boots and returns a Vault client instance, identified by a name. If an instance with the same name already exists, it is returned. Options can be provided for the Vault client constructor. ```APIDOC ## VaultClient.boot(name, [options]) ### Description Boot an instance of Vault. The instance will be stored in a local hash. Calling Vault.boot multiple times with the same name will return the same instance. ### Method `static method` ### Parameters #### Path Parameters - **name** (String) - Required - Vault instance name - **[options]** (Object) - Optional - Options for [Vault#constructor](#new_VaultClient_new). ### Request Example ```javascript const vaultClient = VaultClient.boot('main', { /* ... */ }); ``` ### Response - **VaultClient** - Returns the Vault client instance. ``` -------------------------------- ### Booting and Retrieving VaultClient Instances Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultClient.md Use VaultClient.boot to create or retrieve a named singleton instance. Subsequent calls with the same name return the cached instance. Options are required on the first call. ```javascript const vault1 = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'token', config: { token: '...' } }, }); // Returns the same instance const vault2 = VaultClient.boot('main'); ``` -------------------------------- ### VaultClient Static boot Method Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/types.md Boots a named VaultClient instance with the provided options. This is the recommended way to initialize and manage client instances. ```javascript static boot(name: String, options: VaultClientOptions) → VaultClient ``` -------------------------------- ### VaultClient.boot Source: https://github.com/namecheap/node-vault-client/blob/master/README.md Statically boots a VaultClient instance with a given name and options, returning the client instance. ```APIDOC ## VaultClient.boot(name, [options]) ### Description Statically boots a VaultClient instance with a given name and options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **name** (String) - Required - The name to assign to the Vault client instance. * **options** (Object) - Optional - Configuration options for the client. ``` -------------------------------- ### getData() Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/Lease.md Gets a deep-cloned copy of the entire secret data object. Mutations to the returned object do not affect the original lease. ```APIDOC ## getData() ### Description Get a deep-cloned copy of the entire secret data object. ### Method `getData()` ### Returns `Object` — a deep copy of the secret data ### Notes - Returns a structuredClone (deep copy), so mutations do not affect the Lease - Returns `{}` if no data was present ### Example ```javascript const lease = await vaultClient.read('secret/my-app/config'); const allData = lease.getData(); ``` ``` -------------------------------- ### Combine Static and Dynamic Configuration Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Shows how to mix static configuration values (like server port) with dynamic values fetched from Vault (like API keys). This provides a flexible configuration approach. ```javascript module.exports = { server: { port: 3000, // static hostname: 'localhost', // static }, secrets: { api_key: 'secret/my-app#api_key', // from Vault db_password: 'secret/db#password', // from Vault }, logging: { level: 'info', // static }, }; ``` -------------------------------- ### Handle Missing Config File Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Demonstrates how to catch and log errors when the configuration file cannot be read. Ensure the configuration file exists in the specified directory. ```javascript // Error: Config file /path/to/config/custom-vault-variables.js cannot be read try { await vault.fillNodeConfig(); } catch (err) { console.error(err.message); // VaultError } ``` -------------------------------- ### Get Vault Request Headers Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultClient.md Internal helper to generate request headers, including the authentication token and an optional namespace if configured. ```javascript getHeaders(token) → Object ``` -------------------------------- ### VaultClient.boot Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultClient.md Creates or retrieves a named singleton instance of VaultClient. The first call requires options, while subsequent calls with the same name return the cached instance. ```APIDOC ## VaultClient.boot(name, [options]) ### Description Create or retrieve a named singleton instance. Subsequent calls with the same name return the cached instance. ### Method Static method ### Parameters #### Path Parameters - **name** (String) - Yes - Instance identifier - **options** (Object) - Conditional - Constructor options; required on first call, ignored on subsequent calls ### Request Example ```javascript const vault1 = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'token', config: { token: '...' } }, }); // Returns the same instance const vault2 = VaultClient.boot('main'); ``` ### Response #### Success Response - **VaultClient instance** - The VaultClient instance. ### Throws - `InvalidArgumentsError` — when options are omitted on first call ``` -------------------------------- ### Vault Auth Token Response Format Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/types.md Example of the expected response format for an authentication token from the Vault API. This structure is used by `AuthToken.fromResponse`. ```json { "data": { "id": "s.xxx...", "accessor": "KL3Dxt...", "creation_time": 1234567890, "expire_time": "2026-06-18T12:34:56Z", // optional, RFC3339 "ttl": 3600, "explicit_max_ttl": 86400, "num_uses": 0, "renewable": true, "last_renewal_time": 1234567890 // optional } } ``` -------------------------------- ### Catching InvalidArgumentsError Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/errors.md Shows how to catch InvalidArgumentsError, which is specifically thrown for incorrect arguments or configurations. This example highlights identifying an unsupported authentication method. ```javascript try { VaultClient.boot('main', { api: { url: '...' }, auth: { type: 'unsupported_type', config: {} }, }); } catch (err) { console.error(err instanceof InvalidArgumentsError); // true console.error(err.message); // "Unsupported auth method" } ``` -------------------------------- ### Initialize Vault Client with Token Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Use this snippet to initialize the Vault client for development environments using token authentication. Ensure the VAULT_TOKEN environment variable is set. ```javascript const vault = VaultClient.boot('dev', { api: { url: 'https://vault.dev.internal:8200/' }, auth: { type: 'token', config: { token: process.env.VAULT_TOKEN }, }, }); ``` -------------------------------- ### Setup AWS IAM Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/INDEX.md Configures the Vault client to authenticate using AWS IAM. Specify the IAM role and AWS region. ```javascript VaultClient.boot('prod', { api: { url: 'https://vault.aws.internal:8200/' }, auth: { type: 'iam', config: { role: 'my_ec2_role', region: 'us-west-2', }, }, }); ``` -------------------------------- ### Instantiate VaultClient with Token Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultClient.md Configure and create a new VaultClient instance using token authentication. Ensure the Vault server URL and token are correctly provided. The logger can be set to console or false to disable logging. ```javascript const VaultClient = require('node-vault-client'); const vaultClient = new VaultClient({ api: { url: 'https://vault.example.com:8200/', kv: { autoDetect: true }, }, auth: { type: 'token', config: { token: 's.xxxxxxxxxxxxxxxxxxxxxxxx', namespace: 'my-namespace', // optional }, }, logger: console, }); ``` -------------------------------- ### Initialize Vault Client with Kubernetes Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Set up the Vault client for Kubernetes environments using the Kubernetes auth method. The VAULT_ROLE environment variable must be configured. ```javascript const vault = VaultClient.boot('prod', { api: { url: 'https://vault.kubernetes.default.svc:8200/' }, auth: { type: 'kubernetes', config: { role: process.env.VAULT_ROLE }, }, }); ``` -------------------------------- ### VaultApiClient HTTP Methods Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultApiClient.md VaultApiClient supports various HTTP methods for interacting with Vault. The table below outlines common methods, their purposes, and example paths. ```APIDOC ## VaultApiClient HTTP Methods ### Description This section details the HTTP methods that VaultApiClient supports for interacting with Vault. Each method is described along with its typical purpose and an example of a Vault path where it might be used. ### Methods | Method | Purpose | Example Path | |--------|---------|--------------| | GET | Read a secret | `secret/data/my-app` | | POST | Write, login, perform action | `auth/approle/login` | | PUT | Create/update at a path | `secret/data/my-app` | | DELETE | Delete resource | `secret/data/my-app` | | LIST | List keys at a path | `secret/metadata/` (special) | | PATCH | Partial update (merge-patch) | `secret/data/my-app` (KV v2) | ### Logging VaultApiClient logs at different levels: - **Debug level:** Logs the request method and URI before a fetch, and the response status after a successful request. - **Error level:** Logs request failures. Note that exceptions are thrown for failures and response bodies are never logged due to sensitive data. ### See Also - [VaultClient](VaultClient.md) - [configuration.md](../configuration.md) ``` -------------------------------- ### Cleanup Vault Resources Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/INDEX.md Shows how to initialize a Vault client, perform an operation, and then properly close the client to stop background timers and allow the process to exit. ```javascript const vault = VaultClient.boot('main', { ... }); const secret = await vault.read('secret/data'); vault.close(); // stop refresh timer, allow process exit ``` -------------------------------- ### VaultClient Static get Method Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/types.md Retrieves a previously booted VaultClient instance by its registered name. Useful for accessing a shared client across your application. ```javascript static get(name: String) → VaultClient ``` -------------------------------- ### Configure Vault Client with Static KV Engines Source: https://github.com/namecheap/node-vault-client/blob/master/README.md Initialize the Vault client by statically defining KV engine versions. This is useful when the token lacks permissions for auto-detection. ```javascript const client = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/', engines: { secret: 2, legacy: 1 }, }, auth: { type: 'token', config: { token: '...' } }, }); ``` -------------------------------- ### File Structure Overview Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/00-START-HERE.md This snippet displays the directory structure of the node-vault-client project, indicating the location of various documentation files and modules. ```bash ├── 00-START-HERE.md ← You are here ├── README.md ← Quick start & overview ├── INDEX.md ← Complete API index by task ├── configuration.md ← All constructor options ├── types.md ← Type definitions ├── errors.md ← Error classes ├── KV-engines.md ← KV v1/v2 handling └── api-reference/ ├── VaultClient.md ← Main client class ├── Lease.md ← Secret wrapper ├── VaultApiClient.md ← HTTP layer ├── AuthenticationMethods.md ← All 4 auth backends ├── MountResolver.md ← KV detection └── VaultNodeConfig.md ← npm config integration ``` -------------------------------- ### Get Specific Value from Lease Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/Lease.md Retrieve a single value from the secret data using its key. This method throws an error if the requested key does not exist. ```javascript const lease = await vaultClient.read('secret/my-app/db'); const password = lease.getValue('password'); // throws if 'password' key missing ``` -------------------------------- ### VaultClient API Configuration with Mixed KV Engine Settings Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/configuration.md Demonstrates a mixed configuration for KV engines, using auto-detection for unknown mounts and a static override for the 'secret' engine. ```javascript { api: { url: 'https://vault.example.com:8200/', kv: { autoDetect: true }, // Detect unknown mounts engines: { secret: 2 }, // Override: secret is always v2 }, // ... } ``` -------------------------------- ### Basic Configuration with Vault Substitutions Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Defines the structure for substituting values from Vault. Use the format '#' for dynamic values. Static values are retained as-is. ```javascript // config/custom-vault-variables.js module.exports = { database: { host: 'secret/my-app/db#host', port: 'secret/my-app/db#port', username: 'secret/my-app/db#username', password: 'secret/my-app/db#password', }, api: { key: 'secret/my-app/api#api_key', secret: 'secret/my-app/api#api_secret', }, logging: { level: 'info', // static value, not substituted }, }; ``` -------------------------------- ### VaultClient Constructor Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultClient.md Initializes a new VaultClient instance with the provided options for connecting to and authenticating with HashiCorp Vault. ```APIDOC ## new VaultClient(options) ### Description Initializes a new VaultClient instance with the provided options for connecting to and authenticating with HashiCorp Vault. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (Object) - Required - Configuration object - **options.api** (Object) - Required - Vault API configuration - **options.api.url** (String) - Required - Vault server URL (e.g. `https://vault.example.com:8200/`) - **options.api.apiVersion** (String) - Optional - Vault API version prefix (default: `v1`) - **options.api.requestOptions** (Object) - Optional - Extra options merged into every fetch() call (e.g. undici Dispatcher for proxy/TLS) - **options.api.kv** (Object) - Optional - KV engine configuration - **options.api.kv.autoDetect** (Boolean) - Optional - Auto-detect KV version per mount via `GET sys/internal/ui/mounts/` (default: `false`) - **options.api.engines** (Object) - Optional - Static mount-to-version map override, e.g. `{ secret: 2, legacy: 1 }` - **options.auth** (Object) - Required - Authentication configuration - **options.auth.type** (String) - Required - Auth method: `'token'`, `'appRole'`, `'iam'`, `'kubernetes'` - **options.auth.mount** (String) - Optional - Vault auth backend mount point (default varies per type) - **options.auth.config** (Object) - Required - Auth-specific configuration variables - **options.auth.config.namespace** (String) - Optional - Vault namespace (sent as `X-Vault-Namespace` header) - **options.logger** (Object|Boolean) - Optional - Logger with error/warn/info/debug/trace methods, or `false` to disable (default: `console`) ### Throws - `InvalidArgumentsError` — when options are invalid or auth type is unsupported ### Request Example ```javascript const VaultClient = require('node-vault-client'); const vaultClient = new VaultClient({ api: { url: 'https://vault.example.com:8200/', kv: { autoDetect: true }, }, auth: { type: 'token', config: { token: 's.xxxxxxxxxxxxxxxxxxxxxxxx', namespace: 'my-namespace', // optional }, }, logger: console, }); ``` ### Response None ### Response Example None ``` -------------------------------- ### Initialize Vault Client and Read Secret Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/00-START-HERE.md Initialize the Vault client with token authentication and read a secret from the vault. Ensure the VAULT_TOKEN environment variable is set. ```javascript const VaultClient = require('node-vault-client'); const vault = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'token', config: { token: process.env.VAULT_TOKEN }, }, }); const secret = await vault.read('secret/my-app/db'); console.log(secret.getData()); // { username: '...', password: '...' } ``` -------------------------------- ### Enable and Use KV v2 Engine Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/KV-engines.md Enables a KV v2 secrets engine at the 'secret' path, puts data into it, retrieves the data, and gets its metadata. ```bash vault secrets enable -path=secret -version=2 kv vault kv put secret/my-app/db username=admin password=secret123 vault kv get secret/my-app/db vault kv metadata get secret/my-app/db ``` -------------------------------- ### Initialize Vault Client with AppRole Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/AuthenticationMethods.md Initialize the Vault client for local testing using the AppRole authentication method. Provide the role_id and secret_id directly or via environment variables. ```javascript const vault = VaultClient.boot('test', { api: { url: 'https://vault.local:8200/' }, auth: { type: 'appRole', config: { role_id: '637c065f-c644-5e12-d3d1-e9fa4363af61', secret_id: 'f0ed...', }, }, }); ``` -------------------------------- ### Initialize MountResolver in VaultClient Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/MountResolver.md Demonstrates how a MountResolver instance is created within the VaultClient constructor. It takes a detection function, a list of engines, a logger, and configuration options. ```javascript // In VaultClient constructor const detectFn = (path) => this.__detectMount(path); this.__resolver = new MountResolver(detectFn, engines, this.__log, { disabled: resolverDisabled, }); ``` -------------------------------- ### Handling HTTP Errors Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/errors.md Example demonstrating how to catch and inspect an HttpError thrown by VaultApiClient.makeRequest(). It logs the status code, parsed error body, and the formatted error message. ```javascript try { await vaultClient.read('secret/nonexistent'); } catch (err) { console.error(err.statusCode); // 404 console.error(err.error); // { errors: ['secret not found'] } console.error(err.message); // "404 - {\"errors\":[\"secret not found\"]}" } ``` -------------------------------- ### Singleton Vault Client Management Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/README.md The client utilizes a singleton pattern for named instances. You can create or retrieve instances using `VaultClient.boot()` or `VaultClient.get()`. Ensure instances are cleaned up using `VaultClient.clear()`. ```javascript // Create or retrieve const vault1 = VaultClient.boot('main', options); const vault2 = VaultClient.boot('main', options); // returns vault1 // Same instance console.assert(vault1 === vault2); // Retrieve without creating const vault3 = VaultClient.get('main'); console.assert(vault3 === vault1); // Cleanup VaultClient.clear('main'); VaultClient.get('main'); // throws InvalidArgumentsError ``` -------------------------------- ### Custom Vault Variables Configuration Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultNodeConfig.md Example of a JavaScript configuration file that maps application settings to specific Vault paths and keys. This allows dynamic injection of secrets. ```javascript // config/custom-vault-variables.js module.exports = { database: { username: 'secret/db#username', password: 'secret/db#password', ssl: { cert: 'pki/issue/client#certificate', }, }, }; ``` -------------------------------- ### Error Handling for Detection Failure Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/MountResolver.md Provides an example of how to handle errors when the Vault engine detection fails and no override matches. This typically occurs due to insufficient permissions. ```javascript try { await resolver.resolve('secret/my-app/db'); } catch (err) { // VaultError: // "Failed to detect KV engine version for mount "secret" (path: secret/my-app/db): // 403 - permission denied. Set api.engines or disable autoDetect to bypass detection." } ``` -------------------------------- ### Enable Debug Logging for VaultClient Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/README.md Enable debug logging for the VaultClient during its initialization to observe detailed internal processes such as authentication method selection and token refresh setup. ```javascript VaultClient.boot('main', { api: { url: '...' }, auth: { ... }, logger: console, // logs debug messages }); ``` -------------------------------- ### Write Secrets to Vault Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/README.md This snippet shows how to write a new secret or update an existing one at a given path in Vault. It includes an example of writing a key-value pair and a timestamp. ```javascript await vault.write('secret/my-app/api-key', { key: 'sk-1234567890abcdef', created_at: new Date().toISOString(), }); ``` -------------------------------- ### Configure Token Authentication Source: https://github.com/namecheap/node-vault-client/blob/master/README.md Set up the Vault client with a static token for authentication. Ensure the provided token is valid and has the necessary permissions. ```javascript const vaultClient = VaultClient.boot('main', { api: { url: 'https://vault.example.com:8200/' }, auth: { type: 'token', mount: 'token', // Optional. Vault token auth mount point ("token" by default) config: { token: 's.xxxxxxxxxxxxxxxxxxxxxxxx', // Required. Vault token }, }, }); ``` -------------------------------- ### Handle Vault API Errors Source: https://github.com/namecheap/node-vault-client/blob/master/_autodocs/api-reference/VaultApiClient.md Catch and inspect errors from Vault API requests. This example shows how to access the status code, the error response body, and a formatted error message. ```javascript try { await client.makeRequest('GET', 'secret/data/nonexistent', null, headers); } catch (err) { console.log(err.statusCode); // 404 console.log(err.error); // { errors: ['secret not found'] } console.log(err.message); // "404 - {\"errors\":[\"secret not found\"]}" } ```