跳到主要内容
ecdsa.com
Node.js tls / https / fetchNode.js crypto 模块

错误信息

code: 'DEPTH_ZERO_SELF_SIGNED_CERT'

也可能输出为

  • self-signed certificate; if the root CA is installed locally, try running Node.js with --use-system-ca
  • DEPTH_ZERO_SELF_SIGNED_CERT

Node.js 24.22 打印的消息是“self-signed certificate; if the root CA is installed locally, try running Node.js with --use-system-ca”;较早的版本只打印“self-signed certificate”(Node.js 17 之前为“self signed certificate”)。错误代码才是稳定的、适合搜索的部分。

Node.js tls / https / fetch — error.message "self-signed certificate" (OpenSSL X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, 18)

含义

服务器的证书是自签名的(它就是自己的颁发者,位于证书链的第 0 层,即“depth zero”),而且不在 Node.js 信任的证书集合中。Node.js 报告的消息是“self-signed certificate”,代码为 DEPTH_ZERO_SELF_SIGNED_CERT。这种情况常见于本地开发服务器、内部工具,以及仍在使用安装时生成的证书的服务。

原因

修复方法

  1. 1.

    只为一个 Agent 信任这一张证书

    把服务器的证书作为 ca 传入。这样只接受这一张证书,主机名和有效期检查仍然开启;注意,ca 会替换这个 Agent 的默认根证书。

    js
    // Trust exactly this certificate for this agent (hostname and dates are still checked)
    import https from "node:https";
    import fs from "node:fs";
    
    const agent = new https.Agent({ ca: fs.readFileSync("localhost.pem") });
    https.get("https://localhost:8443/", { agent }, (res) => res.resume());
  2. 2.

    为整个进程添加该证书

    NODE_EXTRA_CA_CERTS 对 https、tls 和 fetch() 同样有效,而且无需修改代码。

    bash
    # Whole process, including fetch(): add the certificate to the trusted set
    NODE_EXTRA_CA_CERTS=./localhost.pem node app.js
  3. 3.

    开发时使用本地 CA

    只需信任一次的本地根证书(mkcert、step-ca)可以为每台开发主机签发正规签名的证书,避免逐张证书设置例外。

    bash
    # Development: a local CA (mkcert) instead of one-off self-signed certificates
    mkcert -install && mkcert localhost 127.0.0.1
    NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem" node app.js
  4. 4.

    临时诊断:rejectUnauthorized: false

    会让该 Agent 接受任何证书,包括攻击者的证书。只可用于快速的本地检查;切勿用于要发布的代码。

    js
    // Temporary diagnostic in a test only: accepts ANY certificate on this agent
    const agent = new https.Agent({ rejectUnauthorized: false });

相关错误

浏览完整的签名错误库