diff --git a/README.md b/README.md index d322255..60366ca 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,20 @@ const server = createServer({key, cert}, () => { }); ``` +On the client side, a mechanism is provided to override some of the TLS +internals of node so that fetch will work correctly. + +Example: + +```js +import {whileCAtrusted} from '@cto.af/ca/client'; + +const fetchResult = await whileCAtrusted( + {}, // CA options, or a PEM-encoded string with the CA cert. + () => fetch('https://localhost:8001') +); +``` + ### CLI A rudimentary CLI is provided. diff --git a/src/client.ts b/src/client.ts index 2dbbd0b..1c745c1 100644 --- a/src/client.ts +++ b/src/client.ts @@ -16,11 +16,17 @@ let currentSym: symbol | undefined = undefined; * @throws On invalid state. */ export async function overrideCreateSecureContext( - options: CertOptions + options: CertOptions | string ): Promise { - const CA = new CertificateAuthority(options); - const {ca} = await CA.init(); - assert(ca, 'Will always be filled in if no exception thrown'); + let cert: string | undefined = undefined; + if (typeof options === 'string') { + cert = options; + } else { + const CA = new CertificateAuthority(options); + const {ca} = await CA.init(); + assert(ca, 'Will always be filled in if no exception thrown'); + ({cert} = ca); + } assert.equal( origCsC.name, @@ -37,7 +43,7 @@ export async function overrideCreateSecureContext( tls.createSecureContext = (opts: tls.SecureContextOptions | undefined): tls.SecureContext => { const res = origCsC(opts); - res.context.addCACert(ca.cert); + res.context.addCACert(cert); return res; }; return currentSym; @@ -75,7 +81,7 @@ export function resetCreateSecureContext(sym: symbol): void { * @returns The result of during. */ export async function whileCAtrusted( - options: CertOptions, + options: CertOptions | string, during: () => T ): Promise> { const sym = await overrideCreateSecureContext(options); diff --git a/test/index.test.js b/test/index.test.js index 068017e..31a1bc4 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -143,6 +143,9 @@ test('whileCAtrusted', async () => { const whileRet = await whileCAtrusted(opts, () => tls.createSecureContext()); assert(whileRet.context); + const certRet = await whileCAtrusted(kc.ca.cert, () => 4); + assert.equal(certRet, 4); + await assert.rejects(async () => { await whileCAtrusted(opts, () => whileCAtrusted(opts, () => 5)); }, /createSecureContext already hooked/);