npm

npm 安装 SSL 证书错误解决记录

Posted by Shane on 2026-03-30

npm 安装 SSL 证书错误解决记录

环境信息

项目 详情
操作系统 macOS Tahoe 26.2
Node.js 版本 v22.16.0
包管理器 npm (v10.x, 随 Node v22 捆绑)
网络环境 非公司网络,无代理/VPN
Registry https://registry.npmjs.org/ (官方源)

问题描述

尝试全局安装 @anthropic-ai/claude-code 时遇到 SSL 证书验证失败:

1
2
3
4
5
6
$ npm install -g @anthropic-ai/claude-code --registry https://registry.npmjs.org/

npm error code UNABLE_TO_GET_ISSUER_CERT_LOCALLY
npm error errno UNABLE_TO_GET_ISSUER_CERT_LOCALLY
npm error request to https://registry.npmjs.com/@anthropic-ai%2fclaude-code failed,
reason: unable to get local issuer certificate

尝试过的失败方案

  1. 切换至淘宝镜像源 (https://registry.npmmirror.com/) - 同样报错
  2. 检查系统时间 - 时间同步正常
  3. 使用 --strict-ssl=false - 可绕过但非根本解决

根因分析

Node.js v22 + macOS Tahoe 环境下,Node 的 OpenSSL 配置无法自动定位系统根证书存储位置。尽管 /etc/ssl/cert.pem 文件存在且有效,但 Node v22 的证书自动检测机制在该 macOS 版本上出现故障,导致无法建立 TLS 信任链。

解决方案

临时解决(单次会话)

1
2
export NODE_EXTRA_CA_CERTS=/etc/ssl/cert.pem
npm install -g @anthropic-ai/claude-code --registry https://registry.npmjs.org/

永久解决(推荐)

将环境变量写入 shell 配置文件,避免每次手动设置:

对于 zsh (macOS 默认):

1
2
echo 'export NODE_EXTRA_CA_CERTS=/etc/ssl/cert.pem' >> ~/.zshrc
source ~/.zshrc

对于 bash:

1
2
echo 'export NODE_EXTRA_CA_CERTS=/etc/ssl/cert.pem' >> ~/.bash_profile
source ~/.bash_profile

验证修复

设置环境变量后,重新执行安装命令:

1
npm install -g @anthropic-ai/claude-code --registry https://registry.npmjs.org/

预期输出:

1
added 1 package in 3s

技术细节补充

证书文件验证

确认 macOS 根证书文件存在且有效:

1
2
3
4
5
ls -la /etc/ssl/cert.pem
# 输出示例:-rw-r--r-- 1 root wheel 382456 Jan 1 00:00 /etc/ssl/cert.pem

openssl x509 -in /etc/ssl/cert.pem -text -noout | head -n 10
# 应能正常解析证书内容

Node.js v22 变更说明

Node.js v22 更新了 crypto 模块的默认证书加载逻辑:

  • 移除了部分硬编码路径
  • 更依赖系统 OpenSSL 配置
  • 在 macOS Tahoe 上,系统 Keychain 与 OpenSSL 的集成发生变化,导致自动检测失败

替代方案(如果环境变量无效)

若上述方案不奏效,可考虑:

  1. 使用 Corepack + Yarn:

    1
    2
    corepack enable
    yarn global add @anthropic-ai/claude-code
  2. 直接下载预构建包:

    1
    2
    3
    curl -L -o claude-code.tgz https://github.com/anthropics/claude-code/releases/latest/download/claude-code-latest.tgz
    npm install -g ./claude-code.tgz
    rm claude-code.tgz
  3. 降级 Node.js 至 v20 LTS:

    1
    2
    3
    4
    # 使用 nvm 管理版本
    nvm install 20
    nvm use 20
    npm install -g @anthropic-ai/claude-code

相关错误代码参考

错误代码 含义 常见原因
UNABLE_TO_GET_ISSUER_CERT_LOCALLY 无法获取本地颁发者证书 根证书缺失或 Node 无法访问系统证书存储
DEPTH_ZERO_SELF_SIGNED_CERT 自签名证书 中间人代理或公司防火墙拦截
UNABLE_TO_VERIFY_LEAF_SIGNATURE 无法验证叶证书签名 证书链不完整

结论

在 macOS Tahoe 26.2 + Node.js v22.16.0 环境下,通过显式设置 NODE_EXTRA_CA_CERTS 环境变量指向系统根证书文件 (/etc/ssl/cert.pem),可解决 npm 的 SSL 证书验证失败问题。这是 Node v22 在该 macOS 版本上的已知兼容性问题,建议将环境变量配置持久化到 shell 配置文件中。