添加根 CA

我正在寻找一种方法来添加一个自定义 CA 到 NPM,这样我就可以使用上述证书(一个内部 git-server)从一个位置下载,而不必使用所有的 CA 检查

npm config set strict-ssl false

有没有办法做到这一点? (如果没有: 是否已经存在缺陷?)

110761 次浏览

You can point npm to a cafile

npm config set cafile /path/to/cert.pem

You can also configure ca string(s) directly.

npm config set ca "cert string"

ca can be an array of cert strings too. In your .npmrc:

ca[]="cert 1 base64 string"
ca[]="cert 2 base64 string"

The npm config commands above will persist the relevant config items to your ~/.npmrc file:

cafile=/path/to/cert.pem

Note: these CA settings will override the default "real world" certificate authority lookups that npm uses. If you try and use any public npm registries via https that aren't signed by your CA certificate, you will get errors.

So, if you need to support both public https npm registries as well as your own, you could use curl's Mozilla based CA bundle and append your CA cert to the cacert.pem file:

curl -o ~/.npm.certs.pem https://curl.se/ca/cacert.pem
cat my-ca-cert.pem >> ~/.npm.certs.pem
npm config set cafile ~/.npm.certs.pem

Unfortunately npm's CA bundle is not editable as it's provided in the source code (thanks tomekwi) but nitzel has provided a generic Node.js method to append a certificate via the NODE_EXTRA_CA_CERTS environment variable.

RHEL Note: If you happen to be using a RHEL based distro and the RHEL packaged nodejs/npm you can use the standard update-ca-trust method as RedHat points their packages at the system CA's.

If Matts Answer isn't helping you, the following Windows PowerShell way worked for me and the similar approaches for CMD/Unix worked for other users:

Windows Powershell
$env:NODE_EXTRA_CA_CERTS=path\to\certificate.pem; npm install

DOS / Windows cmd

(pointed out by Marc in the comments)

set NODE_EXTRA_CA_CERTS=C:\\path\\to\\certificate.pem
npm install

Linux / Unix / Mac OS

(pointed out by Mike & mread1208 in the comments)

export NODE_EXTRA_CA_CERTS=/path/to/trusted/CA.pem
npm install