node-vault

nodevaultMIT活跃维护

Node.js 客户端,用于对接 HashiCorp Vault 的 API,方便在 JS 应用里读取和管理密钥、令牌与策略。

Client for HashiCorp's Vault

v0.13.0发布于 2026-10-11 11:30 UTC557star160fork同步于 2026-11-10 06:01 UTC

怎么上手

从 README 代码块原样提取,可能是其中一种安装方式
npm install -S node-vault
docker-compose up --force-recreate test
npm run docs
硬件要求

README 没有说明硬件要求。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

这个项目的说明还在生成中,先参考下面「最近发版」和 README。

最近发版

5 个版本v0.13.0
  1. v0.13.0Release 0.13.0最新正式版2026-10-11 · 2026-10-11 11:30 UTC

    TL;DR

    • The axios dependency is now ^1.20.0 (was ^1.13.6), fixing 34 advisories that affect 1.13.6; with axios 1.20, HTTPS requests via HTTPS_PROXY tunnel through CONNECT, so proxies no longer see X-Vault-Token.
    • Proxies must therefore allow CONNECT to Vault's port (Squid's defaults block 8200), and one that never answers hangs requests despite timeout (workarounds: NO_PROXY, requestOptions.agentOptions.timeout).
    • kubernetesLogin, addKubernetesRole, getKubernetesRole and deleteKubernetesRole without mount_point now use the client's kubernetesPath (default kubernetes) instead of requesting auth//…, broken since 0.10.3.
    • addKubernetesRole (now taking Vault's token_* fields) and certLogin no longer reject with a TypeError when given arguments, and generateRootStatus is back with its typing; all three had been broken since 0.10.0.
    • Maintenance: dev-only nyc 18.0.0 (was 15.1.0), dropping the transitive uuid; dev lockfile security updates; CI test image moved to Debian bookworm. Docs: README and example/unseal.js cover unsealing an initialized vault.

    Pull requests

    • Add unseal example and docs for already-initialized vaults (#295)
    • fix: pass kubernetesPath into the mustache path context (#302)
    • build(deps): bump form-data from 4.0.5 to 4.0.6 (#304)
    • Fix Node 20 CI job by moving Docker base image to Debian bookworm (#305)
    • fix(deps): bump axios to 1.20.0 and patch vulnerable transitive deps (#308)
    • build(deps): bump uuid and nyc (#309)
    • fix: restore generateRootStatus and repair addKubernetesRole/certLogin schemas (#312)
    • chore(release): bump version (#313)
  2. v0.12.0Release 0.12.02026-03-21 · 2026-03-21 23:16 UTC
    查看更新说明

    TL;DR

    • New startTokenRenewal/startLeaseRenewal renew automatically at 80% of the TTL by default; stop with stopTokenRenewal, stopLeaseRenewal or stopAllRenewals. The client is now an EventEmitter emitting token:renewed, token:expired, token:error:renew and matching lease: events.
    • New KV v2 destroySecretVersions command (POST /:mount/destroy/:path) permanently destroys the given versions of a secret; mount_point defaults to secret.
    • A trailing slash on endpoint or VAULT_ADDR is now stripped, fixing malformed double-slash request URIs such as http://127.0.0.1:8200//v1/secret/hello.
    • Maintenance: added a Grype vulnerability-scan CI workflow (fails on high/critical findings), documented trailing-slash handling in the README, and bumped the transitive dev dependency flatted to 3.4.2.

    Pull requests

    • build(deps-dev): bump flatted from 3.2.7 to 3.4.2 (#287)
    • Strip trailing slash from endpoint to prevent malformed URIs (#288)
    • Document trailing slash handling, close #175 (#291)
    • Add Grype vulnerability scanner workflow (#290)
    • Add automatic token and lease renewal with event-based lifecycle management (#292)
    • Add KV v2 destroySecretVersions command (#293)
    • Bump version from 0.11.1 to 0.12.0 (#294)
  3. v0.11.1Release 0.11.12026-03-12 · 2026-03-12 22:53 UTC
    查看更新说明

    TL;DR

    • TLS options in requestOptions (ca, cert, key, passphrase, pfx, agentOptions, strictSSL) work again, at init or per call; they had been silently ignored since the switch to axios in 0.10.10.
    • timeout, httpsAgent and httpAgent in requestOptions are now passed to axios; they were dropped before, so the README's SOCKS-proxy agent setup had no effect.
    • TypeScript: VaultOptions.requestOptions is now AxiosRequestConfig & TlsOptions, so these TLS fields type-check; TlsOptions uses Node's Buffer, so builds without @types/node fail unless skipLibCheck is on.
    • Docs and tests: README and examples drop stale postman-request references and the ignored followAllRedirects option; new unit tests cover TLS and option forwarding.

    Pull requests

    • Restore backward-compatible requestOptions for axios migration (#286)
  4. v0.11.0Release 0.11.02026-03-12 · 2026-03-12 14:47 UTC
    查看更新说明

    TL;DR

    • Adds transit commands rewrapData, transitCreateKey, transitReadKey, transitListKeys and transitDeleteKey, and exposes the client's command definitions as vault.commands.
    • TypeScript definitions now match the built-in commands: adds unwrap, addKubernetesRole, getKubernetesRole, deleteKubernetesRole; removes the non-existent generateRootStatus and a duplicate ldapLogin; types the commands option as an object map (was an array).
    • The README's new SSL/TLS (agentOptions) and updated SOCKS-proxy (httpsAgent, httpAgent) requestOptions examples have no effect in this release: the built-in axios client ignores those options.
    • Docs and tests: README refreshed (configuration options, environment variables, error handling, AppRole and Kubernetes examples, badges and links); feature list and request-options example updated; new unit tests.

    Pull requests

    • Document requestOptions for SSL/TLS configuration; fix broken rpOptions example (#279)
    • Resolve merge conflicts with master for README update PR (#280)
    • Sync index.d.ts type definitions with commands.js (#283)
    • Add missing transit commands, export commands object, fix commands TypeScript type (#282)
    • Bump version from 0.10.10 to 0.11.0 (#284)
  5. v0.10.10Release 0.10.102026-03-10 · 2026-03-10 23:22 UTC
    查看更新说明

    TL;DR

    • New update(path, data, requestOptions) sends a PATCH (application/merge-patch+json) to add or change keys at a path without removing the others, unlike write, which replaces them all.
    • Regression: requestOptions TLS settings (ca, cert, key, agentOptions, strictSSL) and timeout are ignored, because the new axios wrapper forwards only method, URL, headers and JSON body. Restored in 0.11.1.
    • Network and TLS failures now reject with AxiosError, whose config holds the X-Vault-Token header, so logging the error object can expose the token; empty 204 responses resolve '', not undefined.
    • axios (^1.13.6) replaces the postman-request runtime dependency, so qs, flagged by CVE-2025-15284, is no longer installed; index.d.ts drops its undeclared request import and types the constructor's requestOptions as AxiosRequestConfig.

    Pull requests

    • chore(deps): bump postman-request to .48 (#273)
    • build(deps-dev): bump js-yaml from 3.14.1 to 3.14.2 (#270)
    • Adding Update function, to PATCH a path (#267)
    • build(deps): bump qs from 6.14.1 to 6.14.2 (#275)
    • build(deps-dev): bump minimatch from 3.1.2 to 3.1.5 (#276)
    • Fix postman-request version (#269)
    • Update definition file, fixes #274 (#277)
    • Replace postman-request with axios (#278)
    • Bump version from 0.10.9 to 0.10.10 (#281)

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    node-vault

    Build Status Download Status NPM Version License Dependency Status Open Collective backers and sponsors

    A client for the HTTP API of HashiCorp's Vault written for Node.js.

    Install

    Prerequisites:

    • Node.js >= 18.0.0
    npm install -S node-vault
    

    Note: If you need to use an older version of Node.js (>= 6.x), use node-vault <= v0.10.0. Please be aware that node-vault <= v0.10.0 contains multiple known vulnerabilities ☠️

    TypeScript definitions are included in the package.

    Test

    Run tests using docker-compose (includes vault and postgres) with:

    docker-compose up --force-recreate test
    

    Configuration

    Client Options

    const vault = require('node-vault')({
      apiVersion: 'v1',                        // API version (default: 'v1')
      endpoint: 'http://127.0.0.1:8200',      // Vault server URL (default: 'http://127.0.0.1:8200')
      token: 'MY_TOKEN',                       // Vault token for authentication
      pathPrefix: '',                          // Optional prefix for all request paths
      namespace: 'my-namespace',               // Vault Enterprise namespace
      noCustomHTTPVerbs: false,                // Use GET with ?list=1 instead of LIST HTTP method
      requestOptions: {},                      // Custom axios request options applied to all requests
    });
    

    Note: Trailing slashes in the endpoint URL (e.g. http://127.0.0.1:8200/) are automatically stripped to prevent malformed request URIs.

    Environment Variables

    The client reads the following environment variables as defaults:

    VariableDescription
    VAULT_ADDRVault server URL (overridden by endpoint option)
    VAULT_TOKENVault token (overridden by token option)
    VAULT_NAMESPACEVault Enterprise namespace (overridden by namespace option)
    VAULT_PREFIXRequest path prefix (overridden by pathPrefix option)
    VAULT_SKIP_VERIFYWhen set, disables SSL certificate verification

    Usage

    Init and unseal

    const vault = require('node-vault')({
      apiVersion: 'v1',
      endpoint: 'http://127.0.0.1:8200',
      token: 'MY_TOKEN', // optional; can be set after initialization
    });
    
    // init vault server
    vault.init({ secret_shares: 1, secret_threshold: 1 })
      .then((result) => {
        const keys = result.keys;
        // set token for all following requests
        vault.token = result.root_token;
        // unseal vault server
        return vault.unseal({ secret_shares: 1, key: keys[0] });
      })
      .catch(console.error);
    

    Unseal a vault that is already initialized

    If the vault server has been restarted or sealed, you can unseal it using the unseal keys from the original initialization. If the vault was initialized with secret_threshold > 1, you must call unseal multiple times with different keys until the threshold is met.

    const vault = require('node-vault')({
      apiVersion: 'v1',
      endpoint: 'http://127.0.0.1:8200',
    });
    
    // unseal vault server with a single key
    vault.unseal({ key: 'my-unseal-key' })
      .then(console.log)
      .catch(console.error);
    

    When the vault requires multiple unseal keys (threshold > 1):

    vault.unseal({ key: 'first-unseal-key' })
      .then((result) => {
        // result.sealed will be true until enough keys are provided
        console.log('Sealed:', result.sealed);
        console.log('Progress:', result.progress + '/' + result.t);
        return vault.unseal({ key: 'second-unseal-key' });
      })
      .then((result) => {
        // once the threshold is met, sealed will be false
        console.log('Sealed:', result.sealed);
      })
      .catch(console.error);
    

    See example/unseal.js for a working example.

    Write, read, update and delete secrets

    vault.write('secret/hello', { value: 'world', lease: '1s' })
      .then(() => vault.read('secret/hello'))
      .then(() => vault.delete('secret/hello'))
      .catch(console.error);
    

    The update method sends a PATCH request with application/merge-patch+json content type:

    vault.update('secret/data/hello', { data: { value: 'new-world' } })
      .catch(console.error);
    

    List secrets

    vault.list('secret/metadata/')
      .then((result) => console.log(result.data.keys))
      .catch(console.error);
    

    Kubernetes Auth Example

    const fs = require('fs');
    
    // Read service account token from default mount path
    const jwt = fs.readFileSync('/var/run/secrets/kubernetes.io/serviceaccount/token', { encoding: 'utf8' });
    
    // If the Vault Kubernetes auth endpoint is /auth/example-cluster/login and the role is example-role
    vault.kubernetesLogin({
      role: 'example-role',
      jwt: jwt,
      mount_point: 'example-cluster',
    }).catch(console.error);
    

    AppRole Auth Example

    const vault = require('node-vault')();
    
    vault.approleLogin({
      role_id: 'my-role-id',
      secret_id: 'my-secret-id',
    })
      .then((result) => {
        // client token is automatically set on successful login
        console.log(result.auth.client_token);
      })
      .catch(console.error);
    

    Error Handling

    The client exposes two error types accessible from the module:

    • VaultError — Base error class for all vault-related errors.
    • ApiResponseError — Thrown on non-200/204 responses. Contains a response property with statusCode and body.
    vault.read('secret/missing')
      .catch((err) => {
        console.error(err.message);       // Error message from Vault
        if (err.response) {
          console.error(err.response.statusCode); // e.g. 404
          console.error(err.response.body);       // Response body from Vault
        }
      });
    

    Custom Commands

    You can register custom API commands using generateFunction:

    vault.generateFunction('myCustomEndpoint', {
      method: 'GET',
      path: '/my-custom/endpoint/{{id}}',
    });
    
    // Use the generated function
    vault.myCustomEndpoint({ id: 'abc123' })
      .then(console.log)
      .catch(console.error);
    

    Docs

    Generate docco docs via:

    npm run docs
    

    Examples

    Please have a look at the examples and the generated feature list to see all supported Vault API endpoints.

    Instead of installing all the dependencies like vault itself and postgres, you can use docker and docker-compose to link and run multiple docker containers with all of their dependencies.

    git clone [email protected]:nodevault/node-vault.git
    cd node-vault
    docker-compose up vault
    

    Now you can run the examples from another terminal window.

    First of all you should initialize and unseal the vault:

    node example/init.js
    

    You should see root_token: followed by a long key in the response. Please copy that long key and export it as an environment variable:

    export VAULT_TOKEN=<insert long key here>
    

    Now you are able to run all of the other examples:

    node example/policies.js
    

    Connecting to Vault Through a Bastion Host

    To connect to a vault server in a private network through a bastion host, first open a SOCKS proxy connection:

    ssh -D <socksPort> bastion.example.com
    

    Then configure the client with a SOCKS proxy agent:

    const { SocksProxyAgent } = require('socks-proxy-agent');
    const agent = new SocksProxyAgent(`socks://127.0.0.1:${socksPort}`);
    
    const vault = require('node-vault')({
      apiVersion: 'v1',
      requestOptions: {
        httpsAgent: agent,
        httpAgent: agent,
      },
    });
    

    Custom SSL/TLS Configuration

    If you encounter SSL errors after upgrading to Node 18+ (e.g., EPROTO errors related to unsafe legacy renegotiation disabled), you can pass SSL/TLS options via requestOptions or rpDefaults when initializing the client:

    const vault = require('node-vault')({
      apiVersion: 'v1',
      endpoint: 'https://vault.example.com:8200',
      token: 'MY_TOKEN',
      requestOptions: {
        agentOptions: {
          securityOptions: 'SSL_OP_LEGACY_SERVER_CONNECT',
        },
      },
    });
    

    The requestOptions object supports TLS/SSL options (ca, cert, key, passphrase, agentOptions, strictSSL) as well as timeout, httpsAgent, and httpAgent. TLS options are mapped to an https.Agent and applied to every request. You can also pass native axios request options such as custom headers.

    You can also pass request options per-call to any method:

    vault.read('secret/hello', {
      agentOptions: {
        securityOptions: 'SSL_OP_LEGACY_SERVER_CONNECT',
      },
    });
    

    See example/pass_request_options.js for more examples.

    Backers