How to add custom certificate authority (CA) to nodejs

前端 未结 5 1073
失恋的感觉
失恋的感觉 2020-11-29 02:03

I\'m using a CLI tool to build hybrid mobile apps which has a cool upload feature so I can test the app on a device without going through the app store (it\'s ionic-cli). Ho

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 02:16

    This is not currently possible unless you compile a custom version of nodejs with custom CA certs. Hard-baked CA certs is a current limitation of nodejs until someone submits a PR and it's merged. It's a problem for others as well.

    Below I have some copies of workarounds which might help some people but probably not the OP.

    As far as I know OP can:

    • Custom compile nodejs
    • submit a PR for nodejs to fix the issue
    • file an issue or PR with ionic-cli to support custom CA certs: https://github.com/driftyco/ionic-cli (as suggested by @Nate)
    • Force less security (no TLS or silence verification also suggested by @Nate)

    Others, if you control the nodejs app in question you have more options. You can of course specify the ca cert in each request. Some clever people have shared some workarounds in the github issue https://github.com/nodejs/node/issues/4175. I haven't tried any of these myself yet so no promises, I'm just sharing what I've read.

    DuBistKomisch explains how to get nodejs to use the operating system's CA certs:

    My workaround is to load and parse the system CA certs manually. Then, as recommended by the request docs, pass them in with the ca option everywhere we make a request. I presume you could also just set ca on the global agent if that works for your use case.

    fs.readFileSync('/etc/ssl/certs/ca-certificates.crt')
      .toString()
      .split(/-----END CERTIFICATE-----\n?/)
      // may include an extra empty string at the end
      .filter(function (cert) { return cert !== ''; })
      // effectively split after delimiter by adding it back
      .map(function (cert) { return cert + '-----END CERTIFICATE-----\n'; })
    

    mwain explains how to set the CA certs globally and not on each https request:

    Had similar issues with this, have internal apps using an internally signed cert. Opted to use https.globalAgent and set an array of CA's which are defined in a config and updated on an env basis.

    const trustedCa = [
        '/etc/pki/tls/certs/ca-bundle.crt',
        '/path/to/custom/cert.crt'
    ];
    
    https.globalAgent.options.ca = [];
    for (const ca of trustedCa) {
        https.globalAgent.options.ca.push(fs.readFileSync(ca));
    }
    

提交回复
热议问题