欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

无法验证第一份证书 原因及解决方法

最编程 2024-03-04 22:10:14
...
配图源自 Freepik

背景

此前,在项目中安装依赖时,遇到了如下报错:

yarn install v1.22.19
[1/4] ????  Resolving packages...
[2/4] ????  Fetching packages...
error An unexpected error occurred: "https://r2.cnpmjs.org/form-data/-/form-data-3.0.1.tgz: unable to verify the first certificate".
info If you think this is a bug, please open a bug report with the information provided in "/Users/frankie/Web/ifanr/yuegonghui/activity-collection/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

yarn-error.log 如下

Arguments: 
  /Users/frankie/Library/Application Support/fnm/node-versions/v16.15.0/installation/bin/node /usr/local/bin/yarn

PATH: 
  /Users/frankie/Library/Caches/fnm_multishells/57063_1669556334889/bin:/Users/frankie/.yarn/bin:/usr/local/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/frankie/Library/Caches/fnm_multishells/57063_1669556334889/bin:/Users/frankie/.yarn/bin:/usr/local/sbin:/opt/homebrew/bin:/opt/homebrew/bin

Yarn version: 
  1.22.19

Node version: 
  16.15.0

Platform: 
  darwin arm64

Trace: 
  Error: unable to verify the first certificate
      at TLSSocket.onConnectSecure (node:_tls_wrap:1532:34)
      at TLSSocket.emit (node:events:527:28)
      at TLSSocket._finishInit (node:_tls_wrap:946:8)
      at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:727:12)

npm manifest:
  ...

yarn manifest: 
  No manifest

Lockfile:
  ...

报错信息为:unable to verify the first certificate,与证书有关。由于 yarn installnpm install 走的是 HTTPS 协议,它的安全通过数字证书来保障。数字证书由专门机构颁发,通常是付费的。自签证书,就是自己扮演数字证书机构给自己颁发的证书。

由于自 2014 年 2 月 27 日起,npm 不再支持「自签证书 Self-Signed Certificate」。???? npm Blog

加上,也就是 https://r2.cnpmjs.org/form-data/-/form-data-3.0.1.tgz 所在域名的证书是不被信任的。这点通过 Firefox 浏览器就能发现:

其中 npm 与证书相关的配置有两项

  • ca - 用于指定信任的证书颁发机构(Certificate Authority)。默认为 null,表示仅允许「已知且可信的」证书颁发机构所颁发的证书。
  • strict-ssl - 通过 https 向注册表发出请求时是否进行 SSL 密钥验证,若校验失败,npm 将无法连接到服务器并报错。默认为 true

解决方法

方法一

在确定「安全」的情况下,可以临时关闭 strict-ssl 选项:

$ yarn config set strict-ssl false
$ npm config set strict-ssl false

strict-ssl 设置为 false 时,npm 将不会对服务器的 SSL 证书进行校验,并且即使证书是由不可信的认证机构颁发的也不会报错。这可能会导致安全风险,因为你的网络流量可能被劫持或篡改,而你并不会意识到这一点。因此,应该尽量避免使用 strict-ssl 设置为 false

如果你确实需要使用 strict-ssl 设置为 false,例如你所连接的服务器使用的是自签名的 SSL 证书,应该只在短时间内使用,并在操作完成后尽快将 strict-ssl 设置回 true

方法二(推荐)

找出所有相关的 npm 包,并选择可信的镜像源后重装。

如果你处于具有拦截 HTTPS 代理的环境中,它可能会破坏 npm,与运维人员联系解决。

The end.